text
stringlengths
5
1.04M
/* * LinuxSerialDriverComponentImplCfg.hpp * * Created on: Nov 29, 2016 * Author: tcanham */ #ifndef LINUXSERIALDRIVER_BLSPSERIALDRIVERCOMPONENTIMPLCFG_HPP_ #define LINUXSERIALDRIVER_BLSPSERIALDRIVERCOMPONENTIMPLCFG_HPP_ enum { DR_MAX_NUM_BUFFERS = 20, // Increasing this from 10 b/c RceAdapter couldn't always keep up with just 10 for reads }; #endif /* LINUXSERIALDRIVER_BLSPSERIALDRIVERCOMPONENTIMPLCFG_HPP_ */
// Copyright 2016 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "modules/canvas2d/BaseRenderingContext2D.h" #include "bindings/core/v8/ExceptionMessages.h" #include "bindings/core/v8/ExceptionState.h" #include "bindings/core/v8/ExceptionStatePlaceholder.h" #include "core/css/parser/CSSParser.h" #include "core/frame/ImageBitmap.h" #include "core/html/HTMLCanvasElement.h" #include "core/html/HTMLImageElement.h" #include "core/html/HTMLVideoElement.h" #include "core/html/ImageData.h" #include "modules/canvas2d/CanvasGradient.h" #include "modules/canvas2d/CanvasPattern.h" #include "modules/canvas2d/CanvasStyle.h" #include "modules/canvas2d/Path2D.h" #include "platform/Histogram.h" #include "platform/geometry/FloatQuad.h" #include "platform/graphics/Color.h" #include "platform/graphics/ExpensiveCanvasHeuristicParameters.h" #include "platform/graphics/Image.h" #include "platform/graphics/ImageBuffer.h" #include "platform/graphics/StrokeData.h" #include "platform/graphics/skia/SkiaUtils.h" #include "third_party/skia/include/core/SkImageFilter.h" namespace blink { BaseRenderingContext2D::BaseRenderingContext2D() : m_clipAntialiasing(NotAntiAliased) { m_stateStack.append(CanvasRenderingContext2DState::create()); } BaseRenderingContext2D::~BaseRenderingContext2D() { } CanvasRenderingContext2DState& BaseRenderingContext2D::modifiableState() { realizeSaves(); return *m_stateStack.last(); } void BaseRenderingContext2D::realizeSaves() { validateStateStack(); if (state().hasUnrealizedSaves()) { ASSERT(m_stateStack.size() >= 1); // Reduce the current state's unrealized count by one now, // to reflect the fact we are saving one state. m_stateStack.last()->restore(); m_stateStack.append(CanvasRenderingContext2DState::create(state(), CanvasRenderingContext2DState::DontCopyClipList)); // Set the new state's unrealized count to 0, because it has no outstanding saves. // We need to do this explicitly because the copy constructor and operator= used // by the Vector operations copy the unrealized count from the previous state (in // turn necessary to support correct resizing and unwinding of the stack). m_stateStack.last()->resetUnrealizedSaveCount(); SkCanvas* canvas = drawingCanvas(); if (canvas) canvas->save(); validateStateStack(); } } void BaseRenderingContext2D::save() { m_stateStack.last()->save(); } void BaseRenderingContext2D::restore() { validateStateStack(); if (state().hasUnrealizedSaves()) { // We never realized the save, so just record that it was unnecessary. m_stateStack.last()->restore(); return; } ASSERT(m_stateStack.size() >= 1); if (m_stateStack.size() <= 1) return; m_path.transform(state().transform()); m_stateStack.removeLast(); m_stateStack.last()->clearResolvedFilter(); m_path.transform(state().transform().inverse()); SkCanvas* c = drawingCanvas(); if (c) c->restore(); validateStateStack(); } void BaseRenderingContext2D::restoreMatrixClipStack(SkCanvas* c) const { if (!c) return; HeapVector<Member<CanvasRenderingContext2DState>>::const_iterator currState; DCHECK(m_stateStack.begin() < m_stateStack.end()); for (currState = m_stateStack.begin(); currState < m_stateStack.end(); currState++) { c->setMatrix(SkMatrix::I()); currState->get()->playbackClips(c); c->setMatrix(affineTransformToSkMatrix(currState->get()->transform())); c->save(); } c->restore(); } static inline void convertCanvasStyleToUnionType(CanvasStyle* style, StringOrCanvasGradientOrCanvasPattern& returnValue) { if (CanvasGradient* gradient = style->getCanvasGradient()) { returnValue.setCanvasGradient(gradient); return; } if (CanvasPattern* pattern = style->getCanvasPattern()) { returnValue.setCanvasPattern(pattern); return; } returnValue.setString(style->color()); } void BaseRenderingContext2D::strokeStyle(StringOrCanvasGradientOrCanvasPattern& returnValue) const { convertCanvasStyleToUnionType(state().strokeStyle(), returnValue); } void BaseRenderingContext2D::setStrokeStyle(const StringOrCanvasGradientOrCanvasPattern& style) { ASSERT(!style.isNull()); String colorString; CanvasStyle* canvasStyle = nullptr; if (style.isString()) { colorString = style.getAsString(); if (colorString == state().unparsedStrokeColor()) return; Color parsedColor = 0; if (!parseColorOrCurrentColor(parsedColor, colorString)) return; if (state().strokeStyle()->isEquivalentRGBA(parsedColor.rgb())) { modifiableState().setUnparsedStrokeColor(colorString); return; } canvasStyle = CanvasStyle::createFromRGBA(parsedColor.rgb()); } else if (style.isCanvasGradient()) { canvasStyle = CanvasStyle::createFromGradient(style.getAsCanvasGradient()); } else if (style.isCanvasPattern()) { CanvasPattern* canvasPattern = style.getAsCanvasPattern(); if (originClean() && !canvasPattern->originClean()) setOriginTainted(); canvasStyle = CanvasStyle::createFromPattern(canvasPattern); } ASSERT(canvasStyle); modifiableState().setStrokeStyle(canvasStyle); modifiableState().setUnparsedStrokeColor(colorString); modifiableState().clearResolvedFilter(); } void BaseRenderingContext2D::fillStyle(StringOrCanvasGradientOrCanvasPattern& returnValue) const { convertCanvasStyleToUnionType(state().fillStyle(), returnValue); } void BaseRenderingContext2D::setFillStyle(const StringOrCanvasGradientOrCanvasPattern& style) { ASSERT(!style.isNull()); validateStateStack(); String colorString; CanvasStyle* canvasStyle = nullptr; if (style.isString()) { colorString = style.getAsString(); if (colorString == state().unparsedFillColor()) return; Color parsedColor = 0; if (!parseColorOrCurrentColor(parsedColor, colorString)) return; if (state().fillStyle()->isEquivalentRGBA(parsedColor.rgb())) { modifiableState().setUnparsedFillColor(colorString); return; } canvasStyle = CanvasStyle::createFromRGBA(parsedColor.rgb()); } else if (style.isCanvasGradient()) { canvasStyle = CanvasStyle::createFromGradient(style.getAsCanvasGradient()); } else if (style.isCanvasPattern()) { CanvasPattern* canvasPattern = style.getAsCanvasPattern(); if (originClean() && !canvasPattern->originClean()) setOriginTainted(); if (canvasPattern->getPattern()->isTextureBacked()) disableDeferral(DisableDeferralReasonUsingTextureBackedPattern); canvasStyle = CanvasStyle::createFromPattern(canvasPattern); } ASSERT(canvasStyle); modifiableState().setFillStyle(canvasStyle); modifiableState().setUnparsedFillColor(colorString); modifiableState().clearResolvedFilter(); } double BaseRenderingContext2D::lineWidth() const { return state().lineWidth(); } void BaseRenderingContext2D::setLineWidth(double width) { if (!std::isfinite(width) || width <= 0) return; if (state().lineWidth() == width) return; modifiableState().setLineWidth(width); } String BaseRenderingContext2D::lineCap() const { return lineCapName(state().getLineCap()); } void BaseRenderingContext2D::setLineCap(const String& s) { LineCap cap; if (!parseLineCap(s, cap)) return; if (state().getLineCap() == cap) return; modifiableState().setLineCap(cap); } String BaseRenderingContext2D::lineJoin() const { return lineJoinName(state().getLineJoin()); } void BaseRenderingContext2D::setLineJoin(const String& s) { LineJoin join; if (!parseLineJoin(s, join)) return; if (state().getLineJoin() == join) return; modifiableState().setLineJoin(join); } double BaseRenderingContext2D::miterLimit() const { return state().miterLimit(); } void BaseRenderingContext2D::setMiterLimit(double limit) { if (!std::isfinite(limit) || limit <= 0) return; if (state().miterLimit() == limit) return; modifiableState().setMiterLimit(limit); } double BaseRenderingContext2D::shadowOffsetX() const { return state().shadowOffset().width(); } void BaseRenderingContext2D::setShadowOffsetX(double x) { if (!std::isfinite(x)) return; if (state().shadowOffset().width() == x) return; modifiableState().setShadowOffsetX(x); } double BaseRenderingContext2D::shadowOffsetY() const { return state().shadowOffset().height(); } void BaseRenderingContext2D::setShadowOffsetY(double y) { if (!std::isfinite(y)) return; if (state().shadowOffset().height() == y) return; modifiableState().setShadowOffsetY(y); } double BaseRenderingContext2D::shadowBlur() const { return state().shadowBlur(); } void BaseRenderingContext2D::setShadowBlur(double blur) { if (!std::isfinite(blur) || blur < 0) return; if (state().shadowBlur() == blur) return; modifiableState().setShadowBlur(blur); } String BaseRenderingContext2D::shadowColor() const { return Color(state().shadowColor()).serialized(); } void BaseRenderingContext2D::setShadowColor(const String& colorString) { Color color; if (!parseColorOrCurrentColor(color, colorString)) return; if (state().shadowColor() == color) return; modifiableState().setShadowColor(color.rgb()); } const Vector<double>& BaseRenderingContext2D::getLineDash() const { return state().lineDash(); } static bool lineDashSequenceIsValid(const Vector<double>& dash) { for (size_t i = 0; i < dash.size(); i++) { if (!std::isfinite(dash[i]) || dash[i] < 0) return false; } return true; } void BaseRenderingContext2D::setLineDash(const Vector<double>& dash) { if (!lineDashSequenceIsValid(dash)) return; modifiableState().setLineDash(dash); } double BaseRenderingContext2D::lineDashOffset() const { return state().lineDashOffset(); } void BaseRenderingContext2D::setLineDashOffset(double offset) { if (!std::isfinite(offset) || state().lineDashOffset() == offset) return; modifiableState().setLineDashOffset(offset); } double BaseRenderingContext2D::globalAlpha() const { return state().globalAlpha(); } void BaseRenderingContext2D::setGlobalAlpha(double alpha) { if (!(alpha >= 0 && alpha <= 1)) return; if (state().globalAlpha() == alpha) return; modifiableState().setGlobalAlpha(alpha); } String BaseRenderingContext2D::globalCompositeOperation() const { return compositeOperatorName(compositeOperatorFromSkia(state().globalComposite()), blendModeFromSkia(state().globalComposite())); } void BaseRenderingContext2D::setGlobalCompositeOperation(const String& operation) { CompositeOperator op = CompositeSourceOver; WebBlendMode blendMode = WebBlendModeNormal; if (!parseCompositeAndBlendOperator(operation, op, blendMode)) return; SkXfermode::Mode xfermode = WebCoreCompositeToSkiaComposite(op, blendMode); if (state().globalComposite() == xfermode) return; modifiableState().setGlobalComposite(xfermode); } String BaseRenderingContext2D::filter() const { return state().unparsedFilter(); } void BaseRenderingContext2D::setFilter(const String& filterString) { if (filterString == state().unparsedFilter()) return; CSSValue* filterValue = CSSParser::parseSingleValue(CSSPropertyFilter, filterString, CSSParserContext(HTMLStandardMode, nullptr)); if (!filterValue || filterValue->isInitialValue() || filterValue->isInheritedValue()) return; modifiableState().setUnparsedFilter(filterString); modifiableState().setFilter(filterValue); snapshotStateForFilter(); } SVGMatrixTearOff* BaseRenderingContext2D::currentTransform() const { return SVGMatrixTearOff::create(state().transform()); } void BaseRenderingContext2D::setCurrentTransform(SVGMatrixTearOff* matrixTearOff) { const AffineTransform& transform = matrixTearOff->value(); setTransform(transform.a(), transform.b(), transform.c(), transform.d(), transform.e(), transform.f()); } void BaseRenderingContext2D::scale(double sx, double sy) { SkCanvas* c = drawingCanvas(); if (!c) return; if (!std::isfinite(sx) || !std::isfinite(sy)) return; AffineTransform newTransform = state().transform(); newTransform.scaleNonUniform(sx, sy); if (state().transform() == newTransform) return; modifiableState().setTransform(newTransform); if (!state().isTransformInvertible()) return; c->scale(sx, sy); m_path.transform(AffineTransform().scaleNonUniform(1.0 / sx, 1.0 / sy)); } void BaseRenderingContext2D::rotate(double angleInRadians) { SkCanvas* c = drawingCanvas(); if (!c) return; if (!std::isfinite(angleInRadians)) return; AffineTransform newTransform = state().transform(); newTransform.rotateRadians(angleInRadians); if (state().transform() == newTransform) return; modifiableState().setTransform(newTransform); if (!state().isTransformInvertible()) return; c->rotate(angleInRadians * (180.0 / piFloat)); m_path.transform(AffineTransform().rotateRadians(-angleInRadians)); } void BaseRenderingContext2D::translate(double tx, double ty) { SkCanvas* c = drawingCanvas(); if (!c) return; if (!state().isTransformInvertible()) return; if (!std::isfinite(tx) || !std::isfinite(ty)) return; AffineTransform newTransform = state().transform(); newTransform.translate(tx, ty); if (state().transform() == newTransform) return; modifiableState().setTransform(newTransform); if (!state().isTransformInvertible()) return; c->translate(tx, ty); m_path.transform(AffineTransform().translate(-tx, -ty)); } void BaseRenderingContext2D::transform(double m11, double m12, double m21, double m22, double dx, double dy) { SkCanvas* c = drawingCanvas(); if (!c) return; if (!std::isfinite(m11) || !std::isfinite(m21) || !std::isfinite(dx) || !std::isfinite(m12) || !std::isfinite(m22) || !std::isfinite(dy)) return; AffineTransform transform(m11, m12, m21, m22, dx, dy); AffineTransform newTransform = state().transform() * transform; if (state().transform() == newTransform) return; modifiableState().setTransform(newTransform); if (!state().isTransformInvertible()) return; c->concat(affineTransformToSkMatrix(transform)); m_path.transform(transform.inverse()); } void BaseRenderingContext2D::resetTransform() { SkCanvas* c = drawingCanvas(); if (!c) return; AffineTransform ctm = state().transform(); bool invertibleCTM = state().isTransformInvertible(); // It is possible that CTM is identity while CTM is not invertible. // When CTM becomes non-invertible, realizeSaves() can make CTM identity. if (ctm.isIdentity() && invertibleCTM) return; // resetTransform() resolves the non-invertible CTM state. modifiableState().resetTransform(); c->setMatrix(affineTransformToSkMatrix(baseTransform())); if (invertibleCTM) m_path.transform(ctm); // When else, do nothing because all transform methods didn't update m_path when CTM became non-invertible. // It means that resetTransform() restores m_path just before CTM became non-invertible. } void BaseRenderingContext2D::setTransform(double m11, double m12, double m21, double m22, double dx, double dy) { SkCanvas* c = drawingCanvas(); if (!c) return; if (!std::isfinite(m11) || !std::isfinite(m21) || !std::isfinite(dx) || !std::isfinite(m12) || !std::isfinite(m22) || !std::isfinite(dy)) return; resetTransform(); transform(m11, m12, m21, m22, dx, dy); } void BaseRenderingContext2D::beginPath() { m_path.clear(); } static bool validateRectForCanvas(double& x, double& y, double& width, double& height) { if (!std::isfinite(x) || !std::isfinite(y) || !std::isfinite(width) || !std::isfinite(height)) return false; if (!width && !height) return false; if (width < 0) { width = -width; x -= width; } if (height < 0) { height = -height; y -= height; } return true; } bool BaseRenderingContext2D::isFullCanvasCompositeMode(SkXfermode::Mode op) { // See 4.8.11.1.3 Compositing // CompositeSourceAtop and CompositeDestinationOut are not listed here as the platforms already // implement the specification's behavior. return op == SkXfermode::kSrcIn_Mode || op == SkXfermode::kSrcOut_Mode || op == SkXfermode::kDstIn_Mode || op == SkXfermode::kDstATop_Mode; } static bool isPathExpensive(const Path& path) { const SkPath& skPath = path.getSkPath(); if (ExpensiveCanvasHeuristicParameters::ConcavePathsAreExpensive && !skPath.isConvex()) return true; if (skPath.countPoints() > ExpensiveCanvasHeuristicParameters::ExpensivePathPointCount) return true; return false; } void BaseRenderingContext2D::drawPathInternal(const Path& path, CanvasRenderingContext2DState::PaintType paintType, SkPath::FillType fillType) { if (path.isEmpty()) return; SkPath skPath = path.getSkPath(); FloatRect bounds = path.boundingRect(); skPath.setFillType(fillType); if (paintType == CanvasRenderingContext2DState::StrokePaintType) inflateStrokeRect(bounds); if (!drawingCanvas()) return; if (draw( [&skPath, this](SkCanvas* c, const SkPaint* paint) // draw lambda { c->drawPath(skPath, *paint); }, [](const SkIRect& rect) // overdraw test lambda { return false; }, bounds, paintType)) { if (isPathExpensive(path)) { ImageBuffer* buffer = imageBuffer(); if (buffer) buffer->setHasExpensiveOp(); } } } static SkPath::FillType parseWinding(const String& windingRuleString) { if (windingRuleString == "nonzero") return SkPath::kWinding_FillType; if (windingRuleString == "evenodd") return SkPath::kEvenOdd_FillType; ASSERT_NOT_REACHED(); return SkPath::kEvenOdd_FillType; } void BaseRenderingContext2D::fill(const String& windingRuleString) { trackDrawCall(FillPath); drawPathInternal(m_path, CanvasRenderingContext2DState::FillPaintType, parseWinding(windingRuleString)); } void BaseRenderingContext2D::fill(Path2D* domPath, const String& windingRuleString) { trackDrawCall(FillPath, domPath); drawPathInternal(domPath->path(), CanvasRenderingContext2DState::FillPaintType, parseWinding(windingRuleString)); } void BaseRenderingContext2D::stroke() { trackDrawCall(StrokePath); drawPathInternal(m_path, CanvasRenderingContext2DState::StrokePaintType); } void BaseRenderingContext2D::stroke(Path2D* domPath) { trackDrawCall(StrokePath, domPath); drawPathInternal(domPath->path(), CanvasRenderingContext2DState::StrokePaintType); } void BaseRenderingContext2D::fillRect(double x, double y, double width, double height) { trackDrawCall(FillRect); if (!validateRectForCanvas(x, y, width, height)) return; if (!drawingCanvas()) return; SkRect rect = SkRect::MakeXYWH(x, y, width, height); draw( [&rect, this](SkCanvas* c, const SkPaint* paint) // draw lambda { c->drawRect(rect, *paint); }, [&rect, this](const SkIRect& clipBounds) // overdraw test lambda { return rectContainsTransformedRect(rect, clipBounds); }, rect, CanvasRenderingContext2DState::FillPaintType); } static void strokeRectOnCanvas(const FloatRect& rect, SkCanvas* canvas, const SkPaint* paint) { ASSERT(paint->getStyle() == SkPaint::kStroke_Style); if ((rect.width() > 0) != (rect.height() > 0)) { // When stroking, we must skip the zero-dimension segments SkPath path; path.moveTo(rect.x(), rect.y()); path.lineTo(rect.maxX(), rect.maxY()); path.close(); canvas->drawPath(path, *paint); return; } canvas->drawRect(rect, *paint); } void BaseRenderingContext2D::strokeRect(double x, double y, double width, double height) { trackDrawCall(StrokeRect); if (!validateRectForCanvas(x, y, width, height)) return; if (!drawingCanvas()) return; SkRect rect = SkRect::MakeXYWH(x, y, width, height); FloatRect bounds = rect; inflateStrokeRect(bounds); draw( [&rect, this](SkCanvas* c, const SkPaint* paint) // draw lambda { strokeRectOnCanvas(rect, c, paint); }, [](const SkIRect& clipBounds) // overdraw test lambda { return false; }, bounds, CanvasRenderingContext2DState::StrokePaintType); } void BaseRenderingContext2D::clipInternal(const Path& path, const String& windingRuleString) { SkCanvas* c = drawingCanvas(); if (!c) { return; } if (!state().isTransformInvertible()) { return; } SkPath skPath = path.getSkPath(); skPath.setFillType(parseWinding(windingRuleString)); modifiableState().clipPath(skPath, m_clipAntialiasing); c->clipPath(skPath, SkRegion::kIntersect_Op, m_clipAntialiasing == AntiAliased); if (ExpensiveCanvasHeuristicParameters::ComplexClipsAreExpensive && !skPath.isRect(0) && hasImageBuffer()) { imageBuffer()->setHasExpensiveOp(); } } void BaseRenderingContext2D::clip(const String& windingRuleString) { clipInternal(m_path, windingRuleString); } void BaseRenderingContext2D::clip(Path2D* domPath, const String& windingRuleString) { clipInternal(domPath->path(), windingRuleString); } bool BaseRenderingContext2D::isPointInPath(const double x, const double y, const String& windingRuleString) { return isPointInPathInternal(m_path, x, y, windingRuleString); } bool BaseRenderingContext2D::isPointInPath(Path2D* domPath, const double x, const double y, const String& windingRuleString) { return isPointInPathInternal(domPath->path(), x, y, windingRuleString); } bool BaseRenderingContext2D::isPointInPathInternal(const Path& path, const double x, const double y, const String& windingRuleString) { SkCanvas* c = drawingCanvas(); if (!c) return false; if (!state().isTransformInvertible()) return false; FloatPoint point(x, y); if (!std::isfinite(point.x()) || !std::isfinite(point.y())) return false; AffineTransform ctm = state().transform(); FloatPoint transformedPoint = ctm.inverse().mapPoint(point); return path.contains(transformedPoint, SkFillTypeToWindRule(parseWinding(windingRuleString))); } bool BaseRenderingContext2D::isPointInStroke(const double x, const double y) { return isPointInStrokeInternal(m_path, x, y); } bool BaseRenderingContext2D::isPointInStroke(Path2D* domPath, const double x, const double y) { return isPointInStrokeInternal(domPath->path(), x, y); } bool BaseRenderingContext2D::isPointInStrokeInternal(const Path& path, const double x, const double y) { SkCanvas* c = drawingCanvas(); if (!c) return false; if (!state().isTransformInvertible()) return false; FloatPoint point(x, y); if (!std::isfinite(point.x()) || !std::isfinite(point.y())) return false; AffineTransform ctm = state().transform(); FloatPoint transformedPoint = ctm.inverse().mapPoint(point); StrokeData strokeData; strokeData.setThickness(state().lineWidth()); strokeData.setLineCap(state().getLineCap()); strokeData.setLineJoin(state().getLineJoin()); strokeData.setMiterLimit(state().miterLimit()); Vector<float> lineDash(state().lineDash().size()); std::copy(state().lineDash().begin(), state().lineDash().end(), lineDash.begin()); strokeData.setLineDash(lineDash, state().lineDashOffset()); return path.strokeContains(transformedPoint, strokeData); } void BaseRenderingContext2D::clearRect(double x, double y, double width, double height) { m_usageCounters.numClearRectCalls++; if (!validateRectForCanvas(x, y, width, height)) return; SkCanvas* c = drawingCanvas(); if (!c) return; if (!state().isTransformInvertible()) return; SkIRect clipBounds; if (!c->getClipDeviceBounds(&clipBounds)) return; SkPaint clearPaint; clearPaint.setXfermodeMode(SkXfermode::kClear_Mode); clearPaint.setStyle(SkPaint::kFill_Style); FloatRect rect(x, y, width, height); if (rectContainsTransformedRect(rect, clipBounds)) { checkOverdraw(rect, &clearPaint, CanvasRenderingContext2DState::NoImage, ClipFill); if (drawingCanvas()) drawingCanvas()->drawRect(rect, clearPaint); didDraw(clipBounds); } else { SkIRect dirtyRect; if (computeDirtyRect(rect, clipBounds, &dirtyRect)) { c->drawRect(rect, clearPaint); didDraw(dirtyRect); } } } static inline FloatRect normalizeRect(const FloatRect& rect) { return FloatRect(std::min(rect.x(), rect.maxX()), std::min(rect.y(), rect.maxY()), std::max(rect.width(), -rect.width()), std::max(rect.height(), -rect.height())); } static inline void clipRectsToImageRect(const FloatRect& imageRect, FloatRect* srcRect, FloatRect* dstRect) { if (imageRect.contains(*srcRect)) return; // Compute the src to dst transform FloatSize scale(dstRect->size().width() / srcRect->size().width(), dstRect->size().height() / srcRect->size().height()); FloatPoint scaledSrcLocation = srcRect->location(); scaledSrcLocation.scale(scale.width(), scale.height()); FloatSize offset = dstRect->location() - scaledSrcLocation; srcRect->intersect(imageRect); // To clip the destination rectangle in the same proportion, transform the clipped src rect *dstRect = *srcRect; dstRect->scale(scale.width(), scale.height()); dstRect->move(offset); } static inline CanvasImageSource* toImageSourceInternal(const CanvasImageSourceUnion& value, ExceptionState& exceptionState) { if (value.isHTMLImageElement()) return value.getAsHTMLImageElement(); if (value.isHTMLVideoElement()) return value.getAsHTMLVideoElement(); if (value.isHTMLCanvasElement()) return value.getAsHTMLCanvasElement(); if (value.isImageBitmap()) { if (static_cast<ImageBitmap*>(value.getAsImageBitmap())->isNeutered()) { exceptionState.throwDOMException(InvalidStateError, String::format("The image source is detached")); return nullptr; } return value.getAsImageBitmap(); } ASSERT_NOT_REACHED(); return nullptr; } void BaseRenderingContext2D::drawImage(ExecutionContext* executionContext, const CanvasImageSourceUnion& imageSource, double x, double y, ExceptionState& exceptionState) { CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource, exceptionState); if (!imageSourceInternal) return; FloatSize defaultObjectSize(width(), height()); FloatSize sourceRectSize = imageSourceInternal->elementSize(defaultObjectSize); FloatSize destRectSize = imageSourceInternal->defaultDestinationSize(defaultObjectSize); drawImage(executionContext, imageSourceInternal, 0, 0, sourceRectSize.width(), sourceRectSize.height(), x, y, destRectSize.width(), destRectSize.height(), exceptionState); } void BaseRenderingContext2D::drawImage(ExecutionContext* executionContext, const CanvasImageSourceUnion& imageSource, double x, double y, double width, double height, ExceptionState& exceptionState) { CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource, exceptionState); if (!imageSourceInternal) return; FloatSize defaultObjectSize(this->width(), this->height()); FloatSize sourceRectSize = imageSourceInternal->elementSize(defaultObjectSize); drawImage(executionContext, imageSourceInternal, 0, 0, sourceRectSize.width(), sourceRectSize.height(), x, y, width, height, exceptionState); } void BaseRenderingContext2D::drawImage(ExecutionContext* executionContext, const CanvasImageSourceUnion& imageSource, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState& exceptionState) { CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource, exceptionState); if (!imageSourceInternal) return; drawImage(executionContext, imageSourceInternal, sx, sy, sw, sh, dx, dy, dw, dh, exceptionState); } bool BaseRenderingContext2D::shouldDrawImageAntialiased(const FloatRect& destRect) const { if (!state().shouldAntialias()) return false; SkCanvas* c = drawingCanvas(); ASSERT(c); const SkMatrix &ctm = c->getTotalMatrix(); // Don't disable anti-aliasing if we're rotated or skewed. if (!ctm.rectStaysRect()) return true; // Check if the dimensions of the destination are "small" (less than one // device pixel). To prevent sudden drop-outs. Since we know that // kRectStaysRect_Mask is set, the matrix either has scale and no skew or // vice versa. We can query the kAffine_Mask flag to determine which case // it is. // FIXME: This queries the CTM while drawing, which is generally // discouraged. Always drawing with AA can negatively impact performance // though - that's why it's not always on. SkScalar widthExpansion, heightExpansion; if (ctm.getType() & SkMatrix::kAffine_Mask) widthExpansion = ctm[SkMatrix::kMSkewY], heightExpansion = ctm[SkMatrix::kMSkewX]; else widthExpansion = ctm[SkMatrix::kMScaleX], heightExpansion = ctm[SkMatrix::kMScaleY]; return destRect.width() * fabs(widthExpansion) < 1 || destRect.height() * fabs(heightExpansion) < 1; } void BaseRenderingContext2D::drawImageInternal(SkCanvas* c, CanvasImageSource* imageSource, Image* image, const FloatRect& srcRect, const FloatRect& dstRect, const SkPaint* paint) { trackDrawCall(DrawImage); int initialSaveCount = c->getSaveCount(); SkPaint imagePaint = *paint; if (paint->getImageFilter()) { SkMatrix ctm = c->getTotalMatrix(); SkMatrix invCtm; if (!ctm.invert(&invCtm)) { // There is an earlier check for invertibility, but the arithmetic // in AffineTransform is not exactly identical, so it is possible // for SkMatrix to find the transform to be non-invertible at this stage. // crbug.com/504687 return; } c->save(); c->concat(invCtm); SkRect bounds = dstRect; ctm.mapRect(&bounds); SkPaint layerPaint; layerPaint.setXfermode(sk_ref_sp(paint->getXfermode())); layerPaint.setImageFilter(paint->getImageFilter()); c->saveLayer(&bounds, &layerPaint); c->concat(ctm); imagePaint.setXfermodeMode(SkXfermode::kSrcOver_Mode); imagePaint.setImageFilter(nullptr); } if (!imageSource->isVideoElement()) { imagePaint.setAntiAlias(shouldDrawImageAntialiased(dstRect)); image->draw(c, imagePaint, dstRect, srcRect, DoNotRespectImageOrientation, Image::DoNotClampImageToSourceRect); } else { c->save(); c->clipRect(dstRect); c->translate(dstRect.x(), dstRect.y()); c->scale(dstRect.width() / srcRect.width(), dstRect.height() / srcRect.height()); c->translate(-srcRect.x(), -srcRect.y()); HTMLVideoElement* video = static_cast<HTMLVideoElement*>(imageSource); video->paintCurrentFrame(c, IntRect(IntPoint(), IntSize(video->videoWidth(), video->videoHeight())), &imagePaint); } c->restoreToCount(initialSaveCount); } bool shouldDisableDeferral(CanvasImageSource* imageSource, DisableDeferralReason* reason) { ASSERT(reason); ASSERT(*reason == DisableDeferralReasonUnknown); if (imageSource->isVideoElement()) { *reason = DisableDeferralReasonDrawImageOfVideo; return true; } if (imageSource->isCanvasElement()) { HTMLCanvasElement* canvas = static_cast<HTMLCanvasElement*>(imageSource); if (canvas->isAnimated2D()) { *reason = DisableDeferralReasonDrawImageOfAnimated2dCanvas; return true; } } return false; } void BaseRenderingContext2D::drawImage(ExecutionContext* executionContext, CanvasImageSource* imageSource, double sx, double sy, double sw, double sh, double dx, double dy, double dw, double dh, ExceptionState& exceptionState) { if (!drawingCanvas()) return; RefPtr<Image> image; FloatSize defaultObjectSize(width(), height()); SourceImageStatus sourceImageStatus = InvalidSourceImageStatus; if (!imageSource->isVideoElement()) { AccelerationHint hint = imageBuffer()->isAccelerated() ? PreferAcceleration : PreferNoAcceleration; image = imageSource->getSourceImageForCanvas(&sourceImageStatus, hint, SnapshotReasonDrawImage, defaultObjectSize); if (sourceImageStatus == UndecodableSourceImageStatus) exceptionState.throwDOMException(InvalidStateError, "The HTMLImageElement provided is in the 'broken' state."); if (!image || !image->width() || !image->height()) return; } else { if (!static_cast<HTMLVideoElement*>(imageSource)->hasAvailableVideoFrame()) return; } if (!std::isfinite(dx) || !std::isfinite(dy) || !std::isfinite(dw) || !std::isfinite(dh) || !std::isfinite(sx) || !std::isfinite(sy) || !std::isfinite(sw) || !std::isfinite(sh) || !dw || !dh || !sw || !sh) return; FloatRect srcRect = normalizeRect(FloatRect(sx, sy, sw, sh)); FloatRect dstRect = normalizeRect(FloatRect(dx, dy, dw, dh)); FloatSize imageSize = imageSource->elementSize(defaultObjectSize); clipRectsToImageRect(FloatRect(FloatPoint(), imageSize), &srcRect, &dstRect); imageSource->adjustDrawRects(&srcRect, &dstRect); if (srcRect.isEmpty()) return; DisableDeferralReason reason = DisableDeferralReasonUnknown; if (shouldDisableDeferral(imageSource, &reason)) disableDeferral(reason); else if (image->isTextureBacked()) disableDeferral(DisableDeferralDrawImageWithTextureBackedSourceImage); validateStateStack(); // TODO(xidachen): After collecting some data, come back and prune off // the ones that is not needed. Optional<ScopedUsHistogramTimer> timer; if (imageBuffer() && imageBuffer()->isAccelerated()) { if (imageSource->isVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterVideoGPU, new CustomCountHistogram("Blink.Canvas.DrawImage.Video.GPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterVideoGPU); } else if (imageSource->isCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterCanvasGPU, new CustomCountHistogram("Blink.Canvas.DrawImage.Canvas.GPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterCanvasGPU); } else if (imageSource->isSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterSVGGPU, new CustomCountHistogram("Blink.Canvas.DrawImage.SVG.GPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterSVGGPU); } else if (imageSource->isImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterImageBitmapGPU, new CustomCountHistogram("Blink.Canvas.DrawImage.ImageBitmap.GPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterImageBitmapGPU); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterOthersGPU, new CustomCountHistogram("Blink.Canvas.DrawImage.Others.GPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterOthersGPU); } } else if (imageBuffer() && imageBuffer()->isRecording()) { if (imageSource->isVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterVideoDisplayList, new CustomCountHistogram("Blink.Canvas.DrawImage.Video.DisplayList", 0, 10000000, 50)); timer.emplace(scopedUsCounterVideoDisplayList); } else if (imageSource->isCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterCanvasDisplayList, new CustomCountHistogram("Blink.Canvas.DrawImage.Canvas.DisplayList", 0, 10000000, 50)); timer.emplace(scopedUsCounterCanvasDisplayList); } else if (imageSource->isSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterSVGDisplayList, new CustomCountHistogram("Blink.Canvas.DrawImage.SVG.DisplayList", 0, 10000000, 50)); timer.emplace(scopedUsCounterSVGDisplayList); } else if (imageSource->isImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterImageBitmapDisplayList, new CustomCountHistogram("Blink.Canvas.DrawImage.ImageBitmap.DisplayList", 0, 10000000, 50)); timer.emplace(scopedUsCounterImageBitmapDisplayList); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterOthersDisplayList, new CustomCountHistogram("Blink.Canvas.DrawImage.Others.DisplayList", 0, 10000000, 50)); timer.emplace(scopedUsCounterOthersDisplayList); } } else { if (imageSource->isVideoElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterVideoCPU, new CustomCountHistogram("Blink.Canvas.DrawImage.Video.CPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterVideoCPU); } else if (imageSource->isCanvasElement()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterCanvasCPU, new CustomCountHistogram("Blink.Canvas.DrawImage.Canvas.CPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterCanvasCPU); } else if (imageSource->isSVGSource()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterSVGCPU, new CustomCountHistogram("Blink.Canvas.DrawImage.SVG.CPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterSVGCPU); } else if (imageSource->isImageBitmap()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterImageBitmapCPU, new CustomCountHistogram("Blink.Canvas.DrawImage.ImageBitmap.CPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterImageBitmapCPU); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterOthersCPU, new CustomCountHistogram("Blink.Canvas.DrawImage.Others.CPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterOthersCPU); } } draw( [this, &imageSource, &image, &srcRect, dstRect](SkCanvas* c, const SkPaint* paint) // draw lambda { drawImageInternal(c, imageSource, image.get(), srcRect, dstRect, paint); }, [this, &dstRect](const SkIRect& clipBounds) // overdraw test lambda { return rectContainsTransformedRect(dstRect, clipBounds); }, dstRect, CanvasRenderingContext2DState::ImagePaintType, imageSource->isOpaque() ? CanvasRenderingContext2DState::OpaqueImage : CanvasRenderingContext2DState::NonOpaqueImage); validateStateStack(); bool isExpensive = false; if (ExpensiveCanvasHeuristicParameters::SVGImageSourcesAreExpensive && imageSource->isSVGSource()) isExpensive = true; if (imageSize.width() * imageSize.height() > width() * height() * ExpensiveCanvasHeuristicParameters::ExpensiveImageSizeRatio) isExpensive = true; if (isExpensive) { ImageBuffer* buffer = imageBuffer(); if (buffer) buffer->setHasExpensiveOp(); } if (originClean() && wouldTaintOrigin(imageSource, executionContext)) setOriginTainted(); } void BaseRenderingContext2D::clearCanvas() { FloatRect canvasRect(0, 0, width(), height()); checkOverdraw(canvasRect, 0, CanvasRenderingContext2DState::NoImage, ClipFill); SkCanvas* c = drawingCanvas(); if (c) c->clear(hasAlpha() ? SK_ColorTRANSPARENT : SK_ColorBLACK); } bool BaseRenderingContext2D::rectContainsTransformedRect(const FloatRect& rect, const SkIRect& transformedRect) const { FloatQuad quad(rect); FloatQuad transformedQuad(FloatRect(transformedRect.x(), transformedRect.y(), transformedRect.width(), transformedRect.height())); return state().transform().mapQuad(quad).containsQuad(transformedQuad); } CanvasGradient* BaseRenderingContext2D::createLinearGradient(double x0, double y0, double x1, double y1) { CanvasGradient* gradient = CanvasGradient::create(FloatPoint(x0, y0), FloatPoint(x1, y1)); return gradient; } CanvasGradient* BaseRenderingContext2D::createRadialGradient(double x0, double y0, double r0, double x1, double y1, double r1, ExceptionState& exceptionState) { if (r0 < 0 || r1 < 0) { exceptionState.throwDOMException(IndexSizeError, String::format("The %s provided is less than 0.", r0 < 0 ? "r0" : "r1")); return nullptr; } CanvasGradient* gradient = CanvasGradient::create(FloatPoint(x0, y0), r0, FloatPoint(x1, y1), r1); return gradient; } CanvasPattern* BaseRenderingContext2D::createPattern(ExecutionContext* executionContext, const CanvasImageSourceUnion& imageSource, const String& repetitionType, ExceptionState& exceptionState) { CanvasImageSource* imageSourceInternal = toImageSourceInternal(imageSource, exceptionState); if (!imageSourceInternal) { return nullptr; } return createPattern(executionContext, imageSourceInternal, repetitionType, exceptionState); } CanvasPattern* BaseRenderingContext2D::createPattern(ExecutionContext* executionContext, CanvasImageSource* imageSource, const String& repetitionType, ExceptionState& exceptionState) { if (!imageSource) { return nullptr; } Pattern::RepeatMode repeatMode = CanvasPattern::parseRepetitionType(repetitionType, exceptionState); if (exceptionState.hadException()) return nullptr; SourceImageStatus status; FloatSize defaultObjectSize(width(), height()); RefPtr<Image> imageForRendering = imageSource->getSourceImageForCanvas(&status, PreferNoAcceleration, SnapshotReasonCreatePattern, defaultObjectSize); switch (status) { case NormalSourceImageStatus: break; case ZeroSizeCanvasSourceImageStatus: exceptionState.throwDOMException(InvalidStateError, String::format("The canvas %s is 0.", imageSource->elementSize(defaultObjectSize).width() ? "height" : "width")); return nullptr; case UndecodableSourceImageStatus: exceptionState.throwDOMException(InvalidStateError, "Source image is in the 'broken' state."); return nullptr; case InvalidSourceImageStatus: imageForRendering = Image::nullImage(); break; case IncompleteSourceImageStatus: return nullptr; default: ASSERT_NOT_REACHED(); return nullptr; } ASSERT(imageForRendering); bool originClean = !wouldTaintOrigin(imageSource, executionContext); return CanvasPattern::create(imageForRendering.release(), repeatMode, originClean); } bool BaseRenderingContext2D::computeDirtyRect(const FloatRect& localRect, SkIRect* dirtyRect) { SkIRect clipBounds; if (!drawingCanvas()->getClipDeviceBounds(&clipBounds)) return false; return computeDirtyRect(localRect, clipBounds, dirtyRect); } bool BaseRenderingContext2D::computeDirtyRect(const FloatRect& localRect, const SkIRect& transformedClipBounds, SkIRect* dirtyRect) { FloatRect canvasRect = state().transform().mapRect(localRect); if (alphaChannel(state().shadowColor())) { FloatRect shadowRect(canvasRect); shadowRect.move(state().shadowOffset()); shadowRect.inflate(state().shadowBlur()); canvasRect.unite(shadowRect); } SkIRect canvasIRect; static_cast<SkRect>(canvasRect).roundOut(&canvasIRect); if (!canvasIRect.intersect(transformedClipBounds)) return false; if (dirtyRect) *dirtyRect = canvasIRect; return true; } ImageData* BaseRenderingContext2D::createImageData(ImageData* imageData, ExceptionState &exceptionState) const { ImageData* result = ImageData::create(imageData->size()); if (!result) exceptionState.throwRangeError("Out of memory at ImageData creation"); return result; } ImageData* BaseRenderingContext2D::createImageData(double sw, double sh, ExceptionState& exceptionState) const { if (!sw || !sh) { exceptionState.throwDOMException(IndexSizeError, String::format("The source %s is 0.", sw ? "height" : "width")); return nullptr; } FloatSize logicalSize(fabs(sw), fabs(sh)); if (!logicalSize.isExpressibleAsIntSize()) return nullptr; IntSize size = expandedIntSize(logicalSize); if (size.width() < 1) size.setWidth(1); if (size.height() < 1) size.setHeight(1); ImageData* result = ImageData::create(size); if (!result) exceptionState.throwRangeError("Out of memory at ImageData creation"); return result; } ImageData* BaseRenderingContext2D::getImageData(double sx, double sy, double sw, double sh, ExceptionState& exceptionState) const { m_usageCounters.numGetImageDataCalls++; if (!originClean()) exceptionState.throwSecurityError("The canvas has been tainted by cross-origin data."); else if (!sw || !sh) exceptionState.throwDOMException(IndexSizeError, String::format("The source %s is 0.", sw ? "height" : "width")); if (exceptionState.hadException()) return nullptr; if (sw < 0) { sx += sw; sw = -sw; } if (sh < 0) { sy += sh; sh = -sh; } FloatRect logicalRect(sx, sy, sw, sh); if (logicalRect.width() < 1) logicalRect.setWidth(1); if (logicalRect.height() < 1) logicalRect.setHeight(1); if (!logicalRect.isExpressibleAsIntRect()) return nullptr; Optional<ScopedUsHistogramTimer> timer; if (imageBuffer() && imageBuffer()->isAccelerated()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterGPU, new CustomCountHistogram("Blink.Canvas.GetImageData.GPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterGPU); } else if (imageBuffer() && imageBuffer()->isRecording()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterDisplayList, new CustomCountHistogram("Blink.Canvas.GetImageData.DisplayList", 0, 10000000, 50)); timer.emplace(scopedUsCounterDisplayList); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterCPU, new CustomCountHistogram("Blink.Canvas.GetImageData.CPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterCPU); } IntRect imageDataRect = enclosingIntRect(logicalRect); ImageBuffer* buffer = imageBuffer(); if (!buffer || isContextLost()) { ImageData* result = ImageData::create(imageDataRect.size()); if (!result) exceptionState.throwRangeError("Out of memory at ImageData creation"); return result; } WTF::ArrayBufferContents contents; if (!buffer->getImageData(Unmultiplied, imageDataRect, contents)) { exceptionState.throwRangeError("Out of memory at ImageData creation"); return nullptr; } DOMArrayBuffer* arrayBuffer = DOMArrayBuffer::create(contents); return ImageData::create( imageDataRect.size(), DOMUint8ClampedArray::create(arrayBuffer, 0, arrayBuffer->byteLength())); } void BaseRenderingContext2D::putImageData(ImageData* data, double dx, double dy, ExceptionState& exceptionState) { putImageData(data, dx, dy, 0, 0, data->width(), data->height(), exceptionState); } void BaseRenderingContext2D::putImageData(ImageData* data, double dx, double dy, double dirtyX, double dirtyY, double dirtyWidth, double dirtyHeight, ExceptionState& exceptionState) { m_usageCounters.numPutImageDataCalls++; if (data->data()->bufferBase()->isNeutered()) { exceptionState.throwDOMException(InvalidStateError, "The source data has been neutered."); return; } ImageBuffer* buffer = imageBuffer(); if (!buffer) return; if (dirtyWidth < 0) { dirtyX += dirtyWidth; dirtyWidth = -dirtyWidth; } if (dirtyHeight < 0) { dirtyY += dirtyHeight; dirtyHeight = -dirtyHeight; } FloatRect clipRect(dirtyX, dirtyY, dirtyWidth, dirtyHeight); clipRect.intersect(IntRect(0, 0, data->width(), data->height())); IntSize destOffset(static_cast<int>(dx), static_cast<int>(dy)); IntRect destRect = enclosingIntRect(clipRect); destRect.move(destOffset); destRect.intersect(IntRect(IntPoint(), buffer->size())); if (destRect.isEmpty()) return; Optional<ScopedUsHistogramTimer> timer; if (imageBuffer() && imageBuffer()->isAccelerated()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterGPU, new CustomCountHistogram("Blink.Canvas.PutImageData.GPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterGPU); } else if (imageBuffer() && imageBuffer()->isRecording()) { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterDisplayList, new CustomCountHistogram("Blink.Canvas.PutImageData.DisplayList", 0, 10000000, 50)); timer.emplace(scopedUsCounterDisplayList); } else { DEFINE_THREAD_SAFE_STATIC_LOCAL(CustomCountHistogram, scopedUsCounterCPU, new CustomCountHistogram("Blink.Canvas.PutImageData.CPU", 0, 10000000, 50)); timer.emplace(scopedUsCounterCPU); } IntRect sourceRect(destRect); sourceRect.move(-destOffset); checkOverdraw(destRect, 0, CanvasRenderingContext2DState::NoImage, UntransformedUnclippedFill); buffer->putByteArray(Unmultiplied, data->data()->data(), IntSize(data->width(), data->height()), sourceRect, IntPoint(destOffset)); didDraw(destRect); } void BaseRenderingContext2D::inflateStrokeRect(FloatRect& rect) const { // Fast approximation of the stroke's bounding rect. // This yields a slightly oversized rect but is very fast // compared to Path::strokeBoundingRect(). static const double root2 = sqrtf(2); double delta = state().lineWidth() / 2; if (state().getLineJoin() == MiterJoin) delta *= state().miterLimit(); else if (state().getLineCap() == SquareCap) delta *= root2; rect.inflate(delta); } bool BaseRenderingContext2D::imageSmoothingEnabled() const { return state().imageSmoothingEnabled(); } void BaseRenderingContext2D::setImageSmoothingEnabled(bool enabled) { if (enabled == state().imageSmoothingEnabled()) return; modifiableState().setImageSmoothingEnabled(enabled); } String BaseRenderingContext2D::imageSmoothingQuality() const { return state().imageSmoothingQuality(); } void BaseRenderingContext2D::setImageSmoothingQuality(const String& quality) { if (quality == state().imageSmoothingQuality()) return; modifiableState().setImageSmoothingQuality(quality); } void BaseRenderingContext2D::checkOverdraw(const SkRect& rect, const SkPaint* paint, CanvasRenderingContext2DState::ImageType imageType, DrawType drawType) { SkCanvas* c = drawingCanvas(); if (!c || !imageBuffer()->isRecording()) return; SkRect deviceRect; if (drawType == UntransformedUnclippedFill) { deviceRect = rect; } else { ASSERT(drawType == ClipFill); if (state().hasComplexClip()) return; SkIRect skIBounds; if (!c->getClipDeviceBounds(&skIBounds)) return; deviceRect = SkRect::Make(skIBounds); } const SkImageInfo& imageInfo = c->imageInfo(); if (!deviceRect.contains(SkRect::MakeWH(imageInfo.width(), imageInfo.height()))) return; bool isSourceOver = true; unsigned alpha = 0xFF; if (paint) { if (paint->getLooper() || paint->getImageFilter() || paint->getMaskFilter()) return; SkXfermode* xfermode = paint->getXfermode(); if (xfermode) { SkXfermode::Mode mode; if (xfermode->asMode(&mode)) { isSourceOver = mode == SkXfermode::kSrcOver_Mode; if (!isSourceOver && mode != SkXfermode::kSrc_Mode && mode != SkXfermode::kClear_Mode) return; // The code below only knows how to handle Src, SrcOver, and Clear } else { // unknown xfermode ASSERT_NOT_REACHED(); return; } } alpha = paint->getAlpha(); if (isSourceOver && imageType == CanvasRenderingContext2DState::NoImage) { SkShader* shader = paint->getShader(); if (shader) { if (shader->isOpaque() && alpha == 0xFF) imageBuffer()->willOverwriteCanvas(); return; } } } if (isSourceOver) { // With source over, we need to certify that alpha == 0xFF for all pixels if (imageType == CanvasRenderingContext2DState::NonOpaqueImage) return; if (alpha < 0xFF) return; } imageBuffer()->willOverwriteCanvas(); } void BaseRenderingContext2D::trackDrawCall(DrawCallType callType, Path2D* path2d) { m_usageCounters.numDrawCalls[callType]++; if (callType == FillPath) { SkPath skPath; if (path2d) { skPath = path2d->path().getSkPath(); } else { skPath = m_path.getSkPath(); } if (!(skPath.getConvexity() == SkPath::kConvex_Convexity)) { m_usageCounters.numNonConvexFillPathCalls++; } } if (callType == FillText || callType == FillPath || callType == StrokeText || callType == StrokePath || callType == FillRect || callType == StrokeRect) { CanvasStyle* canvasStyle; if (callType == FillText || callType == FillPath || callType == FillRect) { canvasStyle = state().fillStyle(); } else { canvasStyle = state().strokeStyle(); } if (canvasStyle->getCanvasGradient()) { m_usageCounters.numGradients++; } if (canvasStyle->getCanvasPattern()) { m_usageCounters.numPatterns++; } } if (state().shadowBlur() > 0.0 && SkColorGetA(state().shadowColor()) > 0) { m_usageCounters.numBlurredShadows++; } if (state().hasComplexClip()) { m_usageCounters.numDrawWithComplexClips++; } if (stateHasFilter()) { m_usageCounters.numFilters++; } } const BaseRenderingContext2D::UsageCounters& BaseRenderingContext2D::getUsage() { return m_usageCounters; } DEFINE_TRACE(BaseRenderingContext2D) { visitor->trace(m_stateStack); } BaseRenderingContext2D::UsageCounters::UsageCounters() : numDrawCalls {0, 0, 0, 0, 0, 0}, numNonConvexFillPathCalls(0), numGradients(0), numPatterns(0), numDrawWithComplexClips(0), numBlurredShadows(0), numFilters(0), numGetImageDataCalls(0), numPutImageDataCalls(0), numClearRectCalls(0), numDrawFocusCalls(0) {} } // namespace blink
/*! @file Defines the `boost::hana::Identity` data type. @copyright Louis Dionne 2014 Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt) */ #ifndef BOOST_HANA_IDENTITY_HPP #define BOOST_HANA_IDENTITY_HPP #include <boost/hana/applicative/mcd.hpp> #include <boost/hana/comparable/equal_mcd.hpp> #include <boost/hana/core/datatype.hpp> #include <boost/hana/detail/constexpr.hpp> #include <boost/hana/foldable/unpack_mcd.hpp> #include <boost/hana/functor/fmap_mcd.hpp> #include <boost/hana/monad/flatten_mcd.hpp> #include <boost/hana/orderable/less_mcd.hpp> #include <boost/hana/traversable/traverse_mcd.hpp> namespace boost { namespace hana { //! @ingroup group-datatypes //! The identity data type. //! //! This is a trivial instance of several type classes. It is especially //! useful for unit testing purposes, where one wants a lightweight and //! easy-to-reason-with instance of a type class. //! //! ## Instance of //! `Comparable`, `Orderable`, `Functor`, `Applicative`, `Monad`, //! `Foldable` and `Traversable`. struct Identity { }; namespace detail { namespace repr { template <typename X, typename = operators<Comparable, Orderable, Monad>> struct identity { X value; using hana_datatype = Identity; }; }} //! Wrap a value in the `Identity` data type. BOOST_HANA_CONSTEXPR_LAMBDA auto identity = [](auto x) { return detail::repr::identity<decltype(x)>{x}; }; template <> struct Comparable::instance<Identity, Identity> : Comparable::equal_mcd { template <typename Id1, typename Id2> static constexpr auto equal_impl(Id1 x, Id2 y) { return equal(x.value, y.value); } }; template <> struct Orderable::instance<Identity, Identity> : Orderable::less_mcd { template <typename Id1, typename Id2> static constexpr auto less_impl(Id1 x, Id2 y) { return less(x.value, y.value); } }; template <> struct Functor::instance<Identity> : Functor::fmap_mcd { template <typename F, typename Id> static constexpr auto fmap_impl(F f, Id self) { return identity(f(self.value)); } }; template <> struct Applicative::instance<Identity> : Applicative::mcd { template <typename X> static constexpr auto lift_impl(X x) { return identity(x); } template <typename F, typename X> static constexpr auto ap_impl(F f, X x) { return identity(f.value(x.value)); } }; template <> struct Monad::instance<Identity> : Monad::flatten_mcd<Identity> { template <typename Id> static constexpr auto flatten_impl(Id self) { return self.value; } }; template <> struct Foldable::instance<Identity> : Foldable::unpack_mcd { template <typename Id, typename F> static constexpr auto unpack_impl(Id self, F f) { return f(self.value); } }; template <> struct Traversable::instance<Identity> : Traversable::traverse_mcd { template <typename A, typename F, typename Id> static constexpr auto traverse_impl(F f, Id self) { return fmap(identity, f(self.value)); } }; }} // end namespace boost::hana #endif // !BOOST_HANA_IDENTITY_HPP
// YaMangClient.cpp : 응용 프로그램에 대한 진입점을 정의합니다. // #include "stdafx.h" #include "YaMangClient.h" #ifdef DEBUG #include <crtdbg.h> #endif // DEBUG #include "Logger.h" #include "MainWindow.h" #include "NetworkManager.h" #include "Exception.h" INT_PTR g_LogHandle = -1; int APIENTRY _tWinMain( _In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPTSTR lpCmdLine, _In_ int nCmdShow ) { UNREFERENCED_PARAMETER( hInstance ); UNREFERENCED_PARAMETER( hPrevInstance ); UNREFERENCED_PARAMETER( lpCmdLine ); _CrtSetDbgFlag( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); // 메모리 릭을 체크하려면 아래의 #### 칸에 릭 난 곳 { 숫자 } 표기 된 숫자를 넣어주면 됩니다. // _CrtSetBreakAlloc( #### ); // _CrtSetBreakAlloc( 192 ); // SetUnhandledExceptionFilter( ExceptionFilter ); InstallCrashReporter(); // set_terminate() must be called from every thread BT_SetTerminate(); BT_InsLogEntry( g_LogHandle, BTLL_INFO, _T( "Entering main() function" ) ); #ifdef _PRINT_CONSOLE Logger::GetInstance()->CreateConsole(); #endif // test code std::wstring parameter = lpCmdLine; printf_s( "parameter:%S \n", parameter.c_str() ); srand( static_cast<unsigned int>( time( NULL ) ) ); unsigned int pos = parameter.find( ' ' ); if ( -1 == pos ) { NetworkManager::GetInstance()->SetRoomNumber( 1 ); NetworkManager::GetInstance()->SetMyPlayerID( 1000 + rand() % 101 ); } else { if ( -1 == parameter.find( ' ', pos + 1 ) ) { std::wstring roomNumber = parameter.substr( 0, pos ); std::wstring playerID = parameter.substr( pos+1 ); printf_s( "ROOM:%S PLAYER:%S \n", roomNumber.c_str( ), playerID.c_str( ) ); NetworkManager::GetInstance( )->SetRoomNumber( std::stoi( roomNumber ) ); NetworkManager::GetInstance( )->SetMyPlayerID( std::stoi( playerID ) ); } else { NetworkManager::GetInstance()->SetRoomNumber( 1 ); NetworkManager::GetInstance()->SetMyPlayerID( 1000 + rand() % 101 ); } } // WS_POPUPWINDOW // WS_OVERLAPPEDWINDOW if ( false == MainWindow::GetInstance()->Create( L"YaMang", WS_POPUPWINDOW ) ) { return 0; } MainWindow::GetInstance()->Display( nCmdShow ); #ifndef DEBUG HANDLE mutex = CreateMutex( NULL, FALSE, L"YaMangClientMutex" ); if ( mutex == NULL ) { MessageBox( MainWindow::GetInstance()->Window(), L"Create Mutex Error", L"Mutex", MB_OK | MB_ICONERROR ); return -1; } DWORD waitResult = WaitForSingleObject( mutex, 1 ); switch ( waitResult ) { case WAIT_TIMEOUT: { MessageBox( MainWindow::GetInstance()->Window(), L"Client Already Running", L"Mutex", MB_OK | MB_ICONERROR ); MainWindow::Release(); return -1; } break; case WAIT_OBJECT_0: case WAIT_ABANDONED: default: break; } #endif int result = MainWindow::GetInstance()->RunGame(); MainWindow::Release(); #ifdef _PRINT_CONSOLE Logger::GetInstance()->DestroyConsole(); Logger::Release(); #endif BT_InsLogEntry( g_LogHandle, BTLL_INFO, _T( "Leaving main() function" ) ); BT_CloseLogFile( g_LogHandle ); return result; }
/*******************************************************************/ /* */ /* ADOBE CONFIDENTIAL */ /* _ _ _ _ _ _ _ _ _ _ _ _ _ */ /* */ /* Copyright 2011 Adobe Systems Incorporated */ /* All Rights Reserved. */ /* */ /* NOTICE: All information contained herein is, and remains the */ /* property of Adobe Systems Incorporated and its suppliers, if */ /* any. The intellectual and technical concepts contained */ /* herein are proprietary to Adobe Systems Incorporated and its */ /* suppliers and may be covered by U.S. and Foreign Patents, */ /* patents in process, and are protected by trade secret or */ /* copyright law. Dissemination of this information or */ /* reproduction of this material is strictly forbidden unless */ /* prior written permission is obtained from Adobe Systems */ /* Incorporated. */ /* */ /*******************************************************************/ #include "ControlSurfaceBase.h" // adobesdk #include "adobesdk/controlsurface/plugin/ControlSurfaceMarkerSuite.h" namespace adobesdk { namespace { ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurface_GetConfigIdentifier(ADOBESDK_ControlSurfaceRef inControlSurfaceRef, ADOBESDK_String* outIdentifier) { return reinterpret_cast<const ControlSurfaceBase*>(inControlSurfaceRef)->GetConfigIdentifier(outIdentifier); } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurface_GetControlSurfaceFlags(ADOBESDK_ControlSurfaceRef inControlSurfaceRef, uint32_t* outFlags) { return reinterpret_cast<const ControlSurfaceBase*>(inControlSurfaceRef)->GetControlSurfaceFlags(outFlags); } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurface_GetTransportRef( ADOBESDK_ControlSurfaceRef inControlSurfaceRef, ADOBESDK_ControlSurfaceTransportRef* outTransportRef) { return reinterpret_cast<ControlSurfaceBase*>(inControlSurfaceRef)->GetTransportRef(outTransportRef); } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurface_GetMixerRef( ADOBESDK_ControlSurfaceRef inControlSurfaceRef, ADOBESDK_ControlSurfaceMixerRef* outMixerRef) { return reinterpret_cast<ControlSurfaceBase*>(inControlSurfaceRef)->GetMixerRef(outMixerRef); } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurface_GetMarkerRef( ADOBESDK_ControlSurfaceRef inControlSurfaceRef, ADOBESDK_ControlSurfaceMarkerRef* outMarkerRef) { return reinterpret_cast<ControlSurfaceBase*>(inControlSurfaceRef)->GetMarkerRef(outMarkerRef); } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurface_GetCommandRef( ADOBESDK_ControlSurfaceRef inControlSurfaceRef, ADOBESDK_ControlSurfaceCommandRef* outCommandRef) { return reinterpret_cast<ControlSurfaceBase*>(inControlSurfaceRef)->GetCommandRef(outCommandRef); } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurface_Update(ADOBESDK_ControlSurfaceRef inControlSurfaceRef) { return reinterpret_cast<ControlSurfaceBase*>(inControlSurfaceRef)->Update(); } ////////////////////////////////////////////////////////////////////////////// /// ADOBESDK_ControlSurfaceSuite1 sControlSurfaceSuite = { ControlSurface_GetConfigIdentifier, ControlSurface_GetControlSurfaceFlags, ControlSurface_GetTransportRef, ControlSurface_GetMixerRef, ControlSurface_GetMarkerRef, ControlSurface_GetCommandRef, ControlSurface_Update }; } // namespace ////////////////////////////////////////////////////////////////////////////// /// ControlSurfaceBase::ControlSurfaceBase() { } ////////////////////////////////////////////////////////////////////////////// /// ControlSurfaceBase::~ControlSurfaceBase() { } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurfaceBase::GetConfigIdentifier(ADOBESDK_String* outCongigIdentifier) const { return kSPUnimplementedError; } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurfaceBase::GetControlSurfaceFlags(uint32_t* outControlSurfaceFlags) const { *outControlSurfaceFlags = 0; return kSPNoError; } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurfaceBase::GetTransportRef(ADOBESDK_ControlSurfaceTransportRef* outTransportRef) { *outTransportRef = 0; return kSPNoError; } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurfaceBase::GetMixerRef(ADOBESDK_ControlSurfaceMixerRef* outMixerRef) { *outMixerRef = 0; return kSPNoError; } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurfaceBase::GetMarkerRef(ADOBESDK_ControlSurfaceMarkerRef* outMarkerRef) { *outMarkerRef = 0; return kSPNoError; } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurfaceBase::GetCommandRef(ADOBESDK_ControlSurfaceCommandRef* outCommandRef) { *outCommandRef = 0; return kSPNoError; } ////////////////////////////////////////////////////////////////////////////// /// SPErr ControlSurfaceBase::Update() { return kSPUnimplementedError; } ////////////////////////////////////////////////////////////////////////////// /// void ControlSurfaceBase::RegisterSuite(SPSuitesSuite* inSPSuitesSuite, SPSuiteListRef inSuiteList) { SPSuiteRef controlSurfaceSuiteRef = 0; inSPSuitesSuite->AddSuite( inSuiteList, NULL, kADOBESDK_ControlSurfaceSuite, kADOBESDK_ControlSurfaceSuite_Version1, kADOBESDK_ControlSurfaceSuite_Version1, &sControlSurfaceSuite, &controlSurfaceSuiteRef); } } // namespace adobesdk
#include <bits/stdc++.h> #include <ext/pb_ds/assoc_container.hpp> using namespace __gnu_pbds; using namespace std; #define ff first #define ss second #define int long long #define pb push_back #define mp make_pair #define pii pair<int, int> #define vi vector<int> #define mii map<int, int> #define pqb priority_queue<int> #define pqs priority_queue<int, vi, greater<int>> #define setbits(x) __builtin_popcountll(x) #define zrobits(x) __builtin_ctzll(x) #define mod 1000000007 #define inf 1e18 #define ps(x, y) fixed << setprecision(y) << x #define mk(arr, n, type) type *arr = new type[n]; #define w(x) \ int x; \ cin >> x; \ while (x--) #define FIO \ ios_base::sync_with_stdio(0); \ cin.tie(0); \ cout.tie(0) mt19937 rng(chrono::steady_clock::now().time_since_epoch().count()); typedef tree<int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update> pbds; int get(string &s) { int n = s.length(); vi pre(n + 2, inf); vi suf(n + 2, inf); vi cnt(n + 1, 0); for (int i = 1; i <= n; ++i) { cnt[i] = cnt[i - 1]; if (s[i - 1] == '(') cnt[i]++; else cnt[i]--; } for (int i = 1; i <= n; ++i) pre[i] = min(pre[i - 1], cnt[i]); for (int i = n; i >= 1; --i) suf[i] = min(suf[i + 1], cnt[i]); int ans = 0; for (int i = 1; i <= n; ++i) { bool c1 = (suf[i] >= cnt[i - 1]); bool c2 = (pre[i - 1] >= -cnt[n]); if (c1 & c2) ans++; } return ans; } int32_t main() { FIO; int n; cin >> n; string s; cin >> s; int cnt = 0; for (char ch : s) if (ch == '(') cnt++; else cnt--; if (cnt) { cout << 0 << '\n'; cout << 1 << ' ' << 1 << '\n'; return 0; } int mx = get(s); pii ids = {1, 1}; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { if (s[i] == s[j]) continue; swap(s[i], s[j]); int cur = get(s); if (cur >= mx) mx = cur, ids = {i + 1, j + 1}; swap(s[i], s[j]); } } cout << mx << '\n' << ids.ff << ' ' << ids.ss << '\n'; return 0; }
// file : build2/parser.cxx -*- C++ -*- // copyright : Copyright (c) 2014-2019 Code Synthesis Ltd // license : MIT; see accompanying LICENSE file #include <build2/parser.hxx> #include <sstream> #include <iostream> // cout #include <libbutl/filesystem.mxx> // path_search(), path_match() #include <build2/dump.hxx> #include <build2/file.hxx> #include <build2/scope.hxx> #include <build2/module.hxx> #include <build2/target.hxx> #include <build2/context.hxx> #include <build2/function.hxx> #include <build2/variable.hxx> #include <build2/filesystem.hxx> #include <build2/diagnostics.hxx> #include <build2/prerequisite.hxx> using namespace std; namespace build2 { using type = token_type; class parser::enter_scope { public: enter_scope (): p_ (nullptr), r_ (nullptr), s_ (nullptr), b_ (nullptr) {} enter_scope (parser& p, dir_path&& d) : p_ (&p), r_ (p.root_), s_ (p.scope_), b_ (p.pbase_) { // Try hard not to call normalize(). Most of the time we will go just // one level deeper. // bool n (true); if (d.relative ()) { // Relative scopes are opened relative to out, not src. // if (d.simple () && !d.current () && !d.parent ()) { d = dir_path (p.scope_->out_path ()) /= d.string (); n = false; } else d = p.scope_->out_path () / d; } if (n) d.normalize (); p.switch_scope (d); } ~enter_scope () { if (p_ != nullptr) { p_->scope_ = s_; p_->root_ = r_; p_->pbase_ = b_; } } explicit operator bool () const {return p_ != nullptr;} // Note: move-assignable to empty only. // enter_scope (enter_scope&& x) {*this = move (x);} enter_scope& operator= (enter_scope&& x) { if (this != &x) { p_ = x.p_; r_ = x.r_; s_ = x.s_; b_ = x.b_; x.p_ = nullptr; } return *this; } enter_scope (const enter_scope&) = delete; enter_scope& operator= (const enter_scope&) = delete; private: parser* p_; scope* r_; scope* s_; const dir_path* b_; // Pattern base. }; class parser::enter_target { public: enter_target (): p_ (nullptr), t_ (nullptr) {} enter_target (parser& p, target& t) : p_ (&p), t_ (p.target_) { p.target_ = &t; } enter_target (parser& p, name&& n, // If n.pair, then o is out dir. name&& o, bool implied, const location& loc, tracer& tr) : p_ (&p), t_ (p.target_) { // Find or insert. // auto r (process_target (p, n, o, loc)); p.target_ = &targets.insert (*r.first, // target type move (n.dir), move (o.dir), move (n.value), move (r.second), // extension implied, tr).first; } static const target* find_target (parser& p, name& n, // If n.pair, then o is out dir. name& o, const location& loc, tracer& tr) { auto r (process_target (p, n, o, loc)); return targets.find (*r.first, // target type n.dir, o.dir, n.value, r.second, // extension tr); } static pair<const target_type*, optional<string>> process_target (parser& p, name& n, // If n.pair, then o is out dir. name& o, const location& loc) { auto r (p.scope_->find_target_type (n, loc)); if (r.first == nullptr) p.fail (loc) << "unknown target type " << n.type; bool src (n.pair); // If out-qualified, then it is from src. if (src) { assert (n.pair == '@'); if (!o.directory ()) p.fail (loc) << "expected directory after @"; } dir_path& d (n.dir); const dir_path& sd (p.scope_->src_path ()); const dir_path& od (p.scope_->out_path ()); if (d.empty ()) d = src ? sd : od; // Already dormalized. else { if (d.relative ()) d = (src ? sd : od) / d; d.normalize (); } dir_path out; if (src && sd != od) // If in-source build, then out must be empty. { out = o.dir.relative () ? od / o.dir : move (o.dir); out.normalize (); } o.dir = move (out); // Result. return r; } ~enter_target () { if (p_ != nullptr) p_->target_ = t_; } // Note: move-assignable to empty only. // enter_target (enter_target&& x) {*this = move (x);} enter_target& operator= (enter_target&& x) { p_ = x.p_; t_ = x.t_; x.p_ = nullptr; return *this;} enter_target (const enter_target&) = delete; enter_target& operator= (const enter_target&) = delete; private: parser* p_; target* t_; }; class parser::enter_prerequisite { public: enter_prerequisite (): p_ (nullptr), r_ (nullptr) {} enter_prerequisite (parser& p, prerequisite& r) : p_ (&p), r_ (p.prerequisite_) { assert (p.target_ != nullptr); p.prerequisite_ = &r; } ~enter_prerequisite () { if (p_ != nullptr) p_->prerequisite_ = r_; } // Note: move-assignable to empty only. // enter_prerequisite (enter_prerequisite&& x) {*this = move (x);} enter_prerequisite& operator= (enter_prerequisite&& x) { p_ = x.p_; r_ = x.r_; x.p_ = nullptr; return *this;} enter_prerequisite (const enter_prerequisite&) = delete; enter_prerequisite& operator= (const enter_prerequisite&) = delete; private: parser* p_; prerequisite* r_; }; void parser:: parse_buildfile (istream& is, const path& p, scope& root, scope& base) { path_ = &p; lexer l (is, *path_); lexer_ = &l; root_ = &root; scope_ = &base; pbase_ = scope_->src_path_; target_ = nullptr; prerequisite_ = nullptr; default_target_ = nullptr; enter_buildfile (p); // Needs scope_. token t; type tt; next (t, tt); parse_clause (t, tt); if (tt != type::eos) fail (t) << "unexpected " << t; process_default_target (t); } token parser:: parse_variable (lexer& l, scope& s, const variable& var, type kind) { path_ = &l.name (); lexer_ = &l; scope_ = &s; pbase_ = scope_->src_path_; // Normally NULL. target_ = nullptr; prerequisite_ = nullptr; token t; type tt; parse_variable (t, tt, var, kind); return t; } pair<value, token> parser:: parse_variable_value (lexer& l, scope& s, const dir_path* b, const variable& var) { path_ = &l.name (); lexer_ = &l; scope_ = &s; pbase_ = b; target_ = nullptr; prerequisite_ = nullptr; token t; type tt; value rhs (parse_variable_value (t, tt)); value lhs; apply_value_attributes (&var, lhs, move (rhs), type::assign); return make_pair (move (lhs), move (t)); } bool parser:: parse_clause (token& t, type& tt, bool one) { tracer trace ("parser::parse_clause", &path_); // clause() should always stop at a token that is at the beginning of // the line (except for eof). That is, if something is called to parse // a line, it should parse it until newline (or fail). This is important // for if-else blocks, directory scopes, etc., that assume the } token // they see is on the new line. // bool parsed (false); while (tt != type::eos && !(one && parsed)) { // Extract attributes if any. // assert (attributes_.empty ()); auto at (attributes_push (t, tt)); // We always start with one or more names. // if (tt != type::word && tt != type::lcbrace && // Untyped name group: '{foo ...' tt != type::dollar && // Variable expansion: '$foo ...' tt != type::lparen && // Eval context: '(foo) ...' tt != type::colon) // Empty name: ': ...' { // Something else. Let our caller handle that. // if (at.first) fail (at.second) << "attributes before " << t; else attributes_pop (); break; } // Now we will either parse something or fail. // if (!parsed) parsed = true; // See if this is one of the directives. // if (tt == type::word && keyword (t)) { const string& n (t.value); void (parser::*f) (token&, type&) = nullptr; // @@ Is this the only place where some of these are valid? Probably // also in the var namespace? // if (n == "assert" || n == "assert!") { f = &parser::parse_assert; } else if (n == "print") // Unlike text goes to stdout. { f = &parser::parse_print; } else if (n == "fail" || n == "warn" || n == "info" || n == "text") { f = &parser::parse_diag; } else if (n == "dump") { f = &parser::parse_dump; } else if (n == "source") { f = &parser::parse_source; } else if (n == "include") { f = &parser::parse_include; } else if (n == "run") { f = &parser::parse_run; } else if (n == "import") { f = &parser::parse_import; } else if (n == "export") { f = &parser::parse_export; } else if (n == "using" || n == "using?") { f = &parser::parse_using; } else if (n == "define") { f = &parser::parse_define; } else if (n == "if" || n == "if!") { f = &parser::parse_if_else; } else if (n == "else" || n == "elif" || n == "elif!") { // Valid ones are handled in if_else(). // fail (t) << n << " without if"; } else if (n == "for") { f = &parser::parse_for; } if (f != nullptr) { if (at.first) fail (at.second) << "attributes before " << n; else attributes_pop (); (this->*f) (t, tt); continue; } } location nloc (get_location (t)); names ns (parse_names (t, tt, pattern_mode::ignore)); // Allow things like function calls that don't result in anything. // if (tt == type::newline && ns.empty ()) { if (at.first) fail (at.second) << "standalone attributes"; else attributes_pop (); next (t, tt); continue; } // Check if a string is a wildcard pattern. // auto pattern = [] (const string& s) { return s.find_first_of ("*?") != string::npos; }; // If we have a colon, then this is target-related. // if (tt == type::colon) { // While '{}:' means empty name, '{$x}:' where x is empty list // means empty list. // if (ns.empty ()) fail (t) << "expected target before :"; // Call the specified parsing function (either variable or block) for // each target. We handle multiple targets by replaying the tokens. // since the value/block may contain variable expansions that would be // sensitive to the target context in which they are evaluated. The // function signature is: // // void (token& t, type& tt, const target_type* type, string pat) // auto for_each = [this, &trace, &pattern, &t, &tt, &ns, &nloc] (auto&& f) { // Note: watch out for an out-qualified single target (two names). // replay_guard rg (*this, ns.size () > 2 || (ns.size () == 2 && !ns[0].pair)); for (auto i (ns.begin ()), e (ns.end ()); i != e; ) { name& n (*i); if (n.qualified ()) fail (nloc) << "project name in target " << n; // Figure out if this is a target or a target type/pattern (yeah, // it can be a mixture). // if (pattern (n.value)) { if (n.pair) fail (nloc) << "out-qualified target type/pattern-specific " << "variable"; // If we have the directory, then it is the scope. // enter_scope sg; if (!n.dir.empty ()) sg = enter_scope (*this, move (n.dir)); // Resolve target type. If none is specified or if it is '*', // use the root of the hierarchy. So these are all equivalent: // // *: foo = bar // {*}: foo = bar // *{*}: foo = bar // const target_type* ti ( n.untyped () || n.type == "*" ? &target::static_type : scope_->find_target_type (n.type)); if (ti == nullptr) fail (nloc) << "unknown target type " << n.type; f (t, tt, ti, move (n.value)); } else { name o (n.pair ? move (*++i) : name ()); enter_target tg (*this, move (n), move (o), true /* implied */, nloc, trace); f (t, tt, nullptr, string ()); } if (++i != e) rg.play (); // Replay. } }; next (t, tt); if (tt == type::newline) { // See if this is a target block. // if (peek () == type::lcbrace) { next (t, tt); // Should be on its own line. // if (next (t, tt) != type::newline) fail (t) << "expected newline after {"; if (at.first) fail (at.second) << "attributes before target block"; else attributes_pop (); // Parse the block for each target. // for_each ([this] (token& t, type& tt, const target_type* type, string pat) { next (t, tt); // First token inside the block. parse_variable_block (t, tt, type, move (pat)); if (tt != type::rcbrace) fail (t) << "expected } instead of " << t; }); // Should be on its own line. // if (next (t, tt) == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline after }"; continue; } // If this is not a block, then it is a target without any // prerequisites. Fall through. } // Target-specific variable assignment or dependency declaration, // including a dependency chain and/or prerequisite-specific variable // assignment. // if (at.first) fail (at.second) << "attributes before target"; else attributes_pop (); auto at (attributes_push (t, tt)); if (tt == type::word || tt == type::lcbrace || tt == type::dollar || tt == type::lparen || tt == type::newline || tt == type::eos) { // @@ PAT: currently we pattern-expand target-specific vars. // const location ploc (get_location (t)); names pns (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::expand) : names ()); // Target-specific variable assignment. // if (tt == type::assign || tt == type::prepend || tt == type::append) { type akind (tt); const location aloc (get_location (t)); const variable& var (parse_variable_name (move (pns), ploc)); apply_variable_attributes (var); if (var.visibility > variable_visibility::target) { fail (nloc) << "variable " << var << " has " << var.visibility << " visibility but is assigned on a target"; } // Parse the assignment for each target. // for_each ([this, &var, akind, &aloc] (token& t, type& tt, const target_type* type, string pat) { if (type == nullptr) parse_variable (t, tt, var, akind); else parse_type_pattern_variable (t, tt, *type, move (pat), var, akind, aloc); }); } // Dependency declaration potentially followed by a chain and/or // a prerequisite-specific variable assignment. // else { if (at.first) fail (at.second) << "attributes before prerequisites"; else attributes_pop (); // Make sure none of our targets are patterns (maybe we will allow // quoting later). // for (const name& n: ns) { if (pattern (n.value)) fail (nloc) << "pattern in target " << n; } parse_dependency (t, tt, move (ns), nloc, move (pns), ploc); } if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; continue; } else fail (t) << "unexpected " << t; if (tt == type::eos) continue; fail (t) << "expected newline instead of " << t; } // Variable assignment. // // This can take any of the following forms: // // x = y // foo/ x = y (ns will have two elements) // foo/ [attrs] x = y (tt will be '[') // // In the future we may also want to support: // // foo/ bar/ x = y // if (tt == type::assign || tt == type::prepend || tt == type::append || tt == type::lsbrace) { // Detect and handle the directory scope. If things look off, then we // let parse_variable_name() complain. // dir_path d; if ((ns.size () == 2 && ns[0].directory ()) || (ns.size () == 1 && ns[0].directory () && tt == type::lsbrace)) { if (at.first) fail (at.second) << "attributes before scope directory"; if (tt == type::lsbrace) { attributes_pop (); attributes_push (t, tt); d = move (ns[0].dir); nloc = get_location (t); ns = parse_names (t, tt, pattern_mode::ignore); // It got to be a variable assignment. // if (tt != type::assign && tt != type::prepend && tt != type::append) fail (t) << "expected variable assignment instead of " << t; } else { d = move (ns[0].dir); ns.erase (ns.begin ()); } } // Make sure not a pattern (see also the target case above and scope // below). // if (pattern (d.string ())) fail (nloc) << "pattern in directory " << d.representation (); if (tt != type::lsbrace) { const variable& var (parse_variable_name (move (ns), nloc)); apply_variable_attributes (var); if (var.visibility >= variable_visibility::target) { diag_record dr (fail (nloc)); dr << "variable " << var << " has " << var.visibility << " visibility but is assigned on a scope"; if (var.visibility == variable_visibility::target) dr << info << "consider changing it to '*: " << var << "'"; } { enter_scope sg (d.empty () ? enter_scope () : enter_scope (*this, move (d))); parse_variable (t, tt, var, tt); } if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; continue; } // Not "our" attribute, see if anyone else likes it. } // See if this is a directory scope. // if (tt == type::newline && peek () == type::lcbrace) { if (ns.size () != 1) fail (nloc) << "multiple scope directories"; name& n (ns[0]); if (!n.directory ()) fail (nloc) << "expected scope directory"; dir_path& d (n.dir); // Make sure not a pattern (see also the target and directory cases // above). // if (pattern (d.string ())) fail (nloc) << "pattern in directory " << d.representation (); next (t, tt); // Should be on its own line. // if (next (t, tt) != type::newline) fail (t) << "expected newline after {"; next (t, tt); if (at.first) fail (at.second) << "attributes before scope directory"; else attributes_pop (); // Can contain anything that a top level can. // { enter_scope sg (*this, move (d)); parse_clause (t, tt); } if (tt != type::rcbrace) fail (t) << "expected } instead of " << t; // Should be on its own line. // if (next (t, tt) == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline after }"; continue; } fail (t) << "unexpected " << t; } return parsed; } void parser:: parse_variable_block (token& t, type& tt, const target_type* type, string pat) { // Parse a target or prerequisite-specific variable block. If type is not // NULL, then this is a target type/pattern-specific block. // // enter: first token of first line in the block // leave: rcbrace // // This is a more restricted variant of parse_clause() that only allows // variable assignments. // tracer trace ("parser::parse_variable_block", &path_); while (tt != type::rcbrace && tt != type::eos) { attributes_push (t, tt); location nloc (get_location (t)); names ns (parse_names (t, tt, pattern_mode::ignore, false /* chunk */, "variable name")); if (tt != type::assign && tt != type::prepend && tt != type::append) fail (t) << "expected variable assignment instead of " << t; const variable& var (parse_variable_name (move (ns), nloc)); apply_variable_attributes (var); if (prerequisite_ != nullptr && var.visibility > variable_visibility::target) { fail (t) << "variable " << var << " has " << var.visibility << " visibility but is assigned on a target"; } if (type == nullptr) parse_variable (t, tt, var, tt); else parse_type_pattern_variable (t, tt, *type, pat, // Note: can't move. var, tt, get_location (t)); if (tt != type::newline) fail (t) << "expected newline instead of " << t; next (t, tt); } } void parser:: parse_dependency (token& t, token_type& tt, names&& tns, const location& tloc, // Target names. names&& pns, const location& ploc) // Prereq names. { // Parse a dependency chain and/or a prerequisite-specific variable // assignment. // // enter: colon (anything else is not handled) // leave: newline // tracer trace ("parser::parse_dependency", &path_); // First enter all the targets (normally we will have just one). // small_vector<reference_wrapper<target>, 1> tgs; for (auto i (tns.begin ()), e (tns.end ()); i != e; ++i) { name& n (*i); if (n.qualified ()) fail (tloc) << "project name in target " << n; name o (n.pair ? move (*++i) : name ()); enter_target tg (*this, move (n), move (o), false, tloc, trace); if (default_target_ == nullptr) default_target_ = target_; target_->prerequisites_state_.store (2, memory_order_relaxed); target_->prerequisites_.reserve (pns.size ()); tgs.push_back (*target_); } // Now enter each prerequisite into each target. // for (name& pn: pns) { // We cannot reuse the names if we (potentially) may need to pass them // as targets in case of a chain (see below). // name n (tt != type::colon ? move (pn) : pn); auto rp (scope_->find_target_type (n, ploc)); const target_type* tt (rp.first); optional<string>& e (rp.second); if (tt == nullptr) fail (ploc) << "unknown target type " << n.type; // Current dir collapses to an empty one. // if (!n.dir.empty ()) n.dir.normalize (false, true); // @@ OUT: for now we assume the prerequisite's out is undetermined. The // only way to specify an src prerequisite will be with the explicit // @-syntax. // // Perhaps use @file{foo} as a way to specify it is in the out tree, // e.g., to suppress any src searches? The issue is what to use for such // a special indicator. Also, one can easily and natually suppress any // searches by specifying the absolute path. // prerequisite p (move (n.proj), *tt, move (n.dir), dir_path (), move (n.value), move (e), *scope_); for (auto i (tgs.begin ()), e (tgs.end ()); i != e; ) { // Move last prerequisite (which will normally be the only one). // target& t (*i); t.prerequisites_.push_back (++i == e ? move (p) : prerequisite (p, memory_order_relaxed)); } } // Do we have a dependency chain and/or prerequisite-specific variable // assignment? // if (tt != type::colon) return; // What should we do if there are no prerequisites (for example, because // of an empty wildcard result)? We can fail or we can ignore. In most // cases, however, this is probably an error (for example, forgetting to // checkout a git submodule) so let's not confuse the user and fail (one // can always handle the optional prerequisites case with a variable and // an if). // if (pns.empty ()) fail (ploc) << "no prerequisites in dependency chain or prerequisite-" << "specific variable assignment"; // Call the specified parsing function (either variable or block) for the // last pns.size() prerequisites of each target. We handle multiple // targets and/or prerequisites by replaying the tokens (see the target- // specific case above for details). The function signature is: // // void (token& t, type& tt) // auto for_each = [this, &t, &tt, &tgs, &pns] (auto&& f) { replay_guard rg (*this, tgs.size () > 1 || pns.size () > 1); for (auto ti (tgs.begin ()), te (tgs.end ()); ti != te; ) { target& tg (*ti); enter_target tgg (*this, tg); for (size_t pn (tg.prerequisites_.size ()), pi (pn - pns.size ()); pi != pn; ) { enter_prerequisite pg (*this, tg.prerequisites_[pi]); f (t, tt); if (++pi != pn) rg.play (); // Replay. } if (++ti != te) rg.play (); // Replay. } }; next (t, tt); auto at (attributes_push (t, tt)); // See if this is a prerequisite block. // if (tt == type::newline && peek () == type::lcbrace) { next (t, tt); // Should be on its own line. // if (next (t, tt) != type::newline) fail (t) << "expected newline after {"; if (at.first) fail (at.second) << "attributes before prerequisite block"; else attributes_pop (); // Parse the block for each prerequisites of each target. // for_each ([this] (token& t, token_type& tt) { next (t, tt); // First token of first line in the block. parse_variable_block (t, tt, nullptr, string ()); if (tt != type::rcbrace) fail (t) << "expected } instead of " << t; }); next (t, tt); // Presumably newline after '}'. return; } // @@ PAT: currently we pattern-expand prerequisite-specific vars. // const location loc (get_location (t)); names ns (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::expand) : names ()); // Prerequisite-specific variable assignment. // if (tt == type::assign || tt == type::prepend || tt == type::append) { type at (tt); const variable& var (parse_variable_name (move (ns), loc)); apply_variable_attributes (var); // Parse the assignment for each prerequisites of each target. // for_each ([this, &var, at] (token& t, token_type& tt) { parse_variable (t, tt, var, at); }); } // // Dependency chain. // else { if (at.first) fail (at.second) << "attributes before prerequisites"; else attributes_pop (); // Note that we could have "pre-resolved" these prerequisites to actual // targets or, at least, made their directories absolute. We don't do it // for ease of documentation: with the current semantics we can just say // that the dependency chain is equivalent to specifying each dependency // separately. // parse_dependency (t, tt, move (pns), ploc, move (ns), loc); } } void parser:: source (istream& is, const path& p, const location& loc, bool enter, bool deft) { tracer trace ("parser::source", &path_); l5 ([&]{trace (loc) << "entering " << p;}); if (enter) enter_buildfile (p); const path* op (path_); path_ = &p; lexer l (is, *path_); lexer* ol (lexer_); lexer_ = &l; target* odt; if (deft) { odt = default_target_; default_target_ = nullptr; } token t; type tt; next (t, tt); parse_clause (t, tt); if (tt != type::eos) fail (t) << "unexpected " << t; if (deft) { process_default_target (t); default_target_ = odt; } lexer_ = ol; path_ = op; l5 ([&]{trace (loc) << "leaving " << p;}); } void parser:: parse_source (token& t, type& tt) { // The rest should be a list of buildfiles. Parse them as names in the // value mode to get variable expansion and directory prefixes. // mode (lexer_mode::value, '@'); next (t, tt); const location l (get_location (t)); names ns (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::expand, false, "path", nullptr) : names ()); for (name& n: ns) { if (n.pair || n.qualified () || n.typed () || n.value.empty ()) fail (l) << "expected buildfile instead of " << n; // Construct the buildfile path. // path p (move (n.dir)); p /= path (move (n.value)); // If the path is relative then use the src directory corresponding // to the current directory scope. // if (scope_->src_path_ != nullptr && p.relative ()) p = scope_->src_path () / p; p.normalize (); try { ifdstream ifs (p); source (ifs, p, get_location (t), true /* enter */, false /* default_target */); } catch (const io_error& e) { fail (l) << "unable to read buildfile " << p << ": " << e; } } if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; } void parser:: parse_include (token& t, type& tt) { tracer trace ("parser::parse_include", &path_); if (root_->src_path_ == nullptr) fail (t) << "inclusion during bootstrap"; // The rest should be a list of buildfiles. Parse them as names in the // value mode to get variable expansion and directory prefixes. // mode (lexer_mode::value, '@'); next (t, tt); const location l (get_location (t)); names ns (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::expand, false, "path", nullptr) : names ()); for (name& n: ns) { if (n.pair || n.qualified () || n.typed () || n.empty ()) fail (l) << "expected buildfile instead of " << n; // Construct the buildfile path. If it is a directory, then append // 'buildfile'. // path p (move (n.dir)); if (n.value.empty ()) p /= buildfile_file; else { bool d (path::traits::is_separator (n.value.back ())); p /= path (move (n.value)); if (d) p /= buildfile_file; } l6 ([&]{trace (l) << "relative path " << p;}); // Determine new out_base. // dir_path out_base; if (p.relative ()) { out_base = scope_->out_path () / p.directory (); out_base.normalize (); } else { p.normalize (); // Make sure the path is in this project. Include is only meant // to be used for intra-project inclusion (plus amalgamation). // bool in_out (false); if (!p.sub (root_->src_path ()) && !(in_out = p.sub (root_->out_path ()))) fail (l) << "out of project include " << p; out_base = in_out ? p.directory () : out_src (p.directory (), *root_); } // Switch the scope. Note that we need to do this before figuring // out the absolute buildfile path since we may switch the project // root and src_root with it (i.e., include into a sub-project). // scope* ors (root_); scope* ocs (scope_); const dir_path* opb (pbase_); switch_scope (out_base); // Use the new scope's src_base to get absolute buildfile path // if it is relative. // if (p.relative ()) p = scope_->src_path () / p.leaf (); l6 ([&]{trace (l) << "absolute path " << p;}); if (!root_->buildfiles.insert (p).second) // Note: may be "new" root. { l5 ([&]{trace (l) << "skipping already included " << p;}); pbase_ = opb; scope_ = ocs; root_ = ors; continue; } try { ifdstream ifs (p); source (ifs, p, get_location (t), true /* enter */, true /* default_target */); } catch (const io_error& e) { fail (l) << "unable to read buildfile " << p << ": " << e; } pbase_ = opb; scope_ = ocs; root_ = ors; } if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; } void parser:: parse_run (token& t, type& tt) { // run <name> [<arg>...] // // Parse the command line as names in the value mode to get variable // expansion, etc. // mode (lexer_mode::value); next (t, tt); const location l (get_location (t)); strings args; try { args = convert<strings> (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::ignore, false, "argument", nullptr) : names ()); } catch (const invalid_argument& e) { fail (l) << "invalid run argument: " << e.what (); } if (args.empty () || args[0].empty ()) fail (l) << "expected executable name after run"; cstrings cargs; cargs.reserve (args.size () + 1); transform (args.begin (), args.end (), back_inserter (cargs), [] (const string& s) {return s.c_str ();}); cargs.push_back (nullptr); process pr (run_start (3 /* verbosity */, cargs, 0 /* stdin */, -1 /* stdout */, true /* error */, empty_dir_path /* cwd */, l)); bool bad (false); try { // While a failing process could write garbage to stdout, for simplicity // let's assume it is well behaved. // ifdstream is (move (pr.in_ofd), fdstream_mode::skip); // If there is an error in the output, our diagnostics will look like // this: // // <stdout>:2:3 error: unterminated single quote // buildfile:3:4 info: while parsing foo output // { auto df = make_diag_frame ( [&args, &l](const diag_record& dr) { dr << info (l) << "while parsing " << args[0] << " output"; }); source (is, path ("<stdout>"), l, false /* enter */, false /* default_target */); } is.close (); // Detect errors. } catch (const io_error&) { // Presumably the child process failed and issued diagnostics so let // run_finish() try to deal with that first. // bad = true; } run_finish (cargs, pr, l); if (bad) fail (l) << "error reading " << args[0] << " output"; if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; } void parser:: parse_import (token& t, type& tt) { tracer trace ("parser::parse_import", &path_); if (root_->src_path_ == nullptr) fail (t) << "import during bootstrap"; // General import format: // // import [<var>=](<project>|<project>/<target>])+ // type atype; // Assignment type. value* val (nullptr); const build2::variable* var (nullptr); // We are now in the normal lexing mode and here is the problem: we need // to switch to the value mode so that we don't treat certain characters // as separators (e.g., + in 'libstdc++'). But at the same time we need // to detect if we have the <var>= part. So what we are going to do is // switch to the value mode, get the first token, and then re-parse it // manually looking for =/=+/+=. // mode (lexer_mode::value, '@'); next (t, tt); // Get variable attributes, if any (note that here we will go into a // nested value mode with a different pair character). // auto at (attributes_push (t, tt)); const location vloc (get_location (t)); if (tt == type::word) { // Split the token into the variable name and value at position (p) of // '=', taking into account leading/trailing '+'. The variable name is // returned while the token is set to value. If the resulting token // value is empty, get the next token. Also set assignment type (at). // auto split = [&atype, &t, &tt, this] (size_t p) -> string { string& v (t.value); size_t e; if (p != 0 && v[p - 1] == '+') // += { e = p--; atype = type::append; } else if (p + 1 != v.size () && v[p + 1] == '+') // =+ { e = p + 1; atype = type::prepend; } else // = { e = p; atype = type::assign; } string nv (v, e + 1); // value v.resize (p); // var name v.swap (nv); if (v.empty ()) next (t, tt); return nv; }; // Is this the 'foo=...' case? // size_t p (t.value.find ('=')); auto& vp (var_pool.rw (*scope_)); if (p != string::npos) var = &vp.insert (split (p), true /* overridable */); // // This could still be the 'foo =...' case. // else if (peek () == type::word) { const string& v (peeked ().value); size_t n (v.size ()); // We should start with =/+=/=+. // if (n > 0 && (v[p = 0] == '=' || (n > 1 && v[0] == '+' && v[p = 1] == '='))) { var = &vp.insert (move (t.value), true /* overridable */); next (t, tt); // Get the peeked token. split (p); // Returned name should be empty. } } } if (var != nullptr) { apply_variable_attributes (*var); if (var->visibility >= variable_visibility::target) { fail (vloc) << "variable " << *var << " has " << var->visibility << " visibility but is assigned in import"; } val = atype == type::assign ? &scope_->assign (*var) : &scope_->append (*var); } else { if (at.first) fail (at.second) << "attributes without variable"; else attributes_pop (); } // The rest should be a list of projects and/or targets. Parse them as // names to get variable expansion and directory prefixes. Note: doesn't // make sense to expand patterns (what's the base directory?) // const location l (get_location (t)); names ns (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::ignore) : names ()); for (name& n: ns) { if (n.pair) fail (l) << "unexpected pair in import"; // build2::import() will check the name, if required. // names r (build2::import (*scope_, move (n), l)); if (val != nullptr) { if (atype == type::assign) { val->assign (move (r), var); atype = type::append; // Append subsequent values. } else if (atype == type::prepend) { // Note: multiple values will be prepended in reverse. // val->prepend (move (r), var); } else val->append (move (r), var); } } if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; } void parser:: parse_export (token& t, type& tt) { tracer trace ("parser::parse_export", &path_); scope* ps (scope_->parent_scope ()); // This should be temp_scope. // if (ps == nullptr || ps->out_path () != scope_->out_path ()) fail (t) << "export outside export stub"; // The rest is a value. Parse it as a variable value to get expansion, // attributes, etc. build2::import() will check the names, if required. // location l (get_location (t)); value rhs (parse_variable_value (t, tt)); // While it may seem like supporting attributes is a good idea here, // there is actually little benefit in being able to type them or to // return NULL. // // export_value_ = value (); // Reset to untyped NULL value. // value_attributes (nullptr, // export_value_, // move (rhs), // type::assign); if (attributes& a = attributes_top ()) fail (a.loc) << "attributes in export"; else attributes_pop (); if (!rhs) fail (l) << "null value in export"; if (rhs.type != nullptr) untypify (rhs); export_value_ = move (rhs).as<names> (); if (export_value_.empty ()) fail (l) << "empty value in export"; if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; } void parser:: parse_using (token& t, type& tt) { tracer trace ("parser::parse_using", &path_); bool optional (t.value.back () == '?'); if (optional && boot_) fail (t) << "optional module in bootstrap"; // The rest should be a list of module names. Parse them as names in the // value mode to get variable expansion, etc. // mode (lexer_mode::value, '@'); next (t, tt); const location l (get_location (t)); names ns (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::ignore, false, "module", nullptr) : names ()); for (auto i (ns.begin ()); i != ns.end (); ++i) { string n; standard_version v; if (!i->simple ()) fail (l) << "expected module name instead of " << *i; n = move (i->value); if (i->pair) try { if (i->pair != '@') fail (l) << "unexpected pair style in using directive"; ++i; if (!i->simple ()) fail (l) << "expected module version instead of " << *i; v = standard_version (i->value, standard_version::allow_earliest); } catch (const invalid_argument& e) { fail (l) << "invalid module version '" << i->value << "': " << e; } // Handle the special 'build' module. // if (n == "build") { standard_version_constraint c (move (v), false, nullopt, true); // >= if (!v.empty ()) check_build_version (c, l); } else { assert (v.empty ()); // Module versioning not yet implemented. if (boot_) boot_module (*root_, n, l); else load_module (*root_, *scope_, n, l, optional); } } if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; } void parser:: parse_define (token& t, type& tt) { // define <derived>: <base> // // See tests/define. // if (next (t, tt) != type::word) fail (t) << "expected name instead of " << t << " in target type " << "definition"; string dn (move (t.value)); const location dnl (get_location (t)); if (next (t, tt) != type::colon) fail (t) << "expected ':' instead of " << t << " in target type " << "definition"; next (t, tt); if (tt == type::word) { // Target. // const string& bn (t.value); const target_type* bt (scope_->find_target_type (bn)); if (bt == nullptr) fail (t) << "unknown target type " << bn; if (!scope_->derive_target_type (move (dn), *bt).second) fail (dnl) << "target type " << dn << " already define in this scope"; next (t, tt); // Get newline. } else fail (t) << "expected name instead of " << t << " in target type " << "definition"; if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline instead of " << t; } void parser:: parse_if_else (token& t, type& tt) { // Handle the whole if-else chain. See tests/if-else. // bool taken (false); // One of the branches has been taken. for (;;) { string k (move (t.value)); next (t, tt); bool take (false); // Take this branch? if (k != "else") { // Should we evaluate the expression if one of the branches has // already been taken? On the one hand, evaluating it is a waste // of time. On the other, it can be invalid and the only way for // the user to know their buildfile is valid is to test every // branch. There could also be side effects. We also have the same // problem with ignored branch blocks except there evaluating it // is not an option. So let's skip it. // if (taken) skip_line (t, tt); else { if (tt == type::newline || tt == type::eos) fail (t) << "expected " << k << "-expression instead of " << t; // Parse as names to get variable expansion, evaluation, etc. Note // that we also expand patterns (could be used in nested contexts, // etc; e.g., "if pattern expansion is empty" condition). // const location l (get_location (t)); try { // Should evaluate to 'true' or 'false'. // bool e ( convert<bool> ( parse_value (t, tt, pattern_mode::expand, "expression", nullptr))); take = (k.back () == '!' ? !e : e); } catch (const invalid_argument& e) { fail (l) << e; } } } else take = !taken; if (tt != type::newline) fail (t) << "expected newline instead of " << t << " after " << k << (k != "else" ? "-expression" : ""); // This can be a block or a single line. The block part is a bit // tricky, consider: // // else // {hxx cxx}{options}: install = false // // So we treat it as a block if it's followed immediately by newline. // if (next (t, tt) == type::lcbrace && peek () == type::newline) { next (t, tt); // Get newline. next (t, tt); if (take) { parse_clause (t, tt); taken = true; } else skip_block (t, tt); if (tt != type::rcbrace) fail (t) << "expected } instead of " << t << " at the end of " << k << "-block"; next (t, tt); if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline after }"; } else { if (take) { if (!parse_clause (t, tt, true)) fail (t) << "expected " << k << "-line instead of " << t; taken = true; } else { skip_line (t, tt); if (tt == type::newline) next (t, tt); } } // See if we have another el* keyword. // if (k != "else" && tt == type::word && keyword (t)) { const string& n (t.value); if (n == "else" || n == "elif" || n == "elif!") continue; } break; } } void parser:: parse_for (token& t, type& tt) { // for <varname>: <value> // <line> // // for <varname>: <value> // { // <block> // } // // First take care of the variable name. There is no reason not to // support variable attributes. // next (t, tt); attributes_push (t, tt); // @@ PAT: currently we pattern-expand for var. // const location vloc (get_location (t)); names vns (parse_names (t, tt, pattern_mode::expand)); if (tt != type::colon) fail (t) << "expected ':' instead of " << t << " after variable name"; const variable& var (parse_variable_name (move (vns), vloc)); apply_variable_attributes (var); if (var.visibility >= variable_visibility::target) { fail (vloc) << "variable " << var << " has " << var.visibility << " visibility but is assigned in for-loop"; } // Now the value (list of names) to iterate over. Parse it as a variable // value to get expansion, attributes, etc. // value val; apply_value_attributes ( nullptr, val, parse_variable_value (t, tt), type::assign); // If this value is a vector, then save its element type so that we // can typify each element below. // const value_type* etype (nullptr); if (val && val.type != nullptr) { etype = val.type->element_type; untypify (val); } if (tt != type::newline) fail (t) << "expected newline instead of " << t << " after for"; // Finally the body. The initial thought was to use the token replay // facility but on closer inspection this didn't turn out to be a good // idea (no support for nested replays, etc). So instead we are going to // do a full-blown re-lex. Specifically, we will first skip the line/block // just as we do for non-taken if/else branches while saving the character // sequence that comprises the body. Then we re-lex/parse it on each // iteration. // string body; uint64_t line (lexer_->line); // Line of the first character to be saved. lexer::save_guard sg (*lexer_, body); // This can be a block or a single line, similar to if-else. // bool block (next (t, tt) == type::lcbrace && peek () == type::newline); if (block) { next (t, tt); // Get newline. next (t, tt); skip_block (t, tt); sg.stop (); if (tt != type::rcbrace) fail (t) << "expected } instead of " << t << " at the end of for-block"; next (t, tt); if (tt == type::newline) next (t, tt); else if (tt != type::eos) fail (t) << "expected newline after }"; } else { skip_line (t, tt); sg.stop (); if (tt == type::newline) next (t, tt); } // Iterate. // names& ns (val.as<names> ()); if (ns.empty ()) return; value& v (scope_->assign (var)); istringstream is (move (body)); for (auto i (ns.begin ()), e (ns.end ());; ) { // Set the variable value. // bool pair (i->pair); names n; n.push_back (move (*i)); if (pair) n.push_back (move (*++i)); v = value (move (n)); if (etype != nullptr) typify (v, *etype, &var); lexer l (is, *path_, line); lexer* ol (lexer_); lexer_ = &l; token t; type tt; next (t, tt); if (block) { next (t, tt); // { next (t, tt); // <newline> } parse_clause (t, tt); assert (tt == (block ? type::rcbrace : type::eos)); lexer_ = ol; if (++i == e) break; // Rewind the stream. // is.clear (); is.seekg (0); } } void parser:: parse_assert (token& t, type& tt) { bool neg (t.value.back () == '!'); const location al (get_location (t)); // Parse the next chunk as names to get variable expansion, evaluation, // etc. Do it in the value mode so that we don't treat ':', etc., as // special. // mode (lexer_mode::value); next (t, tt); const location el (get_location (t)); try { // Should evaluate to 'true' or 'false'. // bool e ( convert<bool> ( parse_value (t, tt, pattern_mode::expand, "expression", nullptr, true))); e = (neg ? !e : e); if (e) { skip_line (t, tt); if (tt != type::eos) next (t, tt); // Swallow newline. return; } } catch (const invalid_argument& e) { fail (el) << e; } // Being here means things didn't end up well. Parse the description, if // any, with expansion. Then fail. // names ns (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::ignore, false, "description", nullptr) : names ()); diag_record dr (fail (al)); if (ns.empty ()) dr << "assertion failed"; else dr << ns; } void parser:: parse_print (token& t, type& tt) { // Parse the rest as a variable value to get expansion, attributes, etc. // value rhs (parse_variable_value (t, tt)); value lhs; apply_value_attributes (nullptr, lhs, move (rhs), type::assign); if (lhs) { names storage; cout << reverse (lhs, storage) << endl; } else cout << "[null]" << endl; if (tt != type::eos) next (t, tt); // Swallow newline. } void parser:: parse_diag (token& t, type& tt) { diag_record dr; const location l (get_location (t)); switch (t.value[0]) { case 'f': dr << fail (l); break; case 'w': dr << warn (l); break; case 'i': dr << info (l); break; case 't': dr << text (l); break; default: assert (false); } // Parse the rest as a variable value to get expansion, attributes, etc. // value rhs (parse_variable_value (t, tt)); value lhs; apply_value_attributes (nullptr, lhs, move (rhs), type::assign); if (lhs) { names storage; dr << reverse (lhs, storage); } if (tt != type::eos) next (t, tt); // Swallow newline. } void parser:: parse_dump (token& t, type& tt) { // dump [<target>...] // // If there are no targets, then we dump the current scope. // tracer trace ("parser::parse_dump", &path_); const location l (get_location (t)); next (t, tt); names ns (tt != type::newline && tt != type::eos ? parse_names (t, tt, pattern_mode::ignore) : names ()); text (l) << "dump:"; // Dump directly into diag_stream. // ostream& os (*diag_stream); if (ns.empty ()) { if (scope_ != nullptr) dump (*scope_, " "); // Indent two spaces. else os << " <no current scope>" << endl; } else { for (auto i (ns.begin ()), e (ns.end ()); i != e; ) { name& n (*i++); name o (n.pair ? move (*i++) : name ()); const target* t (enter_target::find_target (*this, n, o, l, trace)); if (t != nullptr) dump (*t, " "); // Indent two spaces. else { os << " <no target " << n; if (n.pair && !o.dir.empty ()) os << '@' << o.dir; os << '>' << endl; } if (i != e) os << endl; } } if (tt != type::eos) next (t, tt); // Swallow newline. } const variable& parser:: parse_variable_name (names&& ns, const location& l) { // The list should contain a single, simple name. // if (ns.size () != 1 || !ns[0].simple () || ns[0].empty ()) fail (l) << "expected variable name instead of " << ns; string& n (ns[0].value); //@@ OLD if (n.front () == '.') // Fully qualified name. n.erase (0, 1); else { //@@ TODO: append namespace if any. } return var_pool.rw (*scope_).insert (move (n), true /* overridable */); } void parser:: parse_variable (token& t, type& tt, const variable& var, type kind) { value rhs (parse_variable_value (t, tt)); value& lhs ( kind == type::assign ? (prerequisite_ != nullptr ? prerequisite_->assign (var) : target_ != nullptr ? target_->assign (var) : /* */ scope_->assign (var)) : (prerequisite_ != nullptr ? prerequisite_->append (var, *target_) : target_ != nullptr ? target_->append (var) : /* */ scope_->append (var))); apply_value_attributes (&var, lhs, move (rhs), kind); } void parser:: parse_type_pattern_variable (token& t, token_type& tt, const target_type& type, string pat, const variable& var, token_type kind, const location& loc) { // Parse target type/pattern-specific variable assignment. // // See old-tests/variable/type-pattern. // Note: expanding the value in the current scope context. // value rhs (parse_variable_value (t, tt)); // Leave the value untyped unless we are assigning. // pair<reference_wrapper<value>, bool> p ( scope_->target_vars[type][move (pat)].insert ( var, kind == type::assign)); value& lhs (p.first); // We store prepend/append values untyped (similar to overrides). // if (rhs.type != nullptr && kind != type::assign) untypify (rhs); if (p.second) { // Note: we are always using assign and we don't pass the variable in // case of prepend/append in order to keep the value untyped. // apply_value_attributes (kind == type::assign ? &var : nullptr, lhs, move (rhs), type::assign); // Map assignment type to the value::extra constant. // lhs.extra = (kind == type::prepend ? 1 : kind == type::append ? 2 : 0); } else { // Existing value. What happens next depends on what we are trying to do // and what's already there. // // Assignment is the easy one: we simply overwrite what's already // there. Also, if we are appending/prepending to a previously assigned // value, then we simply append or prepend normally. // if (kind == type::assign || lhs.extra == 0) { // Above we've instructed insert() not to type the value so we have to // compensate for that now. // if (kind != type::assign) { if (var.type != nullptr && lhs.type != var.type) typify (lhs, *var.type, &var); } else lhs.extra = 0; // Change to assignment. apply_value_attributes (&var, lhs, move (rhs), kind); } else { // This is an append/prepent to a previously appended or prepended // value. We can handle it as long as things are consistent. // if (kind == type::prepend && lhs.extra == 2) fail (loc) << "prepend to a previously appended target type/pattern-" << "specific variable " << var; if (kind == type::append && lhs.extra == 1) fail (loc) << "append to a previously prepended target type/pattern-" << "specific variable " << var; // Do untyped prepend/append. // apply_value_attributes (nullptr, lhs, move (rhs), kind); } } if (lhs.extra != 0 && lhs.type != nullptr) fail (loc) << "typed prepend/append to target type/pattern-specific " << "variable " << var; } value parser:: parse_variable_value (token& t, type& tt) { mode (lexer_mode::value, '@'); next (t, tt); // Parse value attributes if any. Note that it's ok not to have anything // after the attributes (e.g., foo=[null]). // attributes_push (t, tt, true); return tt != type::newline && tt != type::eos ? parse_value (t, tt, pattern_mode::expand) : value (names ()); } static const value_type* map_type (const string& n) { auto ptr = [] (const value_type& vt) {return &vt;}; return n == "bool" ? ptr (value_traits<bool>::value_type) : n == "uint64" ? ptr (value_traits<uint64_t>::value_type) : n == "string" ? ptr (value_traits<string>::value_type) : n == "path" ? ptr (value_traits<path>::value_type) : n == "dir_path" ? ptr (value_traits<dir_path>::value_type) : n == "abs_dir_path" ? ptr (value_traits<abs_dir_path>::value_type) : n == "name" ? ptr (value_traits<name>::value_type) : n == "name_pair" ? ptr (value_traits<name_pair>::value_type) : n == "target_triplet" ? ptr (value_traits<target_triplet>::value_type) : n == "project_name" ? ptr (value_traits<project_name>::value_type) : n == "uint64s" ? ptr (value_traits<uint64s>::value_type) : n == "strings" ? ptr (value_traits<strings>::value_type) : n == "paths" ? ptr (value_traits<paths>::value_type) : n == "dir_paths" ? ptr (value_traits<dir_paths>::value_type) : n == "names" ? ptr (value_traits<vector<name>>::value_type) : nullptr; } void parser:: apply_variable_attributes (const variable& var) { attributes a (attributes_pop ()); if (!a) return; const location& l (a.loc); const value_type* type (nullptr); for (auto& p: a.ats) { string& k (p.first); string& v (p.second); if (const value_type* t = map_type (k)) { if (type != nullptr && t != type) fail (l) << "multiple variable types: " << k << ", " << type->name; type = t; // Fall through. } else { diag_record dr (fail (l)); dr << "unknown variable attribute " << k; if (!v.empty ()) dr << '=' << v; } if (!v.empty ()) fail (l) << "unexpected value for attribute " << k << ": " << v; } if (type != nullptr) { if (var.type == nullptr) { const bool o (true); // Allow overrides. var_pool.update (const_cast<variable&> (var), type, nullptr, &o); } else if (var.type != type) fail (l) << "changing variable " << var << " type from " << var.type->name << " to " << type->name; } } void parser:: apply_value_attributes (const variable* var, value& v, value&& rhs, type kind) { attributes a (attributes_pop ()); const location& l (a.loc); // Essentially this is an attribute-augmented assign/append/prepend. // bool null (false); const value_type* type (nullptr); for (auto& p: a.ats) { string& k (p.first); string& v (p.second); if (k == "null") { if (rhs && !rhs.empty ()) // Note: null means we had an expansion. fail (l) << "value with null attribute"; null = true; // Fall through. } else if (const value_type* t = map_type (k)) { if (type != nullptr && t != type) fail (l) << "multiple value types: " << k << ", " << type->name; type = t; // Fall through. } else { diag_record dr (fail (l)); dr << "unknown value attribute " << k; if (!v.empty ()) dr << '=' << v; } if (!v.empty ()) fail (l) << "unexpected value for attribute " << k << ": " << v; } // When do we set the type and when do we keep the original? This gets // tricky for append/prepend where both values contribute. The guiding // rule here is that if the user specified the type, then they reasonable // expect the resulting value to be of that type. So for assign we always // override the type since it's a new value. For append/prepend we // override if the LHS value is NULL (which also covers undefined). We // also override if LHS is untyped. Otherwise, we require that the types // be the same. Also check that the requested value type doesn't conflict // with the variable type. // if (var != nullptr && var->type != nullptr) { if (type == nullptr) { type = var->type; } else if (var->type != type) { fail (l) << "conflicting variable " << var->name << " type " << var->type->name << " and value type " << type->name; } } // What if both LHS and RHS are typed? For now we do lexical conversion: // if this specific value can be converted, then all is good. The // alternative would be to do type conversion: if any value of RHS type // can be converted to LHS type, then we are good. This may be a better // option in the future but currently our parse_names() implementation // untypifies everything if there are multiple names. And having stricter // rules just for single-element values would be strange. // // We also have "weaker" type propagation for the RHS type. // bool rhs_type (false); if (rhs.type != nullptr) { // Only consider RHS type if there is no explicit or variable type. // if (type == nullptr) { type = rhs.type; rhs_type = true; } // Reduce this to the untyped value case for simplicity. // untypify (rhs); } if (kind == type::assign) { if (type != v.type) { v = nullptr; // Clear old value. v.type = type; } } else if (type != nullptr) { if (!v) v.type = type; else if (v.type == nullptr) typify (v, *type, var); else if (v.type != type && !rhs_type) fail (l) << "conflicting original value type " << v.type->name << " and append/prepend value type " << type->name; } if (null) { if (kind == type::assign) // Ignore for prepend/append. v = nullptr; } else { if (kind == type::assign) { if (rhs) v.assign (move (rhs).as<names> (), var); else v = nullptr; } else if (rhs) // Don't append/prepent NULL. { if (kind == type::prepend) v.prepend (move (rhs).as<names> (), var); else v.append (move (rhs).as<names> (), var); } } } values parser:: parse_eval (token& t, type& tt, pattern_mode pmode) { // enter: lparen // leave: rparen mode (lexer_mode::eval, '@'); // Auto-expires at rparen. next (t, tt); if (tt == type::rparen) return values (); values r (parse_eval_comma (t, tt, pmode, true)); if (tt != type::rparen) fail (t) << "unexpected " << t; // E.g., stray ':'. return r; } values parser:: parse_eval_comma (token& t, type& tt, pattern_mode pmode, bool first) { // enter: first token of LHS // leave: next token after last RHS // Left-associative: parse in a loop for as long as we can. // values r; value lhs (parse_eval_ternary (t, tt, pmode, first)); if (!pre_parse_) r.push_back (move (lhs)); while (tt == type::comma) { next (t, tt); value rhs (parse_eval_ternary (t, tt, pmode)); if (!pre_parse_) r.push_back (move (rhs)); } return r; } value parser:: parse_eval_ternary (token& t, type& tt, pattern_mode pmode, bool first) { // enter: first token of LHS // leave: next token after last RHS // Right-associative (kind of): we parse what's between ?: without // regard for priority and we recurse on what's after :. Here is an // example: // // a ? x ? y : z : b ? c : d // // This should be parsed/evaluated as: // // a ? (x ? y : z) : (b ? c : d) // location l (get_location (t)); value lhs (parse_eval_or (t, tt, pmode, first)); if (tt != type::question) return lhs; // Use the pre-parse mechanism to implement short-circuit. // bool pp (pre_parse_); bool q; try { q = pp ? true : convert<bool> (move (lhs)); } catch (const invalid_argument& e) { fail (l) << e << endf; } if (!pp) pre_parse_ = !q; // Short-circuit middle? next (t, tt); value mhs (parse_eval_ternary (t, tt, pmode)); if (tt != type::colon) fail (t) << "expected ':' instead of " << t; if (!pp) pre_parse_ = q; // Short-circuit right? next (t, tt); value rhs (parse_eval_ternary (t, tt, pmode)); pre_parse_ = pp; return q ? move (mhs) : move (rhs); } value parser:: parse_eval_or (token& t, type& tt, pattern_mode pmode, bool first) { // enter: first token of LHS // leave: next token after last RHS // Left-associative: parse in a loop for as long as we can. // location l (get_location (t)); value lhs (parse_eval_and (t, tt, pmode, first)); // Use the pre-parse mechanism to implement short-circuit. // bool pp (pre_parse_); while (tt == type::log_or) { try { if (!pre_parse_ && convert<bool> (move (lhs))) pre_parse_ = true; next (t, tt); l = get_location (t); value rhs (parse_eval_and (t, tt, pmode)); if (pre_parse_) continue; // Store the result as bool value. // lhs = convert<bool> (move (rhs)); } catch (const invalid_argument& e) { fail (l) << e; } } pre_parse_ = pp; return lhs; } value parser:: parse_eval_and (token& t, type& tt, pattern_mode pmode, bool first) { // enter: first token of LHS // leave: next token after last RHS // Left-associative: parse in a loop for as long as we can. // location l (get_location (t)); value lhs (parse_eval_comp (t, tt, pmode, first)); // Use the pre-parse mechanism to implement short-circuit. // bool pp (pre_parse_); while (tt == type::log_and) { try { if (!pre_parse_ && !convert<bool> (move (lhs))) pre_parse_ = true; next (t, tt); l = get_location (t); value rhs (parse_eval_comp (t, tt, pmode)); if (pre_parse_) continue; // Store the result as bool value. // lhs = convert<bool> (move (rhs)); } catch (const invalid_argument& e) { fail (l) << e; } } pre_parse_ = pp; return lhs; } value parser:: parse_eval_comp (token& t, type& tt, pattern_mode pmode, bool first) { // enter: first token of LHS // leave: next token after last RHS // Left-associative: parse in a loop for as long as we can. // value lhs (parse_eval_value (t, tt, pmode, first)); while (tt == type::equal || tt == type::not_equal || tt == type::less || tt == type::less_equal || tt == type::greater || tt == type::greater_equal) { type op (tt); location l (get_location (t)); next (t, tt); value rhs (parse_eval_value (t, tt, pmode)); if (pre_parse_) continue; // Use (potentially typed) comparison via value. If one of the values is // typed while the other is not, then try to convert the untyped one to // the other's type instead of complaining. This seems like a reasonable // thing to do and will allow us to write: // // if ($build.version > 30000) // // Rather than having to write: // // if ($build.version > [uint64] 30000) // if (lhs.type != rhs.type) { // @@ Would be nice to pass location for diagnostics. // if (lhs.type == nullptr) { if (lhs) typify (lhs, *rhs.type, nullptr); } else if (rhs.type == nullptr) { if (rhs) typify (rhs, *lhs.type, nullptr); } else fail (l) << "comparison between " << lhs.type->name << " and " << rhs.type->name; } bool r; switch (op) { case type::equal: r = lhs == rhs; break; case type::not_equal: r = lhs != rhs; break; case type::less: r = lhs < rhs; break; case type::less_equal: r = lhs <= rhs; break; case type::greater: r = lhs > rhs; break; case type::greater_equal: r = lhs >= rhs; break; default: r = false; assert (false); } // Store the result as a bool value. // lhs = value (r); } return lhs; } value parser:: parse_eval_value (token& t, type& tt, pattern_mode pmode, bool first) { // enter: first token of value // leave: next token after value // Parse value attributes if any. Note that it's ok not to have anything // after the attributes, as in, ($foo == [null]), or even ([null]) // auto at (attributes_push (t, tt, true)); const location l (get_location (t)); value v; switch (tt) { case type::log_not: { next (t, tt); v = parse_eval_value (t, tt, pmode); if (pre_parse_) break; try { // Store the result as bool value. // v = !convert<bool> (move (v)); } catch (const invalid_argument& e) { fail (l) << e; } break; } default: { // If parse_value() gets called, it expects to see a value. Note that // it will also handle nested eval contexts. // v = (tt != type::colon && tt != type::question && tt != type::comma && tt != type::rparen && tt != type::equal && tt != type::not_equal && tt != type::less && tt != type::less_equal && tt != type::greater && tt != type::greater_equal && tt != type::log_or && tt != type::log_and ? parse_value (t, tt, pmode) : value (names ())); } } // If this is the first expression then handle the eval-qual special case // (target-qualified name represented as a special ':'-style pair). // if (first && tt == type::colon) { if (at.first) fail (at.second) << "attributes before target-qualified variable name"; if (!pre_parse_) attributes_pop (); const location nl (get_location (t)); next (t, tt); value n (parse_value (t, tt, pattern_mode::ignore)); if (tt != type::rparen) fail (t) << "expected ')' after variable name"; if (pre_parse_) return v; // Empty. if (v.type != nullptr || !v || v.as<names> ().size () != 1) fail (l) << "expected target before ':'"; if (n.type != nullptr || !n || n.as<names> ().size () != 1) fail (nl) << "expected variable name after ':'"; names& ns (v.as<names> ()); ns.back ().pair = ':'; ns.push_back (move (n.as<names> ().back ())); return v; } else { if (pre_parse_) return v; // Empty. // Process attributes if any. // if (!at.first) { attributes_pop (); return v; } value r; apply_value_attributes (nullptr, r, move (v), type::assign); return r; } } pair<bool, location> parser:: attributes_push (token& t, type& tt, bool standalone) { location l (get_location (t)); bool has (tt == type::lsbrace); if (!pre_parse_) attributes_.push (attributes {has, l, {}}); if (!has) return make_pair (false, l); // Using '@' for attribute key-value pairs would be just too ugly. Seeing // that we control what goes into keys/values, let's use a much nicer '='. // mode (lexer_mode::attribute, '='); next (t, tt); if (tt != type::rsbrace) { names ns ( parse_names ( t, tt, pattern_mode::ignore, false, "attribute", nullptr)); if (!pre_parse_) { attributes& a (attributes_.top ()); for (auto i (ns.begin ()); i != ns.end (); ++i) { string k, v; try { k = convert<string> (move (*i)); } catch (const invalid_argument&) { fail (l) << "invalid attribute key '" << *i << "'"; } if (i->pair) { if (i->pair != '=') fail (l) << "unexpected pair style in attributes"; try { v = convert<string> (move (*++i)); } catch (const invalid_argument&) { fail (l) << "invalid attribute value '" << *i << "'"; } } a.ats.emplace_back (move (k), move (v)); } } } if (tt != type::rsbrace) fail (t) << "expected ']' instead of " << t; next (t, tt); if (!standalone && (tt == type::newline || tt == type::eos)) fail (t) << "standalone attributes"; return make_pair (true, l); } // Splice names from the name view into the destination name list while // doing sensible things with pairs, types, etc. Return the number of // the names added. // // If nv points to nv_storage then the names can be moved. // size_t parser:: splice_names (const location& loc, const names_view& nv, names&& nv_storage, names& ns, const char* what, size_t pairn, const optional<project_name>& pp, const dir_path* dp, const string* tp) { // We could be asked to splice 0 elements (see the name pattern // expansion). In this case may need to pop the first half of the // pair. // if (nv.size () == 0) { if (pairn != 0) ns.pop_back (); return 0; } size_t start (ns.size ()); // Move if nv points to nv_storage, // bool m (nv.data () == nv_storage.data ()); for (const name& cn: nv) { name* n (m ? const_cast<name*> (&cn) : nullptr); // Project. // optional<project_name> p; if (cn.proj) { if (pp) fail (loc) << "nested project name " << *cn.proj << " in " << what; p = m ? move (n->proj) : cn.proj; } else if (pp) p = pp; // Directory. // dir_path d; if (!cn.dir.empty ()) { if (dp != nullptr) { if (cn.dir.absolute ()) fail (loc) << "nested absolute directory " << cn.dir << " in " << what; d = *dp / cn.dir; } else d = m ? move (n->dir) : cn.dir; } else if (dp != nullptr) d = *dp; // Type. // string t; if (!cn.type.empty ()) { if (tp != nullptr) fail (loc) << "nested type name " << cn.type << " in " << what; t = m ? move (n->type) : cn.type; } else if (tp != nullptr) t = *tp; // Value. // string v (m ? move (n->value) : cn.value); // If we are a second half of a pair. // if (pairn != 0) { // Check that there are no nested pairs. // if (cn.pair) fail (loc) << "nested pair in " << what; // And add another first half unless this is the first instance. // if (pairn != ns.size ()) ns.push_back (ns[pairn - 1]); } ns.emplace_back (move (p), move (d), move (t), move (v)); ns.back ().pair = cn.pair; } return ns.size () - start; } // Expand a name pattern. Note that the result can be empty (as in "no // elements"). // size_t parser:: expand_name_pattern (const location& l, names&& pat, names& ns, const char* what, size_t pairn, const dir_path* dp, const string* tp, const target_type* tt) { assert (!pat.empty () && (tp == nullptr || tt != nullptr)); // We are going to accumulate the result in a vector which can result in // quite a few linear searches. However, thanks to a few optimizations, // this shouldn't be an issue for the common cases (e.g., a pattern plus // a few exclusions). // names r; bool dir (false); // Figure out the start directory. // const dir_path* sp; dir_path s; if (dp != nullptr) { if (dp->absolute ()) sp = dp; else { s = *pbase_ / *dp; sp = &s; } } else sp = pbase_; // Compare string to name as paths and according to dir. // auto equal = [&dir] (const string& v, const name& n) -> bool { // Use path comparison (which may be slash/case-insensitive). // return path::traits::compare ( v, dir ? n.dir.representation () : n.value) == 0; }; // Compare name to pattern as paths and according to dir. // auto match = [&dir, sp] (const path& pattern, const name& n) -> bool { const path& p (dir ? path_cast<path> (n.dir) : path (n.value)); return butl::path_match (pattern, p, *sp); }; // Append name/extension to result according to dir. Store an indication // of whether it was amended as well as whether the extension is present // in the pair flag. The extension itself is stored in name::type. // auto append = [&r, &dir] (string&& v, optional<string>&& e, bool a) { name n (dir ? name (dir_path (move (v))) : name (move (v))); if (a) n.pair |= 0x01; if (e) { n.type = move (*e); n.pair |= 0x02; } r.push_back (move (n)); }; auto include_match = [&r, &equal, &append] (string&& m, optional<string>&& e, bool a) { auto i (find_if ( r.begin (), r.end (), [&m, &equal] (const name& n) {return equal (m, n);})); if (i == r.end ()) append (move (m), move (e), a); }; auto include_pattern = [&r, &append, &include_match, sp, &l, this] (string&& p, optional<string>&& e, bool a) { // If we don't already have any matches and our pattern doesn't contain // multiple recursive wildcards, then the result will be unique and we // can skip checking for duplicated. This should help quite a bit in the // common cases where we have a pattern plus maybe a few exclusions. // bool unique (false); if (r.empty ()) { size_t i (p.find ("**")); unique = (i == string::npos || p.find ("**", i + 2) == string::npos); } function<void (string&&, optional<string>&&)> appf; if (unique) appf = [a, &append] (string&& v, optional<string>&& e) { append (move (v), move (e), a); }; else appf = [a, &include_match] (string&& v, optional<string>&& e) { include_match (move (v), move (e), a); }; auto process = [&e, &appf, sp] (path&& m, const string& p, bool interm) { // Ignore entries that start with a dot unless the pattern that // matched them also starts with a dot. Also ignore directories // containing the .buildignore file. // const string& s (m.string ()); if ((p[0] != '.' && s[path::traits::find_leaf (s)] == '.') || (m.to_directory () && exists (*sp / m / buildignore_file))) return !interm; // Note that we have to make copies of the extension since there will // multiple entries for each pattern. // if (!interm) appf (move (m).representation (), optional<string> (e)); return true; }; try { butl::path_search (path (move (p)), process, *sp); } catch (const system_error& e) { fail (l) << "unable to scan " << *sp << ": " << e; } }; auto exclude_match = [&r, &equal] (const string& m) { // We know there can only be one element so we use find_if() instead of // remove_if() for efficiency. // auto i (find_if ( r.begin (), r.end (), [&m, &equal] (const name& n) {return equal (m, n);})); if (i != r.end ()) r.erase (i); }; auto exclude_pattern = [&r, &match] (string&& p) { path pattern (move (p)); for (auto i (r.begin ()); i != r.end (); ) { if (match (pattern, *i)) i = r.erase (i); else ++i; } }; // Process the pattern and inclusions/exclusions. // for (auto b (pat.begin ()), i (b), end (pat.end ()); i != end; ++i) { name& n (*i); bool first (i == b); char s ('\0'); // Inclusion/exclusion sign (+/-). // Reduce inclusions/exclusions group (-/+{foo bar}) to simple name/dir. // if (n.typed () && n.type.size () == 1) { if (!first) { s = n.type[0]; if (s == '-' || s == '+') n.type.clear (); } else { assert (n.type[0] == '+'); // Can only belong to inclusion group. n.type.clear (); } } if (n.empty () || !(n.simple () || n.directory ())) fail (l) << "invalid '" << n << "' in " << what << " pattern"; string v (n.simple () ? move (n.value) : move (n.dir).representation ()); // Figure out if this is inclusion or exclusion. // if (first) s = '+'; // Treat as inclusion. else if (s == '\0') { s = v[0]; assert (s == '-' || s == '+'); // Validated at the token level. v.erase (0, 1); if (v.empty ()) fail (l) << "empty " << what << " pattern"; } // Amend the pattern or match in a target type-specific manner. // // Name splitting must be consistent with scope::find_target_type(). // Since we don't do it for directories, we have to delegate it to the // target_type::pattern() call. // bool a (false); // Amended. optional<string> e; // Extension. { bool d; if (tt != nullptr && tt->pattern != nullptr) { a = tt->pattern (*tt, *scope_, v, e, l, false); d = path::traits::is_separator (v.back ()); } else { d = path::traits::is_separator (v.back ()); if (!d) e = target::split_name (v, l); } // Based on the first pattern verify inclusions/exclusions are // consistently file/directory. // if (first) dir = d; else if (d != dir) fail (l) << "inconsistent file/directory result in " << what << " pattern"; } // Factor non-empty extension back into the name for searching. // // Note that doing it at this stage means we don't support extension // patterns. // if (e && !e->empty ()) { v += '.'; v += *e; } try { if (s == '+') include_pattern (move (v), move (e), a); else { if (v.find_first_of ("*?") != string::npos) exclude_pattern (move (v)); else exclude_match (move (v)); } } catch (const invalid_path& e) { fail (l) << "invalid path '" << e.path << "' in " << what << " pattern"; } } // Post-process the result: remove extension, reverse target type-specific // pattern/match amendments (essentially: cxx{*} -> *.cxx -> foo.cxx -> // cxx{foo}), and recombined the result. // for (name& n: r) { string v; optional<string> e; if (dir) v = move (n.dir).representation (); else { v = move (n.value); if ((n.pair & 0x02) != 0) { e = move (n.type); // Remove non-empty extension from the name (it got to be there, see // above). // if (!e->empty ()) v.resize (v.size () - e->size () - 1); } } bool de (false); // Default extension. if ((n.pair & 0x01) != 0) { de = static_cast<bool> (e); tt->pattern (*tt, *scope_, v, e, l, true); de = de && !e; } if (dir) n.dir = dir_path (move (v)); else { target::combine_name (v, e, de); n.value = move (v); } n.pair = '\0'; } return splice_names ( l, names_view (r), move (r), ns, what, pairn, nullopt, dp, tp); } // Parse names inside {} and handle the following "crosses" (i.e., // {a b}{x y}) if any. Return the number of names added to the list. // size_t parser:: parse_names_trailer (token& t, type& tt, names& ns, pattern_mode pmode, const char* what, const string* separators, size_t pairn, const optional<project_name>& pp, const dir_path* dp, const string* tp, bool cross) { assert (!pre_parse_); if (pp) pmode = pattern_mode::ignore; next (t, tt); // Get what's after '{'. const location loc (get_location (t)); // Start of names. size_t start (ns.size ()); if (pairn == 0 && start != 0 && ns.back ().pair) pairn = start; names r; // Parse names until closing '}' expanding patterns. // auto parse = [&r, &t, &tt, pmode, what, separators, this] ( const optional<project_name>& pp, const dir_path* dp, const string* tp) { const location loc (get_location (t)); size_t start (r.size ()); // This can be an ordinary name group or a pattern (with inclusions and // exclusions). We want to detect which one it is since for patterns we // want just the list of simple names without pair/dir/type added (those // are added after the pattern expansion in parse_names_pattern()). // // Detecting which one it is is tricky. We cannot just peek at the token // and look for some wildcards since the pattern can be the result of an // expansion (or, worse, concatenation). Thus pattern_mode::detect: we // are going to ask parse_names() to detect for us if the first name is // a pattern. And if it is, to refrain from adding pair/dir/type. // optional<const target_type*> pat_tt ( parse_names ( t, tt, r, pmode == pattern_mode::expand ? pattern_mode::detect : pmode, false /* chunk */, what, separators, 0, // Handled by the splice_names() call below. pp, dp, tp, false /* cross */, true /* curly */).pattern); if (tt != type::rcbrace) fail (t) << "expected '}' instead of " << t; // See if this is a pattern. // if (pat_tt) { // Move the pattern names our of the result. // names ps; if (start == 0) ps = move (r); else ps.insert (ps.end (), make_move_iterator (r.begin () + start), make_move_iterator (r.end ())); r.resize (start); expand_name_pattern (loc, move (ps), r, what, 0, dp, tp, *pat_tt); } }; // Parse and expand the first group. // parse (pp, dp, tp); // Handle crosses. The overall plan is to take what's in r, cross each // element with the next group using the re-parse machinery, and store the // result back to r. // while (cross && peek () == type::lcbrace && !peeked ().separated) { next (t, tt); // Get '{'. names ln (move (r)); r.clear (); // Cross with empty LHS/RHS is empty. Handle the LHS case now by parsing // and discaring RHS (empty RHS is handled "naturally" below). // if (ln.size () == 0) { parse (nullopt, nullptr, nullptr); r.clear (); continue; } //@@ This can be a nested replay (which we don't support), for example, // via target-specific var assignment. Add support for nested (2-level // replay)? Why not use replay_guard for storage? Alternatively, don't // use it here (see parse_for() for an alternative approach). // replay_guard rg (*this, ln.size () > 1); for (auto i (ln.begin ()), e (ln.end ()); i != e; ) { next (t, tt); // Get what's after '{'. const location loc (get_location (t)); name& l (*i); // "Promote" the lhs value to type. // if (!l.value.empty ()) { if (!l.type.empty ()) fail (loc) << "nested type name " << l.value; l.type.swap (l.value); } parse (l.proj, l.dir.empty () ? nullptr : &l.dir, l.type.empty () ? nullptr : &l.type); if (++i != e) rg.play (); // Replay. } } // Splice the names into the result. Note that we have already handled // project/dir/type qualification but may still have a pair. Fast-path // common cases. // if (pairn == 0) { if (start == 0) ns = move (r); else ns.insert (ns.end (), make_move_iterator (r.begin ()), make_move_iterator (r.end ())); } else splice_names (loc, names_view (r), move (r), ns, what, pairn, nullopt, nullptr, nullptr); return ns.size () - start; } // Slashe(s) plus '%'. Note that here we assume '/' is there since that's // in our buildfile "syntax". // const string parser::name_separators ( string (path::traits::directory_separators) + '%'); auto parser:: parse_names (token& t, type& tt, names& ns, pattern_mode pmode, bool chunk, const char* what, const string* separators, size_t pairn, const optional<project_name>& pp, const dir_path* dp, const string* tp, bool cross, bool curly) -> parse_names_result { // Note that support for pre-parsing is partial, it does not handle // groups ({}). // // If pairn is not 0, then it is an index + 1 of the first half of the // pair for which we are parsing the second halves, for example: // // a@{b c d{e f} {}} tracer trace ("parser::parse_names", &path_); if (pp) pmode = pattern_mode::ignore; // Returned value NULL/type and pattern (see below). // bool vnull (false); const value_type* vtype (nullptr); optional<const target_type*> rpat; // Buffer that is used to collect the complete name in case of an // unseparated variable expansion or eval context, e.g., foo$bar($baz)fox. // The idea is to concatenate all the individual parts in this buffer and // then re-inject it into the loop as a single token. // // If the concatenation is untyped (see below), then the name should be // simple (i.e., just a string). // bool concat (false); bool concat_quoted (false); name concat_data; auto concat_typed = [&vnull, &vtype, &concat, &concat_data, this] (value&& rhs, const location& loc) { // If we have no LHS yet, then simply copy value/type. // if (concat) { small_vector<value, 2> a; // Convert LHS to value. // a.push_back (value (vtype)); // Potentially typed NULL value. if (!vnull) a.back ().assign (move (concat_data), nullptr); // RHS. // a.push_back (move (rhs)); const char* l ((a[0].type != nullptr ? a[0].type->name : "<untyped>")); const char* r ((a[1].type != nullptr ? a[1].type->name : "<untyped>")); pair<value, bool> p; { // Print the location information in case the function fails. // auto g ( make_exception_guard ( [&loc, l, r] () { if (verb != 0) info (loc) << "while concatenating " << l << " to " << r << info << "use quoting to force untyped concatenation"; })); p = functions.try_call ( scope_, "builtin.concat", vector_view<value> (a), loc); } if (!p.second) fail (loc) << "no typed concatenation of " << l << " to " << r << info << "use quoting to force untyped concatenation"; rhs = move (p.first); // It seems natural to expect that a typed concatenation result // is also typed. // assert (rhs.type != nullptr); } vnull = rhs.null; vtype = rhs.type; if (!vnull) { if (vtype != nullptr) untypify (rhs); names& d (rhs.as<names> ()); // If the value is empty, then untypify() will (typically; no pun // intended) represent it as an empty sequence of names rather than // a sequence of one empty name. This is usually what we need (see // simple_reverse() for details) but not in this case. // if (!d.empty ()) { assert (d.size () == 1); // Must be a single value. concat_data = move (d[0]); } } }; // Set the result pattern target type and switch to the ignore mode. // // The goal of the detect mode is to assemble the "raw" list (the pattern // itself plus inclusions/exclusions) that will then be passed to // parse_names_pattern(). So clear pair, directory, and type (they will be // added during pattern expansion) and change the mode to ignore (to // prevent any expansions in inclusions/exclusions). // auto pattern_detected = [&pairn, &dp, &tp, &rpat, &pmode] (const target_type* ttp) { assert (pmode == pattern_mode::detect); pairn = 0; dp = nullptr; tp = nullptr; pmode = pattern_mode::ignore; rpat = ttp; }; // Return '+' or '-' if a token can start an inclusion or exclusion // (pattern or group), '\0' otherwise. The result can be used as bool. // // @@ Note that we only need to make sure that the leading '+' or '-' // characters are unquoted. We could consider some partially quoted // tokens as starting inclusion or exclusion as well, for example // +'foo*'. However, currently we can not determine which part of a // token is quoted, and so can't distinguish the above token from // '+'foo*. This is why we end up with a criteria that is stricter than // is really required. // auto pattern_prefix = [] (const token& t) -> char { char c; return t.type == type::word && ((c = t.value[0]) == '+' || c == '-') && t.qtype == quote_type::unquoted ? c : '\0'; }; // A name sequence potentially starts with a pattern if it starts with a // literal unquoted plus character. // bool ppat (pmode == pattern_mode::detect && pattern_prefix (t) == '+'); // Potential pattern inclusion group. To be recognized as such it should // start with the literal unquoted '+{' string and expand into a non-empty // name sequence. // // The first name in such a group is a pattern, regardless of whether it // contains wildcard characters or not. The trailing names are inclusions. // For example the following pattern groups are equivalent: // // cxx{+{f* *oo}} // cxx{f* +*oo} // bool pinc (ppat && t.value == "+" && peek () == type::lcbrace && !peeked ().separated); // Number of names in the last group. This is used to detect when // we need to add an empty first pair element (e.g., @y) or when // we have a (for now unsupported) multi-name LHS (e.g., {x y}@z). // size_t count (0); size_t start (ns.size ()); for (bool first (true);; first = false) { // Note that here we assume that, except for the first iterartion, // tt contains the type of the peeked token. // Automatically reset the detect pattern mode to expand after the // first element. // if (pmode == pattern_mode::detect && start != ns.size ()) pmode = pattern_mode::expand; // Return true if the next token (which should be peeked at) won't be // part of the name. // auto last_token = [chunk, this] () { const token& t (peeked ()); type tt (t.type); return ((chunk && t.separated) || (tt != type::word && tt != type::dollar && tt != type::lparen && tt != type::lcbrace && tt != type::pair_separator)); }; // Return true if the next token (which should be peeked at) won't be // part of this concatenation. The et argument can be used to recognize // an extra (unseparated) token type as being concatenated. // auto last_concat = [this] (type et = type::eos) { const token& t (peeked ()); type tt (t.type); return (t.separated || (tt != type::word && tt != type::dollar && tt != type::lparen && (et == type::eos ? true : tt != et))); }; // If we have accumulated some concatenations, then we have two options: // continue accumulating or inject. We inject if the next token is not a // word, var expansion, or eval context or if it is separated. // if (concat && last_concat ()) { // Concatenation does not affect the tokens we get, only what we do // with them. As a result, we never set the concat flag during pre- // parsing. // assert (!pre_parse_); bool quoted (concat_quoted); concat = false; concat_quoted = false; // If this is a result of typed concatenation, then don't inject. For // one we don't want any of the "interpretations" performed in the // word parsing code below. // // And if this is the only name, then we also want to preserve the // type in the result. // // There is one exception, however: if the type is path, dir_path, or // string and what follows is an unseparated '{', then we need to // untypify it and inject in order to support our directory/target- // type syntax (this means that a target type must be a valid path // component). For example: // // $out_root/foo/lib{bar} // $out_root/$libtype{bar} // // And here is another exception: if we have a project, directory, or // type, then this is a name and we should also untypify it (let's for // now do it for the same set of types as the first exception). For // example: // // dir/{$str} // file{$str} // vnull = false; // A concatenation cannot produce NULL. if (vtype != nullptr) { bool e1 (tt == type::lcbrace && !peeked ().separated); bool e2 (pp || dp != nullptr || tp != nullptr); if (e1 || e2) { if (vtype == &value_traits<path>::value_type || vtype == &value_traits<string>::value_type) ; // Representation is already in concat_data.value. else if (vtype == &value_traits<dir_path>::value_type) concat_data.value = move (concat_data.dir).representation (); else { diag_record dr (fail (t)); if (e1) dr << "expected directory and/or target type"; else if (e2) dr << "expected name"; dr << " instead of " << vtype->name << endf; } vtype = nullptr; // Fall through to injection. } else { ns.push_back (move (concat_data)); // Clear the type information if that's not the only name. // if (start != ns.size () || !last_token ()) vtype = nullptr; // Restart the loop (but now with concat mode off) to handle // chunking, etc. // continue; } } // Replace the current token with our injection (after handling it we // will peek at the current token again). // // We don't know what exactly was quoted so approximating as partially // mixed quoted. // tt = type::word; t = token (move (concat_data.value), true, quoted ? quote_type::mixed : quote_type::unquoted, false, t.line, t.column); } else if (!first) { // If we are chunking, stop at the next separated token. // next (t, tt); if (chunk && t.separated) break; // If we are parsing the pattern group, then space-separated tokens // must start inclusions or exclusions (see above). // if (rpat && t.separated && tt != type::rcbrace && !pattern_prefix (t)) fail (t) << "expected name pattern inclusion or exclusion"; } // Name. // // A user may specify a value that is an invalid name (e.g., it contains // '%' but the project name is invalid). While it may seem natural to // expect quoting/escaping to be the answer, we may need to quote names // (e.g., spaces in paths) and so in our model quoted values are still // treated as names and we rely on reversibility if we need to treat // them as values. The reasonable solution to the invalid name problem is // then to treat them as values if they are quoted. // if (tt == type::word) { tt = peek (); if (pre_parse_) continue; string val (move (t.value)); bool quoted (t.qtype != quote_type::unquoted); // Should we accumulate? If the buffer is not empty, then we continue // accumulating (the case where we are separated should have been // handled by the injection code above). If the next token is a var // expansion or eval context and it is not separated, then we need to // start accumulating. // if (concat || // Continue. !last_concat ()) // Start. { // If LHS is typed then do typed concatenation. // if (concat && vtype != nullptr) { // Create untyped RHS. // names ns; ns.push_back (name (move (val))); concat_typed (value (move (ns)), get_location (t)); } else { auto& v (concat_data.value); if (v.empty ()) v = move (val); else v += val; } concat = true; concat_quoted = quoted || concat_quoted; continue; } // Find a separator (slash or %). // string::size_type p (separators != nullptr ? val.find_last_of (*separators) : string::npos); // First take care of project. A project-qualified name is not very // common, so we can afford some copying for the sake of simplicity. // optional<project_name> p1; const optional<project_name>* pp1 (&pp); if (p != string::npos) { bool last (val[p] == '%'); string::size_type q (last ? p : val.rfind ('%', p - 1)); for (; q != string::npos; ) // Breakout loop. { // Process the project name. // string proj (val, 0, q); try { p1 = !proj.empty () ? project_name (move (proj)) : project_name (); } catch (const invalid_argument& e) { if (quoted) // See above. break; fail (t) << "invalid project name '" << proj << "': " << e; } if (pp) fail (t) << "nested project name " << *p1; pp1 = &p1; // Now fix the rest of the name. // val.erase (0, q + 1); p = last ? string::npos : p - (q + 1); break; } } string::size_type n (p != string::npos ? val.size () - 1 : 0); // See if this is a type name, directory prefix, or both. That // is, it is followed by an un-separated '{'. // if (tt == type::lcbrace && !peeked ().separated) { next (t, tt); // Resolve the target, if there is one, for the potential pattern // inclusion group. If we fail, then this is not an inclusion group. // const target_type* ttp (nullptr); if (pinc) { assert (val == "+"); if (tp != nullptr && scope_ != nullptr) { ttp = scope_->find_target_type (*tp); if (ttp == nullptr) ppat = pinc = false; } } if (p != n && tp != nullptr && !pinc) fail (t) << "nested type name " << val; dir_path d1; const dir_path* dp1 (dp); string t1; const string* tp1 (tp); try { if (p == string::npos) // type tp1 = &val; else if (p == n) // directory { if (dp == nullptr) d1 = dir_path (val); else d1 = *dp / dir_path (val); dp1 = &d1; } else // both { t1.assign (val, p + 1, n - p); if (dp == nullptr) d1 = dir_path (val, 0, p + 1); else d1 = *dp / dir_path (val, 0, p + 1); dp1 = &d1; tp1 = &t1; } } catch (const invalid_path& e) { fail (t) << "invalid path '" << e.path << "'"; } count = parse_names_trailer ( t, tt, ns, pmode, what, separators, pairn, *pp1, dp1, tp1, cross); // If empty group or empty name, then this is not a pattern inclusion // group (see above). // if (pinc) { if (count != 0 && (count > 1 || !ns.back ().empty ())) pattern_detected (ttp); ppat = pinc = false; } tt = peek (); continue; } // See if this is a wildcard pattern. // // It should either contain a wildcard character or, in a curly // context, start with unquoted '+'. // if (pmode != pattern_mode::ignore && !*pp1 && // Cannot be project-qualified. !quoted && // Cannot be quoted. ((dp != nullptr && dp->absolute ()) || pbase_ != nullptr) && ((val.find_first_of ("*?") != string::npos) || (curly && val[0] == '+'))) { // Resolve the target if there is one. If we fail, then this is not // a pattern. // const target_type* ttp (tp != nullptr && scope_ != nullptr ? scope_->find_target_type (*tp) : nullptr); if (tp == nullptr || ttp != nullptr) { if (pmode == pattern_mode::detect) { // Strip the literal unquoted plus character for the first // pattern in the group. // if (ppat) { assert (val[0] == '+'); val.erase (0, 1); ppat = pinc = false; } // Reset the detect pattern mode to expand if the pattern is not // followed by the inclusion/exclusion pattern/match. Note that // if it is '}' (i.e., the end of the group), then it is a single // pattern and the expansion is what we want. // if (!pattern_prefix (peeked ())) pmode = pattern_mode::expand; } if (pmode == pattern_mode::expand) { count = expand_name_pattern (get_location (t), names {name (move (val))}, ns, what, pairn, dp, tp, ttp); continue; } pattern_detected (ttp); // Fall through. } } // If we are a second half of a pair, add another first half // unless this is the first instance. // if (pairn != 0 && pairn != ns.size ()) ns.push_back (ns[pairn - 1]); count = 1; // If it ends with a directory separator, then it is a directory. // Note that at this stage we don't treat '.' and '..' as special // (unless they are specified with a directory separator) because // then we would have ended up treating '.: ...' as a directory // scope. Instead, this is handled higher up the processing chain, // in scope::find_target_type(). This would also mess up // reversibility to simple name. // if (p == n) { // For reversibility to simple name, only treat it as a directory // if the string is an exact representation. // dir_path dir (move (val), dir_path::exact); if (!dir.empty ()) { if (dp != nullptr) dir = *dp / dir; ns.emplace_back (*pp1, move (dir), (tp != nullptr ? *tp : string ()), string ()); continue; } } ns.emplace_back (*pp1, (dp != nullptr ? *dp : dir_path ()), (tp != nullptr ? *tp : string ()), move (val)); continue; } // Variable expansion, function call, or eval context. // if (tt == type::dollar || tt == type::lparen) { // These cases are pretty similar in that in both we quickly end up // with a list of names that we need to splice into the result. // location loc; value result_data; const value* result (&result_data); const char* what; // Variable, function, or evaluation context. bool quoted (t.qtype != quote_type::unquoted); if (tt == type::dollar) { // Switch to the variable name mode. We want to use this mode for // $foo but not for $(foo). Since we don't know whether the next // token is a paren or a word, we turn it on and switch to the eval // mode if what we get next is a paren. // mode (lexer_mode::variable); next (t, tt); loc = get_location (t); name qual; string name; if (t.separated) ; // Leave the name empty to fail below. else if (tt == type::word) { if (!pre_parse_) name = move (t.value); } else if (tt == type::lparen) { expire_mode (); values vs (parse_eval (t, tt, pmode)); //@@ OUT will parse @-pair and do well? if (!pre_parse_) { if (vs.size () != 1) fail (loc) << "expected single variable/function name"; value& v (vs[0]); if (!v) fail (loc) << "null variable/function name"; names storage; vector_view<build2::name> ns (reverse (v, storage)); // Movable. size_t n (ns.size ()); // We cannot handle scope-qualification in the eval context as // we do for target-qualification (see eval-qual) since then we // would be treating all paths as qualified variables. So we // have to do it here. // if (n == 2 && ns[0].pair == ':') // $(foo: x) { qual = move (ns[0]); if (qual.empty ()) fail (loc) << "empty variable/function qualification"; } else if (n == 2 && ns[0].directory ()) // $(foo/ x) { qual = move (ns[0]); qual.pair = '/'; } else if (n > 1) fail (loc) << "expected variable/function name instead of '" << ns << "'"; // Note: checked for empty below. // if (!ns[n - 1].simple ()) fail (loc) << "expected variable/function name instead of '" << ns[n - 1] << "'"; name = move (ns[n - 1].value); } } else fail (t) << "expected variable/function name instead of " << t; if (!pre_parse_ && name.empty ()) fail (loc) << "empty variable/function name"; // Figure out whether this is a variable expansion or a function // call. // tt = peek (); // Note that we require function call opening paren to be // unseparated; consider: $x ($x == 'foo' ? 'FOO' : 'BAR'). // if (tt == type::lparen && !peeked ().separated) { // Function call. // next (t, tt); // Get '('. // @@ Should we use (target/scope) qualification (of name) as the // context in which to call the function? Hm, interesting... // values args (parse_eval (t, tt, pmode)); tt = peek (); if (pre_parse_) continue; // As if empty result. // Note that we "move" args to call(). // result_data = functions.call (scope_, name, args, loc); what = "function call"; } else { // Variable expansion. // if (pre_parse_) continue; // As if empty value. lookup l (lookup_variable (move (qual), move (name), loc)); if (l.defined ()) result = l.value; // Otherwise leave as NULL result_data. what = "variable expansion"; } } else { // Context evaluation. // loc = get_location (t); values vs (parse_eval (t, tt, pmode)); tt = peek (); if (pre_parse_) continue; // As if empty result. switch (vs.size ()) { case 0: result_data = value (names ()); break; case 1: result_data = move (vs[0]); break; default: fail (loc) << "expected single value"; } what = "context evaluation"; } // We never end up here during pre-parsing. // assert (!pre_parse_); // Should we accumulate? If the buffer is not empty, then we continue // accumulating (the case where we are separated should have been // handled by the injection code above). If the next token is a word // or an expansion and it is not separated, then we need to start // accumulating. We also reduce the $var{...} case to concatention // and injection. // if (concat || // Continue. !last_concat (type::lcbrace)) // Start. { // This can be a typed or untyped concatenation. The rules that // determine which one it is are as follows: // // 1. Determine if to preserver the type of RHS: if its first // token is quoted, then we do not. // // 2. Given LHS (if any) and RHS we do typed concatenation if // either is typed. // // Here are some interesting corner cases to meditate on: // // $dir/"foo bar" // $dir"/foo bar" // "foo"$dir // "foo""$dir" // ""$dir // // First if RHS is typed but quoted then convert it to an untyped // string. // // Conversion to an untyped string happens differently, depending // on whether we are in a quoted or unquoted context. In an // unquoted context we use $representation() which must return a // "round-trippable representation" (and if that it not possible, // then it should not be overloaded for a type). In a quoted // context we use $string() which returns a "canonical // representation" (e.g., a directory path without a trailing // slash). // if (result->type != nullptr && quoted) { // RHS is already a value but it could be a const reference (to // the variable value) while we need to move things around. So in // this case we make a copy. // if (result != &result_data) result = &(result_data = *result); const char* t (result_data.type->name); pair<value, bool> p; { // Print the location information in case the function fails. // auto g ( make_exception_guard ( [&loc, t] () { if (verb != 0) info (loc) << "while converting " << t << " to string"; })); p = functions.try_call ( scope_, "string", vector_view<value> (&result_data, 1), loc); } if (!p.second) fail (loc) << "no string conversion for " << t; result_data = move (p.first); untypify (result_data); // Convert to untyped simple name. } if ((concat && vtype != nullptr) || // LHS typed. (result->type != nullptr)) // RHS typed. { if (result != &result_data) // Same reason as above. result = &(result_data = *result); concat_typed (move (result_data), loc); } // // Untyped concatenation. Note that if RHS is NULL/empty, we still // set the concat flag. // else if (!result->null && !result->empty ()) { // This can only an untyped value. // // @@ Could move if result == &result_data. // const names& lv (cast<names> (*result)); // This should be a simple value or a simple directory. // if (lv.size () > 1) fail (loc) << "concatenating " << what << " contains multiple " << "values"; const name& n (lv[0]); if (n.qualified ()) fail (loc) << "concatenating " << what << " contains project " << "name"; if (n.typed ()) fail (loc) << "concatenating " << what << " contains type"; if (!n.dir.empty ()) { if (!n.value.empty ()) fail (loc) << "concatenating " << what << " contains " << "directory"; // Note that here we cannot assume what's in dir is really a // path (think s/foo/bar/) so we have to reverse it exactly. // concat_data.value += n.dir.representation (); } else concat_data.value += n.value; } concat = true; concat_quoted = quoted || concat_quoted; } else { // See if we should propagate the value NULL/type. We only do this // if this is the only expansion, that is, it is the first and the // next token is not part of the name. // if (first && last_token ()) { vnull = result->null; vtype = result->type; } // Nothing else to do here if the result is NULL or empty. // if (result->null || result->empty ()) continue; // @@ Could move if nv is result_data; see untypify(). // names nv_storage; names_view nv (reverse (*result, nv_storage)); count = splice_names ( loc, nv, move (nv_storage), ns, what, pairn, pp, dp, tp); } continue; } // Untyped name group without a directory prefix, e.g., '{foo bar}'. // if (tt == type::lcbrace) { count = parse_names_trailer ( t, tt, ns, pmode, what, separators, pairn, pp, dp, tp, cross); tt = peek (); continue; } // A pair separator. // if (tt == type::pair_separator) { if (pairn != 0) fail (t) << "nested pair on the right hand side of a pair"; tt = peek (); if (!pre_parse_) { // Catch double pair separator ('@@'). Maybe we can use for // something later (e.g., escaping). // if (!ns.empty () && ns.back ().pair) fail (t) << "double pair separator"; if (t.separated || count == 0) { // Empty LHS, (e.g., @y), create an empty name. The second test // will be in effect if we have something like v=@y. // ns.emplace_back (pp, (dp != nullptr ? *dp : dir_path ()), (tp != nullptr ? *tp : string ()), string ()); count = 1; } else if (count > 1) fail (t) << "multiple " << what << "s on the left hand side " << "of a pair"; ns.back ().pair = t.value[0]; // If the next token is separated, then we have an empty RHS. Note // that the case where it is not a name/group (e.g., a newline/eos) // is handled below, once we are out of the loop. // if (peeked ().separated) { ns.emplace_back (pp, (dp != nullptr ? *dp : dir_path ()), (tp != nullptr ? *tp : string ()), string ()); count = 0; } } continue; } // Note: remember to update last_token() test if adding new recognized // tokens. if (!first) break; if (tt == type::rcbrace) // Empty name, e.g., dir{}. { // If we are a second half of a pair, add another first half // unless this is the first instance. // if (pairn != 0 && pairn != ns.size ()) ns.push_back (ns[pairn - 1]); ns.emplace_back (pp, (dp != nullptr ? *dp : dir_path ()), (tp != nullptr ? *tp : string ()), string ()); break; } else // Our caller expected this to be something. // fail (t) << "expected " << what << " instead of " << t; } // Handle the empty RHS in a pair, (e.g., y@). // if (!ns.empty () && ns.back ().pair) { ns.emplace_back (pp, (dp != nullptr ? *dp : dir_path ()), (tp != nullptr ? *tp : string ()), string ()); } return parse_names_result {!vnull, vtype, rpat}; } void parser:: skip_line (token& t, type& tt) { for (; tt != type::newline && tt != type::eos; next (t, tt)) ; } void parser:: skip_block (token& t, type& tt) { // Skip until } or eos, keeping track of the {}-balance. // for (size_t b (0); tt != type::eos; ) { if (tt == type::lcbrace || tt == type::rcbrace) { type ptt (peek ()); if (ptt == type::newline || ptt == type::eos) // Block { or }. { if (tt == type::lcbrace) ++b; else { if (b == 0) break; --b; } } } skip_line (t, tt); if (tt != type::eos) next (t, tt); } } bool parser:: keyword (token& t) { assert (replay_ == replay::stop); // Can't be used in a replay. assert (t.type == type::word); // The goal here is to allow using keywords as variable names and // target types without imposing ugly restrictions/decorators on // keywords (e.g., '.using' or 'USING'). A name is considered a // potential keyword if: // // - it is not quoted [so a keyword can always be escaped] and // - next token is '\n' (or eos) or '(' [so if(...) will work] or // - next token is separated and is not '=', '=+', or '+=' [which // means a "directive trailer" can never start with one of them]. // // See tests/keyword. // if (t.qtype == quote_type::unquoted) { // We cannot peek at the whole token here since it might have to be // lexed in a different mode. So peek at its first character. // pair<char, bool> p (lexer_->peek_char ()); char c (p.first); // @@ Just checking for leading '+' is not sufficient, for example: // // print +foo // return c == '\n' || c == '\0' || c == '(' || (p.second && c != '=' && c != '+'); } return false; } // Buildspec parsing. // // Here is the problem: we "overload" '(' and ')' to mean operation // application rather than the eval context. At the same time we want to use // parse_names() to parse names, get variable expansion/function calls, // quoting, etc. We just need to disable the eval context. The way this is // done has two parts: Firstly, we parse names in chunks and detect and // handle the opening paren ourselves. In other words, a buildspec like // 'clean (./)' is "chunked" as 'clean', '(', etc. While this is fairly // straightforward, there is one snag: concatenating eval contexts, as in // 'clean(./)'. Normally, this will be treated as a single chunk and we // don't want that. So here comes the trick (or hack, if you like): the // buildspec lexer mode makes every opening paren token "separated" (i.e., // as if it was preceeded by a space). This will disable concatenating // eval. // // In fact, because this is only done in the buildspec mode, we can still // use eval contexts provided that we quote them: '"cle(an)"'. Note that // function calls also need quoting (since a separated '(' is not treated as // function call): '"$identity(update)"'. // // This poses a problem, though: if it's quoted then it is a concatenated // expansion and therefore cannot contain multiple values, for example, // $identity(foo/ bar/). So what we do is disable this chunking/separation // after both meta-operation and operation were specified. So if we specify // both explicitly, then we can use eval context, function calls, etc., // normally: perform(update($identity(foo/ bar/))). // buildspec parser:: parse_buildspec (istream& is, const path& name) { path_ = &name; // We do "effective escaping" and only for ['"\$(] (basically what's // necessary inside a double-quoted literal plus the single quote). // lexer l (is, *path_, 1 /* line */, "\'\"\\$("); lexer_ = &l; scope_ = root_ = scope::global_; pbase_ = &work; // Use current working directory. target_ = nullptr; prerequisite_ = nullptr; // Turn on the buildspec mode/pairs recognition with '@' as the pair // separator (e.g., src_root/@out_root/exe{foo bar}). // mode (lexer_mode::buildspec, '@'); token t; type tt; next (t, tt); buildspec r (tt != type::eos ? parse_buildspec_clause (t, tt, 0) : buildspec ()); if (tt != type::eos) fail (t) << "expected operation or target instead of " << t; return r; } static bool opname (const name& n) { // First it has to be a non-empty simple name. // if (n.pair || !n.simple () || n.empty ()) return false; // Like C identifier but with '-' instead of '_' as the delimiter. // for (size_t i (0); i != n.value.size (); ++i) { char c (n.value[i]); if (c != '-' && !(i != 0 ? alnum (c) : alpha (c))) return false; } return true; } buildspec parser:: parse_buildspec_clause (token& t, type& tt, size_t depth) { buildspec bs; for (bool first (true);; first = false) { // We always start with one or more names. Eval context (lparen) only // allowed if quoted. // if (tt != type::word && tt != type::lcbrace && // Untyped name group: '{foo ...' tt != type::dollar && // Variable expansion: '$foo ...' !(tt == type::lparen && mode () == lexer_mode::double_quoted) && tt != type::pair_separator) // Empty pair LHS: '@foo ...' { if (first) fail (t) << "expected operation or target instead of " << t; break; } const location l (get_location (t)); // Start of names. // This call will parse the next chunk of output and produce zero or // more names. // names ns (parse_names (t, tt, pattern_mode::expand, depth < 2)); if (ns.empty ()) // Can happen if pattern expansion. fail (l) << "expected operation or target"; // What these names mean depends on what's next. If it is an opening // paren, then they are operation/meta-operation names. Otherwise they // are targets. // if (tt == type::lparen) // Got by parse_names(). { if (ns.empty ()) fail (t) << "expected operation name before '('"; for (const name& n: ns) if (!opname (n)) fail (l) << "expected operation name instead of '" << n << "'"; // Inside '(' and ')' we have another, nested, buildspec. Push another // mode to keep track of the depth (used in the lexer implementation // to decide when to stop separating '('). // mode (lexer_mode::buildspec, '@'); next (t, tt); // Get what's after '('. const location l (get_location (t)); // Start of nested names. buildspec nbs (parse_buildspec_clause (t, tt, depth + 1)); // Parse additional operation/meta-operation parameters. // values params; while (tt == type::comma) { next (t, tt); // Note that for now we don't expand patterns. If it turns out we // need this, then will probably have to be (meta-) operation- // specific (via pre-parse or some such). // params.push_back (tt != type::rparen ? parse_value (t, tt, pattern_mode::ignore) : value (names ())); } if (tt != type::rparen) fail (t) << "expected ')' instead of " << t; expire_mode (); next (t, tt); // Get what's after ')'. // Merge the nested buildspec into ours. But first determine if we are // an operation or meta-operation and do some sanity checks. // bool meta (false); for (const metaopspec& nms: nbs) { // We definitely shouldn't have any meta-operations. // if (!nms.name.empty ()) fail (l) << "nested meta-operation " << nms.name; if (!meta) { // If we have any operations in the nested spec, then this mean // that our names are meta-operation names. // for (const opspec& nos: nms) { if (!nos.name.empty ()) { meta = true; break; } } } } // No nested meta-operations means we should have a single // metaopspec object with empty meta-operation name. // assert (nbs.size () == 1); const metaopspec& nmo (nbs.back ()); if (meta) { for (name& n: ns) { bs.push_back (nmo); bs.back ().name = move (n.value); bs.back ().params = params; } } else { // Since we are not a meta-operation, the nested buildspec should be // just a bunch of targets. // assert (nmo.size () == 1); const opspec& nos (nmo.back ()); if (bs.empty () || !bs.back ().name.empty ()) bs.push_back (metaopspec ()); // Empty (default) meta operation. for (name& n: ns) { bs.back ().push_back (nos); bs.back ().back ().name = move (n.value); bs.back ().back ().params = params; } } } else if (!ns.empty ()) { // Group all the targets into a single operation. In other // words, 'foo bar' is equivalent to 'update(foo bar)'. // if (bs.empty () || !bs.back ().name.empty ()) bs.push_back (metaopspec ()); // Empty (default) meta operation. metaopspec& ms (bs.back ()); for (auto i (ns.begin ()), e (ns.end ()); i != e; ++i) { // @@ We may actually want to support this at some point. // if (i->qualified ()) fail (l) << "expected target name instead of " << *i; if (opname (*i)) ms.push_back (opspec (move (i->value))); else { // Do we have the src_base? // dir_path src_base; if (i->pair) { if (i->pair != '@') fail << "unexpected pair style in buildspec"; if (i->typed ()) fail (l) << "expected target src_base instead of " << *i; src_base = move (i->dir); if (!i->value.empty ()) src_base /= dir_path (move (i->value)); ++i; assert (i != e); // Got to have the second half of the pair. } if (ms.empty () || !ms.back ().name.empty ()) ms.push_back (opspec ()); // Empty (default) operation. opspec& os (ms.back ()); os.emplace_back (move (src_base), move (*i)); } } } } return bs; } lookup parser:: lookup_variable (name&& qual, string&& name, const location& loc) { tracer trace ("parser::lookup_variable", &path_); // Process variable name. @@ OLD // if (name.front () == '.') // Fully namespace-qualified name. name.erase (0, 1); else { //@@ TODO : append namespace if any. } const scope* s (nullptr); const target* t (nullptr); const prerequisite* p (nullptr); // If we are qualified, it can be a scope or a target. // enter_scope sg; enter_target tg; if (qual.empty ()) { s = scope_; t = target_; p = prerequisite_; } else { switch (qual.pair) { case '/': { assert (qual.directory ()); sg = enter_scope (*this, move (qual.dir)); s = scope_; break; } case ':': { qual.pair = '\0'; // @@ OUT TODO // tg = enter_target ( *this, move (qual), build2::name (), true, loc, trace); t = target_; break; } default: assert (false); } } // Lookup. // const auto& var (var_pool.rw (*scope_).insert (move (name), true)); if (p != nullptr) { // The lookup depth is a bit of a hack but should be harmless since // unused. // pair<lookup, size_t> r (p->vars[var], 1); if (!r.first.defined ()) r = t->find_original (var); return var.override == nullptr ? r.first : t->base_scope ().find_override (var, move (r), true).first; } if (t != nullptr) { if (var.visibility > variable_visibility::target) { fail (loc) << "variable " << var << " has " << var.visibility << " visibility but is expanded in target context"; } return (*t)[var]; } if (s != nullptr) { if (var.visibility > variable_visibility::scope) { fail (loc) << "variable " << var << " has " << var.visibility << " visibility but is expanded in scope context"; } return (*s)[var]; } // Undefined/NULL namespace variables are not allowed. // // @@ TMP this isn't proving to be particularly useful. // // if (!l) // { // if (var.name.find ('.') != string::npos) // fail (loc) << "undefined/null namespace variable " << var; // } return lookup (); } void parser:: switch_scope (const dir_path& d) { tracer trace ("parser::switch_scope", &path_); auto p (build2::switch_scope (*root_, d)); scope_ = &p.first; pbase_ = scope_->src_path_; if (p.second != nullptr && p.second != root_) { root_ = p.second; l5 ([&]{trace << "switching to root scope " << root_->out_path ();}); } } void parser:: process_default_target (token& t) { tracer trace ("parser::process_default_target", &path_); // The logic is as follows: if we have an explicit current directory // target, then that's the default target. Otherwise, we take the // first target and use it as a prerequisite to create an implicit // current directory target, effectively making it the default // target via an alias. If there are no targets in this buildfile, // then we don't do anything. // if (default_target_ == nullptr) // No targets in this buildfile. return; target& dt (*default_target_); target* ct ( const_cast<target*> ( // Ok (serial execution). targets.find (dir::static_type, // Explicit current dir target. scope_->out_path (), dir_path (), // Out tree target. string (), nullopt, trace))); if (ct == nullptr) { l5 ([&]{trace (t) << "creating current directory alias for " << dt;}); // While this target is not explicitly mentioned in the buildfile, we // say that we behave as if it were. Thus not implied. // ct = &targets.insert (dir::static_type, scope_->out_path (), dir_path (), string (), nullopt, false, trace).first; // Fall through. } else if (ct->implied) { ct->implied = false; // Fall through. } else return; // Existing and not implied. ct->prerequisites_state_.store (2, memory_order_relaxed); ct->prerequisites_.emplace_back (prerequisite (dt)); } void parser:: enter_buildfile (const path& p) { tracer trace ("parser::enter_buildfile", &path_); dir_path d (p.directory ()); // Figure out if we need out. // dir_path out; if (scope_->src_path_ != nullptr && scope_->src_path () != scope_->out_path () && d.sub (scope_->src_path ())) { out = out_src (d, *root_); } targets.insert<buildfile> ( move (d), move (out), p.leaf ().base ().string (), p.extension (), // Always specified. trace); } type parser:: next (token& t, type& tt) { replay_token r; if (peeked_) { r = move (peek_); peeked_ = false; } else r = replay_ != replay::play ? lexer_next () : replay_next (); if (replay_ == replay::save) replay_data_.push_back (r); t = move (r.token); tt = t.type; return tt; } type parser:: peek () { if (!peeked_) { peek_ = (replay_ != replay::play ? lexer_next () : replay_next ()); peeked_ = true; } return peek_.token.type; } }
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * THE BSD LICENSE * * 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 nor the names of its contributors may be * used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "base/cinfo.h" #include "base/ereport.h" #include "NSJavaUtil.h" #include "NSAPIVirtualServer.h" #include "com_sun_webserver_connector_nsapi_NSAPIVirtualServer.h" NSAPIVirtualServer::NSAPIVirtualServer(VirtualServer* vs) : _vs(vs), _uriMapper(NULL), _jVirtualServer(0L) { } NSAPIVirtualServer::~NSAPIVirtualServer(void) { _vs = NULL; _jVirtualServer = NULL; for (int i = 0; i < _webModules.length(); i++) delete (WebModule*) _webModules[i]; if (_uriMapper != NULL) { delete _uriMapper; _uriMapper = NULL; } } char* NSAPIVirtualServer::getDocumentRoot() { if (_vs) return vs_get_doc_root(_vs); return NULL; } char* NSAPIVirtualServer::translateURI(const char* uri) const { if (_vs) return vs_translate_uri(_vs, uri); return NULL; } // Return the underlying vs. Needed by native realm support. VirtualServer* NSAPIVirtualServer::getVirtualServer() { return _vs; } // // Save the corresponding Java VirtualServer object // void NSAPIVirtualServer::setJavaObject(long jVirtualServer) { _jVirtualServer = jVirtualServer; } // // Return the corresponding Java VirtualServer object // long NSAPIVirtualServer::getJavaObject(void) { return _jVirtualServer; } // XXX : addWebModule assumes that contextPath starts with a '/' and // does not have a trailing '/'. It also assumes that location exists. // jcontext is a reference to the java context object WebModule* NSAPIVirtualServer::addWebModule(const char* contextName, const char* contextPath, long jcontext, const char* location) { WebModule* wm = new WebModule(contextName, contextPath, jcontext, location); if (wm) { _webModules.append((void*) wm); _uriMap.addUriSpace(contextPath, wm); ereport(LOG_VERBOSE, (char*)"Adding web module : context = %s, location = %s", contextPath, location); } return wm; } void NSAPIVirtualServer::createUriMapper(void) { _uriMapper = new UriMapper<WebModule*>(_uriMap); } // matchWebModule checks if a request uri matches a web application // context path using the following rule from the servlet 2.3 spec. // SRV. 11.1 Use of URL Paths // Upon receipt of a client request, the web container determines the web // application to which to forward it. The web application selected must // have the the longest context path that matches the start of the request // URL. The matched part of the URL is the context path when mapping to // servlets. WebModule* NSAPIVirtualServer::matchWebModule(char* uri) { WebModule* wm = NULL; if (_uriMapper) wm = _uriMapper->map(uri); return wm; } JNIEXPORT jstring JNICALL Java_com_sun_webserver_connector_nsapi_NSAPIVirtualServer_jniFindMimeMapping(JNIEnv* env, jobject obj, jlong jniVS, jstring jextension) { NSAPIVirtualServer* nsapiVS = (NSAPIVirtualServer*)jniVS; const char* extension = NULL; if (jextension != NULL) extension = env->GetStringUTFChars(jextension , NULL); const char* type = vs_find_ext_type(nsapiVS->getVirtualServer(), extension); if (jextension != NULL) env->ReleaseStringUTFChars(jextension, extension); if (type == NULL) return NULL; return env->NewStringUTF(type); } JNIEXPORT void JNICALL Java_com_sun_webserver_connector_nsapi_NSAPIVirtualServer_jniSetContextMapping(JNIEnv* env, jobject obj, jlong jniVS, jobject jcontext, jstring jctxname, jstring jctxpath, jstring jctxlocation, jint servlet_size, jintArray servlet_length_array, jbyteArray servlet_mapping, jobjectArray jwrappers, jint mime_size, jintArray mime_length_array, jbyteArray mimes, jint welcome_size, jintArray welcome_length_array, jbyteArray welcome_files, jint error_size, jintArray error_codes, jintArray error_length_array, jbyteArray error_pages, jint sec_size, jintArray url_pattern_length,jintArray sec_len_buffer,jbyteArray sec_byte_buffer, jint count, jintArray filter_len_buffer,jbyteArray filter_byte_buffer, jboolean form_login, jboolean default_servlet_has_content, jboolean useRequestEncforHeaders) { int i, j; NSAPIVirtualServer* nsapiVS = (NSAPIVirtualServer*)jniVS; char key[1024]; char mapping[1024]; const char* ctx_name = NULL; const char* ctx_path = NULL; const char* ctx_location = NULL; if (jctxname != NULL) { ctx_name = env->GetStringUTFChars(jctxname , NULL); } if (jctxpath != NULL) { ctx_path = env->GetStringUTFChars(jctxpath , NULL); } if (jctxlocation != NULL) { ctx_location = env->GetStringUTFChars(jctxlocation , NULL); } // Add a webmodule for this ctx if (jcontext) jcontext = env->NewGlobalRef(jcontext); WebModule* web_module = nsapiVS->addWebModule(ctx_name, ctx_path, (long)jcontext, ctx_location); if (web_module == NULL) { if (jctxname != NULL) { env->ReleaseStringUTFChars(jctxname , ctx_name); } if (jctxpath != NULL) { env->ReleaseStringUTFChars(jctxpath , ctx_path); } if (jctxlocation != NULL) { env->ReleaseStringUTFChars(jctxlocation , ctx_location); } if (jcontext) env->DeleteGlobalRef(jcontext); return; } web_module->setDefaultServletHasContent(default_servlet_has_content); // Handle servlet mapping first before filter mapping and sec constraints // since we use the same hash table for all mappings and we don't want servlet // mapping to be overwritten for a equivalent uri jint* string_length = (jint*)env->GetIntArrayElements(servlet_length_array, NULL); jbyte* cbuf = (jbyte*)env->GetByteArrayElements(servlet_mapping, NULL); jbyte* pbuf = cbuf; int obj_index = 0; // Add servlet mapping first for (i = 0; i < servlet_size; i+=2, obj_index++) { memcpy(key, (const char*)pbuf, string_length[i]); key[string_length[i]] = '\0'; pbuf+= string_length[i]; memcpy(mapping, (const char*)pbuf, string_length[i+1]); mapping[string_length[i+1]] = '\0'; pbuf += string_length[i+1]; jobject wrapper = env->GetObjectArrayElement(jwrappers, obj_index); if (wrapper) wrapper= env->NewGlobalRef(wrapper); if (web_module->addServletMapping(key, mapping, (long)wrapper) == PR_FALSE) { if (wrapper) { env->DeleteGlobalRef(wrapper); } } } env->ReleaseByteArrayElements(servlet_mapping, cbuf, 0); env->ReleaseIntArrayElements(servlet_length_array, string_length, 0); // Handle mime mapping string_length = (jint*)env->GetIntArrayElements(mime_length_array, NULL); cbuf = (jbyte*)env->GetByteArrayElements(mimes, NULL); pbuf = cbuf; for (i = 0; i < mime_size; i+=2) { memcpy(key, (const char*)pbuf, string_length[i]); key[string_length[i]] = '\0'; pbuf+= string_length[i]; memcpy(mapping, (const char*)pbuf, string_length[i+1]); mapping[string_length[i+1]] = '\0'; pbuf += string_length[i+1]; web_module->addMimeMapping(key, mapping); } env->ReleaseByteArrayElements(mimes, cbuf, 0); env->ReleaseIntArrayElements(mime_length_array, string_length, 0); // Handle welcome files if (welcome_size > 0) { string_length = (jint*)env->GetIntArrayElements(welcome_length_array, NULL); cbuf = (jbyte*)env->GetByteArrayElements(welcome_files, NULL); pbuf = cbuf; char ** welcomeFileList = (char**)PERM_MALLOC(welcome_size * sizeof(char**)); for (i = 0; i < welcome_size; i++) { welcomeFileList[i] = (char*)PERM_MALLOC(string_length[i]+1); memcpy(welcomeFileList[i], (const char*)pbuf, string_length[i]); welcomeFileList[i][string_length[i]] = '\0'; pbuf+= string_length[i]; } web_module->setWelcomeFileList(welcome_size, welcomeFileList); env->ReleaseByteArrayElements(welcome_files, cbuf, 0); env->ReleaseIntArrayElements(welcome_length_array, string_length, 0); } // Handle error files string_length = (jint*)env->GetIntArrayElements(error_length_array, NULL); jint* errCodes = (jint*)env->GetIntArrayElements(error_codes, NULL); cbuf = (jbyte*)env->GetByteArrayElements(error_pages, NULL); pbuf = cbuf; for (i = 0; i < error_size; i++) { memcpy(key, (const char*)pbuf, string_length[i]); key[string_length[i]] = '\0'; pbuf+= string_length[i]; web_module->addErrorPage(errCodes[i],key); } env->ReleaseByteArrayElements(error_pages, cbuf, 0); env->ReleaseIntArrayElements(error_length_array, string_length, 0); env->ReleaseIntArrayElements(error_codes, errCodes, 0); // Handle sec constraints string_length = (jint*)env->GetIntArrayElements(sec_len_buffer, NULL); cbuf = (jbyte*)env->GetByteArrayElements(sec_byte_buffer, NULL); jint* url_length = (jint*)env->GetIntArrayElements(url_pattern_length, NULL); pbuf = cbuf; int index = 0; for (i = 0; i < sec_size; i++) { memcpy(key, (const char*)pbuf, string_length[index]); key[string_length[index]] = '\0'; pbuf+= string_length[index++]; for (j = 0; j < url_length[i]; j++) { memcpy(mapping, (const char*)pbuf, string_length[index]); mapping[string_length[index]] = '\0'; pbuf+= string_length[index++]; web_module->addSecurityMapping(key,mapping); } } env->ReleaseIntArrayElements(url_pattern_length,url_length, 0); env->ReleaseByteArrayElements(sec_byte_buffer, cbuf, 0); env->ReleaseIntArrayElements(sec_len_buffer, string_length, 0); // Handle Filter Mappings string_length = (jint*)env->GetIntArrayElements(filter_len_buffer, NULL); cbuf = (jbyte*)env->GetByteArrayElements(filter_byte_buffer, NULL); pbuf = cbuf; for (i = 0; i < count; i+=2) { memcpy(key, (const char*)pbuf, string_length[i]); key[string_length[i]] = '\0'; pbuf+= string_length[i]; memcpy(mapping, (const char*)pbuf, string_length[i+1]); mapping[string_length[i+1]] = '\0'; pbuf += string_length[i+1]; web_module->addFilterMapping(key,mapping); } env->ReleaseByteArrayElements(filter_byte_buffer, cbuf, 0); env->ReleaseIntArrayElements(filter_len_buffer, string_length, 0); // ereport(LOG_FAILURE, "form Login present for %s = %d",ctx_path, form_login); web_module->setUseRequestEncforHeaders(useRequestEncforHeaders); if (jctxname != NULL) { env->ReleaseStringUTFChars(jctxname , ctx_name); } if (jctxpath != NULL) { env->ReleaseStringUTFChars(jctxpath , ctx_path); } if (jctxlocation != NULL) { env->ReleaseStringUTFChars(jctxlocation , ctx_location); } } JNIEXPORT void JNICALL Java_com_sun_webserver_connector_nsapi_NSAPIVirtualServer_jniSetContextUnavailable(JNIEnv* env, jobject obj, jlong jniVS, jobject jcontext, jstring jctxname, jstring jctxpath, jstring jctxlocation) { const char* ctx_name = NULL; const char* ctx_path = NULL; const char* ctx_location = NULL; if (jctxname != NULL) { ctx_name = env->GetStringUTFChars(jctxname , NULL); } if (jctxpath != NULL) { ctx_path = env->GetStringUTFChars(jctxpath , NULL); } if (jctxlocation != NULL) { ctx_location = env->GetStringUTFChars(jctxlocation , NULL); } // Add a webmodule for this ctx if (jcontext) jcontext = env->NewGlobalRef(jcontext); NSAPIVirtualServer* nsapiVS = (NSAPIVirtualServer*)jniVS; WebModule* web_module = nsapiVS->addWebModule(ctx_name, ctx_path, (long)jcontext, ctx_location); if (web_module == NULL) { if (jctxname != NULL) { env->ReleaseStringUTFChars(jctxname , ctx_name); } if (jctxpath != NULL) { env->ReleaseStringUTFChars(jctxpath , ctx_path); } if (jctxlocation != NULL) { env->ReleaseStringUTFChars(jctxlocation , ctx_location); } if (jcontext) env->DeleteGlobalRef(jcontext); return; } web_module->setUnavailable(); if (jctxname != NULL) { env->ReleaseStringUTFChars(jctxname , ctx_name); } if (jctxpath != NULL) { env->ReleaseStringUTFChars(jctxpath , ctx_path); } if (jctxlocation != NULL) { env->ReleaseStringUTFChars(jctxlocation , ctx_location); } } JNIEXPORT jstring JNICALL Java_com_sun_webserver_connector_nsapi_NSAPIVirtualServer_jniGetRealPath (JNIEnv *env, jobject obj, jlong jniVS, jstring juri) { NSAPIVirtualServer* nsapiVS = (NSAPIVirtualServer*)jniVS; jstring jRealPath = NULL; const char* uri = NULL; if (juri != NULL) uri = env->GetStringUTFChars(juri, NULL); char* realPath = nsapiVS->translateURI(uri); jRealPath = NSJavaUtil::createString(env, realPath); FREE(realPath); if (juri != NULL) env->ReleaseStringUTFChars(juri, uri); return jRealPath; } JNIEXPORT void JNICALL Java_com_sun_webserver_connector_nsapi_NSAPIVirtualServer_jniCreateContextUriMapper(JNIEnv* env, jobject obj, jlong jniVS) { NSAPIVirtualServer* nsapiVS = (NSAPIVirtualServer*)jniVS; nsapiVS->createUriMapper(); }
/* * Copyright (C) 2017 The LineageOS Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "android.hardware.vibrator@1.1-service.mata" #include <hidl/HidlTransportSupport.h> #include "Vibrator.h" using android::hardware::configureRpcThreadpool; using android::hardware::joinRpcThreadpool; using android::hardware::vibrator::V1_1::IVibrator; using android::hardware::vibrator::V1_1::implementation::Vibrator; using android::OK; using android::sp; using android::status_t; static constexpr char DURATION_PATH[] = "/sys/devices/virtual/timed_output/vibrator/enable"; static constexpr char VTG_INPUT_PATH[] = "/sys/devices/virtual/timed_output/vibrator/vtg_level"; static constexpr char MODE_PATH[] = "/sys/devices/virtual/timed_output/vibrator/play_mode"; static constexpr char BUFFER_UPDATE_PATH[] = "/sys/devices/virtual/timed_output/vibrator/wf_update"; static constexpr char BUFFER_PATH_PATTERN[] = "/sys/devices/virtual/timed_output/vibrator/wf_s%d"; static constexpr int8_t NUM_BUFFERS = 8; status_t registerVibratorService() { // ostreams below are required std::ofstream duration{DURATION_PATH}; if (!duration) { int error = errno; ALOGE("Failed to open %s (%d): %s", DURATION_PATH, error, strerror(error)); return -error; } std::ofstream vtgInput{VTG_INPUT_PATH}; if (!vtgInput) { int error = errno; ALOGE("Failed to open %s (%d): %s", VTG_INPUT_PATH, error, strerror(error)); return -error; } std::ofstream mode{MODE_PATH}; if (!mode) { int error = errno; ALOGE("Failed to open %s (%d): %s", MODE_PATH, error, strerror(error)); return -error; } std::ofstream bufferUpdate{BUFFER_UPDATE_PATH}; if (!mode) { int error = errno; ALOGE("Failed to open %s (%d): %s", BUFFER_UPDATE_PATH, error, strerror(error)); return -error; } std::vector<std::ofstream> buffers; for (int i = 0; i < NUM_BUFFERS; i++) { char path[sizeof(BUFFER_PATH_PATTERN) + 1]; snprintf(path, sizeof(path), BUFFER_PATH_PATTERN, i); std::ofstream buf{path}; if (!buf) { int error = errno; ALOGE("Failed to open %s (%d): %s", path, error, strerror(error)); return -error; } buffers.push_back(std::move(buf)); } sp<IVibrator> vibrator = new Vibrator(std::move(duration), std::move(vtgInput),std::move(mode), std::move(bufferUpdate), std::move(buffers)); vibrator->registerAsService(); return OK; } int main() { configureRpcThreadpool(1, true); status_t status = registerVibratorService(); if (status != OK) { return status; } ALOGI("Vibrator HAL service ready."); joinRpcThreadpool(); ALOGI("Vibrator HAL service failed to join thread pool."); return 1; }
#pragma once #include <trwlang/node.hpp> #include <vector> #include <unordered_map> namespace trwlang { struct matcher { std::unordered_map<std::string, node const *> hold; bool match (node const & p, node const & e) { stack_expr_.clear(); stack_pattern_.clear(); stack_expr_.push_back(&e); stack_pattern_.push_back(&p); while (stack_pattern_.size() > 0) { node const * p = stack_pattern_.back(); stack_pattern_.pop_back(); if (p == nullptr) { if (stack_expr_.size() == 0) { return false; } if (stack_expr_.back() != nullptr) { return false; } stack_expr_.pop_back(); continue; } if (!consume(*p)) { return false; } } return true; } private: bool consume (node const & p) { switch (p.kind()) { case node_kind::inner_node : return consume_inner_node(p.get_inner_node()); case node_kind::string_node : return consume_string_node(p.get_string_node()); case node_kind::int_node : return consume_int_node(p.get_int_node()); case node_kind::bool_node : return consume_bool_node(p.get_bool_node()); default : assert(false && "not implemented"); } } bool consume_inner_node (inner_node const & p) { if (check_head(p, "PatternAny")) { return consume_pattern_any_node(p); } if (check_head(p, "PatternHold")) { return consume_pattern_hold_node(p); } if (check_head(p, "PatternOneOrMore")) { return consume_pattern_one_or_more_node(p); } if (stack_expr_.size() == 0) { return false; } if (!stack_expr_.back()->is_inner_node()) { return false; } inner_node const & e = stack_expr_.back()->get_inner_node(); stack_expr_.pop_back(); stack_pattern_.push_back(nullptr); for (auto i = p.size_child() - 1; i >= 0; --i) { stack_pattern_.push_back(&p.child(i)); } stack_expr_.push_back(nullptr); for (auto i = e.size_child() - 1; i >= 0; --i) { stack_expr_.push_back(&e.child(i)); } return true; } bool consume_pattern_any_node (inner_node const & p) { assert(check_head(p, "PatternAny")); if (stack_expr_.size() == 0) { return false; } stack_expr_.pop_back(); return true; } bool consume_pattern_hold_node (inner_node const & p) { assert(check_head(p, "PatternHold")); if (p.size_child() != 2) { // TODO: error? return false; } auto & tag = p.child(1); if (!tag.is_string_node()) { // TODO: error? return false; } hold[tag.get_string_node().value] = (stack_expr_.size() > 0 ? stack_expr_.back() : nullptr); stack_pattern_.push_back(&p.child(2)); return true; } bool consume_pattern_one_or_more_node (inner_node const & p) { assert(check_head(p, "PatternOneOrMore")); if (p.size_child() != 1) { return false; } if (stack_expr_.size() == 0) { return false; } if (stack_expr_.back() == nullptr) { return false; } stack_expr_.pop_back(); while (true) { if (stack_expr_.size() == 0) { break; } if (stack_expr_.back() == nullptr) { break; } stack_expr_.pop_back(); } return true; } bool consume_string_node (string_node const & p) { if (stack_expr_.size() == 0) { return false; } if (stack_expr_.back() == nullptr) { return false; } if (!stack_expr_.back()->is_string_node()) { return false; } if (stack_expr_.back()->get_string_node().value != p.value) { return false; } stack_expr_.pop_back(); return true; } bool consume_int_node (int_node const & p) { if (stack_expr_.size() == 0) { return false; } if (stack_expr_.back() == nullptr) { return false; } if (!stack_expr_.back()->is_int_node()) { return false; } if (stack_expr_.back()->get_int_node().value != p.value) { return false; } stack_expr_.pop_back(); return true; } bool consume_bool_node (bool_node const & p) { if (stack_expr_.size() == 0) { return false; } if (stack_expr_.back() == nullptr) { return false; } if (!stack_expr_.back()->is_bool_node()) { return false; } if (stack_expr_.back()->get_bool_node().value != p.value) { return false; } stack_expr_.pop_back(); return true; } std::vector<node const *> stack_pattern_; std::vector<node const *> stack_expr_; }; }
#include <2020/Day14Puzzle.hpp> #include <zeno-engine/Utility/StringExtensions.hpp> #include <algorithm> #include <bitset> #include <cassert> #include <set> #include <functional> namespace TwentyTwenty { Day14Puzzle::Day14Puzzle() : core::PuzzleBase("Docking Data", 2020, 14) { } void Day14Puzzle::initialise(const core::InitialisationInfo& _initialisationInfo) { setInputLines(ze::StringExtensions::splitStringByDelimeter(ze::StringExtensions::loadFileToString(_initialisationInfo.parameters[0]), "\n")); } void Day14Puzzle::setInputLines(const std::vector<std::string>& _inputLines) { m_InputLines = std::vector<std::string>(_inputLines); } std::pair<std::string, std::string> Day14Puzzle::fastSolve() { const auto& parsed = parse(m_InputLines); const auto part1 = doPart1(parsed); const auto part2 = doPart2(parsed); return { part1, part2 }; } std::vector<Day14Struct> Day14Puzzle::parse(const std::vector<std::string>& _inputLines) { std::vector<Day14Struct> parsed; for (unsigned i = 0; i < _inputLines.size(); ++i) { const auto& s = ze::StringExtensions::splitStringByDelimeter(_inputLines[i], " []"); if (s[0] == "mask") { auto& current = parsed.emplace_back(); current.mask = s[2]; } else { auto& current = parsed.back(); current.mem.emplace_back(std::stoll(s[1]),std::stoll(s[3])); } } return parsed; } std::string Day14Puzzle::doPart1(const std::vector<Day14Struct>& _parsed) { std::unordered_map<Day14Number, Day14Number> memory; for (const auto& _program : _parsed) { assert(_program.mask.size() == 36); for (const auto& [loc, val] : _program.mem) { const Day14Number memoryValue = val; std::bitset<36> value(memoryValue); for (unsigned i = 0; i < 36; ++i) { if (_program.mask[i] == '0') { value[36 - 1 - i] = 0; } else if (_program.mask[i] == '1') { value[36 - 1 - i] = 1; } } const Day14Number maskedValue = value.to_ullong(); memory[loc] = maskedValue; } } Day14Number sum = 0; for (const auto& [loc, val] : memory) { sum += val; } return std::to_string(sum); } template<typename T> void iterateCombinations2(const T& c, Day14Number k, std::function<void(const T&)> _callback) { int n = c.size(); int combo = (1 << k) - 1; while (combo < 1 << n) { T temp; for (int i = 0; i < n; ++i) { if ((combo >> i) & 1) { temp.push_back(c[i]); } } _callback(temp); int x = combo & -combo; int y = combo + x; int z = (combo & ~y); combo = z / x; combo >>= 1; combo |= y; } } std::string Day14Puzzle::doPart2(const std::vector<Day14Struct>& _parsed) { std::unordered_map<Day14Number, Day14Number> memory; for (const auto& _program : _parsed) { assert(_program.mask.size() == 36); for (const auto& [loc, val] : _program.mem) { const Day14Number valueValue = val; std::bitset<36> location(loc); std::vector<Day14Number> floatingBitIndex; for (unsigned i = 0; i < 36; ++i) { if (_program.mask[i] == '1') { location[36 - 1 - i] = 1; } else if (_program.mask[i] == 'X') { location[36 - 1 - i] = 0; floatingBitIndex.push_back(36 - 1 - i); } } const auto& call = std::function<void(const std::vector<Day14Number>&)>( [&](const std::vector<Day14Number>& _vec) -> void { std::bitset<36> floatingLocation(location); for (const auto v : _vec) { floatingLocation[static_cast<unsigned>(v)] = 1; } memory[floatingLocation.to_ullong()] = valueValue; }); for (unsigned i = 1; i <= floatingBitIndex.size(); ++i) { iterateCombinations2(floatingBitIndex, (Day14Number)i, call); } call({}); } } Day14Number sum = 0; for (const auto& [loc, val] : memory) { sum += val; } return std::to_string(sum); } }
//============================================================================== // Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <nt2/ieee/include/functions/maxnum.hpp> #include <boost/simd/sdk/simd/io.hpp> #include <vector> #include <nt2/include/constants/valmin.hpp> #include <nt2/include/constants/valmax.hpp> #include <nt2/sdk/unit/tests/cover.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/include/functions/max.hpp> NT2_TEST_CASE_TPL ( maxnum_real, NT2_TYPES) { using nt2::maxnum; using nt2::tag::maxnum_; typedef typename nt2::meta::call<maxnum_(T, T)>::type r_t; nt2::uint32_t NR = NT2_NB_RANDOM_TEST; std::vector<T> in1(NR), in2(NR); std::vector<r_t> ref(NR); nt2::roll(in1, nt2::Valmin<T>()/2, nt2::Valmax<T>()/2); nt2::roll(in2, nt2::Valmin<T>()/2, nt2::Valmax<T>()/2); for(nt2::uint32_t i=0; i < NR ; ++i) { ref[i] = nt2::max(in1[i], in2[i]); } NT2_COVER_ULP_EQUAL(maxnum_, ((T, in1))((T, in2)), ref, 0); }
#define INITGUID #include "c3.h" #include "c3errors.h" #include "globals.h" #include "aui.h" #include "debugwindow.h" extern DebugWindow *g_debugWindow; #include "ConstDB.h" extern ConstDB *g_theConstDB; #include "dynarr.h" #include "SelItem.h" extern SelectedItem *g_selected_item; #include "TurnCnt.h" extern TurnCount *g_turn; #include "bset.h" #include "player.h" #include "Unit.h" #include <objbase.h> #include "IRobot.h" #include "C3GameState.h" #include "aicause.h" #include "IMapGen.h" #include "ic3BlgDB.h" #include "ic3Rand.h" #include "C3UnitDB.h" #include "C3BlgDB.h" #include "C3InstDB.h" #include "CivPaths.h" #include "C3TerrDB.h" #include "C3ErrorReport.h" #include "C3String.h" #include "C3Rand.h" #include "C3Player.h" #include "C3World.h" #include "C3Science.h" #include "C3Government.h" #include "C3Wonder.h" #include "C3Population.h" #include "RobotAstar.h" #include "c3endgamedb.h" #include "aui_surface.h" #include "maputils.h" #include "primitives.h" #include "tileset.h" #include "XY_Coordinates.h" #include "World.h" #include "ic3DipReq.h" #include "profileDB.h" #include "C3Trade.h" #include "TradeOffer.h" #include "SlicObject.h" #include "SlicEngine.h" #include "TradeOfferPool.h" #include "UnitDynArr.h" #include "UnitData.h" #include "tiledmap.h" #include "radarmap.h" #include "Civilisation.h" #include "debugmemory.h" #include "log.h" #include "debugcallstack.h" #include "player.h" extern World *g_theWorld; extern ProfileDB *g_theProfileDB; extern Player **g_player; extern TiledMap *g_tiledMap; extern RadarMap *g_radarMap; #include "tiledmap.h" extern TiledMap *g_tiledMap; #include "chatbox.h" extern ChatBox *g_chatBox; #include "network.h" #include "net_info.h" #include "net_action.h" #include "order.h" #include "director.h" #include "AdvanceRecord.h" #include "UnitRecord.h" #define NO_TIMING_FILENAME_YET "notiming.txt" static char memory_file_name[300] = NO_TIMING_FILENAME_YET; static char time_stamp[300] = NO_TIMING_FILENAME_YET; #ifndef _BFR_ #ifdef TIME_TEST static char timing_file_name[300] = NO_TIMING_FILENAME_YET; #endif #endif extern Director *g_director; extern sint32 g_scenarioUsePlayerNumber; RobotInterface::RobotInterface() { MapPoint *size = g_theWorld->GetSize(); m_the_stop_player = 1; if(g_scenarioUsePlayerNumber != 0) m_the_stop_player = g_scenarioUsePlayerNumber; m_my_turn_is_over = FALSE; sint32 z, x; m_map_value = new MapValueStruct**[size->z]; for (z=0; z<size->z; z++) { m_map_value[z] = new MapValueStruct *[size->x]; for (x=0; x<size->x; x++) { m_map_value[z][x] = new MapValueStruct [size->y]; } } Clear(); } void RobotInterface::ResizeMap(sint32 sx, sint32 sy, sint32 sz) { MapPoint *size = g_theWorld->GetSize(); sint32 z, x; for (z=0; z<size->z; z++) { for (x=0; x<size->x; x++) { delete[] m_map_value[z][x]; } delete[] m_map_value[z]; } delete[] m_map_value; m_map_value = new MapValueStruct**[sz]; for (z=0; z<sz; z++) { m_map_value[z] = new MapValueStruct *[sx]; for (x=0; x<sx; x++) { m_map_value[z][x] = new MapValueStruct [sy]; } } } void RobotInterface::Clear() { sint32 i, j; for (i=0; i<k_MAX_PLAYERS; i++) { for (j=0; j<_MAX_PATH; j++) { m_name[i][j] = 0; } m_robot_dll[i] = NULL; m_robot_create[i] = NULL; m_accumulated_frame_time[i] = 0; m_new_age_unit[i].m_underwater = FALSE; m_new_age_unit[i].m_space = FALSE; m_new_age_unit[i].m_wormhole= FALSE; } } RobotInterface::RobotInterface(CivArchive &archive) { sint32 z, x; MapPoint *size = g_theWorld->GetSize(); m_map_value = new MapValueStruct**[size->z]; for (z=0; z<size->z; z++) { m_map_value[z] = new MapValueStruct *[size->x]; for (x=0; x<size->x; x++) { m_map_value[z][x] = new MapValueStruct [size->y]; } } Clear(); Serialize(archive); } RobotInterface::~RobotInterface() { sint32 i, j; BOOL searching; MapPoint *size = g_theWorld->GetSize(); sint32 z, x; for (z=0; z<size->z; z++) { for (x=0; x<size->x; x++) { delete[] m_map_value[z][x]; } delete[] m_map_value[z]; } delete[] m_map_value; } BOOL RobotInterface::Init(sint32 n_ai, PLAYER_INDEX player_idx[k_MAX_PLAYERS]) { sint32 i; InitStaticSettle(); return TRUE; } BOOL RobotInterface::AddRobotPlayer(const sint32 player_index) { return TRUE; } BOOL RobotInterface::AttachRobotTo(sint32 playerIndex) { Assert(g_player[playerIndex]); if(g_player[playerIndex]) { sint32 i, n, j, k; Player *p = g_player[playerIndex]; n = p->m_all_cities->Num(); for(i = 0; i < n; i++) { MapPoint pos; p->m_all_cities->Access(i).GetPos(pos); BuildQueue *bq = p->m_all_cities->Access(i).AccessData()->GetCityData()->GetBuildQueue(); bq->ClearAllButHead(); p->m_all_cities->Access(i).AccessData()->GetCityData()->KillAllTradeRoutes(); if(g_network.IsClient()) { g_network.SendAction(new NetAction(NET_ACTION_KILL_ALL_TRADE_ROUTES, p->m_all_cities->Access(i).m_id)); } BSetID id = p->m_all_cities_id->Get(i); RegisterCreatedCity(p->m_all_cities->Access(i), playerIndex, id, CAUSE_NEW_CITY_INITIAL, pos); if(bq->GetHead()) { RegisterSetBuildFront(playerIndex, p->m_all_cities->Access(i), bq->GetHead()->m_category, bq->GetHead()->m_type); } } for(i = 0; i < g_theAdvanceDB->NumRecords(); i++) { if(p->m_advances->HasAdvance(i)) { RegisterLearnedScience(playerIndex, i, CAUSE_SCI_INITIAL); } } n = p->m_all_armies->Num(); Army a; sint32 unit_type[k_MAX_ARMY_SIZE]; sint32 unit_hp[k_MAX_ARMY_SIZE]; for(i = 0; i < n; i++) { a = p->m_all_armies->Access(i); for(j = 0; j < a.Num(); j++) { unit_type[j] = a[j].GetType(); unit_hp[j] = sint32(a[j].GetHP()); } BSetID id = p->m_all_armies_id->Get(i); RegisterCreatedArmy(playerIndex, id, CAUSE_NEW_ARMY_INITIAL, 0, a.Num(), unit_type, unit_hp); for(j = 0; j < a.Num(); j++) { if(a[j].GetNumCarried() > 0) { UnitDynamicArray *list = a[j].AccessData()->GetCargoList(); for(k = 0; k < list->Num(); k++) { id = p->m_all_armies_id->Get(i); RegisterInsertCargo(playerIndex, id.GetVal(), list->Access(k).GetType(), (sint32)list->Access(k).GetHP() ); } } } } for(i = 0; i < k_MAX_PLAYERS; i++) { if(p->HasContactWith(i)) RegisterContactMade(playerIndex, i); } n = g_theTradeOfferPool->GetNumTradeOffers(); for(i = 0; i < n; i++) { C3TradeOffer *c3to = new C3TradeOffer(g_theTradeOfferPool->GetTradeOffer(i), playerIndex); c3to->AddRef(); c3to->Release(); } g_player[playerIndex]->m_playerType = PLAYER_TYPE_ROBOT; if(g_network.IsHost()) { g_network.Enqueue(new NetInfo(NET_INFO_CODE_ATTACH_ROBOT, playerIndex)); } if(g_selected_item->GetCurPlayer() == playerIndex) { m_my_turn_is_over = TRUE; if(g_network.IsActive()) { if(playerIndex == g_network.GetPlayerIndex()) { g_director->AddEndTurn(); } else if(g_network.IsLocalPlayer(playerIndex)) { g_turn->EndThisTurnBeginNewTurn(FALSE); } } } } return TRUE; } BOOL RobotInterface::DetachRobotFrom(sint32 playerIndex) { if(!g_player[playerIndex]) return FALSE; if(g_player[playerIndex]) { g_player[playerIndex]->m_playerType = PLAYER_TYPE_HUMAN; m_my_turn_is_over = FALSE; if(g_network.IsHost()) { g_network.Enqueue(new NetInfo(NET_INFO_CODE_DETACH_ROBOT, playerIndex)); } } sint32 rounded = sint32(g_player[playerIndex]->m_materialsTax * 10.0); g_player[playerIndex]->SetMaterialsTax(double(rounded) / 10.0); return TRUE; } BOOL RobotInterface::LoadCom(sint32 p) { sint32 i; return TRUE; } void RobotInterface::Serialize(CivArchive &archive) { sint32 i; CHECKSERIALIZE BOOL r; BOOL has_robot; if (archive.IsStoring()) { archive << m_the_stop_player; archive.PutSINT32(m_my_turn_is_over); archive << m_nAIPlayers; archive.Store((uint8*) m_name, k_MAX_PLAYERS * _MAX_PATH); archive.Store((uint8*) m_accumulated_frame_time, k_MAX_PLAYERS * sizeof(uint32)); for (i=0; i<k_MAX_PLAYERS; i++) { if (IsLivingRobot(i)) { archive.PutSINT32(1); } else { archive.PutSINT32(0); } } sint32 player_idx; for (player_idx=0; player_idx<k_MAX_PLAYERS; player_idx++) { archive.PutSINT32(m_new_age_unit[player_idx].m_underwater); archive.PutSINT32(m_new_age_unit[player_idx].m_space); archive.PutSINT32(m_new_age_unit[player_idx].m_wormhole); } sint32 z, x, y; MapPoint *size = g_theWorld->GetSize(); for (z=0; z<size->z; z++) { for (x=0; x<size->x; x++) { for (y=0; y<size->y; y++) { archive << m_map_value[z][x][y].m_settle_value; } } } } else { archive >> m_the_stop_player; m_my_turn_is_over = archive.GetSINT32(); archive >> m_nAIPlayers; archive.Load((uint8 *)m_name, k_MAX_PLAYERS * _MAX_PATH); archive.Load((uint8 *)m_accumulated_frame_time, k_MAX_PLAYERS * sizeof(uint32)); for (i=0; i<k_MAX_PLAYERS; i++) { has_robot = archive.GetSINT32(); if (has_robot) { } } sint32 player_idx; for (player_idx=0; player_idx<k_MAX_PLAYERS; player_idx++) { m_new_age_unit[player_idx].m_underwater = archive.GetSINT32(); m_new_age_unit[player_idx].m_space = archive.GetSINT32(); m_new_age_unit[player_idx].m_wormhole = archive.GetSINT32(); } sint32 z, x, y; MapPoint *size = g_theWorld->GetSize(); for (z=0; z<size->z; z++) { for (x=0; x<size->x; x++) { for (y=0; y<size->y; y++) { archive >> m_map_value[z][x][y].m_settle_value; } } } if(g_scenarioUsePlayerNumber != 0) m_the_stop_player = g_scenarioUsePlayerNumber; } CHECKSERIALIZE } extern double g_ai_count; BOOL RobotInterface::AiIsMovingThisTurn() const { return FALSE; } BOOL RobotInterface::BeginTurn() { PLAYER_INDEX p = g_selected_item->GetCurPlayer(); m_accumulated_frame_time[p] = 0; m_my_turn_is_over=FALSE; return FALSE; } void C3Robot_Make_Time_Stamp_String() { time_t the_local_time; struct tm *ptr; char *dest_ch = time_stamp; the_local_time=time(NULL); ptr=localtime(&the_local_time); char *ch = asctime(ptr); while (*ch != 0) { if (isalnum(*ch)) *dest_ch = *ch; else *dest_ch = '_'; ch++; dest_ch++; } *dest_ch = 0; } static DWORD start_timing_time = 0; static DWORD last_round_time = 0; #ifdef TIME_TEST void C3Robot_Time_Logging() { int turn_num = g_turn->GetRound(); DWORD my_time = GetTickCount(); if ((turn_num % 10) == 0) { FILE *time_file; if ((turn_num == 0) || (!strcmp(timing_file_name, NO_TIMING_FILENAME_YET))) { if (!strcmp(time_stamp, NO_TIMING_FILENAME_YET)) { C3Robot_Make_Time_Stamp_String(); } sprintf(timing_file_name, "Timing_%s.txt", time_stamp); time_file = fopen(timing_file_name, "w"); start_timing_time = my_time; fprintf(time_file, "Turn\tSeconds\tThis_Round\n"); fclose(time_file); } else { time_file = fopen(timing_file_name, "a"); fprintf(time_file, "%d\t%d\t%5.2f\n", turn_num, (int) ((my_time - start_timing_time)/1000.0), (my_time - last_round_time)/1000.0 ); fclose(time_file); } } last_round_time = my_time; } #endif #ifdef _DEBUG #ifdef _MEMORYLOGGING static long int memory_last_turn = 1000000000; void C3Robot_Memory_Logging() { if (!strcmp(memory_file_name, NO_TIMING_FILENAME_YET)) { if (!strcmp(time_stamp, NO_TIMING_FILENAME_YET)) { C3Robot_Make_Time_Stamp_String(); } sprintf(memory_file_name, "memorylog_%s.txt", time_stamp); } #ifdef _DEBUG_MEMORY FILE *f = NULL; long int total_memory, dll_memory, exe_memory; f = fopen(memory_file_name, "at"); if (!f) { f = fopen(memory_file_name, "wt"); fprintf(f, "Round\tEXE\tDLL\n"); } if (f) { dll_memory = DebugMemory_GetTotalFromDLL(); exe_memory = DebugMemory_GetTotalFromEXE(); total_memory = dll_memory + exe_memory; fprintf(f, "%d\t%d\t%d\n", g_turn->GetRound(), exe_memory, dll_memory); fclose(f); } #else FILE *f = NULL; f = fopen(memory_file_name, "at"); if (!f) { f = fopen(memory_file_name, "wt"); Assert(f); if (f) { fprintf(f, "Round\tBytes\n"); } } if (f) { _CrtMemState state; _CrtMemCheckpoint( &state ); fprintf(f, "%d\t%d\n", g_turn->GetRound(), state.lSizes[_NORMAL_BLOCK]); fclose(f); } #endif DEBUG_MEMORY } #endif #endif sint32 RobotInterface::ProcessRobot(const uint32 target_milliseconds) { BOOL time_is_remaining = TRUE; uint32 start_frame_ms = GetTickCount(); uint32 end_frame_by = start_frame_ms + target_milliseconds; char debug_str[80]; #ifdef _DEBUG sint32 finite_loop_count=0; #endif while(time_is_remaining) { time_is_remaining = FALSE; Assert(finite_loop_count++ < 40); PLAYER_INDEX p = g_selected_item->GetCurPlayer(); if ((NULL == g_player[p]) || (g_player[p]->IsDead())) { if(!g_network.IsActive()) { g_turn->EndThisTurnBeginNewTurn(FALSE); } else { if(p == g_selected_item->GetVisiblePlayer()) { g_director->AddEndTurn(); } else { g_turn->EndThisTurnBeginNewTurn(FALSE); } } m_my_turn_is_over = FALSE; return 0; } if (g_player[p] && g_player[p]->m_playerType != PLAYER_TYPE_ROBOT) { if (!g_network.IsActive()) { if (m_the_stop_player != p) { if(!g_turn->IsHotSeat() && !g_turn->IsEmail()) { g_turn->EndThisTurnBeginNewTurn(FALSE); } else { m_the_stop_player = p; g_selected_item->SetPlayerOnScreen(p); g_slicEngine->BlankScreen(TRUE); g_director->NextPlayer(); g_director->AddCopyVision(); g_tiledMap->InvalidateMix(); g_tiledMap->InvalidateMap(); g_tiledMap->Refresh(); g_radarMap->Update(); g_turn->InformMessages(); g_turn->SendNextPlayerMessage(); } } } return 0; } if (!m_my_turn_is_over) { if (m_accumulated_frame_time[p] < 1) { m_accumulated_frame_time[p] = 1; m_my_turn_is_over = TRUE; } if (!m_my_turn_is_over && (GetTickCount() < end_frame_by)) { m_accumulated_frame_time[p] += GetTickCount() - start_frame_ms; } } if (m_my_turn_is_over) { sint32 oldVisPlayer = g_selected_item->GetVisiblePlayer(); if(g_network.IsClient()) { g_director->AddEndTurn(); } else { if (m_the_stop_player != p) { g_turn->EndThisTurnBeginNewTurn(FALSE); } else if(g_network.IsActive() && g_network.IsHost() && g_player[m_the_stop_player]->GetPlayerType() == PLAYER_TYPE_ROBOT) { if(g_selected_item->GetCurPlayer() == g_selected_item->GetVisiblePlayer()) { g_director->AddEndTurn(); } else { g_turn->EndThisTurnBeginNewTurn(FALSE); } } } if (g_selected_item->GetVisiblePlayer() != oldVisPlayer) { g_selected_item->SetPlayerOnScreen((PLAYER_INDEX)-1); g_tiledMap->InvalidateMix(); g_tiledMap->InvalidateMap(); g_tiledMap->Refresh(); g_radarMap->Update(); } if (p == 0) { #ifdef TIME_TEST C3Robot_Time_Logging(); #endif #ifdef _DEBUG #ifdef _MEMORYLOGGING C3Robot_Memory_Logging(); #endif #endif } sint32 time_left = sint32(end_frame_by) - sint32(GetTickCount()); if ((m_the_stop_player != p) && (sint32(m_accumulated_frame_time[p]) < time_left)) { time_is_remaining = TRUE; } m_accumulated_frame_time[p] = 0; } } return 1; } void RobotInterface::DoWholeTurn() { ProcessRobot(10000000); } void RobotInterface::CleanupARobot(sint32 p) { Assert(0 <= p); Assert(p < k_MAX_PLAYERS); } BOOL RobotInterface::RegisterCreatedArmy(PLAYER_INDEX owner, BSetID &id, const CAUSE_NEW_ARMY cause, const uint32 hc_id, sint32 nUnits, sint32 unit_type[k_MAX_ARMY_SIZE], sint32 unit_hp[k_MAX_ARMY_SIZE]) { return FALSE; } BOOL RobotInterface::RegisterDeadArmy(PLAYER_INDEX owner, BSetID &id, const CAUSE_REMOVE_ARMY cause) { return TRUE; } void RobotInterface::RegisterDeathDifferential (double adjustment, PLAYER_INDEX player, MapPoint &position) { } void RobotInterface::Load_AIP(char *aip_file_name, PLAYER_INDEX player) { Assert (player >= 0); Assert (player < k_MAX_PLAYERS); } void RobotInterface::Set_AILog_Verbosity(sint32 log_level, PLAYER_INDEX player) { Assert (player >= 0); Assert (player < k_MAX_PLAYERS); } void RobotInterface::RegisterAddInstallation(PLAYER_INDEX owner, MapPointData &pos, sint32 inst_type) { } void RobotInterface::RegisterRemoveInstallation(PLAYER_INDEX owner, MapPointData &pos, sint32 inst_type) { MapPoint ipos; ipos.Iso2Norm(pos); } BOOL RobotInterface::RegisterDeadUnit(PLAYER_INDEX owner, uint32 army_id, const sint32 unit_type) { return TRUE; } BOOL RobotInterface::RegisterDeadCity(PLAYER_INDEX owner, Unit &killme, BSetID &id, const CAUSE_REMOVE_CITY cause) { return TRUE; } void RobotInterface::RegisterCityDiedAt(MapPoint &ipos) { } BOOL RobotInterface::RegisterCreatedCity(Unit u, PLAYER_INDEX owner, BSetID &id, const CAUSE_NEW_CITY cause, MapPoint &pos) { return TRUE; } void RobotInterface::RegisterClearCargo(sint32 owner, uint32 army_id) { } void RobotInterface::RegisterInsertCargo(sint32 owner, uint32 army_id, const sint32 unit_type, sint32 hp) { } void RobotInterface::RegisterUnloadCargo(sint32 owner, uint32 army_id, const sint32 unit_type, sint32 hp, CAUSE_REMOVE_ARMY cause ) { } BOOL RobotInterface::RegisterArmyWasJoined(PLAYER_INDEX owner, uint32 target, sint32 nUnits, sint32 unit_type[k_MAX_ARMY_SIZE], sint32 unit_hp[k_MAX_ARMY_SIZE]) { return FALSE; } BOOL RobotInterface::RegisterYourArmyWasMoved(const PLAYER_INDEX owner, const uint32 army_id, const MapPoint &pos) { return FALSE; } void RobotInterface::RegisterHisArmyTeleported (PLAYER_INDEX his_owner, uint32 i_moved, MapPointData *new_pos) { } BOOL RobotInterface::RegisterCreateBuilding(PLAYER_INDEX owner, uint32 city_id, sint32 blg_type) { return FALSE; } BOOL RobotInterface::RegisterLostBuilding(PLAYER_INDEX owner, uint32 city_id, sint32 blg_type) { return FALSE; } BOOL RobotInterface::RegisterNewGovernment(PLAYER_INDEX owner, uint32 city_id, sint32 government_type) { Assert(0 <= owner); Assert(owner < k_MAX_PLAYERS); return TRUE; } void RobotInterface::RegisterNewWGF(PLAYER_INDEX owner, sint32 w, sint32 g, sint32 f) { Assert(0 <= owner); Assert(owner < k_MAX_PLAYERS); } BOOL RobotInterface::RegisterNewCapitolBuilding(PLAYER_INDEX owner, uint32 city_id) { return FALSE; } BOOL RobotInterface::RegisterCreateWonder(PLAYER_INDEX owner, uint32 city_id, sint32 wonder_type) { return FALSE; } BOOL RobotInterface::RegisterLearnedScience(PLAYER_INDEX owner, sint32 idx_sci, CAUSE_SCI cause) { Assert(0 <= owner); Assert(owner < k_MAX_PLAYERS); return FALSE; } void RobotInterface::RegisterNewPlayer(PLAYER_INDEX player_id, CAUSE_NEW_PLAYER cause, NEW_PLAYER_IS type, PLAYER_INDEX old_owner) { sint32 i; if (NEW_PLAYER_IS_ROBOT == type) { m_nAIPlayers++; LoadCom(player_id); AddRobotPlayer(player_id); } } void RobotInterface::RegisterDeadPlayer(PLAYER_INDEX player_id) { sint32 i; } BOOL RobotInterface::IsComLoaded(const sint32 p) const { return FALSE; } #include "profileDB.h" extern ProfileDB *g_theProfileDB; extern RobotInterface *g_robot_interface; BOOL IsThisPlayerARobot(sint32 p) { Assert(0 <= p); Assert(p < k_MAX_PLAYERS); if ((p < 0) || (k_MAX_PLAYERS <= p)) return FALSE; Assert(g_player); Assert(g_player[p]); return (g_player[p]->GetPlayerType() != PLAYER_TYPE_HUMAN); } sint32 RobotInterface::GetNumFuzzySections() const { PLAYER_INDEX p = g_selected_item->GetCurPlayer(); return 0; } sint32 RobotInterface::GetNumFuzzyVariables(const sint32 idx_section) const { PLAYER_INDEX p = g_selected_item->GetCurPlayer(); return 0; } void RobotInterface::GetFuzzyGraph(const sint32 idx_section, const sint32 idx_variable, char *&label, double &minx, double &maxx, double &miny, double &maxy, sint32 &num_graphs, sint32 &num_x, double ***height, double &defuzz_val) { PLAYER_INDEX p = g_selected_item->GetCurPlayer(); } void RobotInterface::ReloadFuzzyLogic(const PLAYER_INDEX p, const BOOL run_rules) { Assert(p); } void RobotInterface::ResetFuzzyInput(const sint32 idx_section, const sint32 idx_variable, double new_defuzz_val) { PLAYER_INDEX p = g_selected_item->GetCurPlayer(); } void RobotInterface::DumpStats() { PLAYER_INDEX p = g_selected_item->GetCurPlayer(); } #define INSURFACE(x, y) (x >= 0 && y >= 0 && x < pSurface->Width() && y < pSurface->Height()) extern void WhackScreen(); BOOL RobotInterface::RegisterCityAttack(PLAYER_INDEX owner, uint32 my_city_id, PLAYER_INDEX his_owner, uint32 his_unit_id, UNIT_ORDER_TYPE attack_type) { return FALSE; } BOOL RobotInterface::RegisterDiplomaticRequest(PLAYER_INDEX owner, IC3DiplomaticRequest *request) { return FALSE; } BOOL RobotInterface::RegisterDiplomaticResponse(PLAYER_INDEX owner, IC3DiplomaticRequest *request) { return FALSE; } void RobotInterface::RegisterAttack(PLAYER_INDEX agressor, PLAYER_INDEX defender) { } void RobotInterface::RegisterFightWinner(sint32 attack_owner, sint32 attack_start_num, sint32 defense_owner, sint32 defense_start_num, sint32 winner) { } void RobotInterface::RegisterContactMade(PLAYER_INDEX contacter, PLAYER_INDEX contactee) { } void RobotInterface::RegisterLeaveOurLands(PLAYER_INDEX i_leave, PLAYER_INDEX get_off_me) { } void RobotInterface::RegisterLeaveOurLandsExpired(PLAYER_INDEX i_leave, PLAYER_INDEX get_off_me) { } void RobotInterface::RegisterPlayerInfo(PLAYER_INDEX index, C3PlayerInfo *pi) { } void RobotInterface::SetInputLogComment(MBCHAR *comment) { } BOOL RobotInterface::GetFliLoggingEnabled(sint32 owner) { return FALSE; } void RobotInterface::SetFliLoggingEnabled(sint32 owner, BOOL enabled) { } void RobotInterface::SendTradeBid(PLAYER_INDEX bidder, PLAYER_INDEX biddee, uint32 fromCity_id, sint32 resource, uint32 toCity_id, sint32 price, uint32 bidId) { } void RobotInterface::RegisterTradeOffer(TradeOffer &offer) { } void RobotInterface::RemoveTradeOffer(TradeOffer &offer) { } void RobotInterface::AcceptTradeOffer(TradeOffer &offer, Unit &sourceCity, Unit &destCity, PLAYER_INDEX player) { } void RobotInterface::RegisterNewContinents() { sint32 p; } void RobotInterface::RegisterBrokenCeaseFire(PLAYER_INDEX breaker, PLAYER_INDEX breakee) { } void RobotInterface::RegisterBrokenAlliance(PLAYER_INDEX breaker, PLAYER_INDEX breakee) { } void RobotInterface::ToggleSuperFastDebugMode(PLAYER_INDEX player, BOOL on) { } void RobotInterface::RegisterHeBuiltUnit(PLAYER_INDEX he_did_it, sint32 unit_type) { } void RobotInterface::RegisterHostileAction(UNIT_ORDER_TYPE attack_type, PLAYER_INDEX target_player, uint32 target_army_id, PLAYER_INDEX his_owner, uint32 his_unit_id, MapPointData *target_pos) { if (target_player >= 0 && target_player < k_MAX_PLAYERS && IsLivingRobot(target_player)) { #if 0 char str1[80]; char str2[80]; switch (attack_type) { case UNIT_ORDER_INVESTIGATE_CITY: sprintf (str1, "UNIT_ORDER_INVESTIGATE_CITY"); break; case UNIT_ORDER_NULLIFY_WALLS: sprintf (str1, "UNIT_ORDER_NULLIFY_WALLS"); break; case UNIT_ORDER_STEAL_TECHNOLOGY: sprintf (str1, "UNIT_ORDER_STEAL_TECHNOLOGY"); break; case UNIT_ORDER_ASSASSINATE: sprintf (str1, "UNIT_ORDER_ASSASSINATE"); break; case UNIT_ORDER_INVESTIGATE_READINESS: sprintf (str1, "UNIT_ORDER_INVESTIGATE_READINESS"); break; case UNIT_ORDER_SUE: sprintf (str1, "UNIT_ORDER_SUE"); break; case UNIT_ORDER_FRANCHISE: sprintf (str1, "UNIT_ORDER_FRANCHISE"); break; case UNIT_ORDER_SUE_FRANCHISE: sprintf (str1, "UNIT_ORDER_SUE_FRANCHISE"); break; case UNIT_ORDER_CAUSE_UNHAPPINESS: sprintf (str1, "UNIT_ORDER_CAUSE_UNHAPPINESS"); break; case UNIT_ORDER_PLANT_NUKE: sprintf (str1, "UNIT_ORDER_PLANT_NUKE"); break; case UNIT_ORDER_SLAVE_RAID: sprintf (str1, "UNIT_ORDER_SLAVE_RAID"); break; case UNIT_ORDER_UNDERGROUND_RAILWAY: sprintf (str1, "UNIT_ORDER_UNDERGROUND_RAILWAY"); break; case UNIT_ORDER_INCITE_UPRISING: sprintf (str1, "UNIT_ORDER_INCITE_UPRISING"); break; case UNIT_ORDER_BIO_INFECT: sprintf (str1, "UNIT_ORDER_BIO_INFECT"); break; case UNIT_ORDER_NANO_INFECT: sprintf (str1, "UNIT_ORDER_NANO_INFECT"); break; case UNIT_ORDER_CONVERT: sprintf (str1, "UNIT_ORDER_CONVERT"); break; case UNIT_ORDER_INDULGENCE: sprintf (str1, "UNIT_ORDER_INDULGENCE"); break; case UNIT_ORDER_SOOTHSAY: sprintf (str1, "UNIT_ORDER_SOOTHSAY"); break; case UNIT_ORDER_INJOIN: sprintf (str1, "UNIT_ORDER_INJOIN"); break; case UNIT_ORDER_THROW_PARTY: sprintf (str1, "UNIT_ORDER_THROW_PARTY"); break; case UNIT_ORDER_INCITE_REVOLUTION: sprintf (str1, "UNIT_ORDER_INCITE_REVOLUTION"); break; case UNIT_ORDER_CREATE_PARK: sprintf (str1, "UNIT_ORDER_CREATE_PARK"); break; case UNIT_ORDER_BOMBARD: sprintf (str1, "UNIT_ORDER_BOMBARD"); break; case UNIT_ORDER_EXPEL: sprintf (str1, "UNIT_ORDER_EXPEL"); break; case UNIT_ORDER_ENSLAVE_SETTLER: sprintf (str1, "UNIT_ORDER_ENSLAVE_SETTLER"); break; case UNIT_ORDER_RUSTLE: sprintf (str1, "UNIT_ORDER_RUSTLE"); break; case UNIT_ORDER_FINISH_ATTACK: sprintf (str1, "UNIT_ORDER_FINISH_ATTACK"); break; case UNIT_ORDER_PILLAGE: sprintf (str1, "UNIT_ORDER_PILLAGE"); break; case UNIT_ORDER_INTERCEPT_TRADE: sprintf (str1, "UNIT_ORDER_INTERCEPT_TRADE"); break; default: Assert(0); } sprintf (str2, "%s target %d attacker %d", str1, target_player, his_owner); g_chatBox->AddLine(2, str2); #endif } } void RobotInterface::RegisterPollution(MapPoint &pos) { MapPoint norm_pos; sint32 owner = g_theWorld->GetOwner(pos); } void RobotInterface::RegisterHeNuked(PLAYER_INDEX he_did_it, PLAYER_INDEX his_target) { sint32 player_idx; } void RobotInterface::RegisterPiracy(PLAYER_INDEX he_did_it, PLAYER_INDEX source_owner, uint32 src_id, PLAYER_INDEX dest_owner, uint32 dest_id, sint32 resource) { } void RobotInterface::RegisterRegardIncrease(PLAYER_INDEX who, sint32 amount) { } void RobotInterface::GetFZRegard(sint32 me, sint32 him, sint32 &diplomatic, sint32 &unit, sint32 &bonus) { } void RobotInterface::SetFZRegard(sint32 me, sint32 him, sint32 diplomatic, sint32 unit, sint32 bonus) { } void RobotInterface::GetAllRegard(sint32 player_idx, double i_like[k_MAX_PLAYERS]) { } void RobotInterface::RegisterAgreementViolation(AGREEMENT_TYPE agreement, PLAYER_INDEX violator, PLAYER_INDEX violatee, sint32 rounds) { } void RobotInterface::RegisterAgreementAgainstMe(PLAYER_INDEX first_player, PLAYER_INDEX second_player, PLAYER_INDEX target_player, double agreement_str) { } char *RobotInterface::GetAIPName(sint32 player) { return NULL; } void RobotInterface::RegisterRemoveBuildNode(PLAYER_INDEX owner, uint32 cityid, sint32 build_category, sint32 unit_type) { } void RobotInterface::RegisterSetBuildFront(PLAYER_INDEX owner, uint32 cityid, sint32 build_category, sint32 unit_type) { } BOOL RobotInterface::IWantToAttackRevealedArmy (uint32 revealed_army_id, MapPoint &pos, PLAYER_INDEX reveled_player, uint32 attacking_army_id, PLAYER_INDEX attacking_player) { return FALSE; } BOOL RobotInterface::ValidateArmyID(PLAYER_INDEX owner, uint32 u_id, sint32 unit_num) { return FALSE; } BOOL RobotInterface::IsLivingRobot(PLAYER_INDEX owner) const { if (owner == -1) return FALSE; Assert(0 <= owner); Assert(owner < k_MAX_PLAYERS); if (g_player[owner] == NULL) return FALSE; if (g_player[owner]->m_isDead) return FALSE; return TRUE; } void RobotInterface::ForceRegard(sint32 ofPlayer, sint32 forPlayer, double toRegard) { } void RobotInterface::ForceHate(sint32 player, sint32 forPlayer) { }
/**************************************************************************** * * Copyright (c) 2020-2021 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. * ****************************************************************************/ #pragma once #include <px4_platform_common/px4_config.h> #include <px4_platform_common/atomic.h> #include <px4_platform_common/defines.h> #include <px4_platform_common/module.h> #include <px4_platform_common/module_params.h> #include <px4_platform_common/px4_work_queue/ScheduledWorkItem.hpp> #include <lib/mixer_module/mixer_module.hpp> #include <lib/parameters/param.h> #include <lib/perf/perf_counter.h> #include <uORB/Publication.hpp> #include <uORB/Subscription.hpp> #include <uORB/SubscriptionCallback.hpp> #include <uORB/topics/battery_status.h> #include <uORB/topics/parameter_update.h> #include <uORB/topics/sensor_gps.h> #include "o1heap/o1heap.h" #include <canard.h> #include <canard_dsdl.h> #include "CanardInterface.hpp" #include "Publishers/Publisher.hpp" #include "Publishers/Gnss.hpp" #include "Publishers/uORB/actuator_outputs.hpp" #include "NodeManager.hpp" #include "SubscriptionManager.hpp" #include "Actuators/EscClient.hpp" /// TODO: Add EscServer.hpp for node-side service /** * UAVCAN mixing class. * It is separate from UavcanNode to have 2 WorkItems and therefore allowing independent scheduling * (I.e. UavcanMixingInterface runs upon actuator_control updates, whereas UavcanNode runs at * a fixed rate or upon bus updates). * Both work items are expected to run on the same work queue. */ class UavcanMixingInterface : public OutputModuleInterface { public: UavcanMixingInterface(pthread_mutex_t &node_mutex, UavcanEscController &esc_controller) //, UavcanServoController &servo_controller) : OutputModuleInterface(MODULE_NAME "-actuators", px4::wq_configurations::uavcan), _node_mutex(node_mutex), _esc_controller(esc_controller)/*, _servo_controller(servo_controller)*/ {} bool updateOutputs(bool stop_motors, uint16_t outputs[MAX_ACTUATORS], unsigned num_outputs, unsigned num_control_groups_updated) override; void mixerChanged() override {}; void printInfo() { _mixing_output.printStatus(); } MixingOutput &mixingOutput() { return _mixing_output; } /// For use with PR-16808 once merged // const char *get_param_prefix() override { return "UCAN1_ACT"; } protected: void Run() override; private: friend class UavcanNode; pthread_mutex_t &_node_mutex; UavcanEscController &_esc_controller; // UavcanServoController &_servo_controller; MixingOutput _mixing_output{MAX_ACTUATORS, *this, MixingOutput::SchedulingPolicy::Auto, false, false}; }; class UavcanNode : public ModuleParams, public px4::ScheduledWorkItem { /* * This memory is allocated for the 01Heap allocator used by * libcanard to store incoming/outcoming data * Current size of 8192 bytes is arbitrary, should be optimized further * when more nodes and messages are on the CAN bus */ static constexpr unsigned HeapSize = 8192; /* * Base interval, has to be complemented with events from the CAN driver * and uORB topics sending data, to decrease response time. */ static constexpr unsigned ScheduleIntervalMs = 10; public: UavcanNode(CanardInterface *interface, uint32_t node_id); ~UavcanNode() override; static int start(uint32_t node_id, uint32_t bitrate); void print_info(); static UavcanNode *instance() { return _instance; } /* The bit rate that can be passed back to the bootloader */ int32_t active_bitrate{0}; private: void init(); void Run() override; void fill_node_info(); void transmit(); // Sends a heartbeat at 1s intervals void sendHeartbeat(); void *_uavcan_heap{nullptr}; CanardInterface *_can_interface; CanardInstance _canard_instance; px4::atomic_bool _task_should_exit{false}; ///< flag to indicate to tear down the CAN driver bool _initialized{false}; ///< number of actuators currently available static UavcanNode *_instance; pthread_mutex_t _node_mutex; uORB::Subscription _parameter_update_sub{ORB_ID(parameter_update)}; perf_counter_t _cycle_perf{perf_alloc(PC_ELAPSED, MODULE_NAME": cycle time")}; perf_counter_t _interval_perf{perf_alloc(PC_INTERVAL, MODULE_NAME": cycle interval")}; // uavcan::node::Heartbeat_1_0 uint8_t _uavcan_node_heartbeat_buffer[uavcan_node_Heartbeat_1_0_EXTENT_BYTES_]; hrt_abstime _uavcan_node_heartbeat_last{0}; CanardTransferID _uavcan_node_heartbeat_transfer_id{0}; DEFINE_PARAMETERS( (ParamInt<px4::params::UAVCAN_V1_ENABLE>) _param_uavcan_v1_enable, (ParamInt<px4::params::UAVCAN_V1_ID>) _param_uavcan_v1_id, (ParamInt<px4::params::UAVCAN_V1_BAUD>) _param_uavcan_v1_baud ) UavcanParamManager _param_manager; NodeManager _node_manager {_canard_instance, _param_manager}; SubscriptionManager _sub_manager {_canard_instance, _param_manager}; UavcanGnssPublisher _gps_pub {_canard_instance, _param_manager}; UORB_over_UAVCAN_actuator_outputs_Publisher _actuator_pub {_canard_instance, _param_manager}; // uORB UavcanEscController _esc_controller {_canard_instance, _param_manager}; // Publication objects: Any object used to bridge a uORB message to a UAVCAN message /// TODO: For some service implementations, it makes sense to have them be both Publishers and Subscribers UavcanPublisher *_publishers[3] {&_gps_pub, &_esc_controller, &_actuator_pub}; UavcanMixingInterface _mixing_output {_node_mutex, _esc_controller}; };
// Generated by using Rcpp::compileAttributes() -> do not edit by hand // Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393 #include <Rcpp.h> using namespace Rcpp; // filterICPSRFiles StringVector filterICPSRFiles(StringVector filePaths, std::string state, std::string outputDir); RcppExport SEXP _nibrs_filterICPSRFiles(SEXP filePathsSEXP, SEXP stateSEXP, SEXP outputDirSEXP) { BEGIN_RCPP Rcpp::RObject rcpp_result_gen; Rcpp::RNGScope rcpp_rngScope_gen; Rcpp::traits::input_parameter< StringVector >::type filePaths(filePathsSEXP); Rcpp::traits::input_parameter< std::string >::type state(stateSEXP); Rcpp::traits::input_parameter< std::string >::type outputDir(outputDirSEXP); rcpp_result_gen = Rcpp::wrap(filterICPSRFiles(filePaths, state, outputDir)); return rcpp_result_gen; END_RCPP } static const R_CallMethodDef CallEntries[] = { {"_nibrs_filterICPSRFiles", (DL_FUNC) &_nibrs_filterICPSRFiles, 3}, {NULL, NULL, 0} }; RcppExport void R_init_nibrs(DllInfo *dll) { R_registerRoutines(dll, NULL, CallEntries, NULL, NULL); R_useDynamicSymbols(dll, FALSE); }
/* * Copyright (C) 2018-2021 Intel Corporation * * SPDX-License-Identifier: MIT * */ #include "shared/source/memory_manager/internal_allocation_storage.h" #include "shared/source/memory_manager/memory_manager.h" #include "shared/test/common/helpers/debug_manager_state_restore.h" #include "shared/test/common/helpers/dispatch_flags_helper.h" #include "shared/test/common/helpers/engine_descriptor_helper.h" #include "shared/test/common/helpers/variable_backup.h" #include "shared/test/common/mocks/mock_allocation_properties.h" #include "shared/test/common/mocks/mock_csr.h" #include "shared/test/common/mocks/mock_device.h" #include "shared/test/common/mocks/mock_gmm_page_table_mngr.h" #include "shared/test/common/mocks/mock_svm_manager.h" #include "opencl/source/helpers/hardware_commands_helper.h" #include "opencl/source/mem_obj/buffer.h" #include "opencl/source/platform/platform.h" #include "opencl/test/unit_test/fixtures/ult_command_stream_receiver_fixture.h" #include "opencl/test/unit_test/mocks/mock_command_queue.h" #include "opencl/test/unit_test/mocks/mock_context.h" #include "opencl/test/unit_test/mocks/mock_event.h" #include "opencl/test/unit_test/mocks/mock_kernel.h" #include "opencl/test/unit_test/mocks/mock_os_context.h" #include "opencl/test/unit_test/mocks/mock_platform.h" #include "opencl/test/unit_test/mocks/mock_program.h" #include "opencl/test/unit_test/mocks/mock_submissions_aggregator.h" #include "test.h" using namespace NEO; using CommandStreamReceiverFlushTaskTests = UltCommandStreamReceiverTest; HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenFlushTaskIsCalledThenNothingIsSubmittedToTheHwAndSubmissionIsRecorded) { typedef typename FamilyType::MI_BATCH_BUFFER_END MI_BATCH_BUFFER_END; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto &cmdBufferList = mockedSubmissionsAggregator->peekCommandBuffers(); EXPECT_FALSE(cmdBufferList.peekIsEmpty()); EXPECT_EQ(cmdBufferList.peekHead(), cmdBufferList.peekTail()); auto cmdBuffer = cmdBufferList.peekHead(); //two more because of preemption allocation and sipKernel in Mid Thread preemption mode size_t csrSurfaceCount = (pDevice->getPreemptionMode() == PreemptionMode::MidThread) ? 2 : 0; csrSurfaceCount += mockCsr->globalFenceAllocation ? 1 : 0; csrSurfaceCount += mockCsr->clearColorAllocation ? 1 : 0; //we should have 3 heaps, tag allocation and csr command stream + cq EXPECT_EQ(5u + csrSurfaceCount, cmdBuffer->surfaces.size()); EXPECT_EQ(0, mockCsr->flushCalledCount); //we should be submitting via csr EXPECT_EQ(cmdBuffer->batchBuffer.commandBufferAllocation, mockCsr->commandStream.getGraphicsAllocation()); EXPECT_EQ(cmdBuffer->batchBuffer.startOffset, 0u); EXPECT_FALSE(cmdBuffer->batchBuffer.requiresCoherency); EXPECT_FALSE(cmdBuffer->batchBuffer.low_priority); //find BB END parseCommands<FamilyType>(commandStream, 0); auto itBBend = find<MI_BATCH_BUFFER_END *>(cmdList.begin(), cmdList.end()); void *bbEndAddress = *itBBend; EXPECT_EQ(bbEndAddress, cmdBuffer->batchBufferEndLocation); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeAndTwoRecordedCommandBuffersWhenFlushTaskIsCalledThenBatchBuffersAreCombined) { typedef typename FamilyType::MI_BATCH_BUFFER_END MI_BATCH_BUFFER_END; typedef typename FamilyType::MI_BATCH_BUFFER_START MI_BATCH_BUFFER_START; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto primaryBatch = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); auto secondBatchBuffer = primaryBatch->next; auto bbEndLocation = primaryBatch->batchBufferEndLocation; auto secondBatchBufferAddress = (uint64_t)ptrOffset(secondBatchBuffer->batchBuffer.commandBufferAllocation->getGpuAddress(), secondBatchBuffer->batchBuffer.startOffset); auto lastbbEndPtr = secondBatchBuffer->batchBuffer.endCmdPtr; mockCsr->flushBatchedSubmissions(); auto batchBufferStart = genCmdCast<MI_BATCH_BUFFER_START *>(bbEndLocation); ASSERT_NE(nullptr, batchBufferStart); EXPECT_EQ(secondBatchBufferAddress, batchBufferStart->getBatchBufferStartAddressGraphicsaddress472()); EXPECT_EQ(mockCsr->recordedCommandBuffer->batchBuffer.endCmdPtr, lastbbEndPtr); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeAndThreeRecordedCommandBuffersWhenFlushTaskIsCalledThenBatchBuffersAreCombined) { typedef typename FamilyType::MI_BATCH_BUFFER_END MI_BATCH_BUFFER_END; typedef typename FamilyType::MI_BATCH_BUFFER_START MI_BATCH_BUFFER_START; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto primaryBatch = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); auto lastBatchBuffer = primaryBatch->next->next; auto bbEndLocation = primaryBatch->next->batchBufferEndLocation; auto lastBatchBufferAddress = (uint64_t)ptrOffset(lastBatchBuffer->batchBuffer.commandBufferAllocation->getGpuAddress(), lastBatchBuffer->batchBuffer.startOffset); auto lastbbEndPtr = lastBatchBuffer->batchBuffer.endCmdPtr; mockCsr->flushBatchedSubmissions(); auto batchBufferStart = genCmdCast<MI_BATCH_BUFFER_START *>(bbEndLocation); ASSERT_NE(nullptr, batchBufferStart); EXPECT_EQ(lastBatchBufferAddress, batchBufferStart->getBatchBufferStartAddressGraphicsaddress472()); EXPECT_EQ(1, mockCsr->flushCalledCount); EXPECT_EQ(mockCsr->recordedCommandBuffer->batchBuffer.endCmdPtr, lastbbEndPtr); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeAndThreeRecordedCommandBuffersThatUsesAllResourceWhenFlushTaskIsCalledThenBatchBuffersAreNotCombined) { typedef typename FamilyType::MI_BATCH_BUFFER_END MI_BATCH_BUFFER_END; typedef typename FamilyType::MI_BATCH_BUFFER_START MI_BATCH_BUFFER_START; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); auto memorySize = (size_t)pDevice->getDeviceInfo().globalMemSize; MockGraphicsAllocation largeAllocation(nullptr, memorySize); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); mockCsr->makeResident(largeAllocation); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); mockCsr->makeResident(largeAllocation); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto primaryBatch = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); auto bbEndLocation = primaryBatch->next->batchBufferEndLocation; mockCsr->flushBatchedSubmissions(); auto batchBufferStart = genCmdCast<MI_BATCH_BUFFER_START *>(bbEndLocation); ASSERT_EQ(nullptr, batchBufferStart); auto bbEnd = genCmdCast<MI_BATCH_BUFFER_END *>(bbEndLocation); EXPECT_NE(nullptr, bbEnd); EXPECT_EQ(3, mockCsr->flushCalledCount); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenFlushTaskIsCalledTwiceThenNothingIsSubmittedToTheHwAndTwoSubmissionAreRecorded) { typedef typename FamilyType::MI_BATCH_BUFFER_END MI_BATCH_BUFFER_END; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto initialBase = commandStream.getCpuBase(); auto initialUsed = commandStream.getUsed(); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); //ensure command stream still used EXPECT_EQ(initialBase, commandStream.getCpuBase()); auto baseAfterFirstFlushTask = commandStream.getCpuBase(); auto usedAfterFirstFlushTask = commandStream.getUsed(); dispatchFlags.requiresCoherency = true; dispatchFlags.lowPriority = true; mockCsr->flushTask(commandStream, commandStream.getUsed(), dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto baseAfterSecondFlushTask = commandStream.getCpuBase(); auto usedAfterSecondFlushTask = commandStream.getUsed(); EXPECT_EQ(initialBase, commandStream.getCpuBase()); EXPECT_EQ(baseAfterSecondFlushTask, baseAfterFirstFlushTask); EXPECT_EQ(baseAfterFirstFlushTask, initialBase); EXPECT_GT(usedAfterFirstFlushTask, initialUsed); EXPECT_GT(usedAfterSecondFlushTask, usedAfterFirstFlushTask); auto &cmdBufferList = mockedSubmissionsAggregator->peekCommandBuffers(); EXPECT_FALSE(cmdBufferList.peekIsEmpty()); EXPECT_NE(cmdBufferList.peekHead(), cmdBufferList.peekTail()); EXPECT_NE(nullptr, cmdBufferList.peekTail()); EXPECT_NE(nullptr, cmdBufferList.peekHead()); auto cmdBuffer1 = cmdBufferList.peekHead(); auto cmdBuffer2 = cmdBufferList.peekTail(); EXPECT_GT(cmdBuffer2->batchBufferEndLocation, cmdBuffer1->batchBufferEndLocation); EXPECT_FALSE(cmdBuffer1->batchBuffer.requiresCoherency); EXPECT_TRUE(cmdBuffer2->batchBuffer.requiresCoherency); EXPECT_FALSE(cmdBuffer1->batchBuffer.low_priority); EXPECT_TRUE(cmdBuffer2->batchBuffer.low_priority); EXPECT_GT(cmdBuffer2->batchBuffer.startOffset, cmdBuffer1->batchBuffer.startOffset); } HWCMDTEST_F(IGFX_GEN8_CORE, CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenRecordedBatchBufferIsBeingSubmittedThenFlushIsCalledWithRecordedCommandBuffer) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); configureCSRtoNonDirtyState<FamilyType>(false); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.requiresCoherency = true; mockCsr->lastSentCoherencyRequest = 1; commandStream.getSpace(4); mockCsr->flushTask(commandStream, 4, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(0, mockCsr->flushCalledCount); auto &surfacesForResidency = mockCsr->getResidencyAllocations(); EXPECT_EQ(0u, surfacesForResidency.size()); auto &cmdBufferList = mockedSubmissionsAggregator->peekCommandBuffers(); EXPECT_FALSE(cmdBufferList.peekIsEmpty()); auto cmdBuffer = cmdBufferList.peekHead(); //preemption allocation + sip kernel size_t csrSurfaceCount = (pDevice->getPreemptionMode() == PreemptionMode::MidThread) ? 2 : 0; csrSurfaceCount += mockCsr->globalFenceAllocation ? 1 : 0; EXPECT_EQ(4u + csrSurfaceCount, cmdBuffer->surfaces.size()); //copy those surfaces std::vector<GraphicsAllocation *> residentSurfaces = cmdBuffer->surfaces; for (auto &graphicsAllocation : residentSurfaces) { EXPECT_TRUE(graphicsAllocation->isResident(mockCsr->getOsContext().getContextId())); EXPECT_EQ(1u, graphicsAllocation->getResidencyTaskCount(mockCsr->getOsContext().getContextId())); } mockCsr->flushBatchedSubmissions(); EXPECT_FALSE(mockCsr->recordedCommandBuffer->batchBuffer.low_priority); EXPECT_TRUE(mockCsr->recordedCommandBuffer->batchBuffer.requiresCoherency); EXPECT_EQ(mockCsr->recordedCommandBuffer->batchBuffer.commandBufferAllocation, commandStream.getGraphicsAllocation()); EXPECT_EQ(4u, mockCsr->recordedCommandBuffer->batchBuffer.startOffset); EXPECT_EQ(1, mockCsr->flushCalledCount); EXPECT_TRUE(mockedSubmissionsAggregator->peekCommandBuffers().peekIsEmpty()); EXPECT_EQ(0u, surfacesForResidency.size()); for (auto &graphicsAllocation : residentSurfaces) { EXPECT_FALSE(graphicsAllocation->isResident(mockCsr->getOsContext().getContextId())); } } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrCreatedWithDedicatedDebugFlagWhenItIsCreatedThenItHasProperDispatchMode) { DebugManagerStateRestore stateRestore; DebugManager.flags.CsrDispatchMode.set(static_cast<uint32_t>(DispatchMode::AdaptiveDispatch)); std::unique_ptr<MockCsrHw2<FamilyType>> mockCsr(new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield())); EXPECT_EQ(DispatchMode::AdaptiveDispatch, mockCsr->dispatchMode); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenBlockingCommandIsSendThenItIsFlushedAndNotBatched) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); configureCSRtoNonDirtyState<FamilyType>(false); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.blocking = true; dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(1, mockCsr->flushCalledCount); EXPECT_TRUE(mockedSubmissionsAggregator->peekCmdBufferList().peekIsEmpty()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenBufferToFlushWhenFlushTaskCalledThenUpdateFlushStamp) { auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); commandStream.getSpace(1); EXPECT_EQ(0, mockCsr->flushCalledCount); auto previousFlushStamp = mockCsr->flushStamp->peekStamp(); auto cmplStamp = flushTask(*mockCsr); EXPECT_GT(mockCsr->flushStamp->peekStamp(), previousFlushStamp); EXPECT_EQ(mockCsr->flushStamp->peekStamp(), cmplStamp.flushStamp); EXPECT_EQ(1, mockCsr->flushCalledCount); } HWCMDTEST_F(IGFX_GEN8_CORE, CommandStreamReceiverFlushTaskTests, givenNothingToFlushWhenFlushTaskCalledThenDontFlushStamp) { auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); configureCSRtoNonDirtyState<FamilyType>(false); EXPECT_EQ(0, mockCsr->flushCalledCount); auto previousFlushStamp = mockCsr->flushStamp->peekStamp(); auto cmplStamp = flushTask(*mockCsr); EXPECT_EQ(mockCsr->flushStamp->peekStamp(), previousFlushStamp); EXPECT_EQ(previousFlushStamp, cmplStamp.flushStamp); EXPECT_EQ(0, mockCsr->flushCalledCount); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenFlushTaskIsCalledThenFlushedTaskCountIsNotModifed) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(1u, mockCsr->peekLatestSentTaskCount()); EXPECT_EQ(0u, mockCsr->peekLatestFlushedTaskCount()); mockCsr->flushBatchedSubmissions(); EXPECT_EQ(1u, mockCsr->peekLatestSentTaskCount()); EXPECT_EQ(1u, mockCsr->peekLatestFlushedTaskCount()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenUpdateTaskCountFromWaitWhenFlushBatchedIsCalledThenFlushedTaskCountIsNotModifed) { DebugManagerStateRestore restorer; DebugManager.flags.UpdateTaskCountFromWait.set(1); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(1u, mockCsr->peekLatestSentTaskCount()); EXPECT_EQ(0u, mockCsr->peekLatestFlushedTaskCount()); mockCsr->flushBatchedSubmissions(); EXPECT_EQ(1u, mockCsr->peekLatestSentTaskCount()); EXPECT_EQ(0u, mockCsr->peekLatestFlushedTaskCount()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInDefaultModeWhenFlushTaskIsCalledThenFlushedTaskCountIsModifed) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; auto &csr = commandQueue.getGpgpuCommandStreamReceiver(); csr.flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(1u, csr.peekLatestSentTaskCount()); EXPECT_EQ(1u, csr.peekLatestFlushedTaskCount()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenFlushTaskIsCalledGivenNumberOfTimesThenFlushIsCalled) { DebugManagerStateRestore restorer; DebugManager.flags.PerformImplicitFlushEveryEnqueueCount.set(2); CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; auto &csr = reinterpret_cast<UltCommandStreamReceiver<FamilyType> &>(commandQueue.getGpgpuCommandStreamReceiver()); csr.overrideDispatchPolicy(DispatchMode::BatchedDispatch); csr.useNewResourceImplicitFlush = false; csr.useGpuIdleImplicitFlush = false; dispatchFlags.implicitFlush = false; csr.flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(1u, csr.peekLatestSentTaskCount()); EXPECT_EQ(0u, csr.peekLatestFlushedTaskCount()); dispatchFlags.implicitFlush = false; csr.flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(2u, csr.peekLatestSentTaskCount()); EXPECT_EQ(2u, csr.peekLatestFlushedTaskCount()); dispatchFlags.implicitFlush = false; csr.flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(3u, csr.peekLatestSentTaskCount()); EXPECT_EQ(2u, csr.peekLatestFlushedTaskCount()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenWaitForTaskCountIsCalledWithTaskCountThatWasNotYetFlushedThenBatchedCommandBuffersAreSubmitted) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto &cmdBufferList = mockedSubmissionsAggregator->peekCommandBuffers(); EXPECT_FALSE(cmdBufferList.peekIsEmpty()); EXPECT_EQ(0u, mockCsr->peekLatestFlushedTaskCount()); auto cmdBuffer = cmdBufferList.peekHead(); EXPECT_EQ(1u, cmdBuffer->taskCount); mockCsr->waitForCompletionWithTimeout(false, 1, 1); EXPECT_EQ(1u, mockCsr->peekLatestFlushedTaskCount()); EXPECT_TRUE(cmdBufferList.peekIsEmpty()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenEnqueueIsMadeThenCurrentMemoryUsedIsTracked) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto cmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); uint64_t expectedUsed = 0; for (const auto &resource : cmdBuffer->surfaces) { expectedUsed += resource->getUnderlyingBufferSize(); } EXPECT_EQ(expectedUsed, mockCsr->peekTotalMemoryUsed()); //after flush it goes to 0 mockCsr->flushBatchedSubmissions(); EXPECT_EQ(0u, mockCsr->peekTotalMemoryUsed()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenSusbsequentEnqueueIsMadeThenOnlyNewResourcesAreTrackedForMemoryUsage) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto cmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); uint64_t expectedUsed = 0; for (const auto &resource : cmdBuffer->surfaces) { expectedUsed += resource->getUnderlyingBufferSize(); } auto additionalSize = 1234; MockGraphicsAllocation graphicsAllocation(nullptr, additionalSize); mockCsr->makeResident(graphicsAllocation); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(expectedUsed + additionalSize, mockCsr->peekTotalMemoryUsed()); mockCsr->flushBatchedSubmissions(); } struct MockedMemoryManager : public OsAgnosticMemoryManager { MockedMemoryManager(ExecutionEnvironment &executionEnvironment) : OsAgnosticMemoryManager(executionEnvironment) {} bool isMemoryBudgetExhausted() const override { return budgetExhausted; } bool budgetExhausted = false; }; HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenTotalResourceUsedExhaustsTheBudgetThenDoImplicitFlush) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); ExecutionEnvironment *executionEnvironment = platform()->peekExecutionEnvironment(); auto mockedMemoryManager = new MockedMemoryManager(*executionEnvironment); executionEnvironment->memoryManager.reset(mockedMemoryManager); auto mockCsr = std::make_unique<MockCsrHw2<FamilyType>>(*executionEnvironment, 0, pDevice->getDeviceBitfield()); mockCsr->setupContext(*pDevice->getDefaultEngine().osContext); if (pDevice->getPreemptionMode() == PreemptionMode::MidThread || pDevice->isDebuggerActive()) { mockCsr->createPreemptionAllocation(); } mockCsr->initializeTagAllocation(); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockedMemoryManager->budgetExhausted = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto cmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); uint64_t expectedUsed = 0; for (const auto &resource : cmdBuffer->surfaces) { expectedUsed += resource->getUnderlyingBufferSize(); } EXPECT_EQ(expectedUsed, mockCsr->peekTotalMemoryUsed()); auto budgetSize = (size_t)pDevice->getDeviceInfo().globalMemSize; MockGraphicsAllocation hugeAllocation(nullptr, budgetSize / 4); mockCsr->makeResident(hugeAllocation); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); //expect 2 flushes, since we cannot batch those submissions EXPECT_EQ(2u, mockCsr->peekLatestFlushedTaskCount()); EXPECT_EQ(0u, mockCsr->peekTotalMemoryUsed()); EXPECT_TRUE(mockedSubmissionsAggregator->peekCommandBuffers().peekIsEmpty()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenTwoTasksArePassedWithTheSameLevelThenThereIsNoPipeControlBetweenThemAfterFlush) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = true; auto taskLevelPriorToSubmission = mockCsr->peekTaskLevel(); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); //now emit with the same taskLevel mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); EXPECT_EQ(taskLevelPriorToSubmission, mockCsr->peekTaskLevel()); //validate if we recorded ppc positions auto firstCmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); EXPECT_NE(nullptr, firstCmdBuffer->pipeControlThatMayBeErasedLocation); auto secondCmdBuffer = firstCmdBuffer->next; EXPECT_NE(nullptr, secondCmdBuffer->pipeControlThatMayBeErasedLocation); EXPECT_NE(firstCmdBuffer->pipeControlThatMayBeErasedLocation, secondCmdBuffer->pipeControlThatMayBeErasedLocation); auto ppc = genCmdCast<typename FamilyType::PIPE_CONTROL *>(firstCmdBuffer->pipeControlThatMayBeErasedLocation); EXPECT_NE(nullptr, ppc); auto ppc2 = genCmdCast<typename FamilyType::PIPE_CONTROL *>(secondCmdBuffer->pipeControlThatMayBeErasedLocation); EXPECT_NE(nullptr, ppc2); //flush needs to bump the taskLevel mockCsr->flushBatchedSubmissions(); EXPECT_EQ(taskLevelPriorToSubmission + 1, mockCsr->peekTaskLevel()); //decode commands to confirm no pipe controls between Walkers parseCommands<FamilyType>(commandQueue); auto itorBatchBufferStartFirst = find<typename FamilyType::MI_BATCH_BUFFER_START *>(cmdList.begin(), cmdList.end()); auto itorBatchBufferStartSecond = find<typename FamilyType::MI_BATCH_BUFFER_START *>(++itorBatchBufferStartFirst, cmdList.end()); //make sure they are not the same EXPECT_NE(cmdList.end(), itorBatchBufferStartFirst); EXPECT_NE(cmdList.end(), itorBatchBufferStartSecond); EXPECT_NE(itorBatchBufferStartFirst, itorBatchBufferStartSecond); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(itorBatchBufferStartFirst, itorBatchBufferStartSecond); EXPECT_EQ(itorPipeControl, itorBatchBufferStartSecond); //first pipe control is nooped, second pipe control is untouched auto noop1 = genCmdCast<typename FamilyType::MI_NOOP *>(ppc); auto noop2 = genCmdCast<typename FamilyType::MI_NOOP *>(ppc2); EXPECT_NE(nullptr, noop1); EXPECT_EQ(nullptr, noop2); auto ppcAfterChange = genCmdCast<typename FamilyType::PIPE_CONTROL *>(ppc2); EXPECT_NE(nullptr, ppcAfterChange); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenDcFlushIsNotRequiredThenItIsNotSet) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); parseCommands<FamilyType>(commandStream); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(cmdList.begin(), cmdList.end()); auto pipeControl = genCmdCast<typename FamilyType::PIPE_CONTROL *>(*itorPipeControl); EXPECT_FALSE(pipeControl->getDcFlushEnable()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenCommandAreSubmittedThenDcFlushIsAdded) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); parseCommands<FamilyType>(commandStream); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(cmdList.begin(), cmdList.end()); auto pipeControl = genCmdCast<typename FamilyType::PIPE_CONTROL *>(*itorPipeControl); mockCsr->flushBatchedSubmissions(); EXPECT_EQ(MemorySynchronizationCommands<FamilyType>::isDcFlushAllowed(), pipeControl->getDcFlushEnable()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWithOutOfOrderModeFisabledWhenCommandAreSubmittedThenDcFlushIsAdded) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = false; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); parseCommands<FamilyType>(commandStream); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(cmdList.begin(), cmdList.end()); auto pipeControl = genCmdCast<typename FamilyType::PIPE_CONTROL *>(*itorPipeControl); mockCsr->flushBatchedSubmissions(); EXPECT_EQ(MemorySynchronizationCommands<FamilyType>::isDcFlushAllowed(), pipeControl->getDcFlushEnable()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenUpdateTaskCountFromWaitSetWhenFlushTaskThenThereIsNoPipeControlForUpdateTaskCount) { DebugManagerStateRestore restorer; DebugManager.flags.UpdateTaskCountFromWait.set(1); CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); parseCommands<FamilyType>(commandStream); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(cmdList.begin(), cmdList.end()); EXPECT_EQ(itorPipeControl, cmdList.end()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenUpdateTaskCountFromWaitSetWhenFlushTaskThenPipeControlIsFlushed) { DebugManagerStateRestore restorer; DebugManager.flags.UpdateTaskCountFromWait.set(1); CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); commandQueue.taskCount = 10; auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); mockCsr->taskCount.store(10); mockCsr->latestFlushedTaskCount.store(5); commandQueue.waitForAllEngines(false, nullptr); parseCommands<FamilyType>(mockCsr->getCS(4096u)); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(cmdList.begin(), cmdList.end()); EXPECT_NE(itorPipeControl, cmdList.end()); EXPECT_EQ(mockCsr->flushCalledCount, 1); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenEnabledDirectSubmissionUpdateTaskCountFromWaitSetWhenFlushTaskThenPipeControlAndBBSIsFlushed) { DebugManagerStateRestore restorer; DebugManager.flags.UpdateTaskCountFromWait.set(1); struct MockCsrHwDirectSubmission : public MockCsrHw2<FamilyType> { using MockCsrHw2<FamilyType>::MockCsrHw2; bool isDirectSubmissionEnabled() const override { return true; } }; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); commandQueue.taskCount = 10; auto mockCsr = new MockCsrHwDirectSubmission(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); mockCsr->taskCount.store(10); mockCsr->latestFlushedTaskCount.store(5); commandQueue.waitForAllEngines(false, nullptr); parseCommands<FamilyType>(mockCsr->getCS(4096u)); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(cmdList.begin(), cmdList.end()); auto itorBBS = find<typename FamilyType::MI_BATCH_BUFFER_START *>(cmdList.begin(), cmdList.end()); EXPECT_NE(itorPipeControl, cmdList.end()); EXPECT_NE(itorBBS, cmdList.end()); EXPECT_EQ(mockCsr->flushCalledCount, 1); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenDcFlushIsRequiredThenPipeControlIsNotRegistredForNooping) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.dcFlush = true; dispatchFlags.outOfOrderExecutionAllowed = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto cmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); EXPECT_EQ(nullptr, cmdBuffer->pipeControlThatMayBeErasedLocation); EXPECT_NE(nullptr, cmdBuffer->epiloguePipeControlLocation); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenEpiloguePipeControlThenDcFlushIsEnabled) { using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = false; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto cmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); ASSERT_NE(nullptr, cmdBuffer->epiloguePipeControlLocation); auto pipeControl = genCmdCast<PIPE_CONTROL *>(cmdBuffer->epiloguePipeControlLocation); ASSERT_NE(nullptr, pipeControl); mockCsr->flushBatchedSubmissions(); EXPECT_EQ(MemorySynchronizationCommands<FamilyType>::isDcFlushAllowed(), pipeControl->getDcFlushEnable()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenEpiloguePipeControlWhendDcFlushDisabledByDebugFlagThenDcFlushIsDisabled) { using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; DebugManagerStateRestore debugRestorer; DebugManager.flags.DisableDcFlushInEpilogue.set(true); CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = false; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto cmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); ASSERT_NE(nullptr, cmdBuffer->epiloguePipeControlLocation); auto pipeControl = genCmdCast<PIPE_CONTROL *>(cmdBuffer->epiloguePipeControlLocation); ASSERT_NE(nullptr, pipeControl); mockCsr->flushBatchedSubmissions(); EXPECT_FALSE(pipeControl->getDcFlushEnable()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeAndOoqFlagSetToFalseWhenTwoTasksArePassedWithTheSameLevelThenThereIsPipeControlBetweenThemAfterFlush) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->timestampPacketWriteEnabled = false; mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = false; auto taskLevelPriorToSubmission = mockCsr->peekTaskLevel(); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); //now emit with the same taskLevel mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); EXPECT_EQ(taskLevelPriorToSubmission, mockCsr->peekTaskLevel()); //validate if we recorded ppc positions auto firstCmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); EXPECT_EQ(nullptr, firstCmdBuffer->pipeControlThatMayBeErasedLocation); auto secondCmdBuffer = firstCmdBuffer->next; EXPECT_EQ(nullptr, secondCmdBuffer->pipeControlThatMayBeErasedLocation); mockCsr->flushBatchedSubmissions(); //decode commands to confirm no pipe controls between Walkers parseCommands<FamilyType>(commandQueue); auto itorBatchBufferStartFirst = find<typename FamilyType::MI_BATCH_BUFFER_START *>(cmdList.begin(), cmdList.end()); auto itorBatchBufferStartSecond = find<typename FamilyType::MI_BATCH_BUFFER_START *>(++itorBatchBufferStartFirst, cmdList.end()); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(itorBatchBufferStartFirst, itorBatchBufferStartSecond); EXPECT_NE(itorPipeControl, itorBatchBufferStartSecond); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeAndOoqFlagSetToFalseWhenTimestampPacketWriteIsEnabledThenNoopPipeControl) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = false; auto taskLevelPriorToSubmission = mockCsr->peekTaskLevel(); mockCsr->timestampPacketWriteEnabled = false; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); auto firstCmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); EXPECT_EQ(nullptr, firstCmdBuffer->pipeControlThatMayBeErasedLocation); auto secondCmdBuffer = firstCmdBuffer->next; EXPECT_EQ(nullptr, secondCmdBuffer->pipeControlThatMayBeErasedLocation); mockCsr->flushBatchedSubmissions(); mockCsr->timestampPacketWriteEnabled = true; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); firstCmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); EXPECT_NE(nullptr, firstCmdBuffer->pipeControlThatMayBeErasedLocation); secondCmdBuffer = firstCmdBuffer->next; EXPECT_NE(nullptr, secondCmdBuffer->pipeControlThatMayBeErasedLocation); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenPipeControlForNoopAddressIsNullThenPipeControlIsNotNooped) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = true; auto taskLevelPriorToSubmission = mockCsr->peekTaskLevel(); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); //now emit with the same taskLevel mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); //validate if we recorded ppc positions auto firstCmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); auto ppc1Location = firstCmdBuffer->pipeControlThatMayBeErasedLocation; firstCmdBuffer->pipeControlThatMayBeErasedLocation = nullptr; auto ppc = genCmdCast<typename FamilyType::PIPE_CONTROL *>(ppc1Location); EXPECT_NE(nullptr, ppc); //call flush, both pipe controls must remain untouched mockCsr->flushBatchedSubmissions(); EXPECT_EQ(taskLevelPriorToSubmission + 1, mockCsr->peekTaskLevel()); //decode commands to confirm no pipe controls between Walkers parseCommands<FamilyType>(commandQueue); auto itorBatchBufferStartFirst = find<typename FamilyType::MI_BATCH_BUFFER_START *>(cmdList.begin(), cmdList.end()); auto itorBatchBufferStartSecond = find<typename FamilyType::MI_BATCH_BUFFER_START *>(++itorBatchBufferStartFirst, cmdList.end()); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(itorBatchBufferStartFirst, itorBatchBufferStartSecond); EXPECT_NE(itorPipeControl, itorBatchBufferStartSecond); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrInBatchingModeWhenThreeTasksArePassedWithTheSameLevelThenThereIsNoPipeControlBetweenThemAfterFlush) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.guardCommandBufferWithPipeControl = true; dispatchFlags.outOfOrderExecutionAllowed = true; auto taskLevelPriorToSubmission = mockCsr->peekTaskLevel(); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); //now emit with the same taskLevel mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevelPriorToSubmission, dispatchFlags, *pDevice); EXPECT_EQ(taskLevelPriorToSubmission, mockCsr->peekTaskLevel()); //validate if we recorded ppc positions auto firstCmdBuffer = mockedSubmissionsAggregator->peekCommandBuffers().peekHead(); auto secondCmdBuffer = firstCmdBuffer->next; auto thirdCmdBuffer = firstCmdBuffer->next->next; EXPECT_NE(nullptr, thirdCmdBuffer->pipeControlThatMayBeErasedLocation); EXPECT_NE(firstCmdBuffer->pipeControlThatMayBeErasedLocation, thirdCmdBuffer->pipeControlThatMayBeErasedLocation); auto ppc = genCmdCast<typename FamilyType::PIPE_CONTROL *>(firstCmdBuffer->pipeControlThatMayBeErasedLocation); auto ppc2 = genCmdCast<typename FamilyType::PIPE_CONTROL *>(secondCmdBuffer->pipeControlThatMayBeErasedLocation); auto ppc3 = genCmdCast<typename FamilyType::PIPE_CONTROL *>(thirdCmdBuffer->pipeControlThatMayBeErasedLocation); EXPECT_NE(nullptr, ppc2); EXPECT_NE(nullptr, ppc3); //flush needs to bump the taskLevel mockCsr->flushBatchedSubmissions(); EXPECT_EQ(taskLevelPriorToSubmission + 1, mockCsr->peekTaskLevel()); //decode commands to confirm no pipe controls between Walkers parseCommands<FamilyType>(commandQueue); auto itorBatchBufferStartFirst = find<typename FamilyType::MI_BATCH_BUFFER_START *>(cmdList.begin(), cmdList.end()); auto itorBatchBufferStartSecond = find<typename FamilyType::MI_BATCH_BUFFER_START *>(++itorBatchBufferStartFirst, cmdList.end()); auto itorBatchBufferStartThird = find<typename FamilyType::MI_BATCH_BUFFER_START *>(++itorBatchBufferStartSecond, cmdList.end()); //make sure they are not the same EXPECT_NE(cmdList.end(), itorBatchBufferStartFirst); EXPECT_NE(cmdList.end(), itorBatchBufferStartSecond); EXPECT_NE(cmdList.end(), itorBatchBufferStartThird); EXPECT_NE(itorBatchBufferStartFirst, itorBatchBufferStartSecond); EXPECT_NE(itorBatchBufferStartThird, itorBatchBufferStartSecond); auto itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(itorBatchBufferStartFirst, itorBatchBufferStartSecond); EXPECT_EQ(itorPipeControl, itorBatchBufferStartSecond); itorPipeControl = find<typename FamilyType::PIPE_CONTROL *>(itorBatchBufferStartSecond, itorBatchBufferStartThird); EXPECT_EQ(itorPipeControl, itorBatchBufferStartThird); //first pipe control is nooped, second pipe control is untouched auto noop1 = genCmdCast<typename FamilyType::MI_NOOP *>(ppc); auto noop2 = genCmdCast<typename FamilyType::MI_NOOP *>(ppc2); auto noop3 = genCmdCast<typename FamilyType::MI_NOOP *>(ppc3); EXPECT_NE(nullptr, noop1); EXPECT_NE(nullptr, noop2); EXPECT_EQ(nullptr, noop3); auto ppcAfterChange = genCmdCast<typename FamilyType::PIPE_CONTROL *>(ppc3); EXPECT_NE(nullptr, ppcAfterChange); } typedef UltCommandStreamReceiverTest CommandStreamReceiverCleanupTests; HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCsrWhenTemporaryAndReusableAllocationsArePresentThenCleanupResourcesOnlyCleansThoseAboveLatestFlushTaskLevel) { auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>(); auto memoryManager = pDevice->getMemoryManager(); auto temporaryToClean = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); auto temporaryToHold = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); auto reusableToClean = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); auto reusableToHold = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); commandStreamReceiver.getInternalAllocationStorage()->storeAllocation(std::unique_ptr<GraphicsAllocation>(temporaryToClean), TEMPORARY_ALLOCATION); commandStreamReceiver.getInternalAllocationStorage()->storeAllocation(std::unique_ptr<GraphicsAllocation>(temporaryToHold), TEMPORARY_ALLOCATION); commandStreamReceiver.getInternalAllocationStorage()->storeAllocation(std::unique_ptr<GraphicsAllocation>(reusableToClean), REUSABLE_ALLOCATION); commandStreamReceiver.getInternalAllocationStorage()->storeAllocation(std::unique_ptr<GraphicsAllocation>(reusableToHold), REUSABLE_ALLOCATION); auto osContextId = commandStreamReceiver.getOsContext().getContextId(); temporaryToClean->updateTaskCount(1, osContextId); reusableToClean->updateTaskCount(1, osContextId); temporaryToHold->updateTaskCount(10, osContextId); reusableToHold->updateTaskCount(10, osContextId); commandStreamReceiver.latestFlushedTaskCount = 9; commandStreamReceiver.cleanupResources(); EXPECT_EQ(reusableToHold, commandStreamReceiver.getAllocationsForReuse().peekHead()); EXPECT_EQ(reusableToHold, commandStreamReceiver.getAllocationsForReuse().peekTail()); EXPECT_EQ(temporaryToHold, commandStreamReceiver.getTemporaryAllocations().peekHead()); EXPECT_EQ(temporaryToHold, commandStreamReceiver.getTemporaryAllocations().peekTail()); commandStreamReceiver.latestFlushedTaskCount = 11; commandStreamReceiver.cleanupResources(); EXPECT_TRUE(commandStreamReceiver.getAllocationsForReuse().peekIsEmpty()); EXPECT_TRUE(commandStreamReceiver.getTemporaryAllocations().peekIsEmpty()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenDispatchFlagsWithThrottleSetToLowWhenFlushTaskIsCalledThenThrottleIsSetInBatchBuffer) { typedef typename FamilyType::MI_BATCH_BUFFER_END MI_BATCH_BUFFER_END; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.throttle = QueueThrottle::LOW; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto &cmdBufferList = mockedSubmissionsAggregator->peekCommandBuffers(); auto cmdBuffer = cmdBufferList.peekHead(); EXPECT_EQ(cmdBuffer->batchBuffer.throttle, QueueThrottle::LOW); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenDispatchFlagsWithThrottleSetToMediumWhenFlushTaskIsCalledThenThrottleIsSetInBatchBuffer) { typedef typename FamilyType::MI_BATCH_BUFFER_END MI_BATCH_BUFFER_END; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.throttle = QueueThrottle::MEDIUM; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto &cmdBufferList = mockedSubmissionsAggregator->peekCommandBuffers(); auto cmdBuffer = cmdBufferList.peekHead(); EXPECT_EQ(cmdBuffer->batchBuffer.throttle, QueueThrottle::MEDIUM); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCommandQueueWithThrottleHintWhenFlushingThenPassThrottleHintToCsr) { MockContext context(pClDevice); cl_queue_properties properties[] = {CL_QUEUE_THROTTLE_KHR, CL_QUEUE_THROTTLE_LOW_KHR, 0}; CommandQueueHw<FamilyType> commandQueue(&context, pClDevice, properties, false); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); cl_int retVal = CL_SUCCESS; auto buffer = std::unique_ptr<Buffer>(Buffer::create(&context, 0, 1, nullptr, retVal)); buffer->forceDisallowCPUCopy = true; uint32_t outPtr; commandQueue.enqueueReadBuffer(buffer.get(), CL_TRUE, 0, 1, &outPtr, nullptr, 0, nullptr, nullptr); EXPECT_EQ(QueueThrottle::LOW, mockCsr->passedDispatchFlags.throttle); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenDispatchFlagsWithThrottleSetToHighWhenFlushTaskIsCalledThenThrottleIsSetInBatchBuffer) { typedef typename FamilyType::MI_BATCH_BUFFER_END MI_BATCH_BUFFER_END; CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); dispatchFlags.throttle = QueueThrottle::HIGH; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto &cmdBufferList = mockedSubmissionsAggregator->peekCommandBuffers(); auto cmdBuffer = cmdBufferList.peekHead(); EXPECT_EQ(cmdBuffer->batchBuffer.throttle, QueueThrottle::HIGH); } HWCMDTEST_F(IGFX_GEN8_CORE, CommandStreamReceiverFlushTaskTests, givenEpilogueRequiredFlagWhenTaskIsSubmittedDirectlyThenItPointsBackToCsr) { configureCSRtoNonDirtyState<FamilyType>(false); auto &commandStreamReceiver = this->pDevice->getUltCommandStreamReceiver<FamilyType>(); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); EXPECT_EQ(0u, commandStreamReceiver.getCmdSizeForEpilogue(dispatchFlags)); dispatchFlags.epilogueRequired = true; dispatchFlags.preemptionMode = PreemptionHelper::getDefaultPreemptionMode(pDevice->getHardwareInfo()); EXPECT_EQ(MemoryConstants::cacheLineSize, commandStreamReceiver.getCmdSizeForEpilogue(dispatchFlags)); auto data = commandStream.getSpace(MemoryConstants::cacheLineSize); memset(data, 0, MemoryConstants::cacheLineSize); commandStreamReceiver.storeMakeResidentAllocations = true; commandStreamReceiver.flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto &commandStreamReceiverStream = commandStreamReceiver.getCS(0u); EXPECT_EQ(MemoryConstants::cacheLineSize * 2, commandStream.getUsed()); EXPECT_EQ(MemoryConstants::cacheLineSize, commandStreamReceiverStream.getUsed()); parseCommands<FamilyType>(commandStream, 0); auto itBBend = find<typename FamilyType::MI_BATCH_BUFFER_END *>(cmdList.begin(), cmdList.end()); EXPECT_EQ(itBBend, cmdList.end()); auto itBatchBufferStart = find<typename FamilyType::MI_BATCH_BUFFER_START *>(cmdList.begin(), cmdList.end()); EXPECT_NE(itBatchBufferStart, cmdList.end()); auto batchBufferStart = genCmdCast<typename FamilyType::MI_BATCH_BUFFER_START *>(*itBatchBufferStart); EXPECT_EQ(batchBufferStart->getBatchBufferStartAddressGraphicsaddress472(), commandStreamReceiverStream.getGraphicsAllocation()->getGpuAddress()); parseCommands<FamilyType>(commandStreamReceiverStream, 0); itBBend = find<typename FamilyType::MI_BATCH_BUFFER_END *>(cmdList.begin(), cmdList.end()); void *bbEndAddress = *itBBend; EXPECT_EQ(commandStreamReceiverStream.getCpuBase(), bbEndAddress); EXPECT_TRUE(commandStreamReceiver.isMadeResident(commandStreamReceiverStream.getGraphicsAllocation())); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenDispatchFlagsWithNewSliceCountWhenFlushTaskThenNewSliceCountIsSet) { CommandQueueHw<FamilyType> commandQueue(nullptr, pClDevice, 0, false); auto &commandStream = commandQueue.getCS(4096u); auto mockCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(mockCsr); mockCsr->useNewResourceImplicitFlush = false; mockCsr->useGpuIdleImplicitFlush = false; mockCsr->overrideDispatchPolicy(DispatchMode::BatchedDispatch); auto mockedSubmissionsAggregator = new mockSubmissionsAggregator(); mockCsr->overrideSubmissionAggregator(mockedSubmissionsAggregator); uint64_t newSliceCount = 1; DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.sliceCount = newSliceCount; mockCsr->flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); auto &cmdBufferList = mockedSubmissionsAggregator->peekCommandBuffers(); auto cmdBuffer = cmdBufferList.peekHead(); EXPECT_EQ(cmdBuffer->batchBuffer.sliceCount, newSliceCount); } template <typename GfxFamily> class UltCommandStreamReceiverForDispatchFlags : public UltCommandStreamReceiver<GfxFamily> { using BaseClass = UltCommandStreamReceiver<GfxFamily>; public: UltCommandStreamReceiverForDispatchFlags(ExecutionEnvironment &executionEnvironment, const DeviceBitfield deviceBitfield) : BaseClass(executionEnvironment, 0, deviceBitfield) {} CompletionStamp flushTask(LinearStream &commandStream, size_t commandStreamStart, const IndirectHeap &dsh, const IndirectHeap &ioh, const IndirectHeap &ssh, uint32_t taskLevel, DispatchFlags &dispatchFlags, Device &device) override { savedDispatchFlags = dispatchFlags; return BaseClass::flushTask(commandStream, commandStreamStart, dsh, ioh, ssh, taskLevel, dispatchFlags, device); } DispatchFlags savedDispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); }; HWTEST_F(CommandStreamReceiverFlushTaskTests, GivenBlockedKernelWhenItIsUnblockedThenDispatchFlagsAreSetCorrectly) { MockContext mockContext; auto csr = new UltCommandStreamReceiverForDispatchFlags<FamilyType>(*pDevice->executionEnvironment, pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(csr); uint32_t numGrfRequired = 666u; auto pCmdQ = std::make_unique<MockCommandQueue>(&mockContext, pClDevice, nullptr, false); auto mockProgram = std::make_unique<MockProgram>(&mockContext, false, toClDeviceVector(*pClDevice)); auto pKernel = MockKernel::create(*pDevice, mockProgram.get(), numGrfRequired); auto kernelInfos = MockKernel::toKernelInfoContainer(pKernel->getKernelInfo(), rootDeviceIndex); MultiDeviceKernel multiDeviceKernel(MockMultiDeviceKernel::toKernelVector(pKernel), kernelInfos); auto event = std::make_unique<MockEvent<Event>>(pCmdQ.get(), CL_COMMAND_MARKER, 0, 0); auto cmdStream = new LinearStream(pDevice->getMemoryManager()->allocateGraphicsMemoryWithProperties({pDevice->getRootDeviceIndex(), 4096, GraphicsAllocation::AllocationType::COMMAND_BUFFER, pDevice->getDeviceBitfield()})); IndirectHeap *dsh = nullptr, *ioh = nullptr, *ssh = nullptr; pCmdQ->allocateHeapMemory(IndirectHeap::DYNAMIC_STATE, 4096u, dsh); pCmdQ->allocateHeapMemory(IndirectHeap::INDIRECT_OBJECT, 4096u, ioh); pCmdQ->allocateHeapMemory(IndirectHeap::SURFACE_STATE, 4096u, ssh); auto blockedCommandsData = std::make_unique<KernelOperation>(cmdStream, *pCmdQ->getGpgpuCommandStreamReceiver().getInternalAllocationStorage()); blockedCommandsData->setHeaps(dsh, ioh, ssh); std::vector<Surface *> surfaces; event->setCommand(std::make_unique<CommandComputeKernel>(*pCmdQ, blockedCommandsData, surfaces, false, false, false, nullptr, pDevice->getPreemptionMode(), pKernel, 1)); event->submitCommand(false); EXPECT_EQ(numGrfRequired, csr->savedDispatchFlags.numGrfRequired); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenDcFlushArgumentIsTrueWhenCallingAddPipeControlThenDcFlushIsEnabled) { using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; std::unique_ptr<uint8_t> buffer(new uint8_t[128]); LinearStream commandStream(buffer.get(), 128); PipeControlArgs args(true); MemorySynchronizationCommands<FamilyType>::addPipeControl(commandStream, args); PIPE_CONTROL *pipeControl = genCmdCast<PIPE_CONTROL *>(buffer.get()); ASSERT_NE(nullptr, pipeControl); EXPECT_EQ(MemorySynchronizationCommands<FamilyType>::isDcFlushAllowed(), pipeControl->getDcFlushEnable()); EXPECT_TRUE(pipeControl->getCommandStreamerStallEnable()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenDcFlushArgumentIsFalseWhenCallingAddPipeControlThenDcFlushIsEnabledOnlyOnGen8) { using PIPE_CONTROL = typename FamilyType::PIPE_CONTROL; std::unique_ptr<uint8_t> buffer(new uint8_t[128]); LinearStream commandStream(buffer.get(), 128); PipeControlArgs args; MemorySynchronizationCommands<FamilyType>::addPipeControl(commandStream, args); PIPE_CONTROL *pipeControl = genCmdCast<PIPE_CONTROL *>(buffer.get()); ASSERT_NE(nullptr, pipeControl); const bool expectedDcFlush = ::renderCoreFamily == IGFX_GEN8_CORE; EXPECT_EQ(expectedDcFlush, pipeControl->getDcFlushEnable()); EXPECT_TRUE(pipeControl->getCommandStreamerStallEnable()); } HWTEST_F(CommandStreamReceiverFlushTaskTests, whenPerDssBackBufferIsAllocatedThenItIsClearedInCleanupResources) { auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>(); ASSERT_NE(nullptr, pDevice); commandStreamReceiver.createPerDssBackedBuffer(*pDevice); EXPECT_NE(nullptr, commandStreamReceiver.perDssBackedBuffer); commandStreamReceiver.cleanupResources(); EXPECT_EQ(nullptr, commandStreamReceiver.perDssBackedBuffer); } HWTEST_F(CommandStreamReceiverFlushTaskTests, whenPerDssBackBufferProgrammingEnabledThenAllocationIsCreated) { auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>(); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.usePerDssBackedBuffer = true; commandStreamReceiver.flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(1u, commandStreamReceiver.createPerDssBackedBufferCalled); EXPECT_NE(nullptr, commandStreamReceiver.perDssBackedBuffer); } HWTEST_F(CommandStreamReceiverFlushTaskTests, whenPerDssBackBufferProgrammingEnabledAndPerDssBackedBufferAlreadyPresentThenNewAllocationIsNotCreated) { auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>(); auto memoryManager = pDevice->getMemoryManager(); commandStreamReceiver.perDssBackedBuffer = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); dispatchFlags.usePerDssBackedBuffer = true; commandStreamReceiver.flushTask(commandStream, 0, dsh, ioh, ssh, taskLevel, dispatchFlags, *pDevice); EXPECT_EQ(0u, commandStreamReceiver.createPerDssBackedBufferCalled); } template <typename GfxFamily> class MockCsrWithFailingFlush : public CommandStreamReceiverHw<GfxFamily> { public: using CommandStreamReceiverHw<GfxFamily>::latestSentTaskCount; using CommandStreamReceiverHw<GfxFamily>::submissionAggregator; MockCsrWithFailingFlush(ExecutionEnvironment &executionEnvironment, uint32_t rootDeviceIndex, const DeviceBitfield deviceBitfield) : CommandStreamReceiverHw<GfxFamily>(executionEnvironment, rootDeviceIndex, deviceBitfield) { this->dispatchMode = DispatchMode::BatchedDispatch; this->tagAddress = &tag; } bool flush(BatchBuffer &batchBuffer, ResidencyContainer &allocationsForResidency) override { return false; } uint32_t tag = 0; }; HWTEST_F(CommandStreamReceiverFlushTaskTests, givenWaitForCompletionWithTimeoutIsCalledWhenFlushBatchedSubmissionsReturnsFailureThenItIsPropagated) { MockCsrWithFailingFlush<FamilyType> mockCsr(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); MockOsContext osContext(0, EngineDescriptorHelper::getDefaultDescriptor(8)); mockCsr.setupContext(osContext); mockCsr.latestSentTaskCount = 1; auto cmdBuffer = std::make_unique<CommandBuffer>(*pDevice); mockCsr.submissionAggregator->recordCommandBuffer(cmdBuffer.release()); EXPECT_FALSE(mockCsr.waitForCompletionWithTimeout(false, 0, 1)); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCommandStreamReceiverWhenFlushTaskIsCalledThenInitializePageTableManagerRegister) { auto csr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); auto csr2 = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(csr); MockGmmPageTableMngr *pageTableManager = new MockGmmPageTableMngr(); csr->pageTableManager.reset(pageTableManager); MockGmmPageTableMngr *pageTableManager2 = new MockGmmPageTableMngr(); csr2->pageTableManager.reset(pageTableManager2); EXPECT_CALL(*pageTableManager, initContextAuxTableRegister(csr, ::testing::_)).Times(1); EXPECT_CALL(*pageTableManager, initContextAuxTableRegister(csr2, ::testing::_)).Times(0); auto memoryManager = pDevice->getMemoryManager(); auto graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); IndirectHeap cs(graphicsAllocation); EXPECT_FALSE(csr->pageTableManagerInitialized); EXPECT_FALSE(csr2->pageTableManagerInitialized); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); csr->flushTask(cs, 0u, cs, cs, cs, 0u, dispatchFlags, *pDevice); EXPECT_TRUE(csr->pageTableManagerInitialized); EXPECT_FALSE(csr2->pageTableManagerInitialized); csr->flushTask(cs, 0u, cs, cs, cs, 0u, dispatchFlags, *pDevice); EXPECT_CALL(*pageTableManager2, initContextAuxTableRegister(csr2, ::testing::_)).Times(1); pDevice->resetCommandStreamReceiver(csr2); csr2->flushTask(cs, 0u, cs, cs, cs, 0u, dispatchFlags, *pDevice); EXPECT_TRUE(csr2->pageTableManagerInitialized); memoryManager->freeGraphicsMemory(graphicsAllocation); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenPageTableManagerPointerWhenCallBlitBufferThenPageTableManagerInitializedForProperCsr) { auto bcsCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); auto bcsCsr2 = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(bcsCsr); MockGmmPageTableMngr *pageTableManager = new MockGmmPageTableMngr(); bcsCsr->pageTableManager.reset(pageTableManager); MockGmmPageTableMngr *pageTableManager2 = new MockGmmPageTableMngr(); bcsCsr2->pageTableManager.reset(pageTableManager2); EXPECT_CALL(*pageTableManager, initContextAuxTableRegister(bcsCsr, ::testing::_)).Times(1); EXPECT_CALL(*pageTableManager2, initContextAuxTableRegister(bcsCsr2, ::testing::_)).Times(0); auto memoryManager = pDevice->getMemoryManager(); auto graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); EXPECT_FALSE(bcsCsr->pageTableManagerInitialized); EXPECT_FALSE(bcsCsr2->pageTableManagerInitialized); auto blitProperties = BlitProperties::constructPropertiesForCopy(graphicsAllocation, //dstAllocation graphicsAllocation, //srcAllocation 0, //dstOffset 0, //srcOffset 0, //copySize 0, //srcRowPitch 0, //srcSlicePitch 0, //dstRowPitch 0, //dstSlicePitch bcsCsr->getClearColorAllocation() //clearColorAllocation ); BlitPropertiesContainer container; container.push_back(blitProperties); bcsCsr->blitBuffer(container, true, false, *pDevice); EXPECT_TRUE(bcsCsr->pageTableManagerInitialized); EXPECT_FALSE(bcsCsr2->pageTableManagerInitialized); EXPECT_CALL(*pageTableManager2, initContextAuxTableRegister(bcsCsr2, ::testing::_)).Times(1); pDevice->resetCommandStreamReceiver(bcsCsr2); bcsCsr2->blitBuffer(container, true, false, *pDevice); EXPECT_TRUE(bcsCsr2->pageTableManagerInitialized); memoryManager->freeGraphicsMemory(graphicsAllocation); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenPageTableManagerPointerWhenCallBlitBufferAndPageTableManagerInitializedThenNotInitializeAgain) { auto bcsCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(bcsCsr); MockGmmPageTableMngr *pageTableManager = new MockGmmPageTableMngr(); bcsCsr->pageTableManager.reset(pageTableManager); EXPECT_CALL(*pageTableManager, initContextAuxTableRegister(bcsCsr, ::testing::_)).Times(1); auto memoryManager = pDevice->getMemoryManager(); auto graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); EXPECT_FALSE(bcsCsr->pageTableManagerInitialized); auto blitProperties = BlitProperties::constructPropertiesForCopy(graphicsAllocation, //dstAllocation graphicsAllocation, //srcAllocation 0, //dstOffset 0, //srcOffset 0, //copySize 0, //srcRowPitch 0, //srcSlicePitch 0, //dstRowPitch 0, //dstSlicePitch bcsCsr->getClearColorAllocation() //clearColorAllocation ); BlitPropertiesContainer container; container.push_back(blitProperties); bcsCsr->blitBuffer(container, true, false, *pDevice); EXPECT_TRUE(bcsCsr->pageTableManagerInitialized); EXPECT_CALL(*pageTableManager, initContextAuxTableRegister(bcsCsr, ::testing::_)).Times(0); bcsCsr->blitBuffer(container, true, false, *pDevice); memoryManager->freeGraphicsMemory(graphicsAllocation); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenNullPageTableManagerWhenCallBlitBufferThenPageTableManagerIsNotInitialized) { auto bcsCsr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); auto bcsCsr2 = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(bcsCsr); bcsCsr->pageTableManager.reset(nullptr); bcsCsr2->pageTableManager.reset(nullptr); auto memoryManager = pDevice->getMemoryManager(); auto graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); EXPECT_FALSE(bcsCsr->pageTableManagerInitialized); EXPECT_FALSE(bcsCsr2->pageTableManagerInitialized); auto blitProperties = BlitProperties::constructPropertiesForCopy(graphicsAllocation, //dstAllocation graphicsAllocation, //srcAllocation 0, //dstOffset 0, //srcOffset 0, //copySize 0, //srcRowPitch 0, //srcSlicePitch 0, //dstRowPitch 0, //dstSlicePitch bcsCsr->getClearColorAllocation() //clearColorAllocation ); BlitPropertiesContainer container; container.push_back(blitProperties); bcsCsr->blitBuffer(container, true, false, *pDevice); EXPECT_FALSE(bcsCsr->pageTableManagerInitialized); EXPECT_FALSE(bcsCsr2->pageTableManagerInitialized); pDevice->resetCommandStreamReceiver(bcsCsr2); bcsCsr2->blitBuffer(container, true, false, *pDevice); EXPECT_FALSE(bcsCsr2->pageTableManagerInitialized); bcsCsr2->pageTableManagerInitialized = true; EXPECT_NO_THROW(bcsCsr2->blitBuffer(container, true, false, *pDevice)); memoryManager->freeGraphicsMemory(graphicsAllocation); } HWTEST_F(CommandStreamReceiverFlushTaskTests, givenCommandStreamReceiverWhenInitializingPageTableManagerRegisterFailsThenPageTableManagerIsNotInitialized) { auto csr = new MockCsrHw2<FamilyType>(*pDevice->executionEnvironment, pDevice->getRootDeviceIndex(), pDevice->getDeviceBitfield()); pDevice->resetCommandStreamReceiver(csr); MockGmmPageTableMngr *pageTableManager = new MockGmmPageTableMngr(); csr->pageTableManager.reset(pageTableManager); EXPECT_CALL(*pageTableManager, initContextAuxTableRegister(csr, ::testing::_)).Times(2).WillRepeatedly(::testing::Return(GMM_ERROR)); auto memoryManager = pDevice->getMemoryManager(); auto graphicsAllocation = memoryManager->allocateGraphicsMemoryWithProperties(MockAllocationProperties{pDevice->getRootDeviceIndex(), MemoryConstants::pageSize}); IndirectHeap cs(graphicsAllocation); EXPECT_FALSE(csr->pageTableManagerInitialized); DispatchFlags dispatchFlags = DispatchFlagsHelper::createDefaultDispatchFlags(); csr->flushTask(cs, 0u, cs, cs, cs, 0u, dispatchFlags, *pDevice); EXPECT_FALSE(csr->pageTableManagerInitialized); csr->flushTask(cs, 0u, cs, cs, cs, 0u, dispatchFlags, *pDevice); EXPECT_FALSE(csr->pageTableManagerInitialized); memoryManager->freeGraphicsMemory(graphicsAllocation); } HWTEST_F(CommandStreamReceiverFlushTaskTests, WhenCsrIsMarkedWithNewResourceThenCallBatchedSubmission) { auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>(); commandStreamReceiver.dispatchMode = DispatchMode::BatchedDispatch; commandStreamReceiver.newResources = true; flushTask(commandStreamReceiver); EXPECT_TRUE(commandStreamReceiver.flushBatchedSubmissionsCalled); } HWTEST_F(CommandStreamReceiverFlushTaskTests, whenSubmissionChangesFromSingleSubdeviceThenCallBatchedSubmission) { auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>(); commandStreamReceiver.dispatchMode = DispatchMode::BatchedDispatch; commandStreamReceiver.wasSubmittedToSingleSubdevice = true; flushTask(commandStreamReceiver); EXPECT_TRUE(commandStreamReceiver.flushBatchedSubmissionsCalled); } HWTEST_F(CommandStreamReceiverFlushTaskTests, whenSubmissionChangesToSingleSubdeviceThenCallBatchedSubmission) { auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>(); commandStreamReceiver.dispatchMode = DispatchMode::BatchedDispatch; flushTaskFlags.useSingleSubdevice = true; flushTask(commandStreamReceiver); EXPECT_TRUE(commandStreamReceiver.flushBatchedSubmissionsCalled); } HWTEST_F(CommandStreamReceiverFlushTaskTests, GivenGpuIsIdleWhenCsrIsEnabledToFlushOnGpuIdleThenCallBatchedSubmission) { auto &commandStreamReceiver = pDevice->getUltCommandStreamReceiver<FamilyType>(); commandStreamReceiver.dispatchMode = DispatchMode::BatchedDispatch; commandStreamReceiver.useGpuIdleImplicitFlush = true; commandStreamReceiver.taskCount = 1u; *commandStreamReceiver.getTagAddress() = 1u; flushTask(commandStreamReceiver); EXPECT_TRUE(commandStreamReceiver.flushBatchedSubmissionsCalled); *commandStreamReceiver.getTagAddress() = 2u; } using SingleRootDeviceCommandStreamReceiverTests = CommandStreamReceiverFlushTaskTests; HWTEST_F(SingleRootDeviceCommandStreamReceiverTests, givenMultipleEventInSingleRootDeviceEnvironmentWhenTheyArePassedToEnqueueWithoutSubmissionThenSemaphoreWaitCommandIsNotProgrammed) { using MI_SEMAPHORE_WAIT = typename FamilyType::MI_SEMAPHORE_WAIT; auto deviceFactory = std::make_unique<UltClDeviceFactory>(1, 0); auto device0 = deviceFactory->rootDevices[0]; auto mockCsr0 = new MockCommandStreamReceiver(*device0->executionEnvironment, device0->getRootDeviceIndex(), device0->getDeviceBitfield()); device0->resetCommandStreamReceiver(mockCsr0); cl_device_id devices[] = {device0}; auto context = std::make_unique<MockContext>(ClDeviceVector(devices, 1), false); auto pCmdQ0 = context.get()->getSpecialQueue(0u); Event event1(pCmdQ0, CL_COMMAND_NDRANGE_KERNEL, 5, 15); Event event2(nullptr, CL_COMMAND_NDRANGE_KERNEL, 6, 16); Event event3(pCmdQ0, CL_COMMAND_NDRANGE_KERNEL, 4, 20); UserEvent userEvent1(&pCmdQ0->getContext()); userEvent1.setStatus(CL_COMPLETE); cl_event eventWaitList[] = { &event1, &event2, &event3, &userEvent1, }; cl_uint numEventsInWaitList = sizeof(eventWaitList) / sizeof(eventWaitList[0]); { pCmdQ0->enqueueMarkerWithWaitList( numEventsInWaitList, eventWaitList, nullptr); HardwareParse csHwParser; csHwParser.parseCommands<FamilyType>(pCmdQ0->getCS(0)); auto semaphores = findAll<MI_SEMAPHORE_WAIT *>(csHwParser.cmdList.begin(), csHwParser.cmdList.end()); EXPECT_EQ(0u, semaphores.size()); } }
// Copyright (c) 2020, Clyde McQueen. // All rights reserved. // // Software License Agreement (BSD License 2.0) // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of the copyright holder nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. #ifndef ORCA_SHARED__MW__POINT_HPP_ #define ORCA_SHARED__MW__POINT_HPP_ #include <cmath> #include "geometry_msgs/msg/point.hpp" #include "orca_shared/mw/acceleration.hpp" #include "orca_shared/mw/twist.hpp" namespace mw { class Point { geometry_msgs::msg::Point msg_; public: Point() = default; explicit Point(const geometry_msgs::msg::Point & msg) : msg_{msg} {} Point(const double & x, const double & y, const double & z) { msg_.x = x; msg_.y = y; msg_.z = z; } geometry_msgs::msg::Point msg() const { return msg_; } double x() const { return msg_.x; } double y() const { return msg_.y; } double z() const { return msg_.z; } double & x() { return msg_.x; } double & y() { return msg_.y; } double & z() { return msg_.z; } void x(const double & v) { msg_.x = v; } void y(const double & v) { msg_.y = v; } void z(const double & v) { msg_.z = v; } double distance_xy(const Point & that) const { return std::hypot(x() - that.x(), y() - that.y()); } double distance_xy(const double & _x, const double & _y) const { return std::hypot(x() - _x, y() - _y); } double distance_z(const Point & that) const { return std::abs(z() - that.z()); } Point motion(const rclcpp::Duration & d, const mw::Twist & v0, const mw::Acceleration & a) const { auto dt = d.seconds(); return Point{x() + v0.x() * dt + 0.5 * a.x() * dt * dt, y() + v0.y() * dt + 0.5 * a.y() * dt * dt, z() + v0.z() * dt + 0.5 * a.z() * dt * dt}; } Point operator+(const Point & that) const { return Point{x() + that.x(), y() + that.y(), z() + that.z()}; } Point operator-(const Point & that) const { return Point{x() - that.x(), y() - that.y(), z() - that.z()}; } Point operator-() const { return Point{-x(), -y(), -z()}; } bool operator==(const Point & that) const { return msg_ == that.msg_; } bool operator!=(const Point & that) const { return !(*this == that); } friend std::ostream & operator<<(std::ostream & os, const Point & v); }; } // namespace mw #endif // ORCA_SHARED__MW__POINT_HPP_
/* C++ program for recursive implementation of Bubble sort */ #include <bits/stdc++.h> using namespace std; // A function for bubble sort void Bubble_Sort(int array[], int N) { // First case if (N == 1) return; /* One pass of bubble sort. After this pass, the largest element is bubbled (or moved) to end.*/ for (int i=0; i<N-1; i++) if (array[i] > array[i+1]) swap(array[i], array[i+1]); // Largest element is fixed, // recur for remaining array Bubble_Sort(array, N-1); } /* Function to print an array */ void Print_Array(int array[], int N) { for (int i=0; i < N; i++) printf("%d ", array[i]); printf("\n"); } // Driver function for testing the above. int main() { int array[] = {32,74,43,86,94,12,10,764}; int N = sizeof(array)/sizeof(array[0]); Bubble_Sort(array, N); printf("Sorted array : \n"); Print_Array(array, N); return 0; }
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2020 The Widecoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include <random.h> #include <compat/cpuid.h> #include <crypto/sha256.h> #include <crypto/sha512.h> #include <support/cleanse.h> #ifdef WIN32 #include <compat.h> // for Windows API #include <wincrypt.h> #endif #include <logging.h> // for LogPrintf() #include <randomenv.h> #include <support/allocators/secure.h> #include <sync.h> // for Mutex #include <util/time.h> // for GetTimeMicros() #include <stdlib.h> #include <thread> #ifndef WIN32 #include <fcntl.h> #include <sys/time.h> #endif #ifdef HAVE_SYS_GETRANDOM #include <sys/syscall.h> #include <linux/random.h> #endif #if defined(HAVE_GETENTROPY) || (defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX)) #include <unistd.h> #endif #if defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX) #include <sys/random.h> #endif #ifdef HAVE_SYSCTL_ARND #include <util/strencodings.h> // for ARRAYLEN #include <sys/sysctl.h> #endif [[noreturn]] static void RandFailure() { LogPrintf("Failed to read randomness, aborting\n"); std::abort(); } static inline int64_t GetPerformanceCounter() noexcept { // Read the hardware time stamp counter when available. // See https://en.wikipedia.org/wiki/Time_Stamp_Counter for more information. #if defined(_MSC_VER) && (defined(_M_IX86) || defined(_M_X64)) return __rdtsc(); #elif !defined(_MSC_VER) && defined(__i386__) uint64_t r = 0; __asm__ volatile ("rdtsc" : "=A"(r)); // Constrain the r variable to the eax:edx pair. return r; #elif !defined(_MSC_VER) && (defined(__x86_64__) || defined(__amd64__)) uint64_t r1 = 0, r2 = 0; __asm__ volatile ("rdtsc" : "=a"(r1), "=d"(r2)); // Constrain r1 to rax and r2 to rdx. return (r2 << 32) | r1; #else // Fall back to using C++11 clock (usually microsecond or nanosecond precision) return std::chrono::high_resolution_clock::now().time_since_epoch().count(); #endif } #ifdef HAVE_GETCPUID static bool g_rdrand_supported = false; static bool g_rdseed_supported = false; static constexpr uint32_t CPUID_F1_ECX_RDRAND = 0x40000000; static constexpr uint32_t CPUID_F7_EBX_RDSEED = 0x00040000; #ifdef bit_RDRND static_assert(CPUID_F1_ECX_RDRAND == bit_RDRND, "Unexpected value for bit_RDRND"); #endif #ifdef bit_RDSEED static_assert(CPUID_F7_EBX_RDSEED == bit_RDSEED, "Unexpected value for bit_RDSEED"); #endif static void InitHardwareRand() { uint32_t eax, ebx, ecx, edx; GetCPUID(1, 0, eax, ebx, ecx, edx); if (ecx & CPUID_F1_ECX_RDRAND) { g_rdrand_supported = true; } GetCPUID(7, 0, eax, ebx, ecx, edx); if (ebx & CPUID_F7_EBX_RDSEED) { g_rdseed_supported = true; } } static void ReportHardwareRand() { // This must be done in a separate function, as InitHardwareRand() may be indirectly called // from global constructors, before logging is initialized. if (g_rdseed_supported) { LogPrintf("Using RdSeed as additional entropy source\n"); } if (g_rdrand_supported) { LogPrintf("Using RdRand as an additional entropy source\n"); } } /** Read 64 bits of entropy using rdrand. * * Must only be called when RdRand is supported. */ static uint64_t GetRdRand() noexcept { // RdRand may very rarely fail. Invoke it up to 10 times in a loop to reduce this risk. #ifdef __i386__ uint8_t ok; // Initialize to 0 to silence a compiler warning that r1 or r2 may be used // uninitialized. Even if rdrand fails (!ok) it will set the output to 0, // but there is no way that the compiler could know that. uint32_t r1 = 0, r2 = 0; for (int i = 0; i < 10; ++i) { __asm__ volatile (".byte 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r1), "=q"(ok) :: "cc"); // rdrand %eax if (ok) break; } for (int i = 0; i < 10; ++i) { __asm__ volatile (".byte 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r2), "=q"(ok) :: "cc"); // rdrand %eax if (ok) break; } return (((uint64_t)r2) << 32) | r1; #elif defined(__x86_64__) || defined(__amd64__) uint8_t ok; uint64_t r1 = 0; // See above why we initialize to 0. for (int i = 0; i < 10; ++i) { __asm__ volatile (".byte 0x48, 0x0f, 0xc7, 0xf0; setc %1" : "=a"(r1), "=q"(ok) :: "cc"); // rdrand %rax if (ok) break; } return r1; #else #error "RdRand is only supported on x86 and x86_64" #endif } /** Read 64 bits of entropy using rdseed. * * Must only be called when RdSeed is supported. */ static uint64_t GetRdSeed() noexcept { // RdSeed may fail when the HW RNG is overloaded. Loop indefinitely until enough entropy is gathered, // but pause after every failure. #ifdef __i386__ uint8_t ok; uint32_t r1, r2; do { __asm__ volatile (".byte 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r1), "=q"(ok) :: "cc"); // rdseed %eax if (ok) break; __asm__ volatile ("pause"); } while(true); do { __asm__ volatile (".byte 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r2), "=q"(ok) :: "cc"); // rdseed %eax if (ok) break; __asm__ volatile ("pause"); } while(true); return (((uint64_t)r2) << 32) | r1; #elif defined(__x86_64__) || defined(__amd64__) uint8_t ok; uint64_t r1; do { __asm__ volatile (".byte 0x48, 0x0f, 0xc7, 0xf8; setc %1" : "=a"(r1), "=q"(ok) :: "cc"); // rdseed %rax if (ok) break; __asm__ volatile ("pause"); } while(true); return r1; #else #error "RdSeed is only supported on x86 and x86_64" #endif } #else /* Access to other hardware random number generators could be added here later, * assuming it is sufficiently fast (in the order of a few hundred CPU cycles). * Slower sources should probably be invoked separately, and/or only from * RandAddPeriodic (which is called once a minute). */ static void InitHardwareRand() {} static void ReportHardwareRand() {} #endif /** Add 64 bits of entropy gathered from hardware to hasher. Do nothing if not supported. */ static void SeedHardwareFast(CSHA512& hasher) noexcept { #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) if (g_rdrand_supported) { uint64_t out = GetRdRand(); hasher.Write((const unsigned char*)&out, sizeof(out)); return; } #endif } /** Add 256 bits of entropy gathered from hardware to hasher. Do nothing if not supported. */ static void SeedHardwareSlow(CSHA512& hasher) noexcept { #if defined(__x86_64__) || defined(__amd64__) || defined(__i386__) // When we want 256 bits of entropy, prefer RdSeed over RdRand, as it's // guaranteed to produce independent randomness on every call. if (g_rdseed_supported) { for (int i = 0; i < 4; ++i) { uint64_t out = GetRdSeed(); hasher.Write((const unsigned char*)&out, sizeof(out)); } return; } // When falling back to RdRand, XOR the result of 1024 results. // This guarantees a reseeding occurs between each. if (g_rdrand_supported) { for (int i = 0; i < 4; ++i) { uint64_t out = 0; for (int j = 0; j < 1024; ++j) out ^= GetRdRand(); hasher.Write((const unsigned char*)&out, sizeof(out)); } return; } #endif } /** Use repeated SHA512 to strengthen the randomness in seed32, and feed into hasher. */ static void Strengthen(const unsigned char (&seed)[32], int microseconds, CSHA512& hasher) noexcept { CSHA512 inner_hasher; inner_hasher.Write(seed, sizeof(seed)); // Hash loop unsigned char buffer[64]; int64_t stop = GetTimeMicros() + microseconds; do { for (int i = 0; i < 1000; ++i) { inner_hasher.Finalize(buffer); inner_hasher.Reset(); inner_hasher.Write(buffer, sizeof(buffer)); } // Benchmark operation and feed it into outer hasher. int64_t perf = GetPerformanceCounter(); hasher.Write((const unsigned char*)&perf, sizeof(perf)); } while (GetTimeMicros() < stop); // Produce output from inner state and feed it to outer hasher. inner_hasher.Finalize(buffer); hasher.Write(buffer, sizeof(buffer)); // Try to clean up. inner_hasher.Reset(); memory_cleanse(buffer, sizeof(buffer)); } #ifndef WIN32 /** Fallback: get 32 bytes of system entropy from /dev/urandom. The most * compatible way to get cryptographic randomness on UNIX-ish platforms. */ static void GetDevURandom(unsigned char *ent32) { int f = open("/dev/urandom", O_RDONLY); if (f == -1) { RandFailure(); } int have = 0; do { ssize_t n = read(f, ent32 + have, NUM_OS_RANDOM_BYTES - have); if (n <= 0 || n + have > NUM_OS_RANDOM_BYTES) { close(f); RandFailure(); } have += n; } while (have < NUM_OS_RANDOM_BYTES); close(f); } #endif /** Get 32 bytes of system entropy. */ void GetOSRand(unsigned char *ent32) { #if defined(WIN32) HCRYPTPROV hProvider; int ret = CryptAcquireContextW(&hProvider, nullptr, nullptr, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT); if (!ret) { RandFailure(); } ret = CryptGenRandom(hProvider, NUM_OS_RANDOM_BYTES, ent32); if (!ret) { RandFailure(); } CryptReleaseContext(hProvider, 0); #elif defined(HAVE_SYS_GETRANDOM) /* Linux. From the getrandom(2) man page: * "If the urandom source has been initialized, reads of up to 256 bytes * will always return as many bytes as requested and will not be * interrupted by signals." */ int rv = syscall(SYS_getrandom, ent32, NUM_OS_RANDOM_BYTES, 0); if (rv != NUM_OS_RANDOM_BYTES) { if (rv < 0 && errno == ENOSYS) { /* Fallback for kernel <3.17: the return value will be -1 and errno * ENOSYS if the syscall is not available, in that case fall back * to /dev/urandom. */ GetDevURandom(ent32); } else { RandFailure(); } } #elif defined(HAVE_GETENTROPY) && defined(__OpenBSD__) /* On OpenBSD this can return up to 256 bytes of entropy, will return an * error if more are requested. * The call cannot return less than the requested number of bytes. getentropy is explicitly limited to openbsd here, as a similar (but not the same) function may exist on other platforms via glibc. */ if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) { RandFailure(); } // Silence a compiler warning about unused function. (void)GetDevURandom; #elif defined(HAVE_GETENTROPY_RAND) && defined(MAC_OSX) /* getentropy() is available on macOS 10.12 and later. */ if (getentropy(ent32, NUM_OS_RANDOM_BYTES) != 0) { RandFailure(); } // Silence a compiler warning about unused function. (void)GetDevURandom; #elif defined(HAVE_SYSCTL_ARND) /* FreeBSD, NetBSD and similar. It is possible for the call to return less * bytes than requested, so need to read in a loop. */ static int name[2] = {CTL_KERN, KERN_ARND}; int have = 0; do { size_t len = NUM_OS_RANDOM_BYTES - have; if (sysctl(name, ARRAYLEN(name), ent32 + have, &len, nullptr, 0) != 0) { RandFailure(); } have += len; } while (have < NUM_OS_RANDOM_BYTES); // Silence a compiler warning about unused function. (void)GetDevURandom; #else /* Fall back to /dev/urandom if there is no specific method implemented to * get system entropy for this OS. */ GetDevURandom(ent32); #endif } namespace { class RNGState { Mutex m_mutex; /* The RNG state consists of 256 bits of entropy, taken from the output of * one operation's SHA512 output, and fed as input to the next one. * Carrying 256 bits of entropy should be sufficient to guarantee * unpredictability as long as any entropy source was ever unpredictable * to an attacker. To protect against situations where an attacker might * observe the RNG's state, fresh entropy is always mixed when * GetStrongRandBytes is called. */ unsigned char m_state[32] GUARDED_BY(m_mutex) = {0}; uint64_t m_counter GUARDED_BY(m_mutex) = 0; bool m_strongly_seeded GUARDED_BY(m_mutex) = false; Mutex m_events_mutex; CSHA256 m_events_hasher GUARDED_BY(m_events_mutex); public: RNGState() noexcept { InitHardwareRand(); } ~RNGState() { } void AddEvent(uint32_t event_info) noexcept { LOCK(m_events_mutex); m_events_hasher.Write((const unsigned char *)&event_info, sizeof(event_info)); // Get the low four bytes of the performance counter. This translates to roughly the // subsecond part. uint32_t perfcounter = (GetPerformanceCounter() & 0xffffffff); m_events_hasher.Write((const unsigned char*)&perfcounter, sizeof(perfcounter)); } /** * Feed (the hash of) all events added through AddEvent() to hasher. */ void SeedEvents(CSHA512& hasher) noexcept { // We use only SHA256 for the events hashing to get the ASM speedups we have for SHA256, // since we want it to be fast as network peers may be able to trigger it repeatedly. LOCK(m_events_mutex); unsigned char events_hash[32]; m_events_hasher.Finalize(events_hash); hasher.Write(events_hash, 32); // Re-initialize the hasher with the finalized state to use later. m_events_hasher.Reset(); m_events_hasher.Write(events_hash, 32); } /** Extract up to 32 bytes of entropy from the RNG state, mixing in new entropy from hasher. * * If this function has never been called with strong_seed = true, false is returned. */ bool MixExtract(unsigned char* out, size_t num, CSHA512&& hasher, bool strong_seed) noexcept { assert(num <= 32); unsigned char buf[64]; static_assert(sizeof(buf) == CSHA512::OUTPUT_SIZE, "Buffer needs to have hasher's output size"); bool ret; { LOCK(m_mutex); ret = (m_strongly_seeded |= strong_seed); // Write the current state of the RNG into the hasher hasher.Write(m_state, 32); // Write a new counter number into the state hasher.Write((const unsigned char*)&m_counter, sizeof(m_counter)); ++m_counter; // Finalize the hasher hasher.Finalize(buf); // Store the last 32 bytes of the hash output as new RNG state. memcpy(m_state, buf + 32, 32); } // If desired, copy (up to) the first 32 bytes of the hash output as output. if (num) { assert(out != nullptr); memcpy(out, buf, num); } // Best effort cleanup of internal state hasher.Reset(); memory_cleanse(buf, 64); return ret; } }; RNGState& GetRNGState() noexcept { // This C++11 idiom relies on the guarantee that static variable are initialized // on first call, even when multiple parallel calls are permitted. static std::vector<RNGState, secure_allocator<RNGState>> g_rng(1); return g_rng[0]; } } /* A note on the use of noexcept in the seeding functions below: * * None of the RNG code should ever throw any exception. */ static void SeedTimestamp(CSHA512& hasher) noexcept { int64_t perfcounter = GetPerformanceCounter(); hasher.Write((const unsigned char*)&perfcounter, sizeof(perfcounter)); } static void SeedFast(CSHA512& hasher) noexcept { unsigned char buffer[32]; // Stack pointer to indirectly commit to thread/callstack const unsigned char* ptr = buffer; hasher.Write((const unsigned char*)&ptr, sizeof(ptr)); // Hardware randomness is very fast when available; use it always. SeedHardwareFast(hasher); // High-precision timestamp SeedTimestamp(hasher); } static void SeedSlow(CSHA512& hasher, RNGState& rng) noexcept { unsigned char buffer[32]; // Everything that the 'fast' seeder includes SeedFast(hasher); // OS randomness GetOSRand(buffer); hasher.Write(buffer, sizeof(buffer)); // Add the events hasher into the mix rng.SeedEvents(hasher); // High-precision timestamp. // // Note that we also commit to a timestamp in the Fast seeder, so we indirectly commit to a // benchmark of all the entropy gathering sources in this function). SeedTimestamp(hasher); } /** Extract entropy from rng, strengthen it, and feed it into hasher. */ static void SeedStrengthen(CSHA512& hasher, RNGState& rng, int microseconds) noexcept { // Generate 32 bytes of entropy from the RNG, and a copy of the entropy already in hasher. unsigned char strengthen_seed[32]; rng.MixExtract(strengthen_seed, sizeof(strengthen_seed), CSHA512(hasher), false); // Strengthen the seed, and feed it into hasher. Strengthen(strengthen_seed, microseconds, hasher); } static void SeedPeriodic(CSHA512& hasher, RNGState& rng) noexcept { // Everything that the 'fast' seeder includes SeedFast(hasher); // High-precision timestamp SeedTimestamp(hasher); // Add the events hasher into the mix rng.SeedEvents(hasher); // Dynamic environment data (performance monitoring, ...) auto old_size = hasher.Size(); RandAddDynamicEnv(hasher); LogPrint(BCLog::RAND, "Feeding %i bytes of dynamic environment data into RNG\n", hasher.Size() - old_size); // Strengthen for 10 ms SeedStrengthen(hasher, rng, 10000); } static void SeedStartup(CSHA512& hasher, RNGState& rng) noexcept { // Gather 256 bits of hardware randomness, if available SeedHardwareSlow(hasher); // Everything that the 'slow' seeder includes. SeedSlow(hasher, rng); // Dynamic environment data (performance monitoring, ...) auto old_size = hasher.Size(); RandAddDynamicEnv(hasher); // Static environment data RandAddStaticEnv(hasher); LogPrint(BCLog::RAND, "Feeding %i bytes of environment data into RNG\n", hasher.Size() - old_size); // Strengthen for 100 ms SeedStrengthen(hasher, rng, 100000); } enum class RNGLevel { FAST, //!< Automatically called by GetRandBytes SLOW, //!< Automatically called by GetStrongRandBytes PERIODIC, //!< Called by RandAddPeriodic() }; static void ProcRand(unsigned char* out, int num, RNGLevel level) noexcept { // Make sure the RNG is initialized first (as all Seed* function possibly need hwrand to be available). RNGState& rng = GetRNGState(); assert(num <= 32); CSHA512 hasher; switch (level) { case RNGLevel::FAST: SeedFast(hasher); break; case RNGLevel::SLOW: SeedSlow(hasher, rng); break; case RNGLevel::PERIODIC: SeedPeriodic(hasher, rng); break; } // Combine with and update state if (!rng.MixExtract(out, num, std::move(hasher), false)) { // On the first invocation, also seed with SeedStartup(). CSHA512 startup_hasher; SeedStartup(startup_hasher, rng); rng.MixExtract(out, num, std::move(startup_hasher), true); } } void GetRandBytes(unsigned char* buf, int num) noexcept { ProcRand(buf, num, RNGLevel::FAST); } void GetStrongRandBytes(unsigned char* buf, int num) noexcept { ProcRand(buf, num, RNGLevel::SLOW); } void RandAddPeriodic() noexcept { ProcRand(nullptr, 0, RNGLevel::PERIODIC); } void RandAddEvent(const uint32_t event_info) noexcept { GetRNGState().AddEvent(event_info); } bool g_mock_deterministic_tests{false}; uint64_t GetRand(uint64_t nMax) noexcept { return FastRandomContext(g_mock_deterministic_tests).randrange(nMax); } int GetRandInt(int nMax) noexcept { return GetRand(nMax); } uint256 GetRandHash() noexcept { uint256 hash; GetRandBytes((unsigned char*)&hash, sizeof(hash)); return hash; } void FastRandomContext::RandomSeed() { uint256 seed = GetRandHash(); rng.SetKey(seed.begin(), 32); requires_seed = false; } uint256 FastRandomContext::rand256() noexcept { if (bytebuf_size < 32) { FillByteBuffer(); } uint256 ret; memcpy(ret.begin(), bytebuf + 64 - bytebuf_size, 32); bytebuf_size -= 32; return ret; } std::vector<unsigned char> FastRandomContext::randbytes(size_t len) { if (requires_seed) RandomSeed(); std::vector<unsigned char> ret(len); if (len > 0) { rng.Keystream(&ret[0], len); } return ret; } FastRandomContext::FastRandomContext(const uint256& seed) noexcept : requires_seed(false), bytebuf_size(0), bitbuf_size(0) { rng.SetKey(seed.begin(), 32); } bool Random_SanityCheck() { uint64_t start = GetPerformanceCounter(); /* This does not measure the quality of randomness, but it does test that * GetOSRand() overwrites all 32 bytes of the output given a maximum * number of tries. */ static const ssize_t MAX_TRIES = 1024; uint8_t data[NUM_OS_RANDOM_BYTES]; bool overwritten[NUM_OS_RANDOM_BYTES] = {}; /* Tracks which bytes have been overwritten at least once */ int num_overwritten; int tries = 0; /* Loop until all bytes have been overwritten at least once, or max number tries reached */ do { memset(data, 0, NUM_OS_RANDOM_BYTES); GetOSRand(data); for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { overwritten[x] |= (data[x] != 0); } num_overwritten = 0; for (int x=0; x < NUM_OS_RANDOM_BYTES; ++x) { if (overwritten[x]) { num_overwritten += 1; } } tries += 1; } while (num_overwritten < NUM_OS_RANDOM_BYTES && tries < MAX_TRIES); if (num_overwritten != NUM_OS_RANDOM_BYTES) return false; /* If this failed, bailed out after too many tries */ // Check that GetPerformanceCounter increases at least during a GetOSRand() call + 1ms sleep. std::this_thread::sleep_for(std::chrono::milliseconds(1)); uint64_t stop = GetPerformanceCounter(); if (stop == start) return false; // We called GetPerformanceCounter. Use it as entropy. CSHA512 to_add; to_add.Write((const unsigned char*)&start, sizeof(start)); to_add.Write((const unsigned char*)&stop, sizeof(stop)); GetRNGState().MixExtract(nullptr, 0, std::move(to_add), false); return true; } FastRandomContext::FastRandomContext(bool fDeterministic) noexcept : requires_seed(!fDeterministic), bytebuf_size(0), bitbuf_size(0) { if (!fDeterministic) { return; } uint256 seed; rng.SetKey(seed.begin(), 32); } FastRandomContext& FastRandomContext::operator=(FastRandomContext&& from) noexcept { requires_seed = from.requires_seed; rng = from.rng; std::copy(std::begin(from.bytebuf), std::end(from.bytebuf), std::begin(bytebuf)); bytebuf_size = from.bytebuf_size; bitbuf = from.bitbuf; bitbuf_size = from.bitbuf_size; from.requires_seed = true; from.bytebuf_size = 0; from.bitbuf_size = 0; return *this; } void RandomInit() { // Invoke RNG code to trigger initialization (if not already performed) ProcRand(nullptr, 0, RNGLevel::FAST); ReportHardwareRand(); }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. #include "mbed.h" #include "DevkitDPSClient.h" #include "DiceCore.h" #include "RiotCore.h" #include "EEPROMInterface.h" #include "iothub_client_version.h" #include "iothub.h" #include "hsm_client_key.h" #include "azure_prov_client/prov_security_factory.h" #include "azure_prov_client/prov_device_client.h" #include "azure_prov_client/prov_device_ll_client.h" #include "azure_prov_client/prov_transport_http_client.h" DEFINE_ENUM_STRINGS(PROV_DEVICE_RESULT, PROV_DEVICE_RESULT_VALUE); DEFINE_ENUM_STRINGS(PROV_DEVICE_REG_STATUS, PROV_DEVICE_REG_STATUS_VALUES); typedef struct CLIENT_SAMPLE_INFO_TAG { unsigned int sleep_time; char* iothub_uri; char* access_key_name; char* device_key; char* device_id; int registration_complete; } CLIENT_SAMPLE_INFO; typedef struct IOTHUB_CLIENT_SAMPLE_INFO_TAG { int connected; int stop_running; } IOTHUB_CLIENT_SAMPLE_INFO; static CLIENT_SAMPLE_INFO user_ctx = { 0 }; static DPS_AUTH_TYPE g_auth_type = DPS_AUTH_X509_INDIVIDUAL; bool is_iothub_from_dps = false; static bool g_trace_on = true; extern void* __start_riot_core; extern void* __stop_riot_core; DICE_DATA DiceData = { 0 }; DICE_CMPND_ID DiceCDI = { DICE_CMPND_TAG , { 0x00 } }; DICE_UDS DiceUDS = { DICE_UDS_TAG, 0 }; void DevkitDPSSetLogTrace(bool ison) { g_trace_on = ison; } uint8_t* getUDSBytesFromString(char* udsString) { if (strlen(udsString) != DPS_UDS_MAX_LEN) { return NULL; } uint8_t* udsBytes = (uint8_t*)malloc(DPS_UDS_MAX_LEN / 2 + 1); char element[2]; unsigned long int resLeft; unsigned long int resRight; memset(element, 0, 2); for (int i = 0; i < (DPS_UDS_MAX_LEN/2); i++) { element[0] = udsString[i * 2]; resLeft = strtoul(element, NULL, 16); element[0] = udsString[i * 2 + 1]; resRight = strtoul(element, NULL, 16); udsBytes[i] = (resLeft << 4) + resRight; } return udsBytes; } char* readUDSString() { uint8_t* udsString = (uint8_t*)malloc(DPS_UDS_MAX_LEN + 1); EEPROMInterface eeprom; int ret = eeprom.read(udsString, DPS_UDS_MAX_LEN, 0x00, DPS_UDS_ZONE_IDX); if (ret < 0) { LogError("Unable to get DPS UDS string from EEPROM. Please set the value in configuration mode."); free(udsString); return NULL; } else if (ret == 0) { LogError("The DPS UDS string is empty.\r\nPlease set the value in configuration mode."); free(udsString); return NULL; } else if (ret < DPS_UDS_MAX_LEN) { LogError("The length of DPS UDS string must be 64.\r\nPlease set the value with correct length in configuration mode."); free(udsString); return NULL; } udsString[DPS_UDS_MAX_LEN] = 0; return (char *)udsString; } static void registation_status_callback(PROV_DEVICE_REG_STATUS reg_status, void* user_context) { if (user_context == NULL) { LogError("user_context is NULL"); } else { LogInfo(">>>Provisioning Status: %s", ENUM_TO_STRING(PROV_DEVICE_REG_STATUS, reg_status)); if (reg_status == PROV_DEVICE_REG_STATUS_CONNECTED) { (void)printf("\r\nRegistration status: CONNECTED\r\n"); } else if (reg_status == PROV_DEVICE_REG_STATUS_REGISTERING) { (void)printf("\r\nRegistration status: REGISTERING\r\n"); } else if (reg_status == PROV_DEVICE_REG_STATUS_ASSIGNING) { (void)printf("\r\nRegistration status: ASSIGNING\r\n"); } } } static void register_device_callback(PROV_DEVICE_RESULT register_result, const char* iothub_uri, const char* device_id, void* user_context) { if (user_context == NULL) { LogError("user_context is NULL"); } else { CLIENT_SAMPLE_INFO* user_ctx = (CLIENT_SAMPLE_INFO*)user_context; if (register_result == PROV_DEVICE_RESULT_OK) { (void)printf("Registration Information received from service: %s!\r\n", iothub_uri); user_ctx->iothub_uri = strdup(iothub_uri); user_ctx->device_id = strdup(device_id); user_ctx->registration_complete = 1; } else { LogError("Failure encountered on registration!"); user_ctx->registration_complete = 2; } } } char* DiceInit(char* udsString) { if (udsString == NULL) { udsString = readUDSString(); } uint8_t* udsBytes = getUDSBytesFromString(udsString); if (udsBytes == NULL) { return NULL; } for (int i = 0; i < DICE_UDS_LENGTH; i++) { DiceUDS.bytes[i] = udsBytes[i]; } delete udsBytes; // Up-front sanity check if (DiceUDS.tag != DICE_UDS_TAG) { return NULL; } // Initialize CDI structure memset(&DiceCDI, 0x00, sizeof(DICE_CMPND_ID)); DiceCDI.tag = DICE_CMPND_TAG; // Pointers to protected DICE Data DiceData.UDS = &DiceUDS; DiceData.CDI = &DiceCDI; // Start of RIoT Invariant Code DiceData.riotCore = (uint8_t*)&__start_riot_core; // Calculate size of RIoT Core if((DiceData.riotSize = (uint8_t*)&__stop_riot_core - DiceData.riotCore) == 0){ return NULL; } #if logging LogInfo("The riot_core start address: %p", &__start_riot_core); LogInfo("The riot_core end address: %p", &__stop_riot_core); #endif return udsString; } bool __attribute__((section(".riot_fw"))) DevkitDPSClientStart(const char* global_prov_uri, const char* id_scope, const char* registration_id, char* udsString, const char* proxy_address, int proxy_port) { bool result = true; if (g_auth_type == DPS_AUTH_SYMMETRIC_KEY && udsString != NULL) { hsm_client_set_registration_name_and_key(registration_id, udsString); } if (global_prov_uri == NULL || id_scope == NULL) { LogError("invalid parameter global_prov_uri: %p id_scope: %p", global_prov_uri, id_scope); result = false; } else if (is_iothub_from_dps) { return result; // already've been here } if (g_auth_type == DPS_AUTH_X509_INDIVIDUAL) { // Initialize DICE udsString = DiceInit(udsString); if (udsString == NULL) { LogError("DiceInit failed! Check UDS string provided or set on configuration mode"); return false; } hsm_client_set_registration_name_and_key(registration_id, udsString); // Launch protected DICE code. This will measure RIoT Core, derive the // CDI value. It must execute with interrupts disabled. Therefore, it // must return so we can restore interrupt state. if (DiceCore() != 0) { return false; } // If DiceCore detects an error condition, it will not enable access to // the volatile storage segment. This attempt to transfer control to RIoT // will trigger a system reset. We will not be able to proceed. // TODO: DETECT WHEN A RESET HAS OCCURRED AND TAKE SOME ACTION. if (RiotStart(DiceCDI.bytes, (uint16_t)DICE_DIGEST_LENGTH, registration_id) != 0) { return false; } } if (IoTHub_Init() != 0) { LogError("Failed to initialize the platform."); result = false; } else if ((g_auth_type == DPS_AUTH_X509_INDIVIDUAL || g_auth_type == DPS_AUTH_X509_GROUP) && prov_dev_security_init(SECURE_DEVICE_TYPE_X509) != 0) { LogError("Failed to initialize the platform."); result = false; } else if (g_auth_type == DPS_AUTH_SYMMETRIC_KEY && prov_dev_security_init(SECURE_DEVICE_TYPE_SYMMETRIC_KEY) != 0) { LogError("Failed to initialize the platform."); result = false; } else { memset(&user_ctx, 0, sizeof(CLIENT_SAMPLE_INFO)); // Set ini user_ctx.registration_complete = 0; user_ctx.sleep_time = 10; LogInfo(" DPS Version: %s\r\n", Prov_Device_GetVersionString()); LogInfo("Iothub Version: %s\r\n", IoTHubClient_GetVersionString()); PROV_DEVICE_LL_HANDLE handle = NULL; if ((handle = Prov_Device_LL_Create(global_prov_uri, id_scope, Prov_Device_HTTP_Protocol)) == NULL) { LogError("failed calling Prov_Device_LL_Create"); result = false; } else { if (proxy_address != NULL) { HTTP_PROXY_OPTIONS http_proxy; http_proxy.host_address = proxy_address; http_proxy.port = proxy_port; if (Prov_Device_LL_SetOption(handle, OPTION_HTTP_PROXY, &http_proxy) != PROV_DEVICE_RESULT_OK) { LogError("Failed to set option \"HTTP Proxy\""); result = false; } } (void)Prov_Device_LL_SetOption(handle, "logtrace", &g_trace_on); if (Prov_Device_LL_SetOption(handle, "TrustedCerts", certificates) != PROV_DEVICE_RESULT_OK) { LogError("Failed to set option \"TrustedCerts\""); result = false; } else if (Prov_Device_LL_Register_Device(handle, register_device_callback, &user_ctx, registation_status_callback, &user_ctx) != PROV_DEVICE_RESULT_OK) { LogError("failed calling Prov_Device_LL_Register_Device"); result = false; } else { // Waiting the register to be completed do { Prov_Device_LL_DoWork(handle); ThreadAPI_Sleep(user_ctx.sleep_time); } while (user_ctx.registration_complete == 0); } // Free DPS client Prov_Device_LL_Destroy(handle); } if (user_ctx.registration_complete != 1) { LogError("registration failed!\r\n"); result = false; } else { is_iothub_from_dps = true; } } return result; } void DevkitDPSSetAuthType(DPS_AUTH_TYPE auth_type) { g_auth_type = auth_type; } char* DevkitDPSGetIoTHubURI(void) { return (is_iothub_from_dps ? user_ctx.iothub_uri : NULL); } char* DevkitDPSGetDeviceID(void) { return (is_iothub_from_dps ? user_ctx.device_id : NULL); }
/* * FileReader.cpp * -------------- * Purpose: A basic class for transparent reading of memory-based files. * Notes : (currently none) * Authors: OpenMPT Devs * The OpenMPT source code is released under the BSD license. Read LICENSE for more details. */ #include "stdafx.h" #include "FileReader.h" #if defined(MPT_ENABLE_TEMPFILE) && MPT_OS_WINDOWS #include <windows.h> #include "mptFileIO.h" #endif // MPT_ENABLE_TEMPFILE && MPT_OS_WINDOWS OPENMPT_NAMESPACE_BEGIN #if defined(MPT_ENABLE_TEMPFILE) && MPT_OS_WINDOWS OnDiskFileWrapper::OnDiskFileWrapper(FileReader &file, const mpt::PathString &fileNameExtension) : m_IsTempFile(false) { try { file.Rewind(); if(file.GetFileName().empty()) { const mpt::PathString tempName = mpt::CreateTempFileName(P_("OpenMPT"), fileNameExtension); #if MPT_OS_WINDOWS && MPT_OS_WINDOWS_WINRT #if (_WIN32_WINNT < 0x0602) #define MPT_ONDISKFILEWRAPPER_NO_CREATEFILE #endif #endif #ifdef MPT_ONDISKFILEWRAPPER_NO_CREATEFILE mpt::ofstream f(tempName, std::ios::binary); if(!f) { throw std::runtime_error(""); } while(!file.EndOfFile()) { FileReader::PinnedRawDataView view = file.ReadPinnedRawDataView(mpt::IO::BUFFERSIZE_NORMAL); std::size_t towrite = view.size(); std::size_t written = 0; do { std::size_t chunkSize = mpt::saturate_cast<std::size_t>(towrite); bool chunkOk = false; chunkOk = mpt::IO::WriteRaw(f, mpt::const_byte_span(view.data() + written, chunkSize)); if(!chunkOk) { throw std::runtime_error(""); } towrite -= chunkSize; written += chunkSize; } while(towrite > 0); } f.close(); #else // !MPT_ONDISKFILEWRAPPER_NO_CREATEFILE HANDLE hFile = NULL; #if MPT_OS_WINDOWS_WINRT hFile = CreateFile2(tempName.AsNative().c_str(), GENERIC_WRITE, FILE_SHARE_READ, CREATE_ALWAYS, NULL); #else hFile = CreateFile(tempName.AsNative().c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, NULL); #endif if(hFile == NULL || hFile == INVALID_HANDLE_VALUE) { throw std::runtime_error(""); } while(!file.EndOfFile()) { FileReader::PinnedRawDataView view = file.ReadPinnedRawDataView(mpt::IO::BUFFERSIZE_NORMAL); std::size_t towrite = view.size(); std::size_t written = 0; do { DWORD chunkSize = mpt::saturate_cast<DWORD>(towrite); DWORD chunkDone = 0; WriteFile(hFile, view.data() + written, chunkSize, &chunkDone, NULL); if(chunkDone != chunkSize) { CloseHandle(hFile); hFile = NULL; throw std::runtime_error(""); } towrite -= chunkDone; written += chunkDone; } while(towrite > 0); } CloseHandle(hFile); hFile = NULL; #endif // MPT_ONDISKFILEWRAPPER_NO_CREATEFILE m_Filename = tempName; m_IsTempFile = true; } else { m_Filename = file.GetFileName(); } } catch (const std::runtime_error &) { m_IsTempFile = false; m_Filename = mpt::PathString(); } } OnDiskFileWrapper::~OnDiskFileWrapper() { if(m_IsTempFile) { DeleteFile(m_Filename.AsNative().c_str()); m_IsTempFile = false; } m_Filename = mpt::PathString(); } bool OnDiskFileWrapper::IsValid() const { return !m_Filename.empty(); } mpt::PathString OnDiskFileWrapper::GetFilename() const { return m_Filename; } #else MPT_MSVC_WORKAROUND_LNK4221(FileReader) #endif // MPT_ENABLE_TEMPFILE && MPT_OS_WINDOWS OPENMPT_NAMESPACE_END
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/webshare/win/fake_uri_runtime_class_factory.h" #include <wrl/implements.h> #include "base/strings/string_piece.h" #include "base/win/scoped_hstring.h" #include "testing/gtest/include/gtest/gtest-spi.h" #include "testing/gtest/include/gtest/gtest.h" using ABI::Windows::Foundation::IUriRuntimeClass; using Microsoft::WRL::ComPtr; using Microsoft::WRL::Make; namespace webshare { TEST(FakeUriRuntimeClassFactoryTest, CreateUri) { if (!base::win::ScopedHString::ResolveCoreWinRTStringDelayload()) return; auto factory = Make<FakeUriRuntimeClassFactory>(); auto uri = base::win::ScopedHString::Create("https://www.site.come"); ComPtr<IUriRuntimeClass> uri_runtime_class; ASSERT_HRESULT_SUCCEEDED(factory->CreateUri(uri.get(), &uri_runtime_class)); HSTRING result; ASSERT_HRESULT_SUCCEEDED(uri_runtime_class->get_RawUri(&result)); auto wrapped_result = base::win::ScopedHString(result); ASSERT_EQ(wrapped_result.GetAsUTF8(), "https://www.site.come"); } TEST(FakeUriRuntimeClassFactoryTest, CreateUri_Invalid) { if (!base::win::ScopedHString::ResolveCoreWinRTStringDelayload()) return; auto factory = Make<FakeUriRuntimeClassFactory>(); auto uri = base::win::ScopedHString::Create(""); ComPtr<IUriRuntimeClass> uri_runtime_class; EXPECT_NONFATAL_FAILURE( ASSERT_HRESULT_FAILED(factory->CreateUri(uri.get(), &uri_runtime_class)), "CreateUri"); uri = base::win::ScopedHString::Create(" "); EXPECT_NONFATAL_FAILURE( ASSERT_HRESULT_FAILED(factory->CreateUri(uri.get(), &uri_runtime_class)), "CreateUri"); uri = base::win::ScopedHString::Create("abc"); EXPECT_NONFATAL_FAILURE( ASSERT_HRESULT_FAILED(factory->CreateUri(uri.get(), &uri_runtime_class)), "CreateUri"); uri = base::win::ScopedHString::Create("http://?k=v"); EXPECT_NONFATAL_FAILURE( ASSERT_HRESULT_FAILED(factory->CreateUri(uri.get(), &uri_runtime_class)), "CreateUri"); } } // namespace webshare
// 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 "init.h" #include "main.h" #include "core.h" #include "chainparams.h" #include "txdb.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "net.h" #include "util.h" #include "ui_interface.h" #include "checkpoints.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/algorithm/string/predicate.hpp> #include <openssl/crypto.h> #ifndef WIN32 #include <signal.h> #endif using namespace std; using namespace boost; std::string strWalletFile; CWallet* pwalletMain; CClientUIInterface uiInterface; #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files, don't count towards to fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif // Used to pass flags to the Bind() function enum BindFlags { BF_NONE = 0, BF_EXPLICIT = (1U << 0), BF_REPORT_ERROR = (1U << 1) }; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets fRequestShutdown, which triggers // the DetectShutdownThread(), which interrupts the main thread group. // DetectShutdownThread() then exits, which causes AppInit() to // continue (it .joins the shutdown thread). // Shutdown() is then // called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Note that if running -daemon the parent process returns from AppInit2 // before adding any threads to the threadGroup, so .join_all() returns // immediately and the parent exits from main(). // // Shutdown for Qt is very similar, only it uses a QTimer to detect // fRequestShutdown getting set, and then does the normal Qt // shutdown thing. // volatile bool fRequestShutdown = false; void StartShutdown() { fRequestShutdown = true; } bool ShutdownRequested() { return fRequestShutdown; } static CCoinsViewDB *pcoinsdbview; void Shutdown() { static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; RenameThread("bitcoin-shutoff"); nTransactionsUpdated++; StopRPCThreads(); ShutdownRPCMining(); bitdb.Flush(false); GenerateBitcoins(false, NULL); StopNode(); { LOCK(cs_main); if (pwalletMain) pwalletMain->SetBestChain(CBlockLocator(pindexBest)); if (pblocktree) pblocktree->Flush(); if (pcoinsTip) pcoinsTip->Flush(); delete pcoinsTip; pcoinsTip = NULL; delete pcoinsdbview; pcoinsdbview = NULL; delete pblocktree; pblocktree = NULL; } bitdb.Flush(true); boost::filesystem::remove(GetPidFile()); UnregisterAllWallets(); delete pwalletMain; } // // Signal handlers are very limited in what they are allowed to do, so: // void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } bool static InitError(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); return false; } bool static InitWarning(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING); return true; } bool static Bind(const CService &addr, unsigned int flags) { if (!(flags & BF_EXPLICIT) && IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError)) { if (flags & BF_REPORT_ERROR) return InitError(strError); return false; } return true; } // Core-specific options shared between UI and daemon std::string HelpMessage() { string strUsage = _("Options:") + "\n"; strUsage += " -? " + _("This help message") + "\n"; strUsage += " -conf=<file> " + _("Specify configuration file (default: num2coin.conf)") + "\n"; strUsage += " -pid=<file> " + _("Specify pid file (default: num2coind.pid)") + "\n"; strUsage += " -gen " + _("Generate coins (default: 0)") + "\n"; strUsage += " -datadir=<dir> " + _("Specify data directory") + "\n"; strUsage += " -wallet=<file> " + _("Specify wallet file (within data directory)") + "\n"; strUsage += " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n"; strUsage += " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n"; strUsage += " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n"; strUsage += " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n"; strUsage += " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n"; strUsage += " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n"; strUsage += " -port=<port> " + _("Listen for connections on <port> (default: 8333 or testnet: 18333)") + "\n"; strUsage += " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n"; strUsage += " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n"; strUsage += " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n"; strUsage += " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n"; strUsage += " -externalip=<ip> " + _("Specify your own public address") + "\n"; strUsage += " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n"; strUsage += " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n"; strUsage += " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n"; strUsage += " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n"; strUsage += " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n"; strUsage += " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n"; strUsage += " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n"; strUsage += " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n"; strUsage += " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n"; strUsage += " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n"; #ifdef USE_UPNP #if USE_UPNP strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n"; #else strUsage += " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n"; #endif #endif strUsage += " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n"; if (fHaveGUI) strUsage += " -server " + _("Accept command line and JSON-RPC commands") + "\n"; #if !defined(WIN32) if (fHaveGUI) strUsage += " -daemon " + _("Run in the background as a daemon and accept commands") + "\n"; #endif strUsage += " -testnet " + _("Use the test network") + "\n"; strUsage += " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n"; strUsage += " -debugnet " + _("Output extra network debugging information") + "\n"; strUsage += " -logtimestamps " + _("Prepend debug output with timestamp") + "\n"; strUsage += " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n"; strUsage += " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n"; strUsage += " -regtest " + _("Enter regression test mode, which uses a special chain in which blocks can be " "solved instantly. This is intended for regression testing tools and app development.") + "\n"; #ifdef WIN32 strUsage += " -printtodebugger " + _("Send trace/debug info to debugger") + "\n"; #endif strUsage += " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n"; strUsage += " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n"; strUsage += " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 8332 or testnet: 18332)") + "\n"; strUsage += " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n"; if (!fHaveGUI) strUsage += " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n"; strUsage += " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n"; strUsage += " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n"; strUsage += " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n"; strUsage += " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n"; strUsage += " -upgradewallet " + _("Upgrade wallet to latest format") + "\n"; strUsage += " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n"; strUsage += " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n"; strUsage += " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n"; strUsage += " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n"; strUsage += " -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n"; strUsage += " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n"; strUsage += " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n"; strUsage += " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n"; strUsage += " -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n"; strUsage += "\n" + _("Block creation options:") + "\n"; strUsage += " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n"; strUsage += " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n"; strUsage += " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n"; strUsage += "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n"; strUsage += " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n"; strUsage += " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n"; strUsage += " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n"; strUsage += " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n"; return strUsage; } struct CImportingNow { CImportingNow() { assert(fImporting == false); fImporting = true; } ~CImportingNow() { assert(fImporting == true); fImporting = false; } }; void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) { RenameThread("bitcoin-loadblk"); // -reindex if (fReindex) { CImportingNow imp; int nFile = 0; while (true) { CDiskBlockPos pos(nFile, 0); FILE *file = OpenBlockFile(pos, true); if (!file) break; printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); LoadExternalBlockFile(file, &pos); nFile++; } pblocktree->WriteReindexing(false); fReindex = false; printf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(); } // hardcoded $DATADIR/bootstrap.dat filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; if (filesystem::exists(pathBootstrap)) { FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); if (file) { CImportingNow imp; filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; printf("Importing bootstrap.dat...\n"); LoadExternalBlockFile(file); RenameOver(pathBootstrap, pathBootstrapOld); } } // -loadblock= BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) { FILE *file = fopen(path.string().c_str(), "rb"); if (file) { CImportingNow imp; printf("Importing %s...\n", path.string().c_str()); LoadExternalBlockFile(file); } } } /** Initialize bitcoin. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) { return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret)); } #endif #ifndef WIN32 umask(077); // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); #endif // ********************************************************* Step 2: parameter interactions Checkpoints::fEnabled = GetBoolArg("-checkpoints", true); if (!SelectParamsFromCommandLine()) { return InitError("Invalid combination of -testnet and -regtest."); } if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified SoftSetBoolArg("-listen", true); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default SoftSetBoolArg("-dnsseed", false); SoftSetBoolArg("-listen", false); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a proxy server is specified SoftSetBoolArg("-listen", false); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) SoftSetBoolArg("-upnp", false); SoftSetBoolArg("-discover", false); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others SoftSetBoolArg("-discover", false); } if (GetBoolArg("-salvagewallet", false)) { // Rewrite just private keys: rescan to find transactions SoftSetBoolArg("-rescan", true); } // Make sure enough file descriptors are available int nBind = std::max((int)mapArgs.count("-bind"), 1); nMaxConnections = GetArg("-maxconnections", 125); nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0); int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS); if (nFD < MIN_CORE_FILEDESCRIPTORS) return InitError(_("Not enough file descriptors available.")); if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS; // ********************************************************* Step 3: parameter-to-internal-flags fDebug = GetBoolArg("-debug", false); fBenchmark = GetBoolArg("-benchmark", false); // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency nScriptCheckThreads = GetArg("-par", 0); if (nScriptCheckThreads <= 0) nScriptCheckThreads += boost::thread::hardware_concurrency(); if (nScriptCheckThreads <= 1) nScriptCheckThreads = 0; else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; // -debug implies fDebug* if (fDebug) fDebugNet = true; else fDebugNet = GetBoolArg("-debugnet", false); if (fDaemon) fServer = true; else fServer = GetBoolArg("-server", false); /* force fServer when running without GUI */ if (!fHaveGUI) fServer = true; fPrintToConsole = GetBoolArg("-printtoconsole", false); fPrintToDebugger = GetBoolArg("-printtodebugger", false); fLogTimestamps = GetBoolArg("-logtimestamps", false); if (mapArgs.count("-timeout")) { int nNewTimeout = GetArg("-timeout", 5000); if (nNewTimeout > 0 && nNewTimeout < 600000) nConnectTimeout = nNewTimeout; } // Continue to put "/P2SH/" in the coinbase to monitor // BIP16 support. // This can be removed eventually... const char* pszP2SH = "/P2SH/"; COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH)); // Fee-per-kilobyte amount considered the same as "free" // If you are mining, be careful setting this: // if you set it to zero then // a transaction spammer can cheaply fill blocks using // 1-satoshi-fee transactions. It should be set above the real // cost to you of processing a transaction. if (mapArgs.count("-mintxfee")) { int64 n = 0; if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0) CTransaction::nMinTxFee = n; else return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str())); } if (mapArgs.count("-minrelaytxfee")) { int64 n = 0; if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0) CTransaction::nMinRelayTxFee = n; else return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str())); } if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str())); if (nTransactionFee > 0.25 * COIN) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); } strWalletFile = GetArg("-wallet", "wallet.dat"); // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log std::string strDataDir = GetDataDir().string(); // Wallet file must be a plain filename without a directory if (strWalletFile != boost::filesystem::basename(strWalletFile) + boost::filesystem::extension(strWalletFile)) return InitError(strprintf(_("Wallet %s resides outside data directory %s\n"), strWalletFile.c_str(), strDataDir.c_str())); // Make sure only a single Bitcoin process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Num2coin is probably already running."), strDataDir.c_str())); if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("Num2coin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str()); printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); if (!fLogTimestamps) printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str()); printf("Default data directory %s\n", GetDefaultDataDir().string().c_str()); printf("Using data directory %s\n", strDataDir.c_str()); printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); std::ostringstream strErrors; if (fDaemon) fprintf(stdout, "Num2coin server starting\n"); if (nScriptCheckThreads) { printf("Using %u threads for script verification\n", nScriptCheckThreads); for (int i=0; i<nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); } int64 nStart; // ********************************************************* Step 5: verify wallet database integrity uiInterface.InitMessage(_("Verifying wallet...")); if (!bitdb.Open(GetDataDir())) { // try moving the database env out of the way boost::filesystem::path pathDatabase = GetDataDir() / "database"; boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime()); try { boost::filesystem::rename(pathDatabase, pathDatabaseBak); printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str()); } catch(boost::filesystem::filesystem_error &error) { // failure is ok (well, not really, but it's not worse than what we started with) } // try again if (!bitdb.Open(GetDataDir())) { // if it still fails, it probably means we can't even create the database env string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str()); return InitError(msg); } } if (GetBoolArg("-salvagewallet", false)) { // Recover readable keypairs: if (!CWalletDB::Recover(bitdb, strWalletFile, true)) return false; } if (filesystem::exists(GetDataDir() / strWalletFile)) { CDBEnv::VerifyResult r = bitdb.Verify(strWalletFile, CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { string msg = strprintf(_("Warning: wallet.dat corrupt, data salvaged!" " Original wallet.dat saved as wallet.{timestamp}.bak in %s; if" " your balance or transactions are incorrect you should" " restore from a backup."), strDataDir.c_str()); InitWarning(msg); } if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); } // ********************************************************* Step 6: network initialization RegisterNodeSignals(GetNodeSignals()); int nSocksVersion = GetArg("-socks", 5); if (nSocksVersion != 4 && nSocksVersion != 5) return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion)); if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str())); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } #if defined(USE_IPV6) #if ! USE_IPV6 else SetLimited(NET_IPV6); #endif #endif CService addrProxy; bool fProxy = false; if (mapArgs.count("-proxy")) { addrProxy = CService(mapArgs["-proxy"], 9050); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str())); if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { #ifdef USE_IPV6 if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy, nSocksVersion); #endif SetNameProxy(addrProxy, nSocksVersion); } fProxy = true; } // -tor can override normal proxy, -notor disables tor entirely if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) { CService addrOnion; if (!mapArgs.count("-tor")) addrOnion = addrProxy; else addrOnion = CService(mapArgs["-tor"], 9050); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str())); SetProxy(NET_TOR, addrOnion, 5); SetReachable(NET_TOR); } // see Step 2: parameter interactions for more information about these fNoListen = !GetBoolArg("-listen", true); fDiscover = GetBoolArg("-discover", true); fNameLookup = GetBoolArg("-dns", true); bool fBound = false; if (!fNoListen) { if (mapArgs.count("-bind")) { BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str())); fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); } } else { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; #ifdef USE_IPV6 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE); #endif fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); } if (!fBound) return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); } if (mapArgs.count("-externalip")) { BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) { CService addrLocal(strAddr, GetListenPort(), fNameLookup); if (!addrLocal.IsValid()) return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str())); AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL); } } BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"]) AddOneShot(strDest); // ********************************************************* Step 7: load block chain fReindex = GetBoolArg("-reindex", false); // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/ filesystem::path blocksDir = GetDataDir() / "blocks"; if (!filesystem::exists(blocksDir)) { filesystem::create_directories(blocksDir); bool linked = false; for (unsigned int i = 1; i < 10000; i++) { filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i); if (!filesystem::exists(source)) break; filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1); try { filesystem::create_hard_link(source, dest); printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str()); linked = true; } catch (filesystem::filesystem_error & e) { // Note: hardlink creation failing is not a disaster, it just means // blocks will get re-downloaded from peers. printf("Error hardlinking blk%04u.dat : %s\n", i, e.what()); break; } } if (linked) { fReindex = true; } } // cache size calculations size_t nTotalCache = GetArg("-dbcache", 25) << 20; if (nTotalCache < (1 << 22)) nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB size_t nBlockTreeDBCache = nTotalCache / 8; if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false)) nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB nTotalCache -= nBlockTreeDBCache; size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache nTotalCache -= nCoinDBCache; nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes bool fLoaded = false; while (!fLoaded) { bool fReset = fReindex; std::string strLoadError; uiInterface.InitMessage(_("Loading block index...")); nStart = GetTimeMillis(); do { try { UnloadBlockIndex(); delete pcoinsTip; delete pcoinsdbview; delete pblocktree; pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); pcoinsTip = new CCoinsViewCache(*pcoinsdbview); if (fReindex) pblocktree->WriteReindexing(true); if (!LoadBlockIndex()) { strLoadError = _("Error loading block database"); break; } // If the loaded chain has a wrong genesis, bail out immediately // (we're likely using a testnet datadir, or the other way around). if (!mapBlockIndex.empty() && pindexGenesisBlock == NULL) return InitError(_("Incorrect or no genesis block found. Wrong datadir for network?")); // Initialize the block index (no-op if non-empty database was already loaded) if (!InitBlockIndex()) { strLoadError = _("Error initializing block database"); break; } // Check for changed -txindex state if (fTxIndex != GetBoolArg("-txindex", false)) { strLoadError = _("You need to rebuild the database using -reindex to change -txindex"); break; } uiInterface.InitMessage(_("Verifying blocks...")); if (!VerifyDB(GetArg("-checklevel", 3), GetArg( "-checkblocks", 288))) { strLoadError = _("Corrupted block database detected"); break; } } catch(std::exception &e) { strLoadError = _("Error opening block database"); break; } fLoaded = true; } while(false); if (!fLoaded) { // first suggest a reindex if (!fReset) { bool fRet = uiInterface.ThreadSafeMessageBox( strLoadError + ".\n\n" + _("Do you want to rebuild the block database now?"), "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; fRequestShutdown = false; } else { printf("Aborted block database rebuild. Exiting.\n"); return false; } } else { return InitError(strLoadError); } } } // as LoadBlockIndex can take several minutes, it's possible the user // requested to kill bitcoin-qt during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { printf("Shutdown requested. Exiting.\n"); return false; } printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart); if (GetBoolArg("-printblockindex", false) || GetBoolArg("-printblocktree", false)) { PrintBlockTree(); return false; } if (mapArgs.count("-printblock")) { string strMatch = mapArgs["-printblock"]; int nFound = 0; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { uint256 hash = (*mi).first; if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0) { CBlockIndex* pindex = (*mi).second; CBlock block; ReadBlockFromDisk(block, pindex); block.BuildMerkleTree(); block.print(); printf("\n"); nFound++; } } if (nFound == 0) printf("No blocks matching %s were found\n", strMatch.c_str()); return false; } // ********************************************************* Step 8: load wallet uiInterface.InitMessage(_("Loading wallet...")); nStart = GetTimeMillis(); bool fFirstRun = true; pwalletMain = new CWallet(strWalletFile); DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); if (nLoadWalletRet != DB_LOAD_OK) { if (nLoadWalletRet == DB_CORRUPT) strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) { string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.")); InitWarning(msg); } else if (nLoadWalletRet == DB_TOO_NEW) strErrors << _("Error loading wallet.dat: Wallet requires newer version of Num2coin") << "\n"; else if (nLoadWalletRet == DB_NEED_REWRITE) { strErrors << _("Wallet needed to be rewritten: restart Num2coin to complete") << "\n"; printf("%s", strErrors.str().c_str()); return InitError(strErrors.str()); } else strErrors << _("Error loading wallet.dat") << "\n"; } if (GetBoolArg("-upgradewallet", fFirstRun)) { int nMaxVersion = GetArg("-upgradewallet", 0); if (nMaxVersion == 0) // the -upgradewallet without argument case { printf("Performing wallet upgrade to %i\n", FEATURE_LATEST); nMaxVersion = CLIENT_VERSION; pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately } else printf("Allowing wallet upgrade up to %i\n", nMaxVersion); if (nMaxVersion < pwalletMain->GetVersion()) strErrors << _("Cannot downgrade wallet") << "\n"; pwalletMain->SetMaxVersion(nMaxVersion); } if (fFirstRun) { // Create new keyUser and set as default key RandAddSeedPerfmon(); CPubKey newDefaultKey; if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) { pwalletMain->SetDefaultKey(newDefaultKey); if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), "")) strErrors << _("Cannot write default address") << "\n"; } pwalletMain->SetBestChain(CBlockLocator(pindexBest)); } printf("%s", strErrors.str().c_str()); printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart); RegisterWallet(pwalletMain); CBlockIndex *pindexRescan = pindexBest; if (GetBoolArg("-rescan", false)) pindexRescan = pindexGenesisBlock; else { CWalletDB walletdb(strWalletFile); CBlockLocator locator; if (walletdb.ReadBestBlock(locator)) pindexRescan = locator.GetBlockIndex(); else pindexRescan = pindexGenesisBlock; } if (pindexBest && pindexBest != pindexRescan) { uiInterface.InitMessage(_("Rescanning...")); printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight); nStart = GetTimeMillis(); pwalletMain->ScanForWalletTransactions(pindexRescan, true); printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart); pwalletMain->SetBestChain(CBlockLocator(pindexBest)); nWalletDBUpdated++; } // ********************************************************* Step 9: import blocks // scan for better chains in the block chain database, that are not yet connected in the active best chain CValidationState state; if (!ConnectBestBlock(state)) strErrors << "Failed to connect best block"; std::vector<boost::filesystem::path> vImportFiles; if (mapArgs.count("-loadblock")) { BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"]) vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); // ********************************************************* Step 10: load peers uiInterface.InitMessage(_("Loading addresses...")); nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) printf("Invalid or missing peers.dat; recreating\n"); } printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n", addrman.size(), GetTimeMillis() - nStart); // ********************************************************* Step 11: start node if (!CheckDiskSpace()) return false; if (!strErrors.str().empty()) return InitError(strErrors.str()); RandAddSeedPerfmon(); //// debug print printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size()); printf("nBestHeight = %d\n", nBestHeight); printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size()); printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size()); printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size()); StartNode(threadGroup); // InitRPCMining is needed here so getwork/getblocktemplate in the GUI debug console works properly. InitRPCMining(); if (fServer) StartRPCThreads(); // Generate coins in the background GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain); // ********************************************************* Step 12: finished uiInterface.InitMessage(_("Done loading")); // Add wallet transactions that aren't already in a block to mapTransactions pwalletMain->ReacceptWalletTransactions(); // Run a thread to flush wallet periodically threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); return !fRequestShutdown; }
// Copyright 2004-present Facebook. All Rights Reserved. #include <ATen/native/UpSample.h> namespace at { namespace native { namespace upsample { TORCH_API c10::SmallVector<int64_t, 3> compute_output_size( c10::IntArrayRef input_size, // Full input tensor size. c10::optional<c10::IntArrayRef> output_size, c10::optional<c10::ArrayRef<double>> scale_factors) { const auto spatial_dimensions = static_cast<int64_t>(input_size.size()) - 2; if (output_size) { TORCH_CHECK(!scale_factors, "Must specify exactly one of output_size and scale_factors"); TORCH_CHECK(static_cast<int64_t>(output_size->size()) == spatial_dimensions); return {output_size->data(), output_size->data() + output_size->size()}; } if (scale_factors) { TORCH_CHECK(!output_size, "Must specify exactly one of output_size and scale_factors"); TORCH_CHECK(static_cast<int64_t>(scale_factors->size()) == spatial_dimensions); c10::SmallVector<int64_t, 3> ret; for (int i = 0; i < spatial_dimensions; ++i) { ret.push_back(static_cast<double>(input_size[i+2]) * scale_factors.value()[i]); } return ret; } TORCH_CHECK(false, "Must specify exactly one of output_size and scale_factors"); } } // namespace upsample } // namespace native } // namespace at
#include <stdlib.h> #include "PcapPlusPlusVersion.h" #include "PcapLiveDevice.h" #include "PcapLiveDeviceList.h" #include "NetworkUtils.h" #include <getopt.h> #include "SystemUtils.h" #define EXIT_WITH_ERROR(reason, ...) do { \ printf("\nError: " reason "\n\n", ## __VA_ARGS__); \ printUsage(); \ exit(1); \ } while(0) using namespace pcpp; static struct option DNSResolverOptions[] = { {"interface", required_argument, 0, 'i'}, {"hostname", required_argument, 0, 's'}, {"dns-server", required_argument, 0, 'd'}, {"gateway", required_argument, 0, 'g'}, {"timeout", optional_argument, 0, 't'}, {"help", no_argument, 0, 'h'}, {"version", no_argument, 0, 'v'}, {"list", no_argument, 0, 'l'}, {0, 0, 0, 0} }; /** * Print application usage */ void printUsage() { printf("\nUsage:\n" "------\n" "%s [-hvl] [-t timeout] [-d dns_server] [-g gateway] [-i interface] -s hostname\n" "\nOptions:\n\n" " -h : Displays this help message and exits\n" " -v : Displays the current version and exists\n" " -l : Print the list of interfaces and exists\n" " -s hostname : Hostname to resolve\n" " -i interface : Use the specified interface. Can be interface name (e.g eth0) or interface IPv4 address. If not set\n" " one of the interfaces that has a default gateway will be used\n" " -d dns_server: IPv4 address of DNS server to send the DNS request to. If not set the DNS request will be sent to the gateway\n" " -g gateway : IPv4 address of the gateway to send the DNS request to. If not set the default gateway will be chosen\n" " -t timeout : How long to wait for a reply (in seconds). Default timeout is 5 seconds\n", AppName::get().c_str()); exit(0); } /** * Print application version */ void printAppVersion() { printf("%s %s\n", AppName::get().c_str(), getPcapPlusPlusVersionFull().c_str()); printf("Built: %s\n", getBuildDateTime().c_str()); printf("Built from: %s\n", getGitInfo().c_str()); exit(0); } /** * Go over all interfaces and output their names */ void listInterfaces() { const std::vector<PcapLiveDevice*>& devList = PcapLiveDeviceList::getInstance().getPcapLiveDevicesList(); printf("\nNetwork interfaces:\n"); for (std::vector<PcapLiveDevice*>::const_iterator iter = devList.begin(); iter != devList.end(); iter++) { std::string defaultGateway = (!(*iter)->getDefaultGateway().isUnspecified() ? (*iter)->getDefaultGateway().toString() : "None"); printf(" -> Name: '%s' IP address: %s Default gateway: %s\n", (*iter)->getName(), (*iter)->getIPv4Address().toString().c_str(), defaultGateway.c_str()); } exit(0); } /** * main method of the application */ int main(int argc, char* argv[]) { AppName::init(argc, argv); std::string hostname; bool hostnameProvided = false; std::string interfaceNameOrIP; bool interfaceNameOrIPProvided = false; IPv4Address dnsServerIP; IPv4Address gatewayIP; int timeoutSec = -1; int optionIndex = 0; char opt = 0; while((opt = getopt_long (argc, argv, "i:d:g:s:t:hvl", DNSResolverOptions, &optionIndex)) != -1) { switch (opt) { case 0: { break; } case 'h': { printUsage(); exit(0); } case 'v': { printAppVersion(); break; } case 'l': { listInterfaces(); exit(0); } case 'i': { interfaceNameOrIP = optarg; interfaceNameOrIPProvided = true; break; } case 'd': { dnsServerIP = IPv4Address(static_cast<char const *>(optarg)); break; } case 'g': { gatewayIP = IPv4Address(static_cast<char const *>(optarg)); break; } case 's': { hostname = optarg; hostnameProvided = true; break; } case 't': { timeoutSec = atoi(optarg); break; } default: { printUsage(); exit(1); } } } // make sure that hostname is provided if (!hostnameProvided) EXIT_WITH_ERROR("Hostname not provided"); // find the interface to send the DNS request from PcapLiveDevice* dev = NULL; // if interface name or IP was provided - find the device accordingly if (interfaceNameOrIPProvided) { IPv4Address interfaceIP(interfaceNameOrIP); if (!interfaceIP.isUnspecified()) { dev = PcapLiveDeviceList::getInstance().getPcapLiveDeviceByIp(interfaceIP); if (dev == NULL) EXIT_WITH_ERROR("Couldn't find interface by provided IP"); } else { dev = PcapLiveDeviceList::getInstance().getPcapLiveDeviceByName(interfaceNameOrIP); if (dev == NULL) EXIT_WITH_ERROR("Couldn't find interface by provided name"); } } // if interface name or IP was not provided - find a device that has a default gateway else { const std::vector<PcapLiveDevice*>& devList = PcapLiveDeviceList::getInstance().getPcapLiveDevicesList(); for (std::vector<PcapLiveDevice*>::const_iterator iter = devList.begin(); iter != devList.end(); iter++) { if (!(*iter)->getDefaultGateway().isUnspecified()) { dev = *iter; break; } } if (dev == NULL) EXIT_WITH_ERROR("Couldn't find an interface with a default gateway"); } printf("Using interface '%s'\n", dev->getIPv4Address().toString().c_str()); // find the IPv4 address for provided hostname double responseTime = 0; uint32_t dnsTTL = 0; IPv4Address resultIP = NetworkUtils::getInstance().getIPv4Address(hostname, dev, responseTime, dnsTTL, timeoutSec, dnsServerIP, gatewayIP); // print resolved IPv4 address if found if (resultIP.isUnspecified()) printf("\nCould not resolve hostname [%s]\n", hostname.c_str()); else printf("\nIP address of [%s] is: %s DNS-TTL=%d time=%dms\n", hostname.c_str(), resultIP.toString().c_str(), dnsTTL, (int)responseTime); }
// MyGridDlg.cpp : implementation file // #include "stdafx.h" #include "MyGridDlg.h" #include "MyFrame.h" #include "afxdialogex.h" #include "Resource.h" #include "StyleColors.h" // MyGridDlg dialog IMPLEMENT_DYNAMIC(MyGridDlg, StyleDialog) MyGridDlg::MyGridDlg(CWnd* pParent /*=nullptr*/) :StyleDialog(IDD_GRIDDIALOG, pParent,true,true) { m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); } MyGridDlg::~MyGridDlg() { } void MyGridDlg::DoDataExchange(CDataExchange* pDX) { StyleDialog::DoDataExchange(pDX); DDX_Control(pDX,IDC_TEXT,m_text,m_string); DDX_Control(pDX,IDC_GRID,m_grid); DDX_Control(pDX,IDOK, m_buttonOK); DDX_Control(pDX,IDCANCEL,m_buttonCancel); } BEGIN_MESSAGE_MAP(MyGridDlg, StyleDialog) ON_NOTIFY(GVN_SELCHANGED, IDC_GRID,OnSelChangedGrid) ON_NOTIFY(GVN_ENDLABELEDIT,IDC_GRID,OnGridEndEdit) ON_COMMAND (ID_THEMA_LIME, OnStyleLime) ON_COMMAND (ID_THEMA_SKYBLUE, OnStyleSkyblue) ON_COMMAND (ID_THEMA_PURPLE, OnStylePurple) ON_COMMAND (ID_THEMA_MODERATE, OnStyleModerateGray) ON_COMMAND (ID_THEMA_PUREGRAY, OnStylePureGray) ON_COMMAND (ID_THEMA_BLACKWHITE,OnStyleBlackWhite) END_MESSAGE_MAP() // MyGridDlg message handlers BOOL MyGridDlg::OnInitDialog() { StyleDialog::OnInitDialog(); SetWindowText("My Grid testing dialog"); SetSysMenu(IDR_MENU4); m_buttonOK.SetStyle("ok"); m_buttonCancel.SetStyle("can"); FillGrid(); SetCanResize(); ShowMinMaxButton(); return TRUE; } // Triggered by SetCanResize void MyGridDlg::SetupDynamicLayout() { // See to it that we get a manager; StyleDialog::SetupDynamicLayout(); CMFCDynamicLayout& manager = *GetDynamicLayout(); #ifdef _DEBUG manager.AssertValid(); #endif HWND grid = m_grid.GetSkin()->GetSafeHwnd(); HWND text = m_text.GetSkin()->GetSafeHwnd(); manager.AddItem(grid, manager.MoveNone(), manager.SizeHorizontalAndVertical(100,100)); manager.AddItem(text, manager.MoveVertical(100), manager.SizeHorizontal(100)); manager.AddItem(m_buttonOK, manager.MoveHorizontalAndVertical(100, 100), manager.SizeNone()); manager.AddItem(m_buttonCancel, manager.MoveHorizontalAndVertical(100, 100), manager.SizeNone()); } void MyGridDlg::FillGrid() { m_grid.SetColumnCount(5); m_grid.SetRowCount(1); m_grid.SetFixedRowCount(1); m_grid.GetCell(0, 0)->SetText("Index"); m_grid.GetCell(0, 1)->SetText("Variable"); m_grid.GetCell(0, 2)->SetText("Value"); m_grid.GetCell(0, 3)->SetText("ComboBox"); m_grid.GetCell(0, 4)->SetText("CheckBox"); m_grid.SetColumnWidth(0, 80); m_grid.SetColumnWidth(1, 280); m_grid.SetColumnWidth(2, 280); m_grid.SetColumnWidth(3, 140); m_grid.SetColumnWidth(4, 80); m_grid.SetEditable(); m_grid.SetSingleColSelection(TRUE); m_grid.SetSingleRowSelection(TRUE); // Add to the list int firstRow = 0; for(int index = 0; index < 50; ++index) { CString col1; CString col2; CString col3; col1.Format("%02d", index + 1); col2.Format("Var_%02d", 50 - index); col3.Format("VALUE_%03d_LONGER", 3 * index); int row = m_grid.InsertRow(col1); m_grid.GetCell(row, 1)->SetText(col2); m_grid.GetCell(row, 2)->SetText(col3); m_grid.SetCellType(row, 3,RUNTIME_CLASS(CGridCellCombo)); m_grid.SetCellType(row, 4,RUNTIME_CLASS(CGridCellCheck)); CGridCellCombo* combo = reinterpret_cast<CGridCellCombo*>(m_grid.GetCell(row, 3)); SetComboList(combo); if (!firstRow) { firstRow = row; } } if (firstRow) { m_grid.SetFocusCell(1, 0); } m_grid.SetSortColumn(0); m_grid.SetSortAscending(TRUE); m_grid.SetHeaderSort(); m_grid.SetFocus(); } void MyGridDlg::SetComboList(CGridCellCombo* p_combo) { CStringArray list; list.Add("First choice"); list.Add("Second 2"); list.Add("3 = Third"); list.Add("Four = 4"); list.Add("Firth of Fifth"); for (int i = 0; i < 30; ++i) { list.Add("Another one"); } p_combo->SetOptions(list); p_combo->SetStyle(CBS_DROPDOWNLIST | CBS_SORT); // p_combo->SetStyle(CBS_DROPDOWN); } void MyGridDlg::AddToText(CString p_text) { CString total = m_text.GetWindowString(); total += p_text; m_text.SetWindowText(total); } void MyGridDlg::OnSelChangedGrid(NMHDR* p_nmhdr,LRESULT* p_result) { NM_GRIDVIEW* pItem = (NM_GRIDVIEW*)p_nmhdr; CString debug; debug.Format("End Selection Change on row %d, col %d (%d Selected)\r\n", pItem->iRow ,pItem->iColumn ,m_grid.GetSelectedCount()); AddToText(debug); *p_result = 0; } void MyGridDlg::OnGridEndEdit(NMHDR* p_nmhdr, LRESULT* p_result) { NM_GRIDVIEW* pItem = (NM_GRIDVIEW*)p_nmhdr; CString debug; debug.Format("End Edit on row %d, col %d\r\n",pItem->iRow,pItem->iColumn); AddToText(debug); *p_result = 0; }
// Boost.Units - A C++ library for zero-overhead dimensional analysis and // unit/quantity manipulation and conversion // // Copyright (C) 2003-2008 Matthias Christian Schabel // Copyright (C) 2008 Steven Watanabe // // 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 QSBOOST_UNITS_CGS_DIMENSIONLESS_HPP #define QSBOOST_UNITS_CGS_DIMENSIONLESS_HPP #include <qsboost/units/systems/cgs/base.hpp> namespace qsboost { namespace units { namespace cgs { QSBOOST_UNITS_STATIC_CONSTANT(cgs_dimensionless,dimensionless); } // namespace cgs } // namespace units } // namespace boost #endif // BOOST_UNITS_CGS_DIMENSIONLESS_HPP
/* * Copyright (c) 2015, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * */ #include <proxygen/lib/http/codec/experimental/HTTP2Framer.h> #include <cstdint> using namespace folly::io; using namespace folly; namespace proxygen { namespace http2 { const uint8_t kMaxFrameType = static_cast<uint8_t>(FrameType::ALTSVC); const boost::optional<uint8_t> kNoPadding; namespace { const uint32_t kLengthMask = 0x00ffffff; const uint32_t kUint31Mask = 0x7fffffff; static const uint64_t kZeroPad[32] = {0}; static const bool kStrictPadding = true; static_assert(sizeof(kZeroPad) == 256, "bad zero padding"); void writePriorityBody(IOBufQueue& queue, uint32_t streamDependency, bool exclusive, uint8_t weight) { DCHECK_EQ(0, ~kUint31Mask & streamDependency); if (exclusive) { streamDependency |= ~kUint31Mask; } QueueAppender appender(&queue, 8); appender.writeBE<uint32_t>(streamDependency); appender.writeBE<uint8_t>(weight); } void writePadding(IOBufQueue& queue, boost::optional<uint8_t> size) { if (size && size.get() > 0) { auto out = IOBuf::create(size.get()); memset(out->writableData(), 0, size.get()); out->append(size.get()); queue.append(std::move(out)); } } /** * Generate just the common frame header. This includes the padding length * bits that sometimes come right after the frame header. Returns the * length field written to the common frame header. */ size_t writeFrameHeader(IOBufQueue& queue, uint32_t length, FrameType type, uint8_t flags, uint32_t stream, boost::optional<uint8_t> padding) noexcept { QueueAppender appender(&queue, kFrameHeaderSize); // the acceptable length is now conditional based on state :( DCHECK_EQ(0, ~kLengthMask & length); DCHECK_EQ(0, ~kUint31Mask & stream); // Adjust length if we will emit a priority section if (flags & PRIORITY) { DCHECK(FrameType::HEADERS == type); length += kFramePrioritySize; DCHECK_EQ(0, ~kLengthMask & length); } // Add or remove padding flags if (padding) { flags |= PADDED; length += padding.get() + 1; } else { flags &= ~PADDED; } DCHECK_EQ(0, ~kLengthMask & length); DCHECK_GE(kMaxFrameType, static_cast<uint8_t>(type)); uint32_t lengthAndType = ((kLengthMask & length) << 8) | static_cast<uint8_t>(type); appender.writeBE<uint32_t>(lengthAndType); appender.writeBE<uint8_t>(flags); appender.writeBE<uint32_t>(kUint31Mask & stream); if (padding) { appender.writeBE<uint8_t>(padding.get()); } return length; } uint32_t parseUint31(Cursor& cursor) { // MUST ignore the 1 bit before the stream-id return kUint31Mask & cursor.readBE<uint32_t>(); } ErrorCode parseErrorCode(Cursor& cursor, ErrorCode& outCode) { auto code = cursor.readBE<uint32_t>(); if (code > kMaxErrorCode) { return ErrorCode::PROTOCOL_ERROR; } outCode = ErrorCode(code); return ErrorCode::NO_ERROR; } PriorityUpdate parsePriorityCommon(Cursor& cursor) { PriorityUpdate priority; uint32_t streamAndExclusive = cursor.readBE<uint32_t>(); priority.weight = cursor.readBE<uint8_t>(); priority.exclusive = ~kUint31Mask & streamAndExclusive; priority.streamDependency = kUint31Mask & streamAndExclusive; return priority; } /** * Given the flags for a frame and the cursor pointing at the top of the * frame-specific section (after the common header), return the number of * bytes to skip at the end of the frame. Caller must ensure there is at * least 1 bytes in the cursor. * * @param cursor The cursor to pull data from * @param header The frame header for the frame being parsed. The length * field may be modified based on the number of optional * padding length fields were read. * @param padding The out parameter that will return the number of padding * bytes at the end of the frame. * @return Nothing if success. The connection error code if failure. */ ErrorCode parsePadding(Cursor& cursor, FrameHeader& header, uint8_t& padding) noexcept { if (header.flags & PADDED) { if (header.length < 1) { return ErrorCode::FRAME_SIZE_ERROR; } header.length -= 1; padding = cursor.readBE<uint8_t>(); } else { padding = 0; } return ErrorCode::NO_ERROR; } ErrorCode skipPadding(Cursor& cursor, uint8_t length, bool verify) { if (verify) { while (length > 0) { auto cur = cursor.peek(); uint8_t toCmp = std::min<size_t>(cur.second, length); if (memcmp(cur.first, kZeroPad, toCmp)) { return ErrorCode::PROTOCOL_ERROR; } cursor.skip(toCmp); length -= toCmp; } } else { cursor.skip(length); } return ErrorCode::NO_ERROR; } } // anonymous namespace bool frameAffectsCompression(FrameType t) { return t == FrameType::HEADERS || t == FrameType::PUSH_PROMISE || t == FrameType::CONTINUATION; } //// Parsing //// ErrorCode parseFrameHeader(Cursor& cursor, FrameHeader& header) noexcept { DCHECK_LE(kFrameHeaderSize, cursor.totalLength()); // MUST ignore the 2 bits before the length uint32_t lengthAndType = cursor.readBE<uint32_t>(); header.length = kLengthMask & (lengthAndType >> 8); uint8_t type = lengthAndType & 0xff; header.type = FrameType(type); header.flags = cursor.readBE<uint8_t>(); header.stream = parseUint31(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseData(Cursor& cursor, FrameHeader header, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; const auto err = parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, header.length - padding); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parseHeaders(Cursor& cursor, FrameHeader header, PriorityUpdate& outPriority, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0 || !(header.stream & 0x1)) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; auto err = parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.flags & PRIORITY) { if (header.length < kFramePrioritySize) { return ErrorCode::FRAME_SIZE_ERROR; } outPriority = parsePriorityCommon(cursor); header.length -= kFramePrioritySize; } if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, header.length - padding); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parsePriority(Cursor& cursor, FrameHeader header, PriorityUpdate& outPriority) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFramePrioritySize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } outPriority = parsePriorityCommon(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseRstStream(Cursor& cursor, FrameHeader header, ErrorCode& outCode) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFrameRstStreamSize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } return parseErrorCode(cursor, outCode); } ErrorCode parseSettings(Cursor& cursor, FrameHeader header, std::deque<SettingPair>& settings) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } if (header.flags & ACK) { if (header.length != 0) { return ErrorCode::FRAME_SIZE_ERROR; } return ErrorCode::NO_ERROR; } if (header.length % 6 != 0) { return ErrorCode::FRAME_SIZE_ERROR; } for (; header.length > 0; header.length -= 6) { uint16_t id = cursor.readBE<uint16_t>(); uint32_t val = cursor.readBE<uint32_t>(); settings.push_back(std::make_pair(SettingsId(id), val)); } return ErrorCode::NO_ERROR; } ErrorCode parsePushPromise(Cursor& cursor, FrameHeader header, uint32_t& outPromisedStream, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; auto err = parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.length < kFramePushPromiseSize) { return ErrorCode::FRAME_SIZE_ERROR; } header.length -= kFramePushPromiseSize; outPromisedStream = parseUint31(cursor); if (outPromisedStream == 0 || outPromisedStream & 0x1) { // client MUST reserve an even stream id greater than 0 return ErrorCode::PROTOCOL_ERROR; } if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, header.length - padding); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parsePing(Cursor& cursor, FrameHeader header, uint64_t& outOpaqueData) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFramePingSize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } cursor.pull(&outOpaqueData, sizeof(outOpaqueData)); return ErrorCode::NO_ERROR; } ErrorCode parseGoaway(Cursor& cursor, FrameHeader header, uint32_t& outLastStreamID, ErrorCode& outCode, std::unique_ptr<IOBuf>& outDebugData) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length < kFrameGoawaySize) { return ErrorCode::FRAME_SIZE_ERROR; } if (header.stream != 0) { return ErrorCode::PROTOCOL_ERROR; } outLastStreamID = parseUint31(cursor); RETURN_IF_ERROR(parseErrorCode(cursor, outCode)); header.length -= kFrameGoawaySize; if (header.length > 0) { cursor.clone(outDebugData, header.length); } return ErrorCode::NO_ERROR; } ErrorCode parseWindowUpdate(Cursor& cursor, FrameHeader header, uint32_t& outAmount) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length != kFrameWindowUpdateSize) { return ErrorCode::FRAME_SIZE_ERROR; } outAmount = parseUint31(cursor); return ErrorCode::NO_ERROR; } ErrorCode parseContinuation(Cursor& cursor, FrameHeader header, std::unique_ptr<IOBuf>& outBuf) noexcept { DCHECK(header.type == FrameType::CONTINUATION); DCHECK_LE(header.length, cursor.totalLength()); if (header.stream == 0) { return ErrorCode::PROTOCOL_ERROR; } uint8_t padding; auto err = parsePadding(cursor, header, padding); RETURN_IF_ERROR(err); if (header.length < padding) { return ErrorCode::PROTOCOL_ERROR; } cursor.clone(outBuf, header.length - padding); return skipPadding(cursor, padding, kStrictPadding); } ErrorCode parseAltSvc(Cursor& cursor, FrameHeader header, uint32_t& outMaxAge, uint32_t& outPort, std::string& outProtocol, std::string& outHost, std::string& outOrigin) noexcept { DCHECK_LE(header.length, cursor.totalLength()); if (header.length < kFrameAltSvcSizeBase) { return ErrorCode::FRAME_SIZE_ERROR; } std::unique_ptr<IOBuf> tmpBuf; outMaxAge = cursor.readBE<uint32_t>(); outPort = cursor.readBE<uint16_t>(); const auto protoLen = cursor.readBE<uint8_t>(); if (header.length < kFrameAltSvcSizeBase + protoLen) { return ErrorCode::FRAME_SIZE_ERROR; } outProtocol = cursor.readFixedString(protoLen); const auto hostLen = cursor.readBE<uint8_t>(); if (header.length < kFrameAltSvcSizeBase + protoLen + hostLen) { return ErrorCode::FRAME_SIZE_ERROR; } outHost = cursor.readFixedString(hostLen); const auto originLen = (header.length - kFrameAltSvcSizeBase - protoLen - hostLen); outOrigin = cursor.readFixedString(originLen); return ErrorCode::NO_ERROR; } //// Egress //// size_t writeData(IOBufQueue& queue, std::unique_ptr<IOBuf> data, uint32_t stream, boost::optional<uint8_t> padding, bool endStream) noexcept { DCHECK_NE(0, stream); uint8_t flags = 0; if (endStream) { flags |= END_STREAM; } const uint64_t dataLen = data ? data->computeChainDataLength() : 0; // Caller must not exceed peer setting for MAX_FRAME_SIZE // TODO: look into using headroom from data to hold the frame header const auto frameLen = writeFrameHeader(queue, dataLen, FrameType::DATA, flags, stream, padding); queue.append(std::move(data)); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writeHeaders(IOBufQueue& queue, std::unique_ptr<IOBuf> headers, uint32_t stream, boost::optional<PriorityUpdate> priority, boost::optional<uint8_t> padding, bool endStream, bool endHeaders) noexcept { DCHECK_NE(0, stream); DCHECK_NE(0, 0x1 & stream); const auto dataLen =(headers) ? headers->computeChainDataLength() : 0; uint32_t flags = 0; if (priority) { flags |= PRIORITY; } if (endStream) { flags |= END_STREAM; } if (endHeaders) { flags |= END_HEADERS; } // padding flags handled directly inside writeFrameHeader() const auto frameLen = writeFrameHeader(queue, dataLen, FrameType::HEADERS, flags, stream, padding); if (priority) { writePriorityBody(queue, priority->streamDependency, priority->exclusive, priority->weight); } if (headers) { queue.append(std::move(headers)); } writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writePriority(IOBufQueue& queue, uint32_t stream, PriorityUpdate priority) noexcept { DCHECK_NE(0, stream); const auto frameLen = writeFrameHeader(queue, kFramePrioritySize, FrameType::PRIORITY, 0, stream, kNoPadding); writePriorityBody(queue, priority.streamDependency, priority.exclusive, priority.weight); return kFrameHeaderSize + frameLen; } size_t writeRstStream(IOBufQueue& queue, uint32_t stream, ErrorCode errorCode) noexcept { DCHECK_NE(0, stream); const auto frameLen = writeFrameHeader(queue, kFrameRstStreamSize, FrameType::RST_STREAM, 0, stream, kNoPadding); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(static_cast<uint32_t>(errorCode)); return kFrameHeaderSize + frameLen; } size_t writeSettings(IOBufQueue& queue, const std::deque<SettingPair>& settings) { const auto settingsSize = settings.size() * 6; const auto frameLen = writeFrameHeader(queue, settingsSize, FrameType::SETTINGS, 0, 0, kNoPadding); QueueAppender appender(&queue, settingsSize); for (const auto& setting: settings) { DCHECK_LE(static_cast<uint32_t>(setting.first), std::numeric_limits<uint16_t>::max()); appender.writeBE<uint16_t>(static_cast<uint16_t>(setting.first)); appender.writeBE<uint32_t>(setting.second); } return kFrameHeaderSize + frameLen; } size_t writeSettingsAck(IOBufQueue& queue) { const auto frameLen = writeFrameHeader(queue, 0, FrameType::SETTINGS, ACK, 0, kNoPadding); return kFrameHeaderSize; } size_t writePushPromise(IOBufQueue& queue, uint32_t associatedStream, uint32_t promisedStream, std::unique_ptr<IOBuf> headers, boost::optional<uint8_t> padding, bool endHeaders) noexcept { DCHECK_NE(0, promisedStream); DCHECK_NE(0, associatedStream); DCHECK_EQ(0, 0x1 & promisedStream); DCHECK_EQ(1, 0x1 & associatedStream); DCHECK_EQ(0, ~kUint31Mask & promisedStream); const auto dataLen = headers->computeChainDataLength(); const auto frameLen = writeFrameHeader(queue, dataLen + kFramePushPromiseSize, FrameType::PUSH_PROMISE, endHeaders ? END_HEADERS : 0, associatedStream, padding); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(promisedStream); queue.append(std::move(headers)); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writePing(IOBufQueue& queue, uint64_t opaqueData, bool ack) noexcept { const auto frameLen = writeFrameHeader(queue, kFramePingSize, FrameType::PING, ack ? ACK : 0, 0, kNoPadding); queue.append(&opaqueData, sizeof(opaqueData)); return kFrameHeaderSize + frameLen; } size_t writeGoaway(IOBufQueue& queue, uint32_t lastStreamID, ErrorCode errorCode, std::unique_ptr<IOBuf> debugData) noexcept { uint32_t debugLen = debugData ? debugData->computeChainDataLength() : 0; DCHECK_EQ(0, ~kLengthMask & debugLen); const auto frameLen = writeFrameHeader(queue, kFrameGoawaySize + debugLen, FrameType::GOAWAY, 0, 0, kNoPadding); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(lastStreamID); appender.writeBE<uint32_t>(static_cast<uint32_t>(errorCode)); queue.append(std::move(debugData)); return kFrameHeaderSize + frameLen; } size_t writeWindowUpdate(IOBufQueue& queue, uint32_t stream, uint32_t amount) noexcept { const auto frameLen = writeFrameHeader(queue, kFrameWindowUpdateSize, FrameType::WINDOW_UPDATE, 0, stream, kNoPadding); DCHECK_EQ(0, ~kUint31Mask & amount); DCHECK_LT(0, amount); QueueAppender appender(&queue, kFrameWindowUpdateSize); appender.writeBE<uint32_t>(amount); return kFrameHeaderSize + frameLen; } size_t writeContinuation(IOBufQueue& queue, uint32_t stream, bool endHeaders, std::unique_ptr<IOBuf> headers, boost::optional<uint8_t> padding) noexcept { DCHECK_NE(0, stream); const auto dataLen = headers->computeChainDataLength(); const auto frameLen = writeFrameHeader(queue, dataLen, FrameType::CONTINUATION, endHeaders ? END_HEADERS : 0, stream, padding); queue.append(std::move(headers)); writePadding(queue, padding); return kFrameHeaderSize + frameLen; } size_t writeAltSvc(IOBufQueue& queue, uint32_t stream, uint32_t maxAge, uint16_t port, StringPiece protocol, StringPiece host, StringPiece origin) noexcept { const auto protoLen = protocol.size(); const auto hostLen = host.size(); const auto originLen = origin.size(); const auto frameLen = protoLen + hostLen + originLen + kFrameAltSvcSizeBase; writeFrameHeader(queue, frameLen, FrameType::ALTSVC, 0, stream, kNoPadding); QueueAppender appender(&queue, frameLen); appender.writeBE<uint32_t>(maxAge); appender.writeBE<uint16_t>(port); appender.writeBE<uint8_t>(protoLen); appender.push(reinterpret_cast<const uint8_t*>(protocol.data()), protoLen); appender.writeBE<uint8_t>(hostLen); appender.push(reinterpret_cast<const uint8_t*>(host.data()), hostLen); appender.push(reinterpret_cast<const uint8_t*>(origin.data()), originLen); return kFrameHeaderSize + frameLen; } const char* getFrameTypeString(FrameType type) { switch (type) { case FrameType::DATA: return "DATA"; case FrameType::HEADERS: return "HEADERS"; case FrameType::PRIORITY: return "PRIORITY"; case FrameType::RST_STREAM: return "RST_STREAM"; case FrameType::SETTINGS: return "SETTINGS"; case FrameType::PUSH_PROMISE: return "PUSH_PROMISE"; case FrameType::PING: return "PING"; case FrameType::GOAWAY: return "GOAWAY"; case FrameType::WINDOW_UPDATE: return "WINDOW_UPDATE"; case FrameType::CONTINUATION: return "CONTINUATION"; case FrameType::ALTSVC: return "ALTSVC"; default: // can happen when type was cast from uint8_t return "Unknown"; } LOG(FATAL) << "Unreachable"; return ""; } }}
// Copyright Benoit Blanchon 2014-2017 // MIT License // // Arduino JSON library // https://bblanchon.github.io/ArduinoJson/ // If you like this project, please add a star! #pragma once #include "ListConstIterator.hpp" #include "ListNode.hpp" namespace ArduinoJson { namespace Internals { // A read-write forward iterator for List<T> template <typename T> class ListIterator { public: explicit ListIterator(ListNode<T> *node = NULL) : _node(node) {} T &operator*() const { return _node->content; } T *operator->() { return &_node->content; } bool operator==(const ListIterator<T> &other) const { return _node == other._node; } bool operator!=(const ListIterator<T> &other) const { return _node != other._node; } ListIterator<T> &operator++() { if (_node) _node = _node->next; return *this; } operator ListConstIterator<T>() const { return ListConstIterator<T>(_node); } private: ListNode<T> *_node; }; } }
#pragma once #include <libgaem/core.hpp> #include <libgaem/render/device.hpp> #include <vector> namespace gaem { class GaemModel { public: struct Vertex { glm::vec2 position; glm::vec3 color; static std::vector<VkVertexInputBindingDescription> getBindingDescriptions(); static std::vector<VkVertexInputAttributeDescription> getAtributeDescriptions(); }; GaemModel(GaemDevice &gaemDevice, const std::vector<Vertex> &vertices); ~GaemModel(); GaemModel(const GaemModel &) = delete; GaemModel &operator=(const GaemModel &) = delete; void bind(VkCommandBuffer commandBuffer); void draw(VkCommandBuffer commandBuffer); private: GaemDevice &gaemDevice; VkBuffer vertexBuffer; VkDeviceMemory vertexBufferMemory; uint32_t vertexCount; void createVertexBuffers(const std::vector<Vertex> &vertices); }; } // namespace gaem
#include "Camera.h" #include <iostream> Camera::Camera() { reset(); } Camera::Camera(const Vector4& e, const Vector4& d, const Vector4& up) { this->e = e; this->d = d; this->up = up; calculate_camera_matrix(); } Camera::~Camera() { } void Camera::calculate_camera_matrix() { Vector4 x, y, z; Matrix4 R, T; z = e - d; z.normalize(); x = up.cross(z); x.normalize(); y = z.cross(x); y.normalize(); R.identity(); R.setColumn(0, x); R.setColumn(1, y); R.setColumn(2, z); T.identity(); T.setColumn(3, e); camera2world = R * T; T.setColumn(3, -e); world2camera = R.transpose() * T; } Matrix4& Camera::getMatrix() { return world2camera; } const double* Camera::getGLMatrix() { return getMatrix().getPointer(); } void Camera::set_center_of_proj(const Vector4& e) { this->e = e; calculate_camera_matrix(); } Vector4& Camera::center_of_proj() { return e; } void Camera::set_center_of_proj(double x, double y, double z) { this->e = Vector4(x, y, z); calculate_camera_matrix(); } Vector4& Camera::look_at() { return d; } void Camera::look_at(const Vector4& d) { this->d = d; calculate_camera_matrix(); } void Camera::look_at(double x, double y, double z) { this->d = Vector4(x, y, z); calculate_camera_matrix(); } void Camera::set_up(const Vector4& up) { this->up = up; calculate_camera_matrix(); } void Camera::set_up(double x, double y, double z) { this->up = Vector4(x, y, z); calculate_camera_matrix(); } void Camera::reset() { e = Vector4(-5, 10, 20); d = Vector4(0, 0, -1); up = Vector4(0, 1, 0); calculate_camera_matrix(); }
// Copyright 2018 Sabre Dart Studios #include "OWSGameplayAbilityTargetActor_Tr.h" #include "DrawDebugHelpers.h" #include "GameFramework/PlayerController.h" #include "Abilities/GameplayAbility.h" // -------------------------------------------------------------------------------------------------------------------------------------------------------- // // AGameplayAbilityTargetActor_Trace // // -------------------------------------------------------------------------------------------------------------------------------------------------------- AOWSGameplayAbilityTargetActor_Tr::AOWSGameplayAbilityTargetActor_Tr(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { PrimaryActorTick.bCanEverTick = true; PrimaryActorTick.TickGroup = TG_PostUpdateWork; MaxRange = 999999.0f; bTraceAffectsAimPitch = true; } void AOWSGameplayAbilityTargetActor_Tr::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (ReticleActor.IsValid()) { ReticleActor.Get()->Destroy(); } Super::EndPlay(EndPlayReason); } void AOWSGameplayAbilityTargetActor_Tr::LineTraceWithFilter(FHitResult& OutHitResult, const UWorld* World, const FOWSGameplayTargetDataFilterHandle FilterHandle, const FVector& Start, const FVector& End, FName ProfileName, const FCollisionQueryParams Params) { check(World); TArray<FHitResult> HitResults; World->LineTraceMultiByProfile(HitResults, Start, End, ProfileName, Params); OutHitResult.TraceStart = Start; OutHitResult.TraceEnd = End; for (int32 HitIdx = 0; HitIdx < HitResults.Num(); ++HitIdx) { const FHitResult& Hit = HitResults[HitIdx]; if (!Hit.HitObjectHandle.IsValid() || FilterHandle.FilterPassesForActor(Hit.HitObjectHandle.FetchActor())) { OutHitResult = Hit; OutHitResult.bBlockingHit = true; // treat it as a blocking hit return; } } } void AOWSGameplayAbilityTargetActor_Tr::SweepWithFilter(FHitResult& OutHitResult, const UWorld* World, const FOWSGameplayTargetDataFilterHandle FilterHandle, const FVector& Start, const FVector& End, const FQuat& Rotation, const FCollisionShape CollisionShape, FName ProfileName, const FCollisionQueryParams Params) { check(World); TArray<FHitResult> HitResults; World->SweepMultiByProfile(HitResults, Start, End, Rotation, ProfileName, CollisionShape, Params); OutHitResult.TraceStart = Start; OutHitResult.TraceEnd = End; for (int32 HitIdx = 0; HitIdx < HitResults.Num(); ++HitIdx) { const FHitResult& Hit = HitResults[HitIdx]; if (!Hit.HitObjectHandle.IsValid() || FilterHandle.FilterPassesForActor(Hit.HitObjectHandle.FetchActor())) { OutHitResult = Hit; OutHitResult.bBlockingHit = true; // treat it as a blocking hit return; } } } void AOWSGameplayAbilityTargetActor_Tr::AimWithPlayerController(const AActor* InSourceActor, FCollisionQueryParams Params, const FVector& TraceStart, FVector& OutTraceEnd, bool bIgnorePitch) const { if (!OwningAbility) // Server and launching client only { return; } APlayerController* PC = OwningAbility->GetCurrentActorInfo()->PlayerController.Get(); check(PC); FVector ViewStart; FRotator ViewRot; PC->GetPlayerViewPoint(ViewStart, ViewRot); const FVector ViewDir = ViewRot.Vector(); FVector ViewEnd = ViewStart + (ViewDir * MaxRange); ClipCameraRayToAbilityRange(ViewStart, ViewDir, TraceStart, MaxRange, ViewEnd); FHitResult HitResult; LineTraceWithFilter(HitResult, InSourceActor->GetWorld(), OWSFilter, ViewStart, ViewEnd, TraceProfile.Name, Params); const bool bUseTraceResult = HitResult.bBlockingHit && (FVector::DistSquared(TraceStart, HitResult.Location) <= (MaxRange * MaxRange)); const FVector AdjustedEnd = (bUseTraceResult) ? HitResult.Location : ViewEnd; FVector AdjustedAimDir = (AdjustedEnd - TraceStart).GetSafeNormal(); if (AdjustedAimDir.IsZero()) { AdjustedAimDir = ViewDir; } if (!bTraceAffectsAimPitch && bUseTraceResult) { FVector OriginalAimDir = (ViewEnd - TraceStart).GetSafeNormal(); if (!OriginalAimDir.IsZero()) { // Convert to angles and use original pitch const FRotator OriginalAimRot = OriginalAimDir.Rotation(); FRotator AdjustedAimRot = AdjustedAimDir.Rotation(); AdjustedAimRot.Pitch = OriginalAimRot.Pitch; AdjustedAimDir = AdjustedAimRot.Vector(); } } OutTraceEnd = TraceStart + (AdjustedAimDir * MaxRange); } bool AOWSGameplayAbilityTargetActor_Tr::ClipCameraRayToAbilityRange(FVector CameraLocation, FVector CameraDirection, FVector AbilityCenter, float AbilityRange, FVector& ClippedPosition) { FVector CameraToCenter = AbilityCenter - CameraLocation; float DotToCenter = FVector::DotProduct(CameraToCenter, CameraDirection); if (DotToCenter >= 0) //If this fails, we're pointed away from the center, but we might be inside the sphere and able to find a good exit point. { float DistanceSquared = CameraToCenter.SizeSquared() - (DotToCenter * DotToCenter); float RadiusSquared = (AbilityRange * AbilityRange); if (DistanceSquared <= RadiusSquared) { float DistanceFromCamera = FMath::Sqrt(RadiusSquared - DistanceSquared); float DistanceAlongRay = DotToCenter + DistanceFromCamera; //Subtracting instead of adding will get the other intersection point ClippedPosition = CameraLocation + (DistanceAlongRay * CameraDirection); //Cam aim point clipped to range sphere return true; } } return false; } void AOWSGameplayAbilityTargetActor_Tr::StartTargeting(UGameplayAbility* InAbility) { Super::StartTargeting(InAbility); SourceActor = InAbility->GetCurrentActorInfo()->AvatarActor.Get(); if (ReticleClass) { AGameplayAbilityWorldReticle* SpawnedReticleActor = GetWorld()->SpawnActor<AGameplayAbilityWorldReticle>(ReticleClass, GetActorLocation(), GetActorRotation()); if (SpawnedReticleActor) { SpawnedReticleActor->InitializeReticle(this, MasterPC, ReticleParams); ReticleActor = SpawnedReticleActor; // This is to catch cases of playing on a listen server where we are using a replicated reticle actor. // (In a client controlled player, this would only run on the client and therefor never replicate. If it runs // on a listen server, the reticle actor may replicate. We want consistancy between client/listen server players. // Just saying 'make the reticle actor non replicated' isnt a good answer, since we want to mix and match reticle // actors and there may be other targeting types that want to replicate the same reticle actor class). if (!ShouldProduceTargetDataOnServer) { SpawnedReticleActor->SetReplicates(false); } } } } void AOWSGameplayAbilityTargetActor_Tr::Tick(float DeltaSeconds) { // very temp - do a mostly hardcoded trace from the source actor if (SourceActor) { FHitResult HitResult = PerformTrace(SourceActor); FVector EndPoint = HitResult.Component.IsValid() ? HitResult.ImpactPoint : HitResult.TraceEnd; #if ENABLE_DRAW_DEBUG if (bDebug) { DrawDebugLine(GetWorld(), SourceActor->GetActorLocation(), EndPoint, FColor::Green, false); DrawDebugSphere(GetWorld(), EndPoint, 16, 10, FColor::Green, false); } #endif // ENABLE_DRAW_DEBUG SetActorLocationAndRotation(EndPoint, SourceActor->GetActorRotation()); } } void AOWSGameplayAbilityTargetActor_Tr::ConfirmTargetingAndContinue() { check(ShouldProduceTargetData()); if (SourceActor) { bDebug = false; FGameplayAbilityTargetDataHandle Handle = MakeTargetData(PerformTrace(SourceActor)); TargetDataReadyDelegate.Broadcast(Handle); } } FGameplayAbilityTargetDataHandle AOWSGameplayAbilityTargetActor_Tr::MakeTargetData(const FHitResult& HitResult) const { /** Note: This will be cleaned up by the FGameplayAbilityTargetDataHandle (via an internal TSharedPtr) */ return StartLocation.MakeTargetDataHandleFromHitResult(OwningAbility, HitResult); }
/* * Copyright 2008-2014 NVIDIA Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <cusp/detail/config.h> #include <thrust/system/detail/generic/select_system.h> #include <cusp/exception.h> #include <cusp/graph/breadth_first_search.h> #include <cusp/system/detail/adl/graph/breadth_first_search.h> #include <cusp/system/detail/generic/graph/breadth_first_search.h> namespace cusp { namespace graph { template <typename DerivedPolicy, typename MatrixType, typename ArrayType> void breadth_first_search(const thrust::detail::execution_policy_base<DerivedPolicy>& exec, const MatrixType& G, const typename MatrixType::index_type src, ArrayType& labels, const bool mark_levels) { using cusp::system::detail::generic::breadth_first_search; return breadth_first_search(thrust::detail::derived_cast(thrust::detail::strip_const(exec)), G, src, labels, mark_levels); } template<typename MatrixType, typename ArrayType> void breadth_first_search(const MatrixType& G, const typename MatrixType::index_type src, ArrayType& labels, const bool mark_levels) { using thrust::system::detail::generic::select_system; typedef typename MatrixType::memory_space System1; typedef typename ArrayType::memory_space System2; System1 system1; System2 system2; return cusp::graph::breadth_first_search(select_system(system1,system2), G, src, labels, mark_levels); } } // end namespace graph } // end namespace cusp
/* -- MAGMA (version 2.5.4) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date October 2020 @generated from magmablas/zgemm_batched.cpp, normal z -> s, Thu Oct 8 23:05:36 2020 @author Jakub Kurzak @author Stan Tomov @author Mark Gates @author Azzam Haidar [zcds]gemm_fermi.cu defines the CPU driver. [zcds]gemm_fermi_kernels.h defines the block sizes for each precision. gemm_stencil_defs.h defines types and functions for precision-independent code. These files are included multiple times, once for each transpose version. gemm_stencil.cuh defines the GPU kernel (device function). gemm_kernel_batched.cuh defines the GPU kernel (global function). The batched version uses gemm_kernel_batched.cuh instead of gemm_kernel.cuh. */ #include "magma_internal.h" #include "commonblas_s.h" #define PRECISION_s void magma_sgemm_batched_core( magma_trans_t transA, magma_trans_t transB, magma_int_t m, magma_int_t n, magma_int_t k, float alpha, float const * const * dA_array, magma_int_t Ai, magma_int_t Aj, magma_int_t ldda, float const * const * dB_array, magma_int_t Bi, magma_int_t Bj, magma_int_t lddb, float beta, float **dC_array, magma_int_t Ci, magma_int_t Cj, magma_int_t lddc, magma_int_t batchCount, magma_queue_t queue ) { magma_int_t use_cublas = magma_srecommend_cublas_gemm_batched(transA, transB, m, n, k); magma_int_t zero_offset = (Ai == 0 && Aj == 0 && Bi == 0 && Bj == 0 && Ci == 0 && Cj == 0); if(use_cublas){ if(zero_offset){ cublasSgemmBatched( queue->cublas_handle(), cublas_trans_const(transA), cublas_trans_const(transB), int(m), int(n), int(k), &alpha, (const float**)dA_array, int(ldda), (const float**)dB_array, int(lddb), &beta, dC_array, int(lddc), int(batchCount) ); } else{ float** dAarray = (float**)queue->get_dAarray(); float** dBarray = (float**)queue->get_dBarray(); float** dCarray = (float**)queue->get_dCarray(); magma_int_t max_batchCount = queue->get_maxBatch(); for(magma_int_t i = 0; i < batchCount; i+=max_batchCount){ magma_int_t batch = min(max_batchCount, batchCount-i); magma_sdisplace_pointers(dAarray, (float**)dA_array + i, ldda, Ai, Aj, batch, queue); magma_sdisplace_pointers(dBarray, (float**)dB_array + i, lddb, Bi, Bj, batch, queue); magma_sdisplace_pointers(dCarray, (float**)dC_array + i, lddc, Ci, Cj, batch, queue); cublasSgemmBatched( queue->cublas_handle(), cublas_trans_const(transA), cublas_trans_const(transB), int(m), int(n), int(k), &alpha, (const float**)dAarray, int(ldda), (const float**)dBarray, int(lddb), &beta, dCarray, int(lddc), int(batch) ); } } } else{ magmablas_sgemm_batched_core( transA, transB, m, n, k, alpha, dA_array, Ai, Aj, ldda, dB_array, Bi, Bj, lddb, beta, dC_array, Ci, Cj, lddc, batchCount, queue); } } /***************************************************************************//** Purpose ------- SGEMM performs one of the matrix-matrix operations C = alpha*op( A )*op( B ) + beta*C, where op( X ) is one of op( X ) = X or op( X ) = X**T or op( X ) = X**H, alpha and beta are scalars, and A, B and C are matrices, with op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. Parameters ---------- @param[in] transA magma_trans_t. On entry, transA specifies the form of op( A ) to be used in the matrix multiplication as follows: - = MagmaNoTrans: op( A ) = A. - = MagmaTrans: op( A ) = A**T. - = MagmaConjTrans: op( A ) = A**H. @param[in] transB magma_trans_t. On entry, transB specifies the form of op( B ) to be used in the matrix multiplication as follows: - = MagmaNoTrans: op( B ) = B. - = MagmaTrans: op( B ) = B**T. - = MagmaConjTrans: op( B ) = B**H. @param[in] m INTEGER. On entry, M specifies the number of rows of the matrix op( A ) and of the matrix C. M must be at least zero. @param[in] n INTEGER. On entry, N specifies the number of columns of the matrix op( B ) and the number of columns of the matrix C. N must be at least zero. @param[in] k INTEGER. On entry, K specifies the number of columns of the matrix op( A ) and the number of rows of the matrix op( B ). K must be at least zero. @param[in] alpha REAL On entry, ALPHA specifies the scalar alpha. @param[in] dA_array Array of pointers, dimension (batchCount). Each is a REAL array A of DIMENSION ( ldda, ka ), where ka is k when transA = MagmaNoTrans, and is m otherwise. Before entry with transA = MagmaNoTrans, the leading m by k part of the array A must contain the matrix A, otherwise the leading k by m part of the array A must contain the matrix A. @param[in] ldda INTEGER. On entry, ldda specifies the first dimension of each array A as declared in the calling (sub) program. When transA = MagmaNoTrans then ldda must be at least max( 1, m ), otherwise ldda must be at least max( 1, k ). @param[in] dB_array Array of pointers, dimension (batchCount). Each is a REAL array B of DIMENSION ( lddb, kb ), where kb is n when transB = MagmaNoTrans, and is k otherwise. Before entry with transB = MagmaNoTrans, the leading k by n part of the array B must contain the matrix B, otherwise the leading n by k part of the array B must contain the matrix B. @param[in] lddb INTEGER. On entry, lddb specifies the first dimension of each array B as declared in the calling (sub) program. When transB = MagmaNoTrans then lddb must be at least max( 1, k ), otherwise lddb must be at least max( 1, n ). @param[in] beta REAL. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then C need not be set on input. @param[in,out] dC_array Array of pointers, dimension (batchCount). Each is a REAL array C of DIMENSION ( lddc, n ). Before entry, the leading m by n part of the array C must contain the matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the array C is overwritten by the m by n matrix ( alpha*op( A )*op( B ) + beta*C ). @param[in] lddc INTEGER. On entry, lddc specifies the first dimension of each array C as declared in the calling (sub) program. lddc must be at least max( 1, m ). @param[in] batchCount INTEGER The number of matrices to operate on. @param[in] queue magma_queue_t Queue to execute in. @ingroup magma_gemm_batched *******************************************************************************/ extern "C" void magmablas_sgemm_batched( magma_trans_t transA, magma_trans_t transB, magma_int_t m, magma_int_t n, magma_int_t k, float alpha, float const * const * dA_array, magma_int_t ldda, float const * const * dB_array, magma_int_t lddb, float beta, float **dC_array, magma_int_t lddc, magma_int_t batchCount, magma_queue_t queue ) { magmablas_sgemm_batched_core( transA, transB, m, n, k, alpha, dA_array, 0, 0, ldda, dB_array, 0, 0, lddb, beta, dC_array, 0, 0, lddc, batchCount, queue ); } /******************************************************************************/ extern "C" void magmablas_sgemm_batched_strided( magma_trans_t transA, magma_trans_t transB, magma_int_t m, magma_int_t n, magma_int_t k, float alpha, float const * dA, magma_int_t ldda, magma_int_t strideA, float const * dB, magma_int_t lddb, magma_int_t strideB, float beta, float * dC, magma_int_t lddc, magma_int_t strideC, magma_int_t batchCount, magma_queue_t queue ) { float** dAarray = (float**)queue->get_dAarray(); float** dBarray = (float**)queue->get_dBarray(); float** dCarray = (float**)queue->get_dCarray(); magma_int_t max_batchCount = queue->get_maxBatch(); for(magma_int_t i = 0; i < batchCount; i+=max_batchCount){ magma_int_t batch = min(max_batchCount, batchCount-i); magma_sset_pointer(dAarray, (float*)(dA + i * strideA), ldda, 0, 0, strideA, batch, queue); magma_sset_pointer(dBarray, (float*)(dB + i * strideB), lddb, 0, 0, strideB, batch, queue); magma_sset_pointer(dCarray, dC + i * strideC, lddc, 0, 0, strideC, batch, queue); magmablas_sgemm_batched_core( transA, transB, m, n, k, alpha, dAarray, 0, 0, ldda, dBarray, 0, 0, lddb, beta, dCarray, 0, 0, lddc, batch, queue); } } /******************************************************************************/ extern "C" void magma_sgemm_batched( magma_trans_t transA, magma_trans_t transB, magma_int_t m, magma_int_t n, magma_int_t k, float alpha, float const * const * dA_array, magma_int_t ldda, float const * const * dB_array, magma_int_t lddb, float beta, float **dC_array, magma_int_t lddc, magma_int_t batchCount, magma_queue_t queue ) { magma_sgemm_batched_core( transA, transB, m, n, k, alpha, dA_array, 0, 0, ldda, dB_array, 0, 0, lddb, beta, dC_array, 0, 0, lddc, batchCount, queue ); }
#include <DataTypes/DataTypeFactory.h> #include <DataTypes/getLeastSupertype.h> #include <DataTypes/getMostSubtype.h> #include <sstream> #pragma GCC diagnostic ignored "-Wmissing-declarations" #include <gtest/gtest.h> namespace DB { static bool operator==(const IDataType & left, const IDataType & right) { return left.equals(right); } std::ostream & operator<<(std::ostream & ostr, const IDataType & dt) { return ostr << dt.getName(); } } using namespace DB; static auto typeFromString(const std::string & str) { auto & data_type_factory = DataTypeFactory::instance(); return data_type_factory.get(str); }; static auto typesFromString(const std::string & str) { std::istringstream data_types_stream(str); DataTypes data_types; std::string data_type; while (data_types_stream >> data_type) data_types.push_back(typeFromString(data_type)); return data_types; }; struct TypesTestCase { const char * from_types; const char * expected_type = nullptr; }; std::ostream & operator<<(std::ostream & ostr, const TypesTestCase & test_case) { ostr << "TypesTestCase{\"" << test_case.from_types << "\", "; if (test_case.expected_type) ostr << "\"" << test_case.expected_type << "\""; else ostr << "nullptr"; return ostr << "}"; } class TypeTest : public ::testing::TestWithParam<TypesTestCase> { public: void SetUp() { const auto & p = GetParam(); from_types = typesFromString(p.from_types); if (p.expected_type) expected_type = typeFromString(p.expected_type); else expected_type.reset(); } public: DataTypes from_types; DataTypePtr expected_type; }; class LeastSuperTypeTest : public TypeTest {}; TEST_P(LeastSuperTypeTest, getLeastSupertype) { if (this->expected_type) { ASSERT_EQ(*this->expected_type, *getLeastSupertype(this->from_types)); } else { EXPECT_ANY_THROW(getLeastSupertype(this->from_types)); } } class MostSubtypeTest : public TypeTest {}; TEST_P(MostSubtypeTest, getLeastSupertype) { if (this->expected_type) { ASSERT_EQ(*this->expected_type, *getMostSubtype(this->from_types)); } else { EXPECT_ANY_THROW(getMostSubtype(this->from_types, true)); } } INSTANTIATE_TEST_SUITE_P(data_type, LeastSuperTypeTest, ::testing::ValuesIn( std::initializer_list<TypesTestCase>{ {"", "Nothing"}, {"Nothing", "Nothing"}, {"UInt8", "UInt8"}, {"UInt8 UInt8", "UInt8"}, {"Int8 Int8", "Int8"}, {"UInt8 Int8", "Int16"}, {"UInt8 Int16", "Int16"}, {"UInt8 UInt32 UInt64", "UInt64"}, {"Int8 Int32 Int64", "Int64"}, {"UInt8 UInt32 Int64", "Int64"}, {"Float32 Float64", "Float64"}, {"Float32 UInt16 Int16", "Float32"}, {"Float32 UInt16 Int32", "Float64"}, {"Float32 Int16 UInt32", "Float64"}, {"Date Date", "Date"}, {"Date DateTime", "DateTime"}, {"Date DateTime64(3)", "DateTime64(3)"}, {"DateTime DateTime64(3)", "DateTime64(3)"}, {"DateTime DateTime64(0)", "DateTime64(0)"}, {"DateTime64(9) DateTime64(3)", "DateTime64(3)"}, {"DateTime DateTime64(12)", "DateTime64(8)"}, {"Date DateTime64(15)", "DateTime64(13)"}, {"String FixedString(32) FixedString(8)", "String"}, {"Array(UInt8) Array(UInt8)", "Array(UInt8)"}, {"Array(UInt8) Array(Int8)", "Array(Int16)"}, {"Array(Float32) Array(Int16) Array(UInt32)", "Array(Float64)"}, {"Array(Array(UInt8)) Array(Array(UInt8))", "Array(Array(UInt8))"}, {"Array(Array(UInt8)) Array(Array(Int8))", "Array(Array(Int16))"}, {"Array(Date) Array(DateTime)", "Array(DateTime)"}, {"Array(String) Array(FixedString(32))", "Array(String)"}, {"Nullable(Nothing) Nothing", "Nullable(Nothing)"}, {"Nullable(UInt8) Int8", "Nullable(Int16)"}, {"Nullable(Nothing) UInt8 Int8", "Nullable(Int16)"}, {"Tuple(Int8,UInt8) Tuple(UInt8,Int8)", "Tuple(Int16,Int16)"}, {"Tuple(Nullable(Nothing)) Tuple(Nullable(UInt8))", "Tuple(Nullable(UInt8))"}, {"Int8 String", nullptr}, {"Int64 UInt64", nullptr}, {"Float32 UInt64", nullptr}, {"Float64 Int64", nullptr}, {"Tuple(Int64) Tuple(UInt64)", nullptr}, {"Tuple(Int64,Int8) Tuple(UInt64)", nullptr}, {"Array(Int64) Array(String)", nullptr}, } ) ); INSTANTIATE_TEST_SUITE_P(data_type, MostSubtypeTest, ::testing::ValuesIn( std::initializer_list<TypesTestCase>{ {"", "Nothing"}, {"Nothing", "Nothing"}, {"UInt8", "UInt8"}, {"UInt8 UInt8", "UInt8"}, {"Int8 Int8", "Int8"}, {"UInt8 Int8", "UInt8"}, {"Int8 UInt16", "Int8"}, {"UInt8 UInt32 UInt64", "UInt8"}, {"Int8 Int32 Int64", "Int8"}, {"UInt8 Int64 UInt64", "UInt8"}, {"Float32 Float64", "Float32"}, {"Float32 UInt16 Int16", "UInt16"}, {"Float32 UInt16 Int32", "UInt16"}, {"Float32 Int16 UInt32", "Int16"}, {"DateTime DateTime", "DateTime"}, {"Date DateTime", "Date"}, {"String FixedString(8)", "FixedString(8)"}, {"FixedString(16) FixedString(8)", "Nothing"}, {"Array(UInt8) Array(UInt8)", "Array(UInt8)"}, {"Array(UInt8) Array(Int8)", "Array(UInt8)"}, {"Array(Float32) Array(Int16) Array(UInt32)", "Array(Int16)"}, {"Array(Array(UInt8)) Array(Array(UInt8))", "Array(Array(UInt8))"}, {"Array(Array(UInt8)) Array(Array(Int8))", "Array(Array(UInt8))"}, {"Array(Date) Array(DateTime)", "Array(Date)"}, {"Array(String) Array(FixedString(32))", "Array(FixedString(32))"}, {"Array(String) Array(FixedString(32))", "Array(FixedString(32))"}, {"Nullable(Nothing) Nothing", "Nothing"}, {"Nullable(UInt8) Int8", "UInt8"}, {"Nullable(Nothing) UInt8 Int8", "Nothing"}, {"Nullable(UInt8) Nullable(Int8)", "Nullable(UInt8)"}, {"Nullable(Nothing) Nullable(Int8)", "Nullable(Nothing)"}, {"Tuple(Int8,UInt8) Tuple(UInt8,Int8)", "Tuple(UInt8,UInt8)"}, {"Tuple(Nullable(Nothing)) Tuple(Nullable(UInt8))", "Tuple(Nullable(Nothing))"}, {"Int8 String", nullptr}, {"Nothing", nullptr}, {"FixedString(16) FixedString(8) String", nullptr}, } ) );
/*========================================================================= * * Copyright Insight Software Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #include "itkFFTTest.h" // Test FFT using VNL Libraries. The test is performed for two 3D // arrays, one of them having the same dimension(4,4,4) and the other // having different dimensions (3,4,5). Images are created with // different dimensions in the test function based on the second // template argument and the size of these dimensions are taken from // the array. The data types used are float and double. int itkVnlFFTTest(int, char *[]) { typedef itk::Image< float, 1> ImageF1; typedef itk::Image< std::complex<float>, 1> ImageCF1; typedef itk::Image< float, 2> ImageF2; typedef itk::Image< std::complex<float>, 2> ImageCF2; typedef itk::Image< float, 3> ImageF3; typedef itk::Image< std::complex<float>, 3> ImageCF3; typedef itk::Image< float, 4> ImageF4; typedef itk::Image< std::complex<float>, 4> ImageCF4; typedef itk::Image< double, 1> ImageD1; typedef itk::Image< std::complex<double>, 1> ImageCD1; typedef itk::Image< double, 2> ImageD2; typedef itk::Image< std::complex<double>, 2> ImageCD2; typedef itk::Image< double, 3> ImageD3; typedef itk::Image< std::complex<double>, 3> ImageCD3; typedef itk::Image< double, 4> ImageD4; typedef itk::Image< std::complex<double>, 4> ImageCD4; unsigned int SizeOfDimensions1[] = { 4,4,4,4 }; unsigned int SizeOfDimensions2[] = { 3,5,4 }; unsigned int SizeOfDimensions3[] = { 7,6,4 }; // Should fail int rval = 0; std::cerr << "Vnl float,1 (4,4,4)" << std::endl; if((test_fft<float,1, itk::VnlForwardFFTImageFilter<ImageF1> , itk::VnlInverseFFTImageFilter<ImageCF1> >(SizeOfDimensions1)) != 0) { rval++; std::cerr << "--------------------- Failed!" << std::endl; } std::cerr << "Vnl float,2 (4,4,4)" << std::endl; if((test_fft<float,2, itk::VnlForwardFFTImageFilter<ImageF2> , itk::VnlInverseFFTImageFilter<ImageCF2> >(SizeOfDimensions1)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl float,3 (4,4,4)" << std::endl; if((test_fft<float,3, itk::VnlForwardFFTImageFilter<ImageF3> , itk::VnlInverseFFTImageFilter<ImageCF3> >(SizeOfDimensions1)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl float,4 (4,4,4)" << std::endl; if((test_fft<float,4, itk::VnlForwardFFTImageFilter<ImageF4> , itk::VnlInverseFFTImageFilter<ImageCF4> >(SizeOfDimensions1)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl double,1 (4,4,4)" << std::endl; if((test_fft<double,1, itk::VnlForwardFFTImageFilter<ImageD1> , itk::VnlInverseFFTImageFilter<ImageCD1> >(SizeOfDimensions1)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl double,2 (4,4,4)" << std::endl; if((test_fft<double,2, itk::VnlForwardFFTImageFilter<ImageD2> , itk::VnlInverseFFTImageFilter<ImageCD2> >(SizeOfDimensions1)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl double,3 (4,4,4)" << std::endl; if((test_fft<double,3, itk::VnlForwardFFTImageFilter<ImageD3> , itk::VnlInverseFFTImageFilter<ImageCD3> >(SizeOfDimensions1)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl float,1 (3,5,4)" << std::endl; if((test_fft<float,1, itk::VnlForwardFFTImageFilter<ImageF1> , itk::VnlInverseFFTImageFilter<ImageCF1> >(SizeOfDimensions2)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl float,2 (3,5,4)" << std::endl; if((test_fft<float,2, itk::VnlForwardFFTImageFilter<ImageF2> , itk::VnlInverseFFTImageFilter<ImageCF2> >(SizeOfDimensions2)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl float,3 (3,5,4)" << std::endl; if((test_fft<float,3, itk::VnlForwardFFTImageFilter<ImageF3> , itk::VnlInverseFFTImageFilter<ImageCF3> >(SizeOfDimensions2)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl double,1 (3,5,4)" << std::endl; if((test_fft<double,1, itk::VnlForwardFFTImageFilter<ImageD1> , itk::VnlInverseFFTImageFilter<ImageCD1> >(SizeOfDimensions2)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl double,2 (3,5,4)" << std::endl; if((test_fft<double,2, itk::VnlForwardFFTImageFilter<ImageD2> , itk::VnlInverseFFTImageFilter<ImageCD2> >(SizeOfDimensions2)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } std::cerr << "Vnl double,3 (3,5,4)" << std::endl; if((test_fft<double,3, itk::VnlForwardFFTImageFilter<ImageD3> , itk::VnlInverseFFTImageFilter<ImageCD3> >(SizeOfDimensions2)) != 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } // These tests should fail. std::cerr << "Vnl float,1 (7,6,4)" << std::endl; if((test_fft<float,1, itk::VnlForwardFFTImageFilter<ImageF1> , itk::VnlInverseFFTImageFilter<ImageCF1> >(SizeOfDimensions3)) == 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } else { std::cerr << "Caught expected size error." << std::endl; } std::cerr << "Vnl float,2 (7,6,4)" << std::endl; if((test_fft<float,2, itk::VnlForwardFFTImageFilter<ImageF2> , itk::VnlInverseFFTImageFilter<ImageCF2> >(SizeOfDimensions3)) == 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } else { std::cerr << "Caught expected size error." << std::endl; } std::cerr << "Vnl float,3 (7,6,4)" << std::endl; if((test_fft<float,3, itk::VnlForwardFFTImageFilter<ImageF3> , itk::VnlInverseFFTImageFilter<ImageCF3> >(SizeOfDimensions3)) == 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } else { std::cerr << "Caught expected size error." << std::endl; } std::cerr << "Vnl double,1 (7,6,4)" << std::endl; if((test_fft<double,1, itk::VnlForwardFFTImageFilter<ImageD1> , itk::VnlInverseFFTImageFilter<ImageCD1> >(SizeOfDimensions3)) == 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } else { std::cerr << "Caught expected size error." << std::endl; } std::cerr << "Vnl double,2 (7,6,4)" << std::endl; if((test_fft<double,2, itk::VnlForwardFFTImageFilter<ImageD2> , itk::VnlInverseFFTImageFilter<ImageCD2> >(SizeOfDimensions3)) == 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } else { std::cerr << "Caught expected size error." << std::endl; } std::cerr << "Vnl double,3 (7,6,4)" << std::endl; if((test_fft<double,3, itk::VnlForwardFFTImageFilter<ImageD3> , itk::VnlInverseFFTImageFilter<ImageCD3> >(SizeOfDimensions3)) == 0) { std::cerr << "--------------------- Failed!" << std::endl; rval++; } else { std::cerr << "Caught expected size error." << std::endl; } return rval == 0 ? 0 : -1; }
#include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <iterator> using namespace std; int main_03_02() { int n; cin >> n; vector<string> v(n); copy_n(istream_iterator<string>(cin), n, begin(v)); sort(begin(v), end(v), [](const string& l, const string& r) { return lexicographical_compare(begin(l), end(l), begin(r), end(r), [](char lc, char rc) { return tolower(lc) < tolower(rc); }); }); copy_n(begin(v), n, ostream_iterator<string>(cout, " ")); return 0; }
/* * Open Chinese Convert * * Copyright 2010-2014 BYVoid <byvoid@byvoid.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "DictEntry.hpp" using namespace opencc; string MultiValueDictEntry::ToString() const { // TODO escape space size_t i = 0; size_t length = Values().size(); std::ostringstream buffer; buffer << Key() << '\t'; for each (const char* value in Values()) { buffer << value; if (i < length - 1) { buffer << ' '; } i++; } return buffer.str(); }
//===-- AMDGPUMCTargetDesc.cpp - AMDGPU Target Descriptions ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // /// \file /// \brief This file provides AMDGPU specific target descriptions. // //===----------------------------------------------------------------------===// #include "AMDGPUMCTargetDesc.h" #include "AMDGPUELFStreamer.h" #include "AMDGPUMCAsmInfo.h" #include "AMDGPUTargetStreamer.h" #include "InstPrinter/AMDGPUInstPrinter.h" #include "SIDefines.h" #include "llvm/MC/MCCodeGenInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCInstrInfo.h" #include "llvm/MC/MCRegisterInfo.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSubtargetInfo.h" #include "llvm/MC/MachineLocation.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/TargetRegistry.h" using namespace llvm; #define GET_INSTRINFO_MC_DESC #include "AMDGPUGenInstrInfo.inc" #define GET_SUBTARGETINFO_MC_DESC #include "AMDGPUGenSubtargetInfo.inc" #define GET_REGINFO_MC_DESC #include "AMDGPUGenRegisterInfo.inc" static MCInstrInfo *createAMDGPUMCInstrInfo() { MCInstrInfo *X = new MCInstrInfo(); InitAMDGPUMCInstrInfo(X); return X; } static MCRegisterInfo *createAMDGPUMCRegisterInfo(const Triple &TT) { MCRegisterInfo *X = new MCRegisterInfo(); InitAMDGPUMCRegisterInfo(X, 0); return X; } static MCSubtargetInfo * createAMDGPUMCSubtargetInfo(const Triple &TT, StringRef CPU, StringRef FS) { return createAMDGPUMCSubtargetInfoImpl(TT, CPU, FS); } static MCCodeGenInfo *createAMDGPUMCCodeGenInfo(const Triple &TT, Reloc::Model RM, CodeModel::Model CM, CodeGenOpt::Level OL) { MCCodeGenInfo *X = new MCCodeGenInfo(); X->initMCCodeGenInfo(RM, CM, OL); return X; } static MCInstPrinter *createAMDGPUMCInstPrinter(const Triple &T, unsigned SyntaxVariant, const MCAsmInfo &MAI, const MCInstrInfo &MII, const MCRegisterInfo &MRI) { return new AMDGPUInstPrinter(MAI, MII, MRI); } static MCTargetStreamer *createAMDGPUAsmTargetStreamer(MCStreamer &S, formatted_raw_ostream &OS, MCInstPrinter *InstPrint, bool isVerboseAsm) { return new AMDGPUTargetAsmStreamer(S, OS); } static MCTargetStreamer * createAMDGPUObjectTargetStreamer( MCStreamer &S, const MCSubtargetInfo &STI) { return new AMDGPUTargetELFStreamer(S); } static MCStreamer *createMCStreamer(const Triple &T, MCContext &Context, MCAsmBackend &MAB, raw_pwrite_stream &OS, MCCodeEmitter *Emitter, bool RelaxAll) { if (T.getOS() == Triple::AMDHSA) return createAMDGPUELFStreamer(Context, MAB, OS, Emitter, RelaxAll); return createELFStreamer(Context, MAB, OS, Emitter, RelaxAll); } extern "C" void LLVMInitializeAMDGPUTargetMC() { for (Target *T : {&TheAMDGPUTarget, &TheGCNTarget}) { RegisterMCAsmInfo<AMDGPUMCAsmInfo> X(*T); TargetRegistry::RegisterMCCodeGenInfo(*T, createAMDGPUMCCodeGenInfo); TargetRegistry::RegisterMCInstrInfo(*T, createAMDGPUMCInstrInfo); TargetRegistry::RegisterMCRegInfo(*T, createAMDGPUMCRegisterInfo); TargetRegistry::RegisterMCSubtargetInfo(*T, createAMDGPUMCSubtargetInfo); TargetRegistry::RegisterMCInstPrinter(*T, createAMDGPUMCInstPrinter); TargetRegistry::RegisterMCAsmBackend(*T, createAMDGPUAsmBackend); TargetRegistry::RegisterELFStreamer(*T, createMCStreamer); } // R600 specific registration TargetRegistry::RegisterMCCodeEmitter(TheAMDGPUTarget, createR600MCCodeEmitter); // GCN specific registration TargetRegistry::RegisterMCCodeEmitter(TheGCNTarget, createSIMCCodeEmitter); TargetRegistry::RegisterAsmTargetStreamer(TheGCNTarget, createAMDGPUAsmTargetStreamer); TargetRegistry::RegisterObjectTargetStreamer(TheGCNTarget, createAMDGPUObjectTargetStreamer); }
#include <moveit_cartesian_plan_plugin/widgets/path_planning_widget.hpp> #include <moveit_cartesian_plan_plugin/point_tree_model.hpp> #include <moveit_cartesian_plan_plugin/generate_cartesian_path.hpp> namespace moveit_cartesian_plan_plugin { namespace widgets { PathPlanningWidget::PathPlanningWidget(std::string ns): param_ns_(ns) { /*! Constructor which calls the init() function. */ init(); } PathPlanningWidget::~PathPlanningWidget() { } void PathPlanningWidget::init() { /*! Initializing the RQT UI. Setting up the default values for the UI components: - Default Values for the MoveIt and Cartesian Path - Validators for the MoveIt and Cartesian Path entries - the MoveIt planning time allowed range is set from 1.0 to 1000.0 seconds - the MoveIt StepSize allowed range is set from 0.001 to 0.1 meters - the Jump Threshold for the IK solutions is set from 0.0 to 10000.0 . . */ ui_.setupUi(this); ui_.txtPointName->setText("0"); //set up the default values for the MoveIt and Cartesian Path ui_.lnEdit_PlanTime->setText("5.0"); ui_.lnEdit_StepSize->setText("0.01"); ui_.lnEdit_JmpThresh->setText("0.0"); //set validators for the entries ui_.lnEdit_PlanTime->setValidator(new QDoubleValidator(1.0,100.0,2,ui_.lnEdit_PlanTime)); ui_.lnEdit_StepSize->setValidator(new QDoubleValidator(0.001,0.1,3,ui_.lnEdit_StepSize)); ui_.lnEdit_JmpThresh->setValidator(new QDoubleValidator(0.0,1000.0,3,ui_.lnEdit_JmpThresh)); //set progress bar when loading way-points from a yaml file. Could be nice when loading large way-points files ui_.progressBar->setRange(0,100); ui_.progressBar->setValue(0); ui_.progressBar->hide(); QStringList headers; headers<<tr("Point")<<tr("Position (m)")<<tr("Orientation (deg)"); PointTreeModel *model = new PointTreeModel(headers,"add_point_button"); ui_.treeView->setModel(model); ui_.btn_LoadPath->setToolTip(tr("Load Way-Points from a file")); ui_.btn_SavePath->setToolTip(tr("Save Way-Points to a file")); ui_.btnAddPoint->setToolTip(tr("Add a new Way-Point")); ui_.btnRemovePoint->setToolTip(tr("Remove a selected Way-Point")); connect(ui_.btnAddPoint,SIGNAL(clicked()),this,SLOT(pointAddUI())); connect(ui_.btnRemovePoint,SIGNAL(clicked()),this,SLOT(pointDeletedUI())); connect(ui_.treeView->selectionModel(),SIGNAL(currentChanged(const QModelIndex& , const QModelIndex& )),this,SLOT(selectedPoint(const QModelIndex& , const QModelIndex&))); connect(ui_.treeView->selectionModel(),SIGNAL(currentChanged(const QModelIndex& , const QModelIndex& )),this,SLOT(treeViewDataChanged(const QModelIndex& , const QModelIndex&))); connect(ui_.targetPoint,SIGNAL(clicked()),this,SLOT(sendCartTrajectoryParamsFromUI())); connect(ui_.targetPoint,SIGNAL(clicked()),this,SLOT(parseWayPointBtn_slot())); connect(ui_.btn_LoadPath,SIGNAL(clicked()),this,SLOT(loadPointsFromFile())); connect(ui_.btn_SavePath,SIGNAL(clicked()),this,SLOT(savePointsToFile())); connect(ui_.btn_ClearAllPoints,SIGNAL(clicked()),this,SLOT(clearAllPoints_slot())); connect(ui_.btn_moveToHome,SIGNAL(clicked()),this,SLOT(moveToHomeFromUI())); connect(ui_.combo_planGroup,SIGNAL(currentIndexChanged ( int )),this,SLOT(selectedPlanGroup(int))); } void PathPlanningWidget::getCartPlanGroup(std::vector< std::string > group_names) { ROS_INFO("setting the name of the planning group in combo box"); int lenght_group = group_names.size(); for(int i=0;i<lenght_group;i++) { ui_.combo_planGroup->addItem(QString::fromStdString(group_names[i])); } } void PathPlanningWidget::selectedPlanGroup(int index) { Q_EMIT sendSendSelectedPlanGroup(index); } void PathPlanningWidget::sendCartTrajectoryParamsFromUI() { /*! This function takes care of sending the User Entered parameters from the RQT to the Cartesian Path Planner. */ double plan_time_,cart_step_size_,cart_jump_thresh_; bool moveit_replan_,avoid_collisions_; plan_time_ = ui_.lnEdit_PlanTime->text().toDouble(); cart_step_size_ = ui_.lnEdit_StepSize->text().toDouble(); cart_jump_thresh_ = ui_.lnEdit_JmpThresh->text().toDouble(); moveit_replan_ = ui_.chk_AllowReplanning->isChecked(); avoid_collisions_ = ui_.chk_AvoidColl->isChecked(); Q_EMIT cartesianPathParamsFromUI_signal(plan_time_,cart_step_size_,cart_jump_thresh_,moveit_replan_,avoid_collisions_); } void PathPlanningWidget::pointRange() { /*! Get the current range of points from the TreeView. This is essential for setting up the number of the item that should be run next. Dealing with the data in the TreeView */ QAbstractItemModel *model=ui_.treeView->model(); int count = model->rowCount()-1; ui_.txtPointName->setValidator(new QIntValidator(1,count,ui_.txtPointName)); } void PathPlanningWidget::initTreeView() { /*! Initialize the Qt TreeView and set the initial value of the User Interaction arrow. */ QAbstractItemModel *model=ui_.treeView->model(); model->setData(model->index(0,0,QModelIndex()),QVariant("add_point_button"),Qt::EditRole); //update the validator for the lineEdit Point pointRange(); } void PathPlanningWidget::selectedPoint(const QModelIndex& current, const QModelIndex& previous) { /*! Get the selected point from the TreeView. This is used for updating the information of the lineEdit which informs gives the number of the currently selected Way-Point. */ ROS_INFO_STREAM("Selected Index Changed"<<current.row()); if(current.parent()==QModelIndex()) ui_.txtPointName->setText(QString::number(current.row())); else if((current.parent()!=QModelIndex()) && (current.parent().parent() == QModelIndex())) ui_.txtPointName->setText(QString::number(current.parent().row())); else ui_.txtPointName->setText(QString::number(current.parent().parent().row())); } void PathPlanningWidget::pointAddUI() { /*! Function for adding new Way-Point from the RQT Widget. The user can set the position and orientation of the Way-Point by entering their values in the LineEdit fields. This function is connected to the AddPoint button click() signal and sends the addPoint(point_pos) to inform the RViz enviroment that a new Way-Point has been added. */ double x,y,z,rx,ry,rz; x = ui_.LineEditX->text().toDouble(); y = ui_.LineEditY->text().toDouble(); z = ui_.LineEditZ->text().toDouble(); rx = DEG2RAD(ui_.LineEditRx->text().toDouble()); ry = DEG2RAD(ui_.LineEditRy->text().toDouble()); rz = DEG2RAD(ui_.LineEditRz->text().toDouble()); // // create transform tf::Transform point_pos( tf::Transform(tf::createQuaternionFromRPY(rx,ry,rz),tf::Vector3(x,y,z))); Q_EMIT addPoint(point_pos); pointRange(); } void PathPlanningWidget::pointDeletedUI() { /*! Function for deleting a Way-Point from the RQT GUI. The name of the Way-Point that needs to be deleted corresponds to the txtPointName line edit field. This slot is connected to the Remove Point button signal. After completion of this function a signal is send to Inform the RViz enviroment that a Way-Point has been deleted from the RQT Widget. */ std::string marker_name; QString qtPointNr = ui_.txtPointName->text(); marker_name = qtPointNr.toUtf8().constData(); int marker_nr = atoi(marker_name.c_str()); if(strcmp(marker_name.c_str(),"0")!=0) { removeRow(marker_nr); pointRange(); Q_EMIT pointDelUI_signal(marker_name.c_str()); } } void PathPlanningWidget::insertRow(const tf::Transform& point_pos,const int count) { /*! Whenever we have a new Way-Point insereted either from the RViz or the RQT Widget the the TreeView needs to update the information and insert new row that corresponds to the new insered point. This function takes care of parsing the data recieved from the RViz or the RQT widget and creating new row with the appropriate data format and Children. One for the position giving us the current position of the Way-Point in all the axis. One child for the orientation giving us the Euler Angles of each axis. */ ROS_INFO("inserting new row in the TreeView"); QAbstractItemModel *model = ui_.treeView->model(); //convert the quartenion to roll pitch yaw angle tf::Vector3 p = point_pos.getOrigin(); tfScalar rx,ry,rz; point_pos.getBasis().getRPY(rx,ry,rz,1); if(count == 0) { model->insertRow(count,model->index(count, 0)); model->setData(model->index(0,0,QModelIndex()),QVariant("add_point_button"),Qt::EditRole); pointRange(); } else { if(!model->insertRow(count,model->index(count, 0))) //&& count==0 { return; } //set the strings of each axis of the position QString pos_x = QString::number(p.x()); QString pos_y = QString::number(p.y()); QString pos_z = QString::number(p.z()); //repeat that with the orientation QString orient_x = QString::number(RAD2DEG(rx)); QString orient_y = QString::number(RAD2DEG(ry)); QString orient_z = QString::number(RAD2DEG(rz)); model->setData(model->index(count,0),QVariant(count),Qt::EditRole); //add a child to the last inserted item. First add children in the treeview that //are just telling the user that if he expands them he can see details about the position and orientation of each point QModelIndex ind = model->index(count, 0); model->insertRows(0, 2, ind); QModelIndex chldind_pos = model->index(0, 0, ind); QModelIndex chldind_orient = model->index(1, 0, ind); model->setData(chldind_pos, QVariant("Position"), Qt::EditRole); model->setData(chldind_orient, QVariant("Orientation"), Qt::EditRole); //*****************************Set the children for the position********************************************************** //now add information about each child separately. For the position we have coordinates for X,Y,Z axis. //therefore we add 3 rows of information model->insertRows(0, 3, chldind_pos); //next we set up the data for each of these columns. First the names model->setData(model->index(0, 0, chldind_pos), QVariant("X:"), Qt::EditRole); model->setData(model->index(1, 0, chldind_pos), QVariant("Y:"), Qt::EditRole); model->setData(model->index(2, 0, chldind_pos), QVariant("Z:"), Qt::EditRole); //second we add the current position information, for each position axis separately model->setData(model->index(0, 1, chldind_pos), QVariant(pos_x), Qt::EditRole); model->setData(model->index(1, 1, chldind_pos), QVariant(pos_y), Qt::EditRole); model->setData(model->index(2, 1, chldind_pos), QVariant(pos_z), Qt::EditRole); //*************************************************************************************************************************** //*****************************Set the children for the orientation********************************************************** //now we repeat everything again,similar as the position for adding the children for the orientation model->insertRows(0, 3, chldind_orient); //next we set up the data for each of these columns. First the names model->setData(model->index(0, 0, chldind_orient), QVariant("Rx:"), Qt::EditRole); model->setData(model->index(1, 0, chldind_orient), QVariant("Ry:"), Qt::EditRole); model->setData(model->index(2, 0, chldind_orient), QVariant("Rz:"), Qt::EditRole); //second we add the current position information, for each position axis separately model->setData(model->index(0, 2, chldind_orient), QVariant(orient_x), Qt::EditRole); model->setData(model->index(1, 2, chldind_orient), QVariant(orient_y), Qt::EditRole); model->setData(model->index(2, 2, chldind_orient), QVariant(orient_z), Qt::EditRole); //**************************************************************************************************************************** pointRange(); } } void PathPlanningWidget::removeRow(int marker_nr) { /*! When the user deletes certain Way-Point either from the RViz or the RQT Widget the TreeView needs to delete that particular row and update the state of the TreeWidget. */ QAbstractItemModel *model = ui_.treeView->model(); model->removeRow(marker_nr,QModelIndex()); ROS_INFO_STREAM("deleting point nr: "<< marker_nr); for(int i=marker_nr;i<=model->rowCount();++i) { model->setData(model->index((i-1),0,QModelIndex()),QVariant((i-1)),Qt::EditRole); } //check how to properly set the selection ui_.treeView->selectionModel()->setCurrentIndex(model->index((model->rowCount()-1),0,QModelIndex()),QItemSelectionModel::ClearAndSelect); ui_.txtPointName->setText(QString::number(model->rowCount()-1)); pointRange(); } void PathPlanningWidget::pointPosUpdated_slot(const tf::Transform& point_pos, const char* marker_name) { /*! When the user updates the position of the Way-Point or the User Interactive Marker, the information in the TreeView also needs to be updated to correspond to the current pose of the InteractiveMarkers. */ QAbstractItemModel *model = ui_.treeView->model(); tf::Vector3 p = point_pos.getOrigin(); tfScalar rx,ry,rz; point_pos.getBasis().getRPY(rx,ry,rz,1); rx = RAD2DEG(rx); ry = RAD2DEG(ry); rz = RAD2DEG(rz); //set the strings of each axis of the position QString pos_x = QString::number(p.x()); QString pos_y = QString::number(p.y()); QString pos_z = QString::number(p.z()); //repeat that with the orientation QString orient_x = QString::number(rx); QString orient_y = QString::number(ry); QString orient_z = QString::number(rz); if((strcmp(marker_name,"add_point_button") == 0) || (atoi(marker_name)==0)) { QString pos_s; pos_s = pos_x + "; " + pos_y + "; " + pos_z + ";"; QString orient_s; orient_s = orient_x + "; " + orient_y + "; " + orient_z + ";"; model->setData(model->index(0,0),QVariant("add_point_button"),Qt::EditRole); model->setData(model->index(0,1),QVariant(pos_s),Qt::EditRole); model->setData(model->index(0,2),QVariant(orient_s),Qt::EditRole); //set up the starting values for the lineEdit of the positions ui_.LineEditX->setText(pos_x); ui_.LineEditY->setText(pos_y); ui_.LineEditZ->setText(pos_z); //set up the starting values for the lineEdit of the orientations, in Euler angles ui_.LineEditRx->setText(orient_x); ui_.LineEditRy->setText(orient_y); ui_.LineEditRz->setText(orient_z); } else { int changed_marker = atoi(marker_name); //**********************update the positions and orientations of the children as well*********************************************************************************************** QModelIndex ind = model->index(changed_marker, 0); QModelIndex chldind_pos = model->index(0, 0, ind); QModelIndex chldind_orient = model->index(1, 0, ind); //second we add the current position information, for each position axis separately model->setData(model->index(0, 1, chldind_pos), QVariant(pos_x), Qt::EditRole); model->setData(model->index(1, 1, chldind_pos), QVariant(pos_y), Qt::EditRole); model->setData(model->index(2, 1, chldind_pos), QVariant(pos_z), Qt::EditRole); //second we add the current position information, for each position axis separately model->setData(model->index(0, 2, chldind_orient), QVariant(orient_x), Qt::EditRole); model->setData(model->index(1, 2, chldind_orient), QVariant(orient_y), Qt::EditRole); model->setData(model->index(2, 2, chldind_orient), QVariant(orient_z), Qt::EditRole); //set up the starting values for the lineEdit of the positions ui_.LineEditX->setText(pos_x); ui_.LineEditY->setText(pos_y); ui_.LineEditZ->setText(pos_z); //set up the starting values for the lineEdit of the orientations, in Euler angles ui_.LineEditRx->setText(orient_x); ui_.LineEditRy->setText(orient_y); ui_.LineEditRz->setText(orient_z); //***************************************************************************************************************************************************************************************** } } void PathPlanningWidget::treeViewDataChanged(const QModelIndex &index,const QModelIndex &index2) { /*! This function handles the user interactions in the TreeView Widget. The function captures an event of data change and updates the information in the TreeView and the RViz enviroment. */ qRegisterMetaType<std::string>("std::string"); QAbstractItemModel *model = ui_.treeView->model(); QVariant index_data; ROS_INFO_STREAM("Data changed in index:" << index.row() << "parent row" <<index2.parent().row()); if ((index.parent() == QModelIndex()) && (index.row()!=0)) { } else if(((index.parent().parent()) != QModelIndex()) && (index.parent().parent().row()!=0)) { QModelIndex main_root = index.parent().parent(); std::stringstream s; s<<main_root.row(); std::string temp_str = s.str(); QModelIndex chldind_pos = model->index(0, 0, main_root.sibling(main_root.row(),0)); QModelIndex chldind_orient = model->index(1, 0, main_root.sibling(main_root.row(),0)); QVariant pos_x = model->data(model->index(0, 1,chldind_pos),Qt::EditRole); QVariant pos_y = model->data(model->index(1, 1,chldind_pos),Qt::EditRole); QVariant pos_z = model->data(model->index(2, 1,chldind_pos),Qt::EditRole); QVariant orient_x = model->data(model->index(0, 2,chldind_orient),Qt::EditRole); QVariant orient_y = model->data(model->index(1, 2,chldind_orient),Qt::EditRole); QVariant orient_z = model->data(model->index(2, 2,chldind_orient),Qt::EditRole); tf::Vector3 p(pos_x.toDouble(),pos_y.toDouble(),pos_z.toDouble()); tfScalar rx,ry,rz; rx = DEG2RAD(orient_x.toDouble()); ry = DEG2RAD(orient_y.toDouble()); rz = DEG2RAD(orient_z.toDouble()); tf::Transform point_pos = tf::Transform(tf::createQuaternionFromRPY(rx,ry,rz),p); Q_EMIT pointPosUpdated_signal(point_pos,temp_str.c_str()); } } void PathPlanningWidget::parseWayPointBtn_slot() { /*! Letting know the Cartesian Path Planner Class that the user has pressed the Execute Cartesian Path button. */ Q_EMIT parseWayPointBtn_signal(); } void PathPlanningWidget::loadPointsFromFile() { /*! Slot that takes care of opening a previously saved Way-Points yaml file. Opens Qt Dialog for selecting the file, opens the file and parses the data. After reading and parsing the data from the file, the information regarding the pose of the Way-Points is send to the RQT and the RViz so they can update their enviroments. */ QString fileName = QFileDialog::getOpenFileName(this, tr("Open Way Points File"), "", tr("Way Points (*.yaml);;All Files (*)")); if (fileName.isEmpty()) { ui_.tabWidget->setEnabled(true); ui_.progressBar->hide(); return; } else { ui_.tabWidget->setEnabled(false); ui_.progressBar->show(); QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) { QMessageBox::information(this, tr("Unable to open file"), file.errorString()); file.close(); ui_.tabWidget->setEnabled(true); ui_.progressBar->hide(); return; } //clear all the scene before loading all the new points from the file!! clearAllPoints_slot(); ROS_INFO_STREAM("Opening the file: "<<fileName.toStdString()); std::string fin(fileName.toStdString()); YAML::Node doc; doc = YAML::LoadFile(fin); //define double for percent of completion double percent_complete; int end_of_doc = doc.size(); for (size_t i = 0; i < end_of_doc; i++) { std::string name; geometry_msgs::Pose pose; tf::Transform pose_tf; double x,y,z,rx, ry, rz; name = doc[i]["name"].as<std::string>(); x = doc[i]["point"][0].as<double>(); y = doc[i]["point"][1].as<double>(); z = doc[i]["point"][2].as<double>(); rx = doc[i]["point"][3].as<double>(); ry = doc[i]["point"][4].as<double>(); rz = doc[i]["point"][5].as<double>(); rx = DEG2RAD(rx); ry = DEG2RAD(ry); rz = DEG2RAD(rz); pose_tf = tf::Transform(tf::createQuaternionFromRPY(rx,ry,rz),tf::Vector3(x,y,z)); percent_complete = (i+1)*100/end_of_doc; ui_.progressBar->setValue(percent_complete); Q_EMIT addPoint(pose_tf); } ui_.tabWidget->setEnabled(true); ui_.progressBar->hide(); } } void PathPlanningWidget::savePointsToFile() { /*! Just inform the RViz enviroment that Save Way-Points button has been pressed. */ Q_EMIT saveToFileBtn_press(); } void PathPlanningWidget::clearAllPoints_slot() { /*! Clear all the Way-Points from the RViz enviroment and the TreeView. */ QAbstractItemModel *model = ui_.treeView->model(); model->removeRows(0,model->rowCount()); ui_.txtPointName->setText("0"); tf::Transform t; t.setIdentity(); insertRow(t,0); pointRange(); Q_EMIT clearAllPoints_signal(); } void PathPlanningWidget::setAddPointUIStartPos(const std::string robot_model_frame,const tf::Transform end_effector) { /*! Setting the default values for the Add New Way-Point from the RQT. The information is taken to correspond to the pose of the loaded Robot end-effector. */ tf::Vector3 p = end_effector.getOrigin(); tfScalar rx,ry,rz; end_effector.getBasis().getRPY(rx,ry,rz,1); rx = RAD2DEG(rx); ry = RAD2DEG(ry); rz = RAD2DEG(rz); //set up the starting values for the lineEdit of the positions ui_.LineEditX->setText(QString::number(p.x())); ui_.LineEditY->setText(QString::number(p.y())); ui_.LineEditZ->setText(QString::number(p.z())); //set up the starting values for the lineEdit of the orientations, in Euler angles ui_.LineEditRx->setText(QString::number(rx)); ui_.LineEditRy->setText(QString::number(ry)); ui_.LineEditRz->setText(QString::number(rz)); } void PathPlanningWidget::cartesianPathStartedHandler() { /*! Disable the RQT Widget when the Cartesian Path is executing. */ ui_.tabWidget->setEnabled(false); ui_.targetPoint->setEnabled(false); } void PathPlanningWidget::cartesianPathFinishedHandler() { /*! Enable the RQT Widget when the Cartesian Path execution is completed. */ ui_.tabWidget->setEnabled(true); ui_.targetPoint->setEnabled(true); } void PathPlanningWidget::cartPathCompleted_slot(double fraction) { /*! Get the information of what is the percentage of completion of the Planned Cartesian path from the Cartesian Path Planner class and display it in Qt label. */ fraction = fraction*100.0; fraction = std::floor(fraction * 100 + 0.5)/100; ui_.lbl_cartPathCompleted->setText("Cartesian path " + QString::number(fraction) + "% completed."); } void PathPlanningWidget::moveToHomeFromUI() { Q_EMIT moveToHomeFromUI_signal(); } } }
/* * Copyright (c) 2018, Intel Corporation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * 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: VRDashStreamingAPI.h * Author: Zhang, Andrew * * Created on January 15, 2019, 1:11 PM */ #include <cstdlib> #include <math.h> //#include "../utils/GlogWrapper.h" #include "OmafDashAccessApi.h" #include "OmafDashSource.h" #include "OmafMediaSource.h" #include "OmafTypes.h" #include "general.h" #ifndef _ANDROID_NDK_OPTION_ #ifdef _USE_TRACE_ #include "../trace/Bandwidth_tp.h" #include "../trace/E2E_latency_tp.h" #endif #endif using namespace std; VCD_USE_VROMAF; VCD_USE_VRVIDEO; Handler OmafAccess_Init(DashStreamingClient *pCtx) { if (pCtx == nullptr) { return nullptr; } OmafMediaSource *pSource = new OmafDashSource(); VCD::OMAF::OmafDashParams omaf_dash_params; const OmafParams &omaf_params = pCtx->omaf_params; // for download if (omaf_params.proxy.http_proxy) { omaf_dash_params.http_proxy_.http_proxy_ = std::string(omaf_params.proxy.http_proxy); } if (omaf_params.proxy.https_proxy) { omaf_dash_params.http_proxy_.https_proxy_ = std::string(omaf_params.proxy.https_proxy); } if (omaf_params.proxy.no_proxy) { omaf_dash_params.http_proxy_.no_proxy_ = std::string(omaf_params.proxy.no_proxy); } if (omaf_params.proxy.proxy_user) { omaf_dash_params.http_proxy_.proxy_user_ = std::string(omaf_params.proxy.proxy_user); } if (omaf_params.proxy.proxy_passwd) { omaf_dash_params.http_proxy_.proxy_passwd_ = std::string(omaf_params.proxy.proxy_passwd); } if (omaf_params.http_params.conn_timeout > 0) { omaf_dash_params.http_params_.conn_timeout_ = omaf_params.http_params.conn_timeout; } if (omaf_params.http_params.total_timeout > 0) { omaf_dash_params.http_params_.total_timeout_ = omaf_params.http_params.total_timeout; } if (omaf_params.http_params.retry_times > 0) { omaf_dash_params.http_params_.retry_times_ = omaf_params.http_params.retry_times; } omaf_dash_params.http_params_.bssl_verify_peer_ = omaf_params.http_params.ssl_verify_peer == 0 ? false : true; omaf_dash_params.http_params_.bssl_verify_host_ = omaf_params.http_params.ssl_verify_host == 0 ? false : true; omaf_dash_params.prediector_params_.enable_ = omaf_params.predictor_params.enable == 0 ? false : true; if (omaf_params.predictor_params.name) { omaf_dash_params.prediector_params_.name_ = std::string(omaf_params.predictor_params.name); } if (omaf_params.predictor_params.libpath) { omaf_dash_params.prediector_params_.libpath_ = std::string(omaf_params.predictor_params.libpath); } omaf_dash_params.stats_params_.enable_ = omaf_params.statistic_params.enable == 0 ? false : true; if (omaf_dash_params.stats_params_.enable_) { omaf_dash_params.stats_params_.window_size_ms_ = omaf_params.statistic_params.window_size_ms; } omaf_dash_params.syncer_params_.enable_ = omaf_params.synchronizer_params.enable == 0 ? false : true; if (omaf_dash_params.syncer_params_.enable_) { omaf_dash_params.syncer_params_.segment_range_size_ = omaf_params.synchronizer_params.segment_range_size; } if (omaf_params.max_parallel_transfers > 0) { omaf_dash_params.max_parallel_transfers_ = omaf_params.max_parallel_transfers; } if (omaf_params.segment_open_timeout_ms > 0) { omaf_dash_params.segment_open_timeout_ms_ = omaf_params.segment_open_timeout_ms; } // for stitch if (omaf_params.max_decode_width > 0) { omaf_dash_params.max_decode_width_ = omaf_params.max_decode_width; } if (omaf_params.max_decode_height > 0) { omaf_dash_params.max_decode_height_ = omaf_params.max_decode_height; } OMAF_LOG(LOG_INFO,"Dash parameter %s\n", omaf_dash_params.to_string().c_str()); pSource->SetOmafDashParams(omaf_dash_params); return (Handler)((long)pSource); } int OmafAccess_OpenMedia(Handler hdl, DashStreamingClient *pCtx, bool enablePredictor, char *predictPluginName, char *libPath) { if (hdl == nullptr || pCtx == nullptr) { return ERROR_INVALID; } OmafMediaSource *pSource = (OmafMediaSource *)hdl; pSource->SetLoop(false); // for android ndk compile, transform char* to string is mandatory string media_url = pCtx->media_url; string cache_path = pCtx->cache_path; string s_predictPluginName = predictPluginName; string s_libPath = libPath; return pSource->OpenMedia(media_url, cache_path, pCtx->log_callback, pCtx->plugin_def, pCtx->enable_extractor, enablePredictor, s_predictPluginName, s_libPath); } int OmafAccess_StartStreaming(Handler hdl) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; return pSource->StartStreaming(); } int OmafAccess_CloseMedia(Handler hdl) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; return pSource->CloseMedia(); } int OmafAccess_SeekMedia(Handler hdl, uint64_t time) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; return pSource->SeekTo(time); } int OmafAccess_GetMediaInfo(Handler hdl, DashMediaInfo *info) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; pSource->GetMediaInfo(info); #ifndef _ANDROID_NDK_OPTION_ #ifdef _USE_TRACE_ const char *dash_mode = (info->streaming_type == 1) ? "static" : "dynamic"; int32_t frameNum = round(float(info->duration) / 1000 * ((float)info->stream_info[0].framerate_num / info->stream_info[0].framerate_den)); tracepoint(bandwidth_tp_provider, segmentation_info, (char *)dash_mode, (int)info->stream_info[0].segmentDuration, (float)info->stream_info[0].framerate_num / info->stream_info[0].framerate_den, (uint32_t)info->stream_count, (uint64_t*)&(info->stream_info[0].bit_rate), frameNum, (int32_t)(info->duration / 1000)); #endif #endif return ERROR_NONE; } int OmafAccess_GetPacket(Handler hdl, int stream_id, DashPacket *packet, int *size, uint64_t *pts, bool needParams, bool clearBuf) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; std::list<MediaPacket *> pkts; pSource->GetPacket(stream_id, &pkts, needParams, clearBuf); if (0 == pkts.size()) { return ERROR_NULL_PACKET; } *size = pkts.size(); int i = 0; for (auto it = pkts.begin(); it != pkts.end(); it++) { MediaPacket *pPkt = (MediaPacket *)(*it); if (!pPkt) { *size -= 1; continue; } if (!(pPkt->GetEOS())) { if (pPkt->GetMediaType() == MediaType_Video) { RegionWisePacking *newRwpk = new RegionWisePacking; const RegionWisePacking &pRwpk = pPkt->GetRwpk(); *newRwpk = pRwpk; newRwpk->rectRegionPacking = new RectangularRegionWisePacking[newRwpk->numRegions]; memcpy_s(newRwpk->rectRegionPacking, pRwpk.numRegions * sizeof(RectangularRegionWisePacking), pRwpk.rectRegionPacking, pRwpk.numRegions * sizeof(RectangularRegionWisePacking)); SourceResolution *srcRes = new SourceResolution[pPkt->GetQualityNum()]; memcpy_s(srcRes, pPkt->GetQualityNum() * sizeof(SourceResolution), pPkt->GetSourceResolutions(), pPkt->GetQualityNum() * sizeof(SourceResolution)); packet[i].rwpk = newRwpk; packet[i].buf = pPkt->MovePayload(); packet[i].size = pPkt->Size(); packet[i].segID = pPkt->GetSegID(); packet[i].videoID = pPkt->GetVideoID(); packet[i].video_codec = pPkt->GetCodecType(); packet[i].pts = pPkt->GetPTS(); packet[i].height = pPkt->GetVideoHeight(); packet[i].width = pPkt->GetVideoWidth(); packet[i].numQuality = pPkt->GetQualityNum(); packet[i].qtyResolution = srcRes; packet[i].tileRowNum = pPkt->GetVideoTileRowNum(); packet[i].tileColNum = pPkt->GetVideoTileColNum(); packet[i].bEOS = pPkt->GetEOS(); #ifndef _ANDROID_NDK_OPTION_ #ifdef _USE_TRACE_ string tag = "sgmtIdx:" + to_string(pPkt->GetSegID()); tag += ";videoIdx:" + to_string(pPkt->GetVideoID()); tracepoint(E2E_latency_tp_provider, post_da_info, pPkt->GetPTS(), tag.c_str()); #endif #endif } else if (pPkt->GetMediaType() == MediaType_Audio) { packet[i].buf = pPkt->MovePayload(); packet[i].size = pPkt->Size(); packet[i].segID = pPkt->GetSegID(); packet[i].pts = pPkt->GetPTS(); packet[i].bEOS = pPkt->GetEOS(); } } else { packet[i].bEOS = true; } i++; delete pPkt; pPkt = NULL; } return ERROR_NONE; } int OmafAccess_SetupHeadSetInfo(Handler hdl, HeadSetInfo *clientInfo) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; return pSource->SetupHeadSetInfo(clientInfo); } int OmafAccess_ChangeViewport(Handler hdl, HeadPose *pose) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; return pSource->ChangeViewport(pose); } int OmafAccess_Statistic(Handler hdl, DashStatisticInfo *info) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; return pSource->GetStatistic(info); } int OmafAccess_Close(Handler hdl) { OmafMediaSource *pSource = (OmafMediaSource *)hdl; delete pSource; // FIXME, when and where to do resource release // OmafCurlDownloader::releaseCurlModule(); return ERROR_NONE; }
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/systemui/doze/DozeLog.h" #include "Elastos.CoreLibrary.IO.h" #include "Elastos.CoreLibrary.Utility.h" #include <elastos/core/AutoLock.h> #include <elastos/core/StringBuilder.h> #include <elastos/core/Math.h> #include <elastos/droid/os/Build.h> #include <elastos/droid/utility/TimeUtils.h> #include <elastos/utility/logging/Logger.h> using Elastos::Droid::Os::Build; using Elastos::Droid::Utility::TimeUtils; using Elastos::Core::AutoLock; using Elastos::Core::StringBuilder; using Elastos::Core::CSystem; using Elastos::Core::ISystem; using Elastos::Text::CSimpleDateFormat; using Elastos::Text::IDateFormat; using Elastos::Utility::CDate; using Elastos::Utility::IDate; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace SystemUI { namespace Doze { //=============================================================== // DozeLog:: //=============================================================== String DozeLog::TAG("DozeLog"); Boolean DozeLog::DEBUG = FALSE;//Logger::IsLoggable(TAG, Logger::___DEBUG); Boolean DozeLog::ENABLED = TRUE; Int32 DozeLog::SIZE = Build::IS_DEBUGGABLE ? 400 : 50; AutoPtr<ISimpleDateFormat> DozeLog::FORMAT; AutoPtr<ArrayOf<Int64> > DozeLog::sTimes; AutoPtr<ArrayOf<String> > DozeLog::sMessages; Int32 DozeLog::sPosition = 0; Int32 DozeLog::sCount = 0; Boolean DozeLog::sPulsing = FALSE; Int64 DozeLog::sSince = 0; AutoPtr<DozeLog::SummaryStats> DozeLog::sPickupPulseNearVibrationStats; AutoPtr<DozeLog::SummaryStats> DozeLog::sPickupPulseNotNearVibrationStats; AutoPtr<DozeLog::SummaryStats> DozeLog::sNotificationPulseStats; AutoPtr<DozeLog::SummaryStats> DozeLog::sScreenOnPulsingStats; AutoPtr<DozeLog::SummaryStats> DozeLog::sScreenOnNotPulsingStats; AutoPtr<DozeLog::SummaryStats> DozeLog::sEmergencyCallStats; AutoPtr<DozeLog::SummaryStats> DozeLog::sProxNearStats; AutoPtr<DozeLog::SummaryStats> DozeLog::sProxFarStats; Boolean DozeLog::sInit = InitStatic(); Object DozeLog::sDozeLog; Boolean DozeLog::InitStatic() { CSimpleDateFormat::New(String("MM-dd HH:mm:ss.SSS"), (ISimpleDateFormat**)&FORMAT); return TRUE; } void DozeLog::TracePickupPulse( /* [in] */ Boolean withinVibrationThreshold) { if (!ENABLED) return; StringBuilder sb("pickupPulse withinVibrationThreshold="); sb += withinVibrationThreshold; Log(sb.ToString()); (withinVibrationThreshold ? sPickupPulseNearVibrationStats.Get() : sPickupPulseNotNearVibrationStats.Get())->Append(); } void DozeLog::TracePulseStart() { if (!ENABLED) return; sPulsing = TRUE; return Log(String("pulseStart")); } void DozeLog::TracePulseFinish() { if (!ENABLED) return; sPulsing = FALSE; return Log(String("pulseFinish")); } void DozeLog::TraceNotificationPulse( /* [in] */ Int64 instance) { if (!ENABLED) return; StringBuilder sb("notificationPulse instance="); sb += instance; Log(sb.ToString()); sNotificationPulseStats->Append(); } void DozeLog::TraceDozing( /* [in] */ IContext* context, /* [in] */ Boolean dozing) { if (!ENABLED) return; sPulsing = FALSE; { AutoLock syncLock(sDozeLog); if (dozing && sMessages == NULL) { sTimes = ArrayOf<Int64>::Alloc(SIZE); sMessages = ArrayOf<String>::Alloc(SIZE); AutoPtr<ISystem> system; Elastos::Core::CSystem::AcquireSingleton((ISystem**)&system); system->GetCurrentTimeMillis(&sSince); sPickupPulseNearVibrationStats = new SummaryStats(); sPickupPulseNotNearVibrationStats = new SummaryStats(); sNotificationPulseStats = new SummaryStats(); sScreenOnPulsingStats = new SummaryStats(); sScreenOnNotPulsingStats = new SummaryStats(); sEmergencyCallStats = new SummaryStats(); sProxNearStats = new SummaryStats(); sProxFarStats = new SummaryStats(); Log(String("init")); assert(0 && "TODO"); // KeyguardUpdateMonitor.getInstance(context).registerCallback(sKeyguardCallback); } } StringBuilder sb("dozing "); sb += dozing; Log(sb.ToString()); } void DozeLog::TraceFling( /* [in] */ Boolean expand, /* [in] */ Boolean aboveThreshold, /* [in] */ Boolean thresholdNeeded, /* [in] */ Boolean screenOnFromTouch) { if (!ENABLED) return; // Log(String("fling expand=") + (Char32)expand + " aboveThreshold=" + (Char32)aboveThreshold + " thresholdNeeded=" // + (Char32)thresholdNeeded + " screenOnFromTouch=" + (Char32)screenOnFromTouch); } void DozeLog::TraceEmergencyCall() { if (!ENABLED) return; Log(String("emergencyCall")); sEmergencyCallStats->Append(); } void DozeLog::TraceKeyguardBouncerChanged( /* [in] */ Boolean showing) { if (!ENABLED) return; StringBuilder sb("bouncer "); sb += showing; Log(sb.ToString()); } void DozeLog::TraceScreenOn() { if (!ENABLED) return; StringBuilder sb("screenOn pulsing="); sb += sPulsing; Log(sb.ToString()); (sPulsing ? sScreenOnPulsingStats : sScreenOnNotPulsingStats)->Append(); sPulsing = FALSE; } void DozeLog::TraceScreenOff( /* [in] */ Int32 why) { if (!ENABLED) return; StringBuilder sb("keyguard"); sb += why; Log(sb.ToString()); } void DozeLog::TraceKeyguard( /* [in] */ Boolean showing) { if (!ENABLED) return; StringBuilder sb("keyguard"); sb += showing; Log(sb.ToString()); if (!showing) { sPulsing = FALSE; } } void DozeLog::TraceProximityResult( /* [in] */ Boolean near, /* [in] */ Int64 millis) { if (!ENABLED) return; StringBuilder sb("proximityResult near="); sb += near; sb += " millis="; sb += millis; Log(sb.ToString()); (near ? sProxNearStats : sProxFarStats)->Append(); } void DozeLog::Dump( /* [in] */ IPrintWriter* pw) { { AutoLock syncLock(sDozeLog); if (sMessages == NULL) return; pw->Println(String(" Doze log:")); Int32 start = (sPosition - sCount + SIZE) % SIZE; for (Int32 i = 0; i < sCount; i++) { Int32 j = (start + i) % SIZE; pw->Print(String(" ")); AutoPtr<IDate> date; CDate::New((*sTimes)[j], (IDate**)&date); String str; IDateFormat::Probe(FORMAT)->Format(date, &str); pw->Print(str); pw->PrintChar(' '); pw->Println((*sMessages)[j]); } pw->Print(String(" Doze summary stats (for ")); AutoPtr<ISystem> system; Elastos::Core::CSystem::AcquireSingleton((ISystem**)&system); Int64 when = 0; system->GetCurrentTimeMillis(&when); TimeUtils::FormatDuration(when - sSince, pw); pw->Println(String("):")); sPickupPulseNearVibrationStats->Dump(pw, String("Pickup pulse (near vibration)")); sPickupPulseNotNearVibrationStats->Dump(pw, String("Pickup pulse (not near vibration)")); sNotificationPulseStats->Dump(pw, String("Notification pulse")); sScreenOnPulsingStats->Dump(pw, String("Screen on (pulsing)")); sScreenOnNotPulsingStats->Dump(pw, String("Screen on (not pulsing)")); sEmergencyCallStats->Dump(pw, String("Emergency call")); sProxNearStats->Dump(pw, String("Proximity (near)")); sProxFarStats->Dump(pw, String("Proximity (far)")); } } void DozeLog::Log( /* [in] */ const String& msg) { { AutoLock syncLock(sDozeLog); if (sMessages == NULL) return; AutoPtr<ISystem> system; Elastos::Core::CSystem::AcquireSingleton((ISystem**)&system); system->GetCurrentTimeMillis(&((*sTimes)[sPosition])); (*sMessages)[sPosition] = msg; sPosition = (sPosition + 1) % SIZE; sCount = Elastos::Core::Math::Min(sCount + 1, SIZE); } if (DEBUG) Logger::D(TAG, msg); } //=============================================================== // DozeLog::SummaryStats //=============================================================== void DozeLog::SummaryStats::Append() { mCount++; } void DozeLog::SummaryStats::Dump( /* [in] */ IPrintWriter* pw, /* [in] */ const String& type) { pw->Print(String(" ")); pw->Print(type); pw->Print(String(": n=")); pw->Print(mCount); pw->Print(String(" (")); AutoPtr<ISystem> system; Elastos::Core::CSystem::AcquireSingleton((ISystem**)&system); Int64 mills = 0; system->GetCurrentTimeMillis(&mills); double perHr = (double) mCount / (mills - sSince) * 1000 * 60 * 60; pw->Print(perHr); pw->Print(String("/hr)")); pw->Println(); } //=============================================================== // DozeLog::KeyguardUpdateMonitorCallback //=============================================================== void DozeLog::KeyguardUpdateMonitorCallback::OnEmergencyCallAction() { TraceEmergencyCall(); } void DozeLog::KeyguardUpdateMonitorCallback::OnKeyguardBouncerChanged( /* [in] */ Boolean bouncer) { TraceKeyguardBouncerChanged(bouncer); } void DozeLog::KeyguardUpdateMonitorCallback::OnScreenTurnedOn() { TraceScreenOn(); } void DozeLog::KeyguardUpdateMonitorCallback::OnScreenTurnedOff( /* [in] */ Int32 why) { TraceScreenOff(why); } void DozeLog::KeyguardUpdateMonitorCallback::OnKeyguardVisibilityChanged( /* [in] */ Boolean showing) { TraceKeyguard(showing); } } // namespace Doze } // namespace SystemUI } // namespace Droid } // namespace Elastos
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/migrationhubstrategy/model/ManagementPreference.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace MigrationHubStrategyRecommendations { namespace Model { ManagementPreference::ManagementPreference() : m_awsManagedResourcesHasBeenSet(false), m_noPreferenceHasBeenSet(false), m_selfManageResourcesHasBeenSet(false) { } ManagementPreference::ManagementPreference(JsonView jsonValue) : m_awsManagedResourcesHasBeenSet(false), m_noPreferenceHasBeenSet(false), m_selfManageResourcesHasBeenSet(false) { *this = jsonValue; } ManagementPreference& ManagementPreference::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("awsManagedResources")) { m_awsManagedResources = jsonValue.GetObject("awsManagedResources"); m_awsManagedResourcesHasBeenSet = true; } if(jsonValue.ValueExists("noPreference")) { m_noPreference = jsonValue.GetObject("noPreference"); m_noPreferenceHasBeenSet = true; } if(jsonValue.ValueExists("selfManageResources")) { m_selfManageResources = jsonValue.GetObject("selfManageResources"); m_selfManageResourcesHasBeenSet = true; } return *this; } JsonValue ManagementPreference::Jsonize() const { JsonValue payload; if(m_awsManagedResourcesHasBeenSet) { payload.WithObject("awsManagedResources", m_awsManagedResources.Jsonize()); } if(m_noPreferenceHasBeenSet) { payload.WithObject("noPreference", m_noPreference.Jsonize()); } if(m_selfManageResourcesHasBeenSet) { payload.WithObject("selfManageResources", m_selfManageResources.Jsonize()); } return payload; } } // namespace Model } // namespace MigrationHubStrategyRecommendations } // namespace Aws
//------------------------------------------------------------------ // Iwa_TiledParticlesFx for Marnie // based on ParticlesFx by Digital Video //------------------------------------------------------------------ // TnzCore includes #include "tofflinegl.h" #include "tstroke.h" #include "tpalette.h" #include "tvectorimage.h" #include "tvectorrenderdata.h" #include "tflash.h" #include "texception.h" #include "trasterimage.h" #include "drawutil.h" // TnzBase includes #include "trasterfx.h" #include "tparamuiconcept.h" // TnzLib includes #include "toonz/toonzimageutils.h" // TnzStdfx includes #include "iwa_particlesengine.h" #include "iwa_particlesmanager.h" #include "iwa_particlesfx.h" //************************************************************************** // Iwa_TiledParticlesFx implementation //************************************************************************** Iwa_TiledParticlesFx::Iwa_TiledParticlesFx() : m_source("Texture"), m_control("Control"), source_ctrl_val(0), bright_thres_val(25), center_val(TPointD(0.0, 0.0)), length_val(5.0), height_val(4.0), maxnum_val(10.0), lifetime_val(DoublePair(100., 100.)), lifetime_ctrl_val(0), column_lifetime_val(false), startpos_val(1), randseed_val(1), gravity_val(0.0), g_angle_val(0.0), gravity_ctrl_val(0), friction_val(0.0), friction_ctrl_val(0), windint_val(0.0), windangle_val(0.0), swingmode_val(new TIntEnumParam(SWING_RANDOM, "Random")), randomx_val(DoublePair(0., 0.)), randomy_val(DoublePair(0., 0.)), randomx_ctrl_val(0), randomy_ctrl_val(0), swing_val(DoublePair(0., 0.)), speed_val(DoublePair(0., 10.)), speed_ctrl_val(0), speeda_val(DoublePair(0., 0.)), speeda_ctrl_val(0), speeda_use_gradient_val(false), speedscale_val(false), toplayer_val(new TIntEnumParam(TOP_YOUNGER, "Younger")), mass_val(DoublePair(1., 1.)), scale_val(DoublePair(100., 100.)), scale_ctrl_val(0), scale_ctrl_all_val(false), rot_val(DoublePair(0., 0.)), rot_ctrl_val(0), trail_val(DoublePair(0., 0.)), trailstep_val(0.0), rotswingmode_val(new TIntEnumParam(SWING_RANDOM, "Random")), rotspeed_val(0.0), rotsca_val(DoublePair(0., 0.)), rotswing_val(DoublePair(0., 0.)), pathaim_val(false), opacity_val(DoublePair(0., 100.)), opacity_ctrl_val(0), trailopacity_val(DoublePair(0., 100.)), scalestep_val(DoublePair(0., 0.)), scalestep_ctrl_val(0), fadein_val(0.0), fadeout_val(0.0), animation_val(new TIntEnumParam(ANIM_HOLD, "Hold Frame")), step_val(1), gencol_ctrl_val(0), gencol_spread_val(0.0), genfadecol_val(0.0), fincol_ctrl_val(0), fincol_spread_val(0.0), finrangecol_val(0.0), finfadecol_val(0.0), foutcol_ctrl_val(0), foutcol_spread_val(0.0), foutrangecol_val(0.0), foutfadecol_val(0.0) , source_gradation_val(false), pick_color_for_every_frame_val(false) /*- 計算モード (背景+粒子/粒子/背景/照明された粒子 -*/ , iw_rendermode_val(new TIntEnumParam(REND_ALL, "All")) /*- 粒子に貼られる絵の素材 -*/ , base_ctrl_val(0) /*- カールノイズ的な動きを与える -*/ , curl_val(0.0) /*- 手前奥でコントロールを立体化してみる -*/ , curl_ctrl_1_val(0), curl_ctrl_2_val(0) /*- 粒子敷き詰め作戦。粒子を正三角形で敷き詰めたときの、 正三角形の一辺の長さをインチで指定する -*/ , iw_triangleSize(15.0) /*- ひらひら回転 -*/ , flap_ctrl_val(0), iw_flap_velocity_val(0.0) /*- 回転角速度 -*/ , iw_flap_dir_sensitivity_val(1.0) /*- 回転軸感度 -*/ /*- ひらひら粒子に照明を当てる -*/ , iw_light_theta_val(60.0) /*- 光源の方向(Degree)-*/ , iw_light_phi_val(45.0) /*- 光源の傾き(Degree)-*/ /*- 読み込みマージン -*/ , margin_val(0.0) /*- 重力を徐々に与えるためのフレーム長 -*/ , iw_gravityBufferFrame_val(0) { addInputPort("Texture1", new TRasterFxPort, 0); addInputPort("Control1", new TRasterFxPort, 1); length_val->setMeasureName("fxLength"); height_val->setMeasureName("fxLength"); center_val->getX()->setMeasureName("fxLength"); center_val->getY()->setMeasureName("fxLength"); bindParam(this, "source_ctrl", source_ctrl_val); bindParam(this, "bright_thres", bright_thres_val); bright_thres_val->setValueRange(0, 255); bindParam(this, "center", center_val); bindParam(this, "length", length_val); length_val->setValueRange(1.0, (std::numeric_limits<double>::max)()); bindParam(this, "height", height_val); height_val->setValueRange(1.0, (std::numeric_limits<double>::max)()); bindParam(this, "birth_rate", maxnum_val); maxnum_val->setValueRange(0.0, (std::numeric_limits<double>::max)()); bindParam(this, "lifetime", lifetime_val); lifetime_val->getMin()->setValueRange(0., +3000.); lifetime_val->getMax()->setValueRange(0., +3000.); bindParam(this, "lifetime_ctrl", lifetime_ctrl_val); bindParam(this, "column_lifetime", column_lifetime_val); bindParam(this, "starting_frame", startpos_val); bindParam(this, "random_seed", randseed_val); bindParam(this, "gravity", gravity_val); gravity_val->setValueRange(0.0, (std::numeric_limits<double>::max)()); bindParam(this, "gravity_angle", g_angle_val); g_angle_val->setMeasureName("angle"); bindParam(this, "gravity_ctrl", gravity_ctrl_val); bindParam(this, "friction", friction_val); bindParam(this, "friction_ctrl", friction_ctrl_val); bindParam(this, "wind", windint_val); bindParam(this, "wind_angle", windangle_val); windangle_val->setMeasureName("angle"); bindParam(this, "swing_mode", swingmode_val); swingmode_val->addItem(SWING_SMOOTH, "Smooth"); bindParam(this, "scattering_x", randomx_val); randomx_val->getMin()->setMeasureName("fxLength"); randomx_val->getMax()->setMeasureName("fxLength"); randomx_val->getMin()->setValueRange(-1000., +1000.); randomx_val->getMax()->setValueRange(-1000., +1000.); bindParam(this, "scattering_y", randomy_val); randomy_val->getMin()->setMeasureName("fxLength"); randomy_val->getMax()->setMeasureName("fxLength"); randomy_val->getMin()->setValueRange(-1000., +1000.); randomy_val->getMax()->setValueRange(-1000., +1000.); bindParam(this, "scattering_x_ctrl", randomx_ctrl_val); bindParam(this, "scattering_y_ctrl", randomy_ctrl_val); bindParam(this, "swing", swing_val); swing_val->getMin()->setValueRange(-1000., +1000.); swing_val->getMax()->setValueRange(-1000., +1000.); speed_val->getMin()->setMeasureName("fxLength"); speed_val->getMax()->setMeasureName("fxLength"); bindParam(this, "speed", speed_val); speed_val->getMin()->setValueRange(-1000., +1000.); speed_val->getMax()->setValueRange(-1000., +1000.); bindParam(this, "speed_ctrl", speed_ctrl_val); bindParam(this, "speed_angle", speeda_val); speeda_val->getMin()->setValueRange(-1000., +1000.); speeda_val->getMax()->setValueRange(-1000., +1000.); speeda_val->getMin()->setMeasureName("angle"); speeda_val->getMax()->setMeasureName("angle"); bindParam(this, "speeda_ctrl", speeda_ctrl_val); bindParam(this, "speeda_use_gradient", speeda_use_gradient_val); bindParam(this, "speed_size", speedscale_val); bindParam(this, "top_layer", toplayer_val); toplayer_val->addItem(TOP_OLDER, "Older"); toplayer_val->addItem(TOP_SMALLER, "Smaller"); toplayer_val->addItem(TOP_BIGGER, "Bigger"); toplayer_val->addItem(TOP_RANDOM, "Random"); bindParam(this, "mass", mass_val); mass_val->getMin()->setValueRange(0., +1000.); mass_val->getMax()->setValueRange(0., +1000.); bindParam(this, "scale", scale_val); scale_val->getMin()->setValueRange(0., +1000.); scale_val->getMax()->setValueRange(0., +1000.); bindParam(this, "scale_ctrl", scale_ctrl_val); bindParam(this, "scale_ctrl_all", scale_ctrl_all_val); bindParam(this, "rot", rot_val); rot_val->getMin()->setValueRange(-1000., +1000.); rot_val->getMax()->setValueRange(-1000., +1000.); rot_val->getMin()->setMeasureName("angle"); rot_val->getMax()->setMeasureName("angle"); bindParam(this, "rot_ctrl", rot_ctrl_val); bindParam(this, "trail", trail_val); trail_val->getMin()->setValueRange(0., +1000.); trail_val->getMax()->setValueRange(0., +1000.); bindParam(this, "trail_step", trailstep_val); trailstep_val->setValueRange(1.0, (std::numeric_limits<double>::max)()); bindParam(this, "spin_swing_mode", rotswingmode_val); rotswingmode_val->addItem(SWING_SMOOTH, "Smooth"); bindParam(this, "spin_speed", rotspeed_val); rotspeed_val->setMeasureName("angle"); bindParam(this, "spin_random", rotsca_val); rotsca_val->getMin()->setValueRange(-1000., +1000.); rotsca_val->getMax()->setValueRange(-1000., +1000.); rotsca_val->getMin()->setMeasureName("angle"); rotsca_val->getMax()->setMeasureName("angle"); bindParam(this, "spin_swing", rotswing_val); rotswing_val->getMin()->setValueRange(-1000., +1000.); rotswing_val->getMax()->setValueRange(-1000., +1000.); rotswing_val->getMin()->setMeasureName("angle"); rotswing_val->getMax()->setMeasureName("angle"); bindParam(this, "path_aim", pathaim_val); bindParam(this, "opacity", opacity_val); opacity_val->getMin()->setValueRange(0., +100.); opacity_val->getMax()->setValueRange(0., +100.); bindParam(this, "opacity_ctrl", opacity_ctrl_val); bindParam(this, "trail_opacity", trailopacity_val); trailopacity_val->getMin()->setValueRange(0., +100.); trailopacity_val->getMax()->setValueRange(0., +100.); bindParam(this, "scale_step", scalestep_val); bindParam(this, "scale_step_ctrl", scalestep_ctrl_val); scalestep_val->getMin()->setValueRange(-100., +100.); scalestep_val->getMax()->setValueRange(-100., +100.); bindParam(this, "fade_in", fadein_val); bindParam(this, "fade_out", fadeout_val); bindParam(this, "animation", animation_val); animation_val->addItem(ANIM_RANDOM, "Random Frame"); animation_val->addItem(ANIM_CYCLE, "Column"); animation_val->addItem(ANIM_R_CYCLE, "Column - Random Start"); animation_val->addItem(ANIM_SR_CYCLE, "Column Swing - Random Start"); bindParam(this, "step", step_val); step_val->setValueRange(1, (std::numeric_limits<int>::max)()); TSpectrum::ColorKey colors[] = { TSpectrum::ColorKey(0, TPixel32::Red), TSpectrum::ColorKey(1, TPixel32::Red)}; gencol_val = TSpectrumParamP(tArrayCount(colors), colors); bindParam(this, "birth_color", gencol_val); bindParam(this, "birth_color_ctrl", gencol_ctrl_val); bindParam(this, "birth_color_spread", gencol_spread_val); gencol_spread_val->setValueRange(0.0, (std::numeric_limits<int>::max)()); bindParam(this, "birth_color_fade", genfadecol_val); genfadecol_val->setValueRange(0.0, 100.0); TSpectrum::ColorKey colors1[] = { TSpectrum::ColorKey(0, TPixel32::Green), TSpectrum::ColorKey(1, TPixel32::Green)}; fincol_val = TSpectrumParamP(tArrayCount(colors1), colors1); bindParam(this, "fadein_color", fincol_val); bindParam(this, "fadein_color_ctrl", fincol_ctrl_val); bindParam(this, "fadein_color_spread", fincol_spread_val); fincol_spread_val->setValueRange(0.0, (std::numeric_limits<int>::max)()); bindParam(this, "fadein_color_range", finrangecol_val); finrangecol_val->setValueRange(0.0, (std::numeric_limits<double>::max)()); bindParam(this, "fadein_color_fade", finfadecol_val); finfadecol_val->setValueRange(0.0, 100.0); TSpectrum::ColorKey colors2[] = { TSpectrum::ColorKey(0, TPixel32::Blue), TSpectrum::ColorKey(1, TPixel32::Blue)}; foutcol_val = TSpectrumParamP(tArrayCount(colors2), colors2); bindParam(this, "fadeout_color", foutcol_val); bindParam(this, "fadeout_color_ctrl", foutcol_ctrl_val); bindParam(this, "fadeout_color_spread", foutcol_spread_val); foutcol_spread_val->setValueRange(0.0, (std::numeric_limits<int>::max)()); bindParam(this, "fadeout_color_range", foutrangecol_val); foutrangecol_val->setValueRange(0.0, (std::numeric_limits<double>::max)()); bindParam(this, "fadeout_color_fade", foutfadecol_val); foutfadecol_val->setValueRange(0.0, 100.0); bindParam(this, "source_gradation", source_gradation_val); bindParam(this, "pick_color_for_every_frame", pick_color_for_every_frame_val); /*- 計算モード (背景+粒子/粒子/背景/照明された粒子) -*/ bindParam(this, "rendermode", iw_rendermode_val); iw_rendermode_val->addItem(REND_PARTICLES, "Particles"); iw_rendermode_val->addItem(REND_BG, "Background"); iw_rendermode_val->addItem(REND_ILLUMINATED, "Illuminated"); /*- 粒子に貼られる絵の素材 -*/ bindParam(this, "base_ctrl", base_ctrl_val); bindParam(this, "curl", curl_val); curl_val->setValueRange(0.0, (std::numeric_limits<double>::max)()); bindParam(this, "curl_ctrl", curl_ctrl_1_val); bindParam(this, "curl_ctrl_2", curl_ctrl_2_val); /*- 粒子敷き詰め作戦。粒子を正三角形で敷き詰めたときの、 正三角形の一辺の長さをインチで指定する -*/ bindParam(this, "triangleSize", iw_triangleSize); iw_triangleSize->setValueRange(0.1, 100); iw_triangleSize->setMeasureName("fxLength"); /*- ひらひら回転 -*/ bindParam(this, "flap_ctrl", flap_ctrl_val); bindParam(this, "flap_velocity", iw_flap_velocity_val); iw_flap_velocity_val->setValueRange(0.0, (std::numeric_limits<double>::max)()); bindParam(this, "flap_dir_sensitivity", iw_flap_dir_sensitivity_val); iw_flap_dir_sensitivity_val->setValueRange(0.0, 1.0); /*- ひらひら粒子に照明を当てる -*/ bindParam(this, "light_theta", iw_light_theta_val); iw_light_theta_val->setValueRange(-1000.0, 1000.0); bindParam(this, "light_phi", iw_light_phi_val); iw_light_phi_val->setValueRange(-1000.0, 1000.0); /*- 読み込みマージン -*/ margin_val->setMeasureName("fxLength"); bindParam(this, "margin", margin_val); margin_val->setValueRange(0, (std::numeric_limits<double>::max)()); /*- 重力を徐々に与えるためのフレーム長 -*/ bindParam(this, "gravityBufferFrame", iw_gravityBufferFrame_val); } //------------------------------------------------------------------ Iwa_TiledParticlesFx::~Iwa_TiledParticlesFx() { } //------------------------------------------------------------------ void Iwa_TiledParticlesFx::getParamUIs(TParamUIConcept *&concepts, int &length) { concepts = new TParamUIConcept[length = 2]; concepts[0].m_type = TParamUIConcept::POINT; concepts[0].m_label = "Center"; concepts[0].m_params.push_back(center_val); concepts[1].m_type = TParamUIConcept::RECT; concepts[1].m_params.push_back(length_val); concepts[1].m_params.push_back(height_val); concepts[1].m_params.push_back(center_val); } //------------------------------------------------------------------ bool Iwa_TiledParticlesFx::doGetBBox(double frame, TRectD &bBox, const TRenderSettings &info) { // Returning an infinite rect. This is necessary since building the actual bbox // is a very complicate task. bBox = TConsts::infiniteRectD; return true; } //------------------------------------------------------------------ std::string Iwa_TiledParticlesFx::getAlias(double frame, const TRenderSettings &info) const { std::string alias = getFxType(); alias += "["; // alias degli effetti connessi alle porte di input separati da virgole // una porta non connessa da luogo a un alias vuoto (stringa vuota) for (int i = 0; i < getInputPortCount(); ++i) { TFxPort *port = getInputPort(i); if (port->isConnected()) { TRasterFxP ifx = port->getFx(); assert(ifx); alias += ifx->getAlias(frame, info); } alias += ","; } std::string paramalias(""); for (int i = 0; i < getParams()->getParamCount(); ++i) { TParam *param = getParams()->getParam(i); paramalias += param->getName() + "=" + param->getValueAlias(frame, 3); } return alias + toString(frame) + "," + toString(getIdentifier()) + paramalias + "]"; } //------------------------------------------------------------------ bool Iwa_TiledParticlesFx::allowUserCacheOnPort(int portNum) { // Only control port are currently allowed to cache upon explicit user's request std::string tmpName = getInputPortName(portNum); return tmpName.find("Control") != std::string::npos; } //------------------------------------------------------------------ void Iwa_TiledParticlesFx::doDryCompute(TRectD &rect, double frame, const TRenderSettings &info) { Iwa_ParticlesManager *pc = Iwa_ParticlesManager::instance(); unsigned long fxId = getIdentifier(); int inputPortCount = getInputPortCount(); int i, j, curr_frame = frame, /*- 現在のフレーム -*/ startframe = startpos_val->getValue(); /*- Particesの開始フレーム -*/ TRenderSettings infoOnInput(info); infoOnInput.m_affine = TAffine(); // Using the standard reference - indep. from cameras. infoOnInput.m_bpp = 64; // Control ports rendered at 32 bit - since not visible. for (i = startframe - 1; i <= curr_frame; ++i) { double frame = tmax(0, i); for (j = 0; j < inputPortCount; ++j) { TFxPort *port = getInputPort(j); std::string tmpName = getInputPortName(j); if (port->isConnected()) { TRasterFxP fx = port->getFx(); // Now, consider that source ports work different than control ones QString portName = QString::fromStdString(tmpName); if (portName.startsWith("C")) { // Control ports are calculated from start to current frame, since // particle mechanics at current frame is influenced by previous ones // (and therefore by all previous control images). TRectD bbox; fx->getBBox(frame, bbox, infoOnInput); if (bbox == TConsts::infiniteRectD) bbox = info.m_affine.inv() * rect; fx->dryCompute(bbox, frame, infoOnInput); } else if (portName.startsWith("T")) { // Particles handle source ports caching procedures on its own. } } } } } //------------------------------------------------------------------ void Iwa_TiledParticlesFx::doCompute(TTile &tile, double frame, const TRenderSettings &ri) { std::vector<int> lastframe; std::vector<TLevelP> partLevel; TPointD p_offset; TDimension p_size(0, 0); /*- 参照画像ポートの取得 -*/ std::vector<TRasterFxPort *> part_ports; /*- テクスチャ素材画像のポート -*/ std::map<int, TRasterFxPort *> ctrl_ports; /*- コントロール画像のポート番号/ポート -*/ int portsCount = this->getInputPortCount(); for (int i = 0; i < portsCount; ++i) { std::string tmpName = this->getInputPortName(i); QString portName = QString::fromStdString(tmpName); if (portName.startsWith("T")) { TRasterFxPort *tmpPart = (TRasterFxPort *)this->getInputPort(tmpName); if (tmpPart->isConnected()) part_ports.push_back((TRasterFxPort *)this->getInputPort(tmpName)); } else { portName.replace(QString("Control"), QString("")); TRasterFxPort *tmpCtrl = (TRasterFxPort *)this->getInputPort(tmpName); if (tmpCtrl->isConnected()) ctrl_ports[portName.toInt()] = (TRasterFxPort *)this->getInputPort(tmpName); } } /*- テクスチャ素材のバウンディングボックスを足し合わせる ←この工程、いらないかも?-*/ if (!part_ports.empty()) { TRectD outTileBBox(tile.m_pos, TDimensionD(tile.getRaster()->getLx(), tile.getRaster()->getLy())); TRectD bbox; for (unsigned int i = 0; i < (int)part_ports.size(); ++i) { const TFxTimeRegion &tr = (*part_ports[i])->getTimeRegion(); lastframe.push_back(tr.getLastFrame() + 1); partLevel.push_back(new TLevel()); partLevel[i]->setName((*part_ports[i])->getAlias(0, ri)); // The particles offset must be calculated without considering the affine's translational // component TRenderSettings riZero(ri); riZero.m_affine.a13 = riZero.m_affine.a23 = 0; // Calculate the bboxes union for (int t = 0; t <= tr.getLastFrame(); ++t) { TRectD inputBox; (*part_ports[i])->getBBox(t, inputBox, riZero); bbox += inputBox; } } if (bbox == TConsts::infiniteRectD) bbox *= outTileBBox; p_size.lx = (int)bbox.getLx() + 1; p_size.ly = (int)bbox.getLy() + 1; p_offset = TPointD(0.5 * (bbox.x0 + bbox.x1), 0.5 * (bbox.y0 + bbox.y1)); } else { partLevel.push_back(new TLevel()); partLevel[0]->setName("particles"); TDimension vecsize(10, 10); TOfflineGL *offlineGlContext = new TOfflineGL(vecsize); offlineGlContext->clear(TPixel32(0, 0, 0, 0)); TStroke *stroke; stroke = makeEllipticStroke(0.07, TPointD((vecsize.lx - 1) * .5, (vecsize.ly - 1) * .5), 2.0, 2.0); TVectorImageP vectmp = new TVectorImage(); TPalette *plt = new TPalette(); vectmp->setPalette(plt); vectmp->addStroke(stroke); TVectorRenderData rd(AffI, TRect(vecsize), plt, 0, true, true); offlineGlContext->makeCurrent(); offlineGlContext->draw(vectmp, rd); partLevel[0]->setFrame(0, TRasterImageP(offlineGlContext->getRaster()->clone())); p_size.lx = vecsize.lx + 1; p_size.ly = vecsize.ly + 1; lastframe.push_back(1); delete offlineGlContext; } Iwa_Particles_Engine myEngine(this, frame); // Retrieving the dpi multiplier from the accumulated affine (which is isotropic). That is, // the affine will be applied *before* this effect - and we'll multiply geometrical parameters // by this dpi mult. in order to compensate. float dpi = sqrt(fabs(ri.m_affine.det())) * 100; TTile tileIn; if (TRaster32P raster32 = tile.getRaster()) { TFlash *flash = 0; myEngine.render_particles(flash, &tile, part_ports, ri, p_size, p_offset, ctrl_ports, partLevel, 1, (int)frame, 1, 0, 0, 0, 0, lastframe, getIdentifier()); } else if (TRaster64P raster64 = tile.getRaster()) { TFlash *flash = 0; myEngine.render_particles(flash, &tile, part_ports, ri, p_size, p_offset, ctrl_ports, partLevel, 1, (int)frame, 1, 0, 0, 0, 0, lastframe, getIdentifier()); } else throw TException("ParticlesFx: unsupported Pixel Type"); } //------------------------------------------------------------------ void Iwa_TiledParticlesFx::compute(TFlash &flash, int frame) { // Particles is currently disabled in Flash... return; } //------------------------------------------------------------------ void Iwa_TiledParticlesFx::compatibilityTranslatePort(int major, int minor, std::string &portName) { VersionNumber version(major, minor); if (version < VersionNumber(1, 16)) { if (portName == "Texture") portName = "Texture1"; } else if (version < VersionNumber(1, 20)) { int idx; bool chop = ((idx = portName.find("Texture")) != std::string::npos && idx > 0) || ((idx = portName.find("Control")) != std::string::npos && idx > 0); if (chop) portName.erase(portName.begin(), portName.begin() + idx); } } //============================================================================== FX_PLUGIN_IDENTIFIER(Iwa_TiledParticlesFx, "iwa_TiledParticlesFx");
#include "s2020/Parser/DatumParser.h" #include "DiagContext.h" #include <gtest/gtest.h> using namespace s2020; using namespace s2020::parser; using namespace s2020::ast; namespace { class DatumParserTest : public ::testing::Test { protected: const llvm::MemoryBuffer &makeBuf(const char *str) { auto id = context_.sm.addNewSourceBuffer( llvm::MemoryBuffer::getMemBuffer(str, "input", true)); return *context_.sm.getSourceBuffer(id); } NumberNode *Num(ExactNumberT n) { return new (context_) NumberNode(context_.makeExactNumber(n)); } SymbolNode *Sym(StringRef name) { return new (context_) SymbolNode(context_.stringTable.getIdentifier(name)); } protected: ASTContext context_{}; }; TEST_F(DatumParserTest, PrintTest) { auto res = parseDatums( context_, makeBuf("hello 10" " (list -10 more)" " (a . b)" " (1 2 3 . 4)" " (10 . (20 . (30 . ())))" " (if [> a 10] (display 1) (display a))")); ASSERT_TRUE(res.hasValue()); std::string str; llvm::raw_string_ostream OS{str}; for (const auto *node : res.getValue()) dump(OS, node); OS.flush(); ASSERT_EQ( "hello\n" "10\n" "(list\n" " -10\n" " more)\n" "(a . b)\n" "(1\n" " 2\n" " 3 . 4)\n" "(10\n" " 20\n" " 30)\n" "(if\n" " (>\n" " a\n" " 10)\n" " (display\n" " 1)\n" " (display\n" " a))\n", str); } TEST_F(DatumParserTest, SmokeTest) { auto parsed = parseDatums( context_, makeBuf("(hello " " 10" " (list -10 more)" " (a . b)" " (1 2 3 . 4)" " (10 . (20 . (30 . ())))" " (if [> a 10] (display 1) (display a)))")); ASSERT_TRUE(parsed.hasValue()); ASSERT_EQ(1, parsed.getValue().size()); auto *l = list( context_, Sym("hello"), Num(10), list(context_, Sym("list"), Num(-10), Sym("more")), cons(context_, Sym("a"), Sym("b")), cons( context_, Num(1), cons(context_, Num(2), cons(context_, Num(3), Num(4)))), list(context_, Num(10), Num(20), Num(30)), list( context_, Sym("if"), list(context_, Sym(">"), Sym("a"), Num(10)), list(context_, Sym("display"), Num(1)), list(context_, Sym("display"), Sym("a")))); ASSERT_TRUE(deepEqual(parsed.getValue().at(0), l)); } } // anonymous namespace
// ImgCore.h // 图像处理函数 #include <string> #include "opencv2/core/core.hpp" #include "opencv2/imgproc/imgproc.hpp" using namespace cv; #define free_ptr(p) if(p) delete p; p = NULL; /* 去除噪音 op: MORPH_OPEN – 开运算(Opening operation) MORPH_CLOSE – 闭运算(Closing operation) MORPH_GRADIENT -形态学梯度(Morphological gradient) MORPH_TOPHAT - “顶帽”(“Top hat”) MORPH_BLACKHAT - “黑帽”(“Black hat“) */ void move_noise(const Mat img_in, Mat &img_out, int kernel, int op, const int repeat=5); /* 获得直方图 */ void get_histogram(const Mat img, Mat &hist); /* 通过softmax算法获得阈值 */ int get_threshed_value_by_softmax(const Mat &img, const Mat &weight); /* * 保存图片 * @para img_path 图像完整路径 * @para mid_name 图像保存后的中间名 */ void save_image(const std::string &img_path, const Mat &img, const std::string &mid_name=""); /* 去除周围空白区域 */ void remove_margin(const Mat img, const Mat &threshed_img, Mat &out_put); /* 归一化 */ void norm_to_size(const Mat img, Mat &output, int size=256); /* 图像分割 */ class Model { public: virtual ~Model(){}; virtual void apply(const Mat &src, const Mat &threshed_img, Mat &dst_src, Mat &dst_threshed) = 0; }; class Roi_region : public Model { public: void apply(const Mat &src, const Mat &threshed_img, Mat &dst_src, Mat &dst_threshed); }; class Max_region : public Model { public: void apply(const Mat &src, const Mat &threshed_img, Mat &dst_src, Mat &dst_threshed); }; class Seg { public: Seg() = delete; Seg(int seg_model=0) : _model_name(seg_model) { _choose_model(seg_model); }; ~Seg() {free_ptr(_model);}; void _choose_model(int model_name); void apply(const Mat &src, const Mat &threshed_img, Mat &dst_src, Mat &dst_threshed); private: int _model_name; Model *_model; };
int ComputeSYMGS_omp( const SparseMatrix & A, const Vector & r, Vector & x, int is_first) { // This line and the next two lines should be removed and your version of ComputeSYMGS should be used. //return ComputeSYMGS_ref(A, r, x); assert(x.localLength==A.localNumberOfColumns); // Make sure x contain space for halo values OPT* opt = (OPT*)(A.optimizationData); const ELL* ell = opt->ell; const double* a = ell->a; const local_int_t* ja = ell->ja; const local_int_t lda = ell->lda; const local_int_t m = ell->m; #ifdef WEIRDTEST const local_int_t mL = ell->mL; const local_int_t mU = ell->mU; #endif const local_int_t n = ell->n; const double alpha = -1.0; const double beta = +1.0; const double* diag = opt->diag; double* idiag = opt->idiag; double* work1 = opt->work1; double* work2 = opt->work2; const local_int_t* icptr = opt->icptr; const local_int_t maxcolor = opt->maxcolor; const local_int_t minhalocolor = opt->minhalocolor; int exchg_calls = 1; const double * const rv = r.values; double * const xv = x.values; local_int_t ics, ice, nn; local_int_t color = 0; omp_barrier_type barr; int nt = omp_get_max_threads(); ///////////////////////// // Now the forward sweep. ///////////////////////// omp_barrier_init(&barr, nt - 1); #pragma omp parallel default(shared) private(ics,ice) { local_int_t ics, ice; // redeclare here, we don't want any private() local_int_t ist, iend, ilen, inc; local_int_t ic = color; int t = omp_get_thread_num(); inc = (n + nt - 1) / nt; ist = t*inc; #pragma omp for schedule(static) for(local_int_t i=0; i<n; i++){ work1[i] = work2[i] = rv[i]; } #ifndef HPCG_NO_MPI #ifdef HYPERCUBE if (t == 0) { ExchangeHalo(A, x, is_first); exchg_calls = 0; } else { // overlap halo exchange with computation, thread #0 does the exchange while (exchg_calls > 0 && ic < minhalocolor) { ics = icptr[ic]; ice = icptr[ic+1]; inc = (ice - ics + nt - 2) / (nt - 1); for (ist=ics+(t-1)*inc; ist<ice; ist+=(nt-1)*inc) { iend = MIN(ist + inc, ice); ilen = iend - ist; gs_block_sweep(ist, iend, a, idiag, lda, m, ja, xv, work1); } // this is a "manual" barrier for all threads but #0 omp_barrier(&barr); ic++; if (t == 1) color = ic; } } #else // HYPERCUBE if (t == 0) { ExchangeHalo(A, x, is_first); exchg_calls = 0; } #endif // HYPERCUBE #endif // HPCG_NO_MPI #pragma omp barrier //ic = color; // thread #0 must know where we are for (ic = color; ic < maxcolor; ic++) { ics = icptr[ic]; ice = icptr[ic+1]; inc = (ice - ics + nt - 1) / nt; #pragma omp for schedule(static,1) for (ist=ics; ist<ice; ist+=inc) { iend = MIN(ist + inc, ice); ilen = iend - ist; gs_block_sweep(ist, iend, a, idiag, lda, m, ja, xv, work1); } } ////////////////////// // Now the back sweep. ////////////////////// for (ic = maxcolor - 1; ic >= 0; ic--) { ics = icptr[ic]; ice = icptr[ic+1]; inc = (ice - ics + nt - 1) / nt; #pragma omp for schedule(static,1) for (ist=ics; ist<ice; ist+=inc) { iend = MIN(ist + inc, ice); ilen = iend - ist; gs_block_sweep(ist, iend, a, idiag, lda, m, ja, xv, work2); } } } // end omp parallel block return 0; }
/**************************************************************************** * * Copyright (c) 2015 Estimation and Control Library (ECL). 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 ECL 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 control.cpp * Control functions for ekf attitude and position estimator. * * @author Paul Riseborough <p_riseborough@live.com.au> * */ #include "../ecl.h" #include "ekf.h" #include <mathlib/mathlib.h> void Ekf::controlFusionModes() { // Store the status to enable change detection _control_status_prev.value = _control_status.value; // Get the magnetic declination calcMagDeclination(); // monitor the tilt alignment if (!_control_status.flags.tilt_align) { // whilst we are aligning the tilt, monitor the variances Vector3f angle_err_var_vec = calcRotVecVariances(); // Once the tilt variances have reduced to equivalent of 3deg uncertainty, re-set the yaw and magnetic field states // and declare the tilt alignment complete if ((angle_err_var_vec(0) + angle_err_var_vec(1)) < sq(0.05235f)) { _control_status.flags.tilt_align = true; _control_status.flags.yaw_align = resetMagHeading(_mag_sample_delayed.mag); // send alignment status message to the console if (_control_status.flags.baro_hgt) { ECL_INFO("EKF aligned, (pressure height, IMU buf: %i, OBS buf: %i)", (int)_imu_buffer_length, (int)_obs_buffer_length); } else if (_control_status.flags.ev_hgt) { ECL_INFO("EKF aligned, (EV height, IMU buf: %i, OBS buf: %i)", (int)_imu_buffer_length, (int)_obs_buffer_length); } else if (_control_status.flags.gps_hgt) { ECL_INFO("EKF aligned, (GPS height, IMU buf: %i, OBS buf: %i)", (int)_imu_buffer_length, (int)_obs_buffer_length); } else if (_control_status.flags.rng_hgt) { ECL_INFO("EKF aligned, (range height, IMU buf: %i, OBS buf: %i)", (int)_imu_buffer_length, (int)_obs_buffer_length); } else { ECL_ERR("EKF aligned, (unknown height, IMU buf: %i, OBS buf: %i)", (int)_imu_buffer_length, (int)_obs_buffer_length); } } } // check faultiness (before pop_first_older_than) to see if we can change back to original height sensor const baroSample &baro_init = _baro_buffer.get_newest(); _baro_hgt_faulty = !((_time_last_imu - baro_init.time_us) < 2 * BARO_MAX_INTERVAL); const gpsSample &gps_init = _gps_buffer.get_newest(); _gps_hgt_faulty = !((_time_last_imu - gps_init.time_us) < 2 * GPS_MAX_INTERVAL); const rangeSample &rng_init = _range_buffer.get_newest(); _rng_hgt_faulty = !((_time_last_imu - rng_init.time_us) < 2 * RNG_MAX_INTERVAL); // check for arrival of new sensor data at the fusion time horizon _gps_data_ready = _gps_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_gps_sample_delayed); _mag_data_ready = _mag_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_mag_sample_delayed); _delta_time_baro_us = _baro_sample_delayed.time_us; _baro_data_ready = _baro_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_baro_sample_delayed); // if we have a new baro sample save the delta time between this sample and the last sample which is // used below for baro offset calculations if (_baro_data_ready) { _delta_time_baro_us = _baro_sample_delayed.time_us - _delta_time_baro_us; } // calculate 2,2 element of rotation matrix from sensor frame to earth frame _R_rng_to_earth_2_2 = _R_to_earth(2, 0) * _sin_tilt_rng + _R_to_earth(2, 2) * _cos_tilt_rng; _range_data_ready = _range_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_range_sample_delayed) && (_R_rng_to_earth_2_2 > _params.range_cos_max_tilt); checkForStuckRange(); _flow_data_ready = _flow_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_flow_sample_delayed) && (_R_to_earth(2, 2) > 0.7071f); _ev_data_ready = _ext_vision_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_ev_sample_delayed); _tas_data_ready = _airspeed_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_airspeed_sample_delayed); // check for height sensor timeouts and reset and change sensor if necessary controlHeightSensorTimeouts(); // control use of observations for aiding controlMagFusion(); controlOpticalFlowFusion(); controlGpsFusion(); controlAirDataFusion(); controlBetaFusion(); controlDragFusion(); controlHeightFusion(); // For efficiency, fusion of direct state observations for position and velocity is performed sequentially // in a single function using sensor data from multiple sources (GPS, baro, range finder, etc) controlVelPosFusion(); // Additional data from an external vision pose estimator can be fused. controlExternalVisionFusion(); // Additional NE velocity data from an auxiliary sensor can be fused controlAuxVelFusion(); // check if we are no longer fusing measurements that directly constrain velocity drift update_deadreckoning_status(); } void Ekf::controlExternalVisionFusion() { // Check for new exernal vision data if (_ev_data_ready) { // if the ev data is not in a NED reference frame, then the transformation between EV and EKF navigation frames // needs to be calculated and the observations rotated into the EKF frame of reference if ((_params.fusion_mode & MASK_ROTATE_EV) && (_params.fusion_mode & MASK_USE_EVPOS) && !_control_status.flags.ev_yaw) { // rotate EV measurements into the EKF Navigation frame calcExtVisRotMat(); } // external vision position aiding selection logic if ((_params.fusion_mode & MASK_USE_EVPOS) && !_control_status.flags.ev_pos && _control_status.flags.tilt_align && _control_status.flags.yaw_align) { // check for a exernal vision measurement that has fallen behind the fusion time horizon if (_time_last_imu - _time_last_ext_vision < 2 * EV_MAX_INTERVAL) { // turn on use of external vision measurements for position _control_status.flags.ev_pos = true; ECL_INFO("EKF commencing external vision position fusion"); // reset the position if we are not already aiding using GPS, else use a relative position // method for fusing the position data if (_control_status.flags.gps) { _fuse_hpos_as_odom = true; } else { resetPosition(); resetVelocity(); } } } // external vision yaw aiding selection logic if (!_control_status.flags.gps && (_params.fusion_mode & MASK_USE_EVYAW) && !_control_status.flags.ev_yaw && _control_status.flags.tilt_align) { // don't start using EV data unless daa is arriving frequently if (_time_last_imu - _time_last_ext_vision < 2 * EV_MAX_INTERVAL) { // reset the yaw angle to the value from the observaton quaternion // get the roll, pitch, yaw estimates from the quaternion states Quatf q_init(_state.quat_nominal); Eulerf euler_init(q_init); // get initial yaw from the observation quaternion const extVisionSample &ev_newest = _ext_vision_buffer.get_newest(); Quatf q_obs(ev_newest.quat); Eulerf euler_obs(q_obs); euler_init(2) = euler_obs(2); // save a copy of the quaternion state for later use in calculating the amount of reset change Quatf quat_before_reset = _state.quat_nominal; // calculate initial quaternion states for the ekf _state.quat_nominal = Quatf(euler_init); // calculate the amount that the quaternion has changed by _state_reset_status.quat_change = quat_before_reset.inversed() * _state.quat_nominal; // add the reset amount to the output observer buffered data // Note q1 *= q2 is equivalent to q1 = q2 * q1 for (uint8_t i = 0; i < _output_buffer.get_length(); i++) { _output_buffer[i].quat_nominal *= _state_reset_status.quat_change; } // apply the change in attitude quaternion to our newest quaternion estimate // which was already taken out from the output buffer _output_new.quat_nominal = _state_reset_status.quat_change * _output_new.quat_nominal; // capture the reset event _state_reset_status.quat_counter++; // flag the yaw as aligned _control_status.flags.yaw_align = true; // turn on fusion of external vision yaw measurements and disable all magnetoemter fusion _control_status.flags.ev_yaw = true; _control_status.flags.mag_hdg = false; _control_status.flags.mag_3D = false; _control_status.flags.mag_dec = false; ECL_INFO("EKF commencing external vision yaw fusion"); } } // determine if we should start using the height observations if (_params.vdist_sensor_type == VDIST_SENSOR_EV) { // don't start using EV data unless data is arriving frequently if (!_control_status.flags.ev_hgt && (_time_last_imu - _time_last_ext_vision < 2 * EV_MAX_INTERVAL)) { setControlEVHeight(); resetHeight(); } } // determine if we should use the vertical position observation if (_control_status.flags.ev_hgt) { _fuse_height = true; } // determine if we should use the horizontal position observations if (_control_status.flags.ev_pos) { _fuse_pos = true; // correct position and height for offset relative to IMU Vector3f pos_offset_body = _params.ev_pos_body - _params.imu_pos_body; Vector3f pos_offset_earth = _R_to_earth * pos_offset_body; _ev_sample_delayed.posNED(0) -= pos_offset_earth(0); _ev_sample_delayed.posNED(1) -= pos_offset_earth(1); _ev_sample_delayed.posNED(2) -= pos_offset_earth(2); // Use an incremental position fusion method for EV data if using GPS or if the observations are not in NED if (_control_status.flags.gps || (_params.fusion_mode & MASK_ROTATE_EV)) { _fuse_hpos_as_odom = true; } else { _fuse_hpos_as_odom = false; } if (_fuse_hpos_as_odom) { if (!_hpos_prev_available) { // no previous observation available to calculate position change _fuse_pos = false; _hpos_prev_available = true; } else { // calculate the change in position since the last measurement Vector3f ev_delta_pos = _ev_sample_delayed.posNED - _pos_meas_prev; // rotate measurement into body frame if required if (_params.fusion_mode & MASK_ROTATE_EV) { ev_delta_pos = _ev_rot_mat * ev_delta_pos; } // use the change in position since the last measurement _vel_pos_innov[3] = _state.pos(0) - _hpos_pred_prev(0) - ev_delta_pos(0); _vel_pos_innov[4] = _state.pos(1) - _hpos_pred_prev(1) - ev_delta_pos(1); } // record observation and estimate for use next time _pos_meas_prev = _ev_sample_delayed.posNED; _hpos_pred_prev(0) = _state.pos(0); _hpos_pred_prev(1) = _state.pos(1); } else { // use the absolute position _vel_pos_innov[3] = _state.pos(0) - _ev_sample_delayed.posNED(0); _vel_pos_innov[4] = _state.pos(1) - _ev_sample_delayed.posNED(1); // check if we have been deadreckoning too long if (_time_last_imu - _time_last_pos_fuse > _params.no_gps_timeout_max) { // don't reset velocity if we have another source of aiding constraining it if (_time_last_imu - _time_last_of_fuse > (uint64_t)1E6) { resetVelocity(); } resetPosition(); } } // observation 1-STD error _posObsNoiseNE = fmaxf(_ev_sample_delayed.posErr, 0.01f); // innovation gate size _posInnovGateNE = fmaxf(_params.ev_innov_gate, 1.0f); } // Fuse available NED position data into the main filter if (_fuse_height || _fuse_pos) { fuseVelPosHeight(); _fuse_pos = _fuse_height = false; _fuse_hpos_as_odom = false; } // determine if we should use the yaw observation if (_control_status.flags.ev_yaw) { fuseHeading(); } } else if (_control_status.flags.ev_pos && (_time_last_imu >= _time_last_ext_vision) && (_time_last_imu - _time_last_ext_vision > (uint64_t)_params.no_gps_timeout_max)) { // Turn off EV fusion mode if no data has been received _control_status.flags.ev_pos = false; ECL_INFO("EKF External Vision Data Stopped"); } } void Ekf::controlOpticalFlowFusion() { // Check if on ground motion is un-suitable for use of optical flow if (!_control_status.flags.in_air) { // When on ground check if the vehicle is being shaken or moved in a way that could cause a loss of navigation float accel_norm = _accel_vec_filt.norm(); bool motion_is_excessive = ((accel_norm > 14.7f) // accel greater than 1.5g || (accel_norm < 4.9f) // accel less than 0.5g || (_ang_rate_mag_filt > _flow_max_rate) // angular rate exceeds flow sensor limit || (_R_to_earth(2,2) < 0.866f)); // tilted more than 30 degrees if (motion_is_excessive) { _time_bad_motion_us = _imu_sample_delayed.time_us; } else { _time_good_motion_us = _imu_sample_delayed.time_us; } } else { _time_bad_motion_us = 0; _time_good_motion_us = _imu_sample_delayed.time_us; } // New optical flow data has fallen behind the fusion time horizon and is ready to be fused if (_flow_data_ready) { // Inhibit flow use if motion is un-suitable or we have good quality GPS // Apply hysteresis to prevent rapid mode switching float gps_err_norm_lim; if (_control_status.flags.opt_flow) { gps_err_norm_lim = 0.7f; } else { gps_err_norm_lim = 1.0f; } // Check if we are in-air and require optical flow to control position drift bool flow_required = _control_status.flags.in_air && (_is_dead_reckoning // is doing inertial dead-reckoning so must constrain drift urgently || (_control_status.flags.opt_flow && !_control_status.flags.gps && !_control_status.flags.ev_pos) // is completely reliant on optical flow || (_control_status.flags.gps && (_gps_error_norm > gps_err_norm_lim))); // is using GPS, but GPS is bad if (!_inhibit_flow_use && _control_status.flags.opt_flow) { // inhibit use of optical flow if motion is unsuitable and we are not reliant on it for flight navigation bool preflight_motion_not_ok = !_control_status.flags.in_air && ((_imu_sample_delayed.time_us - _time_good_motion_us) > (uint64_t)1E5); bool flight_motion_not_ok = _control_status.flags.in_air && !_range_aid_mode_enabled; if ((preflight_motion_not_ok || flight_motion_not_ok) && !flow_required) { _inhibit_flow_use = true; } } else if (_inhibit_flow_use && !_control_status.flags.opt_flow){ // allow use of optical flow if motion is suitable or we are reliant on it for flight navigation bool preflight_motion_ok = !_control_status.flags.in_air && ((_imu_sample_delayed.time_us - _time_bad_motion_us) > (uint64_t)5E6); bool flight_motion_ok = _control_status.flags.in_air && _range_aid_mode_enabled; if (preflight_motion_ok || flight_motion_ok || flow_required) { _inhibit_flow_use = false; } } // Handle cases where we are using optical flow but are no longer able to because data is old // or its use has been inhibited. if (_control_status.flags.opt_flow) { if (_inhibit_flow_use) { _control_status.flags.opt_flow = false; _time_last_of_fuse = 0; } else if (_time_last_imu - _flow_sample_delayed.time_us > (uint64_t)_params.no_gps_timeout_max) { _control_status.flags.opt_flow = false; } } // Accumulate autopilot gyro data across the same time interval as the flow sensor _imu_del_ang_of += _imu_sample_delayed.delta_ang - _state.gyro_bias; _delta_time_of += _imu_sample_delayed.delta_ang_dt; // optical flow fusion mode selection logic if ((_params.fusion_mode & MASK_USE_OF) // optical flow has been selected by the user && !_control_status.flags.opt_flow // we are not yet using flow data && _control_status.flags.tilt_align // we know our tilt attitude && !_inhibit_flow_use && get_terrain_valid()) // we have a valid distance to ground estimate { // If the heading is not aligned, reset the yaw and magnetic field states if (!_control_status.flags.yaw_align) { _control_status.flags.yaw_align = resetMagHeading(_mag_sample_delayed.mag); } // If the heading is valid and use is not inhibited , start using optical flow aiding if (_control_status.flags.yaw_align) { // set the flag and reset the fusion timeout _control_status.flags.opt_flow = true; _time_last_of_fuse = _time_last_imu; // if we are not using GPS then the velocity and position states and covariances need to be set if (!_control_status.flags.gps || !_control_status.flags.ev_pos) { resetVelocity(); resetPosition(); // align the output observer to the EKF states alignOutputFilter(); } } } else if (!(_params.fusion_mode & MASK_USE_OF)) { _control_status.flags.opt_flow = false; } // handle the case when we have optical flow, are reliant on it, but have not been using it for an extended period if (_control_status.flags.opt_flow && !_control_status.flags.gps && !_control_status.flags.ev_pos) { bool do_reset = _time_last_imu - _time_last_of_fuse > _params.no_gps_timeout_max; if (do_reset) { resetVelocity(); resetPosition(); } } // fuse the data if the terrain/distance to bottom is valid but use a more relaxed check to enable it to survive bad range finder data if (_control_status.flags.opt_flow && (_time_last_imu - _time_last_hagl_fuse < (uint64_t)10e6)) { // Update optical flow bias estimates calcOptFlowBias(); // Fuse optical flow LOS rate observations into the main filter fuseOptFlow(); _last_known_posNE(0) = _state.pos(0); _last_known_posNE(1) = _state.pos(1); } } } void Ekf::controlGpsFusion() { // Check for new GPS data that has fallen behind the fusion time horizon if (_gps_data_ready) { // Determine if we should use GPS aiding for velocity and horizontal position // To start using GPS we need angular alignment completed, the local NED origin set and GPS data that has not failed checks recently bool gps_checks_passing = (_time_last_imu - _last_gps_fail_us > (uint64_t)5e6); bool gps_checks_failing = (_time_last_imu - _last_gps_pass_us > (uint64_t)5e6); if ((_params.fusion_mode & MASK_USE_GPS) && !_control_status.flags.gps) { if (_control_status.flags.tilt_align && _NED_origin_initialised && gps_checks_passing) { // If the heading is not aligned, reset the yaw and magnetic field states // Do not use external vision for yaw if using GPS because yaw needs to be // defined relative to an NED reference frame if (!_control_status.flags.yaw_align || _control_status.flags.ev_yaw || _mag_inhibit_yaw_reset_req) { _control_status.flags.yaw_align = false; _control_status.flags.ev_yaw = false; _control_status.flags.yaw_align = resetMagHeading(_mag_sample_delayed.mag); // Handle the special case where we have not been constraining yaw drift or learning yaw bias due // to assumed invalid mag field associated with indoor operation with a downwards looking flow sensor. if (_mag_inhibit_yaw_reset_req) { _mag_inhibit_yaw_reset_req = false; // Zero the yaw bias covariance and set the variance to the initial alignment uncertainty float dt = 0.001f * (float)FILTER_UPDATE_PERIOD_MS; setDiag(P, 12, 12, sq(_params.switch_on_gyro_bias * dt)); } } // If the heading is valid start using gps aiding if (_control_status.flags.yaw_align) { // if we are not already aiding with optical flow, then we need to reset the position and velocity // otherwise we only need to reset the position _control_status.flags.gps = true; if (!_control_status.flags.opt_flow) { if (!resetPosition() || !resetVelocity()) { _control_status.flags.gps = false; } } else if (!resetPosition()) { _control_status.flags.gps = false; } if (_control_status.flags.gps) { ECL_INFO("EKF commencing GPS fusion"); _time_last_gps = _time_last_imu; } } } } else if (!(_params.fusion_mode & MASK_USE_GPS)) { _control_status.flags.gps = false; } // Handle the case where we are using GPS and another source of aiding and GPS is failing checks if (_control_status.flags.gps && gps_checks_failing && (_control_status.flags.opt_flow || _control_status.flags.ev_pos)) { _control_status.flags.gps = false; ECL_WARN("EKF GPS data quality poor - stopping use"); } // handle the case when we now have GPS, but have not been using it for an extended period if (_control_status.flags.gps) { // We are relying on aiding to constrain drift so after a specified time // with no aiding we need to do something bool do_reset = (_time_last_imu - _time_last_pos_fuse > _params.no_gps_timeout_max) && (_time_last_imu - _time_last_delpos_fuse > _params.no_gps_timeout_max) && (_time_last_imu - _time_last_vel_fuse > _params.no_gps_timeout_max) && (_time_last_imu - _time_last_of_fuse > _params.no_gps_timeout_max); // We haven't had an absolute position fix for a longer time so need to do something do_reset = do_reset || (_time_last_imu - _time_last_pos_fuse > 2 * _params.no_gps_timeout_max); if (do_reset) { // use GPS velocity data to check and correct yaw angle if a FW vehicle if (_control_status.flags.fixed_wing && _control_status.flags.in_air) { // if flying a fixed wing aircraft, do a complete reset that includes yaw realignYawGPS(); } resetVelocity(); resetPosition(); _velpos_reset_request = false; ECL_WARN("EKF GPS fusion timeout - reset to GPS"); // Reset the timeout counters _time_last_pos_fuse = _time_last_imu; _time_last_vel_fuse = _time_last_imu; } } // Only use GPS data for position and velocity aiding if enabled if (_control_status.flags.gps) { _fuse_pos = true; _fuse_vert_vel = true; _fuse_hor_vel = true; // correct velocity for offset relative to IMU Vector3f ang_rate = _imu_sample_delayed.delta_ang * (1.0f / _imu_sample_delayed.delta_ang_dt); Vector3f pos_offset_body = _params.gps_pos_body - _params.imu_pos_body; Vector3f vel_offset_body = cross_product(ang_rate, pos_offset_body); Vector3f vel_offset_earth = _R_to_earth * vel_offset_body; _gps_sample_delayed.vel -= vel_offset_earth; // correct position and height for offset relative to IMU Vector3f pos_offset_earth = _R_to_earth * pos_offset_body; _gps_sample_delayed.pos(0) -= pos_offset_earth(0); _gps_sample_delayed.pos(1) -= pos_offset_earth(1); _gps_sample_delayed.hgt += pos_offset_earth(2); // calculate observation process noise float lower_limit = fmaxf(_params.gps_pos_noise, 0.01f); if (_control_status.flags.opt_flow || _control_status.flags.ev_pos) { // if we are using other sources of aiding, then relax the upper observation // noise limit which prevents bad GPS perturbing the position estimate _posObsNoiseNE = fmaxf(_gps_sample_delayed.hacc, lower_limit); } else { // if we are not using another source of aiding, then we are reliant on the GPS // observations to constrain attitude errors and must limit the observation noise value. float upper_limit = fmaxf(_params.pos_noaid_noise, lower_limit); _posObsNoiseNE = math::constrain(_gps_sample_delayed.hacc, lower_limit, upper_limit); } _velObsVarNE(1) = _velObsVarNE(0) = sq(fmaxf(_gps_sample_delayed.sacc, _params.gps_vel_noise)); // calculate innovations _vel_pos_innov[0] = _state.vel(0) - _gps_sample_delayed.vel(0); _vel_pos_innov[1] = _state.vel(1) - _gps_sample_delayed.vel(1); _vel_pos_innov[2] = _state.vel(2) - _gps_sample_delayed.vel(2); _vel_pos_innov[3] = _state.pos(0) - _gps_sample_delayed.pos(0); _vel_pos_innov[4] = _state.pos(1) - _gps_sample_delayed.pos(1); // set innovation gate size _posInnovGateNE = fmaxf(_params.posNE_innov_gate, 1.0f); _hvelInnovGate = fmaxf(_params.vel_innov_gate, 1.0f); } } else if (_control_status.flags.gps && (_imu_sample_delayed.time_us - _gps_sample_delayed.time_us > (uint64_t)10e6)) { _control_status.flags.gps = false; ECL_WARN("EKF GPS data stopped"); } } void Ekf::controlHeightSensorTimeouts() { /* * Handle the case where we have not fused height measurements recently and * uncertainty exceeds the max allowable. Reset using the best available height * measurement source, continue using it after the reset and declare the current * source failed if we have switched. */ // Check for IMU accelerometer vibration induced clipping as evidenced by the vertical innovations being positive and not stale. // Clipping causes the average accel reading to move towards zero which makes the INS think it is falling and produces positive vertical innovations float var_product_lim = sq(_params.vert_innov_test_lim) * sq(_params.vert_innov_test_lim); bool bad_vert_accel = (_control_status.flags.baro_hgt && // we can only run this check if vertical position and velocity observations are indepedant (sq(_vel_pos_innov[5] * _vel_pos_innov[2]) > var_product_lim * (_vel_pos_innov_var[5] * _vel_pos_innov_var[2])) && // vertical position and velocity sensors are in agreement that we have a significant error (_vel_pos_innov[2] > 0.0f) && // positive innovation indicates that the inertial nav thinks it is falling ((_imu_sample_delayed.time_us - _baro_sample_delayed.time_us) < 2 * BARO_MAX_INTERVAL) && // vertical position data is fresh ((_imu_sample_delayed.time_us - _gps_sample_delayed.time_us) < 2 * GPS_MAX_INTERVAL)); // vertical velocity data is fresh // record time of last bad vert accel if (bad_vert_accel) { _time_bad_vert_accel = _time_last_imu; } else { _time_good_vert_accel = _time_last_imu; } // declare a bad vertical acceleration measurement and make the declaration persist // for a minimum of 10 seconds if (_bad_vert_accel_detected) { _bad_vert_accel_detected = (_time_last_imu - _time_bad_vert_accel < BADACC_PROBATION); } else { _bad_vert_accel_detected = bad_vert_accel; } // check if height is continuously failing becasue of accel errors bool continuous_bad_accel_hgt = ((_time_last_imu - _time_good_vert_accel) > (unsigned)_params.bad_acc_reset_delay_us); // check if height has been inertial deadreckoning for too long bool hgt_fusion_timeout = ((_time_last_imu - _time_last_hgt_fuse) > (uint64_t)5e6); // reset the vertical position and velocity states if (hgt_fusion_timeout || continuous_bad_accel_hgt) { // boolean that indicates we will do a height reset bool reset_height = false; // handle the case where we are using baro for height if (_control_status.flags.baro_hgt) { // check if GPS height is available const gpsSample &gps_init = _gps_buffer.get_newest(); bool gps_hgt_available = ((_time_last_imu - gps_init.time_us) < 2 * GPS_MAX_INTERVAL); bool gps_hgt_accurate = (gps_init.vacc < _params.req_vacc); const baroSample &baro_init = _baro_buffer.get_newest(); bool baro_hgt_available = ((_time_last_imu - baro_init.time_us) < 2 * BARO_MAX_INTERVAL); // check for inertial sensing errors in the last 10 seconds bool prev_bad_vert_accel = (_time_last_imu - _time_bad_vert_accel < BADACC_PROBATION); // reset to GPS if adequate GPS data is available and the timeout cannot be blamed on IMU data bool reset_to_gps = gps_hgt_available && gps_hgt_accurate && !_gps_hgt_faulty && !prev_bad_vert_accel; // reset to GPS if GPS data is available and there is no Baro data reset_to_gps = reset_to_gps || (gps_hgt_available && !baro_hgt_available); // reset to Baro if we are not doing a GPS reset and baro data is available bool reset_to_baro = !reset_to_gps && baro_hgt_available; if (reset_to_gps) { // set height sensor health _baro_hgt_faulty = true; // declare the GPS height healthy _gps_hgt_faulty = false; // reset the height mode setControlGPSHeight(); // request a reset reset_height = true; ECL_WARN("EKF baro hgt timeout - reset to GPS"); } else if (reset_to_baro) { // set height sensor health _baro_hgt_faulty = false; // reset the height mode setControlBaroHeight(); // request a reset reset_height = true; ECL_WARN("EKF baro hgt timeout - reset to baro"); } else { // we have nothing we can reset to // deny a reset reset_height = false; } } // handle the case we are using GPS for height if (_control_status.flags.gps_hgt) { // check if GPS height is available const gpsSample &gps_init = _gps_buffer.get_newest(); bool gps_hgt_available = ((_time_last_imu - gps_init.time_us) < 2 * GPS_MAX_INTERVAL); bool gps_hgt_accurate = (gps_init.vacc < _params.req_vacc); // check the baro height source for consistency and freshness const baroSample &baro_init = _baro_buffer.get_newest(); bool baro_data_fresh = ((_time_last_imu - baro_init.time_us) < 2 * BARO_MAX_INTERVAL); float baro_innov = _state.pos(2) - (_hgt_sensor_offset - baro_init.hgt + _baro_hgt_offset); bool baro_data_consistent = fabsf(baro_innov) < (sq(_params.baro_noise) + P[9][9]) * sq(_params.baro_innov_gate); // if baro data is acceptable and GPS data is inaccurate, reset height to baro bool reset_to_baro = baro_data_consistent && baro_data_fresh && !_baro_hgt_faulty && !gps_hgt_accurate; // if GPS height is unavailable and baro data is available, reset height to baro reset_to_baro = reset_to_baro || (!gps_hgt_available && baro_data_fresh); // if we cannot switch to baro and GPS data is available, reset height to GPS bool reset_to_gps = !reset_to_baro && gps_hgt_available; if (reset_to_baro) { // set height sensor health _gps_hgt_faulty = true; _baro_hgt_faulty = false; // reset the height mode setControlBaroHeight(); // request a reset reset_height = true; ECL_WARN("EKF gps hgt timeout - reset to baro"); } else if (reset_to_gps) { // set height sensor health _gps_hgt_faulty = false; // reset the height mode setControlGPSHeight(); // request a reset reset_height = true; ECL_WARN("EKF gps hgt timeout - reset to GPS"); } else { // we have nothing to reset to reset_height = false; } } // handle the case we are using range finder for height if (_control_status.flags.rng_hgt) { // check if range finder data is available const rangeSample &rng_init = _range_buffer.get_newest(); bool rng_data_available = ((_time_last_imu - rng_init.time_us) < 2 * RNG_MAX_INTERVAL); // check if baro data is available const baroSample &baro_init = _baro_buffer.get_newest(); bool baro_data_available = ((_time_last_imu - baro_init.time_us) < 2 * BARO_MAX_INTERVAL); // reset to baro if we have no range data and baro data is available bool reset_to_baro = !rng_data_available && baro_data_available; // reset to range data if it is available bool reset_to_rng = rng_data_available; if (reset_to_baro) { // set height sensor health _rng_hgt_faulty = true; _baro_hgt_faulty = false; // reset the height mode setControlBaroHeight(); // request a reset reset_height = true; ECL_WARN("EKF rng hgt timeout - reset to baro"); } else if (reset_to_rng) { // set height sensor health _rng_hgt_faulty = false; // reset the height mode setControlRangeHeight(); // request a reset reset_height = true; ECL_WARN("EKF rng hgt timeout - reset to rng hgt"); } else { // we have nothing to reset to reset_height = false; } } // handle the case where we are using external vision data for height if (_control_status.flags.ev_hgt) { // check if vision data is available const extVisionSample &ev_init = _ext_vision_buffer.get_newest(); bool ev_data_available = ((_time_last_imu - ev_init.time_us) < 2 * EV_MAX_INTERVAL); // check if baro data is available const baroSample &baro_init = _baro_buffer.get_newest(); bool baro_data_available = ((_time_last_imu - baro_init.time_us) < 2 * BARO_MAX_INTERVAL); // reset to baro if we have no vision data and baro data is available bool reset_to_baro = !ev_data_available && baro_data_available; // reset to ev data if it is available bool reset_to_ev = ev_data_available; if (reset_to_baro) { // set height sensor health _baro_hgt_faulty = false; // reset the height mode setControlBaroHeight(); // request a reset reset_height = true; ECL_WARN("EKF ev hgt timeout - reset to baro"); } else if (reset_to_ev) { // reset the height mode setControlEVHeight(); // request a reset reset_height = true; ECL_WARN("EKF ev hgt timeout - reset to ev hgt"); } else { // we have nothing to reset to reset_height = false; } } // Reset vertical position and velocity states to the last measurement if (reset_height) { resetHeight(); // Reset the timout timer _time_last_hgt_fuse = _time_last_imu; } } } void Ekf::controlHeightFusion() { // set control flags for the desired primary height source if (_range_data_ready) { // correct the range data for position offset relative to the IMU Vector3f pos_offset_body = _params.rng_pos_body - _params.imu_pos_body; Vector3f pos_offset_earth = _R_to_earth * pos_offset_body; _range_sample_delayed.rng += pos_offset_earth(2) / _R_rng_to_earth_2_2; } rangeAidConditionsMet(); _range_aid_mode_selected = (_params.range_aid == 1) && _range_aid_mode_enabled; if (_params.vdist_sensor_type == VDIST_SENSOR_BARO) { if (_range_aid_mode_selected && _range_data_ready && !_rng_hgt_faulty) { setControlRangeHeight(); _fuse_height = true; // we have just switched to using range finder, calculate height sensor offset such that current // measurment matches our current height estimate if (_control_status_prev.flags.rng_hgt != _control_status.flags.rng_hgt) { if (get_terrain_valid()) { _hgt_sensor_offset = _terrain_vpos; } else { _hgt_sensor_offset = _R_rng_to_earth_2_2 * _range_sample_delayed.rng + _state.pos(2); } } } else if (!_range_aid_mode_selected && _baro_data_ready && !_baro_hgt_faulty) { setControlBaroHeight(); _fuse_height = true; // we have just switched to using baro height, we don't need to set a height sensor offset // since we track a separate _baro_hgt_offset if (_control_status_prev.flags.baro_hgt != _control_status.flags.baro_hgt) { _hgt_sensor_offset = 0.0f; } // Turn off ground effect compensation if it times out or sufficient height has been gained // since takeoff. if (_control_status.flags.gnd_effect) { if ((_time_last_imu - _time_last_gnd_effect_on > GNDEFFECT_TIMEOUT) || (((_last_on_ground_posD - _state.pos(2)) > _params.gnd_effect_max_hgt) && _control_status.flags.in_air)) { _control_status.flags.gnd_effect = false; } } } else if (_control_status.flags.gps_hgt && _gps_data_ready && !_gps_hgt_faulty) { // switch to gps if there was a reset to gps _fuse_height = true; // we have just switched to using gps height, calculate height sensor offset such that current // measurment matches our current height estimate if (_control_status_prev.flags.gps_hgt != _control_status.flags.gps_hgt) { _hgt_sensor_offset = _gps_sample_delayed.hgt - _gps_alt_ref + _state.pos(2); } } } // set the height data source to range if requested if ((_params.vdist_sensor_type == VDIST_SENSOR_RANGE) && !_rng_hgt_faulty) { setControlRangeHeight(); _fuse_height = _range_data_ready; // we have just switched to using range finder, calculate height sensor offset such that current // measurment matches our current height estimate if (_control_status_prev.flags.rng_hgt != _control_status.flags.rng_hgt) { // use the parameter rng_gnd_clearance if on ground to avoid a noisy offset initialization (e.g. sonar) if (_control_status.flags.in_air && get_terrain_valid()) { _hgt_sensor_offset = _terrain_vpos; } else if (_control_status.flags.in_air) { _hgt_sensor_offset = _R_rng_to_earth_2_2 * _range_sample_delayed.rng + _state.pos(2); } else { _hgt_sensor_offset = _params.rng_gnd_clearance; } } } else if ((_params.vdist_sensor_type == VDIST_SENSOR_RANGE) && _baro_data_ready && !_baro_hgt_faulty) { setControlBaroHeight(); _fuse_height = true; // we have just switched to using baro height, we don't need to set a height sensor offset // since we track a separate _baro_hgt_offset if (_control_status_prev.flags.baro_hgt != _control_status.flags.baro_hgt) { _hgt_sensor_offset = 0.0f; } } // Determine if GPS should be used as the height source if (_params.vdist_sensor_type == VDIST_SENSOR_GPS) { if (_range_aid_mode_selected && _range_data_ready && !_rng_hgt_faulty) { setControlRangeHeight(); _fuse_height = true; // we have just switched to using range finder, calculate height sensor offset such that current // measurment matches our current height estimate if (_control_status_prev.flags.rng_hgt != _control_status.flags.rng_hgt) { if (get_terrain_valid()) { _hgt_sensor_offset = _terrain_vpos; } else { _hgt_sensor_offset = _R_rng_to_earth_2_2 * _range_sample_delayed.rng + _state.pos(2); } } } else if (!_range_aid_mode_selected && _gps_data_ready && !_gps_hgt_faulty) { setControlGPSHeight(); _fuse_height = true; // we have just switched to using gps height, calculate height sensor offset such that current // measurment matches our current height estimate if (_control_status_prev.flags.gps_hgt != _control_status.flags.gps_hgt) { _hgt_sensor_offset = _gps_sample_delayed.hgt - _gps_alt_ref + _state.pos(2); } } else if (_control_status.flags.baro_hgt && _baro_data_ready && !_baro_hgt_faulty) { // switch to baro if there was a reset to baro _fuse_height = true; // we have just switched to using baro height, we don't need to set a height sensor offset // since we track a separate _baro_hgt_offset if (_control_status_prev.flags.baro_hgt != _control_status.flags.baro_hgt) { _hgt_sensor_offset = 0.0f; } } } // Determine if we rely on EV height but switched to baro if (_params.vdist_sensor_type == VDIST_SENSOR_EV) { if (_control_status.flags.baro_hgt && _baro_data_ready && !_baro_hgt_faulty) { // switch to baro if there was a reset to baro _fuse_height = true; // we have just switched to using baro height, we don't need to set a height sensor offset // since we track a separate _baro_hgt_offset if (_control_status_prev.flags.baro_hgt != _control_status.flags.baro_hgt) { _hgt_sensor_offset = 0.0f; } } } // calculate a filtered offset between the baro origin and local NED origin if we are not using the baro as a height reference if (!_control_status.flags.baro_hgt && _baro_data_ready) { float local_time_step = 1e-6f * _delta_time_baro_us; local_time_step = math::constrain(local_time_step, 0.0f, 1.0f); // apply a 10 second first order low pass filter to baro offset float offset_rate_correction = 0.1f * (_baro_sample_delayed.hgt + _state.pos( 2) - _baro_hgt_offset); _baro_hgt_offset += local_time_step * math::constrain(offset_rate_correction, -0.1f, 0.1f); } if ((_time_last_imu - _time_last_hgt_fuse) > 2 * RNG_MAX_INTERVAL && _control_status.flags.rng_hgt && !_range_data_ready) { // If we are supposed to be using range finder data as the primary height sensor, have missed or rejected measurements // and are on the ground, then synthesise a measurement at the expected on ground value if (!_control_status.flags.in_air) { _range_sample_delayed.rng = _params.rng_gnd_clearance; _range_sample_delayed.time_us = _imu_sample_delayed.time_us; } _fuse_height = true; } } void Ekf::rangeAidConditionsMet() { // if the parameter for range aid is enabled we allow to switch from using the primary height source to using range finder as height source // under the following conditions // 1) we are not further than max_hagl_for_range_aid away from the ground // 2) our ground speed is not higher than max_vel_for_range_aid // 3) Our terrain estimate is stable (needs better checks) // 4) We are in-air if (_control_status.flags.in_air) { // check if we can use range finder measurements to estimate height, use hysteresis to avoid rapid switching bool can_use_range_finder; if (_range_aid_mode_enabled) { can_use_range_finder = (_terrain_vpos - _state.pos(2) < _params.max_hagl_for_range_aid) && get_terrain_valid(); } else { // if we were not using range aid in the previous iteration then require the current height above terrain to be // smaller than 70 % of the maximum allowed ground distance for range aid can_use_range_finder = (_terrain_vpos - _state.pos(2) < 0.7f * _params.max_hagl_for_range_aid) && get_terrain_valid(); } bool horz_vel_valid = (_control_status.flags.gps || _control_status.flags.ev_pos || _control_status.flags.opt_flow) && (_fault_status.value == 0); if (horz_vel_valid) { float ground_vel = sqrtf(_state.vel(0) * _state.vel(0) + _state.vel(1) * _state.vel(1)); if (_range_aid_mode_enabled) { can_use_range_finder &= ground_vel < _params.max_vel_for_range_aid; } else { // if we were not using range aid in the previous iteration then require the ground velocity to be // smaller than 70 % of the maximum allowed ground velocity for range aid can_use_range_finder &= ground_vel < 0.7f * _params.max_vel_for_range_aid; } } else { can_use_range_finder = false; } // use hysteresis to check for hagl if (_range_aid_mode_enabled) { can_use_range_finder &= ((_hagl_innov * _hagl_innov / (sq(_params.range_aid_innov_gate) * _hagl_innov_var)) < 1.0f); } else { // if we were not using range aid in the previous iteration then use a much lower (1/100) threshold to avoid // switching to range finder too soon (wait for terrain to update). can_use_range_finder &= ((_hagl_innov * _hagl_innov / (sq(_params.range_aid_innov_gate) * _hagl_innov_var)) < 0.01f); } _range_aid_mode_enabled = can_use_range_finder; } else { _range_aid_mode_enabled = false; } } void Ekf::checkForStuckRange() { if (_range_data_ready && _range_sample_delayed.time_us - _time_last_rng_ready > (uint64_t)10e6 && _control_status.flags.in_air) { _control_status.flags.rng_stuck = true; //require a variance of rangefinder values to check for "stuck" measurements if (_rng_check_max_val - _rng_check_min_val > 1.0f) { _time_last_rng_ready = _range_sample_delayed.time_us; _rng_check_min_val = 0.0f; _rng_check_max_val = 0.0f; _control_status.flags.rng_stuck = false; } else { if (_range_sample_delayed.rng > _rng_check_max_val) { _rng_check_max_val = _range_sample_delayed.rng; } if (_rng_check_min_val < 0.1f || _range_sample_delayed.rng < _rng_check_min_val) { _rng_check_min_val = _range_sample_delayed.rng; } _range_data_ready = false; } } else if (_range_data_ready) { _time_last_rng_ready = _range_sample_delayed.time_us; } } void Ekf::controlAirDataFusion() { // control activation and initialisation/reset of wind states required for airspeed fusion // If both airspeed and sideslip fusion have timed out and we are not using a drag observation model then we no longer have valid wind estimates bool airspeed_timed_out = _time_last_imu - _time_last_arsp_fuse > (uint64_t)10e6; bool sideslip_timed_out = _time_last_imu - _time_last_beta_fuse > (uint64_t)10e6; if (_control_status.flags.wind && airspeed_timed_out && sideslip_timed_out && !(_params.fusion_mode & MASK_USE_DRAG)) { _control_status.flags.wind = false; } if (_control_status.flags.fuse_aspd && airspeed_timed_out) { _control_status.flags.fuse_aspd = false; } // Always try to fuse airspeed data if available and we are in flight if (_tas_data_ready && _control_status.flags.in_air) { // always fuse airsped data if we are flying and data is present if (!_control_status.flags.fuse_aspd) { _control_status.flags.fuse_aspd = true; } // If starting wind state estimation, reset the wind states and covariances before fusing any data if (!_control_status.flags.wind) { // activate the wind states _control_status.flags.wind = true; // reset the timout timer to prevent repeated resets _time_last_arsp_fuse = _time_last_imu; _time_last_beta_fuse = _time_last_imu; // reset the wind speed states and corresponding covariances resetWindStates(); resetWindCovariance(); } fuseAirspeed(); } } void Ekf::controlBetaFusion() { // control activation and initialisation/reset of wind states required for synthetic sideslip fusion fusion // If both airspeed and sideslip fusion have timed out and we are not using a drag observation model then we no longer have valid wind estimates bool sideslip_timed_out = _time_last_imu - _time_last_beta_fuse > (uint64_t)10e6; bool airspeed_timed_out = _time_last_imu - _time_last_arsp_fuse > (uint64_t)10e6; if (_control_status.flags.wind && airspeed_timed_out && sideslip_timed_out && !(_params.fusion_mode & MASK_USE_DRAG)) { _control_status.flags.wind = false; } // Perform synthetic sideslip fusion when in-air and sideslip fuson had been enabled externally in addition to the following criteria: // Suffient time has lapsed sice the last fusion bool beta_fusion_time_triggered = _time_last_imu - _time_last_beta_fuse > _params.beta_avg_ft_us; if (beta_fusion_time_triggered && _control_status.flags.fuse_beta && _control_status.flags.in_air) { // If starting wind state estimation, reset the wind states and covariances before fusing any data if (!_control_status.flags.wind) { // activate the wind states _control_status.flags.wind = true; // reset the timeout timers to prevent repeated resets _time_last_beta_fuse = _time_last_imu; _time_last_arsp_fuse = _time_last_imu; // reset the wind speed states and corresponding covariances resetWindStates(); resetWindCovariance(); } fuseSideslip(); } } void Ekf::controlDragFusion() { if (_params.fusion_mode & MASK_USE_DRAG) { if (_control_status.flags.in_air && !_mag_inhibit_yaw_reset_req) { if (!_control_status.flags.wind) { // reset the wind states and covariances when starting drag accel fusion _control_status.flags.wind = true; resetWindStates(); resetWindCovariance(); } else if (_drag_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_drag_sample_delayed)) { fuseDrag(); } } else { _control_status.flags.wind = false; } } } void Ekf::controlMagFusion() { // If we are on ground, store the local position and time to use as a reference // Also reset the flight alignment flag so that the mag fields will be re-initialised next time we achieve flight altitude if (!_control_status.flags.in_air) { _last_on_ground_posD = _state.pos(2); _flt_mag_align_complete = false; _num_bad_flight_yaw_events = 0; } // check for new magnetometer data that has fallen behind the fusion time horizon // If we are using external vision data for heading then no magnetometer fusion is used if (!_control_status.flags.ev_yaw && _mag_data_ready) { // Determine if we should use simple magnetic heading fusion which works better when there are large external disturbances // or the more accurate 3-axis fusion if (_control_status.flags.mag_fault) { // do no magnetometer fusion at all _control_status.flags.mag_hdg = false; _control_status.flags.mag_3D = false; } else if (_params.mag_fusion_type == MAG_FUSE_TYPE_AUTO || _params.mag_fusion_type == MAG_FUSE_TYPE_AUTOFW) { // Check if height has increased sufficiently to be away from ground magnetic anomalies bool height_achieved = (_last_on_ground_posD - _state.pos(2)) > 1.5f; // Check if there has been enough change in horizontal velocity to make yaw observable // Apply hysteresis to check to avoid rapid toggling if (_yaw_angle_observable) { _yaw_angle_observable = _accel_lpf_NE.norm() > _params.mag_acc_gate; } else { _yaw_angle_observable = _accel_lpf_NE.norm() > 2.0f * _params.mag_acc_gate; } _yaw_angle_observable = _yaw_angle_observable && (_control_status.flags.gps || _control_status.flags.ev_pos); // check if there is enough yaw rotation to make the mag bias states observable if (!_mag_bias_observable && (fabsf(_yaw_rate_lpf_ef) > _params.mag_yaw_rate_gate)) { // initial yaw motion is detected _mag_bias_observable = true; _yaw_delta_ef = 0.0f; _time_yaw_started = _imu_sample_delayed.time_us; } else if (_mag_bias_observable) { // monitor yaw rotation in 45 deg sections. // a rotation of 45 deg is sufficient to make the mag bias observable if (fabsf(_yaw_delta_ef) > 0.7854f) { _time_yaw_started = _imu_sample_delayed.time_us; _yaw_delta_ef = 0.0f; } // require sustained yaw motion of 50% the initial yaw rate threshold float min_yaw_change_req = 0.5f * _params.mag_yaw_rate_gate * (1e-6f * (float)(_imu_sample_delayed.time_us - _time_yaw_started)); _mag_bias_observable = fabsf(_yaw_delta_ef) > min_yaw_change_req; } else { _mag_bias_observable = false; } // record the last time that movement was suitable for use of 3-axis magnetometer fusion if (_mag_bias_observable || _yaw_angle_observable) { _time_last_movement = _imu_sample_delayed.time_us; } // decide whether 3-axis magnetomer fusion can be used bool use_3D_fusion = _control_status.flags.tilt_align && // Use of 3D fusion requires valid tilt estimates _control_status.flags.in_air && // don't use when on the ground becasue of magnetic anomalies (_flt_mag_align_complete || height_achieved) && // once in-flight field alignment has been performed, ignore relative height ((_imu_sample_delayed.time_us - _time_last_movement) < 2 * 1000 * 1000); // Using 3-axis fusion for a minimum period after to allow for false negatives // perform switch-over if (use_3D_fusion) { if (!_control_status.flags.mag_3D) { if (!_flt_mag_align_complete) { // If we are flying a vehicle that flies forward, eg plane, then we can use the GPS course to check and correct the heading if (_control_status.flags.fixed_wing && _control_status.flags.in_air) { _flt_mag_align_complete = realignYawGPS(); if (_velpos_reset_request) { resetVelocity(); resetPosition(); _velpos_reset_request = false; } } else { _flt_mag_align_complete = resetMagHeading(_mag_sample_delayed.mag); } _control_status.flags.yaw_align = _control_status.flags.yaw_align || _flt_mag_align_complete; } else { // reset the mag field covariances zeroRows(P, 16, 21); zeroCols(P, 16, 21); // re-instate the last used variances for (uint8_t index = 0; index <= 5; index ++) { P[index + 16][index + 16] = _saved_mag_variance[index]; } } } // only use one type of mag fusion at the same time _control_status.flags.mag_3D = _flt_mag_align_complete; _control_status.flags.mag_hdg = !_control_status.flags.mag_3D; } else { // save magnetic field state variances for next time if (_control_status.flags.mag_3D) { for (uint8_t index = 0; index <= 5; index ++) { _saved_mag_variance[index] = P[index + 16][index + 16]; } _control_status.flags.mag_3D = false; } _control_status.flags.mag_hdg = true; } /* Control switch-over between only updating the mag states to updating all states When flying as a fixed wing aircraft, a misaligned magnetometer can cause an error in pitch/roll and accel bias estimates. When MAG_FUSE_TYPE_AUTOFW is selected and the vehicle is flying as a fixed wing, then magnetometer fusion is only allowed to access the magnetic field states. */ _control_status.flags.update_mag_states_only = (_params.mag_fusion_type == MAG_FUSE_TYPE_AUTOFW) && _control_status.flags.fixed_wing; // For the first 5 seconds after switching to 3-axis fusion we allow the magnetic field state estimates to stabilise // before they are used to constrain heading drift _flt_mag_align_converging = ((_imu_sample_delayed.time_us - _flt_mag_align_start_time) < (uint64_t)5e6); if (!_control_status.flags.update_mag_states_only && _control_status_prev.flags.update_mag_states_only) { // When re-commencing use of magnetometer to correct vehicle states // set the field state variance to the observation variance and zero // the covariance terms to allow the field states re-learn rapidly zeroRows(P, 16, 21); zeroCols(P, 16, 21); for (uint8_t index = 0; index <= 5; index ++) { P[index + 16][index + 16] = sq(_params.mag_noise); } } } else if (_params.mag_fusion_type == MAG_FUSE_TYPE_HEADING) { // always use heading fusion _control_status.flags.mag_hdg = true; _control_status.flags.mag_3D = false; } else if (_params.mag_fusion_type == MAG_FUSE_TYPE_3D) { // if transitioning into 3-axis fusion mode, we need to initialise the yaw angle and field states if (!_control_status.flags.mag_3D) { _control_status.flags.yaw_align = resetMagHeading(_mag_sample_delayed.mag) || _control_status.flags.yaw_align; } // always use 3-axis mag fusion _control_status.flags.mag_hdg = false; _control_status.flags.mag_3D = true; } else { // do no magnetometer fusion at all _control_status.flags.mag_hdg = false; _control_status.flags.mag_3D = false; } // if we are using 3-axis magnetometer fusion, but without external aiding, then the declination must be fused as an observation to prevent long term heading drift // fusing declination when gps aiding is available is optional, but recommended to prevent problem if the vehicle is static for extended periods of time if (_control_status.flags.mag_3D && (!_control_status.flags.gps || (_params.mag_declination_source & MASK_FUSE_DECL))) { _control_status.flags.mag_dec = true; } else { _control_status.flags.mag_dec = false; } // If the user has selected auto protection against indoor magnetic field errors, only use the magnetomer // if a yaw angle relative to true North is required for navigation. If no GPS or other earth frame aiding // is available, assume that we are operating indoors and the magnetometer should not be used. bool user_selected = (_params.mag_fusion_type == MAG_FUSE_TYPE_INDOOR); bool not_using_gps = !(_params.fusion_mode & MASK_USE_GPS) || !_control_status.flags.gps; bool not_using_evpos = !(_params.fusion_mode & MASK_USE_EVPOS) || !_control_status.flags.ev_pos; bool not_selected_evyaw = !(_params.fusion_mode & MASK_USE_EVYAW); if (user_selected && not_using_gps && not_using_evpos && not_selected_evyaw) { _mag_use_inhibit = true; } else { _mag_use_inhibit = false; _mag_use_not_inhibit_us = _imu_sample_delayed.time_us; } // If magnetomer use has been inhibited continuously then a yaw reset is required for a valid heading if (uint32_t(_imu_sample_delayed.time_us - _mag_use_not_inhibit_us) > (uint32_t)5e6) { _mag_inhibit_yaw_reset_req = true; } // fuse magnetometer data using the selected methods if (_control_status.flags.mag_3D && _control_status.flags.yaw_align) { fuseMag(); if (_control_status.flags.mag_dec) { fuseDeclination(); } } else if (_control_status.flags.mag_hdg && _control_status.flags.yaw_align) { // fusion of an Euler yaw angle from either a 321 or 312 rotation sequence fuseHeading(); } else { // do no fusion at all } } } void Ekf::controlVelPosFusion() { // if we aren't doing any aiding, fake GPS measurements at the last known position to constrain drift // Coincide fake measurements with baro data for efficiency with a minimum fusion rate of 5Hz if (!(_params.fusion_mode & MASK_USE_GPS)) { _control_status.flags.gps = false; } if (!_control_status.flags.gps && !_control_status.flags.opt_flow && !_control_status.flags.ev_pos && !(_control_status.flags.fuse_aspd && _control_status.flags.fuse_beta)) { // We now need to use a synthetic positon observation to prevent unconstrained drift of the INS states. _using_synthetic_position = true; // Fuse synthetic position observations every 200msec if ((_time_last_imu - _time_last_fake_gps > (uint64_t)2e5) || _fuse_height) { // Reset position and velocity states if we re-commence this aiding method if ((_time_last_imu - _time_last_fake_gps) > (uint64_t)4e5) { resetPosition(); resetVelocity(); _fuse_hpos_as_odom = false; if (_time_last_fake_gps != 0) { ECL_WARN("EKF stopping navigation"); } } _fuse_pos = true; _fuse_hor_vel = false; _fuse_vert_vel = false; _time_last_fake_gps = _time_last_imu; if (_control_status.flags.in_air && _control_status.flags.tilt_align) { _posObsNoiseNE = fmaxf(_params.pos_noaid_noise, _params.gps_pos_noise); } else { _posObsNoiseNE = 0.5f; } _vel_pos_innov[0] = 0.0f; _vel_pos_innov[1] = 0.0f; _vel_pos_innov[2] = 0.0f; _vel_pos_innov[3] = _state.pos(0) - _last_known_posNE(0); _vel_pos_innov[4] = _state.pos(1) - _last_known_posNE(1); // glitch protection is not required so set gate to a large value _posInnovGateNE = 100.0f; } } else { _using_synthetic_position = false; } // Fuse available NED velocity and position data into the main filter if (_fuse_height || _fuse_pos || _fuse_hor_vel || _fuse_vert_vel) { fuseVelPosHeight(); } } void Ekf::controlAuxVelFusion() { bool data_ready = _auxvel_buffer.pop_first_older_than(_imu_sample_delayed.time_us, &_auxvel_sample_delayed); bool primary_aiding = _control_status.flags.gps || _control_status.flags.ev_pos || _control_status.flags.opt_flow; if (data_ready && primary_aiding) { _fuse_hor_vel = _fuse_vert_vel = _fuse_pos = _fuse_height = false; _fuse_hor_vel_aux = true; _aux_vel_innov[0] = _state.vel(0) - _auxvel_sample_delayed.velNE(0); _aux_vel_innov[1] = _state.vel(1) - _auxvel_sample_delayed.velNE(1); _velObsVarNE = _auxvel_sample_delayed.velVarNE; _hvelInnovGate = _params.auxvel_gate; fuseVelPosHeight(); } }
/** Copyright (C) 2018 European Spallation Source ERIC */ #include <arpa/inet.h> #include <chrono> #include <efu/Server.h> #include <sys/socket.h> #include <test/TestBase.h> #include <thread> uint16_t ServerPort = 8889; constexpr int mask_close = 0x0001; constexpr int mask_connect = 0x0002; constexpr int mask_send = 0x0004; const char * message = "DETECTOR_INFO_GET\n"; /// Used in pthread to connect to server and send data void client_thread(int command) { struct sockaddr_in server; int sock = socket(AF_INET , SOCK_STREAM , 0); if (sock == -1) { printf("Could not create socket\n"); } server.sin_addr.s_addr = inet_addr("127.0.0.1"); server.sin_family = AF_INET; server.sin_port = htons( ServerPort ); //Connect to remote server if (command & mask_connect) { if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0) { perror("connect failed. Error\n"); } } if (command & mask_send) { if( send(sock , message , strlen(message) , 0) < 0) { printf("Send failed\n"); } /// Allow time for test to poll for data std::this_thread::sleep_for(std::chrono::seconds(2)); } if (command & mask_close) { close(sock); } } class TestDetector : public Detector { public: explicit TestDetector(BaseSettings settings) : Detector("No name", settings) { }; ~TestDetector() { std::cout << "~TestDetector" << std::endl; }; }; DetectorFactory<TestDetector> Factory; // clang-format on class ServerTest : public TestBase { protected: int keep_running = 1; EFUArgs efu_args; BaseSettings settings = efu_args.getBaseSettings(); Parser * parser; Statistics stats; void SetUp() override { auto detectorif = Factory.create(settings); parser = new Parser(detectorif, stats, keep_running); } void TearDown() override { delete parser; } }; /** Test cases below */ TEST_F(ServerTest, Constructor) { Server server(ServerPort, *parser); ASSERT_TRUE(server.getServerFd() != -1); ASSERT_TRUE(server.getServerPort() == ServerPort); ASSERT_EQ(server.getNumClients(), 0); } // TEST_F(ServerTest, ServerSendInvalidFd) { // Server server(ServerPort, *parser); // ASSERT_EQ(server.getNumClients(), 0); // ASSERT_EQ(server.serverSend(42), -1); // } TEST_F(ServerTest, PollNoData) { Server server(ServerPort, *parser); server.serverPoll(); ASSERT_EQ(server.getNumClients(), 0); } TEST_F(ServerTest, PollConnect) { Server server(ServerPort, *parser); std::thread client(client_thread, mask_connect); client.join(); server.serverPoll(); server.serverPoll(); ASSERT_EQ(server.getNumClients(), 1); ASSERT_EQ(server.getTotalBytesReceived(), 0); } TEST_F(ServerTest, PollWData) { Server server(ServerPort, *parser); std::thread client(client_thread, mask_connect | mask_send); client.join(); server.serverPoll(); server.serverPoll(); ASSERT_EQ(server.getNumClients(), 1); ASSERT_EQ(server.getTotalBytesReceived(), strlen(message)); } TEST_F(ServerTest, PollWDataClose) { Server server(ServerPort, *parser); std::thread client(client_thread, mask_connect | mask_send | mask_close); client.join(); server.serverPoll(); server.serverPoll(); server.serverPoll(); ASSERT_EQ(server.getNumClients(), 0); ASSERT_EQ(server.getTotalBytesReceived(), strlen(message)); } int main(int argc, char **argv) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
// 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 "kudu/consensus/leader_election.h" #include <functional> #include <memory> #include <ostream> #include <string> #include <type_traits> #include <unordered_map> #include <utility> #include <vector> #include <glog/logging.h> #include <gtest/gtest.h> #include "kudu/common/wire_protocol.h" #include "kudu/consensus/consensus-test-util.h" #include "kudu/consensus/consensus.pb.h" #include "kudu/consensus/consensus_peers.h" #include "kudu/consensus/metadata.pb.h" #include "kudu/consensus/raft_consensus.h" #include "kudu/gutil/casts.h" #include "kudu/gutil/gscoped_ptr.h" #include "kudu/gutil/map-util.h" #include "kudu/gutil/ref_counted.h" #include "kudu/gutil/stl_util.h" #include "kudu/gutil/strings/substitute.h" #include "kudu/tserver/tserver.pb.h" #include "kudu/util/countdown_latch.h" #include "kudu/util/monotime.h" #include "kudu/util/status.h" #include "kudu/util/test_macros.h" #include "kudu/util/test_util.h" #include "kudu/util/threadpool.h" namespace kudu { namespace rpc { class Messenger; } // namespace rpc namespace consensus { using std::shared_ptr; using std::string; using std::unordered_map; using std::vector; using strings::Substitute; namespace { const int kLeaderElectionTimeoutSecs = 10; // Generate list of voter uuids. vector<string> GenVoterUUIDs(int num_voters) { vector<string> voter_uuids; for (int i = 0; i < num_voters; i++) { voter_uuids.push_back(Substitute("peer-$0", i)); } return voter_uuids; } } // namespace //////////////////////////////////////// // LeaderElectionTest //////////////////////////////////////// typedef unordered_map<string, PeerProxy*> ProxyMap; // A proxy factory that serves proxies from a map. class FromMapPeerProxyFactory : public PeerProxyFactory { public: explicit FromMapPeerProxyFactory(const ProxyMap* proxy_map) : proxy_map_(proxy_map) { } Status NewProxy(const RaftPeerPB& peer_pb, gscoped_ptr<PeerProxy>* proxy) override { PeerProxy* proxy_ptr = FindPtrOrNull(*proxy_map_, peer_pb.permanent_uuid()); if (!proxy_ptr) return Status::NotFound("no proxy for peer"); proxy->reset(proxy_ptr); return Status::OK(); } const shared_ptr<rpc::Messenger>& messenger() const override { return null_messenger_; } private: // FYI, the tests may add and remove nodes from this map while we hold a // reference to it. const ProxyMap* const proxy_map_; shared_ptr<rpc::Messenger> null_messenger_; }; class LeaderElectionTest : public KuduTest { public: LeaderElectionTest() : tablet_id_("test-tablet"), proxy_factory_(new FromMapPeerProxyFactory(&proxies_)), latch_(1) { CHECK_OK(ThreadPoolBuilder("test-peer-pool").set_max_threads(5).Build(&pool_)); } void ElectionCallback(const ElectionResult& result); protected: void InitUUIDs(int num_voters); void InitNoOpPeerProxies(); void InitDelayableMockedProxies(bool enable_delay); gscoped_ptr<VoteCounter> InitVoteCounter(int num_voters, int majority_size); // Voter 0 is the high-term voter. scoped_refptr<LeaderElection> SetUpElectionWithHighTermVoter(ConsensusTerm election_term); // Predetermine the election results using the specified number of // grant / deny / error responses. // num_grant must be at least 1, for the candidate to vote for itself. // num_grant + num_deny + num_error must add up to an odd number. scoped_refptr<LeaderElection> SetUpElectionWithGrantDenyErrorVotes(ConsensusTerm election_term, int num_grant, int num_deny, int num_error); const string tablet_id_; string candidate_uuid_; vector<string> voter_uuids_; RaftConfigPB config_; ProxyMap proxies_; gscoped_ptr<PeerProxyFactory> proxy_factory_; gscoped_ptr<ThreadPool> pool_; CountDownLatch latch_; gscoped_ptr<ElectionResult> result_; }; void LeaderElectionTest::ElectionCallback(const ElectionResult& result) { result_.reset(new ElectionResult(result)); latch_.CountDown(); } void LeaderElectionTest::InitUUIDs(int num_voters) { voter_uuids_ = GenVoterUUIDs(num_voters); CHECK(!voter_uuids_.empty()); candidate_uuid_ = voter_uuids_.back(); voter_uuids_.pop_back(); } void LeaderElectionTest::InitNoOpPeerProxies() { config_.Clear(); for (const string& uuid : voter_uuids_) { RaftPeerPB* peer_pb = config_.add_peers(); peer_pb->set_permanent_uuid(uuid); peer_pb->set_member_type(RaftPeerPB::VOTER); PeerProxy* proxy = new NoOpTestPeerProxy(pool_.get(), *peer_pb); InsertOrDie(&proxies_, uuid, proxy); } } void LeaderElectionTest::InitDelayableMockedProxies(bool enable_delay) { config_.Clear(); for (const string& uuid : voter_uuids_) { RaftPeerPB* peer_pb = config_.add_peers(); peer_pb->set_permanent_uuid(uuid); peer_pb->set_member_type(RaftPeerPB::VOTER); auto proxy = new DelayablePeerProxy<MockedPeerProxy>(pool_.get(), new MockedPeerProxy(pool_.get())); if (enable_delay) { proxy->DelayResponse(); } InsertOrDie(&proxies_, uuid, proxy); } } gscoped_ptr<VoteCounter> LeaderElectionTest::InitVoteCounter(int num_voters, int majority_size) { gscoped_ptr<VoteCounter> counter(new VoteCounter(num_voters, majority_size)); bool duplicate; CHECK_OK(counter->RegisterVote(candidate_uuid_, VOTE_GRANTED, &duplicate)); CHECK(!duplicate); return std::move(counter); } scoped_refptr<LeaderElection> LeaderElectionTest::SetUpElectionWithHighTermVoter( ConsensusTerm election_term) { const int kNumVoters = 3; const int kMajoritySize = 2; InitUUIDs(kNumVoters); InitDelayableMockedProxies(true); gscoped_ptr<VoteCounter> counter = InitVoteCounter(kNumVoters, kMajoritySize); VoteResponsePB response; response.set_responder_uuid(voter_uuids_[0]); response.set_responder_term(election_term + 1); response.set_vote_granted(false); response.mutable_consensus_error()->set_code(ConsensusErrorPB::INVALID_TERM); StatusToPB(Status::InvalidArgument("Bad term"), response.mutable_consensus_error()->mutable_status()); down_cast<DelayablePeerProxy<MockedPeerProxy>*>(proxies_[voter_uuids_[0]]) ->proxy()->set_vote_response(response); response.Clear(); response.set_responder_uuid(voter_uuids_[1]); response.set_responder_term(election_term); response.set_vote_granted(true); down_cast<DelayablePeerProxy<MockedPeerProxy>*>(proxies_[voter_uuids_[1]]) ->proxy()->set_vote_response(response); VoteRequestPB request; request.set_candidate_uuid(candidate_uuid_); request.set_candidate_term(election_term); request.set_tablet_id(tablet_id_); scoped_refptr<LeaderElection> election( new LeaderElection(config_, proxy_factory_.get(), request, std::move(counter), MonoDelta::FromSeconds(kLeaderElectionTimeoutSecs), std::bind(&LeaderElectionTest::ElectionCallback, this, std::placeholders::_1))); return election; } scoped_refptr<LeaderElection> LeaderElectionTest::SetUpElectionWithGrantDenyErrorVotes( ConsensusTerm election_term, int num_grant, int num_deny, int num_error) { const int kNumVoters = num_grant + num_deny + num_error; CHECK_GE(num_grant, 1); // Gotta vote for yourself. CHECK_EQ(1, kNumVoters % 2); // RaftConfig size must be odd. const int kMajoritySize = (kNumVoters / 2) + 1; InitUUIDs(kNumVoters); InitDelayableMockedProxies(false); // Don't delay the vote responses. gscoped_ptr<VoteCounter> counter = InitVoteCounter(kNumVoters, kMajoritySize); int num_grant_followers = num_grant - 1; // Set up mocked responses based on the params specified in the method arguments. int voter_index = 0; while (voter_index < voter_uuids_.size()) { VoteResponsePB response; if (num_grant_followers > 0) { response.set_responder_uuid(voter_uuids_[voter_index]); response.set_responder_term(election_term); response.set_vote_granted(true); --num_grant_followers; } else if (num_deny > 0) { response.set_responder_uuid(voter_uuids_[voter_index]); response.set_responder_term(election_term); response.set_vote_granted(false); response.mutable_consensus_error()->set_code(ConsensusErrorPB::LAST_OPID_TOO_OLD); StatusToPB(Status::InvalidArgument("Last OpId"), response.mutable_consensus_error()->mutable_status()); --num_deny; } else if (num_error > 0) { response.mutable_error()->set_code(tserver::TabletServerErrorPB::TABLET_NOT_FOUND); StatusToPB(Status::NotFound("Unknown Tablet"), response.mutable_error()->mutable_status()); --num_error; } else { LOG(FATAL) << "Unexpected fallthrough"; } down_cast<DelayablePeerProxy<MockedPeerProxy>*>(proxies_[voter_uuids_[voter_index]]) ->proxy()->set_vote_response(response); ++voter_index; } VoteRequestPB request; request.set_candidate_uuid(candidate_uuid_); request.set_candidate_term(election_term); request.set_tablet_id(tablet_id_); scoped_refptr<LeaderElection> election( new LeaderElection(config_, proxy_factory_.get(), request, std::move(counter), MonoDelta::FromSeconds(kLeaderElectionTimeoutSecs), std::bind(&LeaderElectionTest::ElectionCallback, this, std::placeholders::_1))); return election; } // All peers respond "yes", no failures. TEST_F(LeaderElectionTest, TestPerfectElection) { // Try configuration sizes of 1, 3, 5. vector<int> config_sizes = { 1, 3, 5 }; for (int num_voters : config_sizes) { LOG(INFO) << "Testing election with config size of " << num_voters; int majority_size = (num_voters / 2) + 1; ConsensusTerm election_term = 10L + num_voters; // Just to be able to differentiate. InitUUIDs(num_voters); InitNoOpPeerProxies(); gscoped_ptr<VoteCounter> counter = InitVoteCounter(num_voters, majority_size); VoteRequestPB request; request.set_candidate_uuid(candidate_uuid_); request.set_candidate_term(election_term); request.set_tablet_id(tablet_id_); scoped_refptr<LeaderElection> election( new LeaderElection(config_, proxy_factory_.get(), request, std::move(counter), MonoDelta::FromSeconds(kLeaderElectionTimeoutSecs), std::bind(&LeaderElectionTest::ElectionCallback, this, std::placeholders::_1))); election->Run(); latch_.Wait(); ASSERT_EQ(election_term, result_->vote_request.candidate_term()); ASSERT_EQ(VOTE_GRANTED, result_->decision); pool_->Wait(); proxies_.clear(); // We don't delete them; The election VoterState object // ends up owning them. latch_.Reset(1); } } // Test leader election when we encounter a peer with a higher term before we // have arrived at a majority decision. TEST_F(LeaderElectionTest, TestHigherTermBeforeDecision) { const ConsensusTerm kElectionTerm = 2; scoped_refptr<LeaderElection> election = SetUpElectionWithHighTermVoter(kElectionTerm); election->Run(); // This guy has a higher term. down_cast<DelayablePeerProxy<MockedPeerProxy>*>(proxies_[voter_uuids_[0]]) ->Respond(TestPeerProxy::kRequestVote); latch_.Wait(); ASSERT_EQ(kElectionTerm, result_->vote_request.candidate_term()); ASSERT_EQ(VOTE_DENIED, result_->decision); ASSERT_EQ(kElectionTerm + 1, result_->highest_voter_term); LOG(INFO) << "Election lost. Reason: " << result_->message; // This guy will vote "yes". down_cast<DelayablePeerProxy<MockedPeerProxy>*>(proxies_[voter_uuids_[1]]) ->Respond(TestPeerProxy::kRequestVote); pool_->Wait(); // Wait for the election callbacks to finish before we destroy proxies. } // Test leader election when we encounter a peer with a higher term after we // have arrived at a majority decision of "yes". TEST_F(LeaderElectionTest, TestHigherTermAfterDecision) { const ConsensusTerm kElectionTerm = 2; scoped_refptr<LeaderElection> election = SetUpElectionWithHighTermVoter(kElectionTerm); election->Run(); // This guy will vote "yes". down_cast<DelayablePeerProxy<MockedPeerProxy>*>(proxies_[voter_uuids_[1]]) ->Respond(TestPeerProxy::kRequestVote); latch_.Wait(); ASSERT_EQ(kElectionTerm, result_->vote_request.candidate_term()); ASSERT_EQ(VOTE_GRANTED, result_->decision); ASSERT_EQ(kElectionTerm, result_->highest_voter_term); ASSERT_EQ("achieved majority votes", result_->message); LOG(INFO) << "Election won."; // This guy has a higher term. down_cast<DelayablePeerProxy<MockedPeerProxy>*>(proxies_[voter_uuids_[0]]) ->Respond(TestPeerProxy::kRequestVote); pool_->Wait(); // Wait for the election callbacks to finish before we destroy proxies. } // Out-of-date OpId "vote denied" case. TEST_F(LeaderElectionTest, TestWithDenyVotes) { const ConsensusTerm kElectionTerm = 2; const int kNumGrant = 2; const int kNumDeny = 3; const int kNumError = 0; scoped_refptr<LeaderElection> election = SetUpElectionWithGrantDenyErrorVotes(kElectionTerm, kNumGrant, kNumDeny, kNumError); LOG(INFO) << "Running"; election->Run(); latch_.Wait(); ASSERT_EQ(kElectionTerm, result_->vote_request.candidate_term()); ASSERT_EQ(VOTE_DENIED, result_->decision); ASSERT_EQ(kElectionTerm, result_->highest_voter_term); ASSERT_EQ("could not achieve majority", result_->message); LOG(INFO) << "Election denied."; pool_->Wait(); // Wait for the election callbacks to finish before we destroy proxies. } // Count errors as denied votes. TEST_F(LeaderElectionTest, TestWithErrorVotes) { const ConsensusTerm kElectionTerm = 2; const int kNumGrant = 1; const int kNumDeny = 0; const int kNumError = 4; scoped_refptr<LeaderElection> election = SetUpElectionWithGrantDenyErrorVotes(kElectionTerm, kNumGrant, kNumDeny, kNumError); election->Run(); latch_.Wait(); ASSERT_EQ(kElectionTerm, result_->vote_request.candidate_term()); ASSERT_EQ(VOTE_DENIED, result_->decision); ASSERT_EQ(0, result_->highest_voter_term); // no valid votes ASSERT_EQ("could not achieve majority", result_->message); LOG(INFO) << "Election denied."; pool_->Wait(); // Wait for the election callbacks to finish before we destroy proxies. } // Count errors as denied votes. TEST_F(LeaderElectionTest, TestFailToCreateProxy) { const ConsensusTerm kElectionTerm = 2; const int kNumVoters = 3; const int kMajoritySize = 2; // Initialize the UUIDs and the proxies (which also sets up the config PB). InitUUIDs(kNumVoters); InitNoOpPeerProxies(); // Remove all the proxies. This will make our peer factory return a bad Status. STLDeleteValues(&proxies_); // Our election should now fail as if the votes were denied. VoteRequestPB request; request.set_candidate_uuid(candidate_uuid_); request.set_candidate_term(kElectionTerm); request.set_tablet_id(tablet_id_); gscoped_ptr<VoteCounter> counter = InitVoteCounter(kNumVoters, kMajoritySize); scoped_refptr<LeaderElection> election( new LeaderElection(config_, proxy_factory_.get(), request, std::move(counter), MonoDelta::FromSeconds(kLeaderElectionTimeoutSecs), std::bind(&LeaderElectionTest::ElectionCallback, this, std::placeholders::_1))); election->Run(); latch_.Wait(); ASSERT_EQ(kElectionTerm, result_->vote_request.candidate_term()); ASSERT_EQ(VOTE_DENIED, result_->decision); ASSERT_EQ(0, result_->highest_voter_term); // no votes ASSERT_EQ("could not achieve majority", result_->message); } //////////////////////////////////////// // VoteCounterTest //////////////////////////////////////// class VoteCounterTest : public KuduTest { protected: static void AssertUndecided(const VoteCounter& counter); static void AssertVoteCount(const VoteCounter& counter, int yes_votes, int no_votes); }; void VoteCounterTest::AssertUndecided(const VoteCounter& counter) { ASSERT_FALSE(counter.IsDecided()); ElectionVote decision; Status s = counter.GetDecision(&decision); ASSERT_TRUE(s.IsIllegalState()); ASSERT_STR_CONTAINS(s.ToString(), "Vote not yet decided"); } void VoteCounterTest::AssertVoteCount(const VoteCounter& counter, int yes_votes, int no_votes) { ASSERT_EQ(yes_votes, counter.yes_votes_); ASSERT_EQ(no_votes, counter.no_votes_); ASSERT_EQ(yes_votes + no_votes, counter.GetTotalVotesCounted()); } // Test basic vote counting functionality with an early majority. TEST_F(VoteCounterTest, TestVoteCounter_EarlyDecision) { const int kNumVoters = 3; const int kMajoritySize = 2; vector<string> voter_uuids = GenVoterUUIDs(kNumVoters); // "Yes" decision. { // Start off undecided. VoteCounter counter(kNumVoters, kMajoritySize); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 0, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // First yes vote. bool duplicate; ASSERT_OK(counter.RegisterVote(voter_uuids[0], VOTE_GRANTED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 1, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // Second yes vote wins it in a configuration of 3. ASSERT_OK(counter.RegisterVote(voter_uuids[1], VOTE_GRANTED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_TRUE(counter.IsDecided()); ElectionVote decision; ASSERT_OK(counter.GetDecision(&decision)); ASSERT_TRUE(decision == VOTE_GRANTED); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 2, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); } // "No" decision. { // Start off undecided. VoteCounter counter(kNumVoters, kMajoritySize); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 0, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // First no vote. bool duplicate; ASSERT_OK(counter.RegisterVote(voter_uuids[0], VOTE_DENIED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 0, 1)); ASSERT_FALSE(counter.AreAllVotesIn()); // Second no vote loses it in a configuration of 3. ASSERT_OK(counter.RegisterVote(voter_uuids[1], VOTE_DENIED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_TRUE(counter.IsDecided()); ElectionVote decision; ASSERT_OK(counter.GetDecision(&decision)); ASSERT_TRUE(decision == VOTE_DENIED); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 0, 2)); ASSERT_FALSE(counter.AreAllVotesIn()); } } // Test basic vote counting functionality with the last vote being the deciding vote. TEST_F(VoteCounterTest, TestVoteCounter_LateDecision) { const int kNumVoters = 5; const int kMajoritySize = 3; vector<string> voter_uuids = GenVoterUUIDs(kNumVoters); // Start off undecided. VoteCounter counter(kNumVoters, kMajoritySize); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 0, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // Add single yes vote, still undecided. bool duplicate; ASSERT_OK(counter.RegisterVote(voter_uuids[0], VOTE_GRANTED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 1, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // Attempt duplicate vote. ASSERT_OK(counter.RegisterVote(voter_uuids[0], VOTE_GRANTED, &duplicate)); ASSERT_TRUE(duplicate); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 1, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // Attempt to change vote. Status s = counter.RegisterVote(voter_uuids[0], VOTE_DENIED, &duplicate); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "voted a different way twice"); LOG(INFO) << "Expected vote-changed error: " << s.ToString(); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 1, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // Add more votes... ASSERT_OK(counter.RegisterVote(voter_uuids[1], VOTE_DENIED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 1, 1)); ASSERT_FALSE(counter.AreAllVotesIn()); ASSERT_OK(counter.RegisterVote(voter_uuids[2], VOTE_GRANTED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 2, 1)); ASSERT_FALSE(counter.AreAllVotesIn()); ASSERT_OK(counter.RegisterVote(voter_uuids[3], VOTE_DENIED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_NO_FATAL_FAILURE(AssertUndecided(counter)); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 2, 2)); ASSERT_FALSE(counter.AreAllVotesIn()); // Win the election. ASSERT_OK(counter.RegisterVote(voter_uuids[4], VOTE_GRANTED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_TRUE(counter.IsDecided()); ElectionVote decision; ASSERT_OK(counter.GetDecision(&decision)); ASSERT_TRUE(decision == VOTE_GRANTED); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 3, 2)); ASSERT_TRUE(counter.AreAllVotesIn()); // Attempt to vote with > the whole configuration. s = counter.RegisterVote("some-random-node", VOTE_GRANTED, &duplicate); ASSERT_TRUE(s.IsInvalidArgument()); ASSERT_STR_CONTAINS(s.ToString(), "cause the number of votes to exceed the expected number"); LOG(INFO) << "Expected voters-exceeded error: " << s.ToString(); ASSERT_TRUE(counter.IsDecided()); ASSERT_NO_FATAL_FAILURE(AssertVoteCount(counter, 3, 2)); ASSERT_TRUE(counter.AreAllVotesIn()); } // Test vote counting with an even number of voters. TEST_F(VoteCounterTest, TestVoteCounter_EvenVoters) { const int kNumVoters = 2; const int kMajoritySize = 2; vector<string> voter_uuids = GenVoterUUIDs(kNumVoters); // "Yes" decision. { VoteCounter counter(kNumVoters, kMajoritySize); NO_FATALS(AssertUndecided(counter)); NO_FATALS(AssertVoteCount(counter, 0, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // Initial yes vote. bool duplicate; ASSERT_OK(counter.RegisterVote(voter_uuids[0], VOTE_GRANTED, &duplicate)); ASSERT_FALSE(duplicate); NO_FATALS(AssertUndecided(counter)); NO_FATALS(AssertVoteCount(counter, 1, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // Second yes vote wins it. ASSERT_OK(counter.RegisterVote(voter_uuids[1], VOTE_GRANTED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_TRUE(counter.IsDecided()); ElectionVote decision; ASSERT_OK(counter.GetDecision(&decision)); ASSERT_TRUE(decision == VOTE_GRANTED); NO_FATALS(AssertVoteCount(counter, 2, 0)); ASSERT_TRUE(counter.AreAllVotesIn()); } // "No" decision. { VoteCounter counter(kNumVoters, kMajoritySize); NO_FATALS(AssertUndecided(counter)); NO_FATALS(AssertVoteCount(counter, 0, 0)); ASSERT_FALSE(counter.AreAllVotesIn()); // The first "no" vote guarantees a failed election when num voters == 2. bool duplicate; ASSERT_OK(counter.RegisterVote(voter_uuids[0], VOTE_DENIED, &duplicate)); ASSERT_FALSE(duplicate); ASSERT_TRUE(counter.IsDecided()); ElectionVote decision; ASSERT_OK(counter.GetDecision(&decision)); ASSERT_TRUE(decision == VOTE_DENIED); NO_FATALS(AssertVoteCount(counter, 0, 1)); ASSERT_FALSE(counter.AreAllVotesIn()); } } } // namespace consensus } // namespace kudu
/* * Copyright (c) 2021, The OpenThread Authors. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holder nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /** * @file * This file includes definition for OTBR Agent. */ #ifndef OTBR_AGENT_APPLICATION_HPP_ #define OTBR_AGENT_APPLICATION_HPP_ #include <signal.h> #include <stdint.h> #include <vector> #if OTBR_ENABLE_BORDER_AGENT #include "border_agent/border_agent.hpp" #endif #include "ncp/ncp_openthread.hpp" #if OTBR_ENABLE_BACKBONE_ROUTER #include "backbone_router/backbone_agent.hpp" #endif #if OTBR_ENABLE_REST_SERVER #include "rest/rest_web_server.hpp" #endif #if OTBR_ENABLE_DBUS_SERVER #include "dbus/server/dbus_agent.hpp" #endif #if OTBR_ENABLE_OPENWRT #include "openwrt/ubus/otubus.hpp" #endif #if OTBR_ENABLE_VENDOR_SERVER #include "agent/vendor.hpp" #endif namespace otbr { /** * @addtogroup border-router-agent * * @brief * This module includes definition for OTBR application. * * @{ */ /** * This class implements OTBR application management. * */ class Application : private NonCopyable { public: /** * This constructor initializes the Application instance. * * @param[in] aOpenThread A reference to the OpenThread instance. * */ explicit Application(const std::string & aInterfaceName, const std::string & aBackboneInterfaceName, const std::vector<const char *> &aRadioUrls); /** * This method initializes the Application instance. * */ void Init(void); /** * This method runs the application until exit. * * @retval OTBR_ERROR_NONE The application exited without any error. * @retval OTBR_ERROR_ERRNO The application exited with some system error. * */ otbrError Run(void); private: // Default poll timeout. static const struct timeval kPollTimeout; static void HandleSignal(int aSignal); std::string mInterfaceName; std::string mBackboneInterfaceName; Ncp::ControllerOpenThread mNcp; #if OTBR_ENABLE_BORDER_AGENT BorderAgent mBorderAgent; #endif #if OTBR_ENABLE_BACKBONE_ROUTER BackboneRouter::BackboneAgent mBackboneAgent; #endif #if OTBR_ENABLE_OPENWRT ubus::UBusAgent mUbusAgent; #endif #if OTBR_ENABLE_REST_SERVER rest::RestWebServer mRestWebServer; #endif #if OTBR_ENABLE_DBUS_SERVER DBus::DBusAgent mDBusAgent; #endif #if OTBR_ENABLE_VENDOR_SERVER vendor::VendorServer mVendorServer; #endif static bool sShouldTerminate; }; /** * @} */ } // namespace otbr #endif // OTBR_AGENT_APPLICATION_HPP_
//===- llvm/lib/CodeGen/AsmPrinter/CodeViewDebug.cpp ----------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file contains support for writing Microsoft CodeView debug info. // //===----------------------------------------------------------------------===// #include "CodeViewDebug.h" #include "DwarfExpression.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/DenseMap.h" #include "llvm/ADT/DenseSet.h" #include "llvm/ADT/MapVector.h" #include "llvm/ADT/None.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallString.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/TinyPtrVector.h" #include "llvm/ADT/Triple.h" #include "llvm/ADT/Twine.h" #include "llvm/BinaryFormat/COFF.h" #include "llvm/BinaryFormat/Dwarf.h" #include "llvm/CodeGen/AsmPrinter.h" #include "llvm/CodeGen/LexicalScopes.h" #include "llvm/CodeGen/MachineFrameInfo.h" #include "llvm/CodeGen/MachineFunction.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineModuleInfo.h" #include "llvm/CodeGen/MachineOperand.h" #include "llvm/CodeGen/TargetFrameLowering.h" #include "llvm/CodeGen/TargetRegisterInfo.h" #include "llvm/CodeGen/TargetSubtargetInfo.h" #include "llvm/Config/llvm-config.h" #include "llvm/DebugInfo/CodeView/CVTypeVisitor.h" #include "llvm/DebugInfo/CodeView/CodeView.h" #include "llvm/DebugInfo/CodeView/CodeViewRecordIO.h" #include "llvm/DebugInfo/CodeView/ContinuationRecordBuilder.h" #include "llvm/DebugInfo/CodeView/DebugInlineeLinesSubsection.h" #include "llvm/DebugInfo/CodeView/EnumTables.h" #include "llvm/DebugInfo/CodeView/Line.h" #include "llvm/DebugInfo/CodeView/SymbolRecord.h" #include "llvm/DebugInfo/CodeView/TypeDumpVisitor.h" #include "llvm/DebugInfo/CodeView/TypeIndex.h" #include "llvm/DebugInfo/CodeView/TypeRecord.h" #include "llvm/DebugInfo/CodeView/TypeTableCollection.h" #include "llvm/DebugInfo/CodeView/TypeVisitorCallbackPipeline.h" #include "llvm/IR/Constants.h" #include "llvm/IR/DataLayout.h" #include "llvm/IR/DebugInfoMetadata.h" #include "llvm/IR/DebugLoc.h" #include "llvm/IR/Function.h" #include "llvm/IR/GlobalValue.h" #include "llvm/IR/GlobalVariable.h" #include "llvm/IR/Metadata.h" #include "llvm/IR/Module.h" #include "llvm/MC/MCAsmInfo.h" #include "llvm/MC/MCContext.h" #include "llvm/MC/MCSectionCOFF.h" #include "llvm/MC/MCStreamer.h" #include "llvm/MC/MCSymbol.h" #include "llvm/Support/BinaryByteStream.h" #include "llvm/Support/BinaryStreamReader.h" #include "llvm/Support/BinaryStreamWriter.h" #include "llvm/Support/Casting.h" #include "llvm/Support/CommandLine.h" #include "llvm/Support/Compiler.h" #include "llvm/Support/Endian.h" #include "llvm/Support/Error.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/FormatVariadic.h" #include "llvm/Support/Path.h" #include "llvm/Support/SMLoc.h" #include "llvm/Support/ScopedPrinter.h" #include "llvm/Target/TargetLoweringObjectFile.h" #include "llvm/Target/TargetMachine.h" #include <algorithm> #include <cassert> #include <cctype> #include <cstddef> #include <cstdint> #include <iterator> #include <limits> #include <string> #include <utility> #include <vector> using namespace llvm; using namespace llvm::codeview; namespace { class CVMCAdapter : public CodeViewRecordStreamer { public: CVMCAdapter(MCStreamer &OS, TypeCollection &TypeTable) : OS(&OS), TypeTable(TypeTable) {} void emitBytes(StringRef Data) { OS->emitBytes(Data); } void emitIntValue(uint64_t Value, unsigned Size) { OS->emitIntValueInHex(Value, Size); } void emitBinaryData(StringRef Data) { OS->emitBinaryData(Data); } void AddComment(const Twine &T) { OS->AddComment(T); } void AddRawComment(const Twine &T) { OS->emitRawComment(T); } bool isVerboseAsm() { return OS->isVerboseAsm(); } std::string getTypeName(TypeIndex TI) { std::string TypeName; if (!TI.isNoneType()) { if (TI.isSimple()) TypeName = std::string(TypeIndex::simpleTypeName(TI)); else TypeName = std::string(TypeTable.getTypeName(TI)); } return TypeName; } private: MCStreamer *OS = nullptr; TypeCollection &TypeTable; }; } // namespace static CPUType mapArchToCVCPUType(Triple::ArchType Type) { switch (Type) { case Triple::ArchType::x86: return CPUType::Pentium3; case Triple::ArchType::x86_64: return CPUType::X64; case Triple::ArchType::thumb: return CPUType::Thumb; case Triple::ArchType::aarch64: return CPUType::ARM64; default: report_fatal_error("target architecture doesn't map to a CodeView CPUType"); } } CodeViewDebug::CodeViewDebug(AsmPrinter *AP) : DebugHandlerBase(AP), OS(*Asm->OutStreamer), TypeTable(Allocator) { // If module doesn't have named metadata anchors or COFF debug section // is not available, skip any debug info related stuff. if (!MMI->getModule()->getNamedMetadata("llvm.dbg.cu") || !AP->getObjFileLowering().getCOFFDebugSymbolsSection()) { Asm = nullptr; MMI->setDebugInfoAvailability(false); return; } // Tell MMI that we have debug info. MMI->setDebugInfoAvailability(true); TheCPU = mapArchToCVCPUType(Triple(MMI->getModule()->getTargetTriple()).getArch()); collectGlobalVariableInfo(); // Check if we should emit type record hashes. ConstantInt *GH = mdconst::extract_or_null<ConstantInt>( MMI->getModule()->getModuleFlag("CodeViewGHash")); EmitDebugGlobalHashes = GH && !GH->isZero(); } StringRef CodeViewDebug::getFullFilepath(const DIFile *File) { std::string &Filepath = FileToFilepathMap[File]; if (!Filepath.empty()) return Filepath; StringRef Dir = File->getDirectory(), Filename = File->getFilename(); // If this is a Unix-style path, just use it as is. Don't try to canonicalize // it textually because one of the path components could be a symlink. if (Dir.startswith("/") || Filename.startswith("/")) { if (llvm::sys::path::is_absolute(Filename, llvm::sys::path::Style::posix)) return Filename; Filepath = std::string(Dir); if (Dir.back() != '/') Filepath += '/'; Filepath += Filename; return Filepath; } // Clang emits directory and relative filename info into the IR, but CodeView // operates on full paths. We could change Clang to emit full paths too, but // that would increase the IR size and probably not needed for other users. // For now, just concatenate and canonicalize the path here. if (Filename.find(':') == 1) Filepath = std::string(Filename); else Filepath = (Dir + "\\" + Filename).str(); // Canonicalize the path. We have to do it textually because we may no longer // have access the file in the filesystem. // First, replace all slashes with backslashes. std::replace(Filepath.begin(), Filepath.end(), '/', '\\'); // Remove all "\.\" with "\". size_t Cursor = 0; while ((Cursor = Filepath.find("\\.\\", Cursor)) != std::string::npos) Filepath.erase(Cursor, 2); // Replace all "\XXX\..\" with "\". Don't try too hard though as the original // path should be well-formatted, e.g. start with a drive letter, etc. Cursor = 0; while ((Cursor = Filepath.find("\\..\\", Cursor)) != std::string::npos) { // Something's wrong if the path starts with "\..\", abort. if (Cursor == 0) break; size_t PrevSlash = Filepath.rfind('\\', Cursor - 1); if (PrevSlash == std::string::npos) // Something's wrong, abort. break; Filepath.erase(PrevSlash, Cursor + 3 - PrevSlash); // The next ".." might be following the one we've just erased. Cursor = PrevSlash; } // Remove all duplicate backslashes. Cursor = 0; while ((Cursor = Filepath.find("\\\\", Cursor)) != std::string::npos) Filepath.erase(Cursor, 1); return Filepath; } unsigned CodeViewDebug::maybeRecordFile(const DIFile *F) { StringRef FullPath = getFullFilepath(F); unsigned NextId = FileIdMap.size() + 1; auto Insertion = FileIdMap.insert(std::make_pair(FullPath, NextId)); if (Insertion.second) { // We have to compute the full filepath and emit a .cv_file directive. ArrayRef<uint8_t> ChecksumAsBytes; FileChecksumKind CSKind = FileChecksumKind::None; if (F->getChecksum()) { std::string Checksum = fromHex(F->getChecksum()->Value); void *CKMem = OS.getContext().allocate(Checksum.size(), 1); memcpy(CKMem, Checksum.data(), Checksum.size()); ChecksumAsBytes = ArrayRef<uint8_t>( reinterpret_cast<const uint8_t *>(CKMem), Checksum.size()); switch (F->getChecksum()->Kind) { case DIFile::CSK_MD5: CSKind = FileChecksumKind::MD5; break; case DIFile::CSK_SHA1: CSKind = FileChecksumKind::SHA1; break; case DIFile::CSK_SHA256: CSKind = FileChecksumKind::SHA256; break; } } bool Success = OS.EmitCVFileDirective(NextId, FullPath, ChecksumAsBytes, static_cast<unsigned>(CSKind)); (void)Success; assert(Success && ".cv_file directive failed"); } return Insertion.first->second; } CodeViewDebug::InlineSite & CodeViewDebug::getInlineSite(const DILocation *InlinedAt, const DISubprogram *Inlinee) { auto SiteInsertion = CurFn->InlineSites.insert({InlinedAt, InlineSite()}); InlineSite *Site = &SiteInsertion.first->second; if (SiteInsertion.second) { unsigned ParentFuncId = CurFn->FuncId; if (const DILocation *OuterIA = InlinedAt->getInlinedAt()) ParentFuncId = getInlineSite(OuterIA, InlinedAt->getScope()->getSubprogram()) .SiteFuncId; Site->SiteFuncId = NextFuncId++; OS.EmitCVInlineSiteIdDirective( Site->SiteFuncId, ParentFuncId, maybeRecordFile(InlinedAt->getFile()), InlinedAt->getLine(), InlinedAt->getColumn(), SMLoc()); Site->Inlinee = Inlinee; InlinedSubprograms.insert(Inlinee); getFuncIdForSubprogram(Inlinee); } return *Site; } static StringRef getPrettyScopeName(const DIScope *Scope) { StringRef ScopeName = Scope->getName(); if (!ScopeName.empty()) return ScopeName; switch (Scope->getTag()) { case dwarf::DW_TAG_enumeration_type: case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_union_type: return "<unnamed-tag>"; case dwarf::DW_TAG_namespace: return "`anonymous namespace'"; } return StringRef(); } const DISubprogram *CodeViewDebug::collectParentScopeNames( const DIScope *Scope, SmallVectorImpl<StringRef> &QualifiedNameComponents) { const DISubprogram *ClosestSubprogram = nullptr; while (Scope != nullptr) { if (ClosestSubprogram == nullptr) ClosestSubprogram = dyn_cast<DISubprogram>(Scope); // If a type appears in a scope chain, make sure it gets emitted. The // frontend will be responsible for deciding if this should be a forward // declaration or a complete type. if (const auto *Ty = dyn_cast<DICompositeType>(Scope)) DeferredCompleteTypes.push_back(Ty); StringRef ScopeName = getPrettyScopeName(Scope); if (!ScopeName.empty()) QualifiedNameComponents.push_back(ScopeName); Scope = Scope->getScope(); } return ClosestSubprogram; } static std::string formatNestedName(ArrayRef<StringRef> QualifiedNameComponents, StringRef TypeName) { std::string FullyQualifiedName; for (StringRef QualifiedNameComponent : llvm::reverse(QualifiedNameComponents)) { FullyQualifiedName.append(std::string(QualifiedNameComponent)); FullyQualifiedName.append("::"); } FullyQualifiedName.append(std::string(TypeName)); return FullyQualifiedName; } struct CodeViewDebug::TypeLoweringScope { TypeLoweringScope(CodeViewDebug &CVD) : CVD(CVD) { ++CVD.TypeEmissionLevel; } ~TypeLoweringScope() { // Don't decrement TypeEmissionLevel until after emitting deferred types, so // inner TypeLoweringScopes don't attempt to emit deferred types. if (CVD.TypeEmissionLevel == 1) CVD.emitDeferredCompleteTypes(); --CVD.TypeEmissionLevel; } CodeViewDebug &CVD; }; std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Scope, StringRef Name) { // Ensure types in the scope chain are emitted as soon as possible. // This can create otherwise a situation where S_UDTs are emitted while // looping in emitDebugInfoForUDTs. TypeLoweringScope S(*this); SmallVector<StringRef, 5> QualifiedNameComponents; collectParentScopeNames(Scope, QualifiedNameComponents); return formatNestedName(QualifiedNameComponents, Name); } std::string CodeViewDebug::getFullyQualifiedName(const DIScope *Ty) { const DIScope *Scope = Ty->getScope(); return getFullyQualifiedName(Scope, getPrettyScopeName(Ty)); } TypeIndex CodeViewDebug::getScopeIndex(const DIScope *Scope) { // No scope means global scope and that uses the zero index. if (!Scope || isa<DIFile>(Scope)) return TypeIndex(); assert(!isa<DIType>(Scope) && "shouldn't make a namespace scope for a type"); // Check if we've already translated this scope. auto I = TypeIndices.find({Scope, nullptr}); if (I != TypeIndices.end()) return I->second; // Build the fully qualified name of the scope. std::string ScopeName = getFullyQualifiedName(Scope); StringIdRecord SID(TypeIndex(), ScopeName); auto TI = TypeTable.writeLeafType(SID); return recordTypeIndexForDINode(Scope, TI); } TypeIndex CodeViewDebug::getFuncIdForSubprogram(const DISubprogram *SP) { assert(SP); // Check if we've already translated this subprogram. auto I = TypeIndices.find({SP, nullptr}); if (I != TypeIndices.end()) return I->second; // The display name includes function template arguments. Drop them to match // MSVC. StringRef DisplayName = SP->getName().split('<').first; const DIScope *Scope = SP->getScope(); TypeIndex TI; if (const auto *Class = dyn_cast_or_null<DICompositeType>(Scope)) { // If the scope is a DICompositeType, then this must be a method. Member // function types take some special handling, and require access to the // subprogram. TypeIndex ClassType = getTypeIndex(Class); MemberFuncIdRecord MFuncId(ClassType, getMemberFunctionType(SP, Class), DisplayName); TI = TypeTable.writeLeafType(MFuncId); } else { // Otherwise, this must be a free function. TypeIndex ParentScope = getScopeIndex(Scope); FuncIdRecord FuncId(ParentScope, getTypeIndex(SP->getType()), DisplayName); TI = TypeTable.writeLeafType(FuncId); } return recordTypeIndexForDINode(SP, TI); } static bool isNonTrivial(const DICompositeType *DCTy) { return ((DCTy->getFlags() & DINode::FlagNonTrivial) == DINode::FlagNonTrivial); } static FunctionOptions getFunctionOptions(const DISubroutineType *Ty, const DICompositeType *ClassTy = nullptr, StringRef SPName = StringRef("")) { FunctionOptions FO = FunctionOptions::None; const DIType *ReturnTy = nullptr; if (auto TypeArray = Ty->getTypeArray()) { if (TypeArray.size()) ReturnTy = TypeArray[0]; } // Add CxxReturnUdt option to functions that return nontrivial record types // or methods that return record types. if (auto *ReturnDCTy = dyn_cast_or_null<DICompositeType>(ReturnTy)) if (isNonTrivial(ReturnDCTy) || ClassTy) FO |= FunctionOptions::CxxReturnUdt; // DISubroutineType is unnamed. Use DISubprogram's i.e. SPName in comparison. if (ClassTy && isNonTrivial(ClassTy) && SPName == ClassTy->getName()) { FO |= FunctionOptions::Constructor; // TODO: put the FunctionOptions::ConstructorWithVirtualBases flag. } return FO; } TypeIndex CodeViewDebug::getMemberFunctionType(const DISubprogram *SP, const DICompositeType *Class) { // Always use the method declaration as the key for the function type. The // method declaration contains the this adjustment. if (SP->getDeclaration()) SP = SP->getDeclaration(); assert(!SP->getDeclaration() && "should use declaration as key"); // Key the MemberFunctionRecord into the map as {SP, Class}. It won't collide // with the MemberFuncIdRecord, which is keyed in as {SP, nullptr}. auto I = TypeIndices.find({SP, Class}); if (I != TypeIndices.end()) return I->second; // Make sure complete type info for the class is emitted *after* the member // function type, as the complete class type is likely to reference this // member function type. TypeLoweringScope S(*this); const bool IsStaticMethod = (SP->getFlags() & DINode::FlagStaticMember) != 0; FunctionOptions FO = getFunctionOptions(SP->getType(), Class, SP->getName()); TypeIndex TI = lowerTypeMemberFunction( SP->getType(), Class, SP->getThisAdjustment(), IsStaticMethod, FO); return recordTypeIndexForDINode(SP, TI, Class); } TypeIndex CodeViewDebug::recordTypeIndexForDINode(const DINode *Node, TypeIndex TI, const DIType *ClassTy) { auto InsertResult = TypeIndices.insert({{Node, ClassTy}, TI}); (void)InsertResult; assert(InsertResult.second && "DINode was already assigned a type index"); return TI; } unsigned CodeViewDebug::getPointerSizeInBytes() { return MMI->getModule()->getDataLayout().getPointerSizeInBits() / 8; } void CodeViewDebug::recordLocalVariable(LocalVariable &&Var, const LexicalScope *LS) { if (const DILocation *InlinedAt = LS->getInlinedAt()) { // This variable was inlined. Associate it with the InlineSite. const DISubprogram *Inlinee = Var.DIVar->getScope()->getSubprogram(); InlineSite &Site = getInlineSite(InlinedAt, Inlinee); Site.InlinedLocals.emplace_back(Var); } else { // This variable goes into the corresponding lexical scope. ScopeVariables[LS].emplace_back(Var); } } static void addLocIfNotPresent(SmallVectorImpl<const DILocation *> &Locs, const DILocation *Loc) { auto B = Locs.begin(), E = Locs.end(); if (std::find(B, E, Loc) == E) Locs.push_back(Loc); } void CodeViewDebug::maybeRecordLocation(const DebugLoc &DL, const MachineFunction *MF) { // Skip this instruction if it has the same location as the previous one. if (!DL || DL == PrevInstLoc) return; const DIScope *Scope = DL.get()->getScope(); if (!Scope) return; // Skip this line if it is longer than the maximum we can record. LineInfo LI(DL.getLine(), DL.getLine(), /*IsStatement=*/true); if (LI.getStartLine() != DL.getLine() || LI.isAlwaysStepInto() || LI.isNeverStepInto()) return; ColumnInfo CI(DL.getCol(), /*EndColumn=*/0); if (CI.getStartColumn() != DL.getCol()) return; if (!CurFn->HaveLineInfo) CurFn->HaveLineInfo = true; unsigned FileId = 0; if (PrevInstLoc.get() && PrevInstLoc->getFile() == DL->getFile()) FileId = CurFn->LastFileId; else FileId = CurFn->LastFileId = maybeRecordFile(DL->getFile()); PrevInstLoc = DL; unsigned FuncId = CurFn->FuncId; if (const DILocation *SiteLoc = DL->getInlinedAt()) { const DILocation *Loc = DL.get(); // If this location was actually inlined from somewhere else, give it the ID // of the inline call site. FuncId = getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()).SiteFuncId; // Ensure we have links in the tree of inline call sites. bool FirstLoc = true; while ((SiteLoc = Loc->getInlinedAt())) { InlineSite &Site = getInlineSite(SiteLoc, Loc->getScope()->getSubprogram()); if (!FirstLoc) addLocIfNotPresent(Site.ChildSites, Loc); FirstLoc = false; Loc = SiteLoc; } addLocIfNotPresent(CurFn->ChildSites, Loc); } OS.emitCVLocDirective(FuncId, FileId, DL.getLine(), DL.getCol(), /*PrologueEnd=*/false, /*IsStmt=*/false, DL->getFilename(), SMLoc()); } void CodeViewDebug::emitCodeViewMagicVersion() { OS.emitValueToAlignment(4); OS.AddComment("Debug section magic"); OS.emitInt32(COFF::DEBUG_SECTION_MAGIC); } void CodeViewDebug::endModule() { if (!Asm || !MMI->hasDebugInfo()) return; assert(Asm != nullptr); // The COFF .debug$S section consists of several subsections, each starting // with a 4-byte control code (e.g. 0xF1, 0xF2, etc) and then a 4-byte length // of the payload followed by the payload itself. The subsections are 4-byte // aligned. // Use the generic .debug$S section, and make a subsection for all the inlined // subprograms. switchToDebugSectionForSymbol(nullptr); MCSymbol *CompilerInfo = beginCVSubsection(DebugSubsectionKind::Symbols); emitCompilerInformation(); endCVSubsection(CompilerInfo); emitInlineeLinesSubsection(); // Emit per-function debug information. for (auto &P : FnDebugInfo) if (!P.first->isDeclarationForLinker()) emitDebugInfoForFunction(P.first, *P.second); // Emit global variable debug information. setCurrentSubprogram(nullptr); emitDebugInfoForGlobals(); // Emit retained types. emitDebugInfoForRetainedTypes(); // Switch back to the generic .debug$S section after potentially processing // comdat symbol sections. switchToDebugSectionForSymbol(nullptr); // Emit UDT records for any types used by global variables. if (!GlobalUDTs.empty()) { MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); emitDebugInfoForUDTs(GlobalUDTs); endCVSubsection(SymbolsEnd); } // This subsection holds a file index to offset in string table table. OS.AddComment("File index to string table offset subsection"); OS.emitCVFileChecksumsDirective(); // This subsection holds the string table. OS.AddComment("String table"); OS.emitCVStringTableDirective(); // Emit S_BUILDINFO, which points to LF_BUILDINFO. Put this in its own symbol // subsection in the generic .debug$S section at the end. There is no // particular reason for this ordering other than to match MSVC. emitBuildInfo(); // Emit type information and hashes last, so that any types we translate while // emitting function info are included. emitTypeInformation(); if (EmitDebugGlobalHashes) emitTypeGlobalHashes(); clear(); } static void emitNullTerminatedSymbolName(MCStreamer &OS, StringRef S, unsigned MaxFixedRecordLength = 0xF00) { // The maximum CV record length is 0xFF00. Most of the strings we emit appear // after a fixed length portion of the record. The fixed length portion should // always be less than 0xF00 (3840) bytes, so truncate the string so that the // overall record size is less than the maximum allowed. SmallString<32> NullTerminatedString( S.take_front(MaxRecordLength - MaxFixedRecordLength - 1)); NullTerminatedString.push_back('\0'); OS.emitBytes(NullTerminatedString); } void CodeViewDebug::emitTypeInformation() { if (TypeTable.empty()) return; // Start the .debug$T or .debug$P section with 0x4. OS.SwitchSection(Asm->getObjFileLowering().getCOFFDebugTypesSection()); emitCodeViewMagicVersion(); TypeTableCollection Table(TypeTable.records()); TypeVisitorCallbackPipeline Pipeline; // To emit type record using Codeview MCStreamer adapter CVMCAdapter CVMCOS(OS, Table); TypeRecordMapping typeMapping(CVMCOS); Pipeline.addCallbackToPipeline(typeMapping); Optional<TypeIndex> B = Table.getFirst(); while (B) { // This will fail if the record data is invalid. CVType Record = Table.getType(*B); Error E = codeview::visitTypeRecord(Record, *B, Pipeline); if (E) { logAllUnhandledErrors(std::move(E), errs(), "error: "); llvm_unreachable("produced malformed type record"); } B = Table.getNext(*B); } } void CodeViewDebug::emitTypeGlobalHashes() { if (TypeTable.empty()) return; // Start the .debug$H section with the version and hash algorithm, currently // hardcoded to version 0, SHA1. OS.SwitchSection(Asm->getObjFileLowering().getCOFFGlobalTypeHashesSection()); OS.emitValueToAlignment(4); OS.AddComment("Magic"); OS.emitInt32(COFF::DEBUG_HASHES_SECTION_MAGIC); OS.AddComment("Section Version"); OS.emitInt16(0); OS.AddComment("Hash Algorithm"); OS.emitInt16(uint16_t(GlobalTypeHashAlg::SHA1_8)); TypeIndex TI(TypeIndex::FirstNonSimpleIndex); for (const auto &GHR : TypeTable.hashes()) { if (OS.isVerboseAsm()) { // Emit an EOL-comment describing which TypeIndex this hash corresponds // to, as well as the stringified SHA1 hash. SmallString<32> Comment; raw_svector_ostream CommentOS(Comment); CommentOS << formatv("{0:X+} [{1}]", TI.getIndex(), GHR); OS.AddComment(Comment); ++TI; } assert(GHR.Hash.size() == 8); StringRef S(reinterpret_cast<const char *>(GHR.Hash.data()), GHR.Hash.size()); OS.emitBinaryData(S); } } static SourceLanguage MapDWLangToCVLang(unsigned DWLang) { switch (DWLang) { case dwarf::DW_LANG_C: case dwarf::DW_LANG_C89: case dwarf::DW_LANG_C99: case dwarf::DW_LANG_C11: case dwarf::DW_LANG_ObjC: return SourceLanguage::C; case dwarf::DW_LANG_C_plus_plus: case dwarf::DW_LANG_C_plus_plus_03: case dwarf::DW_LANG_C_plus_plus_11: case dwarf::DW_LANG_C_plus_plus_14: return SourceLanguage::Cpp; case dwarf::DW_LANG_Fortran77: case dwarf::DW_LANG_Fortran90: case dwarf::DW_LANG_Fortran03: case dwarf::DW_LANG_Fortran08: return SourceLanguage::Fortran; case dwarf::DW_LANG_Pascal83: return SourceLanguage::Pascal; case dwarf::DW_LANG_Cobol74: case dwarf::DW_LANG_Cobol85: return SourceLanguage::Cobol; case dwarf::DW_LANG_Java: return SourceLanguage::Java; case dwarf::DW_LANG_D: return SourceLanguage::D; case dwarf::DW_LANG_Swift: return SourceLanguage::Swift; default: // There's no CodeView representation for this language, and CV doesn't // have an "unknown" option for the language field, so we'll use MASM, // as it's very low level. return SourceLanguage::Masm; } } namespace { struct Version { int Part[4]; }; } // end anonymous namespace // Takes a StringRef like "clang 4.0.0.0 (other nonsense 123)" and parses out // the version number. static Version parseVersion(StringRef Name) { Version V = {{0}}; int N = 0; for (const char C : Name) { if (isdigit(C)) { V.Part[N] *= 10; V.Part[N] += C - '0'; } else if (C == '.') { ++N; if (N >= 4) return V; } else if (N > 0) return V; } return V; } void CodeViewDebug::emitCompilerInformation() { MCSymbol *CompilerEnd = beginSymbolRecord(SymbolKind::S_COMPILE3); uint32_t Flags = 0; NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); const MDNode *Node = *CUs->operands().begin(); const auto *CU = cast<DICompileUnit>(Node); // The low byte of the flags indicates the source language. Flags = MapDWLangToCVLang(CU->getSourceLanguage()); // TODO: Figure out which other flags need to be set. OS.AddComment("Flags and language"); OS.emitInt32(Flags); OS.AddComment("CPUType"); OS.emitInt16(static_cast<uint64_t>(TheCPU)); StringRef CompilerVersion = CU->getProducer(); Version FrontVer = parseVersion(CompilerVersion); OS.AddComment("Frontend version"); for (int N = 0; N < 4; ++N) OS.emitInt16(FrontVer.Part[N]); // Some Microsoft tools, like Binscope, expect a backend version number of at // least 8.something, so we'll coerce the LLVM version into a form that // guarantees it'll be big enough without really lying about the version. int Major = 1000 * LLVM_VERSION_MAJOR + 10 * LLVM_VERSION_MINOR + LLVM_VERSION_PATCH; // Clamp it for builds that use unusually large version numbers. Major = std::min<int>(Major, std::numeric_limits<uint16_t>::max()); Version BackVer = {{ Major, 0, 0, 0 }}; OS.AddComment("Backend version"); for (int N = 0; N < 4; ++N) OS.emitInt16(BackVer.Part[N]); OS.AddComment("Null-terminated compiler version string"); emitNullTerminatedSymbolName(OS, CompilerVersion); endSymbolRecord(CompilerEnd); } static TypeIndex getStringIdTypeIdx(GlobalTypeTableBuilder &TypeTable, StringRef S) { StringIdRecord SIR(TypeIndex(0x0), S); return TypeTable.writeLeafType(SIR); } void CodeViewDebug::emitBuildInfo() { // First, make LF_BUILDINFO. It's a sequence of strings with various bits of // build info. The known prefix is: // - Absolute path of current directory // - Compiler path // - Main source file path, relative to CWD or absolute // - Type server PDB file // - Canonical compiler command line // If frontend and backend compilation are separated (think llc or LTO), it's // not clear if the compiler path should refer to the executable for the // frontend or the backend. Leave it blank for now. TypeIndex BuildInfoArgs[BuildInfoRecord::MaxArgs] = {}; NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); const MDNode *Node = *CUs->operands().begin(); // FIXME: Multiple CUs. const auto *CU = cast<DICompileUnit>(Node); const DIFile *MainSourceFile = CU->getFile(); BuildInfoArgs[BuildInfoRecord::CurrentDirectory] = getStringIdTypeIdx(TypeTable, MainSourceFile->getDirectory()); BuildInfoArgs[BuildInfoRecord::SourceFile] = getStringIdTypeIdx(TypeTable, MainSourceFile->getFilename()); // FIXME: Path to compiler and command line. PDB is intentionally blank unless // we implement /Zi type servers. BuildInfoRecord BIR(BuildInfoArgs); TypeIndex BuildInfoIndex = TypeTable.writeLeafType(BIR); // Make a new .debug$S subsection for the S_BUILDINFO record, which points // from the module symbols into the type stream. MCSymbol *BISubsecEnd = beginCVSubsection(DebugSubsectionKind::Symbols); MCSymbol *BIEnd = beginSymbolRecord(SymbolKind::S_BUILDINFO); OS.AddComment("LF_BUILDINFO index"); OS.emitInt32(BuildInfoIndex.getIndex()); endSymbolRecord(BIEnd); endCVSubsection(BISubsecEnd); } void CodeViewDebug::emitInlineeLinesSubsection() { if (InlinedSubprograms.empty()) return; OS.AddComment("Inlinee lines subsection"); MCSymbol *InlineEnd = beginCVSubsection(DebugSubsectionKind::InlineeLines); // We emit the checksum info for files. This is used by debuggers to // determine if a pdb matches the source before loading it. Visual Studio, // for instance, will display a warning that the breakpoints are not valid if // the pdb does not match the source. OS.AddComment("Inlinee lines signature"); OS.emitInt32(unsigned(InlineeLinesSignature::Normal)); for (const DISubprogram *SP : InlinedSubprograms) { assert(TypeIndices.count({SP, nullptr})); TypeIndex InlineeIdx = TypeIndices[{SP, nullptr}]; OS.AddBlankLine(); unsigned FileId = maybeRecordFile(SP->getFile()); OS.AddComment("Inlined function " + SP->getName() + " starts at " + SP->getFilename() + Twine(':') + Twine(SP->getLine())); OS.AddBlankLine(); OS.AddComment("Type index of inlined function"); OS.emitInt32(InlineeIdx.getIndex()); OS.AddComment("Offset into filechecksum table"); OS.emitCVFileChecksumOffsetDirective(FileId); OS.AddComment("Starting line number"); OS.emitInt32(SP->getLine()); } endCVSubsection(InlineEnd); } void CodeViewDebug::emitInlinedCallSite(const FunctionInfo &FI, const DILocation *InlinedAt, const InlineSite &Site) { assert(TypeIndices.count({Site.Inlinee, nullptr})); TypeIndex InlineeIdx = TypeIndices[{Site.Inlinee, nullptr}]; // SymbolRecord MCSymbol *InlineEnd = beginSymbolRecord(SymbolKind::S_INLINESITE); OS.AddComment("PtrParent"); OS.emitInt32(0); OS.AddComment("PtrEnd"); OS.emitInt32(0); OS.AddComment("Inlinee type index"); OS.emitInt32(InlineeIdx.getIndex()); unsigned FileId = maybeRecordFile(Site.Inlinee->getFile()); unsigned StartLineNum = Site.Inlinee->getLine(); OS.emitCVInlineLinetableDirective(Site.SiteFuncId, FileId, StartLineNum, FI.Begin, FI.End); endSymbolRecord(InlineEnd); emitLocalVariableList(FI, Site.InlinedLocals); // Recurse on child inlined call sites before closing the scope. for (const DILocation *ChildSite : Site.ChildSites) { auto I = FI.InlineSites.find(ChildSite); assert(I != FI.InlineSites.end() && "child site not in function inline site map"); emitInlinedCallSite(FI, ChildSite, I->second); } // Close the scope. emitEndSymbolRecord(SymbolKind::S_INLINESITE_END); } void CodeViewDebug::switchToDebugSectionForSymbol(const MCSymbol *GVSym) { // If we have a symbol, it may be in a section that is COMDAT. If so, find the // comdat key. A section may be comdat because of -ffunction-sections or // because it is comdat in the IR. MCSectionCOFF *GVSec = GVSym ? dyn_cast<MCSectionCOFF>(&GVSym->getSection()) : nullptr; const MCSymbol *KeySym = GVSec ? GVSec->getCOMDATSymbol() : nullptr; MCSectionCOFF *DebugSec = cast<MCSectionCOFF>( Asm->getObjFileLowering().getCOFFDebugSymbolsSection()); DebugSec = OS.getContext().getAssociativeCOFFSection(DebugSec, KeySym); OS.SwitchSection(DebugSec); // Emit the magic version number if this is the first time we've switched to // this section. if (ComdatDebugSections.insert(DebugSec).second) emitCodeViewMagicVersion(); } // Emit an S_THUNK32/S_END symbol pair for a thunk routine. // The only supported thunk ordinal is currently the standard type. void CodeViewDebug::emitDebugInfoForThunk(const Function *GV, FunctionInfo &FI, const MCSymbol *Fn) { std::string FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName())); const ThunkOrdinal ordinal = ThunkOrdinal::Standard; // Only supported kind. OS.AddComment("Symbol subsection for " + Twine(FuncName)); MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); // Emit S_THUNK32 MCSymbol *ThunkRecordEnd = beginSymbolRecord(SymbolKind::S_THUNK32); OS.AddComment("PtrParent"); OS.emitInt32(0); OS.AddComment("PtrEnd"); OS.emitInt32(0); OS.AddComment("PtrNext"); OS.emitInt32(0); OS.AddComment("Thunk section relative address"); OS.EmitCOFFSecRel32(Fn, /*Offset=*/0); OS.AddComment("Thunk section index"); OS.EmitCOFFSectionIndex(Fn); OS.AddComment("Code size"); OS.emitAbsoluteSymbolDiff(FI.End, Fn, 2); OS.AddComment("Ordinal"); OS.emitInt8(unsigned(ordinal)); OS.AddComment("Function name"); emitNullTerminatedSymbolName(OS, FuncName); // Additional fields specific to the thunk ordinal would go here. endSymbolRecord(ThunkRecordEnd); // Local variables/inlined routines are purposely omitted here. The point of // marking this as a thunk is so Visual Studio will NOT stop in this routine. // Emit S_PROC_ID_END emitEndSymbolRecord(SymbolKind::S_PROC_ID_END); endCVSubsection(SymbolsEnd); } void CodeViewDebug::emitDebugInfoForFunction(const Function *GV, FunctionInfo &FI) { // For each function there is a separate subsection which holds the PC to // file:line table. const MCSymbol *Fn = Asm->getSymbol(GV); assert(Fn); // Switch to the to a comdat section, if appropriate. switchToDebugSectionForSymbol(Fn); std::string FuncName; auto *SP = GV->getSubprogram(); assert(SP); setCurrentSubprogram(SP); if (SP->isThunk()) { emitDebugInfoForThunk(GV, FI, Fn); return; } // If we have a display name, build the fully qualified name by walking the // chain of scopes. if (!SP->getName().empty()) FuncName = getFullyQualifiedName(SP->getScope(), SP->getName()); // If our DISubprogram name is empty, use the mangled name. if (FuncName.empty()) FuncName = std::string(GlobalValue::dropLLVMManglingEscape(GV->getName())); // Emit FPO data, but only on 32-bit x86. No other platforms use it. if (Triple(MMI->getModule()->getTargetTriple()).getArch() == Triple::x86) OS.EmitCVFPOData(Fn); // Emit a symbol subsection, required by VS2012+ to find function boundaries. OS.AddComment("Symbol subsection for " + Twine(FuncName)); MCSymbol *SymbolsEnd = beginCVSubsection(DebugSubsectionKind::Symbols); { SymbolKind ProcKind = GV->hasLocalLinkage() ? SymbolKind::S_LPROC32_ID : SymbolKind::S_GPROC32_ID; MCSymbol *ProcRecordEnd = beginSymbolRecord(ProcKind); // These fields are filled in by tools like CVPACK which run after the fact. OS.AddComment("PtrParent"); OS.emitInt32(0); OS.AddComment("PtrEnd"); OS.emitInt32(0); OS.AddComment("PtrNext"); OS.emitInt32(0); // This is the important bit that tells the debugger where the function // code is located and what's its size: OS.AddComment("Code size"); OS.emitAbsoluteSymbolDiff(FI.End, Fn, 4); OS.AddComment("Offset after prologue"); OS.emitInt32(0); OS.AddComment("Offset before epilogue"); OS.emitInt32(0); OS.AddComment("Function type index"); OS.emitInt32(getFuncIdForSubprogram(GV->getSubprogram()).getIndex()); OS.AddComment("Function section relative address"); OS.EmitCOFFSecRel32(Fn, /*Offset=*/0); OS.AddComment("Function section index"); OS.EmitCOFFSectionIndex(Fn); OS.AddComment("Flags"); OS.emitInt8(0); // Emit the function display name as a null-terminated string. OS.AddComment("Function name"); // Truncate the name so we won't overflow the record length field. emitNullTerminatedSymbolName(OS, FuncName); endSymbolRecord(ProcRecordEnd); MCSymbol *FrameProcEnd = beginSymbolRecord(SymbolKind::S_FRAMEPROC); // Subtract out the CSR size since MSVC excludes that and we include it. OS.AddComment("FrameSize"); OS.emitInt32(FI.FrameSize - FI.CSRSize); OS.AddComment("Padding"); OS.emitInt32(0); OS.AddComment("Offset of padding"); OS.emitInt32(0); OS.AddComment("Bytes of callee saved registers"); OS.emitInt32(FI.CSRSize); OS.AddComment("Exception handler offset"); OS.emitInt32(0); OS.AddComment("Exception handler section"); OS.emitInt16(0); OS.AddComment("Flags (defines frame register)"); OS.emitInt32(uint32_t(FI.FrameProcOpts)); endSymbolRecord(FrameProcEnd); emitLocalVariableList(FI, FI.Locals); emitGlobalVariableList(FI.Globals); emitLexicalBlockList(FI.ChildBlocks, FI); // Emit inlined call site information. Only emit functions inlined directly // into the parent function. We'll emit the other sites recursively as part // of their parent inline site. for (const DILocation *InlinedAt : FI.ChildSites) { auto I = FI.InlineSites.find(InlinedAt); assert(I != FI.InlineSites.end() && "child site not in function inline site map"); emitInlinedCallSite(FI, InlinedAt, I->second); } for (auto Annot : FI.Annotations) { MCSymbol *Label = Annot.first; MDTuple *Strs = cast<MDTuple>(Annot.second); MCSymbol *AnnotEnd = beginSymbolRecord(SymbolKind::S_ANNOTATION); OS.EmitCOFFSecRel32(Label, /*Offset=*/0); // FIXME: Make sure we don't overflow the max record size. OS.EmitCOFFSectionIndex(Label); OS.emitInt16(Strs->getNumOperands()); for (Metadata *MD : Strs->operands()) { // MDStrings are null terminated, so we can do EmitBytes and get the // nice .asciz directive. StringRef Str = cast<MDString>(MD)->getString(); assert(Str.data()[Str.size()] == '\0' && "non-nullterminated MDString"); OS.emitBytes(StringRef(Str.data(), Str.size() + 1)); } endSymbolRecord(AnnotEnd); } for (auto HeapAllocSite : FI.HeapAllocSites) { const MCSymbol *BeginLabel = std::get<0>(HeapAllocSite); const MCSymbol *EndLabel = std::get<1>(HeapAllocSite); const DIType *DITy = std::get<2>(HeapAllocSite); MCSymbol *HeapAllocEnd = beginSymbolRecord(SymbolKind::S_HEAPALLOCSITE); OS.AddComment("Call site offset"); OS.EmitCOFFSecRel32(BeginLabel, /*Offset=*/0); OS.AddComment("Call site section index"); OS.EmitCOFFSectionIndex(BeginLabel); OS.AddComment("Call instruction length"); OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2); OS.AddComment("Type index"); OS.emitInt32(getCompleteTypeIndex(DITy).getIndex()); endSymbolRecord(HeapAllocEnd); } if (SP != nullptr) emitDebugInfoForUDTs(LocalUDTs); // We're done with this function. emitEndSymbolRecord(SymbolKind::S_PROC_ID_END); } endCVSubsection(SymbolsEnd); // We have an assembler directive that takes care of the whole line table. OS.emitCVLinetableDirective(FI.FuncId, Fn, FI.End); } CodeViewDebug::LocalVarDefRange CodeViewDebug::createDefRangeMem(uint16_t CVRegister, int Offset) { LocalVarDefRange DR; DR.InMemory = -1; DR.DataOffset = Offset; assert(DR.DataOffset == Offset && "truncation"); DR.IsSubfield = 0; DR.StructOffset = 0; DR.CVRegister = CVRegister; return DR; } void CodeViewDebug::collectVariableInfoFromMFTable( DenseSet<InlinedEntity> &Processed) { const MachineFunction &MF = *Asm->MF; const TargetSubtargetInfo &TSI = MF.getSubtarget(); const TargetFrameLowering *TFI = TSI.getFrameLowering(); const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); for (const MachineFunction::VariableDbgInfo &VI : MF.getVariableDbgInfo()) { if (!VI.Var) continue; assert(VI.Var->isValidLocationForIntrinsic(VI.Loc) && "Expected inlined-at fields to agree"); Processed.insert(InlinedEntity(VI.Var, VI.Loc->getInlinedAt())); LexicalScope *Scope = LScopes.findLexicalScope(VI.Loc); // If variable scope is not found then skip this variable. if (!Scope) continue; // If the variable has an attached offset expression, extract it. // FIXME: Try to handle DW_OP_deref as well. int64_t ExprOffset = 0; bool Deref = false; if (VI.Expr) { // If there is one DW_OP_deref element, use offset of 0 and keep going. if (VI.Expr->getNumElements() == 1 && VI.Expr->getElement(0) == llvm::dwarf::DW_OP_deref) Deref = true; else if (!VI.Expr->extractIfOffset(ExprOffset)) continue; } // Get the frame register used and the offset. Register FrameReg; int FrameOffset = TFI->getFrameIndexReference(*Asm->MF, VI.Slot, FrameReg); uint16_t CVReg = TRI->getCodeViewRegNum(FrameReg); // Calculate the label ranges. LocalVarDefRange DefRange = createDefRangeMem(CVReg, FrameOffset + ExprOffset); for (const InsnRange &Range : Scope->getRanges()) { const MCSymbol *Begin = getLabelBeforeInsn(Range.first); const MCSymbol *End = getLabelAfterInsn(Range.second); End = End ? End : Asm->getFunctionEnd(); DefRange.Ranges.emplace_back(Begin, End); } LocalVariable Var; Var.DIVar = VI.Var; Var.DefRanges.emplace_back(std::move(DefRange)); if (Deref) Var.UseReferenceType = true; recordLocalVariable(std::move(Var), Scope); } } static bool canUseReferenceType(const DbgVariableLocation &Loc) { return !Loc.LoadChain.empty() && Loc.LoadChain.back() == 0; } static bool needsReferenceType(const DbgVariableLocation &Loc) { return Loc.LoadChain.size() == 2 && Loc.LoadChain.back() == 0; } void CodeViewDebug::calculateRanges( LocalVariable &Var, const DbgValueHistoryMap::Entries &Entries) { const TargetRegisterInfo *TRI = Asm->MF->getSubtarget().getRegisterInfo(); // Calculate the definition ranges. for (auto I = Entries.begin(), E = Entries.end(); I != E; ++I) { const auto &Entry = *I; if (!Entry.isDbgValue()) continue; const MachineInstr *DVInst = Entry.getInstr(); assert(DVInst->isDebugValue() && "Invalid History entry"); // FIXME: Find a way to represent constant variables, since they are // relatively common. Optional<DbgVariableLocation> Location = DbgVariableLocation::extractFromMachineInstruction(*DVInst); if (!Location) continue; // CodeView can only express variables in register and variables in memory // at a constant offset from a register. However, for variables passed // indirectly by pointer, it is common for that pointer to be spilled to a // stack location. For the special case of one offseted load followed by a // zero offset load (a pointer spilled to the stack), we change the type of // the local variable from a value type to a reference type. This tricks the // debugger into doing the load for us. if (Var.UseReferenceType) { // We're using a reference type. Drop the last zero offset load. if (canUseReferenceType(*Location)) Location->LoadChain.pop_back(); else continue; } else if (needsReferenceType(*Location)) { // This location can't be expressed without switching to a reference type. // Start over using that. Var.UseReferenceType = true; Var.DefRanges.clear(); calculateRanges(Var, Entries); return; } // We can only handle a register or an offseted load of a register. if (Location->Register == 0 || Location->LoadChain.size() > 1) continue; { LocalVarDefRange DR; DR.CVRegister = TRI->getCodeViewRegNum(Location->Register); DR.InMemory = !Location->LoadChain.empty(); DR.DataOffset = !Location->LoadChain.empty() ? Location->LoadChain.back() : 0; if (Location->FragmentInfo) { DR.IsSubfield = true; DR.StructOffset = Location->FragmentInfo->OffsetInBits / 8; } else { DR.IsSubfield = false; DR.StructOffset = 0; } if (Var.DefRanges.empty() || Var.DefRanges.back().isDifferentLocation(DR)) { Var.DefRanges.emplace_back(std::move(DR)); } } // Compute the label range. const MCSymbol *Begin = getLabelBeforeInsn(Entry.getInstr()); const MCSymbol *End; if (Entry.getEndIndex() != DbgValueHistoryMap::NoEntry) { auto &EndingEntry = Entries[Entry.getEndIndex()]; End = EndingEntry.isDbgValue() ? getLabelBeforeInsn(EndingEntry.getInstr()) : getLabelAfterInsn(EndingEntry.getInstr()); } else End = Asm->getFunctionEnd(); // If the last range end is our begin, just extend the last range. // Otherwise make a new range. SmallVectorImpl<std::pair<const MCSymbol *, const MCSymbol *>> &R = Var.DefRanges.back().Ranges; if (!R.empty() && R.back().second == Begin) R.back().second = End; else R.emplace_back(Begin, End); // FIXME: Do more range combining. } } void CodeViewDebug::collectVariableInfo(const DISubprogram *SP) { DenseSet<InlinedEntity> Processed; // Grab the variable info that was squirreled away in the MMI side-table. collectVariableInfoFromMFTable(Processed); for (const auto &I : DbgValues) { InlinedEntity IV = I.first; if (Processed.count(IV)) continue; const DILocalVariable *DIVar = cast<DILocalVariable>(IV.first); const DILocation *InlinedAt = IV.second; // Instruction ranges, specifying where IV is accessible. const auto &Entries = I.second; LexicalScope *Scope = nullptr; if (InlinedAt) Scope = LScopes.findInlinedScope(DIVar->getScope(), InlinedAt); else Scope = LScopes.findLexicalScope(DIVar->getScope()); // If variable scope is not found then skip this variable. if (!Scope) continue; LocalVariable Var; Var.DIVar = DIVar; calculateRanges(Var, Entries); recordLocalVariable(std::move(Var), Scope); } } void CodeViewDebug::beginFunctionImpl(const MachineFunction *MF) { const TargetSubtargetInfo &TSI = MF->getSubtarget(); const TargetRegisterInfo *TRI = TSI.getRegisterInfo(); const MachineFrameInfo &MFI = MF->getFrameInfo(); const Function &GV = MF->getFunction(); auto Insertion = FnDebugInfo.insert({&GV, std::make_unique<FunctionInfo>()}); assert(Insertion.second && "function already has info"); CurFn = Insertion.first->second.get(); CurFn->FuncId = NextFuncId++; CurFn->Begin = Asm->getFunctionBegin(); // The S_FRAMEPROC record reports the stack size, and how many bytes of // callee-saved registers were used. For targets that don't use a PUSH // instruction (AArch64), this will be zero. CurFn->CSRSize = MFI.getCVBytesOfCalleeSavedRegisters(); CurFn->FrameSize = MFI.getStackSize(); CurFn->OffsetAdjustment = MFI.getOffsetAdjustment(); CurFn->HasStackRealignment = TRI->needsStackRealignment(*MF); // For this function S_FRAMEPROC record, figure out which codeview register // will be the frame pointer. CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::None; // None. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::None; // None. if (CurFn->FrameSize > 0) { if (!TSI.getFrameLowering()->hasFP(*MF)) { CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr; CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::StackPtr; } else { // If there is an FP, parameters are always relative to it. CurFn->EncodedParamFramePtrReg = EncodedFramePtrReg::FramePtr; if (CurFn->HasStackRealignment) { // If the stack needs realignment, locals are relative to SP or VFRAME. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::StackPtr; } else { // Otherwise, locals are relative to EBP, and we probably have VLAs or // other stack adjustments. CurFn->EncodedLocalFramePtrReg = EncodedFramePtrReg::FramePtr; } } } // Compute other frame procedure options. FrameProcedureOptions FPO = FrameProcedureOptions::None; if (MFI.hasVarSizedObjects()) FPO |= FrameProcedureOptions::HasAlloca; if (MF->exposesReturnsTwice()) FPO |= FrameProcedureOptions::HasSetJmp; // FIXME: Set HasLongJmp if we ever track that info. if (MF->hasInlineAsm()) FPO |= FrameProcedureOptions::HasInlineAssembly; if (GV.hasPersonalityFn()) { if (isAsynchronousEHPersonality( classifyEHPersonality(GV.getPersonalityFn()))) FPO |= FrameProcedureOptions::HasStructuredExceptionHandling; else FPO |= FrameProcedureOptions::HasExceptionHandling; } if (GV.hasFnAttribute(Attribute::InlineHint)) FPO |= FrameProcedureOptions::MarkedInline; if (GV.hasFnAttribute(Attribute::Naked)) FPO |= FrameProcedureOptions::Naked; if (MFI.hasStackProtectorIndex()) FPO |= FrameProcedureOptions::SecurityChecks; FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedLocalFramePtrReg) << 14U); FPO |= FrameProcedureOptions(uint32_t(CurFn->EncodedParamFramePtrReg) << 16U); if (Asm->TM.getOptLevel() != CodeGenOpt::None && !GV.hasOptSize() && !GV.hasOptNone()) FPO |= FrameProcedureOptions::OptimizedForSpeed; // FIXME: Set GuardCfg when it is implemented. CurFn->FrameProcOpts = FPO; OS.EmitCVFuncIdDirective(CurFn->FuncId); // Find the end of the function prolog. First known non-DBG_VALUE and // non-frame setup location marks the beginning of the function body. // FIXME: is there a simpler a way to do this? Can we just search // for the first instruction of the function, not the last of the prolog? DebugLoc PrologEndLoc; bool EmptyPrologue = true; for (const auto &MBB : *MF) { for (const auto &MI : MBB) { if (!MI.isMetaInstruction() && !MI.getFlag(MachineInstr::FrameSetup) && MI.getDebugLoc()) { PrologEndLoc = MI.getDebugLoc(); break; } else if (!MI.isMetaInstruction()) { EmptyPrologue = false; } } } // Record beginning of function if we have a non-empty prologue. if (PrologEndLoc && !EmptyPrologue) { DebugLoc FnStartDL = PrologEndLoc.getFnDebugLoc(); maybeRecordLocation(FnStartDL, MF); } // Find heap alloc sites and emit labels around them. for (const auto &MBB : *MF) { for (const auto &MI : MBB) { if (MI.getHeapAllocMarker()) { requestLabelBeforeInsn(&MI); requestLabelAfterInsn(&MI); } } } } static bool shouldEmitUdt(const DIType *T) { if (!T) return false; // MSVC does not emit UDTs for typedefs that are scoped to classes. if (T->getTag() == dwarf::DW_TAG_typedef) { if (DIScope *Scope = T->getScope()) { switch (Scope->getTag()) { case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_union_type: return false; } } } while (true) { if (!T || T->isForwardDecl()) return false; const DIDerivedType *DT = dyn_cast<DIDerivedType>(T); if (!DT) return true; T = DT->getBaseType(); } return true; } void CodeViewDebug::addToUDTs(const DIType *Ty) { // Don't record empty UDTs. if (Ty->getName().empty()) return; if (!shouldEmitUdt(Ty)) return; SmallVector<StringRef, 5> ParentScopeNames; const DISubprogram *ClosestSubprogram = collectParentScopeNames(Ty->getScope(), ParentScopeNames); std::string FullyQualifiedName = formatNestedName(ParentScopeNames, getPrettyScopeName(Ty)); if (ClosestSubprogram == nullptr) { GlobalUDTs.emplace_back(std::move(FullyQualifiedName), Ty); } else if (ClosestSubprogram == CurrentSubprogram) { LocalUDTs.emplace_back(std::move(FullyQualifiedName), Ty); } // TODO: What if the ClosestSubprogram is neither null or the current // subprogram? Currently, the UDT just gets dropped on the floor. // // The current behavior is not desirable. To get maximal fidelity, we would // need to perform all type translation before beginning emission of .debug$S // and then make LocalUDTs a member of FunctionInfo } TypeIndex CodeViewDebug::lowerType(const DIType *Ty, const DIType *ClassTy) { // Generic dispatch for lowering an unknown type. switch (Ty->getTag()) { case dwarf::DW_TAG_array_type: return lowerTypeArray(cast<DICompositeType>(Ty)); case dwarf::DW_TAG_typedef: return lowerTypeAlias(cast<DIDerivedType>(Ty)); case dwarf::DW_TAG_base_type: return lowerTypeBasic(cast<DIBasicType>(Ty)); case dwarf::DW_TAG_pointer_type: if (cast<DIDerivedType>(Ty)->getName() == "__vtbl_ptr_type") return lowerTypeVFTableShape(cast<DIDerivedType>(Ty)); LLVM_FALLTHROUGH; case dwarf::DW_TAG_reference_type: case dwarf::DW_TAG_rvalue_reference_type: return lowerTypePointer(cast<DIDerivedType>(Ty)); case dwarf::DW_TAG_ptr_to_member_type: return lowerTypeMemberPointer(cast<DIDerivedType>(Ty)); case dwarf::DW_TAG_restrict_type: case dwarf::DW_TAG_const_type: case dwarf::DW_TAG_volatile_type: // TODO: add support for DW_TAG_atomic_type here return lowerTypeModifier(cast<DIDerivedType>(Ty)); case dwarf::DW_TAG_subroutine_type: if (ClassTy) { // The member function type of a member function pointer has no // ThisAdjustment. return lowerTypeMemberFunction(cast<DISubroutineType>(Ty), ClassTy, /*ThisAdjustment=*/0, /*IsStaticMethod=*/false); } return lowerTypeFunction(cast<DISubroutineType>(Ty)); case dwarf::DW_TAG_enumeration_type: return lowerTypeEnum(cast<DICompositeType>(Ty)); case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_structure_type: return lowerTypeClass(cast<DICompositeType>(Ty)); case dwarf::DW_TAG_union_type: return lowerTypeUnion(cast<DICompositeType>(Ty)); case dwarf::DW_TAG_unspecified_type: if (Ty->getName() == "decltype(nullptr)") return TypeIndex::NullptrT(); return TypeIndex::None(); default: // Use the null type index. return TypeIndex(); } } TypeIndex CodeViewDebug::lowerTypeAlias(const DIDerivedType *Ty) { TypeIndex UnderlyingTypeIndex = getTypeIndex(Ty->getBaseType()); StringRef TypeName = Ty->getName(); addToUDTs(Ty); if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::Int32Long) && TypeName == "HRESULT") return TypeIndex(SimpleTypeKind::HResult); if (UnderlyingTypeIndex == TypeIndex(SimpleTypeKind::UInt16Short) && TypeName == "wchar_t") return TypeIndex(SimpleTypeKind::WideCharacter); return UnderlyingTypeIndex; } TypeIndex CodeViewDebug::lowerTypeArray(const DICompositeType *Ty) { const DIType *ElementType = Ty->getBaseType(); TypeIndex ElementTypeIndex = getTypeIndex(ElementType); // IndexType is size_t, which depends on the bitness of the target. TypeIndex IndexType = getPointerSizeInBytes() == 8 ? TypeIndex(SimpleTypeKind::UInt64Quad) : TypeIndex(SimpleTypeKind::UInt32Long); uint64_t ElementSize = getBaseTypeSize(ElementType) / 8; // Add subranges to array type. DINodeArray Elements = Ty->getElements(); for (int i = Elements.size() - 1; i >= 0; --i) { const DINode *Element = Elements[i]; assert(Element->getTag() == dwarf::DW_TAG_subrange_type); const DISubrange *Subrange = cast<DISubrange>(Element); assert(!Subrange->getRawLowerBound() && "codeview doesn't support subranges with lower bounds"); int64_t Count = -1; if (auto *CI = Subrange->getCount().dyn_cast<ConstantInt*>()) Count = CI->getSExtValue(); // Forward declarations of arrays without a size and VLAs use a count of -1. // Emit a count of zero in these cases to match what MSVC does for arrays // without a size. MSVC doesn't support VLAs, so it's not clear what we // should do for them even if we could distinguish them. if (Count == -1) Count = 0; // Update the element size and element type index for subsequent subranges. ElementSize *= Count; // If this is the outermost array, use the size from the array. It will be // more accurate if we had a VLA or an incomplete element type size. uint64_t ArraySize = (i == 0 && ElementSize == 0) ? Ty->getSizeInBits() / 8 : ElementSize; StringRef Name = (i == 0) ? Ty->getName() : ""; ArrayRecord AR(ElementTypeIndex, IndexType, ArraySize, Name); ElementTypeIndex = TypeTable.writeLeafType(AR); } return ElementTypeIndex; } TypeIndex CodeViewDebug::lowerTypeBasic(const DIBasicType *Ty) { TypeIndex Index; dwarf::TypeKind Kind; uint32_t ByteSize; Kind = static_cast<dwarf::TypeKind>(Ty->getEncoding()); ByteSize = Ty->getSizeInBits() / 8; SimpleTypeKind STK = SimpleTypeKind::None; switch (Kind) { case dwarf::DW_ATE_address: // FIXME: Translate break; case dwarf::DW_ATE_boolean: switch (ByteSize) { case 1: STK = SimpleTypeKind::Boolean8; break; case 2: STK = SimpleTypeKind::Boolean16; break; case 4: STK = SimpleTypeKind::Boolean32; break; case 8: STK = SimpleTypeKind::Boolean64; break; case 16: STK = SimpleTypeKind::Boolean128; break; } break; case dwarf::DW_ATE_complex_float: switch (ByteSize) { case 2: STK = SimpleTypeKind::Complex16; break; case 4: STK = SimpleTypeKind::Complex32; break; case 8: STK = SimpleTypeKind::Complex64; break; case 10: STK = SimpleTypeKind::Complex80; break; case 16: STK = SimpleTypeKind::Complex128; break; } break; case dwarf::DW_ATE_float: switch (ByteSize) { case 2: STK = SimpleTypeKind::Float16; break; case 4: STK = SimpleTypeKind::Float32; break; case 6: STK = SimpleTypeKind::Float48; break; case 8: STK = SimpleTypeKind::Float64; break; case 10: STK = SimpleTypeKind::Float80; break; case 16: STK = SimpleTypeKind::Float128; break; } break; case dwarf::DW_ATE_signed: switch (ByteSize) { case 1: STK = SimpleTypeKind::SignedCharacter; break; case 2: STK = SimpleTypeKind::Int16Short; break; case 4: STK = SimpleTypeKind::Int32; break; case 8: STK = SimpleTypeKind::Int64Quad; break; case 16: STK = SimpleTypeKind::Int128Oct; break; } break; case dwarf::DW_ATE_unsigned: switch (ByteSize) { case 1: STK = SimpleTypeKind::UnsignedCharacter; break; case 2: STK = SimpleTypeKind::UInt16Short; break; case 4: STK = SimpleTypeKind::UInt32; break; case 8: STK = SimpleTypeKind::UInt64Quad; break; case 16: STK = SimpleTypeKind::UInt128Oct; break; } break; case dwarf::DW_ATE_UTF: switch (ByteSize) { case 2: STK = SimpleTypeKind::Character16; break; case 4: STK = SimpleTypeKind::Character32; break; } break; case dwarf::DW_ATE_signed_char: if (ByteSize == 1) STK = SimpleTypeKind::SignedCharacter; break; case dwarf::DW_ATE_unsigned_char: if (ByteSize == 1) STK = SimpleTypeKind::UnsignedCharacter; break; default: break; } // Apply some fixups based on the source-level type name. if (STK == SimpleTypeKind::Int32 && Ty->getName() == "long int") STK = SimpleTypeKind::Int32Long; if (STK == SimpleTypeKind::UInt32 && Ty->getName() == "long unsigned int") STK = SimpleTypeKind::UInt32Long; if (STK == SimpleTypeKind::UInt16Short && (Ty->getName() == "wchar_t" || Ty->getName() == "__wchar_t")) STK = SimpleTypeKind::WideCharacter; if ((STK == SimpleTypeKind::SignedCharacter || STK == SimpleTypeKind::UnsignedCharacter) && Ty->getName() == "char") STK = SimpleTypeKind::NarrowCharacter; return TypeIndex(STK); } TypeIndex CodeViewDebug::lowerTypePointer(const DIDerivedType *Ty, PointerOptions PO) { TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType()); // Pointers to simple types without any options can use SimpleTypeMode, rather // than having a dedicated pointer type record. if (PointeeTI.isSimple() && PO == PointerOptions::None && PointeeTI.getSimpleMode() == SimpleTypeMode::Direct && Ty->getTag() == dwarf::DW_TAG_pointer_type) { SimpleTypeMode Mode = Ty->getSizeInBits() == 64 ? SimpleTypeMode::NearPointer64 : SimpleTypeMode::NearPointer32; return TypeIndex(PointeeTI.getSimpleKind(), Mode); } PointerKind PK = Ty->getSizeInBits() == 64 ? PointerKind::Near64 : PointerKind::Near32; PointerMode PM = PointerMode::Pointer; switch (Ty->getTag()) { default: llvm_unreachable("not a pointer tag type"); case dwarf::DW_TAG_pointer_type: PM = PointerMode::Pointer; break; case dwarf::DW_TAG_reference_type: PM = PointerMode::LValueReference; break; case dwarf::DW_TAG_rvalue_reference_type: PM = PointerMode::RValueReference; break; } if (Ty->isObjectPointer()) PO |= PointerOptions::Const; PointerRecord PR(PointeeTI, PK, PM, PO, Ty->getSizeInBits() / 8); return TypeTable.writeLeafType(PR); } static PointerToMemberRepresentation translatePtrToMemberRep(unsigned SizeInBytes, bool IsPMF, unsigned Flags) { // SizeInBytes being zero generally implies that the member pointer type was // incomplete, which can happen if it is part of a function prototype. In this // case, use the unknown model instead of the general model. if (IsPMF) { switch (Flags & DINode::FlagPtrToMemberRep) { case 0: return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown : PointerToMemberRepresentation::GeneralFunction; case DINode::FlagSingleInheritance: return PointerToMemberRepresentation::SingleInheritanceFunction; case DINode::FlagMultipleInheritance: return PointerToMemberRepresentation::MultipleInheritanceFunction; case DINode::FlagVirtualInheritance: return PointerToMemberRepresentation::VirtualInheritanceFunction; } } else { switch (Flags & DINode::FlagPtrToMemberRep) { case 0: return SizeInBytes == 0 ? PointerToMemberRepresentation::Unknown : PointerToMemberRepresentation::GeneralData; case DINode::FlagSingleInheritance: return PointerToMemberRepresentation::SingleInheritanceData; case DINode::FlagMultipleInheritance: return PointerToMemberRepresentation::MultipleInheritanceData; case DINode::FlagVirtualInheritance: return PointerToMemberRepresentation::VirtualInheritanceData; } } llvm_unreachable("invalid ptr to member representation"); } TypeIndex CodeViewDebug::lowerTypeMemberPointer(const DIDerivedType *Ty, PointerOptions PO) { assert(Ty->getTag() == dwarf::DW_TAG_ptr_to_member_type); bool IsPMF = isa<DISubroutineType>(Ty->getBaseType()); TypeIndex ClassTI = getTypeIndex(Ty->getClassType()); TypeIndex PointeeTI = getTypeIndex(Ty->getBaseType(), IsPMF ? Ty->getClassType() : nullptr); PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 : PointerKind::Near32; PointerMode PM = IsPMF ? PointerMode::PointerToMemberFunction : PointerMode::PointerToDataMember; assert(Ty->getSizeInBits() / 8 <= 0xff && "pointer size too big"); uint8_t SizeInBytes = Ty->getSizeInBits() / 8; MemberPointerInfo MPI( ClassTI, translatePtrToMemberRep(SizeInBytes, IsPMF, Ty->getFlags())); PointerRecord PR(PointeeTI, PK, PM, PO, SizeInBytes, MPI); return TypeTable.writeLeafType(PR); } /// Given a DWARF calling convention, get the CodeView equivalent. If we don't /// have a translation, use the NearC convention. static CallingConvention dwarfCCToCodeView(unsigned DwarfCC) { switch (DwarfCC) { case dwarf::DW_CC_normal: return CallingConvention::NearC; case dwarf::DW_CC_BORLAND_msfastcall: return CallingConvention::NearFast; case dwarf::DW_CC_BORLAND_thiscall: return CallingConvention::ThisCall; case dwarf::DW_CC_BORLAND_stdcall: return CallingConvention::NearStdCall; case dwarf::DW_CC_BORLAND_pascal: return CallingConvention::NearPascal; case dwarf::DW_CC_LLVM_vectorcall: return CallingConvention::NearVector; } return CallingConvention::NearC; } TypeIndex CodeViewDebug::lowerTypeModifier(const DIDerivedType *Ty) { ModifierOptions Mods = ModifierOptions::None; PointerOptions PO = PointerOptions::None; bool IsModifier = true; const DIType *BaseTy = Ty; while (IsModifier && BaseTy) { // FIXME: Need to add DWARF tags for __unaligned and _Atomic switch (BaseTy->getTag()) { case dwarf::DW_TAG_const_type: Mods |= ModifierOptions::Const; PO |= PointerOptions::Const; break; case dwarf::DW_TAG_volatile_type: Mods |= ModifierOptions::Volatile; PO |= PointerOptions::Volatile; break; case dwarf::DW_TAG_restrict_type: // Only pointer types be marked with __restrict. There is no known flag // for __restrict in LF_MODIFIER records. PO |= PointerOptions::Restrict; break; default: IsModifier = false; break; } if (IsModifier) BaseTy = cast<DIDerivedType>(BaseTy)->getBaseType(); } // Check if the inner type will use an LF_POINTER record. If so, the // qualifiers will go in the LF_POINTER record. This comes up for types like // 'int *const' and 'int *__restrict', not the more common cases like 'const // char *'. if (BaseTy) { switch (BaseTy->getTag()) { case dwarf::DW_TAG_pointer_type: case dwarf::DW_TAG_reference_type: case dwarf::DW_TAG_rvalue_reference_type: return lowerTypePointer(cast<DIDerivedType>(BaseTy), PO); case dwarf::DW_TAG_ptr_to_member_type: return lowerTypeMemberPointer(cast<DIDerivedType>(BaseTy), PO); default: break; } } TypeIndex ModifiedTI = getTypeIndex(BaseTy); // Return the base type index if there aren't any modifiers. For example, the // metadata could contain restrict wrappers around non-pointer types. if (Mods == ModifierOptions::None) return ModifiedTI; ModifierRecord MR(ModifiedTI, Mods); return TypeTable.writeLeafType(MR); } TypeIndex CodeViewDebug::lowerTypeFunction(const DISubroutineType *Ty) { SmallVector<TypeIndex, 8> ReturnAndArgTypeIndices; for (const DIType *ArgType : Ty->getTypeArray()) ReturnAndArgTypeIndices.push_back(getTypeIndex(ArgType)); // MSVC uses type none for variadic argument. if (ReturnAndArgTypeIndices.size() > 1 && ReturnAndArgTypeIndices.back() == TypeIndex::Void()) { ReturnAndArgTypeIndices.back() = TypeIndex::None(); } TypeIndex ReturnTypeIndex = TypeIndex::Void(); ArrayRef<TypeIndex> ArgTypeIndices = None; if (!ReturnAndArgTypeIndices.empty()) { auto ReturnAndArgTypesRef = makeArrayRef(ReturnAndArgTypeIndices); ReturnTypeIndex = ReturnAndArgTypesRef.front(); ArgTypeIndices = ReturnAndArgTypesRef.drop_front(); } ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec); CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); FunctionOptions FO = getFunctionOptions(Ty); ProcedureRecord Procedure(ReturnTypeIndex, CC, FO, ArgTypeIndices.size(), ArgListIndex); return TypeTable.writeLeafType(Procedure); } TypeIndex CodeViewDebug::lowerTypeMemberFunction(const DISubroutineType *Ty, const DIType *ClassTy, int ThisAdjustment, bool IsStaticMethod, FunctionOptions FO) { // Lower the containing class type. TypeIndex ClassType = getTypeIndex(ClassTy); DITypeRefArray ReturnAndArgs = Ty->getTypeArray(); unsigned Index = 0; SmallVector<TypeIndex, 8> ArgTypeIndices; TypeIndex ReturnTypeIndex = TypeIndex::Void(); if (ReturnAndArgs.size() > Index) { ReturnTypeIndex = getTypeIndex(ReturnAndArgs[Index++]); } // If the first argument is a pointer type and this isn't a static method, // treat it as the special 'this' parameter, which is encoded separately from // the arguments. TypeIndex ThisTypeIndex; if (!IsStaticMethod && ReturnAndArgs.size() > Index) { if (const DIDerivedType *PtrTy = dyn_cast_or_null<DIDerivedType>(ReturnAndArgs[Index])) { if (PtrTy->getTag() == dwarf::DW_TAG_pointer_type) { ThisTypeIndex = getTypeIndexForThisPtr(PtrTy, Ty); Index++; } } } while (Index < ReturnAndArgs.size()) ArgTypeIndices.push_back(getTypeIndex(ReturnAndArgs[Index++])); // MSVC uses type none for variadic argument. if (!ArgTypeIndices.empty() && ArgTypeIndices.back() == TypeIndex::Void()) ArgTypeIndices.back() = TypeIndex::None(); ArgListRecord ArgListRec(TypeRecordKind::ArgList, ArgTypeIndices); TypeIndex ArgListIndex = TypeTable.writeLeafType(ArgListRec); CallingConvention CC = dwarfCCToCodeView(Ty->getCC()); MemberFunctionRecord MFR(ReturnTypeIndex, ClassType, ThisTypeIndex, CC, FO, ArgTypeIndices.size(), ArgListIndex, ThisAdjustment); return TypeTable.writeLeafType(MFR); } TypeIndex CodeViewDebug::lowerTypeVFTableShape(const DIDerivedType *Ty) { unsigned VSlotCount = Ty->getSizeInBits() / (8 * Asm->MAI->getCodePointerSize()); SmallVector<VFTableSlotKind, 4> Slots(VSlotCount, VFTableSlotKind::Near); VFTableShapeRecord VFTSR(Slots); return TypeTable.writeLeafType(VFTSR); } static MemberAccess translateAccessFlags(unsigned RecordTag, unsigned Flags) { switch (Flags & DINode::FlagAccessibility) { case DINode::FlagPrivate: return MemberAccess::Private; case DINode::FlagPublic: return MemberAccess::Public; case DINode::FlagProtected: return MemberAccess::Protected; case 0: // If there was no explicit access control, provide the default for the tag. return RecordTag == dwarf::DW_TAG_class_type ? MemberAccess::Private : MemberAccess::Public; } llvm_unreachable("access flags are exclusive"); } static MethodOptions translateMethodOptionFlags(const DISubprogram *SP) { if (SP->isArtificial()) return MethodOptions::CompilerGenerated; // FIXME: Handle other MethodOptions. return MethodOptions::None; } static MethodKind translateMethodKindFlags(const DISubprogram *SP, bool Introduced) { if (SP->getFlags() & DINode::FlagStaticMember) return MethodKind::Static; switch (SP->getVirtuality()) { case dwarf::DW_VIRTUALITY_none: break; case dwarf::DW_VIRTUALITY_virtual: return Introduced ? MethodKind::IntroducingVirtual : MethodKind::Virtual; case dwarf::DW_VIRTUALITY_pure_virtual: return Introduced ? MethodKind::PureIntroducingVirtual : MethodKind::PureVirtual; default: llvm_unreachable("unhandled virtuality case"); } return MethodKind::Vanilla; } static TypeRecordKind getRecordKind(const DICompositeType *Ty) { switch (Ty->getTag()) { case dwarf::DW_TAG_class_type: return TypeRecordKind::Class; case dwarf::DW_TAG_structure_type: return TypeRecordKind::Struct; } llvm_unreachable("unexpected tag"); } /// Return ClassOptions that should be present on both the forward declaration /// and the defintion of a tag type. static ClassOptions getCommonClassOptions(const DICompositeType *Ty) { ClassOptions CO = ClassOptions::None; // MSVC always sets this flag, even for local types. Clang doesn't always // appear to give every type a linkage name, which may be problematic for us. // FIXME: Investigate the consequences of not following them here. if (!Ty->getIdentifier().empty()) CO |= ClassOptions::HasUniqueName; // Put the Nested flag on a type if it appears immediately inside a tag type. // Do not walk the scope chain. Do not attempt to compute ContainsNestedClass // here. That flag is only set on definitions, and not forward declarations. const DIScope *ImmediateScope = Ty->getScope(); if (ImmediateScope && isa<DICompositeType>(ImmediateScope)) CO |= ClassOptions::Nested; // Put the Scoped flag on function-local types. MSVC puts this flag for enum // type only when it has an immediate function scope. Clang never puts enums // inside DILexicalBlock scopes. Enum types, as generated by clang, are // always in function, class, or file scopes. if (Ty->getTag() == dwarf::DW_TAG_enumeration_type) { if (ImmediateScope && isa<DISubprogram>(ImmediateScope)) CO |= ClassOptions::Scoped; } else { for (const DIScope *Scope = ImmediateScope; Scope != nullptr; Scope = Scope->getScope()) { if (isa<DISubprogram>(Scope)) { CO |= ClassOptions::Scoped; break; } } } return CO; } void CodeViewDebug::addUDTSrcLine(const DIType *Ty, TypeIndex TI) { switch (Ty->getTag()) { case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_union_type: case dwarf::DW_TAG_enumeration_type: break; default: return; } if (const auto *File = Ty->getFile()) { StringIdRecord SIDR(TypeIndex(0x0), getFullFilepath(File)); TypeIndex SIDI = TypeTable.writeLeafType(SIDR); UdtSourceLineRecord USLR(TI, SIDI, Ty->getLine()); TypeTable.writeLeafType(USLR); } } TypeIndex CodeViewDebug::lowerTypeEnum(const DICompositeType *Ty) { ClassOptions CO = getCommonClassOptions(Ty); TypeIndex FTI; unsigned EnumeratorCount = 0; if (Ty->isForwardDecl()) { CO |= ClassOptions::ForwardReference; } else { ContinuationRecordBuilder ContinuationBuilder; ContinuationBuilder.begin(ContinuationRecordKind::FieldList); for (const DINode *Element : Ty->getElements()) { // We assume that the frontend provides all members in source declaration // order, which is what MSVC does. if (auto *Enumerator = dyn_cast_or_null<DIEnumerator>(Element)) { EnumeratorRecord ER(MemberAccess::Public, APSInt(Enumerator->getValue(), true), Enumerator->getName()); ContinuationBuilder.writeMemberType(ER); EnumeratorCount++; } } FTI = TypeTable.insertRecord(ContinuationBuilder); } std::string FullName = getFullyQualifiedName(Ty); EnumRecord ER(EnumeratorCount, CO, FTI, FullName, Ty->getIdentifier(), getTypeIndex(Ty->getBaseType())); TypeIndex EnumTI = TypeTable.writeLeafType(ER); addUDTSrcLine(Ty, EnumTI); return EnumTI; } //===----------------------------------------------------------------------===// // ClassInfo //===----------------------------------------------------------------------===// struct llvm::ClassInfo { struct MemberInfo { const DIDerivedType *MemberTypeNode; uint64_t BaseOffset; }; // [MemberInfo] using MemberList = std::vector<MemberInfo>; using MethodsList = TinyPtrVector<const DISubprogram *>; // MethodName -> MethodsList using MethodsMap = MapVector<MDString *, MethodsList>; /// Base classes. std::vector<const DIDerivedType *> Inheritance; /// Direct members. MemberList Members; // Direct overloaded methods gathered by name. MethodsMap Methods; TypeIndex VShapeTI; std::vector<const DIType *> NestedTypes; }; void CodeViewDebug::clear() { assert(CurFn == nullptr); FileIdMap.clear(); FnDebugInfo.clear(); FileToFilepathMap.clear(); LocalUDTs.clear(); GlobalUDTs.clear(); TypeIndices.clear(); CompleteTypeIndices.clear(); ScopeGlobals.clear(); } void CodeViewDebug::collectMemberInfo(ClassInfo &Info, const DIDerivedType *DDTy) { if (!DDTy->getName().empty()) { Info.Members.push_back({DDTy, 0}); return; } // An unnamed member may represent a nested struct or union. Attempt to // interpret the unnamed member as a DICompositeType possibly wrapped in // qualifier types. Add all the indirect fields to the current record if that // succeeds, and drop the member if that fails. assert((DDTy->getOffsetInBits() % 8) == 0 && "Unnamed bitfield member!"); uint64_t Offset = DDTy->getOffsetInBits(); const DIType *Ty = DDTy->getBaseType(); bool FullyResolved = false; while (!FullyResolved) { switch (Ty->getTag()) { case dwarf::DW_TAG_const_type: case dwarf::DW_TAG_volatile_type: // FIXME: we should apply the qualifier types to the indirect fields // rather than dropping them. Ty = cast<DIDerivedType>(Ty)->getBaseType(); break; default: FullyResolved = true; break; } } const DICompositeType *DCTy = dyn_cast<DICompositeType>(Ty); if (!DCTy) return; ClassInfo NestedInfo = collectClassInfo(DCTy); for (const ClassInfo::MemberInfo &IndirectField : NestedInfo.Members) Info.Members.push_back( {IndirectField.MemberTypeNode, IndirectField.BaseOffset + Offset}); } ClassInfo CodeViewDebug::collectClassInfo(const DICompositeType *Ty) { ClassInfo Info; // Add elements to structure type. DINodeArray Elements = Ty->getElements(); for (auto *Element : Elements) { // We assume that the frontend provides all members in source declaration // order, which is what MSVC does. if (!Element) continue; if (auto *SP = dyn_cast<DISubprogram>(Element)) { Info.Methods[SP->getRawName()].push_back(SP); } else if (auto *DDTy = dyn_cast<DIDerivedType>(Element)) { if (DDTy->getTag() == dwarf::DW_TAG_member) { collectMemberInfo(Info, DDTy); } else if (DDTy->getTag() == dwarf::DW_TAG_inheritance) { Info.Inheritance.push_back(DDTy); } else if (DDTy->getTag() == dwarf::DW_TAG_pointer_type && DDTy->getName() == "__vtbl_ptr_type") { Info.VShapeTI = getTypeIndex(DDTy); } else if (DDTy->getTag() == dwarf::DW_TAG_typedef) { Info.NestedTypes.push_back(DDTy); } else if (DDTy->getTag() == dwarf::DW_TAG_friend) { // Ignore friend members. It appears that MSVC emitted info about // friends in the past, but modern versions do not. } } else if (auto *Composite = dyn_cast<DICompositeType>(Element)) { Info.NestedTypes.push_back(Composite); } // Skip other unrecognized kinds of elements. } return Info; } static bool shouldAlwaysEmitCompleteClassType(const DICompositeType *Ty) { // This routine is used by lowerTypeClass and lowerTypeUnion to determine // if a complete type should be emitted instead of a forward reference. return Ty->getName().empty() && Ty->getIdentifier().empty() && !Ty->isForwardDecl(); } TypeIndex CodeViewDebug::lowerTypeClass(const DICompositeType *Ty) { // Emit the complete type for unnamed structs. C++ classes with methods // which have a circular reference back to the class type are expected to // be named by the front-end and should not be "unnamed". C unnamed // structs should not have circular references. if (shouldAlwaysEmitCompleteClassType(Ty)) { // If this unnamed complete type is already in the process of being defined // then the description of the type is malformed and cannot be emitted // into CodeView correctly so report a fatal error. auto I = CompleteTypeIndices.find(Ty); if (I != CompleteTypeIndices.end() && I->second == TypeIndex()) report_fatal_error("cannot debug circular reference to unnamed type"); return getCompleteTypeIndex(Ty); } // First, construct the forward decl. Don't look into Ty to compute the // forward decl options, since it might not be available in all TUs. TypeRecordKind Kind = getRecordKind(Ty); ClassOptions CO = ClassOptions::ForwardReference | getCommonClassOptions(Ty); std::string FullName = getFullyQualifiedName(Ty); ClassRecord CR(Kind, 0, CO, TypeIndex(), TypeIndex(), TypeIndex(), 0, FullName, Ty->getIdentifier()); TypeIndex FwdDeclTI = TypeTable.writeLeafType(CR); if (!Ty->isForwardDecl()) DeferredCompleteTypes.push_back(Ty); return FwdDeclTI; } TypeIndex CodeViewDebug::lowerCompleteTypeClass(const DICompositeType *Ty) { // Construct the field list and complete type record. TypeRecordKind Kind = getRecordKind(Ty); ClassOptions CO = getCommonClassOptions(Ty); TypeIndex FieldTI; TypeIndex VShapeTI; unsigned FieldCount; bool ContainsNestedClass; std::tie(FieldTI, VShapeTI, FieldCount, ContainsNestedClass) = lowerRecordFieldList(Ty); if (ContainsNestedClass) CO |= ClassOptions::ContainsNestedClass; // MSVC appears to set this flag by searching any destructor or method with // FunctionOptions::Constructor among the emitted members. Clang AST has all // the members, however special member functions are not yet emitted into // debug information. For now checking a class's non-triviality seems enough. // FIXME: not true for a nested unnamed struct. if (isNonTrivial(Ty)) CO |= ClassOptions::HasConstructorOrDestructor; std::string FullName = getFullyQualifiedName(Ty); uint64_t SizeInBytes = Ty->getSizeInBits() / 8; ClassRecord CR(Kind, FieldCount, CO, FieldTI, TypeIndex(), VShapeTI, SizeInBytes, FullName, Ty->getIdentifier()); TypeIndex ClassTI = TypeTable.writeLeafType(CR); addUDTSrcLine(Ty, ClassTI); addToUDTs(Ty); return ClassTI; } TypeIndex CodeViewDebug::lowerTypeUnion(const DICompositeType *Ty) { // Emit the complete type for unnamed unions. if (shouldAlwaysEmitCompleteClassType(Ty)) return getCompleteTypeIndex(Ty); ClassOptions CO = ClassOptions::ForwardReference | getCommonClassOptions(Ty); std::string FullName = getFullyQualifiedName(Ty); UnionRecord UR(0, CO, TypeIndex(), 0, FullName, Ty->getIdentifier()); TypeIndex FwdDeclTI = TypeTable.writeLeafType(UR); if (!Ty->isForwardDecl()) DeferredCompleteTypes.push_back(Ty); return FwdDeclTI; } TypeIndex CodeViewDebug::lowerCompleteTypeUnion(const DICompositeType *Ty) { ClassOptions CO = ClassOptions::Sealed | getCommonClassOptions(Ty); TypeIndex FieldTI; unsigned FieldCount; bool ContainsNestedClass; std::tie(FieldTI, std::ignore, FieldCount, ContainsNestedClass) = lowerRecordFieldList(Ty); if (ContainsNestedClass) CO |= ClassOptions::ContainsNestedClass; uint64_t SizeInBytes = Ty->getSizeInBits() / 8; std::string FullName = getFullyQualifiedName(Ty); UnionRecord UR(FieldCount, CO, FieldTI, SizeInBytes, FullName, Ty->getIdentifier()); TypeIndex UnionTI = TypeTable.writeLeafType(UR); addUDTSrcLine(Ty, UnionTI); addToUDTs(Ty); return UnionTI; } std::tuple<TypeIndex, TypeIndex, unsigned, bool> CodeViewDebug::lowerRecordFieldList(const DICompositeType *Ty) { // Manually count members. MSVC appears to count everything that generates a // field list record. Each individual overload in a method overload group // contributes to this count, even though the overload group is a single field // list record. unsigned MemberCount = 0; ClassInfo Info = collectClassInfo(Ty); ContinuationRecordBuilder ContinuationBuilder; ContinuationBuilder.begin(ContinuationRecordKind::FieldList); // Create base classes. for (const DIDerivedType *I : Info.Inheritance) { if (I->getFlags() & DINode::FlagVirtual) { // Virtual base. unsigned VBPtrOffset = I->getVBPtrOffset(); // FIXME: Despite the accessor name, the offset is really in bytes. unsigned VBTableIndex = I->getOffsetInBits() / 4; auto RecordKind = (I->getFlags() & DINode::FlagIndirectVirtualBase) == DINode::FlagIndirectVirtualBase ? TypeRecordKind::IndirectVirtualBaseClass : TypeRecordKind::VirtualBaseClass; VirtualBaseClassRecord VBCR( RecordKind, translateAccessFlags(Ty->getTag(), I->getFlags()), getTypeIndex(I->getBaseType()), getVBPTypeIndex(), VBPtrOffset, VBTableIndex); ContinuationBuilder.writeMemberType(VBCR); MemberCount++; } else { assert(I->getOffsetInBits() % 8 == 0 && "bases must be on byte boundaries"); BaseClassRecord BCR(translateAccessFlags(Ty->getTag(), I->getFlags()), getTypeIndex(I->getBaseType()), I->getOffsetInBits() / 8); ContinuationBuilder.writeMemberType(BCR); MemberCount++; } } // Create members. for (ClassInfo::MemberInfo &MemberInfo : Info.Members) { const DIDerivedType *Member = MemberInfo.MemberTypeNode; TypeIndex MemberBaseType = getTypeIndex(Member->getBaseType()); StringRef MemberName = Member->getName(); MemberAccess Access = translateAccessFlags(Ty->getTag(), Member->getFlags()); if (Member->isStaticMember()) { StaticDataMemberRecord SDMR(Access, MemberBaseType, MemberName); ContinuationBuilder.writeMemberType(SDMR); MemberCount++; continue; } // Virtual function pointer member. if ((Member->getFlags() & DINode::FlagArtificial) && Member->getName().startswith("_vptr$")) { VFPtrRecord VFPR(getTypeIndex(Member->getBaseType())); ContinuationBuilder.writeMemberType(VFPR); MemberCount++; continue; } // Data member. uint64_t MemberOffsetInBits = Member->getOffsetInBits() + MemberInfo.BaseOffset; if (Member->isBitField()) { uint64_t StartBitOffset = MemberOffsetInBits; if (const auto *CI = dyn_cast_or_null<ConstantInt>(Member->getStorageOffsetInBits())) { MemberOffsetInBits = CI->getZExtValue() + MemberInfo.BaseOffset; } StartBitOffset -= MemberOffsetInBits; BitFieldRecord BFR(MemberBaseType, Member->getSizeInBits(), StartBitOffset); MemberBaseType = TypeTable.writeLeafType(BFR); } uint64_t MemberOffsetInBytes = MemberOffsetInBits / 8; DataMemberRecord DMR(Access, MemberBaseType, MemberOffsetInBytes, MemberName); ContinuationBuilder.writeMemberType(DMR); MemberCount++; } // Create methods for (auto &MethodItr : Info.Methods) { StringRef Name = MethodItr.first->getString(); std::vector<OneMethodRecord> Methods; for (const DISubprogram *SP : MethodItr.second) { TypeIndex MethodType = getMemberFunctionType(SP, Ty); bool Introduced = SP->getFlags() & DINode::FlagIntroducedVirtual; unsigned VFTableOffset = -1; if (Introduced) VFTableOffset = SP->getVirtualIndex() * getPointerSizeInBytes(); Methods.push_back(OneMethodRecord( MethodType, translateAccessFlags(Ty->getTag(), SP->getFlags()), translateMethodKindFlags(SP, Introduced), translateMethodOptionFlags(SP), VFTableOffset, Name)); MemberCount++; } assert(!Methods.empty() && "Empty methods map entry"); if (Methods.size() == 1) ContinuationBuilder.writeMemberType(Methods[0]); else { // FIXME: Make this use its own ContinuationBuilder so that // MethodOverloadList can be split correctly. MethodOverloadListRecord MOLR(Methods); TypeIndex MethodList = TypeTable.writeLeafType(MOLR); OverloadedMethodRecord OMR(Methods.size(), MethodList, Name); ContinuationBuilder.writeMemberType(OMR); } } // Create nested classes. for (const DIType *Nested : Info.NestedTypes) { NestedTypeRecord R(getTypeIndex(Nested), Nested->getName()); ContinuationBuilder.writeMemberType(R); MemberCount++; } TypeIndex FieldTI = TypeTable.insertRecord(ContinuationBuilder); return std::make_tuple(FieldTI, Info.VShapeTI, MemberCount, !Info.NestedTypes.empty()); } TypeIndex CodeViewDebug::getVBPTypeIndex() { if (!VBPType.getIndex()) { // Make a 'const int *' type. ModifierRecord MR(TypeIndex::Int32(), ModifierOptions::Const); TypeIndex ModifiedTI = TypeTable.writeLeafType(MR); PointerKind PK = getPointerSizeInBytes() == 8 ? PointerKind::Near64 : PointerKind::Near32; PointerMode PM = PointerMode::Pointer; PointerOptions PO = PointerOptions::None; PointerRecord PR(ModifiedTI, PK, PM, PO, getPointerSizeInBytes()); VBPType = TypeTable.writeLeafType(PR); } return VBPType; } TypeIndex CodeViewDebug::getTypeIndex(const DIType *Ty, const DIType *ClassTy) { // The null DIType is the void type. Don't try to hash it. if (!Ty) return TypeIndex::Void(); // Check if we've already translated this type. Don't try to do a // get-or-create style insertion that caches the hash lookup across the // lowerType call. It will update the TypeIndices map. auto I = TypeIndices.find({Ty, ClassTy}); if (I != TypeIndices.end()) return I->second; TypeLoweringScope S(*this); TypeIndex TI = lowerType(Ty, ClassTy); return recordTypeIndexForDINode(Ty, TI, ClassTy); } codeview::TypeIndex CodeViewDebug::getTypeIndexForThisPtr(const DIDerivedType *PtrTy, const DISubroutineType *SubroutineTy) { assert(PtrTy->getTag() == dwarf::DW_TAG_pointer_type && "this type must be a pointer type"); PointerOptions Options = PointerOptions::None; if (SubroutineTy->getFlags() & DINode::DIFlags::FlagLValueReference) Options = PointerOptions::LValueRefThisPointer; else if (SubroutineTy->getFlags() & DINode::DIFlags::FlagRValueReference) Options = PointerOptions::RValueRefThisPointer; // Check if we've already translated this type. If there is no ref qualifier // on the function then we look up this pointer type with no associated class // so that the TypeIndex for the this pointer can be shared with the type // index for other pointers to this class type. If there is a ref qualifier // then we lookup the pointer using the subroutine as the parent type. auto I = TypeIndices.find({PtrTy, SubroutineTy}); if (I != TypeIndices.end()) return I->second; TypeLoweringScope S(*this); TypeIndex TI = lowerTypePointer(PtrTy, Options); return recordTypeIndexForDINode(PtrTy, TI, SubroutineTy); } TypeIndex CodeViewDebug::getTypeIndexForReferenceTo(const DIType *Ty) { PointerRecord PR(getTypeIndex(Ty), getPointerSizeInBytes() == 8 ? PointerKind::Near64 : PointerKind::Near32, PointerMode::LValueReference, PointerOptions::None, Ty->getSizeInBits() / 8); return TypeTable.writeLeafType(PR); } TypeIndex CodeViewDebug::getCompleteTypeIndex(const DIType *Ty) { // The null DIType is the void type. Don't try to hash it. if (!Ty) return TypeIndex::Void(); // Look through typedefs when getting the complete type index. Call // getTypeIndex on the typdef to ensure that any UDTs are accumulated and are // emitted only once. if (Ty->getTag() == dwarf::DW_TAG_typedef) (void)getTypeIndex(Ty); while (Ty->getTag() == dwarf::DW_TAG_typedef) Ty = cast<DIDerivedType>(Ty)->getBaseType(); // If this is a non-record type, the complete type index is the same as the // normal type index. Just call getTypeIndex. switch (Ty->getTag()) { case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_structure_type: case dwarf::DW_TAG_union_type: break; default: return getTypeIndex(Ty); } const auto *CTy = cast<DICompositeType>(Ty); TypeLoweringScope S(*this); // Make sure the forward declaration is emitted first. It's unclear if this // is necessary, but MSVC does it, and we should follow suit until we can show // otherwise. // We only emit a forward declaration for named types. if (!CTy->getName().empty() || !CTy->getIdentifier().empty()) { TypeIndex FwdDeclTI = getTypeIndex(CTy); // Just use the forward decl if we don't have complete type info. This // might happen if the frontend is using modules and expects the complete // definition to be emitted elsewhere. if (CTy->isForwardDecl()) return FwdDeclTI; } // Check if we've already translated the complete record type. // Insert the type with a null TypeIndex to signify that the type is currently // being lowered. auto InsertResult = CompleteTypeIndices.insert({CTy, TypeIndex()}); if (!InsertResult.second) return InsertResult.first->second; TypeIndex TI; switch (CTy->getTag()) { case dwarf::DW_TAG_class_type: case dwarf::DW_TAG_structure_type: TI = lowerCompleteTypeClass(CTy); break; case dwarf::DW_TAG_union_type: TI = lowerCompleteTypeUnion(CTy); break; default: llvm_unreachable("not a record"); } // Update the type index associated with this CompositeType. This cannot // use the 'InsertResult' iterator above because it is potentially // invalidated by map insertions which can occur while lowering the class // type above. CompleteTypeIndices[CTy] = TI; return TI; } /// Emit all the deferred complete record types. Try to do this in FIFO order, /// and do this until fixpoint, as each complete record type typically /// references /// many other record types. void CodeViewDebug::emitDeferredCompleteTypes() { SmallVector<const DICompositeType *, 4> TypesToEmit; while (!DeferredCompleteTypes.empty()) { std::swap(DeferredCompleteTypes, TypesToEmit); for (const DICompositeType *RecordTy : TypesToEmit) getCompleteTypeIndex(RecordTy); TypesToEmit.clear(); } } void CodeViewDebug::emitLocalVariableList(const FunctionInfo &FI, ArrayRef<LocalVariable> Locals) { // Get the sorted list of parameters and emit them first. SmallVector<const LocalVariable *, 6> Params; for (const LocalVariable &L : Locals) if (L.DIVar->isParameter()) Params.push_back(&L); llvm::sort(Params, [](const LocalVariable *L, const LocalVariable *R) { return L->DIVar->getArg() < R->DIVar->getArg(); }); for (const LocalVariable *L : Params) emitLocalVariable(FI, *L); // Next emit all non-parameters in the order that we found them. for (const LocalVariable &L : Locals) if (!L.DIVar->isParameter()) emitLocalVariable(FI, L); } void CodeViewDebug::emitLocalVariable(const FunctionInfo &FI, const LocalVariable &Var) { // LocalSym record, see SymbolRecord.h for more info. MCSymbol *LocalEnd = beginSymbolRecord(SymbolKind::S_LOCAL); LocalSymFlags Flags = LocalSymFlags::None; if (Var.DIVar->isParameter()) Flags |= LocalSymFlags::IsParameter; if (Var.DefRanges.empty()) Flags |= LocalSymFlags::IsOptimizedOut; OS.AddComment("TypeIndex"); TypeIndex TI = Var.UseReferenceType ? getTypeIndexForReferenceTo(Var.DIVar->getType()) : getCompleteTypeIndex(Var.DIVar->getType()); OS.emitInt32(TI.getIndex()); OS.AddComment("Flags"); OS.emitInt16(static_cast<uint16_t>(Flags)); // Truncate the name so we won't overflow the record length field. emitNullTerminatedSymbolName(OS, Var.DIVar->getName()); endSymbolRecord(LocalEnd); // Calculate the on disk prefix of the appropriate def range record. The // records and on disk formats are described in SymbolRecords.h. BytePrefix // should be big enough to hold all forms without memory allocation. SmallString<20> BytePrefix; for (const LocalVarDefRange &DefRange : Var.DefRanges) { BytePrefix.clear(); if (DefRange.InMemory) { int Offset = DefRange.DataOffset; unsigned Reg = DefRange.CVRegister; // 32-bit x86 call sequences often use PUSH instructions, which disrupt // ESP-relative offsets. Use the virtual frame pointer, VFRAME or $T0, // instead. In frames without stack realignment, $T0 will be the CFA. if (RegisterId(Reg) == RegisterId::ESP) { Reg = unsigned(RegisterId::VFRAME); Offset += FI.OffsetAdjustment; } // If we can use the chosen frame pointer for the frame and this isn't a // sliced aggregate, use the smaller S_DEFRANGE_FRAMEPOINTER_REL record. // Otherwise, use S_DEFRANGE_REGISTER_REL. EncodedFramePtrReg EncFP = encodeFramePtrReg(RegisterId(Reg), TheCPU); if (!DefRange.IsSubfield && EncFP != EncodedFramePtrReg::None && (bool(Flags & LocalSymFlags::IsParameter) ? (EncFP == FI.EncodedParamFramePtrReg) : (EncFP == FI.EncodedLocalFramePtrReg))) { DefRangeFramePointerRelHeader DRHdr; DRHdr.Offset = Offset; OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr); } else { uint16_t RegRelFlags = 0; if (DefRange.IsSubfield) { RegRelFlags = DefRangeRegisterRelSym::IsSubfieldFlag | (DefRange.StructOffset << DefRangeRegisterRelSym::OffsetInParentShift); } DefRangeRegisterRelHeader DRHdr; DRHdr.Register = Reg; DRHdr.Flags = RegRelFlags; DRHdr.BasePointerOffset = Offset; OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr); } } else { assert(DefRange.DataOffset == 0 && "unexpected offset into register"); if (DefRange.IsSubfield) { DefRangeSubfieldRegisterHeader DRHdr; DRHdr.Register = DefRange.CVRegister; DRHdr.MayHaveNoName = 0; DRHdr.OffsetInParent = DefRange.StructOffset; OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr); } else { DefRangeRegisterHeader DRHdr; DRHdr.Register = DefRange.CVRegister; DRHdr.MayHaveNoName = 0; OS.emitCVDefRangeDirective(DefRange.Ranges, DRHdr); } } } } void CodeViewDebug::emitLexicalBlockList(ArrayRef<LexicalBlock *> Blocks, const FunctionInfo& FI) { for (LexicalBlock *Block : Blocks) emitLexicalBlock(*Block, FI); } /// Emit an S_BLOCK32 and S_END record pair delimiting the contents of a /// lexical block scope. void CodeViewDebug::emitLexicalBlock(const LexicalBlock &Block, const FunctionInfo& FI) { MCSymbol *RecordEnd = beginSymbolRecord(SymbolKind::S_BLOCK32); OS.AddComment("PtrParent"); OS.emitInt32(0); // PtrParent OS.AddComment("PtrEnd"); OS.emitInt32(0); // PtrEnd OS.AddComment("Code size"); OS.emitAbsoluteSymbolDiff(Block.End, Block.Begin, 4); // Code Size OS.AddComment("Function section relative address"); OS.EmitCOFFSecRel32(Block.Begin, /*Offset=*/0); // Func Offset OS.AddComment("Function section index"); OS.EmitCOFFSectionIndex(FI.Begin); // Func Symbol OS.AddComment("Lexical block name"); emitNullTerminatedSymbolName(OS, Block.Name); // Name endSymbolRecord(RecordEnd); // Emit variables local to this lexical block. emitLocalVariableList(FI, Block.Locals); emitGlobalVariableList(Block.Globals); // Emit lexical blocks contained within this block. emitLexicalBlockList(Block.Children, FI); // Close the lexical block scope. emitEndSymbolRecord(SymbolKind::S_END); } /// Convenience routine for collecting lexical block information for a list /// of lexical scopes. void CodeViewDebug::collectLexicalBlockInfo( SmallVectorImpl<LexicalScope *> &Scopes, SmallVectorImpl<LexicalBlock *> &Blocks, SmallVectorImpl<LocalVariable> &Locals, SmallVectorImpl<CVGlobalVariable> &Globals) { for (LexicalScope *Scope : Scopes) collectLexicalBlockInfo(*Scope, Blocks, Locals, Globals); } /// Populate the lexical blocks and local variable lists of the parent with /// information about the specified lexical scope. void CodeViewDebug::collectLexicalBlockInfo( LexicalScope &Scope, SmallVectorImpl<LexicalBlock *> &ParentBlocks, SmallVectorImpl<LocalVariable> &ParentLocals, SmallVectorImpl<CVGlobalVariable> &ParentGlobals) { if (Scope.isAbstractScope()) return; // Gather information about the lexical scope including local variables, // global variables, and address ranges. bool IgnoreScope = false; auto LI = ScopeVariables.find(&Scope); SmallVectorImpl<LocalVariable> *Locals = LI != ScopeVariables.end() ? &LI->second : nullptr; auto GI = ScopeGlobals.find(Scope.getScopeNode()); SmallVectorImpl<CVGlobalVariable> *Globals = GI != ScopeGlobals.end() ? GI->second.get() : nullptr; const DILexicalBlock *DILB = dyn_cast<DILexicalBlock>(Scope.getScopeNode()); const SmallVectorImpl<InsnRange> &Ranges = Scope.getRanges(); // Ignore lexical scopes which do not contain variables. if (!Locals && !Globals) IgnoreScope = true; // Ignore lexical scopes which are not lexical blocks. if (!DILB) IgnoreScope = true; // Ignore scopes which have too many address ranges to represent in the // current CodeView format or do not have a valid address range. // // For lexical scopes with multiple address ranges you may be tempted to // construct a single range covering every instruction where the block is // live and everything in between. Unfortunately, Visual Studio only // displays variables from the first matching lexical block scope. If the // first lexical block contains exception handling code or cold code which // is moved to the bottom of the routine creating a single range covering // nearly the entire routine, then it will hide all other lexical blocks // and the variables they contain. if (Ranges.size() != 1 || !getLabelAfterInsn(Ranges.front().second)) IgnoreScope = true; if (IgnoreScope) { // This scope can be safely ignored and eliminating it will reduce the // size of the debug information. Be sure to collect any variable and scope // information from the this scope or any of its children and collapse them // into the parent scope. if (Locals) ParentLocals.append(Locals->begin(), Locals->end()); if (Globals) ParentGlobals.append(Globals->begin(), Globals->end()); collectLexicalBlockInfo(Scope.getChildren(), ParentBlocks, ParentLocals, ParentGlobals); return; } // Create a new CodeView lexical block for this lexical scope. If we've // seen this DILexicalBlock before then the scope tree is malformed and // we can handle this gracefully by not processing it a second time. auto BlockInsertion = CurFn->LexicalBlocks.insert({DILB, LexicalBlock()}); if (!BlockInsertion.second) return; // Create a lexical block containing the variables and collect the the // lexical block information for the children. const InsnRange &Range = Ranges.front(); assert(Range.first && Range.second); LexicalBlock &Block = BlockInsertion.first->second; Block.Begin = getLabelBeforeInsn(Range.first); Block.End = getLabelAfterInsn(Range.second); assert(Block.Begin && "missing label for scope begin"); assert(Block.End && "missing label for scope end"); Block.Name = DILB->getName(); if (Locals) Block.Locals = std::move(*Locals); if (Globals) Block.Globals = std::move(*Globals); ParentBlocks.push_back(&Block); collectLexicalBlockInfo(Scope.getChildren(), Block.Children, Block.Locals, Block.Globals); } void CodeViewDebug::endFunctionImpl(const MachineFunction *MF) { const Function &GV = MF->getFunction(); assert(FnDebugInfo.count(&GV)); assert(CurFn == FnDebugInfo[&GV].get()); collectVariableInfo(GV.getSubprogram()); // Build the lexical block structure to emit for this routine. if (LexicalScope *CFS = LScopes.getCurrentFunctionScope()) collectLexicalBlockInfo(*CFS, CurFn->ChildBlocks, CurFn->Locals, CurFn->Globals); // Clear the scope and variable information from the map which will not be // valid after we have finished processing this routine. This also prepares // the map for the subsequent routine. ScopeVariables.clear(); // Don't emit anything if we don't have any line tables. // Thunks are compiler-generated and probably won't have source correlation. if (!CurFn->HaveLineInfo && !GV.getSubprogram()->isThunk()) { FnDebugInfo.erase(&GV); CurFn = nullptr; return; } // Find heap alloc sites and add to list. for (const auto &MBB : *MF) { for (const auto &MI : MBB) { if (MDNode *MD = MI.getHeapAllocMarker()) { CurFn->HeapAllocSites.push_back(std::make_tuple(getLabelBeforeInsn(&MI), getLabelAfterInsn(&MI), dyn_cast<DIType>(MD))); } } } CurFn->Annotations = MF->getCodeViewAnnotations(); CurFn->End = Asm->getFunctionEnd(); CurFn = nullptr; } // Usable locations are valid with non-zero line numbers. A line number of zero // corresponds to optimized code that doesn't have a distinct source location. // In this case, we try to use the previous or next source location depending on // the context. static bool isUsableDebugLoc(DebugLoc DL) { return DL && DL.getLine() != 0; } void CodeViewDebug::beginInstruction(const MachineInstr *MI) { DebugHandlerBase::beginInstruction(MI); // Ignore DBG_VALUE and DBG_LABEL locations and function prologue. if (!Asm || !CurFn || MI->isDebugInstr() || MI->getFlag(MachineInstr::FrameSetup)) return; // If the first instruction of a new MBB has no location, find the first // instruction with a location and use that. DebugLoc DL = MI->getDebugLoc(); if (!isUsableDebugLoc(DL) && MI->getParent() != PrevInstBB) { for (const auto &NextMI : *MI->getParent()) { if (NextMI.isDebugInstr()) continue; DL = NextMI.getDebugLoc(); if (isUsableDebugLoc(DL)) break; } // FIXME: Handle the case where the BB has no valid locations. This would // probably require doing a real dataflow analysis. } PrevInstBB = MI->getParent(); // If we still don't have a debug location, don't record a location. if (!isUsableDebugLoc(DL)) return; maybeRecordLocation(DL, Asm->MF); } MCSymbol *CodeViewDebug::beginCVSubsection(DebugSubsectionKind Kind) { MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), *EndLabel = MMI->getContext().createTempSymbol(); OS.emitInt32(unsigned(Kind)); OS.AddComment("Subsection size"); OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 4); OS.emitLabel(BeginLabel); return EndLabel; } void CodeViewDebug::endCVSubsection(MCSymbol *EndLabel) { OS.emitLabel(EndLabel); // Every subsection must be aligned to a 4-byte boundary. OS.emitValueToAlignment(4); } static StringRef getSymbolName(SymbolKind SymKind) { for (const EnumEntry<SymbolKind> &EE : getSymbolTypeNames()) if (EE.Value == SymKind) return EE.Name; return ""; } MCSymbol *CodeViewDebug::beginSymbolRecord(SymbolKind SymKind) { MCSymbol *BeginLabel = MMI->getContext().createTempSymbol(), *EndLabel = MMI->getContext().createTempSymbol(); OS.AddComment("Record length"); OS.emitAbsoluteSymbolDiff(EndLabel, BeginLabel, 2); OS.emitLabel(BeginLabel); if (OS.isVerboseAsm()) OS.AddComment("Record kind: " + getSymbolName(SymKind)); OS.emitInt16(unsigned(SymKind)); return EndLabel; } void CodeViewDebug::endSymbolRecord(MCSymbol *SymEnd) { // MSVC does not pad out symbol records to four bytes, but LLVM does to avoid // an extra copy of every symbol record in LLD. This increases object file // size by less than 1% in the clang build, and is compatible with the Visual // C++ linker. OS.emitValueToAlignment(4); OS.emitLabel(SymEnd); } void CodeViewDebug::emitEndSymbolRecord(SymbolKind EndKind) { OS.AddComment("Record length"); OS.emitInt16(2); if (OS.isVerboseAsm()) OS.AddComment("Record kind: " + getSymbolName(EndKind)); OS.emitInt16(uint16_t(EndKind)); // Record Kind } void CodeViewDebug::emitDebugInfoForUDTs( const std::vector<std::pair<std::string, const DIType *>> &UDTs) { #ifndef NDEBUG size_t OriginalSize = UDTs.size(); #endif for (const auto &UDT : UDTs) { const DIType *T = UDT.second; assert(shouldEmitUdt(T)); MCSymbol *UDTRecordEnd = beginSymbolRecord(SymbolKind::S_UDT); OS.AddComment("Type"); OS.emitInt32(getCompleteTypeIndex(T).getIndex()); assert(OriginalSize == UDTs.size() && "getCompleteTypeIndex found new UDTs!"); emitNullTerminatedSymbolName(OS, UDT.first); endSymbolRecord(UDTRecordEnd); } } void CodeViewDebug::collectGlobalVariableInfo() { DenseMap<const DIGlobalVariableExpression *, const GlobalVariable *> GlobalMap; for (const GlobalVariable &GV : MMI->getModule()->globals()) { SmallVector<DIGlobalVariableExpression *, 1> GVEs; GV.getDebugInfo(GVEs); for (const auto *GVE : GVEs) GlobalMap[GVE] = &GV; } NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); for (const MDNode *Node : CUs->operands()) { const auto *CU = cast<DICompileUnit>(Node); for (const auto *GVE : CU->getGlobalVariables()) { const DIGlobalVariable *DIGV = GVE->getVariable(); const DIExpression *DIE = GVE->getExpression(); // Emit constant global variables in a global symbol section. if (GlobalMap.count(GVE) == 0 && DIE->isConstant()) { CVGlobalVariable CVGV = {DIGV, DIE}; GlobalVariables.emplace_back(std::move(CVGV)); } const auto *GV = GlobalMap.lookup(GVE); if (!GV || GV->isDeclarationForLinker()) continue; DIScope *Scope = DIGV->getScope(); SmallVector<CVGlobalVariable, 1> *VariableList; if (Scope && isa<DILocalScope>(Scope)) { // Locate a global variable list for this scope, creating one if // necessary. auto Insertion = ScopeGlobals.insert( {Scope, std::unique_ptr<GlobalVariableList>()}); if (Insertion.second) Insertion.first->second = std::make_unique<GlobalVariableList>(); VariableList = Insertion.first->second.get(); } else if (GV->hasComdat()) // Emit this global variable into a COMDAT section. VariableList = &ComdatVariables; else // Emit this global variable in a single global symbol section. VariableList = &GlobalVariables; CVGlobalVariable CVGV = {DIGV, GV}; VariableList->emplace_back(std::move(CVGV)); } } } void CodeViewDebug::emitDebugInfoForGlobals() { // First, emit all globals that are not in a comdat in a single symbol // substream. MSVC doesn't like it if the substream is empty, so only open // it if we have at least one global to emit. switchToDebugSectionForSymbol(nullptr); if (!GlobalVariables.empty()) { OS.AddComment("Symbol subsection for globals"); MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols); emitGlobalVariableList(GlobalVariables); endCVSubsection(EndLabel); } // Second, emit each global that is in a comdat into its own .debug$S // section along with its own symbol substream. for (const CVGlobalVariable &CVGV : ComdatVariables) { const GlobalVariable *GV = CVGV.GVInfo.get<const GlobalVariable *>(); MCSymbol *GVSym = Asm->getSymbol(GV); OS.AddComment("Symbol subsection for " + Twine(GlobalValue::dropLLVMManglingEscape(GV->getName()))); switchToDebugSectionForSymbol(GVSym); MCSymbol *EndLabel = beginCVSubsection(DebugSubsectionKind::Symbols); // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. emitDebugInfoForGlobal(CVGV); endCVSubsection(EndLabel); } } void CodeViewDebug::emitDebugInfoForRetainedTypes() { NamedMDNode *CUs = MMI->getModule()->getNamedMetadata("llvm.dbg.cu"); for (const MDNode *Node : CUs->operands()) { for (auto *Ty : cast<DICompileUnit>(Node)->getRetainedTypes()) { if (DIType *RT = dyn_cast<DIType>(Ty)) { getTypeIndex(RT); // FIXME: Add to global/local DTU list. } } } } // Emit each global variable in the specified array. void CodeViewDebug::emitGlobalVariableList(ArrayRef<CVGlobalVariable> Globals) { for (const CVGlobalVariable &CVGV : Globals) { // FIXME: emitDebugInfoForGlobal() doesn't handle DIExpressions. emitDebugInfoForGlobal(CVGV); } } void CodeViewDebug::emitDebugInfoForGlobal(const CVGlobalVariable &CVGV) { const DIGlobalVariable *DIGV = CVGV.DIGV; const DIScope *Scope = DIGV->getScope(); // For static data members, get the scope from the declaration. if (const auto *MemberDecl = dyn_cast_or_null<DIDerivedType>( DIGV->getRawStaticDataMemberDeclaration())) Scope = MemberDecl->getScope(); std::string QualifiedName = getFullyQualifiedName(Scope, DIGV->getName()); if (const GlobalVariable *GV = CVGV.GVInfo.dyn_cast<const GlobalVariable *>()) { // DataSym record, see SymbolRecord.h for more info. Thread local data // happens to have the same format as global data. MCSymbol *GVSym = Asm->getSymbol(GV); SymbolKind DataSym = GV->isThreadLocal() ? (DIGV->isLocalToUnit() ? SymbolKind::S_LTHREAD32 : SymbolKind::S_GTHREAD32) : (DIGV->isLocalToUnit() ? SymbolKind::S_LDATA32 : SymbolKind::S_GDATA32); MCSymbol *DataEnd = beginSymbolRecord(DataSym); OS.AddComment("Type"); OS.emitInt32(getCompleteTypeIndex(DIGV->getType()).getIndex()); OS.AddComment("DataOffset"); OS.EmitCOFFSecRel32(GVSym, /*Offset=*/0); OS.AddComment("Segment"); OS.EmitCOFFSectionIndex(GVSym); OS.AddComment("Name"); const unsigned LengthOfDataRecord = 12; emitNullTerminatedSymbolName(OS, QualifiedName, LengthOfDataRecord); endSymbolRecord(DataEnd); } else { const DIExpression *DIE = CVGV.GVInfo.get<const DIExpression *>(); assert(DIE->isConstant() && "Global constant variables must contain a constant expression."); uint64_t Val = DIE->getElement(1); MCSymbol *SConstantEnd = beginSymbolRecord(SymbolKind::S_CONSTANT); OS.AddComment("Type"); OS.emitInt32(getTypeIndex(DIGV->getType()).getIndex()); OS.AddComment("Value"); // Encoded integers shouldn't need more than 10 bytes. uint8_t data[10]; BinaryStreamWriter Writer(data, llvm::support::endianness::little); CodeViewRecordIO IO(Writer); cantFail(IO.mapEncodedInteger(Val)); StringRef SRef((char *)data, Writer.getOffset()); OS.emitBinaryData(SRef); OS.AddComment("Name"); emitNullTerminatedSymbolName(OS, QualifiedName); endSymbolRecord(SConstantEnd); } }
#include "leveldb/options.h" #include "leveldb/comparator.h" #include "leveldb/env.h" namespace leveldb { Options::Options() : comparator(BytewiseComparator()), create_if_missing(false), error_if_exists(false), paranoid_checks(false), env(Env::Default()), info_log(NULL), write_buffer_size(4<<20), max_open_files(1000), block_cache(NULL), block_size(4096), block_restart_interval(16), compression(kSnappyCompression), filter_policy(NULL) { } } // namespace leveldb
/* Copyright (c) 2021 David Walters 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 <stdio.h> #include <stdlib.h> #include "utils.h" //============================================================================== // // checksum function by Dandaman955. // "Feel free to do what you want with the code, the source is on GitHub." // https://www.smspower.org/forums/16629-MasterSystemChecksumFixer#107180 // static uint16_t checksum( unsigned char* pBuffer, uint16_t CC_Last, uint16_t ChecksumRange, int i ) { unsigned char cs1 = ( CC_Last >> 8 ) & 0xFF; unsigned char cs2 = CC_Last & 0xFF; unsigned char cs3 = 0; // Artificial carry flag for ADC emulation. unsigned char e = 0; unsigned char ov1 = 0; unsigned char ov2 = 0; do { e = cs2; // LD A, E ov1 = e; // Set first overflow check flag. e += pBuffer[ i ]; // ADD A, (HL) ov2 = e; // Set the second overflow check flag. if ( ov1 > ov2 ) // Is the last value larger than the first (indicating overflow)? { cs3 = 1; // If it is, set the carry for the adc instruction. } cs2 = e; // LD E, A e = cs1; // LD A, D e += cs3; // ADC A, $00 cs3 = 0; // Reset carry flag. cs1 = e; // LD, D, A i++; // INC HL ChecksumRange--; // DEC BC } while ( ChecksumRange ); CC_Last = ( cs1 << 8 ) & 0xFF00; CC_Last |= cs2; return CC_Last; } // Size options, for user friendly display. static const char* ROMHeaderStr[ 16 ] = { "256KB", "512KB", "1MB", "???", "???", "???", "???", "???", "???", "???", "8KB", "16KB", "32KB", "48KB", "64KB", "128KB" }; //============================================================================== //------------------------------------------------------------------------------ // SMSChk //------------------------------------------------------------------------------ int SMSChk( int argc, char** argv ) { if ( argc < 3 ) { PrintHelp( "smschk" ); return 1; } uint16_t TMRValues[ 3 ] = { 0x1FF0, 0x3FF0, 0x7FF0 }; uint8_t ChecksumRanges[ 9 ] = { 0x1F, 0x3F, 0x7F, 0xBF, 0x7F, 0x7F, 0x7F, 0x7F, 0x7F }; uint8_t ROMPages[ 4 ] = { 0x02, 0x06, 0x0E, 0x1E }; uint8_t TMR[ 10 ] = "TMR SEGA"; TMR[ 8 ] = 0xFF; TMR[ 9 ] = 0xFF; unsigned char* buffer; int i; int j; short TMRStart; short TMRAutoGen = 0; bool bHeaderDetected = false; int err; FILE* fp_in; FILE* fp_out; const char* pRomFile = argv[ 2 ]; // ... input file err = fopen_s( &fp_in, pRomFile, "rb" ); if ( err != 0 || fp_in == nullptr ) { PrintError( "Cannot open ROM file \"%s\".", pRomFile ); return 1; } Info( "Loading ROM: \"%s\" ", pRomFile ); fseek( fp_in, 0, SEEK_END ); int fsize = ftell( fp_in ); rewind( fp_in ); printf( "(%d bytes)\n", fsize ); buffer = (unsigned char*)malloc( fsize ); if ( buffer == NULL ) { PrintError( "Couldn't allocate memory for the file." ); return 1; } fread( buffer, sizeof( char ), fsize, fp_in ); fclose( fp_in ); Info( "Looking for \"TMR SEGA\" header ... " ); // Detect the TMR_SEGA header at locations 0x1FF0, 0x3FF0 or 0x7FF0. for ( j = 0; j < 3; j++ ) { TMRStart = TMRValues[ j ]; // Small ROM? if ( TMRStart > fsize ) break; TMRAutoGen = TMRStart; bHeaderDetected = true; // assume so for ( i = 0; i < 8; i++ ) { if ( buffer[ TMRStart + i ] != TMR[ i ] ) { bHeaderDetected = false; break; } } if ( bHeaderDetected ) { printf( "found at 0x%02X\n", TMRStart ); break; } } if ( bHeaderDetected == false ) { if ( TMRAutoGen == 0 ) { printf( "not found\n" ); PrintError( "Couldn't create header." ); free( buffer ); return 1; } else { printf( "adding at 0x%02X\n", TMRAutoGen ); TMRStart = TMRAutoGen; for ( i = 0; i < 10; i++ ) { buffer[ TMRStart + i ] = TMR[ i ]; } } } // Calculate ROM size unsigned char ROMHeader; int fsize8KB = fsize / 8192; ROMHeader = buffer[ TMRStart + 0x0F ] & 0x0F; if ( fsize8KB == 1 ) ROMHeader = 0xA; // 8KB else if ( fsize8KB == 2 ) ROMHeader = 0xB; // 16KB else if ( fsize8KB == 4 ) ROMHeader = 0xC; // 32KB else if ( fsize8KB == 6 ) ROMHeader = 0xD; // 48KB else if ( fsize8KB == 8 ) ROMHeader = 0xE; // 64KB else if ( fsize8KB == 16 ) ROMHeader = 0xF; // 128KB else if ( fsize8KB == 32 ) ROMHeader = 0x0; // 256KB else if ( fsize8KB == 64 ) ROMHeader = 0x1; // 512KB else if ( fsize8KB == 128 ) ROMHeader = 0x2; // 1MB buffer[ TMRStart + 0x0F ] = ( buffer[ TMRStart + 0x0F ] & 0xF0 ) | ROMHeader; // printf( "Size code = 0x%X\n", ROMHeader ); ROMHeader = ( buffer[ TMRStart + 0x0F ] - 0x0A ) & 0x0F; uint16_t ChecksumRange = ( ( ChecksumRanges[ ROMHeader ] << 8 ) & 0xFF00 ) | 0xF0; // printf( "Scan (0 - %d)... ", ChecksumRange ); uint16_t ComputedChecksum = 0; ComputedChecksum = checksum( buffer, ComputedChecksum, ChecksumRange, 0 ); int ROMPage; if ( ROMHeader > 3 ) { ROMPage = ROMPages[ ROMHeader - 4 ] - 1; int i = 0x8000; for ( ; ; ) { ComputedChecksum = checksum( buffer, ComputedChecksum, 0x4000, i ); if ( ROMPage == 0 ) { break; } ROMPage--; i += 0x4000; } } // Open the file for writing. ROMHeader = buffer[ TMRStart + 0x0F ] & 0x0F; Info( "Checksum = 0x%04X; Size Code = 0x%X (%s)\n", ComputedChecksum, ROMHeader, ROMHeaderStr[ ROMHeader ] ); unsigned char Region; Region = buffer[ TMRStart + 0x0F ] >> 4; if ( Region != 3 /*SMS Japan*/ && Region != 4 /*SMS Export*/ ) { // Only the export SMS BIOS actually checks this, so we use that code. Info( "Changing region to \"SMS Export\"\n" ); buffer[ TMRStart + 0xF ] = ROMHeader | 0x40; } // ... output file err = fopen_s( &fp_out, pRomFile, "wb" ); if ( err != 0 || fp_in == nullptr ) { PrintError( "Cannot open output file \"%s\".", pRomFile ); free( buffer ); return 1; } Info( "Writing \"%s\" ... ", pRomFile ); // Updating the new checksum. buffer[ TMRStart + 0xA ] = ComputedChecksum & 0xFF; buffer[ TMRStart + 0xB ] = ( ComputedChecksum >> 8 ) & 0xFF; fwrite( buffer, 1, fsize, fp_out ); // Program-closing goodies. free( buffer ); fclose( fp_out ); printf( "OK\n" ); return 0; } //==============================================================================
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// // // XFAIL: darwin // // NetBSD does not support LC_MONETARY at the moment // XFAIL: netbsd // REQUIRES: locale.fr_FR.UTF-8 // <locale> // class money_get<charT, InputIterator> // iter_type get(iter_type b, iter_type e, bool intl, ios_base& iob, // ios_base::iostate& err, long double& v) const; #include <locale> #include <ios> #include <streambuf> #include <cassert> #include "test_iterators.h" #include "platform_support.h" // locale name macros #include "test_macros.h" typedef std::money_get<char, input_iterator<const char*> > Fn; class my_facet : public Fn { public: explicit my_facet(std::size_t refs = 0) : Fn(refs) {} }; typedef std::money_get<wchar_t, input_iterator<const wchar_t*> > Fw; class my_facetw : public Fw { public: explicit my_facetw(std::size_t refs = 0) : Fw(refs) {} }; // GLIBC 2.27 and newer use U2027 (narrow non-breaking space) as a thousands sep. // this function converts the spaces in string inputs to that character if need // be. FreeBSD's locale data also uses U2027 since 2018. static std::wstring convert_thousands_sep(std::wstring const& in) { #if defined(_CS_GNU_LIBC_VERSION) || defined(__FreeBSD__) #if defined(_CS_GNU_LIBC_VERSION) if (glibc_version_less_than("2.27")) return in; #endif std::wstring out; unsigned I = 0; bool seen_decimal = false; for (; I < in.size(); ++I) { if (seen_decimal || in[I] != L' ') { seen_decimal |= in[I] == L','; out.push_back(in[I]); continue; } assert(in[I] == L' '); out.push_back(L'\u202F'); } return out; #else return in; #endif } int main(int, char**) { std::ios ios(0); std::string loc_name(LOCALE_fr_FR_UTF_8); ios.imbue(std::locale(ios.getloc(), new std::moneypunct_byname<char, false>(loc_name))); ios.imbue(std::locale(ios.getloc(), new std::moneypunct_byname<char, true>(loc_name))); ios.imbue(std::locale(ios.getloc(), new std::moneypunct_byname<wchar_t, false>(loc_name))); ios.imbue(std::locale(ios.getloc(), new std::moneypunct_byname<wchar_t, true>(loc_name))); { const my_facet f(1); // char, national { // zero std::string v = "0,00"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // negative one std::string v = "-0,01"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // positive std::string v = "1 234 567,89 "; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); } { // negative std::string v = "-1 234 567,89"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); } { // negative std::string v = "-1234567,89"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); } { // zero, showbase std::string v = "0,00 \u20ac"; // EURO SIGN showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // zero, showbase std::string v = "0,00 \u20ac"; // EURO SIGN showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // negative one, showbase std::string v = "-0,01 \u20ac"; // EURO SIGN typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // negative one, showbase std::string v = "-0,01 \u20ac"; // EURO SIGN showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // positive, showbase std::string v = "1 234 567,89 \u20ac"; // EURO SIGN typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); } { // positive, showbase std::string v = "1 234 567,89 \u20ac"; // EURO SIGN showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); noshowbase(ios); } { // negative, showbase std::string v = "-1 234 567,89 \u20ac"; // EURO SIGN showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); noshowbase(ios); } { // negative, showbase std::string v = "1 234 567,89 EUR -"; showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + 13); assert(err == std::ios_base::failbit); noshowbase(ios); } { // negative, showbase std::string v = "1 234 567,89 EUR -"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + 13); assert(err == std::ios_base::goodbit); assert(ex == 123456789); } noshowbase(ios); } { const my_facet f(1); // char, international { // zero std::string v = "0,00"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // negative one std::string v = "-0,01"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // positive std::string v = "1 234 567,89 "; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); } { // negative std::string v = "-1 234 567,89"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); } { // negative std::string v = "-1234567,89"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); } { // zero, showbase std::string v = "0,00 EUR"; showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // zero, showbase std::string v = "0,00 EUR"; showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // negative one, showbase std::string v = "-0,01 EUR"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // negative one, showbase std::string v = "-0,01 EUR"; showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // positive, showbase std::string v = "1 234 567,89 EUR"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); } { // positive, showbase std::string v = "1 234 567,89 EUR"; showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); noshowbase(ios); } { // negative, showbase std::string v = "-1 234 567,89 EUR"; showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); noshowbase(ios); } { // negative, showbase std::string v = "1 234 567,89 Eu-"; showbase(ios); typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + 14); assert(err == std::ios_base::failbit); noshowbase(ios); } { // negative, showbase std::string v = "1 234 567,89 Eu-"; typedef input_iterator<const char*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + 13); assert(err == std::ios_base::goodbit); assert(ex == 123456789); } } { const my_facetw f(1); // wchar_t, national { // zero std::wstring v = L"0,00"; typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // negative one std::wstring v = L"-0,01"; typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // positive std::wstring v = convert_thousands_sep(L"1 234 567,89 "); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); } { // negative std::wstring v = convert_thousands_sep(L"-1 234 567,89"); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); } { // negative std::wstring v = L"-1234567,89"; typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); } { // zero, showbase std::wstring v = L"0,00 \u20ac"; // EURO SIGN showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // zero, showbase std::wstring v = L"0,00 \u20ac"; // EURO SIGN showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // negative one, showbase std::wstring v = L"-0,01 \u20ac"; // EURO SIGN typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // negative one, showbase std::wstring v = L"-0,01 \u20ac"; // EURO SIGN showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // positive, showbase std::wstring v = convert_thousands_sep(L"1 234 567,89 \u20ac"); // EURO SIGN typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); } { // positive, showbase std::wstring v = convert_thousands_sep(L"1 234 567,89 \u20ac"); // EURO SIGN showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); noshowbase(ios); } { // negative, showbase std::wstring v = convert_thousands_sep(L"-1 234 567,89 \u20ac"); // EURO SIGN showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); noshowbase(ios); } { // negative, showbase std::wstring v = convert_thousands_sep(L"1 234 567,89 EUR -"); showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + 13); assert(err == std::ios_base::failbit); noshowbase(ios); } { // negative, showbase std::wstring v = convert_thousands_sep(L"1 234 567,89 EUR -"); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), false, ios, err, ex); assert(iter.base() == v.data() + 13); assert(err == std::ios_base::goodbit); assert(ex == 123456789); } } { const my_facetw f(1); // wchar_t, international { // zero std::wstring v = L"0,00"; typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // negative one std::wstring v = L"-0,01"; typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // positive std::wstring v = convert_thousands_sep(L"1 234 567,89 "); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); } { // negative std::wstring v = convert_thousands_sep(L"-1 234 567,89"); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); } { // negative std::wstring v = L"-1234567,89"; typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); } { // zero, showbase std::wstring v = L"0,00 EUR"; showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // zero, showbase std::wstring v = L"0,00 EUR"; showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 0); } { // negative one, showbase std::wstring v = L"-0,01 EUR"; typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // negative one, showbase std::wstring v = L"-0,01 EUR"; showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -1); } { // positive, showbase std::wstring v = convert_thousands_sep(L"1 234 567,89 EUR"); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); } { // positive, showbase std::wstring v = convert_thousands_sep(L"1 234 567,89 EUR"); showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == 123456789); noshowbase(ios); } { // negative, showbase std::wstring v = convert_thousands_sep(L"-1 234 567,89 EUR"); showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + v.size()); assert(err == std::ios_base::eofbit); assert(ex == -123456789); noshowbase(ios); } { // negative, showbase std::wstring v = convert_thousands_sep(L"1 234 567,89 Eu-"); showbase(ios); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + 14); assert(err == std::ios_base::failbit); noshowbase(ios); } { // negative, showbase std::wstring v = convert_thousands_sep(L"1 234 567,89 Eu-"); typedef input_iterator<const wchar_t*> I; long double ex; std::ios_base::iostate err = std::ios_base::goodbit; I iter = f.get(I(v.data()), I(v.data() + v.size()), true, ios, err, ex); assert(iter.base() == v.data() + 13); assert(err == std::ios_base::goodbit); assert(ex == 123456789); } } return 0; }
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "gpu/mali/cl/kernel_option/gemv_opt.h" #include "gpu/mali/cl/kernel_option/transpose_opt.h" #include "gpu/mali/fp16/gemv_mali_fp16.h" inline bool gemvNeedTransInput(TensorDesc cpuDesc, GCLMemDesc desc) { U32 iw, ih, ic, in; U32 iw_str, ih_str, iw_off, ih_off; DataFormat mf = desc.memFormat; gclmem_get_desc_dim(desc, NULL, NULL, &in, &ic, &ih, &iw); gclmem_get_desc_padding(desc, &iw_str, &ih_str, NULL, &iw_off, &ih_off); U32 num = desc.num; if (mf == DF_NCHW) { if (iw * ih * ic * in == num && iw_off == 0 && ih_off == 0) { return false; } } else if (mf == DF_NCHWC4) { if (iw_str == 1 && ih_str == 1 && iw_off == 0 && ih_off == 0) { return false; } } return true; } inline EE gemvTransInput(GCLHandle_t handle, GCLMem_t input, GCLMem_t inputTran) { U32 iw, ih, ic, in; gclmem_get_desc_dim(input->desc, NULL, NULL, &in, &ic, &ih, &iw); GCLMemDesc desc = input->desc; U32 str[3] = {iw, ih, ic * in}; U32 off[3] = {0, 0, 0}; MemFlags flag = CL_MEM_READ_WRITE; CHECK_STATUS(gclmem_set_desc_padding(&desc, str, off, DT_F16, DF_NCHW, GCL_MEM_BUF, flag)); inputTran->desc = desc; MemTransFormType type = (input->desc.memFormat == DF_NCHWC4) ? NCHWC4_TO_NCHW : NCHW_TO_NCHW; CHECK_STATUS(ocl_data_trans_form(handle, input, inputTran, 0, 0, type)); return SUCCESS; } inline EE gemv_build_run_info_core(GCLHandle_t handle, U32 item_c, U32 row, U32 pitch, ActivationMode activeMode, bool useBias, bool useOutputNchwc4, DataType dt, U32 *tmpOff, GCLMem_t tmpBuf, Mem *subTmpBuf, char *kernelName, KernelOpt *kernelOpt) { bool useReduceMode = false; if (item_c > 16) { item_c = item_c >> 4; useReduceMode = true; U32 size = 32 * row * pitch * bytesOf(dt); CHECK_STATUS(gcl_create_sub_buffer(size, tmpOff, tmpBuf, subTmpBuf)); } CHECK_STATUS(set_gemv_opt( item_c, activeMode, useBias, useReduceMode, useOutputNchwc4, dt, kernelName, kernelOpt)); return SUCCESS; } inline EE gemv_run_core(GCLHandle_t handle, U32 item_c, U32 row, U32 col, U32 pitch, U32 ow_str, U32 oh_str, U32 on_str, U32 o_off, Mem vec, Mem mat, Mem bias, Mem tmp, Mem out, char *kernelName, KernelOpt *kernelOpt) { U32 gs[3] = {row, pitch, 1}; U32 ls[3] = {0, 0, 0}; U32 dim = 2; bool useReduceMode = (item_c > 16) ? true : false; if (useReduceMode) { gs[0] = 32; gs[1] = row; gs[2] = pitch; ls[0] = 32; ls[1] = 1; ls[2] = 1; dim = 3; } Kernel kernel; CHECK_STATUS(gcl_create_kernel(handle, kernelName, &kernel, kernelOpt)); CHECK_STATUS(gcl_set_kernelArgs( kernel, row, col, ow_str, oh_str, on_str, o_off, gs[0], gs[1], vec, mat, bias, tmp, out)); gcl_set_kernelVec(handle, kernel, dim, gs, ls, kernelName); #ifdef _DEBUG // CHECK_STATUS(gcl_run_kernel(handle, kernel, dim, gs, ls, kernelName)); // handle->t_total += handle->t_execute; #endif return SUCCESS; } EE gemv_build_run_info(GCLHandle_t handle, U32 item_c, U32 row, U32 pitch, ActivationMode activeMode, bool useBias, bool useOutputNchwc4, DataType dt, U32 *tmpOff, GCLMem_t tmpBuf, Mem *subTmpBuf, char *kernelName, KernelOpt *kernelOpt) { return gemv_build_run_info_core(handle, item_c, row, pitch, activeMode, useBias, useOutputNchwc4, dt, tmpOff, tmpBuf, subTmpBuf, kernelName, kernelOpt); } EE gemv_run(GCLHandle_t handle, U32 item_c, U32 row, U32 col, U32 pitch, U32 ow_str, U32 oh_str, U32 on_str, U32 o_off, Mem vec, Mem mat, Mem bias, Mem tmp, Mem out, char *kernelName, KernelOpt *kernelOpt) { return gemv_run_core(handle, item_c, row, col, pitch, ow_str, oh_str, on_str, o_off, vec, mat, bias, tmp, out, kernelName, kernelOpt); } EE gemv(GCLHandle_t handle, TensorDesc vecDesc, TensorDesc outputDesc, ActivationMode activeMode, bool useOutputNchwc4, U32 *tmpOff, GCLMem_t tmpBuf, GCLMem_t vec, GCLMem_t bias, GCLMem_t mat, GCLMem_t out, ForwardRunInfoMali_t forwardRunInfo) { GCLMem vecTran = *vec; U32 tmpOffVal = *tmpOff; DataType dt = vecDesc.dt; if (gemvNeedTransInput(vecDesc, vec->desc)) { U32 size = tensorNumBytes(vecDesc); CHECK_STATUS(gcl_create_sub_buffer(size, &tmpOffVal, tmpBuf, &vecTran.mem)); CHECK_STATUS(gemvTransInput(handle, vec, &vecTran)); } GCLMemType vmt = vec->desc.memType; GCLMemType omt = out->desc.memType; if (vmt != GCL_MEM_BUF || omt != GCL_MEM_BUF) { CHECK_STATUS(NOT_SUPPORTED); } U32 item_c = forwardRunInfo->best_c[0]; bool useBias = (bias) ? true : false; Mem vecMem, biasMem, matMem, tmpMem, outMem; vecMem = vecTran.mem; biasMem = (useBias) ? bias->mem : vecMem; tmpMem = vecMem; matMem = mat->mem; outMem = out->mem; U32 row, pitch, on_str; U32 ow_str = out->desc.stride[0]; U32 oh_str = out->desc.stride[1]; U32 ow_off = out->desc.offset[0]; U32 oh_off = out->desc.offset[1]; U32 o_off = oh_off * ow_str + ow_off; if (useOutputNchwc4) { row = outputDesc.dims[outputDesc.nDims - 2]; pitch = outputDesc.dims[outputDesc.nDims - 1]; on_str = ow_str * oh_str * ALIGN(row, 4); } else { row = outputDesc.dims[0]; pitch = (outputDesc.nDims > 1) ? outputDesc.dims[1] : 1; on_str = ow_str; } U32 col = tensorNumElements(vecDesc) / pitch; char kernelName[128]; KernelOpt kernelOpt; CHECK_STATUS(gemv_build_run_info_core(handle, item_c, row, pitch, activeMode, useBias, useOutputNchwc4, dt, &tmpOffVal, tmpBuf, &tmpMem, kernelName, &kernelOpt)); CHECK_STATUS(gemv_run_core(handle, item_c, row, col, pitch, ow_str, oh_str, on_str, o_off, vecMem, matMem, biasMem, tmpMem, outMem, kernelName, &kernelOpt)); *tmpOff = tmpOffVal; return SUCCESS; } TensorDesc gemv_transform_filter_desc(TensorDesc filterDesc, U32 item_h, U32 item_c, U32 item_k) { U32 fc = filterDesc.dims[filterDesc.nDims - 2]; U32 fn = filterDesc.dims[filterDesc.nDims - 1]; TensorDesc desc; desc.df = DF_NCHW; desc.dt = DT_F16; desc.nDims = 4; desc.dims[3] = 1; desc.dims[2] = 1; if (item_c > 16) { item_c = item_c >> 4; desc.dims[0] = ALIGN(fc, item_c); desc.dims[1] = fn; } else { desc.dims[0] = fn * item_c; desc.dims[1] = (fc + item_c - 1) / item_c; } return desc; } inline EE gemv_transform_filter_core( GCLHandle_t handle, U32 fc, U32 fn, U32 item_c, DataType dt, Mem filter, Mem filterTran) { char kernelName[128]; KernelOpt kernelOpt; Kernel kernel; U32 gs[2]; U32 ls[2] = {0, 0}; U32 dim = 2; bool useReduceMode = false; if (item_c > 16) { useReduceMode = true; item_c = item_c >> 4; } U32 fcAlign = ALIGN(fc, item_c); gs[0] = fcAlign >> 2; gs[1] = fn; CHECK_STATUS(set_gemv_trans_mat_opt(item_c, useReduceMode, dt, kernelName, &kernelOpt)); CHECK_STATUS(gcl_get_kernel_from_map(handle, kernelName, &kernel, &kernelOpt)); CHECK_STATUS(gcl_set_kernelArgs(kernel, fn, fc, filter, filterTran)); CHECK_STATUS(gcl_run_kernel(handle, kernel, dim, gs, ls, kernelName)); return SUCCESS; } EE gemv_transform_filter_run( GCLHandle_t handle, U32 fc, U32 fn, U32 item_c, DataType dt, Mem filter, Mem filterTran) { return gemv_transform_filter_core(handle, fc, fn, item_c, dt, filter, filterTran); } EE gemv_transform_filter_mali_fp16(GCLHandle_t handle, TensorDesc filterDesc, GCLMem_t filter, TensorDesc *fltmemDesc, GCLMem_t fltmem, ForwardRunInfoMali_t forwardRunInfo) { DataType fdt = filterDesc.dt; U32 fc = filterDesc.dims[filterDesc.nDims - 2]; U32 fn = filterDesc.dims[filterDesc.nDims - 1]; U32 item_h = forwardRunInfo->best_h[0]; U32 item_c = forwardRunInfo->best_c[0]; U32 item_k = forwardRunInfo->best_k[0]; CHECK_STATUS(gemv_transform_filter_core(handle, fc, fn, item_c, fdt, filter->mem, fltmem->mem)); *fltmemDesc = gemv_transform_filter_desc(filterDesc, item_h, item_c, item_k); return SUCCESS; } EE gemv_infer_forward_tmp_bytes_mali_fp16( TensorDesc inputDesc, TensorDesc outputDesc, U32 *bytes, ForwardRunInfoMali_t forwardRunInfo) { U32 size = tensorNumBytes(inputDesc); U32 item_c = forwardRunInfo->best_c[0]; U32 row = 1; U32 pitch = 1; for (U32 i = 0; i < outputDesc.nDims; i++) { if (outputDesc.dims[i] > 1) { row = outputDesc.dims[i]; pitch = (i + 1 <= outputDesc.nDims - 1) ? outputDesc.dims[i + 1] : 1; break; } } if (item_c > 16) { size = ALIGN(size, BUFFER_ALIGN_BASE) + row * pitch * 32 * bytesOf(inputDesc.dt); } *bytes = size; return SUCCESS; }
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/api/electron_api_web_contents.h" #include <limits> #include <memory> #include <set> #include <string> #include <unordered_set> #include <utility> #include <vector> #include "base/containers/id_map.h" #include "base/files/file_util.h" #include "base/json/json_reader.h" #include "base/no_destructor.h" #include "base/optional.h" #include "base/strings/utf_string_conversions.h" #include "base/task/current_thread.h" #include "base/task/post_task.h" #include "base/task/thread_pool.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/threading/thread_restrictions.h" #include "base/threading/thread_task_runner_handle.h" #include "base/values.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/ssl/security_state_tab_helper.h" #include "chrome/browser/ui/views/eye_dropper/eye_dropper.h" #include "chrome/common/pref_names.h" #include "components/prefs/pref_service.h" #include "components/prefs/scoped_user_pref_update.h" #include "components/security_state/content/content_utils.h" #include "components/security_state/core/security_state.h" #include "content/browser/renderer_host/frame_tree_node.h" // nogncheck #include "content/browser/renderer_host/render_frame_host_manager.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_impl.h" // nogncheck #include "content/browser/renderer_host/render_widget_host_view_base.h" // nogncheck #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/context_menu_params.h" #include "content/public/browser/download_request_utils.h" #include "content/public/browser/favicon_status.h" #include "content/public/browser/file_select_listener.h" #include "content/public/browser/native_web_keyboard_event.h" #include "content/public/browser/navigation_details.h" #include "content/public/browser/navigation_entry.h" #include "content/public/browser/navigation_handle.h" #include "content/public/browser/plugin_service.h" #include "content/public/browser/render_frame_host.h" #include "content/public/browser/render_process_host.h" #include "content/public/browser/render_view_host.h" #include "content/public/browser/render_widget_host.h" #include "content/public/browser/render_widget_host_view.h" #include "content/public/browser/security_style_explanation.h" #include "content/public/browser/security_style_explanations.h" #include "content/public/browser/service_worker_context.h" #include "content/public/browser/site_instance.h" #include "content/public/browser/storage_partition.h" #include "content/public/browser/web_contents.h" #include "content/public/common/referrer_type_converters.h" #include "content/public/common/webplugininfo.h" #include "electron/buildflags/buildflags.h" #include "electron/shell/common/api/api.mojom.h" #include "gin/arguments.h" #include "gin/data_object_builder.h" #include "gin/handle.h" #include "gin/object_template_builder.h" #include "gin/wrappable.h" #include "mojo/public/cpp/bindings/associated_remote.h" #include "mojo/public/cpp/bindings/pending_receiver.h" #include "mojo/public/cpp/bindings/remote.h" #include "mojo/public/cpp/system/platform_handle.h" #include "ppapi/buildflags/buildflags.h" #include "printing/buildflags/buildflags.h" #include "shell/browser/api/electron_api_browser_window.h" #include "shell/browser/api/electron_api_debugger.h" #include "shell/browser/api/electron_api_session.h" #include "shell/browser/api/electron_api_web_frame_main.h" #include "shell/browser/api/message_port.h" #include "shell/browser/browser.h" #include "shell/browser/child_web_contents_tracker.h" #include "shell/browser/electron_autofill_driver_factory.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_browser_main_parts.h" #include "shell/browser/electron_javascript_dialog_manager.h" #include "shell/browser/electron_navigation_throttle.h" #include "shell/browser/lib/bluetooth_chooser.h" #include "shell/browser/native_window.h" #include "shell/browser/session_preferences.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/file_dialog.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/web_contents_permission_helper.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_contents_zoom_controller.h" #include "shell/browser/web_dialog_helper.h" #include "shell/browser/web_view_guest_delegate.h" #include "shell/common/api/electron_api_native_image.h" #include "shell/common/color_util.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/base_converter.h" #include "shell/common/gin_converters/blink_converter.h" #include "shell/common/gin_converters/callback_converter.h" #include "shell/common/gin_converters/content_converter.h" #include "shell/common/gin_converters/file_path_converter.h" #include "shell/common/gin_converters/frame_converter.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_converters/gurl_converter.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_converters/net_converter.h" #include "shell/common/gin_converters/value_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/gin_helper/object_template_builder.h" #include "shell/common/language_util.h" #include "shell/common/mouse_util.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "shell/common/v8_value_serializer.h" #include "storage/browser/file_system/isolated_context.h" #include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h" #include "third_party/blink/public/common/input/web_input_event.h" #include "third_party/blink/public/common/messaging/transferable_message_mojom_traits.h" #include "third_party/blink/public/common/page/page_zoom.h" #include "third_party/blink/public/mojom/frame/find_in_page.mojom.h" #include "third_party/blink/public/mojom/frame/fullscreen.mojom.h" #include "third_party/blink/public/mojom/messaging/transferable_message.mojom.h" #include "third_party/blink/public/mojom/renderer_preferences.mojom.h" #include "ui/base/cursor/cursor.h" #include "ui/base/cursor/mojom/cursor_type.mojom-shared.h" #include "ui/display/screen.h" #include "ui/events/base_event_utils.h" #if BUILDFLAG(ENABLE_OSR) #include "shell/browser/osr/osr_render_widget_host_view.h" #include "shell/browser/osr/osr_web_contents_view.h" #endif #if !defined(OS_MAC) #include "ui/aura/window.h" #else #include "ui/base/cocoa/defaults_utils.h" #endif #if defined(OS_LINUX) #include "ui/views/linux_ui/linux_ui.h" #endif #if defined(OS_LINUX) || defined(OS_WIN) #include "ui/gfx/font_render_params.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "extensions/browser/script_executor.h" #include "extensions/browser/view_type_utils.h" #include "shell/browser/extensions/electron_extension_web_contents_observer.h" #endif #if BUILDFLAG(ENABLE_PRINTING) #include "chrome/browser/printing/print_view_manager_basic.h" #include "components/printing/browser/print_manager_utils.h" #include "printing/backend/print_backend.h" // nogncheck #include "printing/mojom/print.mojom.h" #include "shell/browser/printing/print_preview_message_handler.h" #if defined(OS_WIN) #include "printing/backend/win_helper.h" #endif #endif #if BUILDFLAG(ENABLE_COLOR_CHOOSER) #include "chrome/browser/ui/color_chooser.h" #endif #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) #include "chrome/browser/picture_in_picture/picture_in_picture_window_manager.h" #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) #include "components/pdf/browser/pdf_web_contents_helper.h" // nogncheck #include "shell/browser/electron_pdf_web_contents_helper_client.h" #endif #ifndef MAS_BUILD #include "chrome/browser/hang_monitor/hang_crash_dump.h" // nogncheck #endif namespace gin { #if BUILDFLAG(ENABLE_PRINTING) template <> struct Converter<printing::mojom::MarginType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::MarginType* out) { std::string type; if (ConvertFromV8(isolate, val, &type)) { if (type == "default") { *out = printing::mojom::MarginType::kDefaultMargins; return true; } if (type == "none") { *out = printing::mojom::MarginType::kNoMargins; return true; } if (type == "printableArea") { *out = printing::mojom::MarginType::kPrintableAreaMargins; return true; } if (type == "custom") { *out = printing::mojom::MarginType::kCustomMargins; return true; } } return false; } }; template <> struct Converter<printing::mojom::DuplexMode> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, printing::mojom::DuplexMode* out) { std::string mode; if (ConvertFromV8(isolate, val, &mode)) { if (mode == "simplex") { *out = printing::mojom::DuplexMode::kSimplex; return true; } if (mode == "longEdge") { *out = printing::mojom::DuplexMode::kLongEdge; return true; } if (mode == "shortEdge") { *out = printing::mojom::DuplexMode::kShortEdge; return true; } } return false; } }; #endif template <> struct Converter<WindowOpenDisposition> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, WindowOpenDisposition val) { std::string disposition = "other"; switch (val) { case WindowOpenDisposition::CURRENT_TAB: disposition = "default"; break; case WindowOpenDisposition::NEW_FOREGROUND_TAB: disposition = "foreground-tab"; break; case WindowOpenDisposition::NEW_BACKGROUND_TAB: disposition = "background-tab"; break; case WindowOpenDisposition::NEW_POPUP: case WindowOpenDisposition::NEW_WINDOW: disposition = "new-window"; break; case WindowOpenDisposition::SAVE_TO_DISK: disposition = "save-to-disk"; break; default: break; } return gin::ConvertToV8(isolate, disposition); } }; template <> struct Converter<content::SavePageType> { static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, content::SavePageType* out) { std::string save_type; if (!ConvertFromV8(isolate, val, &save_type)) return false; save_type = base::ToLowerASCII(save_type); if (save_type == "htmlonly") { *out = content::SAVE_PAGE_TYPE_AS_ONLY_HTML; } else if (save_type == "htmlcomplete") { *out = content::SAVE_PAGE_TYPE_AS_COMPLETE_HTML; } else if (save_type == "mhtml") { *out = content::SAVE_PAGE_TYPE_AS_MHTML; } else { return false; } return true; } }; template <> struct Converter<electron::api::WebContents::Type> { static v8::Local<v8::Value> ToV8(v8::Isolate* isolate, electron::api::WebContents::Type val) { using Type = electron::api::WebContents::Type; std::string type; switch (val) { case Type::kBackgroundPage: type = "backgroundPage"; break; case Type::kBrowserWindow: type = "window"; break; case Type::kBrowserView: type = "browserView"; break; case Type::kRemote: type = "remote"; break; case Type::kWebView: type = "webview"; break; case Type::kOffScreen: type = "offscreen"; break; default: break; } return gin::ConvertToV8(isolate, type); } static bool FromV8(v8::Isolate* isolate, v8::Local<v8::Value> val, electron::api::WebContents::Type* out) { using Type = electron::api::WebContents::Type; std::string type; if (!ConvertFromV8(isolate, val, &type)) return false; if (type == "backgroundPage") { *out = Type::kBackgroundPage; } else if (type == "browserView") { *out = Type::kBrowserView; } else if (type == "webview") { *out = Type::kWebView; #if BUILDFLAG(ENABLE_OSR) } else if (type == "offscreen") { *out = Type::kOffScreen; #endif } else { return false; } return true; } }; template <> struct Converter<scoped_refptr<content::DevToolsAgentHost>> { static v8::Local<v8::Value> ToV8( v8::Isolate* isolate, const scoped_refptr<content::DevToolsAgentHost>& val) { gin_helper::Dictionary dict(isolate, v8::Object::New(isolate)); dict.Set("id", val->GetId()); dict.Set("url", val->GetURL().spec()); return dict.GetHandle(); } }; } // namespace gin namespace electron { namespace api { namespace { base::IDMap<WebContents*>& GetAllWebContents() { static base::NoDestructor<base::IDMap<WebContents*>> s_all_web_contents; return *s_all_web_contents; } // Called when CapturePage is done. void OnCapturePageDone(gin_helper::Promise<gfx::Image> promise, const SkBitmap& bitmap) { // Hack to enable transparency in captured image promise.Resolve(gfx::Image::CreateFrom1xBitmap(bitmap)); } base::Optional<base::TimeDelta> GetCursorBlinkInterval() { #if defined(OS_MAC) base::TimeDelta interval; if (ui::TextInsertionCaretBlinkPeriod(&interval)) return interval; #elif defined(OS_LINUX) if (auto* linux_ui = views::LinuxUI::instance()) return linux_ui->GetCursorBlinkInterval(); #elif defined(OS_WIN) const auto system_msec = ::GetCaretBlinkTime(); if (system_msec != 0) { return (system_msec == INFINITE) ? base::TimeDelta() : base::TimeDelta::FromMilliseconds(system_msec); } #endif return base::nullopt; } #if BUILDFLAG(ENABLE_PRINTING) // This will return false if no printer with the provided device_name can be // found on the network. We need to check this because Chromium does not do // sanity checking of device_name validity and so will crash on invalid names. bool IsDeviceNameValid(const base::string16& device_name) { #if defined(OS_MAC) base::ScopedCFTypeRef<CFStringRef> new_printer_id( base::SysUTF16ToCFStringRef(device_name)); PMPrinter new_printer = PMPrinterCreateFromPrinterID(new_printer_id.get()); bool printer_exists = new_printer != nullptr; PMRelease(new_printer); return printer_exists; #elif defined(OS_WIN) printing::ScopedPrinterHandle printer; return printer.OpenPrinterWithName(device_name.c_str()); #endif return true; } base::string16 GetDefaultPrinterAsync() { #if defined(OS_WIN) // Blocking is needed here because Windows printer drivers are oftentimes // not thread-safe and have to be accessed on the UI thread. base::ThreadRestrictions::ScopedAllowIO allow_io; #endif scoped_refptr<printing::PrintBackend> print_backend = printing::PrintBackend::CreateInstance( g_browser_process->GetApplicationLocale()); std::string printer_name = print_backend->GetDefaultPrinterName(); // Some devices won't have a default printer, so we should // also check for existing printers and pick the first // one should it exist. if (printer_name.empty()) { printing::PrinterList printers; print_backend->EnumeratePrinters(&printers); if (!printers.empty()) printer_name = printers.front().printer_name; } return base::UTF8ToUTF16(printer_name); } // Copied from // chrome/browser/ui/webui/print_preview/local_printer_handler_default.cc:L36-L54 scoped_refptr<base::TaskRunner> CreatePrinterHandlerTaskRunner() { // USER_VISIBLE because the result is displayed in the print preview dialog. #if !defined(OS_WIN) static constexpr base::TaskTraits kTraits = { base::MayBlock(), base::TaskPriority::USER_VISIBLE}; #endif #if defined(USE_CUPS) // CUPS is thread safe. return base::ThreadPool::CreateTaskRunner(kTraits); #elif defined(OS_WIN) // Windows drivers are likely not thread-safe and need to be accessed on the // UI thread. return content::GetUIThreadTaskRunner( {base::MayBlock(), base::TaskPriority::USER_VISIBLE}); #else // Be conservative on unsupported platforms. return base::ThreadPool::CreateSingleThreadTaskRunner(kTraits); #endif } #endif struct UserDataLink : public base::SupportsUserData::Data { explicit UserDataLink(base::WeakPtr<WebContents> contents) : web_contents(contents) {} base::WeakPtr<WebContents> web_contents; }; const void* kElectronApiWebContentsKey = &kElectronApiWebContentsKey; const char kRootName[] = "<root>"; struct FileSystem { FileSystem() = default; FileSystem(const std::string& type, const std::string& file_system_name, const std::string& root_url, const std::string& file_system_path) : type(type), file_system_name(file_system_name), root_url(root_url), file_system_path(file_system_path) {} std::string type; std::string file_system_name; std::string root_url; std::string file_system_path; }; std::string RegisterFileSystem(content::WebContents* web_contents, const base::FilePath& path) { auto* isolated_context = storage::IsolatedContext::GetInstance(); std::string root_name(kRootName); storage::IsolatedContext::ScopedFSHandle file_system = isolated_context->RegisterFileSystemForPath( storage::kFileSystemTypeNativeLocal, std::string(), path, &root_name); content::ChildProcessSecurityPolicy* policy = content::ChildProcessSecurityPolicy::GetInstance(); content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); int renderer_id = render_view_host->GetProcess()->GetID(); policy->GrantReadFileSystem(renderer_id, file_system.id()); policy->GrantWriteFileSystem(renderer_id, file_system.id()); policy->GrantCreateFileForFileSystem(renderer_id, file_system.id()); policy->GrantDeleteFromFileSystem(renderer_id, file_system.id()); if (!policy->CanReadFile(renderer_id, path)) policy->GrantReadFile(renderer_id, path); return file_system.id(); } FileSystem CreateFileSystemStruct(content::WebContents* web_contents, const std::string& file_system_id, const std::string& file_system_path, const std::string& type) { const GURL origin = web_contents->GetURL().GetOrigin(); std::string file_system_name = storage::GetIsolatedFileSystemName(origin, file_system_id); std::string root_url = storage::GetIsolatedFileSystemRootURIString( origin, file_system_id, kRootName); return FileSystem(type, file_system_name, root_url, file_system_path); } std::unique_ptr<base::DictionaryValue> CreateFileSystemValue( const FileSystem& file_system) { std::unique_ptr<base::DictionaryValue> file_system_value( new base::DictionaryValue()); file_system_value->SetString("type", file_system.type); file_system_value->SetString("fileSystemName", file_system.file_system_name); file_system_value->SetString("rootURL", file_system.root_url); file_system_value->SetString("fileSystemPath", file_system.file_system_path); return file_system_value; } void WriteToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::WriteFile(path, content.data(), content.size()); } void AppendToFile(const base::FilePath& path, const std::string& content) { base::ScopedBlockingCall scoped_blocking_call(FROM_HERE, base::BlockingType::WILL_BLOCK); DCHECK(!path.empty()); base::AppendToFile(path, content.data(), content.size()); } PrefService* GetPrefService(content::WebContents* web_contents) { auto* context = web_contents->GetBrowserContext(); return static_cast<electron::ElectronBrowserContext*>(context)->prefs(); } std::map<std::string, std::string> GetAddedFileSystemPaths( content::WebContents* web_contents) { auto* pref_service = GetPrefService(web_contents); const base::DictionaryValue* file_system_paths_value = pref_service->GetDictionary(prefs::kDevToolsFileSystemPaths); std::map<std::string, std::string> result; if (file_system_paths_value) { base::DictionaryValue::Iterator it(*file_system_paths_value); for (; !it.IsAtEnd(); it.Advance()) { std::string type = it.value().is_string() ? it.value().GetString() : std::string(); result[it.key()] = type; } } return result; } bool IsDevToolsFileSystemAdded(content::WebContents* web_contents, const std::string& file_system_path) { auto file_system_paths = GetAddedFileSystemPaths(web_contents); return file_system_paths.find(file_system_path) != file_system_paths.end(); } } // namespace #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) WebContents::Type GetTypeFromViewType(extensions::ViewType view_type) { switch (view_type) { case extensions::VIEW_TYPE_EXTENSION_BACKGROUND_PAGE: return WebContents::Type::kBackgroundPage; case extensions::VIEW_TYPE_APP_WINDOW: case extensions::VIEW_TYPE_COMPONENT: case extensions::VIEW_TYPE_EXTENSION_DIALOG: case extensions::VIEW_TYPE_EXTENSION_POPUP: case extensions::VIEW_TYPE_BACKGROUND_CONTENTS: case extensions::VIEW_TYPE_EXTENSION_GUEST: case extensions::VIEW_TYPE_TAB_CONTENTS: case extensions::VIEW_TYPE_INVALID: return WebContents::Type::kRemote; } } #endif WebContents::WebContents(v8::Isolate* isolate, content::WebContents* web_contents) : content::WebContentsObserver(web_contents), type_(Type::kRemote), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_(new DevToolsFileSystemIndexer), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})), print_task_runner_(CreatePrinterHandlerTaskRunner()), weak_factory_(this) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) // WebContents created by extension host will have valid ViewType set. extensions::ViewType view_type = extensions::GetViewType(web_contents); if (view_type != extensions::VIEW_TYPE_INVALID) { InitWithExtensionView(isolate, web_contents, view_type); } extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents); script_executor_.reset(new extensions::ScriptExecutor(web_contents)); #endif auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); web_contents->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); web_contents->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); InitZoomController(web_contents, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) : content::WebContentsObserver(web_contents.get()), type_(type), id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_(new DevToolsFileSystemIndexer), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})), print_task_runner_(CreatePrinterHandlerTaskRunner()), weak_factory_(this) { DCHECK(type != Type::kRemote) << "Can't take ownership of a remote WebContents"; auto session = Session::CreateFrom(isolate, GetBrowserContext()); session_.Reset(isolate, session.ToV8()); InitWithSessionAndOptions(isolate, std::move(web_contents), session, gin::Dictionary::CreateEmpty(isolate)); } WebContents::WebContents(v8::Isolate* isolate, const gin_helper::Dictionary& options) : id_(GetAllWebContents().Add(this)), devtools_file_system_indexer_(new DevToolsFileSystemIndexer), file_task_runner_( base::ThreadPool::CreateSequencedTaskRunner({base::MayBlock()})), print_task_runner_(CreatePrinterHandlerTaskRunner()), weak_factory_(this) { // Read options. options.Get("backgroundThrottling", &background_throttling_); // Get type options.Get("type", &type_); #if BUILDFLAG(ENABLE_OSR) bool b = false; if (options.Get(options::kOffscreen, &b) && b) type_ = Type::kOffScreen; #endif // Init embedder earlier options.Get("embedder", &embedder_); // Whether to enable DevTools. options.Get("devTools", &enable_devtools_); // BrowserViews are not attached to a window initially so they should start // off as hidden. This is also important for compositor recycling. See: // https://github.com/electron/electron/pull/21372 initially_shown_ = type_ != Type::kBrowserView; options.Get(options::kShow, &initially_shown_); // Obtain the session. std::string partition; gin::Handle<api::Session> session; if (options.Get("session", &session) && !session.IsEmpty()) { } else if (options.Get("partition", &partition)) { session = Session::FromPartition(isolate, partition); } else { // Use the default session if not specified. session = Session::FromPartition(isolate, ""); } session_.Reset(isolate, session.ToV8()); std::unique_ptr<content::WebContents> web_contents; if (IsGuest()) { scoped_refptr<content::SiteInstance> site_instance = content::SiteInstance::CreateForURL(session->browser_context(), GURL("chrome-guest://fake-host")); content::WebContents::CreateParams params(session->browser_context(), site_instance); guest_delegate_ = std::make_unique<WebViewGuestDelegate>(embedder_->web_contents(), this); params.guest_delegate = guest_delegate_.get(); #if BUILDFLAG(ENABLE_OSR) if (embedder_ && embedder_->IsOffScreen()) { auto* view = new OffScreenWebContentsView( false, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); } else { #endif web_contents = content::WebContents::Create(params); #if BUILDFLAG(ENABLE_OSR) } } else if (IsOffScreen()) { bool transparent = false; options.Get("transparent", &transparent); content::WebContents::CreateParams params(session->browser_context()); auto* view = new OffScreenWebContentsView( transparent, base::BindRepeating(&WebContents::OnPaint, base::Unretained(this))); params.view = view; params.delegate_view = view; web_contents = content::WebContents::Create(params); view->SetWebContents(web_contents.get()); #endif } else { content::WebContents::CreateParams params(session->browser_context()); params.initially_hidden = !initially_shown_; web_contents = content::WebContents::Create(params); } InitWithSessionAndOptions(isolate, std::move(web_contents), session, options); } void WebContents::InitZoomController(content::WebContents* web_contents, const gin_helper::Dictionary& options) { WebContentsZoomController::CreateForWebContents(web_contents); zoom_controller_ = WebContentsZoomController::FromWebContents(web_contents); double zoom_factor; if (options.Get(options::kZoomFactor, &zoom_factor)) zoom_controller_->SetDefaultZoomFactor(zoom_factor); } void WebContents::InitWithSessionAndOptions( v8::Isolate* isolate, std::unique_ptr<content::WebContents> owned_web_contents, gin::Handle<api::Session> session, const gin_helper::Dictionary& options) { Observe(owned_web_contents.get()); // TODO(zcbenz): Make InitWithWebContents take unique_ptr. // At the time of writing we are going through a refactoring and I don't want // to make other people's work harder. InitWithWebContents(owned_web_contents.release(), session->browser_context(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); auto* prefs = web_contents()->GetMutableRendererPrefs(); // Collect preferred languages from OS and browser process. accept_languages // effects HTTP header, navigator.languages, and CJK fallback font selection. // // Note that an application locale set to the browser process might be // different with the one set to the preference list. // (e.g. overridden with --lang) std::string accept_languages = g_browser_process->GetApplicationLocale() + ","; for (auto const& language : electron::GetPreferredLanguages()) { if (language == g_browser_process->GetApplicationLocale()) continue; accept_languages += language + ","; } accept_languages.pop_back(); prefs->accept_languages = accept_languages; #if defined(OS_LINUX) || defined(OS_WIN) // Update font settings. static const base::NoDestructor<gfx::FontRenderParams> params( gfx::GetFontRenderParams(gfx::FontRenderParamsQuery(), nullptr)); prefs->should_antialias_text = params->antialiasing; prefs->use_subpixel_positioning = params->subpixel_positioning; prefs->hinting = params->hinting; prefs->use_autohinter = params->autohinter; prefs->use_bitmaps = params->use_bitmaps; prefs->subpixel_rendering = params->subpixel_rendering; #endif // Honor the system's cursor blink rate settings if (auto interval = GetCursorBlinkInterval()) prefs->caret_blink_interval = *interval; // Save the preferences in C++. // If there's already a WebContentsPreferences object, we created it as part // of the webContents.setWindowOpenHandler path, so don't overwrite it. if (!WebContentsPreferences::From(web_contents())) { new WebContentsPreferences(web_contents(), options); } // Trigger re-calculation of webkit prefs. web_contents()->NotifyPreferencesChanged(); WebContentsPermissionHelper::CreateForWebContents(web_contents()); SecurityStateTabHelper::CreateForWebContents(web_contents()); InitZoomController(web_contents(), options); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions::ElectronExtensionWebContentsObserver::CreateForWebContents( web_contents()); script_executor_.reset(new extensions::ScriptExecutor(web_contents())); #endif AutofillDriverFactory::CreateForWebContents(web_contents()); web_contents()->SetUserAgentOverride(blink::UserAgentOverride::UserAgentOnly( GetBrowserContext()->GetUserAgent()), false); if (IsGuest()) { NativeWindow* owner_window = nullptr; if (embedder_) { // New WebContents's owner_window is the embedder's owner_window. auto* relay = NativeWindowRelay::FromWebContents(embedder_->web_contents()); if (relay) owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); } web_contents()->SetUserData(kElectronApiWebContentsKey, std::make_unique<UserDataLink>(GetWeakPtr())); } #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) void WebContents::InitWithExtensionView(v8::Isolate* isolate, content::WebContents* web_contents, extensions::ViewType view_type) { // Must reassign type prior to calling `Init`. type_ = GetTypeFromViewType(view_type); if (GetType() == Type::kRemote) return; // Allow toggling DevTools for background pages Observe(web_contents); InitWithWebContents(web_contents, GetBrowserContext(), IsGuest()); inspectable_web_contents_->GetView()->SetDelegate(this); SecurityStateTabHelper::CreateForWebContents(web_contents); } #endif void WebContents::InitWithWebContents(content::WebContents* web_contents, ElectronBrowserContext* browser_context, bool is_guest) { browser_context_ = browser_context; web_contents->SetDelegate(this); #if BUILDFLAG(ENABLE_PRINTING) PrintPreviewMessageHandler::CreateForWebContents(web_contents); printing::PrintViewManagerBasic::CreateForWebContents(web_contents); printing::CreateCompositeClientIfNeeded(web_contents, browser_context->GetUserAgent()); #endif #if BUILDFLAG(ENABLE_PDF_VIEWER) pdf::PDFWebContentsHelper::CreateForWebContentsWithClient( web_contents, std::make_unique<ElectronPDFWebContentsHelperClient>()); #endif // Determine whether the WebContents is offscreen. auto* web_preferences = WebContentsPreferences::From(web_contents); offscreen_ = web_preferences && web_preferences->IsEnabled(options::kOffscreen); // Create InspectableWebContents. inspectable_web_contents_.reset(new InspectableWebContents( web_contents, browser_context->prefs(), is_guest)); inspectable_web_contents_->SetDelegate(this); } WebContents::~WebContents() { MarkDestroyed(); // The destroy() is called. if (inspectable_web_contents_) { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) if (type_ == Type::kBackgroundPage) { // Background pages are owned by extensions::ExtensionHost inspectable_web_contents_->ReleaseWebContents(); } #endif inspectable_web_contents_->GetView()->SetDelegate(nullptr); if (web_contents()) { RenderViewDeleted(web_contents()->GetRenderViewHost()); } if (type_ == Type::kBrowserWindow && owner_window()) { // For BrowserWindow we should close the window and clean up everything // before WebContents is destroyed. for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); // BrowserWindow destroys WebContents asynchronously, manually emit the // destroyed event here. WebContentsDestroyed(); } else if (Browser::Get()->is_shutting_down()) { // Destroy WebContents directly when app is shutting down. DestroyWebContents(false /* async */); } else { // Destroy WebContents asynchronously unless app is shutting down, // because destroy() might be called inside WebContents's event handler. bool is_browser_view = type_ == Type::kBrowserView; DestroyWebContents(!(IsGuest() || is_browser_view) /* async */); // The WebContentsDestroyed will not be called automatically because we // destroy the webContents in the next tick. So we have to manually // call it here to make sure "destroyed" event is emitted. WebContentsDestroyed(); } } } void WebContents::DestroyWebContents(bool async) { // This event is only for internal use, which is emitted when WebContents is // being destroyed. Emit("will-destroy"); ResetManagedWebContents(async); } bool WebContents::DidAddMessageToConsole( content::WebContents* source, blink::mojom::ConsoleMessageLevel level, const base::string16& message, int32_t line_no, const base::string16& source_id) { return Emit("console-message", static_cast<int32_t>(level), message, line_no, source_id); } void WebContents::OnCreateWindow( const GURL& target_url, const content::Referrer& referrer, const std::string& frame_name, WindowOpenDisposition disposition, const std::string& features, const scoped_refptr<network::ResourceRequestBody>& body) { Emit("-new-window", target_url, frame_name, disposition, features, referrer, body); } void WebContents::WebContentsCreatedWithFullParams( content::WebContents* source_contents, int opener_render_process_id, int opener_render_frame_id, const content::mojom::CreateNewWindowParams& params, content::WebContents* new_contents) { ChildWebContentsTracker::CreateForWebContents(new_contents); auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents); tracker->url = params.target_url; tracker->frame_name = params.frame_name; tracker->referrer = params.referrer.To<content::Referrer>(); tracker->raw_features = params.raw_features; tracker->body = params.body; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary dict; gin::ConvertFromV8(isolate, pending_child_web_preferences_.Get(isolate), &dict); pending_child_web_preferences_.Reset(); // Associate the preferences passed in via `setWindowOpenHandler` with the // content::WebContents that was just created for the child window. These // preferences will be picked up by the RenderWidgetHost via its call to the // delegate's OverrideWebkitPrefs. new WebContentsPreferences(new_contents, dict); } bool WebContents::IsWebContentsCreationOverridden( content::SiteInstance* source_site_instance, content::mojom::WindowContainerType window_container_type, const GURL& opener_url, const content::mojom::CreateNewWindowParams& params) { bool default_prevented = Emit("-will-add-new-contents", params.target_url, params.frame_name, params.raw_features); // If the app prevented the default, redirect to CreateCustomWebContents, // which always returns nullptr, which will result in the window open being // prevented (window.open() will return null in the renderer). return default_prevented; } void WebContents::SetNextChildWebPreferences( const gin_helper::Dictionary preferences) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); // Store these prefs for when Chrome calls WebContentsCreatedWithFullParams // with the new child contents. pending_child_web_preferences_.Reset(isolate, preferences.GetHandle()); } content::WebContents* WebContents::CreateCustomWebContents( content::RenderFrameHost* opener, content::SiteInstance* source_site_instance, bool is_new_browsing_instance, const GURL& opener_url, const std::string& frame_name, const GURL& target_url, const std::string& partition_id, content::SessionStorageNamespace* session_storage_namespace) { return nullptr; } void WebContents::AddNewContents( content::WebContents* source, std::unique_ptr<content::WebContents> new_contents, const GURL& target_url, WindowOpenDisposition disposition, const gfx::Rect& initial_rect, bool user_gesture, bool* was_blocked) { auto* tracker = ChildWebContentsTracker::FromWebContents(new_contents.get()); DCHECK(tracker); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); auto api_web_contents = CreateAndTake(isolate, std::move(new_contents), Type::kBrowserWindow); if (Emit("-add-new-contents", api_web_contents, disposition, user_gesture, initial_rect.x(), initial_rect.y(), initial_rect.width(), initial_rect.height(), tracker->url, tracker->frame_name, tracker->referrer, tracker->raw_features, tracker->body)) { api_web_contents->DestroyWebContents(false /* async */); } } content::WebContents* WebContents::OpenURLFromTab( content::WebContents* source, const content::OpenURLParams& params) { auto weak_this = GetWeakPtr(); if (params.disposition != WindowOpenDisposition::CURRENT_TAB) { Emit("-new-window", params.url, "", params.disposition, "", params.referrer, params.post_data); return nullptr; } if (!weak_this) return nullptr; content::NavigationController::LoadURLParams load_url_params(params.url); load_url_params.referrer = params.referrer; load_url_params.transition_type = params.transition; load_url_params.extra_headers = params.extra_headers; load_url_params.should_replace_current_entry = params.should_replace_current_entry; load_url_params.is_renderer_initiated = params.is_renderer_initiated; load_url_params.started_from_context_menu = params.started_from_context_menu; load_url_params.initiator_origin = params.initiator_origin; load_url_params.source_site_instance = params.source_site_instance; load_url_params.frame_tree_node_id = params.frame_tree_node_id; load_url_params.redirect_chain = params.redirect_chain; load_url_params.has_user_gesture = params.user_gesture; load_url_params.blob_url_loader_factory = params.blob_url_loader_factory; load_url_params.href_translate = params.href_translate; load_url_params.reload_type = params.reload_type; if (params.post_data) { load_url_params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; load_url_params.post_data = params.post_data; } source->GetController().LoadURLWithParams(load_url_params); return source; } void WebContents::BeforeUnloadFired(content::WebContents* tab, bool proceed, bool* proceed_to_fire_unload) { if (type_ == Type::kBrowserWindow || type_ == Type::kOffScreen) *proceed_to_fire_unload = proceed; else *proceed_to_fire_unload = true; // Note that Chromium does not emit this for navigations. Emit("before-unload-fired", proceed); } void WebContents::SetContentsBounds(content::WebContents* source, const gfx::Rect& rect) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnSetContentBounds(rect); } void WebContents::CloseContents(content::WebContents* source) { Emit("close"); auto* autofill_driver_factory = AutofillDriverFactory::FromWebContents(web_contents()); if (autofill_driver_factory) { autofill_driver_factory->CloseAllPopups(); } if (inspectable_web_contents_) inspectable_web_contents_->GetView()->SetDelegate(nullptr); for (ExtendedWebContentsObserver& observer : observers_) observer.OnCloseContents(); } void WebContents::ActivateContents(content::WebContents* source) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnActivateContents(); } void WebContents::UpdateTargetURL(content::WebContents* source, const GURL& url) { Emit("update-target-url", url); } bool WebContents::HandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (type_ == Type::kWebView && embedder_) { // Send the unhandled keyboard events back to the embedder. return embedder_->HandleKeyboardEvent(source, event); } else { return PlatformHandleKeyboardEvent(source, event); } } #if !defined(OS_MAC) // NOTE: The macOS version of this function is found in // electron_api_web_contents_mac.mm, as it requires calling into objective-C // code. bool WebContents::PlatformHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { // Escape exits tabbed fullscreen mode. if (event.windows_key_code == ui::VKEY_ESCAPE && is_html_fullscreen()) { ExitFullscreenModeForTab(source); return true; } // Check if the webContents has preferences and to ignore shortcuts auto* web_preferences = WebContentsPreferences::From(source); if (web_preferences && web_preferences->IsEnabled("ignoreMenuShortcuts", false)) return false; // Let the NativeWindow handle other parts. if (owner_window()) { owner_window()->HandleKeyboardEvent(source, event); return true; } return false; } #endif content::KeyboardEventProcessingResult WebContents::PreHandleKeyboardEvent( content::WebContents* source, const content::NativeWebKeyboardEvent& event) { if (event.GetType() == blink::WebInputEvent::Type::kRawKeyDown || event.GetType() == blink::WebInputEvent::Type::kKeyUp) { bool prevent_default = Emit("before-input-event", event); if (prevent_default) { return content::KeyboardEventProcessingResult::HANDLED; } } return content::KeyboardEventProcessingResult::NOT_HANDLED; } void WebContents::ContentsZoomChange(bool zoom_in) { Emit("zoom-changed", zoom_in ? "in" : "out"); } void WebContents::EnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options) { auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(source); auto callback = base::BindRepeating(&WebContents::OnEnterFullscreenModeForTab, base::Unretained(this), requesting_frame, options); permission_helper->RequestFullscreenPermission(callback); } void WebContents::OnEnterFullscreenModeForTab( content::RenderFrameHost* requesting_frame, const blink::mojom::FullscreenOptions& options, bool allowed) { if (!allowed) return; if (!owner_window_) return; auto* source = content::WebContents::FromRenderFrameHost(requesting_frame); if (IsFullscreenForTabOrPending(source)) { DCHECK_EQ(fullscreen_frame_, source->GetFocusedFrame()); return; } SetHtmlApiFullscreen(true); owner_window_->NotifyWindowEnterHtmlFullScreen(); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } Emit("enter-html-full-screen"); } void WebContents::ExitFullscreenModeForTab(content::WebContents* source) { if (!owner_window_) return; SetHtmlApiFullscreen(false); owner_window_->NotifyWindowLeaveHtmlFullScreen(); if (native_fullscreen_) { // Explicitly trigger a view resize, as the size is not actually changing if // the browser is fullscreened, too. Chrome does this indirectly from // `chrome/browser/ui/exclusive_access/fullscreen_controller.cc`. source->GetRenderViewHost()->GetWidget()->SynchronizeVisualProperties(); } Emit("leave-html-full-screen"); } void WebContents::RendererUnresponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host, base::RepeatingClosure hang_monitor_restarter) { Emit("unresponsive"); } void WebContents::RendererResponsive( content::WebContents* source, content::RenderWidgetHost* render_widget_host) { Emit("responsive"); } bool WebContents::HandleContextMenu(content::RenderFrameHost* render_frame_host, const content::ContextMenuParams& params) { if (params.custom_context.is_pepper_menu) { Emit("pepper-context-menu", std::make_pair(params, web_contents()), base::BindOnce(&content::WebContents::NotifyContextMenuClosed, base::Unretained(web_contents()), params.custom_context)); } else { Emit("context-menu", std::make_pair(params, web_contents())); } return true; } bool WebContents::OnGoToEntryOffset(int offset) { GoToOffset(offset); return false; } void WebContents::FindReply(content::WebContents* web_contents, int request_id, int number_of_matches, const gfx::Rect& selection_rect, int active_match_ordinal, bool final_update) { if (!final_update) return; v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary result = gin::Dictionary::CreateEmpty(isolate); result.Set("requestId", request_id); result.Set("matches", number_of_matches); result.Set("selectionArea", selection_rect); result.Set("activeMatchOrdinal", active_match_ordinal); result.Set("finalUpdate", final_update); // Deprecate after 2.0 Emit("found-in-page", result.GetHandle()); } bool WebContents::CheckMediaAccessPermission( content::RenderFrameHost* render_frame_host, const GURL& security_origin, blink::mojom::MediaStreamType type) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckMediaAccessPermission(security_origin, type); } void WebContents::RequestMediaAccessPermission( content::WebContents* web_contents, const content::MediaStreamRequest& request, content::MediaResponseCallback callback) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestMediaAccessPermission(request, std::move(callback)); } void WebContents::RequestToLockMouse(content::WebContents* web_contents, bool user_gesture, bool last_unlocked_by_target) { auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); permission_helper->RequestPointerLockPermission(user_gesture); } content::JavaScriptDialogManager* WebContents::GetJavaScriptDialogManager( content::WebContents* source) { if (!dialog_manager_) dialog_manager_ = std::make_unique<ElectronJavaScriptDialogManager>(); return dialog_manager_.get(); } void WebContents::OnAudioStateChanged(bool audible) { Emit("-audio-state-changed", audible); } void WebContents::BeforeUnloadFired(bool proceed, const base::TimeTicks& proceed_time) { // Do nothing, we override this method just to avoid compilation error since // there are two virtual functions named BeforeUnloadFired. } void WebContents::RenderViewCreated(content::RenderViewHost* render_view_host) { if (!background_throttling_) render_view_host->SetSchedulerThrottling(false); } void WebContents::RenderFrameCreated( content::RenderFrameHost* render_frame_host) { auto* rwhv = render_frame_host->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (rwh_impl) rwh_impl->disable_hidden_ = !background_throttling_; } void WebContents::RenderViewDeleted(content::RenderViewHost* render_view_host) { // This event is necessary for tracking any states with respect to // intermediate render view hosts aka speculative render view hosts. Currently // used by object-registry.js to ref count remote objects. Emit("render-view-deleted", render_view_host->GetProcess()->GetID()); if (web_contents()->GetRenderViewHost() == render_view_host) { // When the RVH that has been deleted is the current RVH it means that the // the web contents are being closed. This is communicated by this event. // Currently tracked by guest-window-manager.ts to destroy the // BrowserWindow. Emit("current-render-view-deleted", render_view_host->GetProcess()->GetID()); } } void WebContents::RenderProcessGone(base::TerminationStatus status) { Emit("crashed", status == base::TERMINATION_STATUS_PROCESS_WAS_KILLED); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); gin_helper::Dictionary details = gin_helper::Dictionary::CreateEmpty(isolate); details.Set("reason", status); Emit("render-process-gone", details); } void WebContents::PluginCrashed(const base::FilePath& plugin_path, base::ProcessId plugin_pid) { #if BUILDFLAG(ENABLE_PLUGINS) content::WebPluginInfo info; auto* plugin_service = content::PluginService::GetInstance(); plugin_service->GetPluginInfoByPath(plugin_path, &info); Emit("plugin-crashed", info.name, info.version); #endif // BUILDFLAG(ENABLE_PLUGINS) } void WebContents::MediaStartedPlaying(const MediaPlayerInfo& video_type, const content::MediaPlayerId& id) { Emit("media-started-playing"); } void WebContents::MediaStoppedPlaying( const MediaPlayerInfo& video_type, const content::MediaPlayerId& id, content::WebContentsObserver::MediaStoppedReason reason) { Emit("media-paused"); } void WebContents::DidChangeThemeColor() { auto theme_color = web_contents()->GetThemeColor(); if (theme_color) { Emit("did-change-theme-color", electron::ToRGBHex(theme_color.value())); } else { Emit("did-change-theme-color", nullptr); } } void WebContents::OnInterfaceRequestFromFrame( content::RenderFrameHost* render_frame_host, const std::string& interface_name, mojo::ScopedMessagePipeHandle* interface_pipe) { registry_.TryBindInterface(interface_name, interface_pipe, render_frame_host); } void WebContents::DidAcquireFullscreen(content::RenderFrameHost* rfh) { set_fullscreen_frame(rfh); } void WebContents::DOMContentLoaded( content::RenderFrameHost* render_frame_host) { if (!render_frame_host->GetParent()) Emit("dom-ready"); } void WebContents::DidFinishLoad(content::RenderFrameHost* render_frame_host, const GURL& validated_url) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); auto weak_this = GetWeakPtr(); Emit("did-frame-finish-load", is_main_frame, frame_process_id, frame_routing_id); // ⚠️WARNING!⚠️ // Emit() triggers JS which can call destroy() on |this|. It's not safe to // assume that |this| points to valid memory at this point. if (is_main_frame && weak_this) Emit("did-finish-load"); } void WebContents::DidFailLoad(content::RenderFrameHost* render_frame_host, const GURL& url, int error_code) { bool is_main_frame = !render_frame_host->GetParent(); int frame_process_id = render_frame_host->GetProcess()->GetID(); int frame_routing_id = render_frame_host->GetRoutingID(); Emit("did-fail-load", error_code, "", url, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::DidStartLoading() { Emit("did-start-loading"); } void WebContents::DidStopLoading() { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (web_preferences && web_preferences->IsEnabled(options::kEnablePreferredSizeMode)) web_contents()->GetRenderViewHost()->EnablePreferredSizeMode(); Emit("did-stop-loading"); } bool WebContents::EmitNavigationEvent( const std::string& event, content::NavigationHandle* navigation_handle) { bool is_main_frame = navigation_handle->IsInMainFrame(); int frame_tree_node_id = navigation_handle->GetFrameTreeNodeId(); content::FrameTreeNode* frame_tree_node = content::FrameTreeNode::GloballyFindByID(frame_tree_node_id); content::RenderFrameHostManager* render_manager = frame_tree_node->render_manager(); content::RenderFrameHost* frame_host = nullptr; if (render_manager) { frame_host = render_manager->speculative_frame_host(); if (!frame_host) frame_host = render_manager->current_frame_host(); } int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } bool is_same_document = navigation_handle->IsSameDocument(); auto url = navigation_handle->GetURL(); return Emit(event, url, is_same_document, is_main_frame, frame_process_id, frame_routing_id); } void WebContents::Message(bool internal, const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Message", "channel", channel); // webContents.emit('-ipc-message', new Event(), internal, channel, // arguments); EmitWithSender("-ipc-message", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), internal, channel, std::move(arguments)); } void WebContents::Invoke( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::InvokeCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::Invoke", "channel", channel); // webContents.emit('-ipc-invoke', new Event(), internal, channel, arguments); EmitWithSender("-ipc-invoke", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::OnFirstNonEmptyLayout( content::RenderFrameHost* render_frame_host) { if (render_frame_host == web_contents()->GetMainFrame()) { Emit("ready-to-show"); } } void WebContents::ReceivePostMessage( const std::string& channel, blink::TransferableMessage message, content::RenderFrameHost* render_frame_host) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope handle_scope(isolate); auto wrapped_ports = MessagePort::EntanglePorts(isolate, std::move(message.ports)); v8::Local<v8::Value> message_value = electron::DeserializeV8Value(isolate, message); EmitWithSender("-ipc-ports", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), false, channel, message_value, std::move(wrapped_ports)); } void WebContents::MessageSync( bool internal, const std::string& channel, blink::CloneableMessage arguments, electron::mojom::ElectronBrowser::MessageSyncCallback callback, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageSync", "channel", channel); // webContents.emit('-ipc-message-sync', new Event(sender, message), internal, // channel, arguments); EmitWithSender("-ipc-message-sync", render_frame_host, std::move(callback), internal, channel, std::move(arguments)); } void WebContents::MessageTo(bool internal, int32_t web_contents_id, const std::string& channel, blink::CloneableMessage arguments) { TRACE_EVENT1("electron", "WebContents::MessageTo", "channel", channel); auto* web_contents = FromID(web_contents_id); if (web_contents) { web_contents->SendIPCMessageWithSender(internal, channel, std::move(arguments), ID()); } } void WebContents::MessageHost(const std::string& channel, blink::CloneableMessage arguments, content::RenderFrameHost* render_frame_host) { TRACE_EVENT1("electron", "WebContents::MessageHost", "channel", channel); // webContents.emit('ipc-message-host', new Event(), channel, args); EmitWithSender("ipc-message-host", render_frame_host, electron::mojom::ElectronBrowser::InvokeCallback(), channel, std::move(arguments)); } void WebContents::UpdateDraggableRegions( std::vector<mojom::DraggableRegionPtr> regions) { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDraggableRegionsUpdated(regions); } void WebContents::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { // A WebFrameMain can outlive its RenderFrameHost so we need to mark it as // disposed to prevent access to it. WebFrameMain::RenderFrameDeleted(render_frame_host); } void WebContents::DidStartNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-start-navigation", navigation_handle); } void WebContents::DidRedirectNavigation( content::NavigationHandle* navigation_handle) { EmitNavigationEvent("did-redirect-navigation", navigation_handle); } void WebContents::DidFinishNavigation( content::NavigationHandle* navigation_handle) { if (!navigation_handle->HasCommitted()) return; bool is_main_frame = navigation_handle->IsInMainFrame(); content::RenderFrameHost* frame_host = navigation_handle->GetRenderFrameHost(); int frame_process_id = -1, frame_routing_id = -1; if (frame_host) { frame_process_id = frame_host->GetProcess()->GetID(); frame_routing_id = frame_host->GetRoutingID(); } if (!navigation_handle->IsErrorPage()) { // FIXME: All the Emit() calls below could potentially result in |this| // being destroyed (by JS listening for the event and calling // webContents.destroy()). auto url = navigation_handle->GetURL(); bool is_same_document = navigation_handle->IsSameDocument(); if (is_same_document) { Emit("did-navigate-in-page", url, is_main_frame, frame_process_id, frame_routing_id); } else { const net::HttpResponseHeaders* http_response = navigation_handle->GetResponseHeaders(); std::string http_status_text; int http_response_code = -1; if (http_response) { http_status_text = http_response->GetStatusText(); http_response_code = http_response->response_code(); } Emit("did-frame-navigate", url, http_response_code, http_status_text, is_main_frame, frame_process_id, frame_routing_id); if (is_main_frame) { Emit("did-navigate", url, http_response_code, http_status_text); } } if (IsGuest()) Emit("load-commit", url, is_main_frame); } else { auto url = navigation_handle->GetURL(); int code = navigation_handle->GetNetErrorCode(); auto description = net::ErrorToShortString(code); Emit("did-fail-provisional-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); // Do not emit "did-fail-load" for canceled requests. if (code != net::ERR_ABORTED) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "Failed to load URL: " + url.possibly_invalid_spec() + " with error: " + description, "electron"); Emit("did-fail-load", code, description, url, is_main_frame, frame_process_id, frame_routing_id); } } } void WebContents::TitleWasSet(content::NavigationEntry* entry) { base::string16 final_title; bool explicit_set = true; if (entry) { auto title = entry->GetTitle(); auto url = entry->GetURL(); if (url.SchemeIsFile() && title.empty()) { final_title = base::UTF8ToUTF16(url.ExtractFileName()); explicit_set = false; } else { final_title = title; } } for (ExtendedWebContentsObserver& observer : observers_) observer.OnPageTitleUpdated(final_title, explicit_set); Emit("page-title-updated", final_title, explicit_set); } void WebContents::DidUpdateFaviconURL( content::RenderFrameHost* render_frame_host, const std::vector<blink::mojom::FaviconURLPtr>& urls) { std::set<GURL> unique_urls; for (const auto& iter : urls) { if (iter->icon_type != blink::mojom::FaviconIconType::kFavicon) continue; const GURL& url = iter->icon_url; if (url.is_valid()) unique_urls.insert(url); } Emit("page-favicon-updated", unique_urls); } void WebContents::DevToolsReloadPage() { Emit("devtools-reload-page"); } void WebContents::DevToolsFocused() { Emit("devtools-focused"); } void WebContents::DevToolsOpened() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); DCHECK(inspectable_web_contents_); auto handle = FromOrCreate( isolate, inspectable_web_contents_->GetDevToolsWebContents()); devtools_web_contents_.Reset(isolate, handle.ToV8()); // Set inspected tabID. base::Value tab_id(ID()); inspectable_web_contents_->CallClientFunction("DevToolsAPI.setInspectedTabId", &tab_id, nullptr, nullptr); // Inherit owner window in devtools when it doesn't have one. auto* devtools = inspectable_web_contents_->GetDevToolsWebContents(); bool has_window = devtools->GetUserData(NativeWindowRelay::UserDataKey()); if (owner_window() && !has_window) handle->SetOwnerWindow(devtools, owner_window()); Emit("devtools-opened"); } void WebContents::DevToolsClosed() { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::Locker locker(isolate); v8::HandleScope handle_scope(isolate); devtools_web_contents_.Reset(); Emit("devtools-closed"); } void WebContents::DevToolsResized() { for (ExtendedWebContentsObserver& observer : observers_) observer.OnDevToolsResized(); } bool WebContents::OnMessageReceived(const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(WebContents, message) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void WebContents::SetOwnerWindow(NativeWindow* owner_window) { SetOwnerWindow(GetWebContents(), owner_window); } void WebContents::SetOwnerWindow(content::WebContents* web_contents, NativeWindow* owner_window) { if (owner_window) { owner_window_ = owner_window->GetWeakPtr(); NativeWindowRelay::CreateForWebContents(web_contents, owner_window->GetWeakPtr()); } else { owner_window_ = nullptr; web_contents->RemoveUserData(NativeWindowRelay::UserDataKey()); } #if BUILDFLAG(ENABLE_OSR) auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetNativeWindow(owner_window); #endif } void WebContents::ResetManagedWebContents(bool async) { if (async) { // Browser context should be destroyed only after the WebContents, // this is guaranteed in the sync mode by the order of declaration, // in the async version we maintain a reference until the WebContents // is destroyed. // //electron/patches/chromium/content_browser_main_loop.patch // is required to get the right quit closure for the main message loop. base::ThreadTaskRunnerHandle::Get()->DeleteSoon( FROM_HERE, inspectable_web_contents_.release()); } else { inspectable_web_contents_.reset(); } } content::WebContents* WebContents::GetWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetWebContents(); } content::WebContents* WebContents::GetDevToolsWebContents() const { if (!inspectable_web_contents_) return nullptr; return inspectable_web_contents_->GetDevToolsWebContents(); } void WebContents::MarkDestroyed() { if (GetAllWebContents().Lookup(id_)) GetAllWebContents().Remove(id_); v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); v8::HandleScope scope(isolate); v8::Local<v8::Object> wrapper; if (!GetWrapper(isolate).ToLocal(&wrapper)) return; wrapper->SetAlignedPointerInInternalField(0, nullptr); } // There are three ways of destroying a webContents: // 1. call webContents.destroy(); // 2. garbage collection; // 3. user closes the window of webContents; // 4. the embedder detaches the frame. // For webview only #4 will happen, for BrowserWindow both #1 and #3 may // happen. The #2 should never happen for webContents, because webview is // managed by GuestViewManager, and BrowserWindow's webContents is managed // by api::BrowserWindow. // For #1, the destructor will do the cleanup work and we only need to make // sure "destroyed" event is emitted. For #3, the content::WebContents will // be destroyed on close, and WebContentsDestroyed would be called for it, so // we need to make sure the api::WebContents is also deleted. // For #4, the WebContents will be destroyed by embedder. void WebContents::WebContentsDestroyed() { // Give chance for guest delegate to cleanup its observers // since the native class is only destroyed in the next tick. if (guest_delegate_) guest_delegate_->WillDestroy(); // Cleanup relationships with other parts. // We can not call Destroy here because we need to call Emit first, but we // also do not want any method to be used, so just mark as destroyed here. MarkDestroyed(); Emit("destroyed"); // For guest view based on OOPIF, the WebContents is released by the embedder // frame, and we need to clear the reference to the memory. if (IsGuest() && inspectable_web_contents_) { inspectable_web_contents_->ReleaseWebContents(); ResetManagedWebContents(false); } // Destroy the native class in next tick. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce( [](base::WeakPtr<WebContents> wc) { if (wc) delete wc.get(); }, GetWeakPtr())); } void WebContents::NavigationEntryCommitted( const content::LoadCommittedDetails& details) { Emit("navigation-entry-committed", details.entry->GetURL(), details.is_same_document, details.did_replace_entry); } bool WebContents::GetBackgroundThrottling() const { return background_throttling_; } void WebContents::SetBackgroundThrottling(bool allowed) { background_throttling_ = allowed; auto* rfh = web_contents()->GetMainFrame(); if (!rfh) return; auto* rwhv = rfh->GetView(); if (!rwhv) return; auto* rwh_impl = static_cast<content::RenderWidgetHostImpl*>(rwhv->GetRenderWidgetHost()); if (!rwh_impl) return; rwh_impl->disable_hidden_ = !background_throttling_; web_contents()->GetRenderViewHost()->SetSchedulerThrottling(allowed); if (rwh_impl->is_hidden()) { rwh_impl->WasShown({}); } } int WebContents::GetProcessID() const { return web_contents()->GetMainFrame()->GetProcess()->GetID(); } base::ProcessId WebContents::GetOSProcessID() const { base::ProcessHandle process_handle = web_contents()->GetMainFrame()->GetProcess()->GetProcess().Handle(); return base::GetProcId(process_handle); } WebContents::Type WebContents::GetType() const { return type_; } bool WebContents::Equal(const WebContents* web_contents) const { return ID() == web_contents->ID(); } void WebContents::LoadURL(const GURL& url, const gin_helper::Dictionary& options) { if (!url.is_valid() || url.spec().size() > url::kMaxURLChars) { Emit("did-fail-load", static_cast<int>(net::ERR_INVALID_URL), net::ErrorToShortString(net::ERR_INVALID_URL), url.possibly_invalid_spec(), true); return; } content::NavigationController::LoadURLParams params(url); if (!options.Get("httpReferrer", &params.referrer)) { GURL http_referrer; if (options.Get("httpReferrer", &http_referrer)) params.referrer = content::Referrer(http_referrer.GetAsReferrer(), network::mojom::ReferrerPolicy::kDefault); } std::string user_agent; if (options.Get("userAgent", &user_agent)) web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); std::string extra_headers; if (options.Get("extraHeaders", &extra_headers)) params.extra_headers = extra_headers; scoped_refptr<network::ResourceRequestBody> body; if (options.Get("postData", &body)) { params.post_data = body; params.load_type = content::NavigationController::LOAD_TYPE_HTTP_POST; } GURL base_url_for_data_url; if (options.Get("baseURLForDataURL", &base_url_for_data_url)) { params.base_url_for_data_url = base_url_for_data_url; params.load_type = content::NavigationController::LOAD_TYPE_DATA; } bool reload_ignoring_cache = false; if (options.Get("reloadIgnoringCache", &reload_ignoring_cache) && reload_ignoring_cache) { params.reload_type = content::ReloadType::BYPASSING_CACHE; } // Calling LoadURLWithParams() can trigger JS which destroys |this|. auto weak_this = GetWeakPtr(); // Required to make beforeunload handler work. NotifyUserActivation(); params.transition_type = ui::PAGE_TRANSITION_TYPED; params.should_clear_history_list = true; params.override_user_agent = content::NavigationController::UA_OVERRIDE_TRUE; // Discord non-committed entries to ensure that we don't re-use a pending // entry web_contents()->GetController().DiscardNonCommittedEntries(); web_contents()->GetController().LoadURLWithParams(params); // ⚠️WARNING!⚠️ // LoadURLWithParams() triggers JS events which can call destroy() on |this|. // It's not safe to assume that |this| points to valid memory at this point. if (!weak_this) return; // Set the background color of RenderWidgetHostView. // We have to call it right after LoadURL because the RenderViewHost is only // created after loading a page. auto* const view = weak_this->web_contents()->GetRenderWidgetHostView(); if (view) { auto* web_preferences = WebContentsPreferences::From(web_contents()); std::string color_name; if (web_preferences->GetPreference(options::kBackgroundColor, &color_name)) { view->SetBackgroundColor(ParseHexColor(color_name)); } else { view->SetBackgroundColor(SK_ColorTRANSPARENT); } } } void WebContents::DownloadURL(const GURL& url) { auto* browser_context = web_contents()->GetBrowserContext(); auto* download_manager = content::BrowserContext::GetDownloadManager(browser_context); std::unique_ptr<download::DownloadUrlParameters> download_params( content::DownloadRequestUtils::CreateDownloadForWebContentsMainFrame( web_contents(), url, MISSING_TRAFFIC_ANNOTATION)); download_manager->DownloadUrl(std::move(download_params)); } GURL WebContents::GetURL() const { return web_contents()->GetURL(); } base::string16 WebContents::GetTitle() const { return web_contents()->GetTitle(); } bool WebContents::IsLoading() const { return web_contents()->IsLoading(); } bool WebContents::IsLoadingMainFrame() const { return web_contents()->IsLoadingToDifferentDocument(); } bool WebContents::IsWaitingForResponse() const { return web_contents()->IsWaitingForResponse(); } void WebContents::Stop() { web_contents()->Stop(); } void WebContents::GoBack() { if (!ElectronBrowserClient::Get()->CanUseCustomSiteInstance()) { electron::ElectronBrowserClient::SuppressRendererProcessRestartForOnce(); } web_contents()->GetController().GoBack(); } void WebContents::GoForward() { if (!ElectronBrowserClient::Get()->CanUseCustomSiteInstance()) { electron::ElectronBrowserClient::SuppressRendererProcessRestartForOnce(); } web_contents()->GetController().GoForward(); } void WebContents::GoToOffset(int offset) { if (!ElectronBrowserClient::Get()->CanUseCustomSiteInstance()) { electron::ElectronBrowserClient::SuppressRendererProcessRestartForOnce(); } web_contents()->GetController().GoToOffset(offset); } const std::string WebContents::GetWebRTCIPHandlingPolicy() const { return web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy; } void WebContents::SetWebRTCIPHandlingPolicy( const std::string& webrtc_ip_handling_policy) { if (GetWebRTCIPHandlingPolicy() == webrtc_ip_handling_policy) return; web_contents()->GetMutableRendererPrefs()->webrtc_ip_handling_policy = webrtc_ip_handling_policy; web_contents()->SyncRendererPrefs(); } bool WebContents::IsCrashed() const { return web_contents()->IsCrashed(); } void WebContents::ForcefullyCrashRenderer() { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); if (!rwh) return; content::RenderProcessHost* rph = rwh->GetProcess(); if (rph) { #if defined(OS_LINUX) || defined(OS_CHROMEOS) // A generic |CrashDumpHungChildProcess()| is not implemented for Linux. // Instead we send an explicit IPC to crash on the renderer's IO thread. rph->ForceCrash(); #else // Try to generate a crash report for the hung process. #ifndef MAS_BUILD CrashDumpHungChildProcess(rph->GetProcess().Handle()); #endif rph->Shutdown(content::RESULT_CODE_HUNG); #endif } } void WebContents::SetUserAgent(const std::string& user_agent) { web_contents()->SetUserAgentOverride( blink::UserAgentOverride::UserAgentOnly(user_agent), false); } std::string WebContents::GetUserAgent() { return web_contents()->GetUserAgentOverride().ua_string_override; } v8::Local<v8::Promise> WebContents::SavePage( const base::FilePath& full_file_path, const content::SavePageType& save_type) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); auto* handler = new SavePageHandler(web_contents(), std::move(promise)); handler->Handle(full_file_path, save_type); return handle; } void WebContents::OpenDevTools(gin::Arguments* args) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; std::string state; if (type_ == Type::kWebView || type_ == Type::kBackgroundPage || !owner_window()) { state = "detach"; } bool activate = true; if (args && args->Length() == 1) { gin_helper::Dictionary options; if (args->GetNext(&options)) { options.Get("mode", &state); options.Get("activate", &activate); } } DCHECK(inspectable_web_contents_); inspectable_web_contents_->SetDockState(state); inspectable_web_contents_->ShowDevTools(activate); } void WebContents::CloseDevTools() { if (type_ == Type::kRemote) return; DCHECK(inspectable_web_contents_); inspectable_web_contents_->CloseDevTools(); } bool WebContents::IsDevToolsOpened() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->IsDevToolsViewShowing(); } bool WebContents::IsDevToolsFocused() { if (type_ == Type::kRemote) return false; DCHECK(inspectable_web_contents_); return inspectable_web_contents_->GetView()->IsDevToolsViewFocused(); } void WebContents::EnableDeviceEmulation( const blink::DeviceEmulationParams& params) { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = frame_host ? static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()) : nullptr; if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->EnableDeviceEmulation(params); } } } void WebContents::DisableDeviceEmulation() { if (type_ == Type::kRemote) return; DCHECK(web_contents()); auto* frame_host = web_contents()->GetMainFrame(); if (frame_host) { auto* widget_host_impl = frame_host ? static_cast<content::RenderWidgetHostImpl*>( frame_host->GetView()->GetRenderWidgetHost()) : nullptr; if (widget_host_impl) { auto& frame_widget = widget_host_impl->GetAssociatedFrameWidget(); frame_widget->DisableDeviceEmulation(); } } } void WebContents::ToggleDevTools() { if (IsDevToolsOpened()) CloseDevTools(); else OpenDevTools(nullptr); } void WebContents::InspectElement(int x, int y) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; DCHECK(inspectable_web_contents_); if (!inspectable_web_contents_->GetDevToolsWebContents()) OpenDevTools(nullptr); inspectable_web_contents_->InspectElement(x, y); } void WebContents::InspectSharedWorkerById(const std::string& workerId) { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { if (agent_host->GetId() == workerId) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } } std::vector<scoped_refptr<content::DevToolsAgentHost>> WebContents::GetAllSharedWorkers() { std::vector<scoped_refptr<content::DevToolsAgentHost>> shared_workers; if (type_ == Type::kRemote) return shared_workers; if (!enable_devtools_) return shared_workers; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { shared_workers.push_back(agent_host); } } return shared_workers; } void WebContents::InspectSharedWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeSharedWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::InspectServiceWorker() { if (type_ == Type::kRemote) return; if (!enable_devtools_) return; for (const auto& agent_host : content::DevToolsAgentHost::GetOrCreateAll()) { if (agent_host->GetType() == content::DevToolsAgentHost::kTypeServiceWorker) { OpenDevTools(nullptr); inspectable_web_contents_->AttachTo(agent_host); break; } } } void WebContents::SetIgnoreMenuShortcuts(bool ignore) { auto* web_preferences = WebContentsPreferences::From(web_contents()); DCHECK(web_preferences); web_preferences->preference()->SetKey("ignoreMenuShortcuts", base::Value(ignore)); } void WebContents::SetAudioMuted(bool muted) { web_contents()->SetAudioMuted(muted); } bool WebContents::IsAudioMuted() { return web_contents()->IsAudioMuted(); } bool WebContents::IsCurrentlyAudible() { return web_contents()->IsCurrentlyAudible(); } #if BUILDFLAG(ENABLE_PRINTING) void WebContents::OnGetDefaultPrinter( base::Value print_settings, printing::CompletionCallback print_callback, base::string16 device_name, bool silent, base::string16 default_printer) { // The content::WebContents might be already deleted at this point, and the // PrintViewManagerBasic class does not do null check. if (!web_contents()) { if (print_callback) std::move(print_callback).Run(false, "failed"); return; } base::string16 printer_name = device_name.empty() ? default_printer : device_name; // If there are no valid printers available on the network, we bail. if (printer_name.empty() || !IsDeviceNameValid(printer_name)) { if (print_callback) std::move(print_callback).Run(false, "no valid printers available"); return; } print_settings.SetStringKey(printing::kSettingDeviceName, printer_name); auto* print_view_manager = printing::PrintViewManagerBasic::FromWebContents(web_contents()); auto* focused_frame = web_contents()->GetFocusedFrame(); auto* rfh = focused_frame && focused_frame->HasSelection() ? focused_frame : web_contents()->GetMainFrame(); print_view_manager->PrintNow(rfh, silent, std::move(print_settings), std::move(print_callback)); } void WebContents::Print(gin::Arguments* args) { gin_helper::Dictionary options = gin::Dictionary::CreateEmpty(args->isolate()); base::Value settings(base::Value::Type::DICTIONARY); if (args->Length() >= 1 && !args->GetNext(&options)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid print settings specified."); return; } printing::CompletionCallback callback; if (args->Length() == 2 && !args->GetNext(&callback)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid optional callback provided."); return; } // Set optional silent printing bool silent = false; options.Get("silent", &silent); bool print_background = false; options.Get("printBackground", &print_background); settings.SetBoolKey(printing::kSettingShouldPrintBackgrounds, print_background); // Set custom margin settings gin_helper::Dictionary margins = gin::Dictionary::CreateEmpty(args->isolate()); if (options.Get("margins", &margins)) { printing::mojom::MarginType margin_type = printing::mojom::MarginType::kDefaultMargins; margins.Get("marginType", &margin_type); settings.SetIntKey(printing::kSettingMarginsType, static_cast<int>(margin_type)); if (margin_type == printing::mojom::MarginType::kCustomMargins) { base::Value custom_margins(base::Value::Type::DICTIONARY); int top = 0; margins.Get("top", &top); custom_margins.SetIntKey(printing::kSettingMarginTop, top); int bottom = 0; margins.Get("bottom", &bottom); custom_margins.SetIntKey(printing::kSettingMarginBottom, bottom); int left = 0; margins.Get("left", &left); custom_margins.SetIntKey(printing::kSettingMarginLeft, left); int right = 0; margins.Get("right", &right); custom_margins.SetIntKey(printing::kSettingMarginRight, right); settings.SetPath(printing::kSettingMarginsCustom, std::move(custom_margins)); } } else { settings.SetIntKey( printing::kSettingMarginsType, static_cast<int>(printing::mojom::MarginType::kDefaultMargins)); } // Set whether to print color or greyscale bool print_color = true; options.Get("color", &print_color); auto const color_model = print_color ? printing::mojom::ColorModel::kColor : printing::mojom::ColorModel::kGray; settings.SetIntKey(printing::kSettingColor, static_cast<int>(color_model)); // Is the orientation landscape or portrait. bool landscape = false; options.Get("landscape", &landscape); settings.SetBoolKey(printing::kSettingLandscape, landscape); // We set the default to the system's default printer and only update // if at the Chromium level if the user overrides. // Printer device name as opened by the OS. base::string16 device_name; options.Get("deviceName", &device_name); if (!device_name.empty() && !IsDeviceNameValid(device_name)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("webContents.print(): Invalid deviceName provided."); return; } int scale_factor = 100; options.Get("scaleFactor", &scale_factor); settings.SetIntKey(printing::kSettingScaleFactor, scale_factor); int pages_per_sheet = 1; options.Get("pagesPerSheet", &pages_per_sheet); settings.SetIntKey(printing::kSettingPagesPerSheet, pages_per_sheet); // True if the user wants to print with collate. bool collate = true; options.Get("collate", &collate); settings.SetBoolKey(printing::kSettingCollate, collate); // The number of individual copies to print int copies = 1; options.Get("copies", &copies); settings.SetIntKey(printing::kSettingCopies, copies); // Strings to be printed as headers and footers if requested by the user. std::string header; options.Get("header", &header); std::string footer; options.Get("footer", &footer); if (!(header.empty() && footer.empty())) { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, true); settings.SetStringKey(printing::kSettingHeaderFooterTitle, header); settings.SetStringKey(printing::kSettingHeaderFooterURL, footer); } else { settings.SetBoolKey(printing::kSettingHeaderFooterEnabled, false); } // We don't want to allow the user to enable these settings // but we need to set them or a CHECK is hit. settings.SetIntKey(printing::kSettingPrinterType, static_cast<int>(printing::PrinterType::kLocal)); settings.SetBoolKey(printing::kSettingShouldPrintSelectionOnly, false); settings.SetBoolKey(printing::kSettingRasterizePdf, false); // Set custom page ranges to print std::vector<gin_helper::Dictionary> page_ranges; if (options.Get("pageRanges", &page_ranges)) { base::Value page_range_list(base::Value::Type::LIST); for (auto& range : page_ranges) { int from, to; if (range.Get("from", &from) && range.Get("to", &to)) { base::Value range(base::Value::Type::DICTIONARY); // Chromium uses 1-based page ranges, so increment each by 1. range.SetIntKey(printing::kSettingPageRangeFrom, from + 1); range.SetIntKey(printing::kSettingPageRangeTo, to + 1); page_range_list.Append(std::move(range)); } else { continue; } } if (!page_range_list.GetList().empty()) settings.SetPath(printing::kSettingPageRange, std::move(page_range_list)); } // Duplex type user wants to use. printing::mojom::DuplexMode duplex_mode = printing::mojom::DuplexMode::kSimplex; options.Get("duplexMode", &duplex_mode); settings.SetIntKey(printing::kSettingDuplexMode, static_cast<int>(duplex_mode)); // We've already done necessary parameter sanitization at the // JS level, so we can simply pass this through. base::Value media_size(base::Value::Type::DICTIONARY); if (options.Get("mediaSize", &media_size)) settings.SetKey(printing::kSettingMediaSize, std::move(media_size)); // Set custom dots per inch (dpi) gin_helper::Dictionary dpi_settings; int dpi = 72; if (options.Get("dpi", &dpi_settings)) { int horizontal = 72; dpi_settings.Get("horizontal", &horizontal); settings.SetIntKey(printing::kSettingDpiHorizontal, horizontal); int vertical = 72; dpi_settings.Get("vertical", &vertical); settings.SetIntKey(printing::kSettingDpiVertical, vertical); } else { settings.SetIntKey(printing::kSettingDpiHorizontal, dpi); settings.SetIntKey(printing::kSettingDpiVertical, dpi); } print_task_runner_->PostTaskAndReplyWithResult( FROM_HERE, base::BindOnce(&GetDefaultPrinterAsync), base::BindOnce(&WebContents::OnGetDefaultPrinter, weak_factory_.GetWeakPtr(), std::move(settings), std::move(callback), device_name, silent)); } v8::Local<v8::Promise> WebContents::PrintToPDF(base::DictionaryValue settings) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); gin_helper::Promise<v8::Local<v8::Value>> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); PrintPreviewMessageHandler::FromWebContents(web_contents()) ->PrintToPDF(std::move(settings), std::move(promise)); return handle; } #endif void WebContents::AddWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsAddFileSystem(std::string(), path); } void WebContents::RemoveWorkSpace(gin::Arguments* args, const base::FilePath& path) { if (path.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("path cannot be empty"); return; } DevToolsRemoveFileSystem(path); } void WebContents::Undo() { web_contents()->Undo(); } void WebContents::Redo() { web_contents()->Redo(); } void WebContents::Cut() { web_contents()->Cut(); } void WebContents::Copy() { web_contents()->Copy(); } void WebContents::Paste() { web_contents()->Paste(); } void WebContents::PasteAndMatchStyle() { web_contents()->PasteAndMatchStyle(); } void WebContents::Delete() { web_contents()->Delete(); } void WebContents::SelectAll() { web_contents()->SelectAll(); } void WebContents::Unselect() { web_contents()->CollapseSelection(); } void WebContents::Replace(const base::string16& word) { web_contents()->Replace(word); } void WebContents::ReplaceMisspelling(const base::string16& word) { web_contents()->ReplaceMisspelling(word); } uint32_t WebContents::FindInPage(gin::Arguments* args) { base::string16 search_text; if (!args->GetNext(&search_text) || search_text.empty()) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must provide a non-empty search content"); return 0; } uint32_t request_id = ++find_in_page_request_id_; gin_helper::Dictionary dict; auto options = blink::mojom::FindOptions::New(); if (args->GetNext(&dict)) { dict.Get("forward", &options->forward); dict.Get("matchCase", &options->match_case); dict.Get("findNext", &options->new_session); } web_contents()->Find(request_id, search_text, std::move(options)); return request_id; } void WebContents::StopFindInPage(content::StopFindAction action) { web_contents()->StopFinding(action); } void WebContents::ShowDefinitionForSelection() { #if defined(OS_MAC) auto* const view = web_contents()->GetRenderWidgetHostView(); if (view) view->ShowDefinitionForSelection(); #endif } void WebContents::CopyImageAt(int x, int y) { auto* const host = web_contents()->GetMainFrame(); if (host) host->CopyImageAt(x, y); } void WebContents::Focus() { // Focusing on WebContents does not automatically focus the window on macOS // and Linux, do it manually to match the behavior on Windows. #if defined(OS_MAC) || defined(OS_LINUX) if (owner_window()) owner_window()->Focus(true); #endif web_contents()->Focus(); } #if !defined(OS_MAC) bool WebContents::IsFocused() const { auto* view = web_contents()->GetRenderWidgetHostView(); if (!view) return false; if (GetType() != Type::kBackgroundPage) { auto* window = web_contents()->GetNativeView()->GetToplevelWindow(); if (window && !window->IsVisible()) return false; } return view->HasFocus(); } #endif bool WebContents::SendIPCMessage(bool internal, const std::string& channel, v8::Local<v8::Value> args) { v8::Isolate* isolate = JavascriptEnvironment::GetIsolate(); blink::CloneableMessage message; if (!gin::ConvertFromV8(isolate, args, &message)) { isolate->ThrowException(v8::Exception::Error( gin::StringToV8(isolate, "Failed to serialize arguments"))); return false; } return SendIPCMessageWithSender(internal, channel, std::move(message)); } bool WebContents::SendIPCMessageWithSender(bool internal, const std::string& channel, blink::CloneableMessage args, int32_t sender_id) { auto* frame_host = web_contents()->GetMainFrame(); mojo::AssociatedRemote<mojom::ElectronRenderer> electron_renderer; frame_host->GetRemoteAssociatedInterfaces()->GetInterface(&electron_renderer); electron_renderer->Message(internal, channel, std::move(args), sender_id); return true; } void WebContents::SendInputEvent(v8::Isolate* isolate, v8::Local<v8::Value> input_event) { content::RenderWidgetHostView* view = web_contents()->GetRenderWidgetHostView(); if (!view) return; content::RenderWidgetHost* rwh = view->GetRenderWidgetHost(); blink::WebInputEvent::Type type = gin::GetWebInputEventType(isolate, input_event); if (blink::WebInputEvent::IsMouseEventType(type)) { blink::WebMouseEvent mouse_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseEvent(mouse_event); #endif } else { rwh->ForwardMouseEvent(mouse_event); } return; } } else if (blink::WebInputEvent::IsKeyboardEventType(type)) { content::NativeWebKeyboardEvent keyboard_event( blink::WebKeyboardEvent::Type::kRawKeyDown, blink::WebInputEvent::Modifiers::kNoModifiers, ui::EventTimeForNow()); if (gin::ConvertFromV8(isolate, input_event, &keyboard_event)) { rwh->ForwardKeyboardEvent(keyboard_event); return; } } else if (type == blink::WebInputEvent::Type::kMouseWheel) { blink::WebMouseWheelEvent mouse_wheel_event; if (gin::ConvertFromV8(isolate, input_event, &mouse_wheel_event)) { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) GetOffScreenRenderWidgetHostView()->SendMouseWheelEvent( mouse_wheel_event); #endif } else { // Chromium expects phase info in wheel events (and applies a // DCHECK to verify it). See: https://crbug.com/756524. mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseBegan; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); // Send a synthetic wheel event with phaseEnded to finish scrolling. mouse_wheel_event.has_synthetic_phase = true; mouse_wheel_event.delta_x = 0; mouse_wheel_event.delta_y = 0; mouse_wheel_event.phase = blink::WebMouseWheelEvent::kPhaseEnded; mouse_wheel_event.dispatch_type = blink::WebInputEvent::DispatchType::kEventNonBlocking; rwh->ForwardWheelEvent(mouse_wheel_event); } return; } } isolate->ThrowException( v8::Exception::Error(gin::StringToV8(isolate, "Invalid event object"))); } void WebContents::BeginFrameSubscription(gin::Arguments* args) { bool only_dirty = false; FrameSubscriber::FrameCaptureCallback callback; if (args->Length() > 1) { if (!args->GetNext(&only_dirty)) { args->ThrowError(); return; } } if (!args->GetNext(&callback)) { args->ThrowError(); return; } frame_subscriber_ = std::make_unique<FrameSubscriber>(web_contents(), callback, only_dirty); } void WebContents::EndFrameSubscription() { frame_subscriber_.reset(); } void WebContents::StartDrag(const gin_helper::Dictionary& item, gin::Arguments* args) { base::FilePath file; std::vector<base::FilePath> files; if (!item.Get("files", &files) && item.Get("file", &file)) { files.push_back(file); } v8::Local<v8::Value> icon_value; if (!item.Get("icon", &icon_value)) { gin_helper::ErrorThrower(args->isolate()) .ThrowError("'icon' parameter is required"); return; } NativeImage* icon = nullptr; if (!NativeImage::TryConvertNativeImage(args->isolate(), icon_value, &icon) || icon->image().IsEmpty()) { return; } // Start dragging. if (!files.empty()) { base::CurrentThread::ScopedNestableTaskAllower allow; DragFileItems(files, icon->image(), web_contents()->GetNativeView()); } else { gin_helper::ErrorThrower(args->isolate()) .ThrowError("Must specify either 'file' or 'files' option"); } } v8::Local<v8::Promise> WebContents::CapturePage(gin::Arguments* args) { gfx::Rect rect; gin_helper::Promise<gfx::Image> promise(args->isolate()); v8::Local<v8::Promise> handle = promise.GetHandle(); // get rect arguments if they exist args->GetNext(&rect); auto* const view = web_contents()->GetRenderWidgetHostView(); if (!view) { promise.Resolve(gfx::Image()); return handle; } // Capture full page if user doesn't specify a |rect|. const gfx::Size view_size = rect.IsEmpty() ? view->GetViewBounds().size() : rect.size(); // By default, the requested bitmap size is the view size in screen // coordinates. However, if there's more pixel detail available on the // current system, increase the requested bitmap size to capture it all. gfx::Size bitmap_size = view_size; const gfx::NativeView native_view = view->GetNativeView(); const float scale = display::Screen::GetScreen() ->GetDisplayNearestView(native_view) .device_scale_factor(); if (scale > 1.0f) bitmap_size = gfx::ScaleToCeiledSize(view_size, scale); view->CopyFromSurface(gfx::Rect(rect.origin(), view_size), bitmap_size, base::BindOnce(&OnCapturePageDone, std::move(promise))); return handle; } void WebContents::IncrementCapturerCount(gin::Arguments* args) { gfx::Size size; bool stay_hidden = false; // get size arguments if they exist args->GetNext(&size); // get stayHidden arguments if they exist args->GetNext(&stay_hidden); web_contents()->IncrementCapturerCount(size, stay_hidden); } void WebContents::DecrementCapturerCount(gin::Arguments* args) { bool stay_hidden = false; // get stayHidden arguments if they exist args->GetNext(&stay_hidden); web_contents()->DecrementCapturerCount(stay_hidden); } bool WebContents::IsBeingCaptured() { return web_contents()->IsBeingCaptured(); } void WebContents::OnCursorChanged(const content::WebCursor& webcursor) { const ui::Cursor& cursor = webcursor.cursor(); if (cursor.type() == ui::mojom::CursorType::kCustom) { Emit("cursor-changed", CursorTypeToString(cursor), gfx::Image::CreateFrom1xBitmap(cursor.custom_bitmap()), cursor.image_scale_factor(), gfx::Size(cursor.custom_bitmap().width(), cursor.custom_bitmap().height()), cursor.custom_hotspot()); } else { Emit("cursor-changed", CursorTypeToString(cursor)); } } bool WebContents::IsGuest() const { return type_ == Type::kWebView; } void WebContents::AttachToIframe(content::WebContents* embedder_web_contents, int embedder_frame_id) { if (guest_delegate_) guest_delegate_->AttachToIframe(embedder_web_contents, embedder_frame_id); } bool WebContents::IsOffScreen() const { #if BUILDFLAG(ENABLE_OSR) return type_ == Type::kOffScreen; #else return false; #endif } #if BUILDFLAG(ENABLE_OSR) void WebContents::OnPaint(const gfx::Rect& dirty_rect, const SkBitmap& bitmap) { Emit("paint", dirty_rect, gfx::Image::CreateFrom1xBitmap(bitmap)); } void WebContents::StartPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(true); } void WebContents::StopPainting() { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetPainting(false); } bool WebContents::IsPainting() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv && osr_wcv->IsPainting(); } void WebContents::SetFrameRate(int frame_rate) { auto* osr_wcv = GetOffScreenWebContentsView(); if (osr_wcv) osr_wcv->SetFrameRate(frame_rate); } int WebContents::GetFrameRate() const { auto* osr_wcv = GetOffScreenWebContentsView(); return osr_wcv ? osr_wcv->GetFrameRate() : 0; } #endif void WebContents::Invalidate() { if (IsOffScreen()) { #if BUILDFLAG(ENABLE_OSR) auto* osr_rwhv = GetOffScreenRenderWidgetHostView(); if (osr_rwhv) osr_rwhv->Invalidate(); #endif } else { auto* const window = owner_window(); if (window) window->Invalidate(); } } gfx::Size WebContents::GetSizeForNewRenderView(content::WebContents* wc) { if (IsOffScreen() && wc == web_contents()) { auto* relay = NativeWindowRelay::FromWebContents(web_contents()); if (relay) { auto* owner_window = relay->GetNativeWindow(); return owner_window ? owner_window->GetSize() : gfx::Size(); } } return gfx::Size(); } void WebContents::SetZoomLevel(double level) { zoom_controller_->SetZoomLevel(level); } double WebContents::GetZoomLevel() const { return zoom_controller_->GetZoomLevel(); } void WebContents::SetZoomFactor(gin_helper::ErrorThrower thrower, double factor) { if (factor < std::numeric_limits<double>::epsilon()) { thrower.ThrowError("'zoomFactor' must be a double greater than 0.0"); return; } auto level = blink::PageZoomFactorToZoomLevel(factor); SetZoomLevel(level); } double WebContents::GetZoomFactor() const { auto level = GetZoomLevel(); return blink::PageZoomLevelToZoomFactor(level); } void WebContents::SetTemporaryZoomLevel(double level) { zoom_controller_->SetTemporaryZoomLevel(level); } void WebContents::DoGetZoomLevel( electron::mojom::ElectronBrowser::DoGetZoomLevelCallback callback) { std::move(callback).Run(GetZoomLevel()); } std::vector<base::FilePath> WebContents::GetPreloadPaths() const { auto result = SessionPreferences::GetValidPreloads(GetBrowserContext()); if (auto* web_preferences = WebContentsPreferences::From(web_contents())) { base::FilePath preload; if (web_preferences->GetPreloadPath(&preload)) { result.emplace_back(preload); } } return result; } v8::Local<v8::Value> WebContents::GetWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->preference()); } v8::Local<v8::Value> WebContents::GetLastWebPreferences( v8::Isolate* isolate) const { auto* web_preferences = WebContentsPreferences::From(web_contents()); if (!web_preferences) return v8::Null(isolate); return gin::ConvertToV8(isolate, *web_preferences->last_preference()); } v8::Local<v8::Value> WebContents::GetOwnerBrowserWindow( v8::Isolate* isolate) const { if (owner_window()) return BrowserWindow::From(isolate, owner_window()); else return v8::Null(isolate); } v8::Local<v8::Value> WebContents::Session(v8::Isolate* isolate) { return v8::Local<v8::Value>::New(isolate, session_); } content::WebContents* WebContents::HostWebContents() const { if (!embedder_) return nullptr; return embedder_->web_contents(); } void WebContents::SetEmbedder(const WebContents* embedder) { if (embedder) { NativeWindow* owner_window = nullptr; auto* relay = NativeWindowRelay::FromWebContents(embedder->web_contents()); if (relay) { owner_window = relay->GetNativeWindow(); } if (owner_window) SetOwnerWindow(owner_window); content::RenderWidgetHostView* rwhv = web_contents()->GetRenderWidgetHostView(); if (rwhv) { rwhv->Hide(); rwhv->Show(); } } } void WebContents::SetDevToolsWebContents(const WebContents* devtools) { if (inspectable_web_contents_) inspectable_web_contents_->SetDevToolsWebContents(devtools->web_contents()); } v8::Local<v8::Value> WebContents::GetNativeView(v8::Isolate* isolate) const { gfx::NativeView ptr = web_contents()->GetNativeView(); auto buffer = node::Buffer::Copy(isolate, reinterpret_cast<char*>(&ptr), sizeof(gfx::NativeView)); if (buffer.IsEmpty()) return v8::Null(isolate); else return buffer.ToLocalChecked(); } v8::Local<v8::Value> WebContents::DevToolsWebContents(v8::Isolate* isolate) { if (devtools_web_contents_.IsEmpty()) return v8::Null(isolate); else return v8::Local<v8::Value>::New(isolate, devtools_web_contents_); } v8::Local<v8::Value> WebContents::Debugger(v8::Isolate* isolate) { if (debugger_.IsEmpty()) { auto handle = electron::api::Debugger::Create(isolate, web_contents()); debugger_.Reset(isolate, handle.ToV8()); } return v8::Local<v8::Value>::New(isolate, debugger_); } bool WebContents::WasInitiallyShown() { return initially_shown_; } content::RenderFrameHost* WebContents::MainFrame() { return web_contents()->GetMainFrame(); } void WebContents::GrantOriginAccess(const GURL& url) { content::ChildProcessSecurityPolicy::GetInstance()->GrantCommitOrigin( web_contents()->GetMainFrame()->GetProcess()->GetID(), url::Origin::Create(url)); } void WebContents::NotifyUserActivation() { auto* frame = web_contents()->GetMainFrame(); if (!frame) return; mojo::AssociatedRemote<mojom::ElectronRenderer> renderer; frame->GetRemoteAssociatedInterfaces()->GetInterface(&renderer); renderer->NotifyUserActivation(); } v8::Local<v8::Promise> WebContents::TakeHeapSnapshot( v8::Isolate* isolate, const base::FilePath& file_path) { gin_helper::Promise<void> promise(isolate); v8::Local<v8::Promise> handle = promise.GetHandle(); base::ThreadRestrictions::ScopedAllowIO allow_io; base::File file(file_path, base::File::FLAG_CREATE_ALWAYS | base::File::FLAG_WRITE); if (!file.IsValid()) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } auto* frame_host = web_contents()->GetMainFrame(); if (!frame_host) { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); return handle; } // This dance with `base::Owned` is to ensure that the interface stays alive // until the callback is called. Otherwise it would be closed at the end of // this function. auto electron_renderer = std::make_unique<mojo::AssociatedRemote<mojom::ElectronRenderer>>(); frame_host->GetRemoteAssociatedInterfaces()->GetInterface( electron_renderer.get()); auto* raw_ptr = electron_renderer.get(); (*raw_ptr)->TakeHeapSnapshot( mojo::WrapPlatformFile(base::ScopedPlatformFile(file.TakePlatformFile())), base::BindOnce( [](mojo::AssociatedRemote<mojom::ElectronRenderer>* ep, gin_helper::Promise<void> promise, bool success) { if (success) { promise.Resolve(); } else { promise.RejectWithErrorMessage("takeHeapSnapshot failed"); } }, base::Owned(std::move(electron_renderer)), std::move(promise))); return handle; } void WebContents::UpdatePreferredSize(content::WebContents* web_contents, const gfx::Size& pref_size) { Emit("preferred-size-changed", pref_size); } bool WebContents::CanOverscrollContent() { return false; } content::ColorChooser* WebContents::OpenColorChooser( content::WebContents* web_contents, SkColor color, const std::vector<blink::mojom::ColorSuggestionPtr>& suggestions) { #if BUILDFLAG(ENABLE_COLOR_CHOOSER) return chrome::ShowColorChooser(web_contents, color); #else return nullptr; #endif } std::unique_ptr<content::EyeDropper> WebContents::OpenEyeDropper( content::RenderFrameHost* frame, content::EyeDropperListener* listener) { return ShowEyeDropper(frame, listener); } void WebContents::RunFileChooser( content::RenderFrameHost* render_frame_host, scoped_refptr<content::FileSelectListener> listener, const blink::mojom::FileChooserParams& params) { if (!web_dialog_helper_) web_dialog_helper_ = std::make_unique<WebDialogHelper>(owner_window(), offscreen_); web_dialog_helper_->RunFileChooser(render_frame_host, std::move(listener), params); } void WebContents::EnumerateDirectory( content::WebContents* guest, scoped_refptr<content::FileSelectListener> listener, const base::FilePath& path) { if (!web_dialog_helper_) web_dialog_helper_ = std::make_unique<WebDialogHelper>(owner_window(), offscreen_); web_dialog_helper_->EnumerateDirectory(guest, std::move(listener), path); } bool WebContents::IsFullscreenForTabOrPending( const content::WebContents* source) { return html_fullscreen_; } blink::SecurityStyle WebContents::GetSecurityStyle( content::WebContents* web_contents, content::SecurityStyleExplanations* security_style_explanations) { SecurityStateTabHelper* helper = SecurityStateTabHelper::FromWebContents(web_contents); DCHECK(helper); return security_state::GetSecurityStyle(helper->GetSecurityLevel(), *helper->GetVisibleSecurityState(), security_style_explanations); } bool WebContents::TakeFocus(content::WebContents* source, bool reverse) { if (source && source->GetOutermostWebContents() == source) { // If this is the outermost web contents and the user has tabbed or // shift + tabbed through all the elements, reset the focus back to // the first or last element so that it doesn't stay in the body. source->FocusThroughTabTraversal(reverse); return true; } return false; } content::PictureInPictureResult WebContents::EnterPictureInPicture( content::WebContents* web_contents, const viz::SurfaceId& surface_id, const gfx::Size& natural_size) { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) return PictureInPictureWindowManager::GetInstance()->EnterPictureInPicture( web_contents, surface_id, natural_size); #else return content::PictureInPictureResult::kNotSupported; #endif } void WebContents::ExitPictureInPicture() { #if BUILDFLAG(ENABLE_PICTURE_IN_PICTURE) PictureInPictureWindowManager::GetInstance()->ExitPictureInPicture(); #endif } void WebContents::DevToolsSaveToFile(const std::string& url, const std::string& content, bool save_as) { base::FilePath path; auto it = saved_files_.find(url); if (it != saved_files_.end() && !save_as) { path = it->second; } else { file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.title = url; settings.default_path = base::FilePath::FromUTF8Unsafe(url); if (!file_dialog::ShowSaveDialogSync(settings, &path)) { base::Value url_value(url); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.canceledSaveURL", &url_value, nullptr, nullptr); return; } } saved_files_[url] = path; // Notify DevTools. base::Value url_value(url); base::Value file_system_path_value(path.AsUTF8Unsafe()); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.savedURL", &url_value, &file_system_path_value, nullptr); file_task_runner_->PostTask(FROM_HERE, base::BindOnce(&WriteToFile, path, content)); } void WebContents::DevToolsAppendToFile(const std::string& url, const std::string& content) { auto it = saved_files_.find(url); if (it == saved_files_.end()) return; // Notify DevTools. base::Value url_value(url); inspectable_web_contents_->CallClientFunction("DevToolsAPI.appendedToURL", &url_value, nullptr, nullptr); file_task_runner_->PostTask( FROM_HERE, base::BindOnce(&AppendToFile, it->second, content)); } void WebContents::DevToolsRequestFileSystems() { auto file_system_paths = GetAddedFileSystemPaths(GetDevToolsWebContents()); if (file_system_paths.empty()) { base::ListValue empty_file_system_value; inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &empty_file_system_value, nullptr, nullptr); return; } std::vector<FileSystem> file_systems; for (const auto& file_system_path : file_system_paths) { base::FilePath path = base::FilePath::FromUTF8Unsafe(file_system_path.first); std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); FileSystem file_system = CreateFileSystemStruct(GetDevToolsWebContents(), file_system_id, file_system_path.first, file_system_path.second); file_systems.push_back(file_system); } base::ListValue file_system_value; for (const auto& file_system : file_systems) file_system_value.Append(CreateFileSystemValue(file_system)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemsLoaded", &file_system_value, nullptr, nullptr); } void WebContents::DevToolsAddFileSystem( const std::string& type, const base::FilePath& file_system_path) { base::FilePath path = file_system_path; if (path.empty()) { std::vector<base::FilePath> paths; file_dialog::DialogSettings settings; settings.parent_window = owner_window(); settings.force_detached = offscreen_; settings.properties = file_dialog::OPEN_DIALOG_OPEN_DIRECTORY; if (!file_dialog::ShowOpenDialogSync(settings, &paths)) return; path = paths[0]; } std::string file_system_id = RegisterFileSystem(GetDevToolsWebContents(), path); if (IsDevToolsFileSystemAdded(GetDevToolsWebContents(), path.AsUTF8Unsafe())) return; FileSystem file_system = CreateFileSystemStruct( GetDevToolsWebContents(), file_system_id, path.AsUTF8Unsafe(), type); std::unique_ptr<base::DictionaryValue> file_system_value( CreateFileSystemValue(file_system)); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->SetWithoutPathExpansion(path.AsUTF8Unsafe(), std::make_unique<base::Value>(type)); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.fileSystemAdded", nullptr, file_system_value.get(), nullptr); } void WebContents::DevToolsRemoveFileSystem( const base::FilePath& file_system_path) { if (!inspectable_web_contents_) return; std::string path = file_system_path.AsUTF8Unsafe(); storage::IsolatedContext::GetInstance()->RevokeFileSystemByPath( file_system_path); auto* pref_service = GetPrefService(GetDevToolsWebContents()); DictionaryPrefUpdate update(pref_service, prefs::kDevToolsFileSystemPaths); update.Get()->RemoveWithoutPathExpansion(path, nullptr); base::Value file_system_path_value(path); inspectable_web_contents_->CallClientFunction("DevToolsAPI.fileSystemRemoved", &file_system_path_value, nullptr, nullptr); } void WebContents::DevToolsIndexPath( int request_id, const std::string& file_system_path, const std::string& excluded_folders_message) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsIndexingDone(request_id, file_system_path); return; } if (devtools_indexing_jobs_.count(request_id) != 0) return; std::vector<std::string> excluded_folders; std::unique_ptr<base::Value> parsed_excluded_folders = base::JSONReader::ReadDeprecated(excluded_folders_message); if (parsed_excluded_folders && parsed_excluded_folders->is_list()) { for (const base::Value& folder_path : parsed_excluded_folders->GetList()) { if (folder_path.is_string()) excluded_folders.push_back(folder_path.GetString()); } } devtools_indexing_jobs_[request_id] = scoped_refptr<DevToolsFileSystemIndexer::FileSystemIndexingJob>( devtools_file_system_indexer_->IndexPath( file_system_path, excluded_folders, base::BindRepeating( &WebContents::OnDevToolsIndexingWorkCalculated, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingWorked, weak_factory_.GetWeakPtr(), request_id, file_system_path), base::BindRepeating(&WebContents::OnDevToolsIndexingDone, weak_factory_.GetWeakPtr(), request_id, file_system_path))); } void WebContents::DevToolsStopIndexing(int request_id) { auto it = devtools_indexing_jobs_.find(request_id); if (it == devtools_indexing_jobs_.end()) return; it->second->Stop(); devtools_indexing_jobs_.erase(it); } void WebContents::DevToolsSearchInPath(int request_id, const std::string& file_system_path, const std::string& query) { if (!IsDevToolsFileSystemAdded(GetDevToolsWebContents(), file_system_path)) { OnDevToolsSearchCompleted(request_id, file_system_path, std::vector<std::string>()); return; } devtools_file_system_indexer_->SearchInPath( file_system_path, query, base::BindRepeating(&WebContents::OnDevToolsSearchCompleted, weak_factory_.GetWeakPtr(), request_id, file_system_path)); } #if defined(TOOLKIT_VIEWS) && !defined(OS_MAC) gfx::ImageSkia WebContents::GetDevToolsWindowIcon() { if (!owner_window()) return gfx::ImageSkia(); return owner_window()->GetWindowAppIcon(); } #endif #if defined(OS_LINUX) void WebContents::GetDevToolsWindowWMClass(std::string* name, std::string* class_name) { *class_name = Browser::Get()->GetName(); *name = base::ToLowerASCII(*class_name); } #endif void WebContents::OnDevToolsIndexingWorkCalculated( int request_id, const std::string& file_system_path, int total_work) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value total_work_value(total_work); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingTotalWorkCalculated", &request_id_value, &file_system_path_value, &total_work_value); } void WebContents::OnDevToolsIndexingWorked(int request_id, const std::string& file_system_path, int worked) { base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); base::Value worked_value(worked); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingWorked", &request_id_value, &file_system_path_value, &worked_value); } void WebContents::OnDevToolsIndexingDone(int request_id, const std::string& file_system_path) { devtools_indexing_jobs_.erase(request_id); base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.indexingDone", &request_id_value, &file_system_path_value, nullptr); } void WebContents::OnDevToolsSearchCompleted( int request_id, const std::string& file_system_path, const std::vector<std::string>& file_paths) { base::ListValue file_paths_value; for (const auto& file_path : file_paths) { file_paths_value.AppendString(file_path); } base::Value request_id_value(request_id); base::Value file_system_path_value(file_system_path); inspectable_web_contents_->CallClientFunction( "DevToolsAPI.searchCompleted", &request_id_value, &file_system_path_value, &file_paths_value); } void WebContents::SetHtmlApiFullscreen(bool enter_fullscreen) { // Window is already in fullscreen mode, save the state. if (enter_fullscreen && owner_window_->IsFullscreen()) { native_fullscreen_ = true; html_fullscreen_ = true; return; } // Exit html fullscreen state but not window's fullscreen mode. if (!enter_fullscreen && native_fullscreen_) { html_fullscreen_ = false; return; } // Set fullscreen on window if allowed. auto* web_preferences = WebContentsPreferences::From(GetWebContents()); bool html_fullscreenable = web_preferences ? !web_preferences->IsEnabled( options::kDisableHtmlFullscreenWindowResize) : true; if (html_fullscreenable) { owner_window_->SetFullScreen(enter_fullscreen); } html_fullscreen_ = enter_fullscreen; native_fullscreen_ = false; } // static v8::Local<v8::ObjectTemplate> WebContents::FillObjectTemplate( v8::Isolate* isolate, v8::Local<v8::ObjectTemplate> templ) { gin::InvokerOptions options; options.holder_is_first_argument = true; options.holder_type = "WebContents"; templ->Set( gin::StringToSymbol(isolate, "isDestroyed"), gin::CreateFunctionTemplate( isolate, base::BindRepeating(&gin_helper::Destroyable::IsDestroyed), options)); templ->Set( gin::StringToSymbol(isolate, "destroy"), gin::CreateFunctionTemplate( isolate, base::BindRepeating([](gin::Handle<WebContents> handle) { delete handle.get(); }), options)); // We use gin_helper::ObjectTemplateBuilder instead of // gin::ObjectTemplateBuilder here to handle the fact that WebContents is // destroyable. return gin_helper::ObjectTemplateBuilder(isolate, templ) .SetMethod("getBackgroundThrottling", &WebContents::GetBackgroundThrottling) .SetMethod("setBackgroundThrottling", &WebContents::SetBackgroundThrottling) .SetMethod("getProcessId", &WebContents::GetProcessID) .SetMethod("getOSProcessId", &WebContents::GetOSProcessID) .SetMethod("equal", &WebContents::Equal) .SetMethod("_loadURL", &WebContents::LoadURL) .SetMethod("downloadURL", &WebContents::DownloadURL) .SetMethod("_getURL", &WebContents::GetURL) .SetMethod("getTitle", &WebContents::GetTitle) .SetMethod("isLoading", &WebContents::IsLoading) .SetMethod("isLoadingMainFrame", &WebContents::IsLoadingMainFrame) .SetMethod("isWaitingForResponse", &WebContents::IsWaitingForResponse) .SetMethod("_stop", &WebContents::Stop) .SetMethod("_goBack", &WebContents::GoBack) .SetMethod("_goForward", &WebContents::GoForward) .SetMethod("_goToOffset", &WebContents::GoToOffset) .SetMethod("isCrashed", &WebContents::IsCrashed) .SetMethod("forcefullyCrashRenderer", &WebContents::ForcefullyCrashRenderer) .SetMethod("setUserAgent", &WebContents::SetUserAgent) .SetMethod("getUserAgent", &WebContents::GetUserAgent) .SetMethod("savePage", &WebContents::SavePage) .SetMethod("openDevTools", &WebContents::OpenDevTools) .SetMethod("closeDevTools", &WebContents::CloseDevTools) .SetMethod("isDevToolsOpened", &WebContents::IsDevToolsOpened) .SetMethod("isDevToolsFocused", &WebContents::IsDevToolsFocused) .SetMethod("enableDeviceEmulation", &WebContents::EnableDeviceEmulation) .SetMethod("disableDeviceEmulation", &WebContents::DisableDeviceEmulation) .SetMethod("toggleDevTools", &WebContents::ToggleDevTools) .SetMethod("inspectElement", &WebContents::InspectElement) .SetMethod("setIgnoreMenuShortcuts", &WebContents::SetIgnoreMenuShortcuts) .SetMethod("setAudioMuted", &WebContents::SetAudioMuted) .SetMethod("isAudioMuted", &WebContents::IsAudioMuted) .SetMethod("isCurrentlyAudible", &WebContents::IsCurrentlyAudible) .SetMethod("undo", &WebContents::Undo) .SetMethod("redo", &WebContents::Redo) .SetMethod("cut", &WebContents::Cut) .SetMethod("copy", &WebContents::Copy) .SetMethod("paste", &WebContents::Paste) .SetMethod("pasteAndMatchStyle", &WebContents::PasteAndMatchStyle) .SetMethod("delete", &WebContents::Delete) .SetMethod("selectAll", &WebContents::SelectAll) .SetMethod("unselect", &WebContents::Unselect) .SetMethod("replace", &WebContents::Replace) .SetMethod("replaceMisspelling", &WebContents::ReplaceMisspelling) .SetMethod("findInPage", &WebContents::FindInPage) .SetMethod("stopFindInPage", &WebContents::StopFindInPage) .SetMethod("focus", &WebContents::Focus) .SetMethod("isFocused", &WebContents::IsFocused) .SetMethod("_send", &WebContents::SendIPCMessage) .SetMethod("sendInputEvent", &WebContents::SendInputEvent) .SetMethod("beginFrameSubscription", &WebContents::BeginFrameSubscription) .SetMethod("endFrameSubscription", &WebContents::EndFrameSubscription) .SetMethod("startDrag", &WebContents::StartDrag) .SetMethod("attachToIframe", &WebContents::AttachToIframe) .SetMethod("detachFromOuterFrame", &WebContents::DetachFromOuterFrame) .SetMethod("isOffscreen", &WebContents::IsOffScreen) #if BUILDFLAG(ENABLE_OSR) .SetMethod("startPainting", &WebContents::StartPainting) .SetMethod("stopPainting", &WebContents::StopPainting) .SetMethod("isPainting", &WebContents::IsPainting) .SetMethod("setFrameRate", &WebContents::SetFrameRate) .SetMethod("getFrameRate", &WebContents::GetFrameRate) #endif .SetMethod("invalidate", &WebContents::Invalidate) .SetMethod("setZoomLevel", &WebContents::SetZoomLevel) .SetMethod("getZoomLevel", &WebContents::GetZoomLevel) .SetMethod("setZoomFactor", &WebContents::SetZoomFactor) .SetMethod("getZoomFactor", &WebContents::GetZoomFactor) .SetMethod("getType", &WebContents::GetType) .SetMethod("_getPreloadPaths", &WebContents::GetPreloadPaths) .SetMethod("getWebPreferences", &WebContents::GetWebPreferences) .SetMethod("getLastWebPreferences", &WebContents::GetLastWebPreferences) .SetMethod("getOwnerBrowserWindow", &WebContents::GetOwnerBrowserWindow) .SetMethod("inspectServiceWorker", &WebContents::InspectServiceWorker) .SetMethod("inspectSharedWorker", &WebContents::InspectSharedWorker) .SetMethod("inspectSharedWorkerById", &WebContents::InspectSharedWorkerById) .SetMethod("getAllSharedWorkers", &WebContents::GetAllSharedWorkers) #if BUILDFLAG(ENABLE_PRINTING) .SetMethod("_print", &WebContents::Print) .SetMethod("_printToPDF", &WebContents::PrintToPDF) #endif .SetMethod("_setNextChildWebPreferences", &WebContents::SetNextChildWebPreferences) .SetMethod("addWorkSpace", &WebContents::AddWorkSpace) .SetMethod("removeWorkSpace", &WebContents::RemoveWorkSpace) .SetMethod("showDefinitionForSelection", &WebContents::ShowDefinitionForSelection) .SetMethod("copyImageAt", &WebContents::CopyImageAt) .SetMethod("capturePage", &WebContents::CapturePage) .SetMethod("setEmbedder", &WebContents::SetEmbedder) .SetMethod("setDevToolsWebContents", &WebContents::SetDevToolsWebContents) .SetMethod("getNativeView", &WebContents::GetNativeView) .SetMethod("incrementCapturerCount", &WebContents::IncrementCapturerCount) .SetMethod("decrementCapturerCount", &WebContents::DecrementCapturerCount) .SetMethod("isBeingCaptured", &WebContents::IsBeingCaptured) .SetMethod("setWebRTCIPHandlingPolicy", &WebContents::SetWebRTCIPHandlingPolicy) .SetMethod("getWebRTCIPHandlingPolicy", &WebContents::GetWebRTCIPHandlingPolicy) .SetMethod("_grantOriginAccess", &WebContents::GrantOriginAccess) .SetMethod("takeHeapSnapshot", &WebContents::TakeHeapSnapshot) .SetProperty("id", &WebContents::ID) .SetProperty("session", &WebContents::Session) .SetProperty("hostWebContents", &WebContents::HostWebContents) .SetProperty("devToolsWebContents", &WebContents::DevToolsWebContents) .SetProperty("debugger", &WebContents::Debugger) .SetProperty("_initiallyShown", &WebContents::WasInitiallyShown) .SetProperty("mainFrame", &WebContents::MainFrame) .Build(); } const char* WebContents::GetTypeName() { return "WebContents"; } ElectronBrowserContext* WebContents::GetBrowserContext() const { return static_cast<ElectronBrowserContext*>( web_contents()->GetBrowserContext()); } // static gin::Handle<WebContents> WebContents::New( v8::Isolate* isolate, const gin_helper::Dictionary& options) { gin::Handle<WebContents> handle = gin::CreateHandle(isolate, new WebContents(isolate, options)); gin_helper::CallMethod(isolate, handle.get(), "_init"); return handle; } // static gin::Handle<WebContents> WebContents::CreateAndTake( v8::Isolate* isolate, std::unique_ptr<content::WebContents> web_contents, Type type) { gin::Handle<WebContents> handle = gin::CreateHandle( isolate, new WebContents(isolate, std::move(web_contents), type)); gin_helper::CallMethod(isolate, handle.get(), "_init"); return handle; } // static WebContents* WebContents::From(content::WebContents* web_contents) { if (!web_contents) return nullptr; auto* data = static_cast<UserDataLink*>( web_contents->GetUserData(kElectronApiWebContentsKey)); return data ? data->web_contents.get() : nullptr; } // static gin::Handle<WebContents> WebContents::FromOrCreate( v8::Isolate* isolate, content::WebContents* web_contents) { WebContents* api_web_contents = From(web_contents); if (!api_web_contents) { api_web_contents = new WebContents(isolate, web_contents); gin_helper::CallMethod(isolate, api_web_contents, "_init"); } return gin::CreateHandle(isolate, api_web_contents); } // static gin::Handle<WebContents> WebContents::CreateFromWebPreferences( v8::Isolate* isolate, const gin_helper::Dictionary& web_preferences) { // Check if webPreferences has |webContents| option. gin::Handle<WebContents> web_contents; if (web_preferences.GetHidden("webContents", &web_contents) && !web_contents.IsEmpty()) { // Set webPreferences from options if using an existing webContents. // These preferences will be used when the webContent launches new // render processes. auto* existing_preferences = WebContentsPreferences::From(web_contents->web_contents()); base::DictionaryValue web_preferences_dict; if (gin::ConvertFromV8(isolate, web_preferences.GetHandle(), &web_preferences_dict)) { existing_preferences->Clear(); existing_preferences->Merge(web_preferences_dict); } } else { // Create one if not. web_contents = WebContents::New(isolate, web_preferences); } return web_contents; } // static WebContents* WebContents::FromID(int32_t id) { return GetAllWebContents().Lookup(id); } // static gin::WrapperInfo WebContents::kWrapperInfo = {gin::kEmbedderNativeGin}; } // namespace api } // namespace electron namespace { using electron::api::GetAllWebContents; using electron::api::WebContents; gin::Handle<WebContents> WebContentsFromID(v8::Isolate* isolate, int32_t id) { WebContents* contents = WebContents::FromID(id); return contents ? gin::CreateHandle(isolate, contents) : gin::Handle<WebContents>(); } std::vector<gin::Handle<WebContents>> GetAllWebContentsAsV8( v8::Isolate* isolate) { std::vector<gin::Handle<WebContents>> list; for (auto iter = base::IDMap<WebContents*>::iterator(&GetAllWebContents()); !iter.IsAtEnd(); iter.Advance()) { list.push_back(gin::CreateHandle(isolate, iter.GetCurrentValue())); } return list; } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { v8::Isolate* isolate = context->GetIsolate(); gin_helper::Dictionary dict(isolate, exports); dict.Set("WebContents", WebContents::GetConstructor(context)); dict.SetMethod("fromId", &WebContentsFromID); dict.SetMethod("getAllWebContents", &GetAllWebContentsAsV8); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_browser_web_contents, Initialize)
#include "hsm/hsm.h" #include <boost/hana.hpp> #include <gtest/gtest.h> #include <future> #include <memory> namespace { // States struct S1 { }; struct S2 { }; // Events struct e1 { e1(const std::shared_ptr<std::promise<void>>& called) : called(called) { } std::shared_ptr<std::promise<void>> called; }; struct e2 { }; struct e3 { }; struct e4 { }; // Guards const auto g1 = [](auto) { return true; }; const auto g2 = [](auto) { return false; }; const auto g3 = [](auto) { return true; }; // Actions const auto a1 = [](auto event) {}; const auto a2 = [](auto event) { event.called->set_value(); }; using namespace ::testing; using namespace boost::hana; struct SubState { constexpr auto make_transition_table() { // clang-format off return hsm::transition_table( hsm::transition(S1 {}, hsm::event<e1> {}, g1, a2, S1 {}) ); // clang-format on } constexpr auto initial_state() { return hsm::initial(S1 {}); } }; struct MainState { constexpr auto make_transition_table() { // clang-format off return hsm::transition_table( hsm::transition(S1 {}, hsm::event<e1> {}, g1, a2, S1 {}), hsm::transition(S1 {}, hsm::event<e2> {}, g1, a1, SubState {}), hsm::transition(S1 {}, hsm::event<e3> {}, g2, a1, S2 {}), hsm::transition(S1 {}, hsm::event<e4> {}, g3, a1, S2 {}) ); // clang-format on } constexpr auto initial_state() { return hsm::initial(S1 {}); } }; } class GuardsActionsTests : public Test { protected: hsm::Sm<MainState> sm; }; TEST_F(GuardsActionsTests, should_call_action) { auto actionCalled = std::make_shared<std::promise<void>>(); sm.process_event(e1 { actionCalled }); ASSERT_EQ( std::future_status::ready, actionCalled->get_future().wait_for(std::chrono::seconds(1))); } TEST_F(GuardsActionsTests, should_call_substate_action) { auto actionCalled = std::make_shared<std::promise<void>>(); sm.process_event(e2 {}); sm.process_event(e1 { actionCalled }); ASSERT_EQ( std::future_status::ready, actionCalled->get_future().wait_for(std::chrono::seconds(1))); } TEST_F(GuardsActionsTests, should_block_transition_guard) { ASSERT_TRUE(sm.is(S1 {})); sm.process_event(e3 {}); ASSERT_TRUE(sm.is(S1 {})); } TEST_F(GuardsActionsTests, should_not_block_transition_by_guard) { ASSERT_TRUE(sm.is(S1 {})); sm.process_event(e4 {}); ASSERT_TRUE(sm.is(S2 {})); }
#include "AppDelegate.h" #include "WorldScene.h" USING_NS_CC; static cocos2d::Size designResolutionSize = cocos2d::Size(1024, 768); static cocos2d::Size smallResolutionSize = cocos2d::Size(480, 320); static cocos2d::Size mediumResolutionSize = cocos2d::Size(1024, 768); static cocos2d::Size largeResolutionSize = cocos2d::Size(2048, 1536); AppDelegate::AppDelegate() { } AppDelegate::~AppDelegate() { } // if you want a different context, modify the value of glContextAttrs // it will affect all platforms void AppDelegate::initGLContextAttrs() { // set OpenGL context attributes: red,green,blue,alpha,depth,stencil GLContextAttrs glContextAttrs = {8, 8, 8, 8, 24, 8}; GLView::setGLContextAttrs(glContextAttrs); } // if you want to use the package manager to install more packages, // don't modify or remove this function static int register_all_packages() { return 0; //flag for packages manager } bool AppDelegate::applicationDidFinishLaunching() { // initialize director auto director = Director::getInstance(); auto glview = director->getOpenGLView(); if(!glview) { #if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32) || (CC_TARGET_PLATFORM == CC_PLATFORM_MAC) || (CC_TARGET_PLATFORM == CC_PLATFORM_LINUX) glview = GLViewImpl::createWithRect("gray", cocos2d::Rect(0, 0, designResolutionSize.width, designResolutionSize.height), 1.0f, true); #else glview = GLViewImpl::create("gray"); #endif director->setOpenGLView(glview); } #ifdef _DEBUG // turn on display FPS director->setDisplayStats(true); #endif // set FPS. the default value is 1.0/60 if you don't call this director->setAnimationInterval(1.0f / 60); // Set the design resolution glview->setDesignResolutionSize(designResolutionSize.width, designResolutionSize.height, ResolutionPolicy::NO_BORDER); auto frameSize = glview->getFrameSize(); // if the frame's height is larger than the height of medium size. if (frameSize.height > mediumResolutionSize.height) { director->setContentScaleFactor(MIN(largeResolutionSize.height/designResolutionSize.height, largeResolutionSize.width/designResolutionSize.width)); } // if the frame's height is larger than the height of small size. else if (frameSize.height > smallResolutionSize.height) { director->setContentScaleFactor(MIN(mediumResolutionSize.height/designResolutionSize.height, mediumResolutionSize.width/designResolutionSize.width)); } // if the frame's height is smaller than the height of medium size. else { director->setContentScaleFactor(MIN(smallResolutionSize.height/designResolutionSize.height, smallResolutionSize.width/designResolutionSize.width)); } register_all_packages(); // create a scene. it's an autorelease object auto scene = World::createScene(); // run director->runWithScene(scene); return true; } // This function will be called when the app is inactive. Note, when receiving a phone call it is invoked. void AppDelegate::applicationDidEnterBackground() { Director::getInstance()->stopAnimation(); // if you use SimpleAudioEngine, it must be paused // SimpleAudioEngine::getInstance()->pauseBackgroundMusic(); } // this function will be called when the app is active again void AppDelegate::applicationWillEnterForeground() { Director::getInstance()->startAnimation(); // if you use SimpleAudioEngine, it must resume here // SimpleAudioEngine::getInstance()->resumeBackgroundMusic(); }
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoColorSet_Christmas_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass DinoColorSet_Christmas.DinoColorSet_Christmas_C // 0x0000 (0x0268 - 0x0268) class UDinoColorSet_Christmas_C : public UPrimalColorSet { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass DinoColorSet_Christmas.DinoColorSet_Christmas_C"); return ptr; } void ExecuteUbergraph_DinoColorSet_Christmas(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "base/threading/platform_thread.h" #include <errno.h> #include <pthread.h> #include <sched.h> #include <stddef.h> #include <stdint.h> #include <sys/time.h> #include <sys/types.h> #include <unistd.h> #include <memory> #include "base/debug/activity_tracker.h" #include "base/lazy_instance.h" #include "base/logging.h" #include "base/no_destructor.h" #include "base/threading/platform_thread_internal_posix.h" #include "base/threading/scoped_blocking_call.h" #include "base/threading/thread_id_name_manager.h" #include "build/build_config.h" #if !defined(OS_APPLE) && !defined(OS_FUCHSIA) && !defined(OS_NACL) #include "base/posix/can_lower_nice_to.h" #endif #if defined(OS_LINUX) || defined(OS_CHROMEOS) #include <sys/syscall.h> #endif #if defined(OS_FUCHSIA) #include <zircon/process.h> #else #include <sys/resource.h> #endif namespace base { void InitThreading(); void TerminateOnThread(); size_t GetDefaultThreadStackSize(const pthread_attr_t& attributes); namespace { struct ThreadParams { ThreadParams() : delegate(nullptr), joinable(false), priority(ThreadPriority::NORMAL) {} PlatformThread::Delegate* delegate; bool joinable; ThreadPriority priority; }; void* ThreadFunc(void* params) { PlatformThread::Delegate* delegate = nullptr; { std::unique_ptr<ThreadParams> thread_params( static_cast<ThreadParams*>(params)); delegate = thread_params->delegate; if (!thread_params->joinable) base::ThreadRestrictions::SetSingletonAllowed(false); #if !defined(OS_NACL) #if defined(OS_APPLE) PlatformThread::SetCurrentThreadRealtimePeriodValue( PlatformThread::GetRealtimePeriod(delegate)); #endif // Threads on linux/android may inherit their priority from the thread // where they were created. This explicitly sets the priority of all new // threads. PlatformThread::SetCurrentThreadPriority(thread_params->priority); #endif } ThreadIdNameManager::GetInstance()->RegisterThread( PlatformThread::CurrentHandle().platform_handle(), PlatformThread::CurrentId()); delegate->ThreadMain(); ThreadIdNameManager::GetInstance()->RemoveName( PlatformThread::CurrentHandle().platform_handle(), PlatformThread::CurrentId()); base::TerminateOnThread(); return nullptr; } bool CreateThread(size_t stack_size, bool joinable, PlatformThread::Delegate* delegate, PlatformThreadHandle* thread_handle, ThreadPriority priority) { DCHECK(thread_handle); base::InitThreading(); pthread_attr_t attributes; pthread_attr_init(&attributes); // Pthreads are joinable by default, so only specify the detached // attribute if the thread should be non-joinable. if (!joinable) pthread_attr_setdetachstate(&attributes, PTHREAD_CREATE_DETACHED); // Get a better default if available. if (stack_size == 0) stack_size = base::GetDefaultThreadStackSize(attributes); if (stack_size > 0) pthread_attr_setstacksize(&attributes, stack_size); std::unique_ptr<ThreadParams> params(new ThreadParams); params->delegate = delegate; params->joinable = joinable; params->priority = priority; pthread_t handle; int err = pthread_create(&handle, &attributes, ThreadFunc, params.get()); bool success = !err; if (success) { // ThreadParams should be deleted on the created thread after used. ignore_result(params.release()); } else { // Value of |handle| is undefined if pthread_create fails. handle = 0; errno = err; PLOG(ERROR) << "pthread_create"; } *thread_handle = PlatformThreadHandle(handle); pthread_attr_destroy(&attributes); return success; } #if defined(OS_LINUX) || defined(OS_CHROMEOS) // Store the thread ids in local storage since calling the SWI can be // expensive and PlatformThread::CurrentId is used liberally. Clear // the stored value after a fork() because forking changes the thread // id. Forking without going through fork() (e.g. clone()) is not // supported, but there is no known usage. Using thread_local is // fine here (despite being banned) since it is going to be allowed // but is blocked on a clang bug for Mac (https://crbug.com/829078) // and we can't use ThreadLocalStorage because of re-entrancy due to // CHECK/DCHECKs. thread_local pid_t g_thread_id = -1; class InitAtFork { public: InitAtFork() { pthread_atfork(nullptr, nullptr, internal::ClearTidCache); } }; #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) } // namespace #if defined(OS_LINUX) || defined(OS_CHROMEOS) namespace internal { void ClearTidCache() { g_thread_id = -1; } } // namespace internal #endif // defined(OS_LINUX) || defined(OS_CHROMEOS) // static PlatformThreadId PlatformThread::CurrentId() { // Pthreads doesn't have the concept of a thread ID, so we have to reach down // into the kernel. #if defined(OS_APPLE) return pthread_mach_thread_np(pthread_self()); #elif defined(OS_LINUX) || defined(OS_CHROMEOS) static NoDestructor<InitAtFork> init_at_fork; if (g_thread_id == -1) { g_thread_id = syscall(__NR_gettid); } else { DCHECK_EQ(g_thread_id, syscall(__NR_gettid)) << "Thread id stored in TLS is different from thread id returned by " "the system. It is likely that the process was forked without going " "through fork()."; } return g_thread_id; #elif defined(OS_ANDROID) return gettid(); #elif defined(OS_FUCHSIA) return zx_thread_self(); #elif defined(OS_SOLARIS) || defined(OS_QNX) return pthread_self(); #elif defined(OS_NACL) && defined(__GLIBC__) return pthread_self(); #elif defined(OS_NACL) && !defined(__GLIBC__) // Pointers are 32-bits in NaCl. return reinterpret_cast<int32_t>(pthread_self()); #elif defined(OS_POSIX) && defined(OS_AIX) return pthread_self(); #elif defined(OS_POSIX) && !defined(OS_AIX) return reinterpret_cast<int64_t>(pthread_self()); #endif } // static PlatformThreadRef PlatformThread::CurrentRef() { return PlatformThreadRef(pthread_self()); } // static PlatformThreadHandle PlatformThread::CurrentHandle() { return PlatformThreadHandle(pthread_self()); } // static void PlatformThread::YieldCurrentThread() { sched_yield(); } // static void PlatformThread::Sleep(TimeDelta duration) { struct timespec sleep_time, remaining; // Break the duration into seconds and nanoseconds. // NOTE: TimeDelta's microseconds are int64s while timespec's // nanoseconds are longs, so this unpacking must prevent overflow. sleep_time.tv_sec = duration.InSeconds(); duration -= TimeDelta::FromSeconds(sleep_time.tv_sec); sleep_time.tv_nsec = duration.InMicroseconds() * 1000; // nanoseconds while (nanosleep(&sleep_time, &remaining) == -1 && errno == EINTR) sleep_time = remaining; } // static const char* PlatformThread::GetName() { return ThreadIdNameManager::GetInstance()->GetName(CurrentId()); } // static bool PlatformThread::CreateWithPriority(size_t stack_size, Delegate* delegate, PlatformThreadHandle* thread_handle, ThreadPriority priority) { return CreateThread(stack_size, true /* joinable thread */, delegate, thread_handle, priority); } // static bool PlatformThread::CreateNonJoinable(size_t stack_size, Delegate* delegate) { return CreateNonJoinableWithPriority(stack_size, delegate, ThreadPriority::NORMAL); } // static bool PlatformThread::CreateNonJoinableWithPriority(size_t stack_size, Delegate* delegate, ThreadPriority priority) { PlatformThreadHandle unused; bool result = CreateThread(stack_size, false /* non-joinable thread */, delegate, &unused, priority); return result; } // static void PlatformThread::Join(PlatformThreadHandle thread_handle) { // Record the event that this thread is blocking upon (for hang diagnosis). base::debug::ScopedThreadJoinActivity thread_activity(&thread_handle); // Joining another thread may block the current thread for a long time, since // the thread referred to by |thread_handle| may still be running long-lived / // blocking tasks. base::internal::ScopedBlockingCallWithBaseSyncPrimitives scoped_blocking_call( FROM_HERE, base::BlockingType::MAY_BLOCK); CHECK_EQ(0, pthread_join(thread_handle.platform_handle(), nullptr)); } // static void PlatformThread::Detach(PlatformThreadHandle thread_handle) { CHECK_EQ(0, pthread_detach(thread_handle.platform_handle())); } // Mac and Fuchsia have their own Set/GetCurrentThreadPriority() // implementations. #if !defined(OS_APPLE) && !defined(OS_FUCHSIA) // static bool PlatformThread::CanIncreaseThreadPriority(ThreadPriority priority) { #if defined(OS_NACL) return false; #else auto platform_specific_ability = internal::CanIncreaseCurrentThreadPriorityForPlatform(priority); if (platform_specific_ability) return platform_specific_ability.value(); return internal::CanLowerNiceTo( internal::ThreadPriorityToNiceValue(priority)); #endif // defined(OS_NACL) } // static void PlatformThread::SetCurrentThreadPriorityImpl(ThreadPriority priority) { #if defined(OS_NACL) NOTIMPLEMENTED(); #else if (internal::SetCurrentThreadPriorityForPlatform(priority)) return; // setpriority(2) should change the whole thread group's (i.e. process) // priority. However, as stated in the bugs section of // http://man7.org/linux/man-pages/man2/getpriority.2.html: "under the current // Linux/NPTL implementation of POSIX threads, the nice value is a per-thread // attribute". Also, 0 is prefered to the current thread id since it is // equivalent but makes sandboxing easier (https://crbug.com/399473). const int nice_setting = internal::ThreadPriorityToNiceValue(priority); if (setpriority(PRIO_PROCESS, 0, nice_setting)) { DVPLOG(1) << "Failed to set nice value of thread (" << PlatformThread::CurrentId() << ") to " << nice_setting; } #endif // defined(OS_NACL) } // static ThreadPriority PlatformThread::GetCurrentThreadPriority() { #if defined(OS_NACL) NOTIMPLEMENTED(); return ThreadPriority::NORMAL; #else // Mirrors SetCurrentThreadPriority()'s implementation. auto platform_specific_priority = internal::GetCurrentThreadPriorityForPlatform(); if (platform_specific_priority) return platform_specific_priority.value(); // Need to clear errno before calling getpriority(): // http://man7.org/linux/man-pages/man2/getpriority.2.html errno = 0; int nice_value = getpriority(PRIO_PROCESS, 0); if (errno != 0) { DVPLOG(1) << "Failed to get nice value of thread (" << PlatformThread::CurrentId() << ")"; return ThreadPriority::NORMAL; } return internal::NiceValueToThreadPriority(nice_value); #endif // !defined(OS_NACL) } #endif // !defined(OS_APPLE) && !defined(OS_FUCHSIA) // static size_t PlatformThread::GetDefaultThreadStackSize() { pthread_attr_t attributes; pthread_attr_init(&attributes); return base::GetDefaultThreadStackSize(attributes); } } // namespace base
// NOLINT(legal/copyright) // SYMBOL "file_slurp" template <typename T1> int casadi_file_slurp(const char* fname, casadi_int n, T1* x) { casadi_int i; FILE *fp; fp = fopen(fname, "r"); if (!fp) return 1; for (i=0;i<n;++i) { if (fscanf(fp, "%lg", x++)<=0) return 2; } fclose(fp); return 0; }
#define WIN32_LEAN_AND_MEAN #include <windows.h> class SavedWindowData { public: SavedWindowData(); void Save(HWND hwnd, int numMonitors); void Restore(int numMonitors); bool IsStillUsed() const; bool CheckUnusedCount(); private: static const int MAX_MONITORS = 5; static const int MIN_MONITORS = 2; void ReportAction(const TCHAR* action, const WINDOWPLACEMENT& placement, int numMonitors); int _unusedCount; WINDOWPLACEMENT _windowPlacement[MAX_MONITORS - MIN_MONITORS + 1]; HWND _hwnd; TCHAR _wndClass[64]; // window class, for verification. };
/* * Copyright (C) 2005 - 2012 MaNGOS <http://www.getmangos.com/> * * Copyright (C) 2008 - 2012 Trinity <http://www.trinitycore.org/> * * Copyright (C) 2010 - 2012 ProjectSkyfire <http://www.projectskyfire.org/> * * Copyright (C) 2011 - 2012 ArkCORE <http://www.arkania.net/> * * 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 */ #include "BoundingIntervalHierarchy.h" void BIH::buildHierarchy(std::vector<uint32> &tempTree, buildData &dat, BuildStats &stats) { // create space for the first node tempTree.push_back(3 << 30); // dummy leaf tempTree.insert(tempTree.end(), 2, 0); //tempTree.add(0); // seed bbox AABound gridBox = { bounds.low(), bounds.high() }; AABound nodeBox = gridBox; // seed subdivide function subdivide(0, dat.numPrims - 1, tempTree, dat, gridBox, nodeBox, 0, 1, stats); } void BIH::subdivide(int left, int right, std::vector<uint32> &tempTree, buildData &dat, AABound &gridBox, AABound &nodeBox, int nodeIndex, int depth, BuildStats &stats) { if ((right - left + 1) <= dat.maxPrims || depth >= MAX_STACK_SIZE) { // write leaf node stats.updateLeaf(depth, right - left + 1); createNode(tempTree, nodeIndex, left, right); return; } // calculate extents int axis = -1, prevAxis, rightOrig; float clipL = G3D::fnan(), clipR = G3D::fnan(), prevClip = G3D::fnan(); float split = G3D::fnan(), prevSplit; bool wasLeft = true; while (true) { prevAxis = axis; prevSplit = split; // perform quick consistency checks Vector3 d(gridBox.hi - gridBox.lo); if (d.x < 0 || d.y < 0 || d.z < 0) throw std::logic_error("negative node extents"); for (int i = 0; i < 3; i++) { if (nodeBox.hi[i] < gridBox.lo[i] || nodeBox.lo[i] > gridBox.hi[i]) { //UI.printError(Module.ACCEL, "Reached tree area in error - discarding node with: %d objects", right - left + 1); throw std::logic_error("invalid node overlap"); } } // find longest axis axis = d.primaryAxis(); split = 0.5f * (gridBox.lo[axis] + gridBox.hi[axis]); // partition L/R subsets clipL = -G3D::inf(); clipR = G3D::inf(); rightOrig = right; // save this for later float nodeL = G3D::inf(); float nodeR = -G3D::inf(); for (int i = left; i <= right;) { int obj = dat.indices[i]; float minb = dat.primBound[obj].low()[axis]; float maxb = dat.primBound[obj].high()[axis]; float center = (minb + maxb) * 0.5f; if (center <= split) { // stay left i++; if (clipL < maxb) clipL = maxb; } else { // move to the right most int t = dat.indices[i]; dat.indices[i] = dat.indices[right]; dat.indices[right] = t; right--; if (clipR > minb) clipR = minb; } nodeL = std::min(nodeL, minb); nodeR = std::max(nodeR, maxb); } // check for empty space if (nodeL > nodeBox.lo[axis] && nodeR < nodeBox.hi[axis]) { float nodeBoxW = nodeBox.hi[axis] - nodeBox.lo[axis]; float nodeNewW = nodeR - nodeL; // node box is too big compare to space occupied by primitives? if (1.3f * nodeNewW < nodeBoxW) { stats.updateBVH2(); int nextIndex = tempTree.size(); // allocate child tempTree.push_back(0); tempTree.push_back(0); tempTree.push_back(0); // write bvh2 clip node stats.updateInner(); tempTree[nodeIndex + 0] = (axis << 30) | (1 << 29) | nextIndex; tempTree[nodeIndex + 1] = floatToRawIntBits(nodeL); tempTree[nodeIndex + 2] = floatToRawIntBits(nodeR); // update nodebox and recurse nodeBox.lo[axis] = nodeL; nodeBox.hi[axis] = nodeR; subdivide(left, rightOrig, tempTree, dat, gridBox, nodeBox, nextIndex, depth + 1, stats); return; } } // ensure we are making progress in the subdivision if (right == rightOrig) { // all left if (prevAxis == axis && G3D::fuzzyEq(prevSplit, split)) { // we are stuck here - create a leaf stats.updateLeaf(depth, right - left + 1); createNode(tempTree, nodeIndex, left, right); return; } if (clipL <= split) { // keep looping on left half gridBox.hi[axis] = split; prevClip = clipL; wasLeft = true; continue; } gridBox.hi[axis] = split; prevClip = G3D::fnan(); } else if (left > right) { // all right if (prevAxis == axis && G3D::fuzzyEq(prevSplit, split)) { // we are stuck here - create a leaf stats.updateLeaf(depth, right - left + 1); createNode(tempTree, nodeIndex, left, right); return; } right = rightOrig; if (clipR >= split) { // keep looping on right half gridBox.lo[axis] = split; prevClip = clipR; wasLeft = false; continue; } gridBox.lo[axis] = split; prevClip = G3D::fnan(); } else { // we are actually splitting stuff if (prevAxis != -1 && !isnan(prevClip)) { // second time through - lets create the previous split // since it produced empty space int nextIndex = tempTree.size(); // allocate child node tempTree.push_back(0); tempTree.push_back(0); tempTree.push_back(0); if (wasLeft) { // create a node with a left child // write leaf node stats.updateInner(); tempTree[nodeIndex + 0] = (prevAxis << 30) | nextIndex; tempTree[nodeIndex + 1] = floatToRawIntBits(prevClip); tempTree[nodeIndex + 2] = floatToRawIntBits(G3D::inf()); } else { // create a node with a right child // write leaf node stats.updateInner(); tempTree[nodeIndex + 0] = (prevAxis << 30) | (nextIndex - 3); tempTree[nodeIndex + 1] = floatToRawIntBits(-G3D::inf()); tempTree[nodeIndex + 2] = floatToRawIntBits(prevClip); } // count stats for the unused leaf depth++; stats.updateLeaf(depth, 0); // now we keep going as we are, with a new nodeIndex: nodeIndex = nextIndex; } break; } } // compute index of child nodes int nextIndex = tempTree.size(); // allocate left node int nl = right - left + 1; int nr = rightOrig - (right + 1) + 1; if (nl > 0) { tempTree.push_back(0); tempTree.push_back(0); tempTree.push_back(0); } else nextIndex -= 3; // allocate right node if (nr > 0) { tempTree.push_back(0); tempTree.push_back(0); tempTree.push_back(0); } // write leaf node stats.updateInner(); tempTree[nodeIndex + 0] = (axis << 30) | nextIndex; tempTree[nodeIndex + 1] = floatToRawIntBits(clipL); tempTree[nodeIndex + 2] = floatToRawIntBits(clipR); // prepare L/R child boxes AABound gridBoxL(gridBox), gridBoxR(gridBox); AABound nodeBoxL(nodeBox), nodeBoxR(nodeBox); gridBoxL.hi[axis] = gridBoxR.lo[axis] = split; nodeBoxL.hi[axis] = clipL; nodeBoxR.lo[axis] = clipR; // recurse if (nl > 0) subdivide(left, right, tempTree, dat, gridBoxL, nodeBoxL, nextIndex, depth + 1, stats); else stats.updateLeaf(depth + 1, 0); if (nr > 0) subdivide(right + 1, rightOrig, tempTree, dat, gridBoxR, nodeBoxR, nextIndex + 3, depth + 1, stats); else stats.updateLeaf(depth + 1, 0); } bool BIH::writeToFile(FILE *wf) const { uint32 treeSize = tree.size(); uint32 check = 0, count = 0; check += fwrite(&bounds.low(), sizeof(float), 3, wf); check += fwrite(&bounds.high(), sizeof(float), 3, wf); check += fwrite(&treeSize, sizeof(uint32), 1, wf); check += fwrite(&tree[0], sizeof(uint32), treeSize, wf); count = objects.size(); check += fwrite(&count, sizeof(uint32), 1, wf); check += fwrite(&objects[0], sizeof(uint32), count, wf); return check == (3 + 3 + 2 + treeSize + count); } bool BIH::readFromFile(FILE *rf) { uint32 treeSize; Vector3 lo, hi; uint32 check = 0, count = 0; check += fread(&lo, sizeof(float), 3, rf); check += fread(&hi, sizeof(float), 3, rf); bounds = AABox(lo, hi); check += fread(&treeSize, sizeof(uint32), 1, rf); tree.resize(treeSize); check += fread(&tree[0], sizeof(uint32), treeSize, rf); check += fread(&count, sizeof(uint32), 1, rf); objects.resize(count); // = new uint32[nObjects]; check += fread(&objects[0], sizeof(uint32), count, rf); return check == (3 + 3 + 2 + treeSize + count); } void BIH::BuildStats::updateLeaf(int depth, int n) { numLeaves++; minDepth = std::min(depth, minDepth); maxDepth = std::max(depth, maxDepth); sumDepth += depth; minObjects = std::min(n, minObjects); maxObjects = std::max(n, maxObjects); sumObjects += n; int nl = std::min(n, 5); ++numLeavesN[nl]; } void BIH::BuildStats::printStats() { printf("Tree stats:\n"); printf(" * Nodes: %d\n", numNodes); printf(" * Leaves: %d\n", numLeaves); printf(" * Objects: min %d\n", minObjects); printf(" avg %.2f\n", (float) sumObjects / numLeaves); printf(" avg(n>0) %.2f\n", (float) sumObjects / (numLeaves - numLeavesN[0])); printf(" max %d\n", maxObjects); printf(" * Depth: min %d\n", minDepth); printf(" avg %.2f\n", (float) sumDepth / numLeaves); printf(" max %d\n", maxDepth); printf(" * Leaves w/: N=0 %3d%%\n", 100 * numLeavesN[0] / numLeaves); printf(" N=1 %3d%%\n", 100 * numLeavesN[1] / numLeaves); printf(" N=2 %3d%%\n", 100 * numLeavesN[2] / numLeaves); printf(" N=3 %3d%%\n", 100 * numLeavesN[3] / numLeaves); printf(" N=4 %3d%%\n", 100 * numLeavesN[4] / numLeaves); printf(" N>4 %3d%%\n", 100 * numLeavesN[5] / numLeaves); printf(" * BVH2 nodes: %d (%3d%%)\n", numBVH2, 100 * numBVH2 / (numNodes + numLeaves - 2 * numBVH2)); }
#include <bits/stdc++.h> using namespace std; typedef long long ll; int main() { cout<< "Enter the no of diamonds"<<endl; ll x; cin>>x; vector<ll> mp,np; ll i,var1; cout<< "Enter the purity levels of all diamonds"<<endl; for(i=0;i<x;i++) { cin>>var1; mp.push_back(var1); } cout<< "Enter the minimum prices of all diamonds"<<endl; for(i=0;i<x;i++) { cin>>var1; np.push_back(var1); } cout<< "Enter the no of clients"<<endl; ll z; cin>>z; ll k[z],r[z],j; cout<< "Enter the values of k"<<endl; for(i=0;i<z;i++) { cin>>k[i]; } cout<< "Enter the values of r"<<endl; for(i=0;i<z;i++) { cin>>r[i]; } ll ans=0; for(i=0;i<z;i++) { for(j=0;j<mp.size();j++) { if(mp[j]>k[i] && np[j]<=r[i]) { ans++; mp.erase(mp.begin()+j); np.erase(np.begin()+j); break; } } } cout<<ans<<endl; return 0; }
/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */ /* If you are missing that file, acquire a complete release at teeworlds.com. */ #include <engine/demo.h> #include <engine/shared/demo.h> #include <engine/engine.h> #include <engine/shared/config.h> #include <game/generated/client_data.h> #include <game/client/components/particles.h> #include <game/client/components/skins.h> #include <game/client/components/flow.h> #include <game/client/components/damageind.h> #include <game/client/components/sounds.h> #include <game/client/gameclient.h> #include "effects.h" inline vec2 RandomDir() { return normalize(vec2(frandom()-0.5f, frandom()-0.5f)); } CEffects::CEffects() { m_Add50hz = false; m_Add100hz = false; } void CEffects::AirJump(vec2 Pos) { CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_AIRJUMP; p.m_Pos = Pos + vec2(-6.0f, 16.0f); p.m_Vel = vec2(0, -200); p.m_LifeSpan = 0.5f; p.m_StartSize = 48.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; p.m_Rotspeed = pi*2; p.m_Gravity.y = 500; p.m_Friction = 0.7f; p.m_FlowAffected = 0.0f; m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); p.m_Pos = Pos + vec2(6.0f, 16.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_PLAYER_AIRJUMP, 1.0f, Pos); } void CEffects::DamageIndicator(vec2 Pos, vec2 Dir) { m_pClient->m_pDamageind->Create(Pos, Dir); } void CEffects::PowerupShine(vec2 Pos, vec2 size) { if(!m_Add50hz) return; CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SLICE; p.m_Pos = Pos + vec2((frandom()-0.5f)*size.x, (frandom()-0.5f)*size.y); p.m_Vel = vec2(0, 0); p.m_LifeSpan = 0.5f; p.m_StartSize = 16.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; p.m_Rotspeed = pi*2; p.m_Gravity.y = 500; p.m_Friction = 0.9f; p.m_FlowAffected = 0.0f; m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } void CEffects::SmokeTrail(vec2 Pos, vec2 Vel) { if(!m_Add50hz) return; CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; p.m_Vel = Vel + RandomDir()*50.0f; p.m_LifeSpan = 0.5f + frandom()*0.5f; p.m_StartSize = 12.0f + frandom()*8; p.m_EndSize = 0; p.m_Friction = 0.7f; p.m_Gravity.y = frandom()*-500.0f; m_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p); } void CEffects::SkidTrail(vec2 Pos, vec2 Vel) { if(!m_Add100hz) return; CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; p.m_Vel = Vel + RandomDir()*50.0f; p.m_LifeSpan = 0.5f + frandom()*0.5f; p.m_StartSize = 24.0f + frandom()*12; p.m_EndSize = 0; p.m_Friction = 0.7f; p.m_Gravity.y = frandom()*-500.0f; p.m_Color = vec4(0.75f,0.75f,0.75f,1.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } void CEffects::BulletTrail(vec2 Pos) { if(!m_Add100hz) return; CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_BALL; p.m_Pos = Pos; p.m_LifeSpan = 0.25f + frandom()*0.25f; p.m_StartSize = 8.0f; p.m_EndSize = 0; p.m_Friction = 0.7f; m_pClient->m_pParticles->Add(CParticles::GROUP_PROJECTILE_TRAIL, &p); } void CEffects::PlayerSpawn(vec2 Pos) { for(int i = 0; i < 32; i++) { CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SHELL; p.m_Pos = Pos; p.m_Vel = RandomDir() * (powf(frandom(), 3)*600.0f); p.m_LifeSpan = 0.3f + frandom()*0.3f; p.m_StartSize = 64.0f + frandom()*32; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; p.m_Rotspeed = frandom(); p.m_Gravity.y = frandom()*-400.0f; p.m_Friction = 0.7f; p.m_Color = vec4(0xb5/255.0f, 0x50/255.0f, 0xcb/255.0f, 1.0f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_PLAYER_SPAWN, 1.0f, Pos); } void CEffects::PlayerDeath(vec2 Pos, int ClientID) { vec3 BloodColor(1.0f,1.0f,1.0f); if(ClientID >= 0) { if(m_pClient->m_aClients[ClientID].m_UseCustomColor) BloodColor = m_pClient->m_pSkins->GetColorV3(m_pClient->m_aClients[ClientID].m_ColorBody); else { const CSkins::CSkin *s = m_pClient->m_pSkins->Get(m_pClient->m_aClients[ClientID].m_SkinID); if(s) BloodColor = s->m_BloodColor; } } for(int i = 0; i < 64; i++) { CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SPLAT01 + (rand()%3); p.m_Pos = Pos; p.m_Vel = RandomDir() * ((frandom()+0.1f)*900.0f); p.m_LifeSpan = 0.3f + frandom()*0.3f; p.m_StartSize = 24.0f + frandom()*16; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; p.m_Rotspeed = (frandom()-0.5f) * pi; p.m_Gravity.y = 800.0f; p.m_Friction = 0.8f; vec3 c = BloodColor * (0.75f + frandom()*0.25f); p.m_Color = vec4(c.r, c.g, c.b, 0.75f); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } } void CEffects::Explosion(vec2 Pos) { // add to flow for(int y = -8; y <= 8; y++) for(int x = -8; x <= 8; x++) { if(x == 0 && y == 0) continue; float a = 1 - (length(vec2(x,y)) / length(vec2(8,8))); m_pClient->m_pFlow->Add(Pos+vec2(x,y)*16, normalize(vec2(x,y))*5000.0f*a, 10.0f); } // add the explosion CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_EXPL01; p.m_Pos = Pos; p.m_LifeSpan = 0.4f; p.m_StartSize = 150.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); // add the smoke for(int i = 0; i < 24; i++) { CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_SMOKE; p.m_Pos = Pos; p.m_Vel = RandomDir() * ((1.0f + frandom()*0.2f) * 1000.0f); p.m_LifeSpan = 0.5f + frandom()*0.4f; p.m_StartSize = 32.0f + frandom()*8; p.m_EndSize = 0; p.m_Gravity.y = frandom()*-800.0f; p.m_Friction = 0.4f; p.m_Color = mix(vec4(0.75f,0.75f,0.75f,1.0f), vec4(0.5f,0.5f,0.5f,1.0f), frandom()); m_pClient->m_pParticles->Add(CParticles::GROUP_GENERAL, &p); } } void CEffects::HammerHit(vec2 Pos) { // add the explosion CParticle p; p.SetDefault(); p.m_Spr = SPRITE_PART_HIT01; p.m_Pos = Pos; p.m_LifeSpan = 0.3f; p.m_StartSize = 120.0f; p.m_EndSize = 0; p.m_Rot = frandom()*pi*2; m_pClient->m_pParticles->Add(CParticles::GROUP_EXPLOSIONS, &p); m_pClient->m_pSounds->Play(CSounds::CHN_WORLD, SOUND_HAMMER_HIT, 1.0f, Pos); } void CEffects::OnRender() { static int64 LastUpdate100hz = 0; static int64 LastUpdate50hz = 0; if(Client()->State() == IClient::STATE_DEMOPLAYBACK) { if (m_pClient->DemoPlayer()->m_Recording) { if(Client()->DemoTimeGet()-LastUpdate100hz > time_freq()/100) { m_Add100hz = true; LastUpdate100hz = Client()->DemoTimeGet(); } else m_Add100hz = false; if(Client()->DemoTimeGet()-LastUpdate50hz > time_freq()/100) { m_Add50hz = true; LastUpdate50hz = Client()->DemoTimeGet(); } else m_Add50hz = false; if(m_Add50hz) m_pClient->m_pFlow->Update(); return; } const IDemoPlayer::CInfo *pInfo = DemoPlayer()->BaseInfo(); if(time_get()-LastUpdate100hz > time_freq()/(100*pInfo->m_Speed)) { m_Add100hz = true; LastUpdate100hz = time_get(); } else m_Add100hz = false; if(time_get()-LastUpdate50hz > time_freq()/(100*pInfo->m_Speed)) { m_Add50hz = true; LastUpdate50hz = time_get(); } else m_Add50hz = false; if(m_Add50hz) m_pClient->m_pFlow->Update(); return; } if(time_get()-LastUpdate100hz > time_freq()/100) { m_Add100hz = true; LastUpdate100hz = time_get(); } else m_Add100hz = false; if(time_get()-LastUpdate50hz > time_freq()/100) { m_Add50hz = true; LastUpdate50hz = time_get(); } else m_Add50hz = false; if(m_Add50hz) m_pClient->m_pFlow->Update(); }
/* * Copyright (c) 2018-2019, The Mybtcfx Developers. * Portions Copyright (c) 2012-2017, The CryptoNote Developers, The Bytecoin Developers. * * This file is part of 4xBIT. * * This file is subject to the terms and conditions defined in the * file 'LICENSE', which is part of this source code package. */ #include "PaymentGateService.h" #include <future> #include "Common/SignalHandler.h" #include "Common/Util.h" #include "InProcessNode/InProcessNode.h" #include "Logging/LoggerRef.h" #include "PaymentGate/PaymentServiceJsonRpcServer.h" #include "Common/ScopeExit.h" #include "CryptoNoteCore/Core.h" #include "CryptoNoteCore/DatabaseBlockchainCache.h" #include "CryptoNoteCore/DatabaseBlockchainCacheFactory.h" #include "CryptoNoteCore/DataBaseConfig.h" #include "CryptoNoteCore/MainChainStorage.h" #include "CryptoNoteCore/RocksDBWrapper.h" #include "CryptoNoteProtocol/CryptoNoteProtocolHandler.h" #include "P2p/NetNode.h" #include <System/Context.h> #include "Wallet/WalletGreen.h" #ifdef ERROR #undef ERROR #endif #ifdef _WIN32 #include <direct.h> #else #include <unistd.h> #endif using namespace PaymentService; void changeDirectory(const std::string& path) { if (chdir(path.c_str())) { throw std::runtime_error("Couldn't change directory to \'" + path + "\': " + strerror(errno)); } } void stopSignalHandler(PaymentGateService* pg) { pg->stop(); } PaymentGateService::PaymentGateService() : dispatcher(nullptr), stopEvent(nullptr), config(), service(nullptr), logger(), currencyBuilder(logger), fileLogger(Logging::TRACE), consoleLogger(Logging::INFO) { consoleLogger.setPattern("%D %T %L "); fileLogger.setPattern("%D %T %L "); } bool PaymentGateService::init(int argc, char** argv) { if (!config.init(argc, argv)) { return false; } logger.setMaxLevel(static_cast<Logging::Level>(config.gateConfiguration.logLevel)); logger.setPattern("%D %T %L "); logger.addLogger(consoleLogger); Logging::LoggerRef log(logger, "main"); if (config.gateConfiguration.testnet) { log(Logging::INFO) << "Starting in testnet mode"; currencyBuilder.testnet(true); } if (!config.gateConfiguration.serverRoot.empty()) { changeDirectory(config.gateConfiguration.serverRoot); log(Logging::INFO) << "Current working directory now is " << config.gateConfiguration.serverRoot; } fileStream.open(config.gateConfiguration.logFile, std::ofstream::app); if (!fileStream) { throw std::runtime_error("Couldn't open log file"); } fileLogger.attachToStream(fileStream); logger.addLogger(fileLogger); return true; } WalletConfiguration PaymentGateService::getWalletConfig() const { return WalletConfiguration{ config.gateConfiguration.containerFile, config.gateConfiguration.containerPassword, config.gateConfiguration.syncFromZero }; } const CryptoNote::Currency PaymentGateService::getCurrency() { return currencyBuilder.currency(); } void PaymentGateService::run() { System::Dispatcher localDispatcher; System::Event localStopEvent(localDispatcher); this->dispatcher = &localDispatcher; this->stopEvent = &localStopEvent; Tools::SignalHandler::install(std::bind(&stopSignalHandler, this)); Logging::LoggerRef log(logger, "run"); if (config.startInprocess) { runInProcess(log); } else { runRpcProxy(log); } this->dispatcher = nullptr; this->stopEvent = nullptr; } void PaymentGateService::stop() { Logging::LoggerRef log(logger, "stop"); log(Logging::INFO, Logging::BRIGHT_WHITE) << "Stop signal caught"; if (dispatcher != nullptr) { dispatcher->remoteSpawn([&]() { if (stopEvent != nullptr) { stopEvent->set(); } }); } } void PaymentGateService::runInProcess(Logging::LoggerRef& log) { log(Logging::INFO) << "Starting Payment Gate with local node"; CryptoNote::DataBaseConfig dbConfig; //TODO: make command line options dbConfig.setConfigFolderDefaulted(true); dbConfig.setDataDir(config.dataDir); dbConfig.setMaxOpenFiles(100); dbConfig.setReadCacheSize(128*1024*1024); dbConfig.setWriteBufferSize(128*1024*1024); dbConfig.setTestnet(false); dbConfig.setBackgroundThreadsCount(2); if (dbConfig.isConfigFolderDefaulted()) { if (!Tools::create_directories_if_necessary(dbConfig.getDataDir())) { throw std::runtime_error("Can't create directory: " + dbConfig.getDataDir()); } } else { if (!Tools::directoryExists(dbConfig.getDataDir())) { throw std::runtime_error("Directory does not exist: " + dbConfig.getDataDir()); } } CryptoNote::RocksDBWrapper database(logger); database.init(dbConfig); Tools::ScopeExit dbShutdownOnExit([&database] () { database.shutdown(); }); if (!CryptoNote::DatabaseBlockchainCache::checkDBSchemeVersion(database, logger)) { dbShutdownOnExit.cancel(); database.shutdown(); database.destoy(dbConfig); database.init(dbConfig); dbShutdownOnExit.resume(); } CryptoNote::Currency currency = currencyBuilder.currency(); log(Logging::INFO) << "initializing core"; CryptoNote::Core core( currency, logger, CryptoNote::Checkpoints(logger), *dispatcher, std::unique_ptr<CryptoNote::IBlockchainCacheFactory>(new CryptoNote::DatabaseBlockchainCacheFactory(database, log.getLogger())), CryptoNote::createSwappedMainChainStorage(dbConfig.getDataDir(), currency)); core.load(); CryptoNote::CryptoNoteProtocolHandler protocol(currency, *dispatcher, core, nullptr, logger); CryptoNote::NodeServer p2pNode(*dispatcher, protocol, logger); protocol.set_p2p_endpoint(&p2pNode); log(Logging::INFO) << "initializing p2pNode"; if (!p2pNode.init(config.netNodeConfig)) { throw std::runtime_error("Failed to init p2pNode"); } std::unique_ptr<CryptoNote::INode> node(new CryptoNote::InProcessNode(core, protocol, *dispatcher)); std::error_code nodeInitStatus; node->init([&log, &nodeInitStatus](std::error_code ec) { nodeInitStatus = ec; }); if (nodeInitStatus) { log(Logging::WARNING, Logging::YELLOW) << "Failed to init node: " << nodeInitStatus.message(); throw std::system_error(nodeInitStatus); } else { log(Logging::INFO) << "node is inited successfully"; } log(Logging::INFO) << "Spawning p2p server"; System::Event p2pStarted(*dispatcher); System::Context<> context(*dispatcher, [&]() { p2pStarted.set(); p2pNode.run(); }); p2pStarted.wait(); runWalletService(currency, *node); p2pNode.sendStopSignal(); context.get(); node->shutdown(); p2pNode.deinit(); } void PaymentGateService::runRpcProxy(Logging::LoggerRef& log) { log(Logging::INFO) << "Starting Payment Gate with remote node"; CryptoNote::Currency currency = currencyBuilder.currency(); std::unique_ptr<CryptoNote::INode> node( PaymentService::NodeFactory::createNode( config.remoteNodeConfig.daemonHost, config.remoteNodeConfig.daemonPort, log.getLogger())); runWalletService(currency, *node); } void PaymentGateService::runWalletService(const CryptoNote::Currency& currency, CryptoNote::INode& node) { PaymentService::WalletConfiguration walletConfiguration{ config.gateConfiguration.containerFile, config.gateConfiguration.containerPassword, config.gateConfiguration.syncFromZero }; std::unique_ptr<CryptoNote::WalletGreen> wallet(new CryptoNote::WalletGreen(*dispatcher, currency, node, logger)); service = new PaymentService::WalletService(currency, *dispatcher, node, *wallet, *wallet, walletConfiguration, logger); std::unique_ptr<PaymentService::WalletService> serviceGuard(service); try { service->init(); } catch (std::exception& e) { Logging::LoggerRef(logger, "run")(Logging::ERROR, Logging::BRIGHT_RED) << "Failed to init walletService reason: " << e.what(); return; } if (config.gateConfiguration.printAddresses) { // print addresses and exit std::vector<std::string> addresses; service->getAddresses(addresses); for (const auto& address: addresses) { std::cout << "Address: " << address << std::endl; } } else { PaymentService::PaymentServiceJsonRpcServer rpcServer(*dispatcher, *stopEvent, *service, logger); rpcServer.start(config.gateConfiguration.bindAddress, config.gateConfiguration.bindPort); Logging::LoggerRef(logger, "PaymentGateService")(Logging::INFO, Logging::BRIGHT_WHITE) << "JSON-RPC server stopped, stopping wallet service..."; try { service->saveWallet(); } catch (std::exception& ex) { Logging::LoggerRef(logger, "saveWallet")(Logging::WARNING, Logging::YELLOW) << "Couldn't save container: " << ex.what(); } } }
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/test/base/testing_browser_process.h" #include "base/prefs/pref_service.h" #include "base/strings/string_util.h" #include "base/time/default_tick_clock.h" #include "build/build_config.h" #include "chrome/browser/background/background_mode_manager.h" #include "chrome/browser/browser_process.h" #include "chrome/browser/browser_process_impl.h" #include "chrome/browser/printing/print_job_manager.h" #include "chrome/browser/profiles/profile_manager.h" #include "chrome/browser/ui/apps/chrome_apps_client.h" #include "chrome/test/base/testing_browser_process_platform_part.h" #include "components/network_time/network_time_tracker.h" #include "content/public/browser/notification_service.h" #include "net/url_request/url_request_context_getter.h" #include "testing/gtest/include/gtest/gtest.h" #include "ui/message_center/message_center.h" #if !defined(OS_IOS) #include "chrome/browser/notifications/notification_ui_manager.h" #include "chrome/browser/prerender/prerender_tracker.h" #include "chrome/browser/safe_browsing/safe_browsing_service.h" #endif #if defined(ENABLE_CONFIGURATION_POLICY) #include "components/policy/core/browser/browser_policy_connector.h" #else #include "components/policy/core/common/policy_service_stub.h" #endif // defined(ENABLE_CONFIGURATION_POLICY) #if defined(ENABLE_EXTENSIONS) #include "chrome/browser/extensions/chrome_extensions_browser_client.h" #include "chrome/browser/media_galleries/media_file_system_registry.h" #include "components/storage_monitor/storage_monitor.h" #include "components/storage_monitor/test_storage_monitor.h" #endif #if defined(ENABLE_FULL_PRINTING) #include "chrome/browser/printing/background_printing_manager.h" #include "chrome/browser/printing/print_preview_dialog_controller.h" #endif // static TestingBrowserProcess* TestingBrowserProcess::GetGlobal() { return static_cast<TestingBrowserProcess*>(g_browser_process); } // static void TestingBrowserProcess::CreateInstance() { DCHECK(!g_browser_process); g_browser_process = new TestingBrowserProcess; } // static void TestingBrowserProcess::DeleteInstance() { // g_browser_process must be NULL during its own destruction. BrowserProcess* browser_process = g_browser_process; g_browser_process = NULL; delete browser_process; } TestingBrowserProcess::TestingBrowserProcess() : notification_service_(content::NotificationService::Create()), module_ref_count_(0), app_locale_("en"), local_state_(NULL), io_thread_(NULL), system_request_context_(NULL), platform_part_(new TestingBrowserProcessPlatformPart()) { #if defined(ENABLE_EXTENSIONS) extensions_browser_client_.reset( new extensions::ChromeExtensionsBrowserClient); apps::AppsClient::Set(ChromeAppsClient::GetInstance()); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); #endif } TestingBrowserProcess::~TestingBrowserProcess() { EXPECT_FALSE(local_state_); #if defined(ENABLE_CONFIGURATION_POLICY) SetBrowserPolicyConnector(NULL); #endif #if defined(ENABLE_EXTENSIONS) extensions::ExtensionsBrowserClient::Set(NULL); #endif // Destructors for some objects owned by TestingBrowserProcess will use // g_browser_process if it is not NULL, so it must be NULL before proceeding. DCHECK_EQ(static_cast<BrowserProcess*>(NULL), g_browser_process); } void TestingBrowserProcess::ResourceDispatcherHostCreated() { } void TestingBrowserProcess::EndSession() { } MetricsServicesManager* TestingBrowserProcess::GetMetricsServicesManager() { return NULL; } MetricsService* TestingBrowserProcess::metrics_service() { return NULL; } rappor::RapporService* TestingBrowserProcess::rappor_service() { return NULL; } IOThread* TestingBrowserProcess::io_thread() { return io_thread_; } WatchDogThread* TestingBrowserProcess::watchdog_thread() { return NULL; } ProfileManager* TestingBrowserProcess::profile_manager() { #if defined(OS_IOS) NOTIMPLEMENTED(); return NULL; #else return profile_manager_.get(); #endif } void TestingBrowserProcess::SetProfileManager(ProfileManager* profile_manager) { #if !defined(OS_IOS) // NotificationUIManager can contain references to elements in the current // ProfileManager (for example, the MessageCenterSettingsController maintains // a pointer to the ProfileInfoCache). So when we change the ProfileManager // (typically during test shutdown) make sure to reset any objects that might // maintain references to it. See SetLocalState() for a description of a // similar situation. notification_ui_manager_.reset(); profile_manager_.reset(profile_manager); #endif } PrefService* TestingBrowserProcess::local_state() { return local_state_; } chrome_variations::VariationsService* TestingBrowserProcess::variations_service() { return NULL; } policy::BrowserPolicyConnector* TestingBrowserProcess::browser_policy_connector() { #if defined(ENABLE_CONFIGURATION_POLICY) if (!browser_policy_connector_) browser_policy_connector_ = platform_part_->CreateBrowserPolicyConnector(); return browser_policy_connector_.get(); #else return NULL; #endif } policy::PolicyService* TestingBrowserProcess::policy_service() { #if defined(OS_IOS) NOTIMPLEMENTED(); return NULL; #elif defined(ENABLE_CONFIGURATION_POLICY) return browser_policy_connector()->GetPolicyService(); #else if (!policy_service_) policy_service_.reset(new policy::PolicyServiceStub()); return policy_service_.get(); #endif } IconManager* TestingBrowserProcess::icon_manager() { return NULL; } GLStringManager* TestingBrowserProcess::gl_string_manager() { return NULL; } GpuModeManager* TestingBrowserProcess::gpu_mode_manager() { return NULL; } BackgroundModeManager* TestingBrowserProcess::background_mode_manager() { return NULL; } void TestingBrowserProcess::set_background_mode_manager_for_test( scoped_ptr<BackgroundModeManager> manager) { NOTREACHED(); } StatusTray* TestingBrowserProcess::status_tray() { return NULL; } SafeBrowsingService* TestingBrowserProcess::safe_browsing_service() { #if defined(OS_IOS) NOTIMPLEMENTED(); return NULL; #else return sb_service_.get(); #endif } safe_browsing::ClientSideDetectionService* TestingBrowserProcess::safe_browsing_detection_service() { return NULL; } net::URLRequestContextGetter* TestingBrowserProcess::system_request_context() { return system_request_context_; } BrowserProcessPlatformPart* TestingBrowserProcess::platform_part() { return platform_part_.get(); } extensions::EventRouterForwarder* TestingBrowserProcess::extension_event_router_forwarder() { return NULL; } NotificationUIManager* TestingBrowserProcess::notification_ui_manager() { #if defined(ENABLE_NOTIFICATIONS) if (!notification_ui_manager_.get()) notification_ui_manager_.reset( NotificationUIManager::Create(local_state())); return notification_ui_manager_.get(); #else NOTIMPLEMENTED(); return NULL; #endif } message_center::MessageCenter* TestingBrowserProcess::message_center() { return message_center::MessageCenter::Get(); } IntranetRedirectDetector* TestingBrowserProcess::intranet_redirect_detector() { return NULL; } void TestingBrowserProcess::CreateDevToolsHttpProtocolHandler( chrome::HostDesktopType host_desktop_type, const std::string& ip, int port) { } unsigned int TestingBrowserProcess::AddRefModule() { return ++module_ref_count_; } unsigned int TestingBrowserProcess::ReleaseModule() { DCHECK_GT(module_ref_count_, 0U); return --module_ref_count_; } bool TestingBrowserProcess::IsShuttingDown() { return false; } printing::PrintJobManager* TestingBrowserProcess::print_job_manager() { #if defined(ENABLE_FULL_PRINTING) if (!print_job_manager_.get()) print_job_manager_.reset(new printing::PrintJobManager()); return print_job_manager_.get(); #else NOTIMPLEMENTED(); return NULL; #endif } printing::PrintPreviewDialogController* TestingBrowserProcess::print_preview_dialog_controller() { #if defined(ENABLE_FULL_PRINTING) if (!print_preview_dialog_controller_.get()) print_preview_dialog_controller_ = new printing::PrintPreviewDialogController(); return print_preview_dialog_controller_.get(); #else NOTIMPLEMENTED(); return NULL; #endif } printing::BackgroundPrintingManager* TestingBrowserProcess::background_printing_manager() { #if defined(ENABLE_FULL_PRINTING) if (!background_printing_manager_.get()) { background_printing_manager_.reset( new printing::BackgroundPrintingManager()); } return background_printing_manager_.get(); #else NOTIMPLEMENTED(); return NULL; #endif } const std::string& TestingBrowserProcess::GetApplicationLocale() { return app_locale_; } void TestingBrowserProcess::SetApplicationLocale( const std::string& app_locale) { app_locale_ = app_locale; } DownloadStatusUpdater* TestingBrowserProcess::download_status_updater() { return NULL; } DownloadRequestLimiter* TestingBrowserProcess::download_request_limiter() { return NULL; } ChromeNetLog* TestingBrowserProcess::net_log() { return NULL; } prerender::PrerenderTracker* TestingBrowserProcess::prerender_tracker() { #if defined(OS_IOS) NOTIMPLEMENTED(); return NULL; #else if (!prerender_tracker_.get()) prerender_tracker_.reset(new prerender::PrerenderTracker()); return prerender_tracker_.get(); #endif } component_updater::ComponentUpdateService* TestingBrowserProcess::component_updater() { return NULL; } CRLSetFetcher* TestingBrowserProcess::crl_set_fetcher() { return NULL; } component_updater::PnaclComponentInstaller* TestingBrowserProcess::pnacl_component_installer() { return NULL; } MediaFileSystemRegistry* TestingBrowserProcess::media_file_system_registry() { #if defined(OS_IOS) || defined(OS_ANDROID) NOTIMPLEMENTED(); return NULL; #else if (!media_file_system_registry_) media_file_system_registry_.reset(new MediaFileSystemRegistry()); return media_file_system_registry_.get(); #endif } bool TestingBrowserProcess::created_local_state() const { return (local_state_ != NULL); } #if defined(ENABLE_WEBRTC) WebRtcLogUploader* TestingBrowserProcess::webrtc_log_uploader() { return NULL; } #endif network_time::NetworkTimeTracker* TestingBrowserProcess::network_time_tracker() { if (!network_time_tracker_) { DCHECK(local_state_); network_time_tracker_.reset(new network_time::NetworkTimeTracker( scoped_ptr<base::TickClock>(new base::DefaultTickClock()), local_state_)); } return network_time_tracker_.get(); } gcm::GCMDriver* TestingBrowserProcess::gcm_driver() { return NULL; } void TestingBrowserProcess::SetSystemRequestContext( net::URLRequestContextGetter* context_getter) { system_request_context_ = context_getter; } void TestingBrowserProcess::SetLocalState(PrefService* local_state) { if (!local_state) { // The local_state_ PrefService is owned outside of TestingBrowserProcess, // but some of the members of TestingBrowserProcess hold references to it // (for example, via PrefNotifier members). But given our test // infrastructure which tears down individual tests before freeing the // TestingBrowserProcess, there's not a good way to make local_state outlive // these dependencies. As a workaround, whenever local_state_ is cleared // (assumedly as part of exiting the test and freeing TestingBrowserProcess) // any components owned by TestingBrowserProcess that depend on local_state // are also freed. network_time_tracker_.reset(); #if !defined(OS_IOS) notification_ui_manager_.reset(); #endif #if defined(ENABLE_CONFIGURATION_POLICY) SetBrowserPolicyConnector(NULL); #endif } local_state_ = local_state; } void TestingBrowserProcess::SetIOThread(IOThread* io_thread) { io_thread_ = io_thread; } void TestingBrowserProcess::SetBrowserPolicyConnector( policy::BrowserPolicyConnector* connector) { #if defined(ENABLE_CONFIGURATION_POLICY) if (browser_policy_connector_) { browser_policy_connector_->Shutdown(); } browser_policy_connector_.reset(connector); #else CHECK(false); #endif } void TestingBrowserProcess::SetSafeBrowsingService( SafeBrowsingService* sb_service) { #if !defined(OS_IOS) NOTIMPLEMENTED(); sb_service_ = sb_service; #endif } /////////////////////////////////////////////////////////////////////////////// TestingBrowserProcessInitializer::TestingBrowserProcessInitializer() { TestingBrowserProcess::CreateInstance(); } TestingBrowserProcessInitializer::~TestingBrowserProcessInitializer() { TestingBrowserProcess::DeleteInstance(); }
//============================================================================= /** * @file amh_rh_ss.cpp * * $Id: amh_rh_ss.cpp 95536 2012-02-20 12:34:23Z johnnyw $ * * Creates code for AMH-RH operations. * * @author Mayur Deshpande <mayur@ics.uci.edu> */ //============================================================================= #include "operation.h" be_visitor_amh_rh_operation_ss::be_visitor_amh_rh_operation_ss ( be_visitor_context *ctx) : be_visitor_operation (ctx) { } be_visitor_amh_rh_operation_ss::~be_visitor_amh_rh_operation_ss (void) { } int be_visitor_amh_rh_operation_ss::visit_operation (be_operation *node) { // Nothing to be done for oneway operations. if (node->flags () == AST_Operation::OP_oneway) { return 0; } /// These are not for the server side. if (node->is_sendc_ami ()) { return 0; } // Output stream. TAO_OutStream *os = this->ctx_->stream (); UTL_Scope *s = this->ctx_->attribute () ? this->ctx_->attribute ()->defined_in () : node->defined_in (); be_interface *intf = be_interface::narrow_from_scope (s); if (intf == 0) { be_porttype *pt = be_porttype::narrow_from_scope (s); if (pt == 0) { ACE_ERROR_RETURN ((LM_ERROR, ACE_TEXT ("be_visitor_amh_rh_operation_sh::") ACE_TEXT ("visit_operation - ") ACE_TEXT ("bad scope\n")), -1); } else { intf = this->ctx_->interface (); } } char *buf = 0; intf->compute_full_name ("TAO_", "", buf); ACE_CString response_handler_implementation_name ("POA_"); response_handler_implementation_name += buf; // buf was allocated by ACE_OS::strdup, so we need to use free instead // of delete. ACE_OS::free (buf); buf = 0; // Step 1 : Generate return type: always void *os << be_nl_2 << "// TAO_IDL - Generated from" << be_nl << "// " << __FILE__ << ":" << __LINE__ << be_nl_2; *os << "void" << be_nl << response_handler_implementation_name.c_str () << "::"; // Check if we are an attribute node in disguise if (this->ctx_->attribute ()) { // now check if we are a "get" or "set" operation if (node->nmembers () == 1) // set { *os << "_set_"; } else { *os << "_get_"; } } *os << this->ctx_->port_prefix ().c_str () << node->local_name (); // Step 2 : Generate the params of the method be_visitor_context ctx (*this->ctx_); // Set the substate because response handler operations without // parameters don't use the environment parameter in the body. ctx.sub_state (TAO_CodeGen::TAO_AMH_RESPONSE_HANDLER_OPERATION); be_visitor_operation_arglist visitor (&ctx); if (node->accept (&visitor) == -1) { ACE_ERROR_RETURN ((LM_ERROR, "(%N:%l) be_visitor_amh_rh_operation_ss::" "visit_operation - " "codegen for argument list failed\n"), -1); } int is_an_exception_reply = 0; // Find out if the operation is one of the *_excep() operations, the // conditions are: // 1) The local_name ends in _excep() // 2) There is exactly one argument // 3) The argument takes an implied valuetype generated from the // original interface // 4) The implied valuetype ends in ExceptionHolder const char *last_underbar = ACE_OS::strrchr (node->full_name (), '_'); if (last_underbar != 0 && ACE_OS::strcmp (last_underbar, "_excep") == 0) { if (node->nmembers () == 1) { UTL_ScopeActiveIterator i (node, UTL_Scope::IK_decls); if (!i.is_done ()) { be_argument *argument = be_argument::narrow_from_decl (i.item ()); be_valuetype *vt = be_valuetype::narrow_from_decl (argument->field_type ()); if (vt != 0 && vt->original_interface () == intf->original_interface ()) { const char *last_E = ACE_OS::strrchr (vt->full_name (), 'E'); if (last_E != 0 && ACE_OS::strcmp (last_E, "ExceptionHolder") == 0) { is_an_exception_reply = 1; } } } } } if (is_an_exception_reply) { // Remove the trailing '_excep' from the operation name, we know // there is one from the checks above... ACE_CString operation_name (node->local_name ()->get_string ()); ACE_CString::size_type const idx = operation_name.rfind ('_'); ACE_ASSERT (idx != ACE_CString::npos); operation_name[idx] = '\0'; *os << be_nl << "{" << be_idt_nl << "try" << be_nl << "{" << be_idt_nl << "holder->raise_" << operation_name.c_str () << " ();" << be_uidt_nl << "}" << be_nl << "catch ( ::CORBA::Exception& ex)" << be_nl << "{" << be_idt_nl << "this->_tao_rh_send_exception (ex);" << be_uidt_nl << "}" << be_uidt_nl << "}"; } else { // Step 3: Generate actual code for the method *os << be_nl << "{" << be_idt_nl << "this->_tao_rh_init_reply ();" << be_nl_2; this->marshal_params (node); *os << be_nl << "this->_tao_rh_send_reply ();" << be_uidt_nl << "}"; } return 0; } int be_visitor_amh_rh_operation_ss::marshal_params (be_operation *node) { TAO_OutStream *os = this->ctx_->stream (); be_visitor_context ctx; // Now make sure that we have some in and inout parameters. Otherwise, there // is nothing to be marshaled out. if (this->has_param_type (node, AST_Argument::dir_IN) || this->has_param_type (node, AST_Argument::dir_INOUT)) { // marshal the in and inout arguments *os << "if (!(" << be_idt << be_idt_nl; // Marshal each in and inout argument. ctx = *this->ctx_; ctx.state (TAO_CodeGen::TAO_OPERATION_ARG_INVOKE_CS); ctx.sub_state (TAO_CodeGen::TAO_CDR_OUTPUT); be_visitor_operation_argument_invoke visitor (&ctx); if (node->accept (&visitor) == -1) { ACE_ERROR_RETURN ((LM_ERROR, "(%N:%l) be_visitor_amh_rh_operation_ss::" "gen_demarshal_params - " "codegen for demarshal failed\n"), -1); } *os << be_uidt_nl << "))" << be_nl << "{" << be_idt_nl; // If marshaling fails, raise exception. if (this->gen_raise_exception ("::CORBA::MARSHAL", "") == -1) { ACE_ERROR_RETURN ((LM_ERROR, "(%N:%l) gen_raise_exception failed\n"), -1); } *os << be_uidt_nl << "}" << be_uidt_nl; } return 0; }
#include "stdafx.h" #include "Color.h" Color::Color() : r(0), g(0), b(0) {} Color::Color(byte r, byte g, byte b) : r(r), g(g), b(b) {} byte &Color::operator[](nat item) { switch (item) { case 0: return b; case 1: return r; case 2: return g; } return r; }
#ifndef BANK_MANAGER_HPP #define BANK_MANAGER_HPP #include "Transaction.hpp" #include "coherence/lang.ns" #include "coherence/net/NamedCache.hpp" using namespace coherence::lang; using coherence::net::NamedCache; class BankManager { public: // ----- constructor ---------------------------------------------------- BankManager(); BankManager(const std::string& accountsCache); // ----- destructor ------------------------------------------------------ ~BankManager(); // ----- public API ------------------------------------------------------ void deposit(long long accountId, const Money& oAmount, Transaction& oResult); void withdraw(long long accountId, const Money& oMoney, Transaction& oResult); // ---- data members ----------------------------------------------------- protected: FinalHandle<NamedCache> m_hAccountsCache; }; #endif
// // 54. Spiral Matrix.cpp // leetcode // // Created by Yuebin Yang on 2017/2/3. // Copyright © 2017年 yuebin. All rights reserved. // #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { vector<int> result; //see if it is empty if(matrix.empty()) return result; int rows=matrix.size(); int cols=matrix[0].size(); int start_x=0; int start_y=0; int end_x=cols-1; int end_y=rows-1; int count=cols*rows; int completed=0; //to see if all the points have been visited. while(completed<count) { //move towards right for(int i=start_x;i<=end_x;i++) { result.push_back(matrix[start_y][i]); completed++; } start_y++; if(start_y>end_y) break; //move downward for(int i=start_y;i<=end_y;i++) { result.push_back((matrix[i][end_x])); completed++; } end_x--; if(start_x>end_x) break; //move towards left for(int i=end_x;i>=start_x;i--) { result.push_back(matrix[end_y][i]); completed++; } end_y--; if(start_y>end_y) break; //move upward for(int i=end_y;i>=start_y;i--) { result.push_back(matrix[i][start_x]); completed++; } start_x++; if(start_x>end_x) break; }//end while return result; } }; int main(){ Solution s; vector<vector<int> > matrix = {}; vector<int> result = s.spiralOrder(matrix); for(int i = 0;i < result.size();++i){ cout<<result[i]<<" "; }//for cout<<endl; return 0; }
class Solution { public: int countSubstrings(string s, string t) { map<string, int> tCnt; for(int pos = 0; pos < t.length(); ++pos){ for(int len = 1; pos + len - 1 < t.length(); ++len){ tCnt[t.substr(pos, len)] += 1; } } int answer = 0; for(int pos = 0; pos < s.length(); ++pos){ for(int len = 1; pos + len - 1 < s.length(); ++len){ string sSubstr = s.substr(pos, len); for(int i = 0; i < sSubstr.length(); ++i){ char originalChar = sSubstr[i]; for(int newChar = 'a'; newChar <= 'z'; ++newChar){ if(newChar != originalChar){ sSubstr[i] = newChar; if(tCnt.count(sSubstr)){ answer += tCnt[sSubstr]; } } } sSubstr[i] = originalChar; } } } return answer; } };
// grid.cpp /** * Copyright (C) 2010 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kSharding #include "mongo/platform/basic.h" #include "mongo/s/grid.h" #include "pcrecpp.h" #include <iomanip> #include "mongo/client/connpool.h" #include "mongo/client/replica_set_monitor.h" #include "mongo/db/json.h" #include "mongo/db/namespace_string.h" #include "mongo/db/write_concern.h" #include "mongo/s/cluster_write.h" #include "mongo/s/grid.h" #include "mongo/s/mongos_options.h" #include "mongo/s/shard.h" #include "mongo/s/type_collection.h" #include "mongo/s/type_database.h" #include "mongo/s/type_settings.h" #include "mongo/s/type_shard.h" #include "mongo/util/fail_point_service.h" #include "mongo/util/log.h" #include "mongo/util/startup_test.h" #include "mongo/util/stringutils.h" namespace mongo { using std::endl; using std::istringstream; using std::map; using std::ostringstream; using std::set; using std::setfill; using std::setw; using std::stringstream; using std::vector; MONGO_FP_DECLARE(neverBalance); DBConfigPtr Grid::getDBConfig( StringData ns , bool create , const string& shardNameHint ) { string database = nsToDatabase( ns ); if ( database == "config" ) return configServerPtr; uassert( 15918, str::stream() << "invalid database name: " << database, NamespaceString::validDBName( database ) ); scoped_lock l( _lock ); DBConfigPtr& dbConfig = _databases[database]; if( ! dbConfig ){ dbConfig.reset(new DBConfig( database )); // Protect initial load from connectivity errors, otherwise we won't be able // to perform any task. bool loaded = false; try { try { loaded = dbConfig->load(); } catch ( const DBException& ) { // Retry again, if the config server are now up, the previous call should have // cleared all the bad connections in the pool and this should succeed. loaded = dbConfig->load(); } } catch( DBException& e ){ e.addContext( "error loading initial database config information" ); warning() << e.what() << endl; dbConfig.reset(); throw; } if( ! loaded ){ if( create ){ // Protect creation of initial db doc from connectivity errors try{ // note here that cc->primary == 0. log() << "couldn't find database [" << database << "] in config db" << endl; { // lets check case ScopedDbConnection conn(configServer.modelServer(), 30); BSONObjBuilder b; b.appendRegex( "_id" , (string)"^" + pcrecpp::RE::QuoteMeta( database ) + "$" , "i" ); BSONObj dbObj = conn->findOne( DatabaseType::ConfigNS , b.obj() ); conn.done(); // If our name is exactly the same as the name we want, try loading // the database again. if (!dbObj.isEmpty() && dbObj[DatabaseType::name()].String() == database) { if (dbConfig->load()) return dbConfig; } // TODO: This really shouldn't fall through, but without metadata // management there's no good way to make sure this works all the time // when the database is getting rapidly created and dropped. // For now, just do exactly what we used to do. if ( ! dbObj.isEmpty() ) { uasserted( DatabaseDifferCaseCode, str::stream() << "can't have 2 databases that just differ on case " << " have: " << dbObj[DatabaseType::name()].String() << " want to add: " << database ); } } Shard primary; if ( database == "admin" ) { primary = configServer.getPrimary(); } else if ( shardNameHint.empty() ) { primary = Shard::pick(); } else { // use the shard name if provided Shard shard; shard.reset( shardNameHint ); primary = shard; } if ( primary.ok() ) { dbConfig->setPrimary( primary.getName() ); // saves 'cc' to configDB log() << "\t put [" << database << "] on: " << primary << endl; } else { uasserted( 10185 , "can't find a shard to put new db on" ); } } catch( DBException& e ){ e.addContext( "error creating initial database config information" ); warning() << e.what() << endl; dbConfig.reset(); throw; } } else { dbConfig.reset(); } } } return dbConfig; } void Grid::removeDB( const std::string& database ) { uassert( 10186 , "removeDB expects db name" , database.find( '.' ) == string::npos ); scoped_lock l( _lock ); _databases.erase( database ); } void Grid::removeDBIfExists( const DBConfig& database ) { scoped_lock l( _lock ); map<string,DBConfigPtr>::iterator it = _databases.find( database.getName() ); if( it != _databases.end() && it->second.get() == &database ){ _databases.erase( it ); log() << "erased database " << database.getName() << " from local registry" << endl; } else{ log() << database.getName() << "already erased from local registry" << endl; } } bool Grid::allowLocalHost() const { return _allowLocalShard; } void Grid::setAllowLocalHost( bool allow ) { _allowLocalShard = allow; } bool Grid::addShard( string* name , const ConnectionString& servers , long long maxSize , string& errMsg ) { // name can be NULL, so provide a dummy one here to avoid testing it elsewhere string nameInternal; if ( ! name ) { name = &nameInternal; } ReplicaSetMonitorPtr rsMonitor; // Check whether the host (or set) exists and run several sanity checks on this request. // There are two set of sanity checks: making sure adding this particular shard is consistent // with the replica set state (if it exists) and making sure this shards databases can be // brought into the grid without conflict. vector<string> dbNames; try { ScopedDbConnection newShardConn(servers.toString()); newShardConn->getLastError(); if ( newShardConn->type() == ConnectionString::SYNC ) { newShardConn.done(); errMsg = "can't use sync cluster as a shard. for replica set, have to use <setname>/<server1>,<server2>,..."; return false; } BSONObj resIsMongos; bool ok = newShardConn->runCommand( "admin" , BSON( "isdbgrid" << 1 ) , resIsMongos ); // should return ok=0, cmd not found if it's a normal mongod if ( ok ) { errMsg = "can't add a mongos process as a shard"; newShardConn.done(); return false; } BSONObj resIsMaster; ok = newShardConn->runCommand( "admin" , BSON( "isMaster" << 1 ) , resIsMaster ); if ( !ok ) { ostringstream ss; ss << "failed running isMaster: " << resIsMaster; errMsg = ss.str(); newShardConn.done(); return false; } // if the shard has only one host, make sure it is not part of a replica set string setName = resIsMaster["setName"].str(); string commandSetName = servers.getSetName(); if ( commandSetName.empty() && ! setName.empty() ) { ostringstream ss; ss << "host is part of set " << setName << ", use replica set url format <setname>/<server1>,<server2>,...."; errMsg = ss.str(); newShardConn.done(); return false; } if ( !commandSetName.empty() && setName.empty() ) { ostringstream ss; ss << "host did not return a set name, is the replica set still initializing? " << resIsMaster; errMsg = ss.str(); newShardConn.done(); return false; } // if the shard is part of replica set, make sure it is the right one if ( ! commandSetName.empty() && ( commandSetName != setName ) ) { ostringstream ss; ss << "host is part of a different set: " << setName; errMsg = ss.str(); newShardConn.done(); return false; } if( setName.empty() ) { // check this isn't a --configsvr BSONObj res; bool ok = newShardConn->runCommand("admin",BSON("replSetGetStatus"<<1),res); ostringstream ss; if( !ok && res["info"].type() == String && res["info"].String() == "configsvr" ) { errMsg = "the specified mongod is a --configsvr and should thus not be a shard server"; newShardConn.done(); return false; } } // if the shard is part of a replica set, make sure all the hosts mentioned in 'servers' are part of // the set. It is fine if not all members of the set are present in 'servers'. bool foundAll = true; string offendingHost; if ( ! commandSetName.empty() ) { set<string> hostSet; BSONObjIterator iter( resIsMaster["hosts"].Obj() ); while ( iter.more() ) { hostSet.insert( iter.next().String() ); // host:port } if ( resIsMaster["passives"].isABSONObj() ) { BSONObjIterator piter( resIsMaster["passives"].Obj() ); while ( piter.more() ) { hostSet.insert( piter.next().String() ); // host:port } } if ( resIsMaster["arbiters"].isABSONObj() ) { BSONObjIterator piter( resIsMaster["arbiters"].Obj() ); while ( piter.more() ) { hostSet.insert( piter.next().String() ); // host:port } } vector<HostAndPort> hosts = servers.getServers(); for ( size_t i = 0 ; i < hosts.size() ; i++ ) { if (!hosts[i].hasPort()) { hosts[i] = HostAndPort(hosts[i].host(), hosts[i].port()); } string host = hosts[i].toString(); // host:port if ( hostSet.find( host ) == hostSet.end() ) { offendingHost = host; foundAll = false; break; } } } if ( ! foundAll ) { ostringstream ss; ss << "in seed list " << servers.toString() << ", host " << offendingHost << " does not belong to replica set " << setName; errMsg = ss.str(); newShardConn.done(); return false; } // shard name defaults to the name of the replica set if ( name->empty() && ! setName.empty() ) *name = setName; // In order to be accepted as a new shard, that mongod must not have any database name that exists already // in any other shards. If that test passes, the new shard's databases are going to be entered as // non-sharded db's whose primary is the newly added shard. BSONObj resListDB; ok = newShardConn->runCommand( "admin" , BSON( "listDatabases" << 1 ) , resListDB ); if ( !ok ) { ostringstream ss; ss << "failed listing " << servers.toString() << "'s databases:" << resListDB; errMsg = ss.str(); newShardConn.done(); return false; } BSONObjIterator i( resListDB["databases"].Obj() ); while ( i.more() ) { BSONObj dbEntry = i.next().Obj(); const string& dbName = dbEntry["name"].String(); if ( _isSpecialLocalDB( dbName ) ) { // 'local', 'admin', and 'config' are system DBs and should be excluded here continue; } else { dbNames.push_back( dbName ); } } if ( newShardConn->type() == ConnectionString::SET ) rsMonitor = ReplicaSetMonitor::get( setName ); newShardConn.done(); } catch ( DBException& e ) { if ( servers.type() == ConnectionString::SET ) { ReplicaSetMonitor::remove( servers.getSetName() ); } ostringstream ss; ss << "couldn't connect to new shard "; ss << e.what(); errMsg = ss.str(); return false; } // check that none of the existing shard candidate's db's exist elsewhere for ( vector<string>::const_iterator it = dbNames.begin(); it != dbNames.end(); ++it ) { DBConfigPtr config = getDBConfig( *it , false ); if ( config.get() != NULL ) { ostringstream ss; ss << "can't add shard " << servers.toString() << " because a local database '" << *it; ss << "' exists in another " << config->getPrimary().toString(); errMsg = ss.str(); return false; } } // if a name for a shard wasn't provided, pick one. if ( name->empty() && ! _getNewShardName( name ) ) { errMsg = "error generating new shard name"; return false; } // build the ConfigDB shard document BSONObjBuilder b; b.append(ShardType::name(), *name); b.append(ShardType::host(), rsMonitor ? rsMonitor->getServerAddress() : servers.toString()); if (maxSize > 0) { b.append(ShardType::maxSize(), maxSize); } BSONObj shardDoc = b.obj(); { ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30); // check whether the set of hosts (or single host) is not an already a known shard BSONObj old = conn->findOne(ShardType::ConfigNS, BSON(ShardType::host(servers.toString()))); if ( ! old.isEmpty() ) { errMsg = "host already used"; conn.done(); return false; } conn.done(); } log() << "going to add shard: " << shardDoc << endl; Status result = clusterInsert( ShardType::ConfigNS, shardDoc, WriteConcernOptions::AllConfigs, NULL ); if ( !result.isOK() ) { errMsg = result.reason(); log() << "error adding shard: " << shardDoc << " err: " << errMsg << endl; return false; } Shard::reloadShardInfo(); // add all databases of the new shard for ( vector<string>::const_iterator it = dbNames.begin(); it != dbNames.end(); ++it ) { DBConfigPtr config = getDBConfig( *it , true , *name ); if ( ! config ) { log() << "adding shard " << servers << " even though could not add database " << *it << endl; } } // Record in changelog BSONObjBuilder shardDetails; shardDetails.append("name", *name); shardDetails.append("host", servers.toString()); configServer.logChange("addShard", "", shardDetails.obj()); return true; } bool Grid::knowAboutShard( const string& name ) const { ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30); BSONObj shard = conn->findOne(ShardType::ConfigNS, BSON(ShardType::host(name))); conn.done(); return ! shard.isEmpty(); } bool Grid::_getNewShardName( string* name ) const { DEV verify( name ); bool ok = false; int count = 0; ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30); BSONObj o = conn->findOne(ShardType::ConfigNS, Query(fromjson("{" + ShardType::name() + ": /^shard/}")) .sort(BSON(ShardType::name() << -1 ))); if ( ! o.isEmpty() ) { string last = o[ShardType::name()].String(); istringstream is( last.substr( 5 ) ); is >> count; count++; } if (count < 9999) { stringstream ss; ss << "shard" << setfill('0') << setw(4) << count; *name = ss.str(); ok = true; } conn.done(); return ok; } /* * Returns whether balancing is enabled, with optional namespace "ns" parameter for balancing on a particular * collection. */ bool Grid::shouldBalance(const SettingsType& balancerSettings) const { // Allow disabling the balancer for testing if (MONGO_FAIL_POINT(neverBalance)) return false; if (balancerSettings.isBalancerStoppedSet() && balancerSettings.getBalancerStopped()) { return false; } if (balancerSettings.isBalancerActiveWindowSet()) { boost::posix_time::ptime now = boost::posix_time::second_clock::local_time(); return _inBalancingWindow(balancerSettings.getBalancerActiveWindow(), now); } return true; } bool Grid::getBalancerSettings(SettingsType* settings, string* errMsg) const { BSONObj balancerDoc; ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30); try { balancerDoc = conn->findOne(SettingsType::ConfigNS, BSON(SettingsType::key("balancer"))); conn.done(); } catch (const DBException& ex) { *errMsg = str::stream() << "failed to read balancer settings from " << conn.getHost() << ": " << causedBy(ex); return false; } return settings->parseBSON(balancerDoc, errMsg); } bool Grid::getConfigShouldBalance() const { SettingsType balSettings; string errMsg; if (!getBalancerSettings(&balSettings, &errMsg)) { warning() << errMsg; return false; } if (!balSettings.isKeySet()) { // Balancer settings doc does not exist. Default to yes. return true; } return shouldBalance(balSettings); } bool Grid::getCollShouldBalance(const std::string& ns) const { BSONObj collDoc; ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30); try { collDoc = conn->findOne(CollectionType::ConfigNS, BSON(CollectionType::ns(ns))); conn.done(); } catch (const DBException& e){ conn.kill(); warning() << "could not determine whether balancer should be running, error getting" << "config data from " << conn.getHost() << causedBy(e) << endl; // if anything goes wrong, we shouldn't try balancing return false; } return !collDoc[CollectionType::noBalance()].trueValue(); } bool Grid::_inBalancingWindow( const BSONObj& balancerDoc , const boost::posix_time::ptime& now ) { // check the 'activeWindow' marker // if present, it is an interval during the day when the balancer should be active // { start: "08:00" , stop: "19:30" }, strftime format is %H:%M BSONElement windowElem = balancerDoc[SettingsType::balancerActiveWindow()]; if ( windowElem.eoo() ) { return true; } // check if both 'start' and 'stop' are present if ( ! windowElem.isABSONObj() ) { warning() << "'activeWindow' format is { start: \"hh:mm\" , stop: ... }" << balancerDoc << endl; return true; } BSONObj intervalDoc = windowElem.Obj(); const string start = intervalDoc["start"].str(); const string stop = intervalDoc["stop"].str(); if ( start.empty() || stop.empty() ) { warning() << "must specify both start and end of balancing window: " << intervalDoc << endl; return true; } // check that both 'start' and 'stop' are valid time-of-day boost::posix_time::ptime startTime, stopTime; if ( ! toPointInTime( start , &startTime ) || ! toPointInTime( stop , &stopTime ) ) { warning() << "cannot parse active window (use hh:mm 24hs format): " << intervalDoc << endl; return true; } LOG(1).stream() << "_inBalancingWindow: " << " now: " << now << " startTime: " << startTime << " stopTime: " << stopTime; // allow balancing if during the activeWindow // note that a window may be open during the night if ( stopTime > startTime ) { if ( ( now >= startTime ) && ( now <= stopTime ) ) { return true; } } else if ( startTime > stopTime ) { if ( ( now >=startTime ) || ( now <= stopTime ) ) { return true; } } return false; } bool Grid::_isSpecialLocalDB( const string& dbName ) { return ( dbName == "local" ) || ( dbName == "admin" ) || ( dbName == "config" ); } void Grid::flushConfig() { scoped_lock lk( _lock ); _databases.clear(); } BSONObj Grid::getConfigSetting( const std::string& name ) const { ScopedDbConnection conn(configServer.getPrimary().getConnString(), 30); BSONObj result = conn->findOne( SettingsType::ConfigNS, BSON( SettingsType::key(name) ) ); conn.done(); return result; } Grid grid; // unit tests class BalancingWindowUnitTest : public StartupTest { public: void run() { if (!isMongos()) return; // T0 < T1 < now < T2 < T3 and Error const string T0 = "9:00"; const string T1 = "11:00"; boost::posix_time::ptime now( currentDate(), boost::posix_time::hours( 13 ) + boost::posix_time::minutes( 48 ) ); const string T2 = "17:00"; const string T3 = "21:30"; const string E = "28:35"; // closed in the past BSONObj w1 = BSON( SettingsType::balancerActiveWindow( BSON( "start" << T0 << "stop" << T1 ) ) ); // not opened until the future BSONObj w2 = BSON( SettingsType::balancerActiveWindow( BSON( "start" << T2 << "stop" << T3 ) ) ); // open now BSONObj w3 = BSON( SettingsType::balancerActiveWindow( BSON( "start" << T1 << "stop" << T2 ) ) ); // open since last day BSONObj w4 = BSON( SettingsType::balancerActiveWindow( BSON( "start" << T3 << "stop" << T2 ) ) ); verify( ! Grid::_inBalancingWindow( w1 , now ) ); verify( ! Grid::_inBalancingWindow( w2 , now ) ); verify( Grid::_inBalancingWindow( w3 , now ) ); verify( Grid::_inBalancingWindow( w4 , now ) ); // bad input should not stop the balancer // empty window BSONObj w5; // missing stop BSONObj w6 = BSON( SettingsType::balancerActiveWindow( BSON( "start" << 1 ) ) ); // missing start BSONObj w7 = BSON( SettingsType::balancerActiveWindow( BSON( "stop" << 1 ) ) ); // active window marker missing BSONObj w8 = BSON( "wrongMarker" << 1 << "start" << 1 << "stop" << 1 ); // garbage in window BSONObj w9 = BSON( SettingsType::balancerActiveWindow( BSON( "start" << T3 << "stop" << E ) ) ); verify( Grid::_inBalancingWindow( w5 , now ) ); verify( Grid::_inBalancingWindow( w6 , now ) ); verify( Grid::_inBalancingWindow( w7 , now ) ); verify( Grid::_inBalancingWindow( w8 , now ) ); verify( Grid::_inBalancingWindow( w9 , now ) ); LOG(1) << "BalancingWidowObjTest passed" << endl; } } BalancingWindowObjTest; }
/* +----------------------------------------------------------------------+ | HipHop for PHP | +----------------------------------------------------------------------+ | Copyright (c) 2010-2013 Facebook, Inc. (http://www.facebook.com) | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ */ #include "hphp/compiler/analysis/class_scope.h" #include "hphp/compiler/analysis/analysis_result.h" #include "hphp/compiler/analysis/code_error.h" #include "hphp/compiler/analysis/constant_table.h" #include "hphp/compiler/analysis/file_scope.h" #include "hphp/compiler/analysis/function_scope.h" #include "hphp/compiler/analysis/variable_table.h" #include "hphp/compiler/construct.h" #include "hphp/compiler/expression/class_constant_expression.h" #include "hphp/compiler/expression/closure_expression.h" #include "hphp/compiler/expression/constant_expression.h" #include "hphp/compiler/expression/scalar_expression.h" #include "hphp/compiler/expression/unary_op_expression.h" #include "hphp/compiler/expression/simple_function_call.h" #include "hphp/compiler/option.h" #include "hphp/compiler/parser/parser.h" #include "hphp/compiler/statement/interface_statement.h" #include "hphp/compiler/statement/function_statement.h" #include "hphp/compiler/statement/method_statement.h" #include "hphp/compiler/statement/statement_list.h" #include "hphp/runtime/base/builtin_functions.h" #include "hphp/runtime/base/class_info.h" #include "hphp/compiler/statement/class_variable.h" #include "hphp/compiler/statement/class_constant.h" #include "hphp/compiler/statement/use_trait_statement.h" #include "hphp/compiler/statement/trait_prec_statement.h" #include "hphp/compiler/statement/trait_alias_statement.h" #include "hphp/runtime/base/zend_string.h" #include "hphp/util/util.h" #include <boost/foreach.hpp> #include <boost/tuple/tuple.hpp> using namespace HPHP; using std::map; /////////////////////////////////////////////////////////////////////////////// ClassScope::ClassScope(KindOf kindOf, const std::string &name, const std::string &parent, const vector<string> &bases, const std::string &docComment, StatementPtr stmt, const std::vector<UserAttributePtr> &attrs) : BlockScope(name, docComment, stmt, BlockScope::ClassScope), m_parent(parent), m_bases(bases), m_attribute(0), m_redeclaring(-1), m_kindOf(kindOf), m_derivesFromRedeclaring(FromNormal), m_traitStatus(NOT_FLATTENED), m_volatile(false), m_persistent(false), m_derivedByDynamic(false), m_sep(false), m_needsCppCtor(false), m_needsInit(true), m_knownBases(0) { m_dynamic = Option::IsDynamicClass(m_name); // dynamic class is also volatile m_volatile = Option::AllVolatile || m_dynamic; for (unsigned i = 0; i < attrs.size(); ++i) { if (m_userAttributes.find(attrs[i]->getName()) != m_userAttributes.end()) { attrs[i]->parseTimeFatal(Compiler::DeclaredAttributeTwice, "Redeclared attribute %s", attrs[i]->getName().c_str()); } m_userAttributes[attrs[i]->getName()] = attrs[i]->getExp(); } assert(m_parent.empty() || (!m_bases.empty() && m_bases[0] == m_parent)); } // System ClassScope::ClassScope(AnalysisResultPtr ar, const std::string &name, const std::string &parent, const std::vector<std::string> &bases, const FunctionScopePtrVec &methods) : BlockScope(name, "", StatementPtr(), BlockScope::ClassScope), m_parent(parent), m_bases(bases), m_attribute(0), m_redeclaring(-1), m_kindOf(KindOfObjectClass), m_derivesFromRedeclaring(FromNormal), m_traitStatus(NOT_FLATTENED), m_dynamic(false), m_volatile(false), m_persistent(false), m_derivedByDynamic(false), m_sep(false), m_needsCppCtor(false), m_needsInit(true), m_knownBases(0) { BOOST_FOREACH(FunctionScopePtr f, methods) { if (f->getName() == "__construct") setAttribute(HasConstructor); else if (f->getName() == "__destruct") setAttribute(HasDestructor); else if (f->getName() == "__get") setAttribute(HasUnknownPropGetter); else if (f->getName() == "__set") setAttribute(HasUnknownPropSetter); else if (f->getName() == "__call") setAttribute(HasUnknownMethodHandler); else if (f->getName() == "__callstatic") { setAttribute(HasUnknownStaticMethodHandler); } else if (f->getName() == "__isset") setAttribute(HasUnknownPropTester); else if (f->getName() == "__unset") setAttribute(HasPropUnsetter); else if (f->getName() == "__invoke") setAttribute(HasInvokeMethod); addFunction(ar, f); } setAttribute(Extension); setAttribute(System); assert(m_parent.empty() || (!m_bases.empty() && m_bases[0] == m_parent)); } const std::string &ClassScope::getOriginalName() const { if (m_stmt) { return dynamic_pointer_cast<InterfaceStatement>(m_stmt)-> getOriginalName(); } return m_originalName; } // like getId(), but without the label formatting std::string ClassScope::getDocName() const { string name = getOriginalName(); if (m_redeclaring < 0) { return name; } return name + Option::IdPrefix + boost::lexical_cast<std::string>(m_redeclaring); } std::string ClassScope::getId() const { string name = CodeGenerator::FormatLabel(getOriginalName()); if (m_redeclaring < 0) { return name; } return name + Option::IdPrefix + boost::lexical_cast<std::string>(m_redeclaring); } bool ClassScope::NeedStaticArray(ClassScopePtr cls, FunctionScopePtr func) { return cls && cls->getAttribute(NotFinal) && !func->isPrivate(); } /////////////////////////////////////////////////////////////////////////////// void ClassScope::derivedMagicMethods(ClassScopePtr super) { super->setAttribute(NotFinal); if (derivedByDynamic()) { super->m_derivedByDynamic = true; } if (m_attribute & (HasUnknownPropGetter| MayHaveUnknownPropGetter| InheritsUnknownPropGetter)) { super->setAttribute(MayHaveUnknownPropGetter); } if (m_attribute & (HasUnknownPropSetter| MayHaveUnknownPropSetter| InheritsUnknownPropSetter)) { super->setAttribute(MayHaveUnknownPropSetter); } if (m_attribute & (HasUnknownPropTester| MayHaveUnknownPropTester| InheritsUnknownPropTester)) { super->setAttribute(MayHaveUnknownPropTester); } if (m_attribute & (HasPropUnsetter| MayHavePropUnsetter| InheritsPropUnsetter)) { super->setAttribute(MayHavePropUnsetter); } if (m_attribute & (HasUnknownMethodHandler| MayHaveUnknownMethodHandler| InheritsUnknownMethodHandler)) { super->setAttribute(MayHaveUnknownMethodHandler); } if (m_attribute & (HasUnknownStaticMethodHandler| MayHaveUnknownStaticMethodHandler| InheritsUnknownStaticMethodHandler)) { super->setAttribute(MayHaveUnknownStaticMethodHandler); } if (m_attribute & (HasInvokeMethod| MayHaveInvokeMethod| InheritsInvokeMethod)) { super->setAttribute(MayHaveInvokeMethod); } if (m_attribute & (HasArrayAccess| MayHaveArrayAccess| InheritsArrayAccess)) { super->setAttribute(MayHaveArrayAccess); } } void ClassScope::inheritedMagicMethods(ClassScopePtr super) { if (super->m_attribute & UsesUnknownTrait) { setAttribute(UsesUnknownTrait); } if (super->m_attribute & (HasUnknownPropGetter|InheritsUnknownPropGetter)) { setAttribute(InheritsUnknownPropGetter); } if (super->m_attribute & (HasUnknownPropSetter|InheritsUnknownPropSetter)) { setAttribute(InheritsUnknownPropSetter); } if (super->m_attribute & (HasUnknownPropTester|InheritsUnknownPropTester)) { setAttribute(InheritsUnknownPropTester); } if (super->m_attribute & (HasPropUnsetter|InheritsPropUnsetter)) { setAttribute(InheritsPropUnsetter); } if (super->m_attribute & (HasUnknownMethodHandler|InheritsUnknownMethodHandler)) { setAttribute(InheritsUnknownMethodHandler); } if (super->m_attribute & (HasUnknownStaticMethodHandler|InheritsUnknownStaticMethodHandler)) { setAttribute(InheritsUnknownStaticMethodHandler); } if (super->m_attribute & (HasInvokeMethod|InheritsInvokeMethod)) { setAttribute(InheritsInvokeMethod); } if (super->m_attribute & (HasArrayAccess|InheritsArrayAccess)) { setAttribute(InheritsArrayAccess); } } bool ClassScope::implementsArrayAccess() { return getAttribute(MayHaveArrayAccess) | getAttribute(HasArrayAccess) | getAttribute(InheritsArrayAccess); } bool ClassScope::implementsAccessor(int prop) { if (m_attribute & prop) return true; if (prop & MayHaveUnknownPropGetter) { prop |= HasUnknownPropGetter | InheritsUnknownPropGetter; } if (prop & MayHaveUnknownPropSetter) { prop |= HasUnknownPropSetter | InheritsUnknownPropSetter; } if (prop & MayHaveUnknownPropTester) { prop |= HasUnknownPropTester | InheritsUnknownPropTester; } if (prop & MayHavePropUnsetter) { prop |= HasPropUnsetter | InheritsPropUnsetter; } return m_attribute & prop; } void ClassScope::checkDerivation(AnalysisResultPtr ar, hphp_string_iset &seen) { seen.insert(m_name); hphp_string_iset bases; for (int i = m_bases.size() - 1; i >= 0; i--) { const string &base = m_bases[i]; if (seen.find(base) != seen.end() || bases.find(base) != bases.end()) { Compiler::Error( Compiler::InvalidDerivation, m_stmt, "The class hierarchy contains a circular reference involving " + base); if (i == 0 && !m_parent.empty()) { assert(base == m_parent); m_parent.clear(); } m_bases.erase(m_bases.begin() + i); continue; } bases.insert(base); ClassScopePtrVec parents = ar->findClasses(Util::toLower(base)); for (unsigned int j = 0; j < parents.size(); j++) { parents[j]->checkDerivation(ar, seen); } } seen.erase(m_name); } void ClassScope::collectMethods(AnalysisResultPtr ar, StringToFunctionScopePtrMap &funcs, bool collectPrivate /* = true */, bool forInvoke /* = false */) { // add all functions this class has for (FunctionScopePtrVec::const_iterator iter = m_functionsVec.begin(); iter != m_functionsVec.end(); ++iter) { const FunctionScopePtr &fs = *iter; if (!collectPrivate && fs->isPrivate()) continue; FunctionScopePtr &func = funcs[fs->getName()]; if (!func) { func = fs; } else { func->setVirtual(); fs->setVirtual(); fs->setHasOverride(); if (fs->isFinal()) { std::string s__MockClass = "__MockClass"; ClassScopePtr derivedClass = func->getContainingClass(); if (derivedClass->m_userAttributes.find(s__MockClass) == derivedClass->m_userAttributes.end()) { Compiler::Error(Compiler::InvalidOverride, fs->getStmt(), func->getStmt()); } } } } int n = forInvoke ? m_parent.empty() ? 0 : 1 : m_bases.size(); // walk up for (int i = 0; i < n; i++) { const string &base = m_bases[i]; ClassScopePtr super = ar->findClass(base); if (super) { if (super->isRedeclaring()) { if (forInvoke) continue; const ClassScopePtrVec &classes = ar->findRedeclaredClasses(base); StringToFunctionScopePtrMap pristine(funcs); BOOST_FOREACH(ClassScopePtr cls, classes) { cls->m_derivedByDynamic = true; StringToFunctionScopePtrMap cur(pristine); derivedMagicMethods(cls); cls->collectMethods(ar, cur, false, forInvoke); inheritedMagicMethods(cls); funcs.insert(cur.begin(), cur.end()); cls->getVariables()-> forceVariants(ar, VariableTable::AnyNonPrivateVars); } if (base == m_parent) { m_derivesFromRedeclaring = DirectFromRedeclared; getVariables()->forceVariants(ar, VariableTable::AnyNonPrivateVars, false); getVariables()->setAttribute(VariableTable::NeedGlobalPointer); } else if (isInterface()) { m_derivesFromRedeclaring = DirectFromRedeclared; } setVolatile(); } else { derivedMagicMethods(super); super->collectMethods(ar, funcs, false, forInvoke); inheritedMagicMethods(super); if (super->derivesFromRedeclaring()) { if (base == m_parent) { m_derivesFromRedeclaring = IndirectFromRedeclared; getVariables()->forceVariants(ar, VariableTable::AnyNonPrivateVars); } else if (isInterface()) { m_derivesFromRedeclaring = IndirectFromRedeclared; } setVolatile(); } else if (super->isVolatile()) { setVolatile(); } } } else { Compiler::Error(Compiler::UnknownBaseClass, m_stmt, base); if (base == m_parent) { ar->declareUnknownClass(m_parent); m_derivesFromRedeclaring = DirectFromRedeclared; getVariables()->setAttribute(VariableTable::NeedGlobalPointer); getVariables()->forceVariants(ar, VariableTable::AnyNonPrivateVars); setVolatile(); } else { if (isInterface()) { m_derivesFromRedeclaring = DirectFromRedeclared; } m_bases.erase(m_bases.begin() + i); n--; i--; } } } } void ClassScope::importTraitProperties(AnalysisResultPtr ar) { for (unsigned i = 0; i < m_usedTraitNames.size(); i++) { ClassScopePtr tCls = ar->findClass(m_usedTraitNames[i]); if (!tCls) continue; ClassStatementPtr tStmt = dynamic_pointer_cast<ClassStatement>(tCls->getStmt()); StatementListPtr tStmts = tStmt->getStmts(); if (!tStmts) continue; for (int s = 0; s < tStmts->getCount(); s++) { ClassVariablePtr prop = dynamic_pointer_cast<ClassVariable>((*tStmts)[s]); if (prop) { ClassVariablePtr cloneProp = dynamic_pointer_cast<ClassVariable>( dynamic_pointer_cast<ClassStatement>(m_stmt)->addClone(prop)); cloneProp->resetScope(shared_from_this(), true); cloneProp->addTraitPropsToScope(ar, dynamic_pointer_cast<ClassScope>(shared_from_this())); } } } } MethodStatementPtr ClassScope::importTraitMethod(const TraitMethod& traitMethod, AnalysisResultPtr ar, string methName, GeneratorRenameMap& genRenameMap, const std::map<string, MethodStatementPtr>& importedTraitMethods) { MethodStatementPtr meth = traitMethod.m_method; string origMethName = traitMethod.m_originalName; ModifierExpressionPtr modifiers = traitMethod.m_modifiers; if (meth->getOrigGeneratorFunc()) { const string &name = meth->getOrigGeneratorFunc()->getName(); if (!importedTraitMethods.count(name)) { // Dont import the generator, if the origGenerator wasnt imported // this happens when a generator in the trait is hidden by a non-generator // method in the importing class. return MethodStatementPtr(); } } MethodStatementPtr cloneMeth = dynamic_pointer_cast<MethodStatement>( dynamic_pointer_cast<ClassStatement>(m_stmt)->addClone(meth)); cloneMeth->setName(methName); cloneMeth->setOriginalName(origMethName); // Note: keep previous modifiers if none specified when importing the trait if (modifiers && modifiers->getCount()) { cloneMeth->setModifiers(modifiers); } FunctionScopePtr funcScope = meth->getFunctionScope(); // Trait method typehints, self and parent, need to be converted ClassScopePtr cScope = dynamic_pointer_cast<ClassScope>(shared_from_this()); cloneMeth->fixupSelfAndParentTypehints( cScope ); // Generator methods need to be renamed, otherwise code gen produces multiple // continuation classes with the same name if (funcScope->isGenerator()) { const string& newName = getNewGeneratorName(funcScope, genRenameMap); methName = origMethName = newName; cloneMeth->setName(newName); cloneMeth->setOriginalName(newName); } FunctionScopePtr cloneFuncScope (new HPHP::FunctionScope(funcScope, ar, methName, origMethName, cloneMeth, cloneMeth->getModifiers())); cloneMeth->resetScope(cloneFuncScope, true); cloneFuncScope->setOuterScope(shared_from_this()); informClosuresAboutScopeClone(cloneMeth, cloneFuncScope, ar); cloneMeth->addTraitMethodToScope(ar, dynamic_pointer_cast<ClassScope>(shared_from_this())); // Preserve original filename (as this varies per-function and not per-unit // in the case of methods imported from flattened traits) cloneMeth->setOriginalFilename(meth->getFileScope()->getName()); return cloneMeth; } void ClassScope::informClosuresAboutScopeClone( ConstructPtr root, FunctionScopePtr outerScope, AnalysisResultPtr ar) { if (!root) { return; } for (int i = 0; i < root->getKidCount(); i++) { ConstructPtr cons = root->getNthKid(i); ClosureExpressionPtr closure = dynamic_pointer_cast<ClosureExpression>(cons); if (!closure) { informClosuresAboutScopeClone(cons, outerScope, ar); continue; } FunctionStatementPtr func = closure->getClosureFunction(); HPHP::FunctionScopePtr funcScope = func->getFunctionScope(); assert(funcScope->isClosure()); funcScope->addClonedTraitOuterScope(outerScope); // Don't need to recurse } } void ClassScope::addImportTraitMethod(const TraitMethod &traitMethod, const string &methName) { m_importMethToTraitMap[methName].push_back(traitMethod); } void ClassScope::setImportTraitMethodModifiers(const string &methName, ClassScopePtr traitCls, ModifierExpressionPtr modifiers) { TraitMethodList &methList = m_importMethToTraitMap[methName]; for (TraitMethodList::iterator iter = methList.begin(); iter != methList.end(); iter++) { if (iter->m_trait == traitCls) { iter->m_modifiers = modifiers; return; } } } MethodStatementPtr ClassScope::findTraitMethod(AnalysisResultPtr ar, ClassScopePtr trait, const string &methodName, std::set<ClassScopePtr> &visitedTraits) { if (visitedTraits.find(trait) != visitedTraits.end()) { return MethodStatementPtr(); } visitedTraits.insert(trait); ClassStatementPtr tStmt = dynamic_pointer_cast<ClassStatement>(trait->getStmt()); StatementListPtr tStmts = tStmt->getStmts(); // Look in the current trait for (int s = 0; s < tStmts->getCount(); s++) { MethodStatementPtr meth = dynamic_pointer_cast<MethodStatement>((*tStmts)[s]); if (meth) { // Handle methods if (meth->getName() == methodName) { return meth; } } } // Look into children traits for (int s = 0; s < tStmts->getCount(); s++) { UseTraitStatementPtr useTraitStmt = dynamic_pointer_cast<UseTraitStatement>((*tStmts)[s]); if (useTraitStmt) { vector<string> usedTraits; useTraitStmt->getUsedTraitNames(usedTraits); for (unsigned i = 0; i < usedTraits.size(); i++) { MethodStatementPtr foundMethod = findTraitMethod(ar, ar->findClass(usedTraits[i]), methodName, visitedTraits); if (foundMethod) return foundMethod; } } } return MethodStatementPtr(); // not found } void ClassScope::findTraitMethodsToImport(AnalysisResultPtr ar, ClassScopePtr trait) { ClassStatementPtr tStmt = dynamic_pointer_cast<ClassStatement>(trait->getStmt()); StatementListPtr tStmts = tStmt->getStmts(); if (!tStmts) return; for (int s = 0; s < tStmts->getCount(); s++) { MethodStatementPtr meth = dynamic_pointer_cast<MethodStatement>((*tStmts)[s]); if (meth) { TraitMethod traitMethod(trait, meth, ModifierExpressionPtr(), MethodStatementPtr()); addImportTraitMethod(traitMethod, meth->getName()); } } } void ClassScope::applyTraitPrecRule(TraitPrecStatementPtr stmt) { const string methodName = Util::toLower(stmt->getMethodName()); const string selectedTraitName = Util::toLower(stmt->getTraitName()); std::set<string> otherTraitNames; stmt->getOtherTraitNames(otherTraitNames); map<string,TraitMethodList>::iterator methIter = m_importMethToTraitMap.find(methodName); if (methIter == m_importMethToTraitMap.end()) { Compiler::Error(Compiler::UnknownObjectMethod, stmt); return; } bool foundSelectedTrait = false; TraitMethodList &methList = methIter->second; for (TraitMethodList::iterator nextTraitIter = methList.begin(); nextTraitIter != methList.end(); ) { TraitMethodList::iterator traitIter = nextTraitIter++; string availTraitName = traitIter->m_trait->getName(); if (availTraitName == selectedTraitName) { foundSelectedTrait = true; } else { if (otherTraitNames.find(availTraitName) != otherTraitNames.end()) { otherTraitNames.erase(availTraitName); methList.erase(traitIter); } } } // Report error if didn't find the selected trait if (!foundSelectedTrait) { Compiler::Error(Compiler::UnknownTrait, stmt); } // Sanity checking: otherTraitNames should be empty now if (otherTraitNames.size()) { Compiler::Error(Compiler::UnknownTrait, stmt); } } bool ClassScope::hasMethod(const string &methodName) const { return m_functions.find(methodName) != m_functions.end(); } ClassScopePtr ClassScope::findSingleTraitWithMethod(AnalysisResultPtr ar, const string &methodName) const { ClassScopePtr trait = ClassScopePtr(); for (unsigned i = 0; i < m_usedTraitNames.size(); i++) { ClassScopePtr tCls = ar->findClass(m_usedTraitNames[i]); if (!tCls) continue; if (tCls->hasMethod(methodName)) { if (trait) { // more than one trait contains method return ClassScopePtr(); } trait = tCls; } } return trait; } void ClassScope::addTraitAlias(TraitAliasStatementPtr aliasStmt) { const string &traitName = aliasStmt->getTraitName(); const string &origMethName = aliasStmt->getMethodName(); const string &newMethName = aliasStmt->getNewMethodName(); string origName = traitName.empty() ? "(null)" : traitName; origName += "::" + origMethName; m_traitAliases.push_back(std::pair<string, string>(newMethName, origName)); } void ClassScope::applyTraitAliasRule(AnalysisResultPtr ar, TraitAliasStatementPtr stmt) { const string traitName = Util::toLower(stmt->getTraitName()); const string origMethName = Util::toLower(stmt->getMethodName()); const string newMethName = Util::toLower(stmt->getNewMethodName()); // Get the trait's "class" ClassScopePtr traitCls; if (traitName.empty()) { traitCls = findSingleTraitWithMethod(ar, origMethName); } else { traitCls = ar->findClass(traitName); } if (!traitCls || !(traitCls->isTrait())) { Compiler::Error(Compiler::UnknownTrait, stmt); return; } // Keep record of alias rule addTraitAlias(stmt); // Get the method std::set<ClassScopePtr> visitedTraits; MethodStatementPtr methStmt = findTraitMethod(ar, traitCls, origMethName, visitedTraits); if (!methStmt) { Compiler::Error(Compiler::UnknownTraitMethod, stmt); return; } if (origMethName == newMethName) { setImportTraitMethodModifiers(origMethName, traitCls, stmt->getModifiers()); } else { // Insert renamed entry into the set of methods to be imported TraitMethod traitMethod(traitCls, methStmt, stmt->getModifiers(), stmt, stmt->getNewMethodName()); addImportTraitMethod(traitMethod, newMethName); } } void ClassScope::applyTraitRules(AnalysisResultPtr ar) { ClassStatementPtr classStmt = dynamic_pointer_cast<ClassStatement>(getStmt()); assert(classStmt); StatementListPtr stmts = classStmt->getStmts(); if (!stmts) return; for (int s = 0; s < stmts->getCount(); s++) { StatementPtr stmt = (*stmts)[s]; UseTraitStatementPtr useStmt = dynamic_pointer_cast<UseTraitStatement>(stmt); if (!useStmt) continue; StatementListPtr rules = useStmt->getStmts(); for (int r = 0; r < rules->getCount(); r++) { StatementPtr rule = (*rules)[r]; TraitPrecStatementPtr precStmt = dynamic_pointer_cast<TraitPrecStatement>(rule); if (precStmt) { applyTraitPrecRule(precStmt); } else { TraitAliasStatementPtr aliasStmt = dynamic_pointer_cast<TraitAliasStatement>(rule); assert(aliasStmt); applyTraitAliasRule(ar, aliasStmt); } } } } // This method removes trait abstract methods that are either: // 1) implemented by other traits // 2) duplicate void ClassScope::removeSpareTraitAbstractMethods(AnalysisResultPtr ar) { for (MethodToTraitListMap::iterator iter = m_importMethToTraitMap.begin(); iter != m_importMethToTraitMap.end(); iter++) { TraitMethodList& tMethList = iter->second; bool hasNonAbstractMeth = false; unsigned countAbstractMeths = 0; for (TraitMethodList::const_iterator traitMethIter = tMethList.begin(); traitMethIter != tMethList.end(); traitMethIter++) { ModifierExpressionPtr modifiers = traitMethIter->m_modifiers ? traitMethIter->m_modifiers : traitMethIter->m_method->getModifiers(); if (!(modifiers->isAbstract())) { hasNonAbstractMeth = true; } else { countAbstractMeths++; } } if (hasNonAbstractMeth || countAbstractMeths > 1) { // Erase spare abstract declarations bool firstAbstractMeth = true; for (TraitMethodList::iterator nextTraitIter = tMethList.begin(); nextTraitIter != tMethList.end(); ) { TraitMethodList::iterator traitIter = nextTraitIter++; ModifierExpressionPtr modifiers = traitIter->m_modifiers ? traitIter->m_modifiers : traitIter->m_method->getModifiers(); if (modifiers->isAbstract()) { if (hasNonAbstractMeth || !firstAbstractMeth) { tMethList.erase(traitIter); } firstAbstractMeth = false; } } } } } const string& ClassScope::getNewGeneratorName( FunctionScopePtr genFuncScope, GeneratorRenameMap &genRenameMap) { assert(genFuncScope->isGenerator()); const string& oldName = genFuncScope->getName(); GeneratorRenameMap::iterator mapIt = genRenameMap.find(oldName); if (mapIt != genRenameMap.end()) { return mapIt->second; } string newName = ParserBase::newContinuationName( oldName + "_" + lexical_cast<string>(genFuncScope->getNewID()) ); genRenameMap[oldName] = newName; return genRenameMap[oldName]; } void ClassScope::renameCreateContinuationCalls(AnalysisResultPtr ar, ConstructPtr c, ImportedMethodMap &importedMethods) { if (!c) return; SimpleFunctionCallPtr funcCall = dynamic_pointer_cast<SimpleFunctionCall>(c); if (funcCall && funcCall->getName() == "hphp_create_continuation") { ExpressionListPtr params = funcCall->getParams(); assert(params->getCount() >= 2); const string &oldClassName = dynamic_pointer_cast<ScalarExpression>((*params)[0])->getString(); ClassScopePtr oldClassScope = ar->findClass(oldClassName); if (!oldClassScope || !oldClassScope->isTrait()) return; const string &oldGenName = dynamic_pointer_cast<ScalarExpression>((*params)[1])->getString(); MethodStatementPtr origGenStmt = importedMethods[Util::toLower(oldGenName)]; assert(origGenStmt); const string &newGenName = origGenStmt->getOriginalName(); ExpressionPtr newGenExpr = funcCall->makeScalarExpression(ar, newGenName); ExpressionPtr newClsExpr = funcCall->makeScalarExpression(ar, getName()); (*params)[0] = newClsExpr; (*params)[1] = newGenExpr; funcCall->analyzeProgram(ar); return; } for (int i=0; i < c->getKidCount(); i++) { renameCreateContinuationCalls(ar, c->getNthKid(i), importedMethods); } } void ClassScope::relinkGeneratorMethods( AnalysisResultPtr ar, ImportedMethodMap &importedMethods) { for (ImportedMethodMap::const_iterator methIt = importedMethods.begin(); methIt != importedMethods.end(); methIt++) { MethodStatementPtr newMeth = methIt->second; // Skip non-generator methods if (!newMeth) continue; if (newMeth->getOrigGeneratorFunc()) { // Get corresponding original generator method in the current class const string& origGenName = newMeth->getOrigGeneratorFunc()->getName(); MethodStatementPtr origGenStmt = importedMethods[origGenName]; assert(origGenStmt); // It must be an orig gen func already, we're just updating to point // to the corresponding method cloned from the trait assert(origGenStmt->getGeneratorFunc()); newMeth->setOrigGeneratorFunc(origGenStmt); origGenStmt->setGeneratorFunc(newMeth); } // OrigGenerator methods need to have their hphp_create_continuation calls // patched to the new generator name. if (newMeth->getGeneratorFunc()) { renameCreateContinuationCalls(ar, newMeth, importedMethods); } } } void ClassScope::importUsedTraits(AnalysisResultPtr ar) { if (m_traitStatus == FLATTENED) return; if (m_traitStatus == BEING_FLATTENED) { Compiler::Error(Compiler::CyclicDependentTraits, getStmt()); return; } if (m_usedTraitNames.size() == 0) { m_traitStatus = FLATTENED; return; } m_traitStatus = BEING_FLATTENED; // First, make sure that parent classes have their traits imported if (!m_parent.empty()) { ClassScopePtr parent = ar->findClass(m_parent); if (parent) { parent->importUsedTraits(ar); } } // Find trait methods to be imported for (unsigned i = 0; i < m_usedTraitNames.size(); i++) { ClassScopePtr tCls = ar->findClass(m_usedTraitNames[i]); if (!tCls || !(tCls->isTrait())) { setAttribute(UsesUnknownTrait); Compiler::Error(Compiler::UnknownTrait, getStmt()); continue; } // First, make sure the used trait is flattened tCls->importUsedTraits(ar); findTraitMethodsToImport(ar, tCls); } // Apply rules applyTraitRules(ar); // Remove trait abstract methods provided by other traits and duplicates removeSpareTraitAbstractMethods(ar); // Apply precedence of current class over used traits for (MethodToTraitListMap::iterator iter = m_importMethToTraitMap.begin(); iter != m_importMethToTraitMap.end(); ) { MethodToTraitListMap::iterator thisiter = iter; iter++; if (findFunction(ar, thisiter->first, 0, 0) != FunctionScopePtr()) { m_importMethToTraitMap.erase(thisiter); } } std::map<string, MethodStatementPtr> importedTraitMethods; std::vector<std::pair<string,const TraitMethod*> > importedTraitsWithOrigName; GeneratorRenameMap genRenameMap; // Actually import the methods for (MethodToTraitListMap::const_iterator iter = m_importMethToTraitMap.begin(); iter != m_importMethToTraitMap.end(); iter++) { // The rules may rule out a method from all traits. // In this case, simply don't import the method. if (iter->second.size() == 0) { continue; } // Consistency checking: each name must only refer to one imported method if (iter->second.size() > 1) { Compiler::Error(Compiler::MethodInMultipleTraits, getStmt()); } else { TraitMethodList::const_iterator traitMethIter = iter->second.begin(); if ((traitMethIter->m_modifiers ? traitMethIter->m_modifiers : traitMethIter->m_method->getModifiers())->isAbstract()) { // Skip abstract methods, if method already exists in the class if (findFunction(ar, iter->first, true) || importedTraitMethods.count(iter->first)) { continue; } } if (traitMethIter->m_modifiers && traitMethIter->m_modifiers->isStatic()) { Compiler::Error(Compiler::InvalidAccessModifier, traitMethIter->m_modifiers); continue; } string sourceName = traitMethIter->m_ruleStmt ? Util::toLower(((TraitAliasStatement*)traitMethIter->m_ruleStmt.get())-> getMethodName()) : iter->first; importedTraitMethods[sourceName] = MethodStatementPtr(); importedTraitsWithOrigName.push_back( make_pair(sourceName, &*traitMethIter)); } } for (unsigned i = 0; i < importedTraitsWithOrigName.size(); i++) { const string &sourceName = importedTraitsWithOrigName[i].first; const TraitMethod *traitMethod = importedTraitsWithOrigName[i].second; MethodStatementPtr newMeth = importTraitMethod( *traitMethod, ar, Util::toLower(traitMethod->m_originalName), genRenameMap, importedTraitMethods); if (newMeth) { importedTraitMethods[sourceName] = newMeth; } } // Relink generator and origGenerator methods relinkGeneratorMethods(ar, importedTraitMethods); // Import trait properties importTraitProperties(ar); m_traitStatus = FLATTENED; } bool ClassScope::usesTrait(const string &traitName) const { for (unsigned i = 0; i < m_usedTraitNames.size(); i++) { if (traitName == m_usedTraitNames[i]) { return true; } } return false; } bool ClassScope::needsInvokeParent(AnalysisResultConstPtr ar, bool considerSelf /* = true */) { // check all functions this class has if (considerSelf) { for (FunctionScopePtrVec::const_iterator iter = m_functionsVec.begin(); iter != m_functionsVec.end(); ++iter) { if ((*iter)->isPrivate()) return true; } } // walk up if (!m_parent.empty()) { ClassScopePtr super = ar->findClass(m_parent); return !super || super->isRedeclaring() || super->needsInvokeParent(ar); } return false; } bool ClassScope::derivesDirectlyFrom(const std::string &base) const { BOOST_FOREACH(std::string base_i, m_bases) { if (strcasecmp(base_i.c_str(), base.c_str()) == 0) return true; } return false; } bool ClassScope::derivesFrom(AnalysisResultConstPtr ar, const std::string &base, bool strict, bool def) const { if (derivesDirectlyFrom(base)) return true; BOOST_FOREACH(std::string base_i, m_bases) { ClassScopePtr cl = ar->findClass(base_i); if (cl) { if (strict && cl->isRedeclaring()) { if (def) return true; continue; } if (cl->derivesFrom(ar, base, strict, def)) return true; } } return false; } ClassScopePtr ClassScope::FindCommonParent(AnalysisResultConstPtr ar, const std::string &cn1, const std::string &cn2) { ClassScopePtr cls1 = ar->findClass(cn1); ClassScopePtr cls2 = ar->findClass(cn2); if (!cls1 || !cls2) return ClassScopePtr(); if (cls1->getName() == cls2->getName()) return cls1; if (cls1->derivesFrom(ar, cn2, true, false)) return cls2; if (cls2->derivesFrom(ar, cn1, true, false)) return cls1; // walk up the class hierarchy. BOOST_FOREACH(const std::string &base1, cls1->m_bases) { BOOST_FOREACH(const std::string &base2, cls2->m_bases) { ClassScopePtr parent = FindCommonParent(ar, base1, base2); if (parent) return parent; } } return ClassScopePtr(); } void ClassScope::setVolatile() { if (!m_volatile) { m_volatile = true; Lock lock(s_depsMutex); const BlockScopeRawPtrFlagsVec &orderedUsers = getOrderedUsers(); for (BlockScopeRawPtrFlagsVec::const_iterator it = orderedUsers.begin(), end = orderedUsers.end(); it != end; ++it) { BlockScopeRawPtrFlagsVec::value_type pf = *it; if (pf->second & UseKindParentRef) { BlockScopeRawPtr scope = pf->first; if (scope->is(BlockScope::ClassScope)) { ((HPHP::ClassScope*)scope.get())->setVolatile(); } } } } } FunctionScopePtr ClassScope::findFunction(AnalysisResultConstPtr ar, const std::string &name, bool recursive, bool exclIntfBase /* = false */) { assert(Util::toLower(name) == name); StringToFunctionScopePtrMap::const_iterator iter; iter = m_functions.find(name); if (iter != m_functions.end()) { assert(iter->second); return iter->second; } // walk up if (recursive) { int s = m_bases.size(); for (int i = 0; i < s; i++) { const string &base = m_bases[i]; ClassScopePtr super = ar->findClass(base); if (!super) continue; if (exclIntfBase && super->isInterface()) break; if (super->isRedeclaring()) { if (base == m_parent) { m_derivesFromRedeclaring = DirectFromRedeclared; break; } continue; } FunctionScopePtr func = super->findFunction(ar, name, true, exclIntfBase); if (func) return func; } } if (!Option::AllDynamic && derivesFromRedeclaring() == DirectFromRedeclared) { setDynamic(ar, name); } return FunctionScopePtr(); } FunctionScopePtr ClassScope::findConstructor(AnalysisResultConstPtr ar, bool recursive) { StringToFunctionScopePtrMap::const_iterator iter; string name; if (classNameCtor()) { name = getName(); } else { name = "__construct"; } iter = m_functions.find(name); if (iter != m_functions.end()) { assert(iter->second); return iter->second; } // walk up if (recursive && derivesFromRedeclaring() != DirectFromRedeclared) { ClassScopePtr super = ar->findClass(m_parent); if (super) { FunctionScopePtr func = super->findConstructor(ar, true); if (func) return func; } } if (!Option::AllDynamic && derivesFromRedeclaring() == DirectFromRedeclared) { setDynamic(ar, name); } return FunctionScopePtr(); } void ClassScope::setStaticDynamic(AnalysisResultConstPtr ar) { for (FunctionScopePtrVec::const_iterator iter = m_functionsVec.begin(); iter != m_functionsVec.end(); ++iter) { FunctionScopePtr fs = *iter; if (fs->isStatic()) fs->setDynamic(); } if (!m_parent.empty()) { if (derivesFromRedeclaring() == DirectFromRedeclared) { const ClassScopePtrVec &parents = ar->findRedeclaredClasses(m_parent); BOOST_FOREACH(ClassScopePtr cl, parents) { cl->setStaticDynamic(ar); } } else { ClassScopePtr parent = ar->findClass(m_parent); if (parent) { parent->setStaticDynamic(ar); } } } } void ClassScope::setDynamic(AnalysisResultConstPtr ar, const std::string &name) { StringToFunctionScopePtrMap::const_iterator iter = m_functions.find(name); if (iter != m_functions.end()) { FunctionScopePtr fs = iter->second; fs->setDynamic(); } else if (!m_parent.empty()) { if (derivesFromRedeclaring() == DirectFromRedeclared) { const ClassScopePtrVec &parents = ar->findRedeclaredClasses(m_parent); BOOST_FOREACH(ClassScopePtr cl, parents) { cl->setDynamic(ar, name); } } else { ClassScopePtr parent = ar->findClass(m_parent); if (parent) { parent->setDynamic(ar, name); } } } } void ClassScope::setSystem() { setAttribute(ClassScope::System); m_volatile = m_dynamic = false; for (FunctionScopePtrVec::const_iterator iter = m_functionsVec.begin(); iter != m_functionsVec.end(); ++iter) { (*iter)->setSystem(); } } bool ClassScope::needLazyStaticInitializer() { return getVariables()->getAttribute(VariableTable::ContainsDynamicStatic) || getConstants()->hasDynamic(); } bool ClassScope::hasConst(const string &name) const { const Symbol *sym = m_constants->getSymbol(name); assert(!sym || sym->isPresent()); return sym; } Symbol *ClassScope::findProperty(ClassScopePtr &cls, const string &name, AnalysisResultConstPtr ar) { return getVariables()->findProperty(cls, name, ar); } TypePtr ClassScope::checkProperty(BlockScopeRawPtr context, Symbol *sym, TypePtr type, bool coerce, AnalysisResultConstPtr ar) { return getVariables()->checkProperty(context, sym, type, coerce, ar); } TypePtr ClassScope::checkConst(BlockScopeRawPtr context, const std::string &name, TypePtr type, bool coerce, AnalysisResultConstPtr ar, ConstructPtr construct, const std::vector<std::string> &bases, BlockScope *&defScope) { defScope = nullptr; return getConstants()->check(context, name, type, coerce, ar, construct, m_bases, defScope); } void ClassScope::getAllParents(AnalysisResultConstPtr ar, std::vector<std::string> &names) { if (m_stmt) { if (isInterface()) { boost::dynamic_pointer_cast<InterfaceStatement> (m_stmt)->getAllParents(ar, names); } else { boost::dynamic_pointer_cast<ClassStatement> (m_stmt)->getAllParents(ar, names); } } else { for (unsigned i = 0; i < m_bases.size(); i++) { const string &base = m_bases[i]; names.push_back(base); if (ClassScopePtr cls = ar->findClass(base)) { if (!cls->isRedeclaring()) { cls->getAllParents(ar, names); } } } } } void ClassScope::getInterfaces(AnalysisResultConstPtr ar, std::vector<std::string> &names, bool recursive /* = true */) const { ClassScope *self = const_cast<ClassScope*>(this); if (recursive && !m_parent.empty()) { ClassScopePtr cls(ar->findClass(m_parent)); if (cls && cls->isRedeclaring()) { cls = self->findExactClass(cls); } if (cls) cls->getInterfaces(ar, names, true); } if (!m_bases.empty()) { vector<string>::const_iterator begin = m_parent.empty() ? m_bases.begin() : m_bases.begin() + 1; for (vector<string>::const_iterator it = begin; it != m_bases.end(); ++it) { ClassScopePtr cls(ar->findClass(*it)); if (cls && cls->isRedeclaring()) { cls = self->findExactClass(cls); } if (cls) names.push_back(cls->getDocName()); else names.push_back(*it); if (cls && recursive) { cls->getInterfaces(ar, names, true); } } } } ClassScopePtr ClassScope::getParentScope(AnalysisResultConstPtr ar) const { if (m_parent.empty()) return ClassScopePtr(); return ar->findClass(m_parent); } void ClassScope::serialize(JSON::CodeError::OutputStream &out) const { JSON::CodeError::MapStream ms(out); std::map<string, int> propMap; std::set<string> names; m_variables->getNames(names); BOOST_FOREACH(string name, names) { int pm = 0; if (m_variables->isPublic(name)) pm |= ClassScope::Public; else if (m_variables->isPrivate(name)) pm |= ClassScope::Private; else if (m_variables->isProtected(name)) pm |= ClassScope::Protected; if (m_variables->isStatic(name)) pm |= ClassScope::Static; propMap[name] = pm; } names.clear(); vector<string> cnames; m_constants->getSymbols(cnames); // What's a mod again? ms.add("attributes", m_attribute) .add("kind", m_kindOf) .add("parent", m_parent) .add("bases", m_bases) .add("properties", propMap) .add("functions", m_functions); ms.add("consts"); JSON::CodeError::MapStream cs(out); BOOST_FOREACH(string cname, cnames) { TypePtr type = m_constants->getType(cname); if (!type) { cs.add(cname, -1); } else if (type->isSpecificObject()) { cs.add(cname, type->getName()); } else { cs.add(cname, type->getKindOf()); } } cs.done(); ms.done(); } static inline string GetDocName(AnalysisResultPtr ar, BlockScopeRawPtr scope, const string &name) { ClassScopePtr c(ar->findClass(name)); if (c && c->isRedeclaring()) { ClassScopePtr exact(scope->findExactClass(c)); return exact ? exact->getDocName() : c->getOriginalName(); // if we can't tell which redec class, // then don't use the redec name } // TODO: pick a better way of signaling unknown? return c ? c->getDocName() : "UnknownClass"; } class GetDocNameFunctor { public: GetDocNameFunctor(AnalysisResultPtr ar, BlockScopeRawPtr scope) : m_ar(ar), m_scope(scope) {} inline string operator()(const string &name) const { return GetDocName(m_ar, m_scope, name); } private: AnalysisResultPtr m_ar; BlockScopeRawPtr m_scope; }; void ClassScope::serialize(JSON::DocTarget::OutputStream &out) const { // TODO(stephentu): fix this hack ClassScopeRawPtr self(const_cast<ClassScope*>(this)); JSON::DocTarget::MapStream ms(out); ms.add("name", getDocName()); ms.add("line", getStmt() ? getStmt()->getLocation()->line0 : 0); ms.add("docs", m_docComment); ms.add("parent"); if (m_parent.empty()) { out << JSON::Null(); } else { out << GetDocName(out.analysisResult(), self, m_parent); } vector<string> ifaces; getInterfaces(out.analysisResult(), ifaces, true); vector<string> origIfaces; origIfaces.resize(ifaces.size()); transform(ifaces.begin(), ifaces.end(), origIfaces.begin(), GetDocNameFunctor(out.analysisResult(), self)); ms.add("interfaces", origIfaces); int mods = 0; // TODO: you should really only get one of these, we should assert this if (m_kindOf == KindOfAbstractClass) mods |= ClassInfo::IsAbstract; if (m_kindOf == KindOfFinalClass) mods |= ClassInfo::IsFinal; if (m_kindOf == KindOfInterface) mods |= ClassInfo::IsInterface; if (m_kindOf == KindOfTrait) mods |= ClassInfo::IsTrait; ms.add("modifiers", mods); FunctionScopePtrVec funcs; getFunctionsFlattened(0, funcs); ms.add("methods", funcs); vector<Symbol*> rawSymbols; getVariables()->getSymbols(rawSymbols, true); vector<SymClassVarWrapper> wrappedSymbols; for (vector<Symbol*>::iterator it = rawSymbols.begin(); it != rawSymbols.end(); ++it) { wrappedSymbols.push_back(SymClassVarWrapper(*it)); } ms.add("properties", wrappedSymbols); // TODO: constants ms.done(); } bool ClassScope::hasProperty(const string &name) const { const Symbol *sym = m_variables->getSymbol(name); assert(!sym || sym->isPresent()); return sym; } void ClassScope::setRedeclaring(AnalysisResultConstPtr ar, int redecId) { if (isTrait()) { Compiler::Error(Compiler::RedeclaredTrait, m_stmt); } m_redeclaring = redecId; setVolatile(); // redeclared class is also volatile for (FunctionScopePtrVec::const_iterator iter = m_functionsVec.begin(); iter != m_functionsVec.end(); ++iter) { (*iter)->setDynamic(); } } ClassScopePtr ClassScope::getRootParent(AnalysisResultConstPtr ar, const std::string &methodName) { ClassScopePtr root = dynamic_pointer_cast<ClassScope>(shared_from_this()); for (ClassScopePtr cls = getParentScope(ar); cls; cls = cls->getParentScope(ar)) { if (methodName.empty() || cls->m_functions.find(methodName) != cls->m_functions.end()) { root = cls; } } return root; } void ClassScope::getRootParents(AnalysisResultConstPtr ar, const std::string &methodName, ClassScopePtrVec &roots, ClassScopePtr curClass) { ClassScopePtr root = dynamic_pointer_cast<ClassScope>(shared_from_this()); if (m_parent.empty()) { roots.push_back(curClass); } else { ClassScopePtrVec parents = ar->findRedeclaredClasses(m_parent); for (unsigned int i = 0; i < parents.size(); i++) { ClassScopePtr cls = parents[i]; if (methodName.empty() || cls->m_functions.find(methodName) != cls->m_functions.end()) { curClass = cls; } cls->getRootParents(ar, methodName, roots, curClass); } } } bool ClassScope::addFunction(AnalysisResultConstPtr ar, FunctionScopePtr funcScope) { FunctionScopePtr &func = m_functions[funcScope->getName()]; if (func) { func->getStmt()->parseTimeFatal(Compiler::DeclaredMethodTwice, "Redeclared method %s::%s", getOriginalName().c_str(), func->getOriginalName().c_str()); } func = funcScope; m_functionsVec.push_back(funcScope); return true; } bool ClassScope::canSkipCreateMethod(AnalysisResultConstPtr ar) const { // create() is not necessary if // 1) not inheriting from any class // 2) no constructor defined (__construct or class name) // 3) no init() defined if (derivesFromRedeclaring() || getAttribute(HasConstructor) || getAttribute(ClassNameConstructor) || needsInitMethod()) { return false; } if (!m_parent.empty()) { ClassScopePtr parent = getParentScope(ar); if (parent) return parent->canSkipCreateMethod(ar); } return true; }
// Written: fmckenna /* ***************************************************************************** Copyright (c) 2016-2017, The Regents of the University of California (Regents). All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY 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; OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of the FreeBSD Project. REGENTS SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE AND ACCOMPANYING DOCUMENTATION, IF ANY, PROVIDED HEREUNDER IS PROVIDED "AS IS". REGENTS HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. *************************************************************************** */ // Written: fmckenna #include "EarthquakeEventSelection.h" #include <QHBoxLayout> #include <QVBoxLayout> #include <QStackedWidget> #include <QComboBox> #include <QPushButton> #include <QJsonObject> #include <QJsonArray> #include <QLabel> #include <QLineEdit> #include <QDebug> #include <QFileDialog> #include <QPushButton> #include <sectiontitle.h> //#include <InputWidgetEDP.h> #include <InputWidgetExistingEvent.h> #include <ExistingSimCenterEvents.h> #include <UniformMotionInput.h> #include <ExistingPEER_Events.h> #include "SHAMotionWidget.h" #include <UserDefinedApplication.h> #include "StochasticMotionInputWidget.h" #include "RockOutcrop.h" EarthquakeEventSelection::EarthquakeEventSelection(RandomVariablesContainer *theRandomVariableIW, QWidget *parent) : SimCenterAppWidget(parent), theCurrentEvent(0), theRandomVariablesContainer(theRandomVariableIW) { QVBoxLayout *layout = new QVBoxLayout(); // // the selection part // QHBoxLayout *theSelectionLayout = new QHBoxLayout(); QLabel *label = new QLabel(); label->setText(QString("Loading Type")); eventSelection = new QComboBox(); eventSelection->setObjectName("LoadingTypeCombox"); // eventSelection->addItem(tr("Existing")); eventSelection->addItem(tr("Multiple Existing")); eventSelection->addItem(tr("Multiple PEER")); eventSelection->addItem(tr("Hazard Based Event")); eventSelection->addItem(tr("Site Response")); eventSelection->addItem(tr("Stochastic Ground Motion")); eventSelection->addItem(tr("User Application")); eventSelection->setItemData(1, "A Seismic event using Seismic Hazard Analysis and Record Selection/Scaling", Qt::ToolTipRole); theSelectionLayout->addWidget(label); theSelectionLayout->addWidget(eventSelection); theSelectionLayout->addStretch(); layout->addLayout(theSelectionLayout); // // create the stacked widget // theStackedWidget = new QStackedWidget(); // // create the individual load widgets & add to stacked widget // //theExistingEventsWidget = new InputWidgetExistingEvent(theRandomVariablesContainer); //theStackedWidget->addWidget(theExistingEventsWidget); theExistingEvents = new ExistingSimCenterEvents(theRandomVariablesContainer); theStackedWidget->addWidget(theExistingEvents); theExistingPeerEvents = new ExistingPEER_Events(theRandomVariablesContainer); theStackedWidget->addWidget(theExistingPeerEvents); //Adding SHA based ground motion widget theSHA_MotionWidget = new SHAMotionWidget(theRandomVariablesContainer); theStackedWidget->addWidget(theSHA_MotionWidget); // Adding SRT widget theRockOutcrop = new RockOutcrop(theRandomVariablesContainer); theStackedWidget->addWidget(theRockOutcrop); // Adding stochastic ground motion model widget theStochasticMotionWidget = new StochasticMotionInputWidget(theRandomVariablesContainer); theStackedWidget->addWidget(theStochasticMotionWidget); theUserDefinedApplication = new UserDefinedApplication(theRandomVariablesContainer); theStackedWidget->addWidget(theUserDefinedApplication); layout->addWidget(theStackedWidget); this->setLayout(layout); theCurrentEvent=theExistingEvents; connect(eventSelection, SIGNAL(currentIndexChanged(QString)), this, SLOT(eventSelectionChanged(QString))); } EarthquakeEventSelection::~EarthquakeEventSelection() { } bool EarthquakeEventSelection::outputToJSON(QJsonObject &jsonObject) { QJsonArray eventArray; QJsonObject singleEventData; theCurrentEvent->outputToJSON(singleEventData); eventArray.append(singleEventData); jsonObject["Events"]=eventArray; return true; } bool EarthquakeEventSelection::inputFromJSON(QJsonObject &jsonObject) { QString type; QJsonObject theEvent; if (jsonObject.contains("Events")) { QJsonArray theEvents = jsonObject["Events"].toArray(); QJsonValue theValue = theEvents.at(0); if (theValue.isNull()) { qDebug() << "EarthquakeEventSelection::no Event in Events"; return false; } theEvent = theValue.toObject(); } else { qDebug() << "EarthquakeEventSelection::no Events"; return false; } if (theCurrentEvent != 0) { return theCurrentEvent->inputFromJSON(theEvent); } return false; } void EarthquakeEventSelection::eventSelectionChanged(const QString &arg1) { // // switch stacked widgets depending on text // note type output in json and name in pull down are not the same and hence the || // if (arg1 == "Multiple Existing") { theStackedWidget->setCurrentIndex(0); theCurrentEvent = theExistingEvents; } else if(arg1 == "Multiple PEER") { theStackedWidget->setCurrentIndex(1); theCurrentEvent = theExistingPeerEvents; } else if(arg1 == "Hazard Based Event") { theStackedWidget->setCurrentIndex(2); theCurrentEvent = theSHA_MotionWidget; } else if (arg1 == "Site Response") { theStackedWidget->setCurrentIndex(3); theCurrentEvent = theRockOutcrop; } else if (arg1 == "Stochastic Ground Motion") { theStackedWidget->setCurrentIndex(4); theCurrentEvent = theStochasticMotionWidget; } else if(arg1 == "User Application") { theStackedWidget->setCurrentIndex(5); theCurrentEvent = theUserDefinedApplication; } else { qDebug() << "ERROR .. EarthquakeEventSelection selection .. type unknown: " << arg1; } } bool EarthquakeEventSelection::outputAppDataToJSON(QJsonObject &jsonObject) { QJsonArray eventArray; QJsonObject singleEventData; theCurrentEvent->outputAppDataToJSON(singleEventData); eventArray.append(singleEventData); jsonObject["Events"]=eventArray; return true; } bool EarthquakeEventSelection::inputAppDataFromJSON(QJsonObject &jsonObject) { QJsonObject theEvent; QString type; // from Events get the single event if (jsonObject.contains("Events")) { QJsonArray theEvents = jsonObject["Events"].toArray(); QJsonValue theValue = theEvents.at(0); if (theValue.isNull()) { return false; } theEvent = theValue.toObject(); if (theEvent.contains("Application")) { QJsonValue theName = theEvent["Application"]; type = theName.toString(); } else return false; } else return false; // based on application name value set event type int index = 0; if ((type == QString("Existing Events")) || (type == QString("ExistingSimCenterEvents"))) { index = 0; } else if ((type == QString("Existing PEER Events")) || (type == QString("ExistingPEER_Events"))) { index = 1; } else if (type == QString("Hazard Based Event")) { index = 2; } else if (type == QString("Site Response") || type == QString("SiteResponse")) { index = 3; } else if (type == QString("Stochastic Ground Motion Model") || type == QString("Stochastic Ground Motion") || type == QString("StochasticGroundMotion") || type == QString("StochasticMotion")) { index = 4; } else if ((type == QString("User Application")) || (type == QString("UserDefinedApplication"))) { index = 5; } else { return false; } eventSelection->setCurrentIndex(index); // invoke inputAppDataFromJSON on new type if (theCurrentEvent != 0 && !theEvent.isEmpty()) { return theCurrentEvent->inputAppDataFromJSON(theEvent); } } bool EarthquakeEventSelection::copyFiles(QString &destDir) { if (theCurrentEvent != 0) { return theCurrentEvent->copyFiles(destDir); } return false; }
// // Copyright (c) 2009-2010 Mikko Mononen memon@inside.org // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. // #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <string.h> #include "SDL.h" #include "SDL_opengl.h" #include "imgui.h" #include "InputGeom.h" #include "Sample.h" #include "Sample_SoloMeshSimple.h" #include "Recast.h" #include "RecastDebugDraw.h" #include "RecastDump.h" #include "DetourNavMesh.h" #include "DetourNavMeshBuilder.h" #include "DetourDebugDraw.h" #include "NavMeshTesterTool.h" #include "OffMeshConnectionTool.h" #include "ConvexVolumeTool.h" #include "CrowdTool.h" #ifdef WIN32 # define snprintf _snprintf #endif Sample_SoloMeshSimple::Sample_SoloMeshSimple() : m_keepInterResults(true), m_totalBuildTimeMs(0), m_triareas(0), m_solid(0), m_chf(0), m_cset(0), m_pmesh(0), m_dmesh(0), m_drawMode(DRAWMODE_NAVMESH) { setTool(new NavMeshTesterTool); } Sample_SoloMeshSimple::~Sample_SoloMeshSimple() { cleanup(); } void Sample_SoloMeshSimple::cleanup() { delete [] m_triareas; m_triareas = 0; rcFreeHeightField(m_solid); m_solid = 0; rcFreeCompactHeightfield(m_chf); m_chf = 0; rcFreeContourSet(m_cset); m_cset = 0; rcFreePolyMesh(m_pmesh); m_pmesh = 0; rcFreePolyMeshDetail(m_dmesh); m_dmesh = 0; dtFreeNavMesh(m_navMesh); m_navMesh = 0; } void Sample_SoloMeshSimple::handleSettings() { Sample::handleCommonSettings(); if (imguiCheck("Keep Itermediate Results", m_keepInterResults)) m_keepInterResults = !m_keepInterResults; imguiSeparator(); char msg[64]; snprintf(msg, 64, "Build Time: %.1fms", m_totalBuildTimeMs); imguiLabel(msg); imguiSeparator(); } void Sample_SoloMeshSimple::handleTools() { int type = !m_tool ? TOOL_NONE : m_tool->type(); if (imguiCheck("Test Navmesh", type == TOOL_NAVMESH_TESTER)) { setTool(new NavMeshTesterTool); } if (imguiCheck("Create Off-Mesh Connections", type == TOOL_OFFMESH_CONNECTION)) { setTool(new OffMeshConnectionTool); } if (imguiCheck("Create Convex Volumes", type == TOOL_CONVEX_VOLUME)) { setTool(new ConvexVolumeTool); } if (imguiCheck("Create Crowds", type == TOOL_CROWD)) { setTool(new CrowdTool); } imguiSeparatorLine(); imguiIndent(); if (m_tool) m_tool->handleMenu(); imguiUnindent(); } void Sample_SoloMeshSimple::handleDebugMode() { // Check which modes are valid. bool valid[MAX_DRAWMODE]; for (int i = 0; i < MAX_DRAWMODE; ++i) valid[i] = false; if (m_geom) { valid[DRAWMODE_NAVMESH] = m_navMesh != 0; valid[DRAWMODE_NAVMESH_TRANS] = m_navMesh != 0; valid[DRAWMODE_NAVMESH_BVTREE] = m_navMesh != 0; valid[DRAWMODE_NAVMESH_NODES] = m_navQuery != 0; valid[DRAWMODE_NAVMESH_INVIS] = m_navMesh != 0; valid[DRAWMODE_MESH] = true; valid[DRAWMODE_VOXELS] = m_solid != 0; valid[DRAWMODE_VOXELS_WALKABLE] = m_solid != 0; valid[DRAWMODE_COMPACT] = m_chf != 0; valid[DRAWMODE_COMPACT_DISTANCE] = m_chf != 0; valid[DRAWMODE_COMPACT_REGIONS] = m_chf != 0; valid[DRAWMODE_REGION_CONNECTIONS] = m_cset != 0; valid[DRAWMODE_RAW_CONTOURS] = m_cset != 0; valid[DRAWMODE_BOTH_CONTOURS] = m_cset != 0; valid[DRAWMODE_CONTOURS] = m_cset != 0; valid[DRAWMODE_POLYMESH] = m_pmesh != 0; valid[DRAWMODE_POLYMESH_DETAIL] = m_dmesh != 0; } int unavail = 0; for (int i = 0; i < MAX_DRAWMODE; ++i) if (!valid[i]) unavail++; if (unavail == MAX_DRAWMODE) return; imguiLabel("Draw"); if (imguiCheck("Input Mesh", m_drawMode == DRAWMODE_MESH, valid[DRAWMODE_MESH])) m_drawMode = DRAWMODE_MESH; if (imguiCheck("Navmesh", m_drawMode == DRAWMODE_NAVMESH, valid[DRAWMODE_NAVMESH])) m_drawMode = DRAWMODE_NAVMESH; if (imguiCheck("Navmesh Invis", m_drawMode == DRAWMODE_NAVMESH_INVIS, valid[DRAWMODE_NAVMESH_INVIS])) m_drawMode = DRAWMODE_NAVMESH_INVIS; if (imguiCheck("Navmesh Trans", m_drawMode == DRAWMODE_NAVMESH_TRANS, valid[DRAWMODE_NAVMESH_TRANS])) m_drawMode = DRAWMODE_NAVMESH_TRANS; if (imguiCheck("Navmesh BVTree", m_drawMode == DRAWMODE_NAVMESH_BVTREE, valid[DRAWMODE_NAVMESH_BVTREE])) m_drawMode = DRAWMODE_NAVMESH_BVTREE; if (imguiCheck("Navmesh Nodes", m_drawMode == DRAWMODE_NAVMESH_NODES, valid[DRAWMODE_NAVMESH_NODES])) m_drawMode = DRAWMODE_NAVMESH_NODES; if (imguiCheck("Voxels", m_drawMode == DRAWMODE_VOXELS, valid[DRAWMODE_VOXELS])) m_drawMode = DRAWMODE_VOXELS; if (imguiCheck("Walkable Voxels", m_drawMode == DRAWMODE_VOXELS_WALKABLE, valid[DRAWMODE_VOXELS_WALKABLE])) m_drawMode = DRAWMODE_VOXELS_WALKABLE; if (imguiCheck("Compact", m_drawMode == DRAWMODE_COMPACT, valid[DRAWMODE_COMPACT])) m_drawMode = DRAWMODE_COMPACT; if (imguiCheck("Compact Distance", m_drawMode == DRAWMODE_COMPACT_DISTANCE, valid[DRAWMODE_COMPACT_DISTANCE])) m_drawMode = DRAWMODE_COMPACT_DISTANCE; if (imguiCheck("Compact Regions", m_drawMode == DRAWMODE_COMPACT_REGIONS, valid[DRAWMODE_COMPACT_REGIONS])) m_drawMode = DRAWMODE_COMPACT_REGIONS; if (imguiCheck("Region Connections", m_drawMode == DRAWMODE_REGION_CONNECTIONS, valid[DRAWMODE_REGION_CONNECTIONS])) m_drawMode = DRAWMODE_REGION_CONNECTIONS; if (imguiCheck("Raw Contours", m_drawMode == DRAWMODE_RAW_CONTOURS, valid[DRAWMODE_RAW_CONTOURS])) m_drawMode = DRAWMODE_RAW_CONTOURS; if (imguiCheck("Both Contours", m_drawMode == DRAWMODE_BOTH_CONTOURS, valid[DRAWMODE_BOTH_CONTOURS])) m_drawMode = DRAWMODE_BOTH_CONTOURS; if (imguiCheck("Contours", m_drawMode == DRAWMODE_CONTOURS, valid[DRAWMODE_CONTOURS])) m_drawMode = DRAWMODE_CONTOURS; if (imguiCheck("Poly Mesh", m_drawMode == DRAWMODE_POLYMESH, valid[DRAWMODE_POLYMESH])) m_drawMode = DRAWMODE_POLYMESH; if (imguiCheck("Poly Mesh Detail", m_drawMode == DRAWMODE_POLYMESH_DETAIL, valid[DRAWMODE_POLYMESH_DETAIL])) m_drawMode = DRAWMODE_POLYMESH_DETAIL; if (unavail) { imguiValue("Tick 'Keep Itermediate Results'"); imguiValue("to see more debug mode options."); } } void Sample_SoloMeshSimple::handleRender() { if (!m_geom || !m_geom->getMesh()) return; DebugDrawGL dd; glEnable(GL_FOG); glDepthMask(GL_TRUE); if (m_drawMode == DRAWMODE_MESH) { // Draw mesh duDebugDrawTriMeshSlope(&dd, m_geom->getMesh()->getVerts(), m_geom->getMesh()->getVertCount(), m_geom->getMesh()->getTris(), m_geom->getMesh()->getNormals(), m_geom->getMesh()->getTriCount(), m_agentMaxSlope); m_geom->drawOffMeshConnections(&dd); } else if (m_drawMode != DRAWMODE_NAVMESH_TRANS) { // Draw mesh duDebugDrawTriMesh(&dd, m_geom->getMesh()->getVerts(), m_geom->getMesh()->getVertCount(), m_geom->getMesh()->getTris(), m_geom->getMesh()->getNormals(), m_geom->getMesh()->getTriCount(), 0); m_geom->drawOffMeshConnections(&dd); } glDisable(GL_FOG); glDepthMask(GL_FALSE); // Draw bounds const float* bmin = m_geom->getMeshBoundsMin(); const float* bmax = m_geom->getMeshBoundsMax(); duDebugDrawBoxWire(&dd, bmin[0],bmin[1],bmin[2], bmax[0],bmax[1],bmax[2], duRGBA(255,255,255,128), 1.0f); if (m_navMesh && m_navQuery && (m_drawMode == DRAWMODE_NAVMESH || m_drawMode == DRAWMODE_NAVMESH_TRANS || m_drawMode == DRAWMODE_NAVMESH_BVTREE || m_drawMode == DRAWMODE_NAVMESH_NODES || m_drawMode == DRAWMODE_NAVMESH_INVIS)) { if (m_drawMode != DRAWMODE_NAVMESH_INVIS) duDebugDrawNavMeshWithClosedList(&dd, *m_navMesh, *m_navQuery, m_navMeshDrawFlags); if (m_drawMode == DRAWMODE_NAVMESH_BVTREE) duDebugDrawNavMeshBVTree(&dd, *m_navMesh); if (m_drawMode == DRAWMODE_NAVMESH_NODES) duDebugDrawNavMeshNodes(&dd, *m_navQuery); } glDepthMask(GL_TRUE); if (m_chf && m_drawMode == DRAWMODE_COMPACT) duDebugDrawCompactHeightfieldSolid(&dd, *m_chf); if (m_chf && m_drawMode == DRAWMODE_COMPACT_DISTANCE) duDebugDrawCompactHeightfieldDistance(&dd, *m_chf); if (m_chf && m_drawMode == DRAWMODE_COMPACT_REGIONS) duDebugDrawCompactHeightfieldRegions(&dd, *m_chf); if (m_solid && m_drawMode == DRAWMODE_VOXELS) { glEnable(GL_FOG); duDebugDrawHeightfieldSolid(&dd, *m_solid); glDisable(GL_FOG); } if (m_solid && m_drawMode == DRAWMODE_VOXELS_WALKABLE) { glEnable(GL_FOG); duDebugDrawHeightfieldWalkable(&dd, *m_solid); glDisable(GL_FOG); } if (m_cset && m_drawMode == DRAWMODE_RAW_CONTOURS) { glDepthMask(GL_FALSE); duDebugDrawRawContours(&dd, *m_cset); glDepthMask(GL_TRUE); } if (m_cset && m_drawMode == DRAWMODE_BOTH_CONTOURS) { glDepthMask(GL_FALSE); duDebugDrawRawContours(&dd, *m_cset, 0.5f); duDebugDrawContours(&dd, *m_cset); glDepthMask(GL_TRUE); } if (m_cset && m_drawMode == DRAWMODE_CONTOURS) { glDepthMask(GL_FALSE); duDebugDrawContours(&dd, *m_cset); glDepthMask(GL_TRUE); } if (m_chf && m_cset && m_drawMode == DRAWMODE_REGION_CONNECTIONS) { duDebugDrawCompactHeightfieldRegions(&dd, *m_chf); glDepthMask(GL_FALSE); duDebugDrawRegionConnections(&dd, *m_cset); glDepthMask(GL_TRUE); } if (m_pmesh && m_drawMode == DRAWMODE_POLYMESH) { glDepthMask(GL_FALSE); duDebugDrawPolyMesh(&dd, *m_pmesh); glDepthMask(GL_TRUE); } if (m_dmesh && m_drawMode == DRAWMODE_POLYMESH_DETAIL) { glDepthMask(GL_FALSE); duDebugDrawPolyMeshDetail(&dd, *m_dmesh); glDepthMask(GL_TRUE); } m_geom->drawConvexVolumes(&dd); if (m_tool) m_tool->handleRender(); glDepthMask(GL_TRUE); } void Sample_SoloMeshSimple::handleRenderOverlay(double* proj, double* model, int* view) { if (m_tool) m_tool->handleRenderOverlay(proj, model, view); } void Sample_SoloMeshSimple::handleMeshChanged(class InputGeom* geom) { Sample::handleMeshChanged(geom); dtFreeNavMesh(m_navMesh); m_navMesh = 0; if (m_tool) { m_tool->reset(); m_tool->init(this); } } bool Sample_SoloMeshSimple::handleBuild() { if (!m_geom || !m_geom->getMesh()) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Input mesh is not specified."); return false; } cleanup(); const float* bmin = m_geom->getMeshBoundsMin(); const float* bmax = m_geom->getMeshBoundsMax(); const float* verts = m_geom->getMesh()->getVerts(); const int nverts = m_geom->getMesh()->getVertCount(); const int* tris = m_geom->getMesh()->getTris(); const int ntris = m_geom->getMesh()->getTriCount(); // // Step 1. Initialize build config. // // Init build configuration from GUI memset(&m_cfg, 0, sizeof(m_cfg)); m_cfg.cs = m_cellSize; m_cfg.ch = m_cellHeight; m_cfg.walkableSlopeAngle = m_agentMaxSlope; m_cfg.walkableHeight = (int)ceilf(m_agentHeight / m_cfg.ch); m_cfg.walkableClimb = (int)floorf(m_agentMaxClimb / m_cfg.ch); m_cfg.walkableRadius = (int)ceilf(m_agentRadius / m_cfg.cs); m_cfg.maxEdgeLen = (int)(m_edgeMaxLen / m_cellSize); m_cfg.maxSimplificationError = m_edgeMaxError; m_cfg.minRegionArea = (int)rcSqr(m_regionMinSize); // Note: area = size*size m_cfg.mergeRegionArea = (int)rcSqr(m_regionMergeSize); // Note: area = size*size m_cfg.maxVertsPerPoly = (int)m_vertsPerPoly; m_cfg.detailSampleDist = m_detailSampleDist < 0.9f ? 0 : m_cellSize * m_detailSampleDist; m_cfg.detailSampleMaxError = m_cellHeight * m_detailSampleMaxError; // Set the area where the navigation will be build. // Here the bounds of the input mesh are used, but the // area could be specified by an user defined box, etc. rcVcopy(m_cfg.bmin, bmin); rcVcopy(m_cfg.bmax, bmax); rcCalcGridSize(m_cfg.bmin, m_cfg.bmax, m_cfg.cs, &m_cfg.width, &m_cfg.height); // Reset build times gathering. m_ctx->resetTimers(); // Start the build process. m_ctx->startTimer(RC_TIMER_TOTAL); m_ctx->log(RC_LOG_PROGRESS, "Building navigation:"); m_ctx->log(RC_LOG_PROGRESS, " - %d x %d cells", m_cfg.width, m_cfg.height); m_ctx->log(RC_LOG_PROGRESS, " - %.1fK verts, %.1fK tris", nverts/1000.0f, ntris/1000.0f); // // Step 2. Rasterize input polygon soup. // // Allocate voxel heightfield where we rasterize our input data to. m_solid = rcAllocHeightfield(); if (!m_solid) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'solid'."); return false; } if (!rcCreateHeightfield(m_ctx, *m_solid, m_cfg.width, m_cfg.height, m_cfg.bmin, m_cfg.bmax, m_cfg.cs, m_cfg.ch)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create solid heightfield."); return false; } // Allocate array that can hold triangle area types. // If you have multiple meshes you need to process, allocate // and array which can hold the max number of triangles you need to process. m_triareas = new unsigned char[ntris]; if (!m_triareas) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'm_triareas' (%d).", ntris); return false; } // Find triangles which are walkable based on their slope and rasterize them. // If your input data is multiple meshes, you can transform them here, calculate // the are type for each of the meshes and rasterize them. memset(m_triareas, 0, ntris*sizeof(unsigned char)); rcMarkWalkableTriangles(m_ctx, m_cfg.walkableSlopeAngle, verts, nverts, tris, ntris, m_triareas); rcRasterizeTriangles(m_ctx, verts, nverts, tris, m_triareas, ntris, *m_solid, m_cfg.walkableClimb); if (!m_keepInterResults) { delete [] m_triareas; m_triareas = 0; } // // Step 3. Filter walkables surfaces. // // Once all geoemtry is rasterized, we do initial pass of filtering to // remove unwanted overhangs caused by the conservative rasterization // as well as filter spans where the character cannot possibly stand. rcFilterLowHangingWalkableObstacles(m_ctx, m_cfg.walkableClimb, *m_solid); rcFilterLedgeSpans(m_ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid); rcFilterWalkableLowHeightSpans(m_ctx, m_cfg.walkableHeight, *m_solid); // // Step 4. Partition walkable surface to simple regions. // // Compact the heightfield so that it is faster to handle from now on. // This will result more cache coherent data as well as the neighbours // between walkable cells will be calculated. m_chf = rcAllocCompactHeightfield(); if (!m_chf) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'chf'."); return false; } if (!rcBuildCompactHeightfield(m_ctx, m_cfg.walkableHeight, m_cfg.walkableClimb, *m_solid, *m_chf)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build compact data."); return false; } if (!m_keepInterResults) { rcFreeHeightField(m_solid); m_solid = 0; } // Erode the walkable area by agent radius. if (!rcErodeWalkableArea(m_ctx, m_cfg.walkableRadius, *m_chf)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not erode."); return false; } // (Optional) Mark areas. const ConvexVolume* vols = m_geom->getConvexVolumes(); for (int i = 0; i < m_geom->getConvexVolumeCount(); ++i) rcMarkConvexPolyArea(m_ctx, vols[i].verts, vols[i].nverts, vols[i].hmin, vols[i].hmax, (unsigned char)vols[i].area, *m_chf); // Prepare for region partitioning, by calculating distance field along the walkable surface. if (!rcBuildDistanceField(m_ctx, *m_chf)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build distance field."); return false; } // Partition the walkable surface into simple regions without holes. if (!rcBuildRegions(m_ctx, *m_chf, m_cfg.borderSize, m_cfg.minRegionArea, m_cfg.mergeRegionArea)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build regions."); return false; } // // Step 5. Trace and simplify region contours. // // Create contours. m_cset = rcAllocContourSet(); if (!m_cset) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'cset'."); return false; } if (!rcBuildContours(m_ctx, *m_chf, m_cfg.maxSimplificationError, m_cfg.maxEdgeLen, *m_cset)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not create contours."); return false; } // // Step 6. Build polygons mesh from contours. // // Build polygon navmesh from the contours. m_pmesh = rcAllocPolyMesh(); if (!m_pmesh) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'pmesh'."); return false; } if (!rcBuildPolyMesh(m_ctx, *m_cset, m_cfg.maxVertsPerPoly, *m_pmesh)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not triangulate contours."); return false; } // // Step 7. Create detail mesh which allows to access approximate height on each polygon. // m_dmesh = rcAllocPolyMeshDetail(); if (!m_dmesh) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Out of memory 'pmdtl'."); return false; } if (!rcBuildPolyMeshDetail(m_ctx, *m_pmesh, *m_chf, m_cfg.detailSampleDist, m_cfg.detailSampleMaxError, *m_dmesh)) { m_ctx->log(RC_LOG_ERROR, "buildNavigation: Could not build detail mesh."); return false; } if (!m_keepInterResults) { rcFreeCompactHeightfield(m_chf); m_chf = 0; rcFreeContourSet(m_cset); m_cset = 0; } // At this point the navigation mesh data is ready, you can access it from m_pmesh. // See duDebugDrawPolyMesh or dtCreateNavMeshData as examples how to access the data. // // (Optional) Step 8. Create Detour data from Recast poly mesh. // // The GUI may allow more max points per polygon than Detour can handle. // Only build the detour navmesh if we do not exceed the limit. if (m_cfg.maxVertsPerPoly <= DT_VERTS_PER_POLYGON) { unsigned char* navData = 0; int navDataSize = 0; // Update poly flags from areas. for (int i = 0; i < m_pmesh->npolys; ++i) { if (m_pmesh->areas[i] == RC_WALKABLE_AREA) m_pmesh->areas[i] = SAMPLE_POLYAREA_GROUND; if (m_pmesh->areas[i] == SAMPLE_POLYAREA_GROUND || m_pmesh->areas[i] == SAMPLE_POLYAREA_GRASS || m_pmesh->areas[i] == SAMPLE_POLYAREA_ROAD) { m_pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK; } else if (m_pmesh->areas[i] == SAMPLE_POLYAREA_WATER) { m_pmesh->flags[i] = SAMPLE_POLYFLAGS_SWIM; } else if (m_pmesh->areas[i] == SAMPLE_POLYAREA_DOOR) { m_pmesh->flags[i] = SAMPLE_POLYFLAGS_WALK | SAMPLE_POLYFLAGS_DOOR; } } dtNavMeshCreateParams params; memset(&params, 0, sizeof(params)); params.verts = m_pmesh->verts; params.vertCount = m_pmesh->nverts; params.polys = m_pmesh->polys; params.polyAreas = m_pmesh->areas; params.polyFlags = m_pmesh->flags; params.polyCount = m_pmesh->npolys; params.nvp = m_pmesh->nvp; params.detailMeshes = m_dmesh->meshes; params.detailVerts = m_dmesh->verts; params.detailVertsCount = m_dmesh->nverts; params.detailTris = m_dmesh->tris; params.detailTriCount = m_dmesh->ntris; params.offMeshConVerts = m_geom->getOffMeshConnectionVerts(); params.offMeshConRad = m_geom->getOffMeshConnectionRads(); params.offMeshConDir = m_geom->getOffMeshConnectionDirs(); params.offMeshConAreas = m_geom->getOffMeshConnectionAreas(); params.offMeshConFlags = m_geom->getOffMeshConnectionFlags(); params.offMeshConUserID = m_geom->getOffMeshConnectionId(); params.offMeshConCount = m_geom->getOffMeshConnectionCount(); params.walkableHeight = m_agentHeight; params.walkableRadius = m_agentRadius; params.walkableClimb = m_agentMaxClimb; rcVcopy(params.bmin, m_pmesh->bmin); rcVcopy(params.bmax, m_pmesh->bmax); params.cs = m_cfg.cs; params.ch = m_cfg.ch; if (!dtCreateNavMeshData(&params, &navData, &navDataSize)) { m_ctx->log(RC_LOG_ERROR, "Could not build Detour navmesh."); return false; } m_navMesh = dtAllocNavMesh(); if (!m_navMesh) { dtFree(navData); m_ctx->log(RC_LOG_ERROR, "Could not create Detour navmesh"); return false; } if (m_navMesh->init(navData, navDataSize, DT_TILE_FREE_DATA) != DT_SUCCESS) { dtFree(navData); m_ctx->log(RC_LOG_ERROR, "Could not init Detour navmesh"); return false; } if (m_navQuery->init(m_navMesh, 2048) != DT_SUCCESS) { m_ctx->log(RC_LOG_ERROR, "Could not init Detour navmesh query"); return false; } } m_ctx->stopTimer(RC_TIMER_TOTAL); // Show performance stats. duLogBuildTimes(*m_ctx, m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)); m_ctx->log(RC_LOG_PROGRESS, ">> Polymesh: %d vertices %d polygons", m_pmesh->nverts, m_pmesh->npolys); m_totalBuildTimeMs = m_ctx->getAccumulatedTime(RC_TIMER_TOTAL)/1000.0f; if (m_tool) m_tool->init(this); return true; }
/** * 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. */ // // Created by Darin on 20/07/2018. // #include "update_global_config_task.h" UpdateGlobalConfigTask::UpdateGlobalConfigTask(const std::string &script) : WeexTask("") { this->script = script; } void UpdateGlobalConfigTask::run(WeexRuntime *runtime) { runtime->updateGlobalConfig(script); }
/************************************************************************* * * REALM CONFIDENTIAL * __________________ * * [2011] - [2014] Realm Inc * All Rights Reserved. * * NOTICE: All information contained herein is, and remains * the property of Realm Incorporated and its suppliers, * if any. The intellectual and technical concepts contained * herein are proprietary to Realm Incorporated * and its suppliers and may be covered by U.S. and Foreign Patents, * patents in process, and are protected by trade secret or copyright law. * Dissemination of this information or reproduction of this material * is strictly forbidden unless prior written permission is obtained * from Realm Incorporated. * **************************************************************************/ #ifndef REALM_COMMIT_LOG_HPP #define REALM_COMMIT_LOG_HPP #ifdef REALM_ENABLE_REPLICATION #include <exception> #include <realm/replication.hpp> #include <realm/binary_data.hpp> #include <realm/lang_bind_helper.hpp> namespace realm { class CommitLog; class LogFileError: public std::runtime_error { public: LogFileError(std::string file_name): std::runtime_error(file_name) { } }; // Create a writelog collector and associate it with a filepath. You'll need one writelog // collector for each shared group. Commits from writelog collectors for a specific filepath // may later be obtained through other writelog collectors associated with said filepath. // The caller assumes ownership of the writelog collector and must destroy it, but only AFTER // destruction of the shared group using it. std::unique_ptr<Replication> makeWriteLogCollector(std::string filepath, bool server_synchronization_mode = false, const char* encryption_key = 0); } // namespace realm #endif // REALM_ENABLE_REPLICATION #endif // REALM_COMMIT_LOG_HPP
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/c/builtin_op_data.h" #include "tensorflow/lite/c/c_api_internal.h" #include "tensorflow/lite/experimental/micro/kernels/all_ops_resolver.h" #include "tensorflow/lite/experimental/micro/kernels/test_utils.h" #include "tensorflow/lite/experimental/micro/simple_tensor_allocator.h" #include "tensorflow/lite/experimental/micro/testing/micro_test.h" namespace tflite { namespace testing { namespace { void TestDepthwiseConvFloat(std::initializer_list<int> input_dims_data, std::initializer_list<float> input_data, std::initializer_list<int> filter_dims_data, std::initializer_list<float> filter_data, std::initializer_list<int> bias_dims_data, std::initializer_list<float> bias_data, std::initializer_list<float> expected_output_data, std::initializer_list<int> output_dims_data, TfLiteFusedActivation activation, float* output_data) { TfLiteIntArray* input_dims = IntArrayFromInitializer(input_dims_data); TfLiteIntArray* filter_dims = IntArrayFromInitializer(filter_dims_data); TfLiteIntArray* bias_dims = IntArrayFromInitializer(bias_dims_data); TfLiteIntArray* output_dims = IntArrayFromInitializer(output_dims_data); const int output_dims_count = ElementCount(*output_dims); constexpr int inputs_size = 3; constexpr int outputs_size = 1; constexpr int tensors_size = inputs_size + outputs_size; TfLiteTensor tensors[tensors_size] = { CreateFloatTensor(input_data, input_dims, "input_tensor"), CreateFloatTensor(filter_data, filter_dims, "filter_tensor"), CreateFloatTensor(bias_data, bias_dims, "bias_tensor"), CreateFloatTensor(output_data, output_dims, "output_tensor"), }; TfLiteContext context; PopulateContext(tensors, tensors_size, &context); ::tflite::ops::micro::AllOpsResolver resolver; const TfLiteRegistration* registration = resolver.FindOp(tflite::BuiltinOperator_DEPTHWISE_CONV_2D, 1); TF_LITE_MICRO_EXPECT_NE(nullptr, registration); int input_depth = input_dims->data[3]; int output_depth = filter_dims->data[3]; int depth_mul = output_depth / input_depth; TfLiteDepthwiseConvParams builtin_data = { kTfLitePaddingValid, 1, 1, depth_mul, activation, }; const char* init_data = reinterpret_cast<const char*>(&builtin_data); size_t init_data_size = 0; void* user_data = nullptr; if (registration->init) { user_data = registration->init(&context, init_data, init_data_size); } int inputs_array_data[] = {3, 0, 1, 2}; TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data); int outputs_array_data[] = {1, 3}; TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data); int temporaries_array_data[] = {0}; TfLiteIntArray* temporaries_array = IntArrayFromInts(temporaries_array_data); TfLiteNode node; node.inputs = inputs_array; node.outputs = outputs_array; node.temporaries = temporaries_array; node.user_data = user_data; node.builtin_data = reinterpret_cast<void*>(&builtin_data); node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; node.delegate = nullptr; if (registration->prepare) { TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->prepare(&context, &node)); } TF_LITE_MICRO_EXPECT_NE(nullptr, registration->invoke); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(&context, &node)); if (registration->free) { registration->free(&context, user_data); } for (int i = 0; i < output_dims_count; ++i) { TF_LITE_MICRO_EXPECT_NEAR(expected_output_data.begin()[i], output_data[i], 1e-5f); } } void TestDepthwiseConvQuantized( std::initializer_list<int> input_dims_data, std::initializer_list<uint8_t> input_data, float input_min, float input_max, std::initializer_list<int> filter_dims_data, std::initializer_list<uint8_t> filter_data, float filter_min, float filter_max, std::initializer_list<int> bias_dims_data, std::initializer_list<int32_t> bias_data, float bias_min, float bias_max, std::initializer_list<uint8_t> expected_output_data, std::initializer_list<int> output_dims_data, float output_min, float output_max, TfLiteFusedActivation activation, uint8_t* output_data) { TfLiteIntArray* input_dims = IntArrayFromInitializer(input_dims_data); TfLiteIntArray* filter_dims = IntArrayFromInitializer(filter_dims_data); TfLiteIntArray* bias_dims = IntArrayFromInitializer(bias_dims_data); TfLiteIntArray* output_dims = IntArrayFromInitializer(output_dims_data); const int output_dims_count = ElementCount(*output_dims); constexpr int inputs_size = 3; constexpr int outputs_size = 1; constexpr int tensors_size = inputs_size + outputs_size; TfLiteTensor tensors[tensors_size] = { CreateQuantizedTensor(input_data, input_dims, "input_tensor", input_min, input_max), CreateQuantizedTensor(filter_data, filter_dims, "filter_tensor", filter_min, filter_max), CreateQuantized32Tensor(bias_data, bias_dims, "bias_tensor", bias_min, bias_max), CreateQuantizedTensor(output_data, output_dims, "output_tensor", output_min, output_max), }; TfLiteContext context; PopulateContext(tensors, tensors_size, &context); ::tflite::ops::micro::AllOpsResolver resolver; const TfLiteRegistration* registration = resolver.FindOp(tflite::BuiltinOperator_DEPTHWISE_CONV_2D, 1); TF_LITE_MICRO_EXPECT_NE(nullptr, registration); int input_depth = input_dims->data[3]; int output_depth = filter_dims->data[3]; int depth_mul = output_depth / input_depth; TfLiteDepthwiseConvParams builtin_data = { kTfLitePaddingValid, 1, 1, depth_mul, activation, }; const char* init_data = reinterpret_cast<const char*>(&builtin_data); size_t init_data_size = 0; void* user_data = nullptr; if (registration->init) { user_data = registration->init(&context, init_data, init_data_size); } int inputs_array_data[] = {3, 0, 1, 2}; TfLiteIntArray* inputs_array = IntArrayFromInts(inputs_array_data); int outputs_array_data[] = {1, 3}; TfLiteIntArray* outputs_array = IntArrayFromInts(outputs_array_data); int temporaries_array_data[] = {0}; TfLiteIntArray* temporaries_array = IntArrayFromInts(temporaries_array_data); TfLiteNode node; node.inputs = inputs_array; node.outputs = outputs_array; node.temporaries = temporaries_array; node.user_data = user_data; node.builtin_data = reinterpret_cast<void*>(&builtin_data); node.custom_initial_data = nullptr; node.custom_initial_data_size = 0; node.delegate = nullptr; if (registration->prepare) { TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->prepare(&context, &node)); } TF_LITE_MICRO_EXPECT_NE(nullptr, registration->invoke); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(&context, &node)); if (registration->free) { registration->free(&context, user_data); } for (int i = 0; i < output_dims_count; ++i) { TF_LITE_MICRO_EXPECT_EQ(expected_output_data.begin()[i], output_data[i]); } } } // namespace } // namespace testing } // namespace tflite TF_LITE_MICRO_TESTS_BEGIN TF_LITE_MICRO_TEST(SimpleTest) { const int output_dims_count = 8; float output_data[output_dims_count]; tflite::testing::TestDepthwiseConvFloat( // {4, 1, 3, 2, 2}, // Input shape. { 1, 2, 7, 8, // Input values. 3, 4, 9, 10, // 5, 6, 11, 12, // }, {4, 1, 2, 2, 4}, // Filters shape. { 1, 2, 3, 4, // Filters values. -9, 10, -11, 12, // 5, 6, 7, 8, // 13, -14, 15, -16, // }, {1, 4}, // Bias shape. { 1, 2, 3, 4, // Bias values. }, { 71, -34, 99, -20, // Expected results. 91, -26, 127, -4, // }, {4, 1, 2, 1, 4}, // Output shape. kTfLiteActNone, output_data); } TF_LITE_MICRO_TEST(SimpleTestQuantized) { using tflite::testing::F2Q; using tflite::testing::F2Q32; const float input_min = -63.5f; const float input_max = 64.0f; const float filter_min = -63.5f; const float filter_max = 64.0f; const float bias_min = 0.0f; const float bias_max = 64.0f * (1 << 24); const float output_min = -127.0f; const float output_max = 128.0f; const int output_dims_count = 8; uint8_t output_data[output_dims_count]; tflite::testing::TestDepthwiseConvQuantized( // {4, 1, 3, 2, 2}, // Input shape. { // Input values. F2Q(1, input_min, input_max), F2Q(2, input_min, input_max), F2Q(7, input_min, input_max), F2Q(8, input_min, input_max), F2Q(3, input_min, input_max), F2Q(4, input_min, input_max), F2Q(9, input_min, input_max), F2Q(10, input_min, input_max), F2Q(5, input_min, input_max), F2Q(6, input_min, input_max), F2Q(11, input_min, input_max), F2Q(12, input_min, input_max), }, input_min, input_max, // Input quantization range. {4, 1, 2, 2, 4}, // Filter shape. { // Filter values. F2Q(1, filter_min, filter_max), F2Q(2, filter_min, filter_max), F2Q(3, filter_min, filter_max), F2Q(4, filter_min, filter_max), F2Q(-9, filter_min, filter_max), F2Q(10, filter_min, filter_max), F2Q(-11, filter_min, filter_max), F2Q(12, filter_min, filter_max), F2Q(5, filter_min, filter_max), F2Q(6, filter_min, filter_max), F2Q(7, filter_min, filter_max), F2Q(8, filter_min, filter_max), F2Q(13, filter_min, filter_max), F2Q(-14, filter_min, filter_max), F2Q(15, filter_min, filter_max), F2Q(-16, filter_min, filter_max), }, filter_min, filter_max, // Filter quantization range. {1, 4}, // Bias shape. { // Bias values. F2Q32(1, bias_min, bias_max), F2Q32(2, bias_min, bias_max), F2Q32(3, bias_min, bias_max), F2Q32(4, bias_min, bias_max), }, bias_min, bias_max, // Bias quantization range. { // Expected results. F2Q(71, output_min, output_max), F2Q(-34, output_min, output_max), F2Q(99, output_min, output_max), F2Q(-20, output_min, output_max), F2Q(91, output_min, output_max), F2Q(-26, output_min, output_max), F2Q(127, output_min, output_max), F2Q(-4, output_min, output_max), }, {4, 1, 2, 1, 4}, // Output shape. output_min, output_max, // Output quantization range. kTfLiteActNone, output_data); } TF_LITE_MICRO_TEST(SimpleTestRelu) { const int output_dims_count = 8; float output_data[output_dims_count]; tflite::testing::TestDepthwiseConvFloat( // {4, 1, 3, 2, 2}, // Input shape. { 1, 2, 7, 8, // Input values. 3, 4, 9, 10, // 5, 6, 11, 12, // }, {4, 1, 2, 2, 4}, // Filters shape. { 1, 2, 3, 4, // Filters values. -9, 10, -11, 12, // 5, 6, 7, 8, // 13, -14, 15, -16, // }, {1, 4}, // Bias shape. { 1, 2, 3, 4, // Bias values. }, { 71, 0, 99, 0, // Expected results. 91, 0, 127, 0, // }, {4, 1, 2, 1, 4}, // Output shape. kTfLiteActRelu, output_data); } TF_LITE_MICRO_TEST(SimpleTestReluQuantized) { using tflite::testing::F2Q; using tflite::testing::F2Q32; const float input_min = -63.5f; const float input_max = 64.0f; const float filter_min = -63.5f; const float filter_max = 64.0f; const float bias_min = 0.0f; const float bias_max = 64.0f * (1 << 24); const float output_min = -127.0f; const float output_max = 128.0f; const int output_dims_count = 8; uint8_t output_data[output_dims_count]; tflite::testing::TestDepthwiseConvQuantized( // {4, 1, 3, 2, 2}, // Input shape. { // Input values. F2Q(1, input_min, input_max), F2Q(2, input_min, input_max), F2Q(7, input_min, input_max), F2Q(8, input_min, input_max), F2Q(3, input_min, input_max), F2Q(4, input_min, input_max), F2Q(9, input_min, input_max), F2Q(10, input_min, input_max), F2Q(5, input_min, input_max), F2Q(6, input_min, input_max), F2Q(11, input_min, input_max), F2Q(12, input_min, input_max), }, input_min, input_max, // Input quantization range. {4, 1, 2, 2, 4}, // Filter shape. { // Filter values. F2Q(1, filter_min, filter_max), F2Q(2, filter_min, filter_max), F2Q(3, filter_min, filter_max), F2Q(4, filter_min, filter_max), F2Q(-9, filter_min, filter_max), F2Q(10, filter_min, filter_max), F2Q(-11, filter_min, filter_max), F2Q(12, filter_min, filter_max), F2Q(5, filter_min, filter_max), F2Q(6, filter_min, filter_max), F2Q(7, filter_min, filter_max), F2Q(8, filter_min, filter_max), F2Q(13, filter_min, filter_max), F2Q(-14, filter_min, filter_max), F2Q(15, filter_min, filter_max), F2Q(-16, filter_min, filter_max), }, filter_min, filter_max, // Filter quantization range. {1, 4}, // Bias shape. { // Bias values. F2Q32(1, bias_min, bias_max), F2Q32(2, bias_min, bias_max), F2Q32(3, bias_min, bias_max), F2Q32(4, bias_min, bias_max), }, bias_min, bias_max, // Bias quantization range. { // Expected results. F2Q(71, output_min, output_max), F2Q(0, output_min, output_max), F2Q(99, output_min, output_max), F2Q(0, output_min, output_max), F2Q(91, output_min, output_max), F2Q(0, output_min, output_max), F2Q(127, output_min, output_max), F2Q(0, output_min, output_max), }, {4, 1, 2, 1, 4}, // Output shape. output_min, output_max, // Output quantization range. kTfLiteActRelu, output_data); } TF_LITE_MICRO_TESTS_END
// Copyright (c) 2016-2020 Intel Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "convolution_kernel_b_fs_yx_fsv16.h" #include "kernel_selector_utils.h" #include <vector> #include <algorithm> namespace kernel_selector { ConvolutionKernel_b_fs_yx_fsv16::ConvolutionKernel_b_fs_yx_fsv16() : ConvolutionKernelBase("convolution_gpu_bfyx_f16") { std::vector<size_t> outputBlockWidths = { 2, 4, 8 }; std::vector<std::string> executionModes = ConvolutionKernelBase::autoTuneOptions; for (auto w : outputBlockWidths) { for (auto exeMode : executionModes) { autoTuneOptions.emplace_back(AutoTuneOption{ w, exeMode }); } } } ConvolutionKernel_b_fs_yx_fsv16::AutoTuneOption ConvolutionKernel_b_fs_yx_fsv16::GetAutoTuneOptions(const Params& params, int /*autoTuneIndex*/) const { const convolution_params& cp = static_cast<const convolution_params&>(params); auto x = cp.output.X().v; auto f = cp.output.Feature().v; if (x * f <= 256) { if (x <= 8 || x * f <= 128) return { 2, DEFAULT }; else return { 4, DEFAULT }; } else if (x * f <= 1536) { return { 4, DEFAULT }; } else { if (x >= 8 && x < 12 && x * f < 2600) return { 4, DEFAULT }; else if (x < 12 && x * f < 8192) return { 8, DEFAULT }; else return { 8, AGE_BASED }; } } float ConvolutionKernel_b_fs_yx_fsv16::EstimateOccupancy(const convolution_params& params, const ConvolutionTuningData& tuning_data) const { auto tuneOptions = GetAutoTuneOptions(params, 0); auto blockWidth = tuneOptions.blockWidth; auto x = params.output.X().v; auto y = params.output.Y().v; auto f = params.output.Feature().v; auto b = params.output.Batch().v; auto threads = CeilDiv(x, blockWidth) * y * CeilDiv(f, tuning_data.feature_block_size) * tuning_data.slm_div_factor * b; return static_cast<float>(threads) / static_cast<float>(params.engineInfo.maxThreadsPerDevice); } ConvolutionKernel_b_fs_yx_fsv16::ConvolutionTuningData ConvolutionKernel_b_fs_yx_fsv16::GetTuningParams(const convolution_params& params) const { ConvolutionTuningData tuning_data; const auto& input = params.inputs[0]; size_t ic_blocks = CeilDiv(input.Feature().v / params.groups, tuning_data.feature_block_size); size_t max_slm_div_factor = params.engineInfo.maxWorkGroupSize / tuning_data.sub_group_size; bool slm_exception = params.output.X().v == 3 && params.output.Y().v == 3 && params.output.ElementSize() == 4 && params.output.Feature().v <= 512; if (params.engineInfo.deviceType == dev_type::integrated_gpu && params.engineInfo.bIMADSupport && !slm_exception) while (ic_blocks % (tuning_data.slm_div_factor * 2) == 0 && (tuning_data.slm_div_factor * 2 <= max_slm_div_factor) && EstimateOccupancy(params, tuning_data) < 4.0) tuning_data.slm_div_factor *= 2; tuning_data.work_group_size = tuning_data.slm_div_factor * tuning_data.sub_group_size; return tuning_data; } ParamsKey ConvolutionKernel_b_fs_yx_fsv16::GetSupportedKey() const { ParamsKey k; k.EnableInputDataType(Datatype::F16); k.EnableInputDataType(Datatype::F32); k.EnableOutputDataType(Datatype::F16); k.EnableOutputDataType(Datatype::F32); k.EnableOutputDataType(Datatype::INT8); k.EnableOutputDataType(Datatype::UINT8); k.EnableInputWeightsType(WeightsType::F16); k.EnableInputWeightsType(WeightsType::F32); k.EnableDifferentTypes(); k.EnableInputLayout(DataLayout::b_fs_yx_fsv16); k.EnableOutputLayout(DataLayout::b_fs_yx_fsv16); k.EnableTensorOffset(); k.EnableTensorPitches(); k.EnableDilation(); k.EnableBiasPerFeature(); // TODO Add bias per output support to kernel // k.EnableBiasPerOutput(); k.EnableNonBiasTerm(); k.EnableSplitSupport(); k.EnableBatching(); k.EnableDepthwiseSeparableOpt(); k.EnableSubGroup(); k.EnableSubGroupShort(); k.EnableGroupedConvolution(); return k; } ConvolutionKernelBase::DispatchData ConvolutionKernel_b_fs_yx_fsv16::SetDefault(const convolution_params& params, int autoTuneIndex) const { DispatchData dispatchData = ConvolutionKernelBase::SetDefault(params); ConvolutionTuningData tuning_data = GetTuningParams(params); const auto& out = params.output; auto autoTune = GetAutoTuneOptions(params, autoTuneIndex); dispatchData.cldnnStyle.blockWidth = autoTune.blockWidth; auto x = out.X().v; auto y = out.Y().v; auto f = out.Feature().v; auto b = out.Batch().v; dispatchData.gws[0] = CeilDiv(x, autoTune.blockWidth) * y; dispatchData.gws[1] = Align(f, tuning_data.feature_block_size) * tuning_data.slm_div_factor; dispatchData.gws[2] = b; dispatchData.lws[0] = 1; dispatchData.lws[1] = tuning_data.work_group_size; dispatchData.lws[2] = 1; return dispatchData; } KernelsPriority ConvolutionKernel_b_fs_yx_fsv16::GetKernelsPriority(const Params& params, const optional_params& /*options*/) const { const auto& p = static_cast<const convolution_params&>(params); return p.output.Batch().v == 1 ? FORCE_PRIORITY_2 : FORCE_PRIORITY_7; } bool ConvolutionKernel_b_fs_yx_fsv16::Validate(const Params& p, const optional_params& o) const { if (!ConvolutionKernelBase::Validate(p, o) || !CovolutionCheckInput(p, o)) { return false; } const auto& params = static_cast<const convolution_params&>(p); ConvolutionTuningData tuning_data = GetTuningParams(params); const auto& input = params.inputs[0]; const auto& output = params.output; if (params.groups > 1) { auto outFeaturesPerGroup = output.Feature().v / params.groups; auto inFeaturesPerGroup = input.Feature().v / params.groups; auto multipleGroupsInputPreload = (tuning_data.feature_block_size % outFeaturesPerGroup == 0) && (tuning_data.feature_block_size % inFeaturesPerGroup == 0) && (tuning_data.feature_block_size / outFeaturesPerGroup > 1) && (tuning_data.feature_block_size / inFeaturesPerGroup > 1) && (outFeaturesPerGroup != 1) && (inFeaturesPerGroup != 1); auto grouped = inFeaturesPerGroup % tuning_data.sub_group_size == 0 && (outFeaturesPerGroup % tuning_data.sub_group_size == 0 || tuning_data.sub_group_size % outFeaturesPerGroup == 0); if (!multipleGroupsInputPreload && !grouped) return false; } // Check that padding before features doesn't miss-align the blocks if (input.Feature().pad.before % tuning_data.feature_block_size != 0 || output.Feature().pad.before % tuning_data.feature_block_size != 0) return false; if (!params.bias.empty() && params.bias[0].GetDType() != input.GetDType()) return false; return true; } JitConstants ConvolutionKernel_b_fs_yx_fsv16::GetJitConstants(const convolution_params& params, const DispatchData& dispatchData) const { auto input = params.inputs[0]; auto output = params.output; auto jit = Parent::GetJitConstants(params, dispatchData); ConvolutionTuningData tuning_data = GetTuningParams(params); auto blockWidth = dispatchData.cldnnStyle.blockWidth; if (!params.fused_ops.empty()) { auto input_dt = GetActivationType(params); FusedOpsConfiguration conf_vec = { "_VEC", {"b", "(feature_block * 16)", "y", "x"}, "dst", input_dt, blockWidth, LoadType::LT_ALIGNED_READ, BoundaryCheck::ENABLED, IndexType::TENSOR_COORD, Tensor::DataChannelName::X }; FusedOpsConfiguration conf_scalar = { "_SCALAR", {"b", "(feature_block * 16)", "y", "(x + i)"}, "dst[i]", input_dt, 1, LoadType::LT_ALIGNED_READ, BoundaryCheck::ENABLED, IndexType::TENSOR_COORD, Tensor::DataChannelName::X }; jit.Merge(MakeFusedOpsJitConstants(params, {conf_vec, conf_scalar})); } size_t input_line_size = std::min(params.stride.x * (blockWidth - 1) + (params.weights.X().v - 1)*params.dilation.x + 1, input.X().v + input.X().pad.Total()); auto outFeaturesPerGroup = output.Feature().v / params.groups; auto inFeaturesPerGroup = input.Feature().v / params.groups; auto multipleGroupsInputPreload = (tuning_data.feature_block_size % outFeaturesPerGroup == 0) && (tuning_data.feature_block_size % inFeaturesPerGroup == 0) && (tuning_data.feature_block_size / outFeaturesPerGroup > 1) && (tuning_data.feature_block_size / inFeaturesPerGroup > 1); if (multipleGroupsInputPreload) jit.AddConstant(MakeJitConstant("MULTIPLE_GROUPS_INPUT_PRELOAD", 1)); jit.AddConstant(MakeJitConstant("OUTPUT_X_BLOCK_SIZE", blockWidth)); jit.AddConstant(MakeJitConstant("INPUT_LINE_SIZE", input_line_size)); jit.AddConstant(MakeJitConstant("SUB_GROUP_SIZE", tuning_data.sub_group_size)); jit.AddConstant(MakeJitConstant("X_BLOCKS", CeilDiv(output.X().v, blockWidth))); jit.AddConstant(MakeJitConstant("SLM_DIV_FACTOR", tuning_data.slm_div_factor)); jit.AddConstant(MakeJitConstant("WORK_GROUP_SIZE", tuning_data.work_group_size)); jit.AddConstant(MakeJitConstant("IC_BLOCKS", CeilDiv(inFeaturesPerGroup, tuning_data.feature_block_size))); if (params.output.Feature().v % tuning_data.feature_block_size != 0) { jit.AddConstant(MakeJitConstant("OUTPUT_LEFTOVERS", 1)); } if (inFeaturesPerGroup % tuning_data.feature_block_size != 0 && !multipleGroupsInputPreload) { jit.AddConstant(MakeJitConstant("INPUT_LEFTOVERS", 1)); } return jit; } KernelsData ConvolutionKernel_b_fs_yx_fsv16::GetTunedKernelsDataByIndex(const Params& params, const optional_params& options, const int autoTuneIndex) const { auto tuneOptions = GetAutoTuneOptions(params, autoTuneIndex); return GetCommonKernelsData(params, options, tuneOptions.exeMode, autoTuneIndex); } KernelsData ConvolutionKernel_b_fs_yx_fsv16::GetKernelsData(const Params& params, const optional_params& options) const { return GetTunedKernelsDataByIndex(params, options); } KernelsData ConvolutionKernel_b_fs_yx_fsv16::GetKernelsDataForAutoTune(const Params& params, const optional_params& options) const { if (!Validate(params, options)) { return {}; } KernelsData res = {}; for (size_t i = 0; i < autoTuneOptions.size(); i++) { KernelsData kd = GetTunedKernelsDataByIndex(params, options, static_cast<int>(i)); if (!kd.empty()) { res.emplace_back(kd[0]); } } return res; } } // namespace kernel_selector
/* * Copyright 2020-2022 Hewlett Packard Enterprise Development LP * Copyright 2004-2019 Cray Inc. * Other additional copyright holders may be indicated within. * * The entirety of this work is 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 "CForLoop.h" #include "astutil.h" #include "AstVisitor.h" #include "build.h" #include "codegen.h" #include "driver.h" #include "ForLoop.h" #include "LayeredValueTable.h" #ifdef HAVE_LLVM #include "llvm/IR/Module.h" #endif #include <algorithm> #ifdef HAVE_LLVM // Returns the loop metadata node to associate with the branch. // If thisLoopParallelAccess is set, accessGroup will be set to the // metadata node to use in llvm.access.group metadata for this loop. static llvm::MDNode* generateLoopMetadata(bool thisLoopParallelAccess, llvm::MDNode*& accessGroup) { GenInfo* info = gGenInfo; auto &ctx = info->module->getContext(); std::vector<llvm::Metadata*> args; // Resolve operand 0 for the loop id self reference auto tmpNode = llvm::MDNode::getTemporary(ctx, llvm::None); args.push_back(tmpNode.get()); // llvm.loop.vectorize.enable metadata is only used by LoopVectorizer to: // 1) Explicitly disable vectorization of particular loop // 2) Print warning when vectorization is enabled (using metadata) and // vectorization didn't occur // Here we do not emit that metadata; instead emitting parallel // llvm.loop.parallel_accesses. // Does the current loop, or any outer loop in the loop stack, // require llvm.loop.parallel_accesses metadata? bool anyParallelAccesses = false; if (thisLoopParallelAccess) { anyParallelAccesses = true; accessGroup = llvm::MDNode::getDistinct(ctx, {}); } else { accessGroup = NULL; for (auto & loopData : info->loopStack) { if (loopData.markMemoryOps) anyParallelAccesses = true; } } if (anyParallelAccesses) { std::vector<llvm::Metadata*> v; v.push_back(llvm::MDString::get(ctx, "llvm.loop.parallel_accesses")); // Generate {"llvm.loop.parallel_accesses", group1, group2, ...} // where the groups are any parallel loops we are currently in // (including outer loops to this loop). if (thisLoopParallelAccess) { v.push_back(accessGroup); } for (auto & loopData : info->loopStack) { if (loopData.markMemoryOps) { v.push_back(loopData.accessGroup); } } llvm::MDNode* parAccesses = llvm::MDNode::get(ctx, v); args.push_back(parAccesses); } // When using the Region Vectorizer, emit rv.loop.vectorize.enable metadata if(fRegionVectorizer) { llvm::Constant* one = llvm::ConstantInt::get(llvm::Type::getInt1Ty(ctx), true); llvm::Metadata *loopVectorizeEnable[] = { llvm::MDString::get(ctx, "rv.loop.vectorize.enable"), llvm::ConstantAsMetadata::get(one) }; args.push_back(llvm::MDNode::get(ctx, loopVectorizeEnable)); // Note that the Region Vectorizer once required // llvm.loop.vectorize.width but no longer does. } llvm::MDNode *loopMetadata = llvm::MDNode::get(ctx, args); loopMetadata->replaceOperandWith(0, loopMetadata); return loopMetadata; } // loopMetadata is the metadata to associate with the branch. // It will be extended to add llvm.loop.parallel_accesses // for the current loop (represented by parallel_accesses) // as well as any enclosing loops (from loopStack). static void addLoopMetadata(llvm::Instruction* instruction, llvm::MDNode* loopMetadata, llvm::MDNode* accessGroup) { instruction->setMetadata("llvm.loop", loopMetadata); } #endif /************************************ | ************************************* * * * Instance methods * * * ************************************* | ************************************/ GenRet CForLoop::codegen() { GenInfo* info = gGenInfo; FILE* outfile = info->cfile; GenRet ret; codegenStmt(this); reportVectorizable(); if (outfile) { BlockStmt* initBlock = initBlockGet(); // These copy calls are needed or else values get code generated twice. std::string init = codegenCForLoopHeader(initBlock->copy()); BlockStmt* testBlock = testBlockGet(); std::string test = codegenCForLoopHeader(testBlock->copy()); // wrap the test with paren. Could probably check if it already has // outer paren to make the code a little cleaner. if (test != "") test = "(" + test + ")"; BlockStmt* incrBlock = incrBlockGet(); std::string incr = codegenCForLoopHeader(incrBlock->copy()); std::string hdr = "for (" + init + "; " + test + "; " + incr + ") "; info->cStatements.push_back(hdr); if (this != getFunction()->body) info->cStatements.push_back("{\n"); body.codegen(""); if (this != getFunction()->body) { std::string end = "}"; CondStmt* cond = toCondStmt(parentExpr); if (!cond || !(cond->thenStmt == this && cond->elseStmt)) end += "\n"; info->cStatements.push_back(end); } } else { #ifdef HAVE_LLVM llvm::Function* func = info->irBuilder->GetInsertBlock()->getParent(); llvm::BasicBlock* blockStmtInit = NULL; llvm::BasicBlock* blockStmtBody = NULL; llvm::BasicBlock* blockStmtEnd = NULL; BlockStmt* initBlock = initBlockGet(); BlockStmt* testBlock = testBlockGet(); BlockStmt* incrBlock = incrBlockGet(); assert(initBlock && testBlock && incrBlock); getFunction()->codegenUniqueNum++; blockStmtBody = llvm::BasicBlock::Create(info->module->getContext(), FNAME("blk_body")); blockStmtEnd = llvm::BasicBlock::Create(info->module->getContext(), FNAME("blk_end")); // In order to track more easily with the C backend and because mem2reg should optimize // all of these cases, we generate a for loop as the same as // if(cond) do { body; step; } while(cond). // However it is appealing to generate these low-level loops directly // in LLVM IR: // * could avoid repeated loads // * could simplify generated IR // * could avoid problems identifying induction variables // Create the init basic block blockStmtInit = llvm::BasicBlock::Create(info->module->getContext(), FNAME("blk_c_for_init")); func->getBasicBlockList().push_back(blockStmtInit); // Insert an explicit branch from the current block to the init block info->irBuilder->CreateBr(blockStmtInit); // Now switch to the init block for code generation info->irBuilder->SetInsertPoint(blockStmtInit); // Code generate the init block. initBlock->body.codegen(""); // Add the loop condition to figure out if we run the loop at all. GenRet test0 = codegenCForLoopCondition(testBlock); llvm::Value* condValue0 = test0.val; // Normalize it to boolean if (condValue0->getType() != llvm::Type::getInt1Ty(info->module->getContext())) condValue0 = info->irBuilder->CreateICmpNE(condValue0, llvm::ConstantInt::get(condValue0->getType(), 0), FNAME("condition")); // Create the conditional branch info->irBuilder->CreateCondBr(condValue0, blockStmtBody, blockStmtEnd); // Now add the body. func->getBasicBlockList().push_back(blockStmtBody); info->irBuilder->SetInsertPoint(blockStmtBody); info->lvt->addLayer(); llvm::MDNode* accessGroup = nullptr; llvm::MDNode* loopMetadata = nullptr; if(fNoVectorize == false && isVectorizable()) { loopMetadata = generateLoopMetadata(isParallelAccessVectorizable(), accessGroup); LoopData data(accessGroup, isParallelAccessVectorizable()); info->loopStack.push_back(data); } body.codegen(""); if(loopMetadata) info->loopStack.pop_back(); info->lvt->removeLayer(); incrBlock->body.codegen(""); GenRet test1 = codegenCForLoopCondition(testBlock); llvm::Value* condValue1 = test1.val; // Normalize it to boolean if (condValue1->getType() != llvm::Type::getInt1Ty(info->module->getContext())) condValue1 = info->irBuilder->CreateICmpNE(condValue1, llvm::ConstantInt::get(condValue1->getType(), 0), FNAME("condition")); // Create the conditional branch llvm::Instruction* endLoopBranch = info->irBuilder->CreateCondBr(condValue1, blockStmtBody, blockStmtEnd); if(loopMetadata) addLoopMetadata(endLoopBranch, loopMetadata, accessGroup); func->getBasicBlockList().push_back(blockStmtEnd); info->irBuilder->SetInsertPoint(blockStmtEnd); if (blockStmtBody) INT_ASSERT(blockStmtBody->getParent() == func); if (blockStmtEnd ) INT_ASSERT(blockStmtEnd->getParent() == func); #endif } return ret; } // This function is used to codegen the init, test, and incr segments of c for // loops. In c for loops instead of using statements comma operators must be // used. So for the init instead of generating something like: // i = 4; // j = 4; // // We need to generate: // i = 4, j = 4 std::string CForLoop::codegenCForLoopHeader(BlockStmt* block) { GenInfo* info = gGenInfo; std::string seg = ""; for_alist(expr, block->body) { CallExpr* call = toCallExpr(expr); // Generate defExpr normally (they always get codegenned at the top of a // function currently, if that changes this code will probably be wrong.) if (DefExpr* defExpr = toDefExpr(expr)) { defExpr->codegen(); } // If inlining is off, the init, test, and incr are just functions and we // need to generate them inline so we use codegenValue. The semicolon is // added so it can be replaced with the comma later. If inlining is on // the test will be a <= and it also needs to be codegenned with // codegenValue. // // TODO when the test operator is user specifiable and not just <= this // will need to be updated to include all possible conditionals. (I'm // imagining we'll want a separate function that can check if a primitive // is a conditional as I think we'll need that info elsewhere.) else if (call && (call->isResolved() || isRelationalOperator(call) || call->isPrimitive(PRIM_GET_MEMBER_VALUE))) { std::string callStr = codegenValue(call).c; if (callStr != "") { seg += callStr + ';'; } } // Similar to above, generate symExprs else if (SymExpr* symExpr = toSymExpr(expr)) { std::string symStr = codegenValue(symExpr).c; if (symStr != "") { seg += symStr + ';'; } } // Everything else is just a bunch of statements. We do normal codegen() on // them which ends up putting whatever got codegenned into CStatements. We // pop all of those back off (note that the order we pop and attach to our // segment is important.) else { int prevStatements = (int) info->cStatements.size(); expr->codegen(); int newStatements = (int) info->cStatements.size() - prevStatements; for (std::vector<std::string>::iterator it = info->cStatements.end() - newStatements; it != info->cStatements.end(); ++it) { seg += *it; } info->cStatements.erase(info->cStatements.end() - newStatements, info->cStatements.end()); } } // replace all the semicolons (from "statements") with commas std::replace(seg.begin(), seg.end(), ';', ','); // remove all the newlines seg.erase(std::remove(seg.begin(), seg.end(), '\n'), seg.end()); // remove the last character if any were generated (it's a trailing comma // since we previously had an appropriate "trailing" semicolon) if (seg.size () > 0) seg.resize (seg.size () - 1); return seg; } GenRet CForLoop::codegenCForLoopCondition(BlockStmt* block) { GenRet ret; #ifdef HAVE_LLVM for_alist(expr, block->body) { ret = expr->codegen(); } return codegenValue(ret); #else return ret; #endif }
/* uefipatch_main.cpp Copyright (c) 2018, LongSoft. All rights reserved. This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. */ #include <QCoreApplication> #include <QString> #include <QStringList> #include <iostream> #include <string> #include "../version.h" #include "uefipatch.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); a.setOrganizationName("LongSoft"); a.setOrganizationDomain("longsoft.me"); a.setApplicationName("UEFIPatch"); UEFIPatch w; UINT8 result = ERR_SUCCESS; const QStringList &args = a.arguments(); UINT32 argumentsCount = args.length(); if (argumentsCount < 2) { std::cout << "UEFIPatch " PROGRAM_VERSION " - UEFI image file patching utility" << std::endl << std::endl << "Usage: UEFIPatch image_file [patches.txt] [-o output]" << std::endl << "Usage: UEFIPatch image_file [-p \"Guid SectionType Patch\"] [-o output]" << std::endl << std::endl << "Patches will be read from patches.txt file by default\n"; return ERR_SUCCESS; } QString inputPath = a.arguments().at(1); QString patches = "patches.txt"; QString outputPath = inputPath + ".patched"; int patchFrom = PATCH_FROM_FILE; for (UINT32 i = 2; i < argumentsCount; i++) { if ((args.at(i) == "-p" || args.at(i) == "--patch") && i + 1 < argumentsCount) { patchFrom = PATCH_FROM_ARG; patches = args.at(i+1); i++; } else if ((args.at(i) == "-o" || args.at(i) == "--output") && i + 1 < argumentsCount) { outputPath = args.at(i+1); i++; } else if (patches == "patches.txt") { patches = args.at(i); } else { result = ERR_INVALID_PARAMETER; } } if (result == ERR_SUCCESS) { if (patchFrom == PATCH_FROM_FILE) { result = w.patchFromFile(inputPath, patches, outputPath); } else if (patchFrom == PATCH_FROM_ARG) { result = w.patchFromArg(inputPath, patches, outputPath); } } switch (result) { case ERR_SUCCESS: std::cout << "Image patched" << std::endl; break; case ERR_INVALID_PARAMETER: std::cout << "Function called with invalid parameter" << std::endl; break; case ERR_NOTHING_TO_PATCH: std::cout << "No patches can be applied to input file" << std::endl; break; case ERR_UNKNOWN_PATCH_TYPE: std::cout << "Unknown patch type" << std::endl; break; case ERR_PATCH_OFFSET_OUT_OF_BOUNDS: std::cout << "Patch offset out of bounds" << std::endl; break; case ERR_INVALID_SYMBOL: std::cout << "Pattern format mismatch" << std::endl; break; case ERR_INVALID_FILE: std::cout << patches.toStdString() << " file not found or can't be read" << std::endl; break; case ERR_FILE_OPEN: std::cout << "Input file not found" << std::endl; break; case ERR_FILE_READ: std::cout << "Input file can't be read" << std::endl; break; case ERR_FILE_WRITE: std::cout << "Output file can't be written" << std::endl; break; default: std::cout << "Error " << result << std::endl; } return result; }
/****************************************************************************** This source file is part of the tomviz project. Copyright Kitware, Inc. This source code is released under the New BSD License, (the "License"). 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 "ActiveObjects.h" #include "ModuleManager.h" #include "pqActiveObjects.h" #include "pqApplicationCore.h" #include "pqPipelineSource.h" #include "pqServer.h" #include "pqView.h" #include "Utilities.h" #include "vtkSMSourceProxy.h" #include "vtkSMViewProxy.h" namespace tomviz { //----------------------------------------------------------------------------- ActiveObjects::ActiveObjects() : Superclass(), ActiveDataSource(NULL), VoidActiveDataSource(NULL), ActiveModule(NULL), VoidActiveModule(NULL) { this->connect(&pqActiveObjects::instance(), SIGNAL(viewChanged(pqView*)), SLOT(viewChanged(pqView*))); this->connect(&ModuleManager::instance(), SIGNAL(dataSourceRemoved(DataSource*)), SLOT(dataSourceRemoved(DataSource*))); this->connect(&ModuleManager::instance(), SIGNAL(moduleRemoved(Module*)), SLOT(moduleRemoved(Module*))); } //----------------------------------------------------------------------------- ActiveObjects::~ActiveObjects() { } //----------------------------------------------------------------------------- ActiveObjects& ActiveObjects::instance() { static ActiveObjects theInstance; return theInstance; } //----------------------------------------------------------------------------- void ActiveObjects::setActiveView(vtkSMViewProxy* view) { pqActiveObjects::instance().setActiveView(tomviz::convert<pqView*>(view)); } //----------------------------------------------------------------------------- vtkSMViewProxy* ActiveObjects::activeView() const { pqView* view = pqActiveObjects::instance().activeView(); return view ? view->getViewProxy() : NULL; } //----------------------------------------------------------------------------- void ActiveObjects::viewChanged(pqView* view) { emit this->viewChanged(view ? view->getViewProxy() : NULL); } //----------------------------------------------------------------------------- void ActiveObjects::dataSourceRemoved(DataSource* ds) { if (this->VoidActiveDataSource == ds) { this->setActiveDataSource(NULL); } } //----------------------------------------------------------------------------- void ActiveObjects::moduleRemoved(Module* mdl) { if (this->VoidActiveModule == mdl) { this->setActiveModule(NULL); } } //----------------------------------------------------------------------------- void ActiveObjects::setActiveDataSource(DataSource* source) { if (this->VoidActiveDataSource != source) { this->ActiveDataSource = source; this->VoidActiveDataSource = source; emit this->dataSourceChanged(this->ActiveDataSource); } } //----------------------------------------------------------------------------- vtkSMSessionProxyManager* ActiveObjects::proxyManager() const { pqServer* server = pqActiveObjects::instance().activeServer(); return server ? server->proxyManager() : NULL; } //----------------------------------------------------------------------------- void ActiveObjects::setActiveModule(Module* module) { if (this->VoidActiveModule != module) { this->VoidActiveModule = module; this->ActiveModule = module; if (module) { this->setActiveView(module->view()); this->setActiveDataSource(module->dataSource()); } emit this->moduleChanged(module); } } //----------------------------------------------------------------------------- void ActiveObjects::renderAllViews() { pqApplicationCore::instance()->render(); } //----------------------------------------------------------------------------- } // end of namespace tomviz
// Name: // This program calculates the tax and tip on a restaurant bill. #include <iostream> int main() { double tax, tip, total_bill, total_meal_cost; // Welcome to the Restaurant Bill Calculator. std::cout << "Welcome to the Restaurant Bill Calculator!\n "; std::cout << "What is the 'total meal cost'? "; std::cin >> total_meal_cost; // Adding tax to total cost. tax = 0.0775 * total_meal_cost; std::cout << "Tax: \t\t " << tax << "\n"; // Adding tip to total cost. tip = 0.20 * total_meal_cost; std::cout << "Tip: \t\t " << tip << "\n"; // Calculate total meal cost, tax, and tip. total_bill = total_meal_cost + tax + tip; // The total bill cost. std::cout << "Total Bill: \t" << total_bill << " \n"; return 0; }
#include <Processors/LimitTransform.h> namespace DB { namespace ErrorCodes { extern const int LOGICAL_ERROR; } LimitTransform::LimitTransform( const Block & header_, UInt64 limit_, UInt64 offset_, size_t num_streams, bool always_read_till_end_, bool with_ties_, SortDescription description_) : IProcessor(InputPorts(num_streams, header_), OutputPorts(num_streams, header_)) , limit(limit_), offset(offset_) , always_read_till_end(always_read_till_end_) , with_ties(with_ties_), description(std::move(description_)) { if (num_streams != 1 && with_ties) throw Exception("Cannot use LimitTransform with multiple ports and ties.", ErrorCodes::LOGICAL_ERROR); ports_data.resize(num_streams); size_t cur_stream = 0; for (auto & input : inputs) { ports_data[cur_stream].input_port = &input; ++cur_stream; } cur_stream = 0; for (auto & output : outputs) { ports_data[cur_stream].output_port = &output; ++cur_stream; } for (const auto & desc : description) { if (!desc.column_name.empty()) sort_column_positions.push_back(header_.getPositionByName(desc.column_name)); else sort_column_positions.push_back(desc.column_number); } } Chunk LimitTransform::makeChunkWithPreviousRow(const Chunk & chunk, UInt64 row) const { assert(row < chunk.getNumRows()); ColumnRawPtrs current_columns = extractSortColumns(chunk.getColumns()); MutableColumns last_row_sort_columns; for (size_t i = 0; i < current_columns.size(); ++i) { last_row_sort_columns.emplace_back(current_columns[i]->cloneEmpty()); last_row_sort_columns[i]->insertFrom(*current_columns[i], row); } return Chunk(std::move(last_row_sort_columns), 1); } IProcessor::Status LimitTransform::prepare( const PortNumbers & updated_input_ports, const PortNumbers & updated_output_ports) { bool has_full_port = false; auto process_pair = [&](size_t pos) { auto status = preparePair(ports_data[pos]); switch (status) { case IProcessor::Status::Finished: { if (!ports_data[pos].is_finished) { ports_data[pos].is_finished = true; ++num_finished_port_pairs; } return; } case IProcessor::Status::PortFull: { has_full_port = true; return; } case IProcessor::Status::NeedData: return; default: throw Exception( "Unexpected status for LimitTransform::preparePair : " + IProcessor::statusToName(status), ErrorCodes::LOGICAL_ERROR); } }; for (auto pos : updated_input_ports) process_pair(pos); for (auto pos : updated_output_ports) process_pair(pos); /// All ports are finished. It may happen even before we reached the limit (has less data then limit). if (num_finished_port_pairs == ports_data.size()) return Status::Finished; bool limit_is_unreachable = (limit > std::numeric_limits<UInt64>::max() - offset); /// If we reached limit for some port, then close others. Otherwise some sources may infinitely read data. /// Example: SELECT * FROM system.numbers_mt WHERE number = 1000000 LIMIT 1 if ((!limit_is_unreachable && rows_read >= offset + limit) && !previous_row_chunk && !always_read_till_end) { for (auto & input : inputs) input.close(); for (auto & output : outputs) output.finish(); return Status::Finished; } if (has_full_port) return Status::PortFull; return Status::NeedData; } LimitTransform::Status LimitTransform::prepare() { if (ports_data.size() != 1) throw Exception("prepare without arguments is not supported for multi-port LimitTransform.", ErrorCodes::LOGICAL_ERROR); return prepare({0}, {0}); } LimitTransform::Status LimitTransform::preparePair(PortsData & data) { auto & output = *data.output_port; auto & input = *data.input_port; /// Check can output. bool output_finished = false; if (output.isFinished()) { output_finished = true; if (!always_read_till_end) { input.close(); return Status::Finished; } } if (!output_finished && !output.canPush()) { input.setNotNeeded(); return Status::PortFull; } bool limit_is_unreachable = (limit > std::numeric_limits<UInt64>::max() - offset); /// Check if we are done with pushing. bool is_limit_reached = !limit_is_unreachable && rows_read >= offset + limit && !previous_row_chunk; if (is_limit_reached) { if (!always_read_till_end) { output.finish(); input.close(); return Status::Finished; } } /// Check can input. if (input.isFinished()) { output.finish(); return Status::Finished; } input.setNeeded(); if (!input.hasData()) return Status::NeedData; data.current_chunk = input.pull(true); auto rows = data.current_chunk.getNumRows(); if (rows_before_limit_at_least) rows_before_limit_at_least->add(rows); /// Skip block (for 'always_read_till_end' case). if (is_limit_reached || output_finished) { data.current_chunk.clear(); if (input.isFinished()) { output.finish(); return Status::Finished; } /// Now, we pulled from input, and it must be empty. input.setNeeded(); return Status::NeedData; } /// Process block. rows_read += rows; if (rows_read <= offset) { data.current_chunk.clear(); if (input.isFinished()) { output.finish(); return Status::Finished; } /// Now, we pulled from input, and it must be empty. input.setNeeded(); return Status::NeedData; } if (rows <= std::numeric_limits<UInt64>::max() - offset && rows_read >= offset + rows && !limit_is_unreachable && rows_read <= offset + limit) { /// Return the whole chunk. /// Save the last row of current chunk to check if next block begins with the same row (for WITH TIES). if (with_ties && rows_read == offset + limit) previous_row_chunk = makeChunkWithPreviousRow(data.current_chunk, data.current_chunk.getNumRows() - 1); } else /// This function may be heavy to execute in prepare. But it happens no more then twice, and make code simpler. splitChunk(data); bool may_need_more_data_for_ties = previous_row_chunk || rows_read - rows <= offset + limit; /// No more data is needed. if (!always_read_till_end && !limit_is_unreachable && rows_read >= offset + limit && !may_need_more_data_for_ties) input.close(); output.push(std::move(data.current_chunk)); return Status::PortFull; } void LimitTransform::splitChunk(PortsData & data) { auto current_chunk_sort_columns = extractSortColumns(data.current_chunk.getColumns()); UInt64 num_rows = data.current_chunk.getNumRows(); UInt64 num_columns = data.current_chunk.getNumColumns(); bool limit_is_unreachable = (limit > std::numeric_limits<UInt64>::max() - offset); if (previous_row_chunk && !limit_is_unreachable && rows_read >= offset + limit) { /// Scan until the first row, which is not equal to previous_row_chunk (for WITH TIES) UInt64 current_row_num = 0; for (; current_row_num < num_rows; ++current_row_num) { if (!sortColumnsEqualAt(current_chunk_sort_columns, current_row_num)) break; } auto columns = data.current_chunk.detachColumns(); if (current_row_num < num_rows) { previous_row_chunk = {}; for (UInt64 i = 0; i < num_columns; ++i) columns[i] = columns[i]->cut(0, current_row_num); } data.current_chunk.setColumns(std::move(columns), current_row_num); return; } /// return a piece of the block UInt64 start = 0; /// ------------[....(...).] /// <----------------------> rows_read /// <----------> num_rows /// <---------------> offset /// <---> start assert(offset < rows_read); if (offset + num_rows > rows_read) start = offset + num_rows - rows_read; /// ------------[....(...).] /// <----------------------> rows_read /// <----------> num_rows /// <---------------> offset /// <---> limit /// <---> length /// <---> start /// Or: /// -----------------(------[....)....] /// <---------------------------------> rows_read /// <---------> num_rows /// <---------------> offset /// <-----------> limit /// <----> length /// 0 = start UInt64 length = num_rows - start; if (!limit_is_unreachable && offset + limit < rows_read) { if (offset + limit < rows_read - num_rows) length = 0; else length = offset + limit - (rows_read - num_rows) - start; } /// check if other rows in current block equals to last one in limit if (with_ties && length) { UInt64 current_row_num = start + length; previous_row_chunk = makeChunkWithPreviousRow(data.current_chunk, current_row_num - 1); for (; current_row_num < num_rows; ++current_row_num) { if (!sortColumnsEqualAt(current_chunk_sort_columns, current_row_num)) { previous_row_chunk = {}; break; } } length = current_row_num - start; } if (length == num_rows) return; auto columns = data.current_chunk.detachColumns(); for (UInt64 i = 0; i < num_columns; ++i) columns[i] = columns[i]->cut(start, length); data.current_chunk.setColumns(std::move(columns), length); } ColumnRawPtrs LimitTransform::extractSortColumns(const Columns & columns) const { ColumnRawPtrs res; res.reserve(description.size()); for (size_t pos : sort_column_positions) res.push_back(columns[pos].get()); return res; } bool LimitTransform::sortColumnsEqualAt(const ColumnRawPtrs & current_chunk_sort_columns, UInt64 current_chunk_row_num) const { assert(current_chunk_sort_columns.size() == previous_row_chunk.getNumColumns()); size_t size = current_chunk_sort_columns.size(); const auto & previous_row_sort_columns = previous_row_chunk.getColumns(); for (size_t i = 0; i < size; ++i) if (0 != current_chunk_sort_columns[i]->compareAt(current_chunk_row_num, 0, *previous_row_sort_columns[i], 1)) return false; return true; } }
#include "de_web_plugin.h" #include "de_web_plugin_private.h" #include "thermostat_ui_configuration.h" /*! Handle packets related to the ZCL Thermostat UI Configration cluster. \param ind the APS level data indication containing the ZCL packet \param zclFrame the actual ZCL frame which holds the Thermostat cluster command or attribute */ void DeRestPluginPrivate::handleThermostatUiConfigurationClusterIndication(const deCONZ::ApsDataIndication &ind, deCONZ::ZclFrame &zclFrame) { Sensor *sensor = getSensorNodeForAddressAndEndpoint(ind.srcAddress(), ind.srcEndpoint(), QLatin1String("ZHAThermostat")); if (!sensor) { DBG_Printf(DBG_INFO, "No thermostat sensor found for 0x%016llX, endpoint: 0x%02X\n", ind.srcAddress().ext(), ind.srcEndpoint()); return; } QDataStream stream(zclFrame.payload()); stream.setByteOrder(QDataStream::LittleEndian); bool isReadAttr = false; bool isReporting = false; if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReadAttributesResponseId) { isReadAttr = true; } if (zclFrame.isProfileWideCommand() && zclFrame.commandId() == deCONZ::ZclReportAttributesId) { isReporting = true; } // Read ZCL reporting and ZCL Read Attributes Response if (isReadAttr || isReporting) { const NodeValue::UpdateType updateType = isReadAttr ? NodeValue::UpdateByZclRead : NodeValue::UpdateByZclReport; bool configUpdated = false; bool stateUpdated = false; while (!stream.atEnd()) { quint16 attrId; quint8 attrTypeId; stream >> attrId; if (isReadAttr) { quint8 status; stream >> status; // Read Attribute Response status if (status != deCONZ::ZclSuccessStatus) { continue; } } stream >> attrTypeId; deCONZ::ZclAttribute attr(attrId, attrTypeId, QLatin1String(""), deCONZ::ZclRead, false); if (!attr.readFromStream(stream)) { continue; } ResourceItem *item = nullptr; switch (attrId) { case THERM_UI_ATTRID_KEYPAD_LOCKOUT: { bool locked = attr.numericValue().u8 > 0 ? true : false; item = sensor->item(RConfigLocked); if (item && item->toBool() != locked) { item->setValue(locked); enqueueEvent(Event(RSensors, RConfigLocked, sensor->id(), item)); configUpdated = true; } sensor->setZclValue(updateType, ind.srcEndpoint(), THERMOSTAT_UI_CONFIGURATION_CLUSTER_ID, attrId, attr.numericValue()); } break; case THERM_UI_ATTRID_VIEWING_DIRECTION: { if (sensor->modelId() == QLatin1String("eTRV0100") || sensor->modelId() == QLatin1String("TRV001") || sensor->modelId() == QLatin1String("eT093WRO")) { bool displayflipped = attr.numericValue().u8 > 0 ? true : false; item = sensor->item(RConfigDisplayFlipped); if (item && item->toBool() != displayflipped) { item->setValue(displayflipped); enqueueEvent(Event(RSensors, RConfigDisplayFlipped, sensor->id(), item)); configUpdated = true; } } sensor->setZclValue(updateType, ind.srcEndpoint(), THERMOSTAT_UI_CONFIGURATION_CLUSTER_ID, attrId, attr.numericValue()); } break; default: break; } } if (stateUpdated) { sensor->updateStateTimestamp(); enqueueEvent(Event(RSensors, RStateLastUpdated, sensor->id())); } if (configUpdated || stateUpdated) { updateSensorEtag(&*sensor); sensor->setNeedSaveDatabase(true); queSaveDb(DB_SENSORS, DB_SHORT_SAVE_DELAY); } } } /*! Write Attribute on thermostat ui configuration cluster. \param task - the task item \param attrId \param attrType \param attrValue \return true - on success false - on error */ bool DeRestPluginPrivate::addTaskThermostatUiConfigurationReadWriteAttribute(TaskItem &task, uint8_t readOrWriteCmd, uint16_t attrId, uint8_t attrType, uint32_t attrValue, uint16_t mfrCode) { if (readOrWriteCmd != deCONZ::ZclReadAttributesId && readOrWriteCmd != deCONZ::ZclWriteAttributesId) { DBG_Printf(DBG_INFO, "Thermostat invalid parameter readOrWriteCmd %d\n", readOrWriteCmd); return false; } task.taskType = TaskThermostat; task.req.setClusterId(THERMOSTAT_UI_CONFIGURATION_CLUSTER_ID); task.req.setProfileId(HA_PROFILE_ID); task.zclFrame.payload().clear(); task.zclFrame.setSequenceNumber(zclSeq++); task.zclFrame.setCommandId(readOrWriteCmd); task.zclFrame.setFrameControl(deCONZ::ZclFCProfileCommand | deCONZ::ZclFCDirectionClientToServer | deCONZ::ZclFCDisableDefaultResponse); if (mfrCode != 0x0000) { task.zclFrame.setFrameControl(task.zclFrame.frameControl() | deCONZ::ZclFCManufacturerSpecific); task.zclFrame.setManufacturerCode(mfrCode); } // payload QDataStream stream(&task.zclFrame.payload(), QIODevice::WriteOnly); stream.setByteOrder(QDataStream::LittleEndian); if (readOrWriteCmd == deCONZ::ZclWriteAttributesId) { stream << attrId; stream << attrType; deCONZ::ZclAttribute attr(attrId, attrType, QLatin1String(""), deCONZ::ZclWrite, true); attr.setValue(QVariant(attrValue)); if (!attr.writeToStream(stream)) { return false; } } { // ZCL frame task.req.asdu().clear(); // cleanup old request data if there is any QDataStream stream(&task.req.asdu(), QIODevice::WriteOnly); stream.setByteOrder(QDataStream::LittleEndian); task.zclFrame.writeToStream(stream); } return addTask(task); }
// Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved. // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR // COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. #include "sys.h" #include "error.h" #include "types.h" #include "gpu/mali/fp16/deconvolution_mali_fp16.h" #include "gpu/mali/fp16/deconvolution_direct_mali_fp16.h" inline EE deconv_direct_core_mali_fp16(GCLHandle_t handle, TensorDesc inputDesc, const GCLMem_t input, TensorDesc filterDesc, const GCLMem_t filter, ConvolutionParamSpec convParamSpec, ForwardRunInfoMali_t forwardRunInfo, TensorDesc biasDesc, const GCLMem_t bias, U32 tmpBytes, GCLMem_t tmpBuf, TensorDesc outputDesc, GCLMem_t output, ActivationMode activationMode) { UNUSED(biasDesc); UNUSED(tmpBytes); UNUSED(tmpBuf); cl_mem inbuf, biasmem, outbuf, fltbuf; inbuf = input->mem; fltbuf = filter->mem; biasmem = bias->mem; outbuf = output->mem; U32 iw, ih, ic; U32 fn, fw, fh, fc, sw, sh, pw, ph; U32 ow, oh, oc, on; sw = convParamSpec.stride_w; sh = convParamSpec.stride_h; ph = convParamSpec.padding_top; pw = convParamSpec.padding_left; tensorSelectGet(inputDesc, NULL, NULL, NULL, &ic, &ih, &iw); tensorSelectGet(filterDesc, NULL, NULL, &fn, &fc, &fh, &fw); tensorSelectGet(outputDesc, NULL, NULL, &on, &oc, &oh, &ow); U32 iw_str, ih_str, ihw_str, ic_str, iw_off, ih_off; ih_str = input->desc.stride[0]; iw_str = input->desc.stride[1]; ic_str = input->desc.stride[2]; ih_off = input->desc.offset[0]; iw_off = input->desc.offset[1]; ihw_str = ih_str * iw_str; U32 ow_str, oh_str, ohw_str, ow_off, oh_off; oh_str = output->desc.stride[0]; ow_str = output->desc.stride[1]; oh_off = output->desc.offset[0]; ow_off = output->desc.offset[1]; ohw_str = oh_str * ow_str; char kernelname[128]; U32 gs[3]; U32 ls[3] = {0, 0, 0}; U32 dim; Kernel kernel; // switch(activationMode) { // case ACTIVATION_RELU: // strcpy(modeName, "relu_"); // break; // case ACTIVATION_RELU6: // strcpy(modeName, "relu6_"); // break; // case ACTIVATION_NULL: // strcpy(modeName, ""); // break; // default: // return NOT_SUPPORTED; // } // if(item_k == 0) { // if((ih_str > 1 || iw_str > 1) && (item_c != 4)) CHECK_STATUS(NOT_SUPPORTED); // sprintf(kernelname, "conv_direct_spe_fwhs1_%s%d", modeName, item_c); // ic_str = filter->desc.stride[1]; // ow = fn; // gs[0] = fn; // gs[1] = 1; // gs[2] = 1; // dim = 1; // } else { // item_k = item_k >> 2; // sprintf(kernelname, "conv_direct_s%d_%s%d%d%d",sw, modeName, fw, item_w, item_k); sprintf(kernelname, "deconv_direct"); gs[0] = oh; gs[1] = ow; gs[2] = (oc + 3) / 4; dim = 3; // } U32 in_channel_blocks = (ic + 3) / 4; U32 out_channel_blocks = gs[2]; pw = fw - pw - 1; ph = fh - ph - 1; U32 align_h = sh - 1 - ph; U32 align_w = sw - 1 - pw; CHECK_STATUS(gcl_create_kernel(handle, kernelname, &kernel)); CHECK_STATUS(gcl_set_kernelArgs(kernel, inbuf, fltbuf, outbuf, biasmem, iw, iw_str, iw_off, ih, ih_str, ih_off, fw, fh, fc, fn, sw, sh, pw, ph, ow, ow_str, ow_off, oh, oh_str, oh_off, ic, oc, align_h, align_w, in_channel_blocks, out_channel_blocks)); gcl_set_kernelVec(handle, kernel, dim, gs, ls, kernelname); #ifdef _DEBUG CHECK_STATUS(gcl_run_kernel(handle, kernel, dim, gs, ls, kernelname)); CHECK_STATUS(gcl_print_memory<F16>(handle, input, "deconv_direct_input")); CHECK_STATUS(gcl_print_memory<F16>(handle, filter, "deconv_direct_filter")); CHECK_STATUS(gcl_print_memory<F16>(handle, bias, "deconv_direct_bias")); CHECK_STATUS(gcl_print_memory<F16>(handle, output, "deconv_direct_output")); handle->t_total += handle->t_execute; #endif return SUCCESS; } EE deconvolution_direct_transform_filter_bytes_mali_fp16(TensorDesc filterDesc, ForwardRunInfoMali_t forwardRunInfo, GCLMemDesc_t gclmemFilterDesc, U32 *bytes) { U32 fw, fh, fc, fn; tensorSelectGet(filterDesc, NULL, NULL, &fn, &fc, &fh, &fw); U32 item_c = forwardRunInfo->best_c[0]; U32 item_k = forwardRunInfo->best_k[0]; U32 s0 = 0; U32 s1 = 0; U32 s2 = 0; U32 num = 0; U32 byteSize; if (item_c == 4) { s0 = fw * fh; s1 = (fc + item_c - 1) / item_c; s2 = (fn + item_k - 1) / item_k; gclmemFilterDesc->memFormat = DF_NCHWN4C4; num = s0 * s1 * s2 * item_c * item_k; } else { CHECK_STATUS(NOT_MATCH); } byteSize = num * bytesOf(DT_F16); gclmemFilterDesc->stride[0] = s0; gclmemFilterDesc->stride[1] = s1; gclmemFilterDesc->stride[2] = s2; gclmemFilterDesc->offset[0] = 0; gclmemFilterDesc->offset[1] = 0; gclmemFilterDesc->offset[2] = 0; gclmemFilterDesc->num = num; gclmemFilterDesc->byteSize = byteSize; gclmemFilterDesc->memType = GCL_MEM_BUF; gclmemFilterDesc->flags = CL_MEM_READ_WRITE; gclmemFilterDesc->host_ptr = NULL; *bytes = 0; return SUCCESS; } EE deconvolution_direct_transform_filter_mali_fp16(GCLHandle_t handle, TensorDesc filterDesc, GCLMem_t filter, ForwardRunInfoMali_t forwardRunInfo, TensorDesc *fltmemDesc, GCLMem_t fltmem) { DataType fdt; DataFormat fdf; U32 fw, fh, fc, fn; tensorSelectGet(filterDesc, &fdt, &fdf, &fn, &fc, &fh, &fw); U32 fwh = fw * fh; U32 item_k = forwardRunInfo->best_k[0]; if (item_k != 4) { CHECK_STATUS(NOT_MATCH); } // if(item_k == 0) item_k = fn; char kernelname[128]; Kernel kernel; sprintf(kernelname, "deconv_direct_trans_fltbuf"); CHECK_STATUS(gcl_get_kernel_from_map(handle, kernelname, &kernel)); CHECK_STATUS(gcl_set_kernelArgs(kernel, fwh, fc, fn, filter->mem, fltmem->mem)); U32 gs[3] = {fwh, (fc + 3) / 4, (fn + 3) / 4 * 4}; U32 ls[3] = {0, 0, 0}; U32 dim = 3; CHECK_STATUS(gcl_run_kernel(handle, kernel, dim, gs, ls, kernelname)); *fltmemDesc = tensor4df(fdt, fdf, fn, fc, fh, fw); #ifdef _DEBUG CHECK_STATUS(gcl_print_memory<F16>(handle, filter, "deconv_direct_filter_org")); CHECK_STATUS(gcl_print_memory<F16>(handle, fltmem, "deconv_direct_filter_tran")); #endif return SUCCESS; } EE deconvolution_direct_infer_forward_tmp_bytes_mali_fp16(TensorDesc inputDesc, TensorDesc filterDesc, TensorDesc outputDesc, ConvolutionParamSpec convParamSpec, ForwardRunInfoMali_t forwardRunInfo, U32 *bytes) { UNUSED(inputDesc); UNUSED(filterDesc); UNUSED(outputDesc); UNUSED(convParamSpec); UNUSED(forwardRunInfo); *bytes = 0; return SUCCESS; } EE deconvolution_direct_mali_fp16(GCLHandle_t handle, TensorDesc inputDesc, const GCLMem_t input, TensorDesc filterDesc, const GCLMem_t filter, ConvolutionParamSpec convParamSpec, ForwardRunInfoMali_t forwardRunInfo, TensorDesc biasDesc, const GCLMem_t bias, U32 tmpBytes, GCLMem_t tmpBuf, TensorDesc outputDesc, GCLMem_t output, ActivationMode activationMode) { U32 fw, fh, ih, iw; tensorSelectGet(filterDesc, NULL, NULL, NULL, NULL, &fh, &fw); tensorSelectGet(inputDesc, NULL, NULL, NULL, NULL, &ih, &iw); CHECK_STATUS(fill_output_zero(handle, output, outputDesc)); if (inputDesc.df == DF_NCHW || (fw == 1 && fw == 1 && ih == 1 && iw == 1)) { CHECK_STATUS(deconv_direct_core_mali_fp16(handle, inputDesc, input, filterDesc, filter, convParamSpec, forwardRunInfo, biasDesc, bias, tmpBytes, tmpBuf, outputDesc, output, activationMode)); } else { CHECK_STATUS(NOT_SUPPORTED); } return SUCCESS; }
/*! * Copyright (c) 2018 by Contributors * Implementation of IR Node API * \file node.cc */ #include <tvm/node/node.h> #include <memory> #include <atomic> #include <mutex> #include <unordered_map> namespace tvm { namespace { // single manager of operator information. struct TypeManager { // mutex to avoid registration from multiple threads. // recursive is needed for trigger(which calls UpdateAttrMap) std::mutex mutex; std::atomic<uint32_t> type_counter{0}; std::unordered_map<std::string, uint32_t> key2index; std::vector<std::string> index2key; // get singleton of the static TypeManager* Global() { static TypeManager inst; return &inst; } }; } // namespace const bool Node::_DerivedFrom(uint32_t tid) const { static uint32_t tindex = TypeKey2Index(Node::_type_key); return tid == tindex; } // this is slow, usually caller always hold the result in a static variable. uint32_t Node::TypeKey2Index(const char* key) { TypeManager *t = TypeManager::Global(); std::lock_guard<std::mutex>(t->mutex); std::string skey = key; auto it = t->key2index.find(skey); if (it != t->key2index.end()) { return it->second; } uint32_t tid = ++(t->type_counter); t->key2index[skey] = tid; t->index2key.push_back(skey); return tid; } const char* Node::TypeIndex2Key(uint32_t index) { TypeManager *t = TypeManager::Global(); std::lock_guard<std::mutex>(t->mutex); internal_assert(index != 0); return t->index2key.at(index - 1).c_str(); } } // namespace tvm
//////////////////////////////////////////////////// // BSD 3-Clause License // // Copyright (C) 2020, University of Duisburg-Essen, // University of Edinburgh // Copyright note valid unless otherwise stated in // individual files. // All rights reserved. //////////////////////////////////////////////////// #include "crocoddyl/core/utils/exception.hpp" #include "crocoddyl/multibody/costs/impulse-cop-position.hpp" namespace crocoddyl { template <typename _Scalar> CostModelImpulseCoPPositionTpl<_Scalar>::CostModelImpulseCoPPositionTpl(boost::shared_ptr<StateMultibody> state, boost::shared_ptr<ActivationModelAbstract> activation, const FrameCoPSupport& cop_support) : Base(state, activation, 0), cop_support_(cop_support) {} template <typename _Scalar> CostModelImpulseCoPPositionTpl<_Scalar>::CostModelImpulseCoPPositionTpl(boost::shared_ptr<StateMultibody> state, const FrameCoPSupport& cop_support) : Base(state, boost::make_shared<ActivationModelQuadraticBarrier>(ActivationBounds(VectorXs::Zero(4), std::numeric_limits<_Scalar>::max() * VectorXs::Ones(4))), 0), cop_support_(cop_support) {} template <typename Scalar> CostModelImpulseCoPPositionTpl<Scalar>::~CostModelImpulseCoPPositionTpl() {} template <typename Scalar> void CostModelImpulseCoPPositionTpl<Scalar>::calc(const boost::shared_ptr<CostDataAbstract>& data, const Eigen::Ref<const VectorXs>&, const Eigen::Ref<const VectorXs>&) { Data* d = static_cast<Data*>(data.get()); // Compute the cost residual r = A * f data->r.noalias() = cop_support_.get_A() * d->impulse->jMf.actInv(d->impulse->f).toVector(); // Compute the cost activation_->calc(data->activation, data->r); data->cost = data->activation->a_value; } template <typename Scalar> void CostModelImpulseCoPPositionTpl<Scalar>::calcDiff(const boost::shared_ptr<CostDataAbstract>& data, const Eigen::Ref<const VectorXs>&, const Eigen::Ref<const VectorXs>&) { // Update all data Data* d = static_cast<Data*>(data.get()); // Get the derivatives of the local impulse wrench const MatrixXs& df_dx = d->impulse->df_dx; const Matrix46& A = cop_support_.get_A(); // Compute the derivatives of the activation function activation_->calcDiff(data->activation, data->r); // Compute the derivative of the cost residual data->Rx.noalias() = A * df_dx; // Compute the first order derivative of the cost function data->Lx.noalias() = data->Rx.transpose() * data->activation->Ar; // Compute the second order derivative of the cost function data->Lxx.noalias() = data->Rx.transpose() * data->activation->Arr * data->Rx; } template <typename Scalar> boost::shared_ptr<CostDataAbstractTpl<Scalar> > CostModelImpulseCoPPositionTpl<Scalar>::createData( DataCollectorAbstract* const data) { return boost::allocate_shared<Data>(Eigen::aligned_allocator<Data>(), this, data); } template <typename Scalar> void CostModelImpulseCoPPositionTpl<Scalar>::set_referenceImpl(const std::type_info& ti, const void* pv) { if (ti == typeid(FrameCoPSupport)) { cop_support_ = *static_cast<const FrameCoPSupport*>(pv); } else { throw_pretty("Invalid argument: incorrect type (it should be FrameCoPSupport)"); } } template <typename Scalar> void CostModelImpulseCoPPositionTpl<Scalar>::get_referenceImpl(const std::type_info& ti, void* pv) const { if (ti == typeid(FrameCoPSupport)) { FrameCoPSupport& ref_map = *static_cast<FrameCoPSupport*>(pv); ref_map = cop_support_; } else { throw_pretty("Invalid argument: incorrect type (it should be FrameCoPSupport)"); } } } // namespace crocoddyl
/* * Copyright (c) 2022 Salesforce, Inc. * All rights reserved. * SPDX-License-Identifier: BSD-3-Clause * For full license text, see the LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause */ #include "git_api.h" #include <cstring> #include <cstdlib> #include "git2.h" #include "git2/sys/repository.h" #include "minitrace.h" #include "utils/std_helpers.h" #define GIT2(x) \ do \ { \ int error = x; \ if (error < 0) \ { \ const git_error* e = git_error_last(); \ ERR("GitAPI: " << error << ":" << e->klass << ": " << e->message); \ exit(error); \ } \ } while (false) GitAPI::GitAPI(bool fsyncEnable) { git_libgit2_init(); GIT2(git_libgit2_opts(GIT_OPT_ENABLE_FSYNC_GITDIR, (int)fsyncEnable)); } GitAPI::~GitAPI() { if (m_Repo) { git_repository_free(m_Repo); m_Repo = nullptr; } git_libgit2_shutdown(); } bool GitAPI::IsRepositoryClonedFrom(const std::string& depotPath) { git_oid oid; GIT2(git_reference_name_to_id(&oid, m_Repo, "HEAD")); git_commit* headCommit = nullptr; GIT2(git_commit_lookup(&headCommit, m_Repo, &oid)); std::string message = git_commit_message(headCommit); size_t depotPathStart = message.find("depot-paths = \"") + 15; size_t depotPathEnd = message.find("\": change") - 1; std::string repoDepotPath = message.substr(depotPathStart, depotPathEnd - depotPathStart + 1) + "..."; git_commit_free(headCommit); return repoDepotPath == depotPath; } void GitAPI::OpenRepository(const std::string& repoPath) { GIT2(git_repository_open(&m_Repo, repoPath.c_str())); } bool GitAPI::InitializeRepository(const std::string& srcPath) { GIT2(git_repository_init(&m_Repo, srcPath.c_str(), true)); SUCCESS("Initialized Git repository at " << srcPath); return true; } bool GitAPI::IsHEADExists() { git_oid oid; int errorCode = git_reference_name_to_id(&oid, m_Repo, "HEAD"); if (errorCode && errorCode != GIT_ENOTFOUND) { GIT2(errorCode); } return errorCode == 0; } git_oid GitAPI::CreateBlob(const std::vector<char>& data) { git_oid oid; GIT2(git_blob_create_from_buffer(&oid, m_Repo, data.data(), data.size())); return oid; } std::string GitAPI::DetectLatestCL() { git_oid oid; GIT2(git_reference_name_to_id(&oid, m_Repo, "HEAD")); git_commit* headCommit = nullptr; GIT2(git_commit_lookup(&headCommit, m_Repo, &oid)); std::string message = git_commit_message(headCommit); size_t clStart = message.find_last_of("change = ") + 1; std::string cl(message.begin() + clStart, message.end() - 1); git_commit_free(headCommit); return cl; } void GitAPI::CreateIndex() { MTR_SCOPE("Git", __func__); GIT2(git_repository_index(&m_Index, m_Repo)); if (IsHEADExists()) { git_oid oid_parent_commit = {}; GIT2(git_reference_name_to_id(&oid_parent_commit, m_Repo, "HEAD")); git_commit* head_commit = nullptr; GIT2(git_commit_lookup(&head_commit, m_Repo, &oid_parent_commit)); git_tree* head_commit_tree = nullptr; GIT2(git_commit_tree(&head_commit_tree, head_commit)); GIT2(git_index_read_tree(m_Index, head_commit_tree)); git_tree_free(head_commit_tree); git_commit_free(head_commit); WARN("Loaded index was refreshed to match the tree of the current HEAD commit"); } else { WARN("No HEAD commit was found. Created a fresh index."); } } void GitAPI::AddFileToIndex(const std::string& depotPath, const std::string& depotFile, const std::vector<char>& contents, const bool plusx) { git_index_entry entry; memset(&entry, 0, sizeof(entry)); entry.mode = GIT_FILEMODE_BLOB; if (plusx) { entry.mode = GIT_FILEMODE_BLOB_EXECUTABLE; // 0100755 } std::string depotPathTrunc = depotPath.substr(0, depotPath.size() - 3); // -3 to remove trailing ... std::string gitFilePath = depotFile; STDHelpers::Erase(gitFilePath, depotPathTrunc); entry.path = gitFilePath.c_str(); GIT2(git_index_add_from_buffer(m_Index, &entry, contents.data(), contents.size())); } void GitAPI::RemoveFileFromIndex(const std::string& depotPath, const std::string& depotFile) { std::string depotPathTrunc = depotPath.substr(0, depotPath.size() - 3); // -3 to remove trailing ... std::string gitFilePath = depotFile; STDHelpers::Erase(gitFilePath, depotPathTrunc); GIT2(git_index_remove_bypath(m_Index, gitFilePath.c_str())); } std::string GitAPI::Commit( const std::string& depotPath, const std::string& cl, const std::string& user, const std::string& email, const int& timezone, const std::string& desc, const int64_t& timestamp) { MTR_SCOPE("Git", __func__); git_oid commitTreeID; GIT2(git_index_write_tree_to(&commitTreeID, m_Index, m_Repo)); git_tree* commitTree = nullptr; GIT2(git_tree_lookup(&commitTree, m_Repo, &commitTreeID)); git_signature* author = nullptr; GIT2(git_signature_new(&author, user.c_str(), email.c_str(), timestamp, timezone)); git_reference* ref = nullptr; git_object* parent = nullptr; { int error = git_revparse_ext(&parent, &ref, m_Repo, "HEAD"); if (error == GIT_ENOTFOUND) { WARN("GitAPI: HEAD not found. Creating first commit"); } } git_oid commitID; // -3 to remove the trailing "..." std::string commitMsg = cl + " - " + desc + "\n[p4-fusion: depot-paths = \"" + depotPath.substr(0, depotPath.size() - 3) + "\": change = " + cl + "]"; GIT2(git_commit_create_v(&commitID, m_Repo, "HEAD", author, author, "UTF-8", commitMsg.c_str(), commitTree, parent ? 1 : 0, parent)); git_object_free(parent); git_reference_free(ref); git_signature_free(author); git_tree_free(commitTree); return git_oid_tostr_s(&commitID); } void GitAPI::CloseIndex() { GIT2(git_index_write(m_Index)); git_index_free(m_Index); }
// Copyright (C) 2016-2017 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library 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 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License along // with this library; see the file COPYING3. If not see // <http://www.gnu.org/licenses/>. // { dg-options "-std=gnu++17" } #include <unordered_map> #include <algorithm> #include <testsuite_hooks.h> using test_type = std::unordered_map<int, int>; struct hash { auto operator()(int i) const noexcept { return ~std::hash<int>()(i); } }; struct equal : std::equal_to<> { }; template<typename C1, typename C2> bool equal_elements(const C1& c1, const C2& c2) { if (c2.size() != c1.size()) return false; for (auto& i : c1) if (c2.count(i.first) != c1.count(i.first)) return false; return true; } void test01() { const test_type c0{ {1, 10}, {2, 20}, {3, 30} }; test_type c1 = c0, c2 = c0; c1.merge(c2); VERIFY( c1 == c0 ); VERIFY( c2 == c0 ); c1.clear(); c1.merge(c2); VERIFY( c1 == c0 ); VERIFY( c2.empty() ); c2.merge(std::move(c1)); VERIFY( c1.empty() ); VERIFY( c2 == c0 ); } void test02() { const test_type c0{ {1, 10}, {2, 20}, {3, 30} }; test_type c1 = c0; std::unordered_map<int, int, hash, equal> c2( c0.begin(), c0.end() ); c1.merge(c2); VERIFY( c1 == c0 ); VERIFY( equal_elements(c2, c0) ); c1.clear(); c1.merge(c2); VERIFY( c1 == c0 ); VERIFY( c2.empty() ); c2.merge(c1); VERIFY( c1.empty() ); VERIFY( equal_elements(c2, c0) ); c1.merge(std::move(c2)); VERIFY( c2.empty() ); VERIFY( c1 == c0 ); } void test03() { const test_type c0{ {1, 10}, {2, 20}, {3, 30} }; test_type c1 = c0; std::unordered_multimap<int, int, hash, equal> c2( c0.begin(), c0.end() ); c1.merge(c2); VERIFY( c1 == c0 ); VERIFY( equal_elements(c2, c0) ); c1.clear(); c1.merge(c2); VERIFY( c1 == c0 ); VERIFY( c2.empty() ); c2.merge(c1); VERIFY( c1.empty() ); VERIFY( equal_elements(c2, c0) ); c1 = c0; c2.merge(c1); VERIFY( c1.empty() ); VERIFY( c2.size() == (2 * c0.size()) ); VERIFY( c2.count(1) == 2 ); VERIFY( c2.count(2) == 2 ); VERIFY( c2.count(3) == 2 ); c1.merge(c2); VERIFY( c1 == c0 ); VERIFY( equal_elements(c2, c0) ); c1.merge(std::move(c2)); VERIFY( c1 == c0 ); VERIFY( equal_elements(c2, c0) ); c1.clear(); c1.merge(std::move(c2)); VERIFY( c1 == c0 ); VERIFY( c2.empty() ); } int main() { test01(); test02(); test03(); }
/* * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com> * * SPDX-License-Identifier: BSD-2-Clause */ #include "FileDB.h" #include <AK/LexicalPath.h> #include <AK/NonnullRefPtr.h> #include <LibCore/File.h> namespace LanguageServers { RefPtr<const GUI::TextDocument> FileDB::get_document(String const& filename) const { auto absolute_path = to_absolute_path(filename); auto document_optional = m_open_files.get(absolute_path); if (!document_optional.has_value()) return nullptr; return *document_optional.value(); } RefPtr<GUI::TextDocument> FileDB::get_document(String const& filename) { auto document = reinterpret_cast<FileDB const*>(this)->get_document(filename); if (document.is_null()) return nullptr; return adopt_ref(*const_cast<GUI::TextDocument*>(document.leak_ref())); } Optional<String> FileDB::get_or_read_from_filesystem(StringView filename) const { auto absolute_path = to_absolute_path(filename); auto document = get_document(absolute_path); if (document) return document->text(); document = create_from_filesystem(absolute_path); if (document) return document->text(); return {}; } bool FileDB::is_open(String const& filename) const { return m_open_files.contains(to_absolute_path(filename)); } bool FileDB::add(String const& filename, int fd) { auto document = create_from_fd(fd); if (!document) return false; m_open_files.set(to_absolute_path(filename), document.release_nonnull()); return true; } String FileDB::to_absolute_path(String const& filename) const { if (LexicalPath { filename }.is_absolute()) { return filename; } if (m_project_root.is_null()) return filename; return LexicalPath { String::formatted("{}/{}", m_project_root, filename) }.string(); } RefPtr<GUI::TextDocument> FileDB::create_from_filesystem(String const& filename) const { auto file = Core::File::open(to_absolute_path(filename), Core::OpenMode::ReadOnly); if (file.is_error()) { dbgln("failed to create document for {} from filesystem", filename); return nullptr; } return create_from_file(*file.value()); } RefPtr<GUI::TextDocument> FileDB::create_from_fd(int fd) const { auto file = Core::File::construct(); if (!file->open(fd, Core::OpenMode::ReadOnly, Core::File::ShouldCloseFileDescriptor::Yes)) { errno = file->error(); perror("open"); dbgln("Failed to open project file"); return nullptr; } return create_from_file(*file); } class DefaultDocumentClient final : public GUI::TextDocument::Client { public: virtual ~DefaultDocumentClient() override = default; virtual void document_did_append_line() override {}; virtual void document_did_insert_line(size_t) override {}; virtual void document_did_remove_line(size_t) override {}; virtual void document_did_remove_all_lines() override {}; virtual void document_did_change(GUI::AllowCallback) override {}; virtual void document_did_set_text(GUI::AllowCallback) override {}; virtual void document_did_set_cursor(const GUI::TextPosition&) override {}; virtual void document_did_update_undo_stack() override { } virtual bool is_automatic_indentation_enabled() const override { return false; } virtual int soft_tab_width() const override { return 4; } }; static DefaultDocumentClient s_default_document_client; RefPtr<GUI::TextDocument> FileDB::create_from_file(Core::File& file) const { auto content = file.read_all(); StringView content_view(content); auto document = GUI::TextDocument::create(&s_default_document_client); document->set_text(content_view); return document; } void FileDB::on_file_edit_insert_text(String const& filename, String const& inserted_text, size_t start_line, size_t start_column) { VERIFY(is_open(filename)); auto document = get_document(filename); VERIFY(document); GUI::TextPosition start_position { start_line, start_column }; document->insert_at(start_position, inserted_text, &s_default_document_client); dbgln_if(FILE_CONTENT_DEBUG, "{}", document->text()); } void FileDB::on_file_edit_remove_text(String const& filename, size_t start_line, size_t start_column, size_t end_line, size_t end_column) { // TODO: If file is not open - need to get its contents // Otherwise- somehow verify that respawned language server is synced with all file contents VERIFY(is_open(filename)); auto document = get_document(filename); VERIFY(document); GUI::TextPosition start_position { start_line, start_column }; GUI::TextRange range { GUI::TextPosition { start_line, start_column }, GUI::TextPosition { end_line, end_column } }; document->remove(range); dbgln_if(FILE_CONTENT_DEBUG, "{}", document->text()); } RefPtr<GUI::TextDocument> FileDB::create_with_content(String const& content) { StringView content_view(content); auto document = GUI::TextDocument::create(&s_default_document_client); document->set_text(content_view); return document; } bool FileDB::add(String const& filename, String const& content) { auto document = create_with_content(content); if (!document) { VERIFY_NOT_REACHED(); return false; } m_open_files.set(to_absolute_path(filename), document.release_nonnull()); return true; } }
/* Copyright 2012-present Facebook, Inc. * Licensed under the Apache License, Version 2.0 */ #include "make_unique.h" #include "watchman.h" #include "InMemoryView.h" #ifdef HAVE_PORT_CREATE #define WATCHMAN_PORT_EVENTS \ FILE_MODIFIED | FILE_ATTRIB | FILE_NOFOLLOW struct watchman_port_file { file_obj_t port_file; w_string name; }; struct PortFSWatcher : public Watcher { FileDescriptor port_fd; /* map of file name to watchman_port_file */ watchman::Synchronized< std::unordered_map<w_string, std::unique_ptr<watchman_port_file>>> port_files; port_event_t portevents[WATCHMAN_BATCH_LIMIT]; explicit PortFSWatcher(w_root_t* root); std::unique_ptr<watchman_dir_handle> startWatchDir( w_root_t* root, struct watchman_dir* dir, struct timeval now, const char* path) override; bool startWatchFile(struct watchman_file* file) override; bool consumeNotify(w_root_t* root, struct watchman_pending_collection* coll) override; bool waitNotify(int timeoutms) override; void do_watch(w_string_t* name, struct stat* st); }; static const struct flag_map pflags[] = { {FILE_ACCESS, "FILE_ACCESS"}, {FILE_MODIFIED, "FILE_MODIFIED"}, {FILE_ATTRIB, "FILE_ATTRIB"}, {FILE_DELETE, "FILE_DELETE"}, {FILE_RENAME_TO, "FILE_RENAME_TO"}, {FILE_RENAME_FROM, "FILE_RENAME_FROM"}, {UNMOUNTED, "UNMOUNTED"}, {MOUNTEDOVER, "MOUNTEDOVER"}, {0, nullptr}, }; static std::unique_ptr<watchman_port_file> make_port_file( const w_string& name, struct stat* st) { auto f = watchman::make_unique<watchman_port_file>(); f->name = name; f->port_file.fo_name = (char*)name->buf; f->port_file.fo_atime = st->st_atim; f->port_file.fo_mtime = st->st_mtim; f->port_file.fo_ctime = st->st_ctim; return f; } PortFSWatcher::PortFSWatcher(w_root_t* root) : Watcher("portfs", 0), port_fd(port_create(), "port_create()") { port_files.reserve(root->config.getInt(CFG_HINT_NUM_DIRS, HINT_NUM_DIRS)); port_fd.setCloExec(); } void PortFSWatcher::do_watch(w_string_t* name, struct stat* st) { auto wlock = port_files.wlock(); if (port_files.find(name) != port_files.end()) { // Already watching it return; } auto f = make_port_file(name, st); auto rawFile = f.get(); wlock->emplace(name, std::move(f)); w_log(W_LOG_DBG, "watching %s\n", name->buf); errno = 0; if (port_associate( port_fd.fd(), PORT_SOURCE_FILE, (uintptr_t)&rawFile->port_file, WATCHMAN_PORT_EVENTS, (void*)rawFile)) { int err = errno; w_log( W_LOG_ERR, "port_associate %s %s\n", rawFile->port_file.fo_name, strerror(errno)); wlock->erase(name); throw std::system_error(err, std::generic_category(), "port_associate"); } } bool PortFSWatcher::startWatchFile(struct watchman_file* file) { w_string_t *name; bool success = false; name = w_string_path_cat(file->parent->path, file->name); if (!name) { return false; } do_watch(name, &file->st); w_string_delref(name); return success; } std::unique_ptr<watchman_dir_handle> PortFSWatcher::startWatchDir( w_root_t* root, struct watchman_dir* dir, struct timeval now, const char* path) { struct stat st; auto osdir = w_dir_open(path); if (fstat(dirfd(osdir), &st) == -1) { // whaaa? root->scheduleRecrawl("fstat failed"); throw std::system_error( errno, std::generic_category(), std::string("fstat failed for dir ") + path); } auto dir_name = dir->getFullPath(); do_watch(dir_name, &st); return osdir; } bool PortFSWatcher::consumeNotify( w_root_t* root, struct watchman_pending_collection* coll) { uint_t i, n; struct timeval now; errno = 0; n = 1; if (port_getn( port_fd.fd(), portevents, sizeof(portevents) / sizeof(portevents[0]), &n, nullptr)) { if (errno == EINTR) { return false; } w_log(W_LOG_FATAL, "port_getn: %s\n", strerror(errno)); } w_log(W_LOG_DBG, "port_getn: n=%u\n", n); if (n == 0) { return false; } auto wlock = port_files.wlock(); for (i = 0; i < n; i++) { struct watchman_port_file *f; uint32_t pe = portevents[i].portev_events; char flags_label[128]; f = (struct watchman_port_file*)portevents[i].portev_user; w_expand_flags(pflags, pe, flags_label, sizeof(flags_label)); w_log(W_LOG_DBG, "port: %s [0x%x %s]\n", f->port_file.fo_name, pe, flags_label); if ((pe & (FILE_RENAME_FROM|UNMOUNTED|MOUNTEDOVER|FILE_DELETE)) && w_string_equal(f->name, root->root_path)) { w_log( W_LOG_ERR, "root dir %s has been (re)moved (code 0x%x %s), canceling watch\n", root->root_path.c_str(), pe, flags_label); root->cancel(); return false; } w_pending_coll_add(coll, f->name, now, W_PENDING_RECURSIVE|W_PENDING_VIA_NOTIFY); // It was port_dissociate'd implicitly. We'll re-establish a // watch later when portfs_root_start_watch_(file|dir) are called again wlock->erase(f->name); } return true; } bool PortFSWatcher::waitNotify(int timeoutms) { int n; struct pollfd pfd; pfd.fd = port_fd.fd(); pfd.events = POLLIN; n = poll(&pfd, 1, timeoutms); return n == 1; } static RegisterWatcher<PortFSWatcher> reg( "portfs", 1 /* higher priority than inotify */); #endif // HAVE_PORT_CREATE /* vim:ts=2:sw=2:et: */
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE401_Memory_Leak__strdup_char_83_bad.cpp Label Definition File: CWE401_Memory_Leak__strdup.label.xml Template File: sources-sinks-83_bad.tmpl.cpp */ /* * @description * CWE: 401 Memory Leak * BadSource: Allocate data using strdup() * GoodSource: Allocate data on the stack * Sinks: * GoodSink: call free() on data * BadSink : no deallocation of data * Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack * * */ #ifndef OMITBAD #include "std_testcase.h" #include "CWE401_Memory_Leak__strdup_char_83.h" namespace CWE401_Memory_Leak__strdup_char_83 { CWE401_Memory_Leak__strdup_char_83_bad::CWE401_Memory_Leak__strdup_char_83_bad(char * dataCopy) { data = dataCopy; { char myString[] = "myString"; /* POTENTIAL FLAW: Allocate memory from the heap using a function that requires free() for deallocation */ data = strdup(myString); /* Use data */ printLine(data); } } CWE401_Memory_Leak__strdup_char_83_bad::~CWE401_Memory_Leak__strdup_char_83_bad() { /* POTENTIAL FLAW: No deallocation of memory */ /* no deallocation */ ; /* empty statement needed for some flow variants */ } } #endif /* OMITBAD */
#include <Common/escapeForFileName.h> #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-compare" #include <gtest/gtest.h> #pragma GCC diagnostic pop using namespace DB; TEST(Common, unescapeForFileName) { EXPECT_EQ(unescapeForFileName(escapeForFileName("172.19.0.6")), "172.19.0.6"); EXPECT_EQ(unescapeForFileName(escapeForFileName("abcd.")), "abcd."); EXPECT_EQ(unescapeForFileName(escapeForFileName("abcd")), "abcd"); EXPECT_EQ(unescapeForFileName(escapeForFileName("..::")), "..::"); }
/****************************************************************************** Copyright (c) 2017, Farbod Farshidian. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ #include "ocs2_ddp/DDP_HelperFunctions.h" #include <algorithm> #include <iostream> #include <ocs2_core/PreComputation.h> #include <ocs2_core/integration/TrapezoidalIntegration.h> #include <ocs2_oc/approximate_model/LinearQuadraticApproximator.h> #include <ocs2_oc/oc_data/Metrics.h> namespace ocs2 { /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ void computeRolloutMetrics(OptimalControlProblem& problem, const PrimalSolution& primalSolution, MetricsCollection& metrics) { const auto& tTrajectory = primalSolution.timeTrajectory_; const auto& xTrajectory = primalSolution.stateTrajectory_; const auto& uTrajectory = primalSolution.inputTrajectory_; const auto& postEventIndices = primalSolution.postEventIndices_; clear(metrics); metrics.preJumps.reserve(postEventIndices.size()); metrics.intermediates.reserve(tTrajectory.size()); auto nextPostEventIndexItr = postEventIndices.begin(); const auto request = Request::Cost + Request::Constraint + Request::SoftConstraint; for (size_t k = 0; k < tTrajectory.size(); k++) { // intermediate time cost and constraints problem.preComputationPtr->request(request, tTrajectory[k], xTrajectory[k], uTrajectory[k]); metrics.intermediates.push_back(computeIntermediateMetrics(problem, tTrajectory[k], xTrajectory[k], uTrajectory[k])); // event time cost and constraints if (nextPostEventIndexItr != postEventIndices.end() && k + 1 == *nextPostEventIndexItr) { problem.preComputationPtr->requestPreJump(request, tTrajectory[k], xTrajectory[k]); metrics.preJumps.push_back(computePreJumpMetrics(problem, tTrajectory[k], xTrajectory[k])); nextPostEventIndexItr++; } } // final time cost and constraints if (!tTrajectory.empty()) { problem.preComputationPtr->requestFinal(request, tTrajectory.back(), xTrajectory.back()); metrics.final = computeFinalMetrics(problem, tTrajectory.back(), xTrajectory.back()); } } /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ PerformanceIndex computeRolloutPerformanceIndex(const scalar_array_t& timeTrajectory, const MetricsCollection& metrics) { assert(timeTrajectory.size() == metrics.intermediates.size()); PerformanceIndex performanceIndex; // Total cost: // - Final: state cost, state soft-constraints // - PreJumps: state cost, state soft-constraints // - Intermediates: state/state-input cost, state/state-input soft-constraints performanceIndex.cost = metrics.final.cost; std::for_each(metrics.preJumps.begin(), metrics.preJumps.end(), [&](const Metrics& m) { return performanceIndex.cost + m.cost; }); scalar_array_t costTrajectory(timeTrajectory.size()); std::transform(metrics.intermediates.begin(), metrics.intermediates.end(), costTrajectory.begin(), [](const Metrics& m) { return m.cost; }); performanceIndex.cost += trapezoidalIntegration(timeTrajectory, costTrajectory); // Dynamics violation: performanceIndex.dynamicsViolationSSE = 0.0; // Equality constraints' SSE: // - Final: state equality constraints // - PreJumps: state equality constraints // - Intermediates: state/state-input equality constraints performanceIndex.equalityConstraintsSSE = metrics.final.stateEqConstraint.squaredNorm(); std::for_each(metrics.preJumps.begin(), metrics.preJumps.end(), [&](const Metrics& m) { return performanceIndex.equalityConstraintsSSE + m.stateEqConstraint.squaredNorm(); }); scalar_array_t equalityNorm2Trajectory(timeTrajectory.size()); std::transform(metrics.intermediates.begin(), metrics.intermediates.end(), equalityNorm2Trajectory.begin(), [](const Metrics& m) { return m.stateEqConstraint.squaredNorm() + m.stateInputEqConstraint.squaredNorm(); }); performanceIndex.equalityConstraintsSSE += trapezoidalIntegration(timeTrajectory, equalityNorm2Trajectory); // Equality Lagrangians penalty // - Final: state equality Lagrangians // - PreJumps: state equality Lagrangians // - Intermediates: state/state-input equality Lagrangians performanceIndex.equalityLagrangian = metrics.final.stateEqLagrangian; std::for_each(metrics.preJumps.begin(), metrics.preJumps.end(), [&](const Metrics& m) { return performanceIndex.equalityLagrangian + m.stateEqLagrangian; }); scalar_array_t equalityPenaltyTrajectory(timeTrajectory.size()); std::transform(metrics.intermediates.begin(), metrics.intermediates.end(), equalityPenaltyTrajectory.begin(), [&](const Metrics& m) { return m.stateEqLagrangian + m.stateInputEqLagrangian; }); performanceIndex.equalityLagrangian += trapezoidalIntegration(timeTrajectory, equalityPenaltyTrajectory); // Inequality Lagrangians penalty // - Final: state inequality Lagrangians // - PreJumps: state inequality Lagrangians // - Intermediates: state/state-input inequality Lagrangians performanceIndex.inequalityLagrangian = metrics.final.stateIneqLagrangian; std::for_each(metrics.preJumps.begin(), metrics.preJumps.end(), [&](const Metrics& m) { return performanceIndex.inequalityLagrangian + m.stateIneqLagrangian; }); scalar_array_t inequalityPenaltyTrajectory(timeTrajectory.size()); std::transform(metrics.intermediates.begin(), metrics.intermediates.end(), inequalityPenaltyTrajectory.begin(), [&](const Metrics& m) { return m.stateIneqLagrangian + m.stateInputIneqLagrangian; }); performanceIndex.inequalityLagrangian += trapezoidalIntegration(timeTrajectory, inequalityPenaltyTrajectory); return performanceIndex; } /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ scalar_t rolloutTrajectory(RolloutBase& rollout, scalar_t initTime, const vector_t& initState, scalar_t finalTime, PrimalSolution& primalSolution) { // rollout with controller const auto xCurrent = rollout.run(initTime, initState, finalTime, primalSolution.controllerPtr_.get(), primalSolution.modeSchedule_, primalSolution.timeTrajectory_, primalSolution.postEventIndices_, primalSolution.stateTrajectory_, primalSolution.inputTrajectory_); if (!xCurrent.allFinite()) { throw std::runtime_error("[rolloutTrajectory] System became unstable during the rollout!"); } // average time step return (finalTime - initTime) / static_cast<scalar_t>(primalSolution.timeTrajectory_.size()); } /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ scalar_t computeControllerUpdateIS(const LinearController& controller) { scalar_array_t biasArraySquaredNorm(controller.timeStamp_.size()); std::transform(controller.deltaBiasArray_.begin(), controller.deltaBiasArray_.end(), biasArraySquaredNorm.begin(), [](const vector_t& b) { return b.squaredNorm(); }); // integrates using the trapezoidal approximation method return trapezoidalIntegration(controller.timeStamp_, biasArraySquaredNorm); } /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ void incrementController(scalar_t stepLength, const LinearController& unoptimizedController, LinearController& controller) { controller.clear(); controller.timeStamp_ = unoptimizedController.timeStamp_; controller.gainArray_ = unoptimizedController.gainArray_; controller.biasArray_.resize(unoptimizedController.size()); for (size_t k = 0; k < unoptimizedController.size(); k++) { controller.biasArray_[k] = unoptimizedController.biasArray_[k] + stepLength * unoptimizedController.deltaBiasArray_[k]; } } /******************************************************************************************************/ /******************************************************************************************************/ /******************************************************************************************************/ void retrieveActiveNormalizedTime(const std::pair<int, int>& partitionInterval, const scalar_array_t& timeTrajectory, const size_array_t& postEventIndices, scalar_array_t& normalizedTimeTrajectory, size_array_t& normalizedPostEventIndices) { // Although the rightmost point is excluded from the current interval, i.e. it won't be written into the dual solution array, we still // the following two (+1) are essential to start the backward pass auto firstTimeItr = timeTrajectory.begin() + partitionInterval.first; auto lastTimeItr = timeTrajectory.begin() + partitionInterval.second + 1; const int N = partitionInterval.second - partitionInterval.first + 1; // normalized time normalizedTimeTrajectory.resize(N); std::transform(firstTimeItr, lastTimeItr, normalizedTimeTrajectory.rbegin(), [](scalar_t t) -> scalar_t { return -t; }); auto firstEventItr = std::upper_bound(postEventIndices.begin(), postEventIndices.end(), partitionInterval.first); auto lastEventItr = std::upper_bound(postEventIndices.begin(), postEventIndices.end(), partitionInterval.second); const int NE = std::distance(firstEventItr, lastEventItr); // normalized event past the index normalizedPostEventIndices.resize(NE); std::transform(firstEventItr, lastEventItr, normalizedPostEventIndices.rbegin(), [N, &partitionInterval](size_t i) -> size_t { return N - i + partitionInterval.first; }); } } // namespace ocs2
#include "knn.h" extern "C"{ void workload( float inputQuery[NUM_FEATURE], float searchSpace[NUM_PT_IN_SEARCHSPACE*NUM_FEATURE], float distance[NUM_PT_IN_SEARCHSPACE] ){ #pragma HLS INTERFACE m_axi port=inputQuery offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=inputQuery bundle=control #pragma HLS INTERFACE m_axi port=searchSpace offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=searchSpace bundle=control #pragma HLS INTERFACE m_axi port=distance offset=slave bundle=gmem #pragma HLS INTERFACE s_axilite port=distance bundle=control #pragma HLS INTERFACE s_axilite port=return bundle=control float sum; float feature_delta; for(int i = 0; i < NUM_PT_IN_SEARCHSPACE; ++i){ sum = 0.0; for(int j = 0; j < NUM_FEATURE; ++j){ feature_delta = searchSpace[i*NUM_FEATURE+j] - inputQuery[j]; sum += feature_delta*feature_delta; } distance[i] = sum; } return; } }
#include "global.h" #include "PumpDevice.h" void PumpDevice::Open() { AddElementToQueue( IOHIDElementCookie(2) ); AddElementToQueue( IOHIDElementCookie(3) ); AddElementToQueue( IOHIDElementCookie(4) ); AddElementToQueue( IOHIDElementCookie(6) ); AddElementToQueue( IOHIDElementCookie(7) ); AddElementToQueue( IOHIDElementCookie(8) ); } void PumpDevice::GetButtonPresses( vector<DeviceInput>& vPresses, IOHIDElementCookie cookie, int value, const RageTimer& now ) const { DeviceButton db1 = DeviceButton_Invalid; DeviceButton db2 = DeviceButton_Invalid; bool pressed1 = !(value & 0x1); bool pressed2 = !(value & 0x2); switch( uintptr_t(cookie) ) { case 2: db2 = JOY_BUTTON_1; // bit 9 break; case 3: db1 = JOY_BUTTON_5; // bit 10 db2 = JOY_BUTTON_4; // bit 11 break; case 4: db1 = JOY_BUTTON_2; // bit 12 db2 = JOY_BUTTON_3; // bit 13 break; case 6: db1 = JOY_BUTTON_6; // bit 16 db2 = JOY_BUTTON_7; // bit 17 break; case 7: db1 = JOY_BUTTON_11; // bit 18 db2 = JOY_BUTTON_10; // bit 19 break; case 8: db1 = JOY_BUTTON_8; // bit 20 db2 = JOY_BUTTON_9; // bit 21 break; } if( db1 != DeviceButton_Invalid ) vPresses.push_back( DeviceInput(m_Id, db1, pressed1 ? 1.0f : 0.0f , now) ); if( db2 != DeviceButton_Invalid ) vPresses.push_back( DeviceInput(m_Id, db2, pressed2 ? 1.0f : 0.0f , now) ); } int PumpDevice::AssignIDs( InputDevice startID ) { if( !IsPump(startID) ) return -1; m_Id = startID; return 1; } void PumpDevice::GetDevicesAndDescriptions( vector<InputDeviceInfo>& vDevices ) const { vDevices.push_back( InputDeviceInfo(m_Id, "Pump USB") ); } /* * (c) 2006 Steve Checkoway * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, and/or sell copies of the Software, and to permit persons to * whom the Software is furnished to do so, provided that the above * copyright notice(s) and this permission notice appear in all copies of * the Software and that both the above copyright notice(s) and this * permission notice appear in supporting documentation. * * 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 OF * THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS * INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR * OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */
#include <stdio.h> #include <stdlib.h> #include <string.h> main(){ int idade; char nome[20]; printf("Digite a sua idade: "); scanf("%i", &idade); fflush(stdin); //limpa o buffer printf("Digite seu nome:"); gets(nome); printf("%s", nome); }