text
stringlengths 54
60.6k
|
|---|
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: urltransformer.cxx,v $
*
* $Revision: 1.15 $
*
* last change: $Author: rt $ $Date: 2007-04-03 13:50:24 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#ifndef __FRAMEWORK_SERVICES_URLTRANSFORMER_HXX_
#include <services/urltransformer.hxx>
#endif
#ifndef __FRAMEWORK_THREADHELP_RESETABLEGUARD_HXX_
#include <threadhelp/resetableguard.hxx>
#endif
#ifndef __FRAMEWORK_MACROS_DEBUG_HXX_
#include <macros/debug.hxx>
#endif
#ifndef __FRAMEWORK_SERVICES_H_
#include <services.h>
#endif
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#ifndef _URLOBJ_HXX
#include <tools/urlobj.hxx>
#endif
#ifndef _RTL_USTRBUF_HXX_
#include <rtl/ustrbuf.hxx>
#endif
#ifndef _SV_SVAPP_HXX
#include <vcl/svapp.hxx>
#endif
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
using namespace ::osl ;
using namespace ::rtl ;
using namespace ::cppu ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::util ;
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// non exported definitions
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
URLTransformer::URLTransformer( const Reference< XMultiServiceFactory >& xFactory )
// Init baseclasses first
// Attention:
// Don't change order of initialization!
// ThreadHelpBase is a struct with a mutex as member. We can't use a mutex as member, while
// we must garant right initialization and a valid value of this! First initialize
// baseclasses and then members. And we need the mutex for other baseclasses !!!
: ThreadHelpBase ( &Application::GetSolarMutex() )
, OWeakObject ( )
// Init member
, m_xFactory ( xFactory )
{
// Safe impossible cases.
// Method not defined for all incoming parameter.
LOG_ASSERT( xFactory.is(), "URLTransformer::URLTransformer()\nInvalid parameter detected!\n" )
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
URLTransformer::~URLTransformer()
{
}
//*****************************************************************************************************************
// XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XINTERFACE_3 ( URLTransformer ,
OWeakObject ,
DIRECT_INTERFACE(XTypeProvider ),
DIRECT_INTERFACE(XServiceInfo ),
DIRECT_INTERFACE(XURLTransformer )
)
DEFINE_XTYPEPROVIDER_3 ( URLTransformer ,
XTypeProvider ,
XServiceInfo ,
XURLTransformer
)
DEFINE_XSERVICEINFO_MULTISERVICE ( URLTransformer ,
OWeakObject ,
SERVICENAME_URLTRANSFORMER ,
IMPLEMENTATIONNAME_URLTRANSFORMER
)
DEFINE_INIT_SERVICE ( URLTransformer,
{
}
)
//*****************************************************************************************************************
// XURLTransformer
//*****************************************************************************************************************
sal_Bool SAL_CALL URLTransformer::parseStrict( URL& aURL ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases.
if (( &aURL == NULL ) ||
( aURL.Complete.getLength() < 1 ) )
{
return sal_False;
}
// Try to extract the protocol
sal_Int32 nURLIndex = aURL.Complete.indexOf( sal_Unicode( ':' ));
OUString aProtocol;
if ( nURLIndex > 1 )
{
aProtocol = aURL.Complete.copy( 0, nURLIndex+1 );
// If INetURLObject knows this protocol let it parse
if ( INetURLObject::CompareProtocolScheme( aProtocol ) != INET_PROT_NOT_VALID )
{
// Initialize parser with given URL.
INetURLObject aParser( aURL.Complete );
// Get all information about this URL.
INetProtocol eINetProt = aParser.GetProtocol();
if ( eINetProt == INET_PROT_NOT_VALID )
{
return sal_False;
}
else if ( !aParser.HasError() )
{
aURL.Protocol = INetURLObject::GetScheme( aParser.GetProtocol() );
aURL.User = aParser.GetUser ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Password = aParser.GetPass ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Server = aParser.GetHost ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Port = (sal_Int16)aParser.GetPort();
sal_Int32 nCount = aParser.getSegmentCount( false );
if ( nCount > 0 )
{
// Don't add last segment as it is the name!
--nCount;
rtl::OUStringBuffer aPath;
for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ )
{
aPath.append( sal_Unicode( '/' ));
aPath.append( aParser.getName( nIndex, false, INetURLObject::NO_DECODE ));
}
if ( nCount > 0 )
aPath.append( sal_Unicode( '/' )); // final slash!
aURL.Path = aPath.makeStringAndClear();
aURL.Name = aParser.getName( INetURLObject::LAST_SEGMENT, false, INetURLObject::NO_DECODE );
}
else
{
aURL.Path = aParser.GetURLPath( INetURLObject::NO_DECODE );
aURL.Name = aParser.GetName ( );
}
aURL.Arguments = aParser.GetParam ( INetURLObject::NO_DECODE );
aURL.Mark = aParser.GetMark ( INetURLObject::DECODE_WITH_CHARSET );
// INetURLObject supports only an intelligent method of parsing URL's. So write
// back Complete to have a valid encoded URL in all cases!
aURL.Complete = aParser.GetMainURL( INetURLObject::NO_DECODE );
aURL.Complete = aURL.Complete.intern();
aParser.SetMark ( OUString() );
aParser.SetParam( OUString() );
aURL.Main = aParser.GetMainURL( INetURLObject::NO_DECODE );
// Return "URL is parsed".
return sal_True;
}
}
else
{
// Minmal support for unknown protocols. This is mandatory to support the "Protocol Handlers" implemented
// in framework!
aURL.Protocol = aProtocol;
aURL.Main = aURL.Complete;
aURL.Path = aURL.Complete.copy( nURLIndex+1 );;
// Return "URL is parsed".
return sal_True;
}
}
return sal_False;
}
//*****************************************************************************************************************
// XURLTransformer
//*****************************************************************************************************************
sal_Bool SAL_CALL URLTransformer::parseSmart( URL& aURL ,
const OUString& sSmartProtocol ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases.
if (( &aURL == NULL ) ||
( aURL.Complete.getLength() < 1 ) )
{
return sal_False;
}
// Initialize parser with given URL.
INetURLObject aParser;
aParser.SetSmartProtocol( INetURLObject::CompareProtocolScheme( sSmartProtocol ));
bool bOk = aParser.SetSmartURL( aURL.Complete );
if ( bOk )
{
// Get all information about this URL.
aURL.Protocol = INetURLObject::GetScheme( aParser.GetProtocol() );
aURL.User = aParser.GetUser ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Password = aParser.GetPass ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Server = aParser.GetHost ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Port = (sal_Int16)aParser.GetPort();
sal_Int32 nCount = aParser.getSegmentCount( false );
if ( nCount > 0 )
{
// Don't add last segment as it is the name!
--nCount;
rtl::OUStringBuffer aPath;
for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ )
{
aPath.append( sal_Unicode( '/' ));
aPath.append( aParser.getName( nIndex, false, INetURLObject::NO_DECODE ));
}
if ( nCount > 0 )
aPath.append( sal_Unicode( '/' )); // final slash!
aURL.Path = aPath.makeStringAndClear();
aURL.Name = aParser.getName( INetURLObject::LAST_SEGMENT, false, INetURLObject::NO_DECODE );
}
else
{
aURL.Path = aParser.GetURLPath( INetURLObject::NO_DECODE );
aURL.Name = aParser.GetName ( );
}
aURL.Arguments = aParser.GetParam ( INetURLObject::NO_DECODE );
aURL.Mark = aParser.GetMark ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Complete = aParser.GetMainURL( INetURLObject::NO_DECODE );
aParser.SetMark ( OUString() );
aParser.SetParam( OUString() );
aURL.Main = aParser.GetMainURL( INetURLObject::NO_DECODE );
// Return "URL is parsed".
return sal_True;
}
else
{
// Minmal support for unknown protocols. This is mandatory to support the "Protocol Handlers" implemented
// in framework!
if ( INetURLObject::CompareProtocolScheme( sSmartProtocol ) == INET_PROT_NOT_VALID )
{
// Try to extract the protocol
sal_Int32 nIndex = aURL.Complete.indexOf( sal_Unicode( ':' ));
OUString aProtocol;
if ( nIndex > 1 )
{
aProtocol = aURL.Complete.copy( 0, nIndex+1 );
// If INetURLObject knows this protocol something is wrong as detected before =>
// give up and return false!
if ( INetURLObject::CompareProtocolScheme( aProtocol ) != INET_PROT_NOT_VALID )
return sal_False;
else
aURL.Protocol = aProtocol;
}
else
return sal_False;
aURL.Main = aURL.Complete;
aURL.Path = aURL.Complete.copy( nIndex+1 );
return sal_True;
}
else
return sal_False;
}
}
//*****************************************************************************************************************
// XURLTransformer
//*****************************************************************************************************************
sal_Bool SAL_CALL URLTransformer::assemble( URL& aURL ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases.
if ( &aURL == NULL )
return sal_False ;
// Initialize parser.
INetURLObject aParser;
if ( INetURLObject::CompareProtocolScheme( aURL.Protocol ) != INET_PROT_NOT_VALID )
{
OUStringBuffer aCompletePath( aURL.Path );
// Concat the name if it is provided, just support a final slash
if ( aURL.Name.getLength() > 0 )
{
sal_Int32 nIndex = aURL.Path.lastIndexOf( sal_Unicode('/') );
if ( nIndex == ( aURL.Path.getLength() -1 ))
aCompletePath.append( aURL.Name );
else
{
aCompletePath.append( sal_Unicode( '/' ) );
aCompletePath.append( aURL.Name );
}
}
bool bResult = aParser.ConcatData(
INetURLObject::CompareProtocolScheme( aURL.Protocol ) ,
aURL.User ,
aURL.Password ,
aURL.Server ,
aURL.Port ,
aCompletePath.makeStringAndClear() );
if ( !bResult )
return sal_False;
// First parse URL WITHOUT ...
aURL.Main = aParser.GetMainURL( INetURLObject::NO_DECODE );
// ...and then WITH parameter and mark.
aParser.SetParam( aURL.Arguments);
aParser.SetMark ( aURL.Mark, INetURLObject::ENCODE_ALL );
aURL.Complete = aParser.GetMainURL( INetURLObject::NO_DECODE );
// Return "URL is assembled".
return sal_True;
}
else if ( aURL.Protocol.getLength() > 0 )
{
// Minimal support for unknown protocols
OUStringBuffer aBuffer( aURL.Protocol );
aBuffer.append( aURL.Path );
aURL.Complete = aBuffer.makeStringAndClear();
aURL.Main = aURL.Complete;
return sal_True;
}
return sal_False;
}
//*****************************************************************************************************************
// XURLTransformer
//*****************************************************************************************************************
OUString SAL_CALL URLTransformer::getPresentation( const URL& aURL ,
sal_Bool bWithPassword ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases.
if (( &aURL == NULL ) ||
( aURL.Complete.getLength() < 1 ) ||
(( bWithPassword != sal_True ) &&
( bWithPassword != sal_False ) ) )
{
return OUString();
}
// Check given URL
URL aTestURL = aURL;
sal_Bool bParseResult = parseSmart( aTestURL, aTestURL.Protocol );
if ( bParseResult )
{
if ( !bWithPassword && aTestURL.Password.getLength() > 0 )
{
// Exchange password text with other placeholder string
aTestURL.Password = OUString::createFromAscii( "<******>" );
assemble( aTestURL );
}
// Convert internal URLs to "praesentation"-URLs!
rtl::OUString sPraesentationURL;
INetURLObject::translateToExternal( aTestURL.Complete, sPraesentationURL, INetURLObject::DECODE_UNAMBIGUOUS );
return sPraesentationURL;
}
else
return OUString();
}
//_________________________________________________________________________________________________________________
// debug methods
//_________________________________________________________________________________________________________________
} // namespace framework
<commit_msg>INTEGRATION: CWS changefileheader (1.15.176); FILE MERGED 2008/04/01 15:18:45 thb 1.15.176.3: #i85898# Stripping all external header guards 2008/04/01 10:58:13 thb 1.15.176.2: #i85898# Stripping all external header guards 2008/03/28 15:35:29 rt 1.15.176.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: urltransformer.cxx,v $
* $Revision: 1.16 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_framework.hxx"
//_________________________________________________________________________________________________________________
// my own includes
//_________________________________________________________________________________________________________________
#include <services/urltransformer.hxx>
#include <threadhelp/resetableguard.hxx>
#include <macros/debug.hxx>
#include <services.h>
//_________________________________________________________________________________________________________________
// interface includes
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// includes of other projects
//_________________________________________________________________________________________________________________
#include <tools/urlobj.hxx>
#include <rtl/ustrbuf.hxx>
#include <vcl/svapp.hxx>
//_________________________________________________________________________________________________________________
// namespace
//_________________________________________________________________________________________________________________
namespace framework{
using namespace ::osl ;
using namespace ::rtl ;
using namespace ::cppu ;
using namespace ::com::sun::star::uno ;
using namespace ::com::sun::star::lang ;
using namespace ::com::sun::star::util ;
//_________________________________________________________________________________________________________________
// non exported const
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// non exported definitions
//_________________________________________________________________________________________________________________
//_________________________________________________________________________________________________________________
// declarations
//_________________________________________________________________________________________________________________
//*****************************************************************************************************************
// constructor
//*****************************************************************************************************************
URLTransformer::URLTransformer( const Reference< XMultiServiceFactory >& xFactory )
// Init baseclasses first
// Attention:
// Don't change order of initialization!
// ThreadHelpBase is a struct with a mutex as member. We can't use a mutex as member, while
// we must garant right initialization and a valid value of this! First initialize
// baseclasses and then members. And we need the mutex for other baseclasses !!!
: ThreadHelpBase ( &Application::GetSolarMutex() )
, OWeakObject ( )
// Init member
, m_xFactory ( xFactory )
{
// Safe impossible cases.
// Method not defined for all incoming parameter.
LOG_ASSERT( xFactory.is(), "URLTransformer::URLTransformer()\nInvalid parameter detected!\n" )
}
//*****************************************************************************************************************
// destructor
//*****************************************************************************************************************
URLTransformer::~URLTransformer()
{
}
//*****************************************************************************************************************
// XInterface, XTypeProvider, XServiceInfo
//*****************************************************************************************************************
DEFINE_XINTERFACE_3 ( URLTransformer ,
OWeakObject ,
DIRECT_INTERFACE(XTypeProvider ),
DIRECT_INTERFACE(XServiceInfo ),
DIRECT_INTERFACE(XURLTransformer )
)
DEFINE_XTYPEPROVIDER_3 ( URLTransformer ,
XTypeProvider ,
XServiceInfo ,
XURLTransformer
)
DEFINE_XSERVICEINFO_MULTISERVICE ( URLTransformer ,
OWeakObject ,
SERVICENAME_URLTRANSFORMER ,
IMPLEMENTATIONNAME_URLTRANSFORMER
)
DEFINE_INIT_SERVICE ( URLTransformer,
{
}
)
//*****************************************************************************************************************
// XURLTransformer
//*****************************************************************************************************************
sal_Bool SAL_CALL URLTransformer::parseStrict( URL& aURL ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases.
if (( &aURL == NULL ) ||
( aURL.Complete.getLength() < 1 ) )
{
return sal_False;
}
// Try to extract the protocol
sal_Int32 nURLIndex = aURL.Complete.indexOf( sal_Unicode( ':' ));
OUString aProtocol;
if ( nURLIndex > 1 )
{
aProtocol = aURL.Complete.copy( 0, nURLIndex+1 );
// If INetURLObject knows this protocol let it parse
if ( INetURLObject::CompareProtocolScheme( aProtocol ) != INET_PROT_NOT_VALID )
{
// Initialize parser with given URL.
INetURLObject aParser( aURL.Complete );
// Get all information about this URL.
INetProtocol eINetProt = aParser.GetProtocol();
if ( eINetProt == INET_PROT_NOT_VALID )
{
return sal_False;
}
else if ( !aParser.HasError() )
{
aURL.Protocol = INetURLObject::GetScheme( aParser.GetProtocol() );
aURL.User = aParser.GetUser ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Password = aParser.GetPass ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Server = aParser.GetHost ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Port = (sal_Int16)aParser.GetPort();
sal_Int32 nCount = aParser.getSegmentCount( false );
if ( nCount > 0 )
{
// Don't add last segment as it is the name!
--nCount;
rtl::OUStringBuffer aPath;
for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ )
{
aPath.append( sal_Unicode( '/' ));
aPath.append( aParser.getName( nIndex, false, INetURLObject::NO_DECODE ));
}
if ( nCount > 0 )
aPath.append( sal_Unicode( '/' )); // final slash!
aURL.Path = aPath.makeStringAndClear();
aURL.Name = aParser.getName( INetURLObject::LAST_SEGMENT, false, INetURLObject::NO_DECODE );
}
else
{
aURL.Path = aParser.GetURLPath( INetURLObject::NO_DECODE );
aURL.Name = aParser.GetName ( );
}
aURL.Arguments = aParser.GetParam ( INetURLObject::NO_DECODE );
aURL.Mark = aParser.GetMark ( INetURLObject::DECODE_WITH_CHARSET );
// INetURLObject supports only an intelligent method of parsing URL's. So write
// back Complete to have a valid encoded URL in all cases!
aURL.Complete = aParser.GetMainURL( INetURLObject::NO_DECODE );
aURL.Complete = aURL.Complete.intern();
aParser.SetMark ( OUString() );
aParser.SetParam( OUString() );
aURL.Main = aParser.GetMainURL( INetURLObject::NO_DECODE );
// Return "URL is parsed".
return sal_True;
}
}
else
{
// Minmal support for unknown protocols. This is mandatory to support the "Protocol Handlers" implemented
// in framework!
aURL.Protocol = aProtocol;
aURL.Main = aURL.Complete;
aURL.Path = aURL.Complete.copy( nURLIndex+1 );;
// Return "URL is parsed".
return sal_True;
}
}
return sal_False;
}
//*****************************************************************************************************************
// XURLTransformer
//*****************************************************************************************************************
sal_Bool SAL_CALL URLTransformer::parseSmart( URL& aURL ,
const OUString& sSmartProtocol ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases.
if (( &aURL == NULL ) ||
( aURL.Complete.getLength() < 1 ) )
{
return sal_False;
}
// Initialize parser with given URL.
INetURLObject aParser;
aParser.SetSmartProtocol( INetURLObject::CompareProtocolScheme( sSmartProtocol ));
bool bOk = aParser.SetSmartURL( aURL.Complete );
if ( bOk )
{
// Get all information about this URL.
aURL.Protocol = INetURLObject::GetScheme( aParser.GetProtocol() );
aURL.User = aParser.GetUser ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Password = aParser.GetPass ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Server = aParser.GetHost ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Port = (sal_Int16)aParser.GetPort();
sal_Int32 nCount = aParser.getSegmentCount( false );
if ( nCount > 0 )
{
// Don't add last segment as it is the name!
--nCount;
rtl::OUStringBuffer aPath;
for ( sal_Int32 nIndex = 0; nIndex < nCount; nIndex++ )
{
aPath.append( sal_Unicode( '/' ));
aPath.append( aParser.getName( nIndex, false, INetURLObject::NO_DECODE ));
}
if ( nCount > 0 )
aPath.append( sal_Unicode( '/' )); // final slash!
aURL.Path = aPath.makeStringAndClear();
aURL.Name = aParser.getName( INetURLObject::LAST_SEGMENT, false, INetURLObject::NO_DECODE );
}
else
{
aURL.Path = aParser.GetURLPath( INetURLObject::NO_DECODE );
aURL.Name = aParser.GetName ( );
}
aURL.Arguments = aParser.GetParam ( INetURLObject::NO_DECODE );
aURL.Mark = aParser.GetMark ( INetURLObject::DECODE_WITH_CHARSET );
aURL.Complete = aParser.GetMainURL( INetURLObject::NO_DECODE );
aParser.SetMark ( OUString() );
aParser.SetParam( OUString() );
aURL.Main = aParser.GetMainURL( INetURLObject::NO_DECODE );
// Return "URL is parsed".
return sal_True;
}
else
{
// Minmal support for unknown protocols. This is mandatory to support the "Protocol Handlers" implemented
// in framework!
if ( INetURLObject::CompareProtocolScheme( sSmartProtocol ) == INET_PROT_NOT_VALID )
{
// Try to extract the protocol
sal_Int32 nIndex = aURL.Complete.indexOf( sal_Unicode( ':' ));
OUString aProtocol;
if ( nIndex > 1 )
{
aProtocol = aURL.Complete.copy( 0, nIndex+1 );
// If INetURLObject knows this protocol something is wrong as detected before =>
// give up and return false!
if ( INetURLObject::CompareProtocolScheme( aProtocol ) != INET_PROT_NOT_VALID )
return sal_False;
else
aURL.Protocol = aProtocol;
}
else
return sal_False;
aURL.Main = aURL.Complete;
aURL.Path = aURL.Complete.copy( nIndex+1 );
return sal_True;
}
else
return sal_False;
}
}
//*****************************************************************************************************************
// XURLTransformer
//*****************************************************************************************************************
sal_Bool SAL_CALL URLTransformer::assemble( URL& aURL ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases.
if ( &aURL == NULL )
return sal_False ;
// Initialize parser.
INetURLObject aParser;
if ( INetURLObject::CompareProtocolScheme( aURL.Protocol ) != INET_PROT_NOT_VALID )
{
OUStringBuffer aCompletePath( aURL.Path );
// Concat the name if it is provided, just support a final slash
if ( aURL.Name.getLength() > 0 )
{
sal_Int32 nIndex = aURL.Path.lastIndexOf( sal_Unicode('/') );
if ( nIndex == ( aURL.Path.getLength() -1 ))
aCompletePath.append( aURL.Name );
else
{
aCompletePath.append( sal_Unicode( '/' ) );
aCompletePath.append( aURL.Name );
}
}
bool bResult = aParser.ConcatData(
INetURLObject::CompareProtocolScheme( aURL.Protocol ) ,
aURL.User ,
aURL.Password ,
aURL.Server ,
aURL.Port ,
aCompletePath.makeStringAndClear() );
if ( !bResult )
return sal_False;
// First parse URL WITHOUT ...
aURL.Main = aParser.GetMainURL( INetURLObject::NO_DECODE );
// ...and then WITH parameter and mark.
aParser.SetParam( aURL.Arguments);
aParser.SetMark ( aURL.Mark, INetURLObject::ENCODE_ALL );
aURL.Complete = aParser.GetMainURL( INetURLObject::NO_DECODE );
// Return "URL is assembled".
return sal_True;
}
else if ( aURL.Protocol.getLength() > 0 )
{
// Minimal support for unknown protocols
OUStringBuffer aBuffer( aURL.Protocol );
aBuffer.append( aURL.Path );
aURL.Complete = aBuffer.makeStringAndClear();
aURL.Main = aURL.Complete;
return sal_True;
}
return sal_False;
}
//*****************************************************************************************************************
// XURLTransformer
//*****************************************************************************************************************
OUString SAL_CALL URLTransformer::getPresentation( const URL& aURL ,
sal_Bool bWithPassword ) throw( RuntimeException )
{
// Ready for multithreading
ResetableGuard aGuard( m_aLock );
// Safe impossible cases.
if (( &aURL == NULL ) ||
( aURL.Complete.getLength() < 1 ) ||
(( bWithPassword != sal_True ) &&
( bWithPassword != sal_False ) ) )
{
return OUString();
}
// Check given URL
URL aTestURL = aURL;
sal_Bool bParseResult = parseSmart( aTestURL, aTestURL.Protocol );
if ( bParseResult )
{
if ( !bWithPassword && aTestURL.Password.getLength() > 0 )
{
// Exchange password text with other placeholder string
aTestURL.Password = OUString::createFromAscii( "<******>" );
assemble( aTestURL );
}
// Convert internal URLs to "praesentation"-URLs!
rtl::OUString sPraesentationURL;
INetURLObject::translateToExternal( aTestURL.Complete, sPraesentationURL, INetURLObject::DECODE_UNAMBIGUOUS );
return sPraesentationURL;
}
else
return OUString();
}
//_________________________________________________________________________________________________________________
// debug methods
//_________________________________________________________________________________________________________________
} // namespace framework
<|endoftext|>
|
<commit_before>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Full-stack compiler that converts a source code string to bytecode.
*/
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <jsonrpc/json/json.h>
using namespace std;
namespace dev
{
namespace solidity
{
void CompilerStack::setSource(string const& _sourceCode)
{
reset();
m_scanner = make_shared<Scanner>(CharStream(_sourceCode));
}
void CompilerStack::parse()
{
if (!m_scanner)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source not available."));
m_contractASTNode = Parser().parse(m_scanner);
m_globalContext = make_shared<GlobalContext>();
m_globalContext->setCurrentContract(*m_contractASTNode);
NameAndTypeResolver(m_globalContext->getDeclarations()).resolveNamesAndTypes(*m_contractASTNode);
m_parseSuccessful = true;
}
void CompilerStack::parse(string const& _sourceCode)
{
setSource(_sourceCode);
parse();
}
bytes const& CompilerStack::compile(bool _optimize)
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
m_bytecode.clear();
m_compiler = make_shared<Compiler>();
m_compiler->compileContract(*m_contractASTNode, m_globalContext->getMagicVariables());
return m_bytecode = m_compiler->getAssembledBytecode(_optimize);
}
bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
parse(_sourceCode);
return compile(_optimize);
}
void CompilerStack::streamAssembly(ostream& _outStream)
{
if (!m_compiler || m_bytecode.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful."));
m_compiler->streamAssembly(_outStream);
}
string const& CompilerStack::getInterface()
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_interface.empty())
{
stringstream interface;
interface << '[';
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
unsigned functionsCount = exportedFunctions.size();
for (FunctionDefinition const* f: exportedFunctions)
{
auto streamVariables = [&](vector<ASTPointer<VariableDeclaration>> const& _vars)
{
unsigned varCount = _vars.size();
for (ASTPointer<VariableDeclaration> const& var: _vars)
{
interface << "{"
<< "\"name\":" << escaped(var->getName(), false) << ","
<< "\"type\":" << escaped(var->getType()->toString(), false)
<< "}";
if (--varCount > 0)
interface << ",";
}
};
interface << '{'
<< "\"name\":" << escaped(f->getName(), false) << ","
<< "\"inputs\":[";
streamVariables(f->getParameters());
interface << "],"
<< "\"outputs\":[";
streamVariables(f->getReturnParameters());
interface << "]"
<< "}";
if (--functionsCount > 0)
interface << ",";
}
interface << ']';
m_interface = interface.str();
}
return m_interface;
}
string const& CompilerStack::getDocumentation()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_documentation.empty())
{
Json::Value doc;
Json::Value methods;
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value user;
user["user"] = Json::Value(*f->getDocumentation());
methods[f->getName()] = user;
}
doc["methods"] = methods;
m_documentation = writer.write(doc);
}
return m_documentation;
}
bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
CompilerStack stack;
return stack.compile(_sourceCode, _optimize);
}
}
}
<commit_msg>Using jsoncpp for exporting ABI interface from solidity<commit_after>/*
This file is part of cpp-ethereum.
cpp-ethereum 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.
cpp-ethereum 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 cpp-ethereum. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* @author Christian <c@ethdev.com>
* @date 2014
* Full-stack compiler that converts a source code string to bytecode.
*/
#include <libsolidity/AST.h>
#include <libsolidity/Scanner.h>
#include <libsolidity/Parser.h>
#include <libsolidity/GlobalContext.h>
#include <libsolidity/NameAndTypeResolver.h>
#include <libsolidity/Compiler.h>
#include <libsolidity/CompilerStack.h>
#include <jsonrpc/json/json.h>
using namespace std;
namespace dev
{
namespace solidity
{
void CompilerStack::setSource(string const& _sourceCode)
{
reset();
m_scanner = make_shared<Scanner>(CharStream(_sourceCode));
}
void CompilerStack::parse()
{
if (!m_scanner)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Source not available."));
m_contractASTNode = Parser().parse(m_scanner);
m_globalContext = make_shared<GlobalContext>();
m_globalContext->setCurrentContract(*m_contractASTNode);
NameAndTypeResolver(m_globalContext->getDeclarations()).resolveNamesAndTypes(*m_contractASTNode);
m_parseSuccessful = true;
}
void CompilerStack::parse(string const& _sourceCode)
{
setSource(_sourceCode);
parse();
}
bytes const& CompilerStack::compile(bool _optimize)
{
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
m_bytecode.clear();
m_compiler = make_shared<Compiler>();
m_compiler->compileContract(*m_contractASTNode, m_globalContext->getMagicVariables());
return m_bytecode = m_compiler->getAssembledBytecode(_optimize);
}
bytes const& CompilerStack::compile(string const& _sourceCode, bool _optimize)
{
parse(_sourceCode);
return compile(_optimize);
}
void CompilerStack::streamAssembly(ostream& _outStream)
{
if (!m_compiler || m_bytecode.empty())
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Compilation was not successful."));
m_compiler->streamAssembly(_outStream);
}
string const& CompilerStack::getInterface()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_interface.empty())
{
Json::Value methods(Json::arrayValue);
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value method;
Json::Value inputs(Json::arrayValue);
Json::Value outputs(Json::arrayValue);
auto streamVariables = [&](vector<ASTPointer<VariableDeclaration>> const& _vars,
Json::Value &json)
{
for (ASTPointer<VariableDeclaration> const& var: _vars)
{
Json::Value input;
input["name"] = var->getName();
input["type"] = var->getType()->toString();
json.append(input);
}
};
method["name"] = f->getName();
streamVariables(f->getParameters(), inputs);
method["inputs"] = inputs;
streamVariables(f->getReturnParameters(), outputs);
method["outputs"] = outputs;
methods.append(method);
}
m_interface = writer.write(methods);
}
return m_interface;
}
string const& CompilerStack::getDocumentation()
{
Json::StyledWriter writer;
if (!m_parseSuccessful)
BOOST_THROW_EXCEPTION(CompilerError() << errinfo_comment("Parsing was not successful."));
if (m_documentation.empty())
{
Json::Value doc;
Json::Value methods;
vector<FunctionDefinition const*> exportedFunctions = m_contractASTNode->getInterfaceFunctions();
for (FunctionDefinition const* f: exportedFunctions)
{
Json::Value user;
user["user"] = Json::Value(*f->getDocumentation());
methods[f->getName()] = user;
}
doc["methods"] = methods;
m_documentation = writer.write(doc);
}
return m_documentation;
}
bytes CompilerStack::staticCompile(std::string const& _sourceCode, bool _optimize)
{
CompilerStack stack;
return stack.compile(_sourceCode, _optimize);
}
}
}
<|endoftext|>
|
<commit_before>//
// AmstradCPC.cpp
// Clock Signal
//
// Created by Thomas Harte on 30/07/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#include "StaticAnalyser.hpp"
#include "../../Storage/Disk/Parsers/CPM.hpp"
#include "../../Storage/Disk/Encodings/MFM.hpp"
static bool strcmp_insensitive(const char *a, const char *b) {
if(strlen(a) != strlen(b)) return false;
while(*a) {
if(tolower(*a) != towlower(*b)) return false;
a++;
b++;
}
return true;
}
static std::string RunCommandFor(const Storage::Disk::CPM::File &file) {
return "run\"" + file.name + "\n";
}
static void InspectDataCatalogue(
const Storage::Disk::CPM::Catalogue &catalogue,
StaticAnalyser::Target &target) {
// Make a copy of all files and filter out any that are marked as system.
std::vector<Storage::Disk::CPM::File> candidate_files = catalogue.files;
candidate_files.erase(
std::remove_if(candidate_files.begin(), candidate_files.end(), [](const Storage::Disk::CPM::File &file) {
return file.system;
}),
candidate_files.end());
// If there's just one file, run that.
if(candidate_files.size() == 1) {
target.loadingCommand = RunCommandFor(candidate_files[0]);
return;
}
// If only one file is [potentially] BASIC, run that one; otherwise if only one has a suffix
// that AMSDOS allows to be omitted, pick that one.
int basic_files = 0;
int implicit_suffixed_files = 0;
size_t last_basic_file = 0;
size_t last_implicit_suffixed_file = 0;
for(size_t c = 0; c < candidate_files.size(); c++) {
// Files with nothing but spaces in their name can't be loaded by the user, so disregard them.
if(candidate_files[c].type == " " && candidate_files[c].name == " ")
continue;
// Check for whether this is [potentially] BASIC.
if(candidate_files[c].data.size() >= 128 && !((candidate_files[c].data[18] >> 1) & 7)) {
basic_files++;
last_basic_file = c;
}
// Check suffix for emptiness.
if(
candidate_files[c].type == " " ||
strcmp_insensitive(candidate_files[c].type.c_str(), "BAS") ||
strcmp_insensitive(candidate_files[c].type.c_str(), "BIN")
) {
implicit_suffixed_files++;
last_implicit_suffixed_file = c;
}
}
if(basic_files == 1 || implicit_suffixed_files == 1) {
size_t selected_file = (basic_files == 1) ? last_basic_file : last_implicit_suffixed_file;
target.loadingCommand = RunCommandFor(candidate_files[selected_file]);
return;
}
// Desperation.
target.loadingCommand = "cat\n";
}
static void InspectSystemCatalogue(
const std::shared_ptr<Storage::Disk::Disk> &disk,
const Storage::Disk::CPM::Catalogue &catalogue,
StaticAnalyser::Target &target) {
Storage::Encodings::MFM::Parser parser(true, disk);
// Check that the boot sector exists and looks like it had content written to it.
std::shared_ptr<Storage::Encodings::MFM::Sector> boot_sector = parser.get_sector(0, 0, 0x41);
if(boot_sector != nullptr) {
// Check that the first 64 bytes of the sector aren't identical; if they are then probably
// this disk was formatted and the filler byte never replaced.
bool matched = true;
for(size_t c = 1; c < 64; c++) {
if(boot_sector->data[c] != boot_sector->data[0]) {
matched = false;
break;
}
}
// This is a system disk, then launch it as though it were CP/M.
if(!matched) {
target.loadingCommand = "|cpm\n";
return;
}
}
InspectDataCatalogue(catalogue, target);
}
void StaticAnalyser::AmstradCPC::AddTargets(
const std::list<std::shared_ptr<Storage::Disk::Disk>> &disks,
const std::list<std::shared_ptr<Storage::Tape::Tape>> &tapes,
const std::list<std::shared_ptr<Storage::Cartridge::Cartridge>> &cartridges,
std::list<StaticAnalyser::Target> &destination) {
Target target;
target.machine = Target::AmstradCPC;
target.probability = 1.0;
target.disks = disks;
target.tapes = tapes;
target.cartridges = cartridges;
target.amstradcpc.model = AmstradCPCModel::CPC6128;
if(!target.tapes.empty()) {
// Ugliness flows here: assume the CPC isn't smart enough to pause between pressing
// enter and responding to the follow-on prompt to press a key, so just type for
// a while. Yuck!
target.loadingCommand = "|tape\nrun\"\n1234567890";
}
if(!target.disks.empty()) {
Storage::Disk::CPM::ParameterBlock data_format;
data_format.sectors_per_track = 9;
data_format.tracks = 40;
data_format.block_size = 1024;
data_format.first_sector = 0xc1;
data_format.catalogue_allocation_bitmap = 0xc000;
data_format.reserved_tracks = 0;
std::unique_ptr<Storage::Disk::CPM::Catalogue> data_catalogue = Storage::Disk::CPM::GetCatalogue(target.disks.front(), data_format);
if(data_catalogue) {
InspectDataCatalogue(*data_catalogue, target);
} else {
Storage::Disk::CPM::ParameterBlock system_format;
system_format.sectors_per_track = 9;
system_format.tracks = 40;
system_format.block_size = 1024;
system_format.first_sector = 0x41;
system_format.catalogue_allocation_bitmap = 0xc000;
system_format.reserved_tracks = 2;
std::unique_ptr<Storage::Disk::CPM::Catalogue> system_catalogue = Storage::Disk::CPM::GetCatalogue(target.disks.front(), system_format);
if(system_catalogue) {
InspectSystemCatalogue(target.disks.front(), *system_catalogue, target);
}
}
}
destination.push_back(target);
}
<commit_msg>Adjusted rules so as not to type unnecessary spaces in the name, and to include the extension if AMSDOS won't imply it.<commit_after>//
// AmstradCPC.cpp
// Clock Signal
//
// Created by Thomas Harte on 30/07/2017.
// Copyright © 2017 Thomas Harte. All rights reserved.
//
#include "StaticAnalyser.hpp"
#include "../../Storage/Disk/Parsers/CPM.hpp"
#include "../../Storage/Disk/Encodings/MFM.hpp"
static bool strcmp_insensitive(const char *a, const char *b) {
if(strlen(a) != strlen(b)) return false;
while(*a) {
if(tolower(*a) != towlower(*b)) return false;
a++;
b++;
}
return true;
}
static bool is_implied_extension(const std::string &extension) {
return
extension == " " ||
strcmp_insensitive(extension.c_str(), "BAS") ||
strcmp_insensitive(extension.c_str(), "BIN");
}
static std::string RunCommandFor(const Storage::Disk::CPM::File &file) {
// Trim spaces from the name.
std::string name = file.name;
name.erase(std::find_if(name.rbegin(), name.rend(), [](int ch) {
return !std::isspace(ch);
}).base(), name.end());
// Form the basic command.
std::string command = "run\"" + name;
// Consider whether the extension is required.
if(!is_implied_extension(file.type)) {
command += "." + file.type;
}
// Add a newline and return.
return command + "\n";
}
static void InspectDataCatalogue(
const Storage::Disk::CPM::Catalogue &catalogue,
StaticAnalyser::Target &target) {
// Make a copy of all files and filter out any that are marked as system.
std::vector<Storage::Disk::CPM::File> candidate_files = catalogue.files;
candidate_files.erase(
std::remove_if(candidate_files.begin(), candidate_files.end(), [](const Storage::Disk::CPM::File &file) {
return file.system;
}),
candidate_files.end());
// If there's just one file, run that.
if(candidate_files.size() == 1) {
target.loadingCommand = RunCommandFor(candidate_files[0]);
return;
}
// If only one file is [potentially] BASIC, run that one; otherwise if only one has a suffix
// that AMSDOS allows to be omitted, pick that one.
int basic_files = 0;
int implicit_suffixed_files = 0;
size_t last_basic_file = 0;
size_t last_implicit_suffixed_file = 0;
for(size_t c = 0; c < candidate_files.size(); c++) {
// Files with nothing but spaces in their name can't be loaded by the user, so disregard them.
if(candidate_files[c].type == " " && candidate_files[c].name == " ")
continue;
// Check for whether this is [potentially] BASIC.
if(candidate_files[c].data.size() >= 128 && !((candidate_files[c].data[18] >> 1) & 7)) {
basic_files++;
last_basic_file = c;
}
// Check suffix for emptiness.
if(is_implied_extension(candidate_files[c].type)) {
implicit_suffixed_files++;
last_implicit_suffixed_file = c;
}
}
if(basic_files == 1 || implicit_suffixed_files == 1) {
size_t selected_file = (basic_files == 1) ? last_basic_file : last_implicit_suffixed_file;
target.loadingCommand = RunCommandFor(candidate_files[selected_file]);
return;
}
// Desperation.
target.loadingCommand = "cat\n";
}
static void InspectSystemCatalogue(
const std::shared_ptr<Storage::Disk::Disk> &disk,
const Storage::Disk::CPM::Catalogue &catalogue,
StaticAnalyser::Target &target) {
Storage::Encodings::MFM::Parser parser(true, disk);
// Check that the boot sector exists and looks like it had content written to it.
std::shared_ptr<Storage::Encodings::MFM::Sector> boot_sector = parser.get_sector(0, 0, 0x41);
if(boot_sector != nullptr) {
// Check that the first 64 bytes of the sector aren't identical; if they are then probably
// this disk was formatted and the filler byte never replaced.
bool matched = true;
for(size_t c = 1; c < 64; c++) {
if(boot_sector->data[c] != boot_sector->data[0]) {
matched = false;
break;
}
}
// This is a system disk, then launch it as though it were CP/M.
if(!matched) {
target.loadingCommand = "|cpm\n";
return;
}
}
InspectDataCatalogue(catalogue, target);
}
void StaticAnalyser::AmstradCPC::AddTargets(
const std::list<std::shared_ptr<Storage::Disk::Disk>> &disks,
const std::list<std::shared_ptr<Storage::Tape::Tape>> &tapes,
const std::list<std::shared_ptr<Storage::Cartridge::Cartridge>> &cartridges,
std::list<StaticAnalyser::Target> &destination) {
Target target;
target.machine = Target::AmstradCPC;
target.probability = 1.0;
target.disks = disks;
target.tapes = tapes;
target.cartridges = cartridges;
target.amstradcpc.model = AmstradCPCModel::CPC6128;
if(!target.tapes.empty()) {
// Ugliness flows here: assume the CPC isn't smart enough to pause between pressing
// enter and responding to the follow-on prompt to press a key, so just type for
// a while. Yuck!
target.loadingCommand = "|tape\nrun\"\n1234567890";
}
if(!target.disks.empty()) {
Storage::Disk::CPM::ParameterBlock data_format;
data_format.sectors_per_track = 9;
data_format.tracks = 40;
data_format.block_size = 1024;
data_format.first_sector = 0xc1;
data_format.catalogue_allocation_bitmap = 0xc000;
data_format.reserved_tracks = 0;
std::unique_ptr<Storage::Disk::CPM::Catalogue> data_catalogue = Storage::Disk::CPM::GetCatalogue(target.disks.front(), data_format);
if(data_catalogue) {
InspectDataCatalogue(*data_catalogue, target);
} else {
Storage::Disk::CPM::ParameterBlock system_format;
system_format.sectors_per_track = 9;
system_format.tracks = 40;
system_format.block_size = 1024;
system_format.first_sector = 0x41;
system_format.catalogue_allocation_bitmap = 0xc000;
system_format.reserved_tracks = 2;
std::unique_ptr<Storage::Disk::CPM::Catalogue> system_catalogue = Storage::Disk::CPM::GetCatalogue(target.disks.front(), system_format);
if(system_catalogue) {
InspectSystemCatalogue(target.disks.front(), *system_catalogue, target);
}
}
}
destination.push_back(target);
}
<|endoftext|>
|
<commit_before>// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iomanip>
#include <string>
#include "third_party/boringssl/src/include/openssl/siphash.h"
#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
#include "net/third_party/quiche/src/quic/core/quic_types.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_endian.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_text_utils.h"
namespace quic {
namespace {
// QuicConnectionIdHasher can be used to generate a stable connection ID hash
// function that will return the same value for two equal connection IDs for
// the duration of process lifetime. It is meant to be used as input to data
// structures that do not outlast process lifetime. A new key is generated once
// per process to prevent attackers from crafting connection IDs in such a way
// that they always land in the same hash bucket.
class QuicConnectionIdHasher {
public:
explicit inline QuicConnectionIdHasher()
: QuicConnectionIdHasher(QuicRandom::GetInstance()) {}
explicit inline QuicConnectionIdHasher(QuicRandom* random) {
random->RandBytes(&sip_hash_key_, sizeof(sip_hash_key_));
}
inline size_t Hash(const char* input, size_t input_len) const {
return static_cast<size_t>(SIPHASH_24(
sip_hash_key_, reinterpret_cast<const uint8_t*>(input), input_len));
}
private:
uint64_t sip_hash_key_[2];
};
} // namespace
QuicConnectionId::QuicConnectionId() : QuicConnectionId(nullptr, 0) {}
QuicConnectionId::QuicConnectionId(const char* data, uint8_t length) {
static_assert(
kQuicMaxConnectionIdLength <= std::numeric_limits<uint8_t>::max(),
"kQuicMaxConnectionIdLength too high");
if (length > kQuicMaxConnectionIdLength) {
QUIC_BUG << "Attempted to create connection ID of length " << length;
length = kQuicMaxConnectionIdLength;
}
length_ = length;
if (length_ == 0) {
return;
}
if (!GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
memcpy(data_, data, length_);
return;
}
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 1, 6);
if (length_ <= sizeof(data_short_)) {
memcpy(data_short_, data, length_);
return;
}
data_long_ = reinterpret_cast<char*>(malloc(length_));
CHECK_NE(nullptr, data_long_);
memcpy(data_long_, data, length_);
}
QuicConnectionId::~QuicConnectionId() {
if (!GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
return;
}
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 2, 6);
if (length_ > sizeof(data_short_)) {
free(data_long_);
data_long_ = nullptr;
}
}
QuicConnectionId::QuicConnectionId(const QuicConnectionId& other)
: QuicConnectionId(other.data(), other.length()) {}
QuicConnectionId& QuicConnectionId::operator=(const QuicConnectionId& other) {
set_length(other.length());
memcpy(mutable_data(), other.data(), length_);
return *this;
}
const char* QuicConnectionId::data() const {
if (!GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
return data_;
}
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 3, 6);
if (length_ <= sizeof(data_short_)) {
return data_short_;
}
return data_long_;
}
char* QuicConnectionId::mutable_data() {
if (!GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
return data_;
}
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 4, 6);
if (length_ <= sizeof(data_short_)) {
return data_short_;
}
return data_long_;
}
uint8_t QuicConnectionId::length() const {
return length_;
}
void QuicConnectionId::set_length(uint8_t length) {
if (GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 5, 6);
char temporary_data[sizeof(data_short_)];
if (length > sizeof(data_short_)) {
if (length_ <= sizeof(data_short_)) {
// Copy data from data_short_ to data_long_.
memcpy(temporary_data, data_short_, length_);
data_long_ = reinterpret_cast<char*>(malloc(length));
CHECK_NE(nullptr, data_long_);
memcpy(data_long_, temporary_data, length_);
} else {
// Resize data_long_.
char* realloc_result =
reinterpret_cast<char*>(realloc(data_long_, length));
CHECK_NE(nullptr, realloc_result);
data_long_ = realloc_result;
}
} else if (length_ > sizeof(data_short_)) {
// Copy data from data_long_ to data_short_.
memcpy(temporary_data, data_long_, length);
free(data_long_);
data_long_ = nullptr;
memcpy(data_short_, temporary_data, length);
}
}
length_ = length;
}
bool QuicConnectionId::IsEmpty() const {
return length_ == 0;
}
size_t QuicConnectionId::Hash() const {
if (!GetQuicRestartFlag(quic_connection_id_use_siphash)) {
uint64_t data_bytes[3] = {0, 0, 0};
static_assert(sizeof(data_bytes) >= kQuicMaxConnectionIdLength,
"kQuicMaxConnectionIdLength changed");
memcpy(data_bytes, data(), length_);
// This Hash function is designed to return the same value as the host byte
// order representation when the connection ID length is 64 bits.
return QuicEndian::NetToHost64(kQuicDefaultConnectionIdLength ^ length_ ^
data_bytes[0] ^ data_bytes[1] ^
data_bytes[2]);
}
QUIC_RESTART_FLAG_COUNT(quic_connection_id_use_siphash);
static const QuicConnectionIdHasher hasher = QuicConnectionIdHasher();
return hasher.Hash(data(), length_);
}
std::string QuicConnectionId::ToString() const {
if (IsEmpty()) {
return std::string("0");
}
return QuicTextUtils::HexEncode(data(), length_);
}
std::ostream& operator<<(std::ostream& os, const QuicConnectionId& v) {
os << v.ToString();
return os;
}
bool QuicConnectionId::operator==(const QuicConnectionId& v) const {
return length_ == v.length_ && memcmp(data(), v.data(), length_) == 0;
}
bool QuicConnectionId::operator!=(const QuicConnectionId& v) const {
return !(v == *this);
}
bool QuicConnectionId::operator<(const QuicConnectionId& v) const {
if (length_ < v.length_) {
return true;
}
if (length_ > v.length_) {
return false;
}
return memcmp(data(), v.data(), length_) < 0;
}
QuicConnectionId EmptyQuicConnectionId() {
return QuicConnectionId();
}
static_assert(kQuicDefaultConnectionIdLength == sizeof(uint64_t),
"kQuicDefaultConnectionIdLength changed");
static_assert(kQuicDefaultConnectionIdLength == PACKET_8BYTE_CONNECTION_ID,
"kQuicDefaultConnectionIdLength changed");
} // namespace quic
<commit_msg>Remove redundant use of keyword explicit on QuicConnectionIdHasher default constructor<commit_after>// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "net/third_party/quiche/src/quic/core/quic_connection_id.h"
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <iomanip>
#include <string>
#include "third_party/boringssl/src/include/openssl/siphash.h"
#include "net/third_party/quiche/src/quic/core/crypto/quic_random.h"
#include "net/third_party/quiche/src/quic/core/quic_types.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_bug_tracker.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_endian.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flag_utils.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_flags.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_logging.h"
#include "net/third_party/quiche/src/quic/platform/api/quic_text_utils.h"
namespace quic {
namespace {
// QuicConnectionIdHasher can be used to generate a stable connection ID hash
// function that will return the same value for two equal connection IDs for
// the duration of process lifetime. It is meant to be used as input to data
// structures that do not outlast process lifetime. A new key is generated once
// per process to prevent attackers from crafting connection IDs in such a way
// that they always land in the same hash bucket.
class QuicConnectionIdHasher {
public:
inline QuicConnectionIdHasher()
: QuicConnectionIdHasher(QuicRandom::GetInstance()) {}
explicit inline QuicConnectionIdHasher(QuicRandom* random) {
random->RandBytes(&sip_hash_key_, sizeof(sip_hash_key_));
}
inline size_t Hash(const char* input, size_t input_len) const {
return static_cast<size_t>(SIPHASH_24(
sip_hash_key_, reinterpret_cast<const uint8_t*>(input), input_len));
}
private:
uint64_t sip_hash_key_[2];
};
} // namespace
QuicConnectionId::QuicConnectionId() : QuicConnectionId(nullptr, 0) {}
QuicConnectionId::QuicConnectionId(const char* data, uint8_t length) {
static_assert(
kQuicMaxConnectionIdLength <= std::numeric_limits<uint8_t>::max(),
"kQuicMaxConnectionIdLength too high");
if (length > kQuicMaxConnectionIdLength) {
QUIC_BUG << "Attempted to create connection ID of length " << length;
length = kQuicMaxConnectionIdLength;
}
length_ = length;
if (length_ == 0) {
return;
}
if (!GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
memcpy(data_, data, length_);
return;
}
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 1, 6);
if (length_ <= sizeof(data_short_)) {
memcpy(data_short_, data, length_);
return;
}
data_long_ = reinterpret_cast<char*>(malloc(length_));
CHECK_NE(nullptr, data_long_);
memcpy(data_long_, data, length_);
}
QuicConnectionId::~QuicConnectionId() {
if (!GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
return;
}
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 2, 6);
if (length_ > sizeof(data_short_)) {
free(data_long_);
data_long_ = nullptr;
}
}
QuicConnectionId::QuicConnectionId(const QuicConnectionId& other)
: QuicConnectionId(other.data(), other.length()) {}
QuicConnectionId& QuicConnectionId::operator=(const QuicConnectionId& other) {
set_length(other.length());
memcpy(mutable_data(), other.data(), length_);
return *this;
}
const char* QuicConnectionId::data() const {
if (!GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
return data_;
}
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 3, 6);
if (length_ <= sizeof(data_short_)) {
return data_short_;
}
return data_long_;
}
char* QuicConnectionId::mutable_data() {
if (!GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
return data_;
}
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 4, 6);
if (length_ <= sizeof(data_short_)) {
return data_short_;
}
return data_long_;
}
uint8_t QuicConnectionId::length() const {
return length_;
}
void QuicConnectionId::set_length(uint8_t length) {
if (GetQuicRestartFlag(quic_use_allocated_connection_ids)) {
QUIC_RESTART_FLAG_COUNT_N(quic_use_allocated_connection_ids, 5, 6);
char temporary_data[sizeof(data_short_)];
if (length > sizeof(data_short_)) {
if (length_ <= sizeof(data_short_)) {
// Copy data from data_short_ to data_long_.
memcpy(temporary_data, data_short_, length_);
data_long_ = reinterpret_cast<char*>(malloc(length));
CHECK_NE(nullptr, data_long_);
memcpy(data_long_, temporary_data, length_);
} else {
// Resize data_long_.
char* realloc_result =
reinterpret_cast<char*>(realloc(data_long_, length));
CHECK_NE(nullptr, realloc_result);
data_long_ = realloc_result;
}
} else if (length_ > sizeof(data_short_)) {
// Copy data from data_long_ to data_short_.
memcpy(temporary_data, data_long_, length);
free(data_long_);
data_long_ = nullptr;
memcpy(data_short_, temporary_data, length);
}
}
length_ = length;
}
bool QuicConnectionId::IsEmpty() const {
return length_ == 0;
}
size_t QuicConnectionId::Hash() const {
if (!GetQuicRestartFlag(quic_connection_id_use_siphash)) {
uint64_t data_bytes[3] = {0, 0, 0};
static_assert(sizeof(data_bytes) >= kQuicMaxConnectionIdLength,
"kQuicMaxConnectionIdLength changed");
memcpy(data_bytes, data(), length_);
// This Hash function is designed to return the same value as the host byte
// order representation when the connection ID length is 64 bits.
return QuicEndian::NetToHost64(kQuicDefaultConnectionIdLength ^ length_ ^
data_bytes[0] ^ data_bytes[1] ^
data_bytes[2]);
}
QUIC_RESTART_FLAG_COUNT(quic_connection_id_use_siphash);
static const QuicConnectionIdHasher hasher = QuicConnectionIdHasher();
return hasher.Hash(data(), length_);
}
std::string QuicConnectionId::ToString() const {
if (IsEmpty()) {
return std::string("0");
}
return QuicTextUtils::HexEncode(data(), length_);
}
std::ostream& operator<<(std::ostream& os, const QuicConnectionId& v) {
os << v.ToString();
return os;
}
bool QuicConnectionId::operator==(const QuicConnectionId& v) const {
return length_ == v.length_ && memcmp(data(), v.data(), length_) == 0;
}
bool QuicConnectionId::operator!=(const QuicConnectionId& v) const {
return !(v == *this);
}
bool QuicConnectionId::operator<(const QuicConnectionId& v) const {
if (length_ < v.length_) {
return true;
}
if (length_ > v.length_) {
return false;
}
return memcmp(data(), v.data(), length_) < 0;
}
QuicConnectionId EmptyQuicConnectionId() {
return QuicConnectionId();
}
static_assert(kQuicDefaultConnectionIdLength == sizeof(uint64_t),
"kQuicDefaultConnectionIdLength changed");
static_assert(kQuicDefaultConnectionIdLength == PACKET_8BYTE_CONNECTION_ID,
"kQuicDefaultConnectionIdLength changed");
} // namespace quic
<|endoftext|>
|
<commit_before>#include <string>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <unistd.h>
#include <boost/format.hpp>
#include <SDL2/SDL.h>
static const int WIDTH = 32 * 6;
static const int HEIGHT = 64 * 3;
static const int WHEEL_DIA = 16;
static const int TIMEOUT = 3000;
static const float PI = 3.14159265358979f;
static const float DIST_PER_REV = WHEEL_DIA * PI / 5280 / 12;
static const float VELO_FALLOFF = 0.0005f;
// TODO pass at runtime
static const std::string SERIAL = "/dev/cu.usbmodem12341";
struct Stats {
float dist, time, velo;
unsigned long last_rev, next_rev;
};
void draw_text(SDL_Renderer* renderer, SDL_Texture* texture, int x, int y, std::string text) {
SDL_Rect source = { 0, 0, 0, 64 };
SDL_Rect dest = { x, y, 0, 64 };
for (std::string::iterator i = text.begin(); i != text.end(); ++i) {
if ((*i) >= '0' && (*i) <= '9') {
source.x = ((*i) - '/') * 32;
source.w = dest.w = 32;
} else if ((*i) == ' ') {
source.x = 0;
source.w = dest.w = 32;
} else if ((*i) == ':') {
source.x = 352;
source.w = dest.w = 16;
} else if ((*i) == '.') {
source.x = 368;
source.w = dest.w = 16;
}
SDL_RenderCopy(renderer, texture, &source, &dest);
dest.x += source.w;
}
}
void draw_rect(SDL_Renderer* renderer, SDL_Texture* texture, int dx, int dy, int sx, int sy, int w, int h) {
SDL_Rect source = {sx, sy, w, h};
SDL_Rect dest = {dx, dy, w, h};
SDL_RenderCopy(renderer, texture, &source, &dest);
}
void draw(SDL_Renderer* renderer, SDL_Texture* texture, Stats* stats) {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
long sec = lroundf(stats->time);
draw_text(renderer, texture, 0, 0, boost::str(boost::format("%4.1f") % stats->velo));
draw_text(renderer, texture, 0, 64, boost::str(boost::format("%5.2f") % stats->dist));
draw_text(renderer, texture, 0, 128, boost::str(boost::format("%u:%02u:%02u") % (sec / 3600) % ((sec / 60) % 60) % (sec % 60)));
draw_rect(renderer, texture, 132, 0, 384, 0, 64, 64);
draw_rect(renderer, texture, 160, 64, 448, 0, 32, 64);
SDL_RenderPresent(renderer);
}
void handle_rev(int rpm, Stats* stats) {
unsigned long current = SDL_GetTicks();
long elapsed = current - stats->last_rev;
if (elapsed < TIMEOUT) {
stats->dist += DIST_PER_REV;
stats->velo = rpm * 60 * DIST_PER_REV;
fprintf(stderr, "Revolution! v:%.2f\n", stats->velo);
if (stats->velo > 0.0f) {
float next = DIST_PER_REV / stats->velo;
fprintf(stderr, "Next rev in %.3f seconds\n", next * 3600);
stats->next_rev = current + lroundf(next * 3600000);
} else {
stats->next_rev = 0;
}
} else {
stats->velo = 0;
fprintf(stderr, "Timeout!\n");
}
stats->last_rev = current;
}
int main() {
SDL_Window* window = SDL_CreateWindow("Bike Stats", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, 0);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
SDL_Surface* surface = SDL_LoadBMP("sprites.bmp");
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_Event event;
bool running = true;
int serial = open(SERIAL.c_str(), O_RDONLY | O_NONBLOCK);
if (serial == -1) {
fprintf(stderr, "Error opening serial device %s: %u\n", SERIAL.c_str(), errno);
return -1;
}
long last_tick = 0;
Stats stats = { 0.0f, 0.0f, 0.0f, 0, 0 };
char buffer[256];
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) running = false;
}
ssize_t bytes = read(serial, buffer, 256);
if (bytes > 0) {
int rpm = atoi(buffer);
fprintf(stderr, "Got RPM %u\n", rpm);
handle_rev(rpm, &stats);
} else if (bytes == 0) {
// ignore this and continue
// fprintf(stderr, "EOF on serial device\n");
// break;
} else if (errno != EAGAIN) {
fprintf(stderr, "Error reading from serial device: %u\n", errno);
break;
}
long current = SDL_GetTicks();
long elapsed = current - last_tick;
if (stats.velo > 0.0f) stats.time += elapsed / 1000.0f;
last_tick = current;
if (current > stats.next_rev) {
stats.velo -= VELO_FALLOFF;
if (stats.velo < 0.0f) stats.velo = 0.0f;
}
draw(renderer, texture, &stats);
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
return 0;
}
<commit_msg>Fix signed compare warning<commit_after>#include <string>
#include <errno.h>
#include <fcntl.h>
#include <math.h>
#include <unistd.h>
#include <boost/format.hpp>
#include <SDL2/SDL.h>
static const int WIDTH = 32 * 6;
static const int HEIGHT = 64 * 3;
static const int WHEEL_DIA = 16;
static const int TIMEOUT = 3000;
static const float PI = 3.14159265358979f;
static const float DIST_PER_REV = WHEEL_DIA * PI / 5280 / 12;
static const float VELO_FALLOFF = 0.0005f;
// TODO pass at runtime
static const std::string SERIAL = "/dev/cu.usbmodem12341";
struct Stats {
float dist, time, velo;
unsigned long last_rev, next_rev;
};
void draw_text(SDL_Renderer* renderer, SDL_Texture* texture, int x, int y, std::string text) {
SDL_Rect source = { 0, 0, 0, 64 };
SDL_Rect dest = { x, y, 0, 64 };
for (std::string::iterator i = text.begin(); i != text.end(); ++i) {
if ((*i) >= '0' && (*i) <= '9') {
source.x = ((*i) - '/') * 32;
source.w = dest.w = 32;
} else if ((*i) == ' ') {
source.x = 0;
source.w = dest.w = 32;
} else if ((*i) == ':') {
source.x = 352;
source.w = dest.w = 16;
} else if ((*i) == '.') {
source.x = 368;
source.w = dest.w = 16;
}
SDL_RenderCopy(renderer, texture, &source, &dest);
dest.x += source.w;
}
}
void draw_rect(SDL_Renderer* renderer, SDL_Texture* texture, int dx, int dy, int sx, int sy, int w, int h) {
SDL_Rect source = {sx, sy, w, h};
SDL_Rect dest = {dx, dy, w, h};
SDL_RenderCopy(renderer, texture, &source, &dest);
}
void draw(SDL_Renderer* renderer, SDL_Texture* texture, Stats* stats) {
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
SDL_RenderClear(renderer);
long sec = lroundf(stats->time);
draw_text(renderer, texture, 0, 0, boost::str(boost::format("%4.1f") % stats->velo));
draw_text(renderer, texture, 0, 64, boost::str(boost::format("%5.2f") % stats->dist));
draw_text(renderer, texture, 0, 128, boost::str(boost::format("%u:%02u:%02u") % (sec / 3600) % ((sec / 60) % 60) % (sec % 60)));
draw_rect(renderer, texture, 132, 0, 384, 0, 64, 64);
draw_rect(renderer, texture, 160, 64, 448, 0, 32, 64);
SDL_RenderPresent(renderer);
}
void handle_rev(int rpm, Stats* stats) {
unsigned long current = SDL_GetTicks();
long elapsed = current - stats->last_rev;
if (elapsed < TIMEOUT) {
stats->dist += DIST_PER_REV;
stats->velo = rpm * 60 * DIST_PER_REV;
fprintf(stderr, "Revolution! v:%.2f\n", stats->velo);
if (stats->velo > 0.0f) {
float next = DIST_PER_REV / stats->velo;
fprintf(stderr, "Next rev in %.3f seconds\n", next * 3600);
stats->next_rev = current + lroundf(next * 3600000);
} else {
stats->next_rev = 0;
}
} else {
stats->velo = 0;
fprintf(stderr, "Timeout!\n");
}
stats->last_rev = current;
}
int main() {
SDL_Window* window = SDL_CreateWindow("Bike Stats", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, WIDTH, HEIGHT, 0);
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, 0);
SDL_Surface* surface = SDL_LoadBMP("sprites.bmp");
SDL_Texture* texture = SDL_CreateTextureFromSurface(renderer, surface);
SDL_Event event;
bool running = true;
int serial = open(SERIAL.c_str(), O_RDONLY | O_NONBLOCK);
if (serial == -1) {
fprintf(stderr, "Error opening serial device %s: %u\n", SERIAL.c_str(), errno);
return -1;
}
long last_tick = 0;
Stats stats = { 0.0f, 0.0f, 0.0f, 0, 0 };
char buffer[256];
while (running) {
while (SDL_PollEvent(&event)) {
if (event.type == SDL_QUIT) running = false;
}
ssize_t bytes = read(serial, buffer, 256);
if (bytes > 0) {
int rpm = atoi(buffer);
fprintf(stderr, "Got RPM %u\n", rpm);
handle_rev(rpm, &stats);
} else if (bytes == 0) {
// ignore this and continue
// fprintf(stderr, "EOF on serial device\n");
// break;
} else if (errno != EAGAIN) {
fprintf(stderr, "Error reading from serial device: %u\n", errno);
break;
}
unsigned long current = SDL_GetTicks();
unsigned long elapsed = current - last_tick;
if (stats.velo > 0.0f) stats.time += elapsed / 1000.0f;
last_tick = current;
if (current > stats.next_rev) {
stats.velo -= VELO_FALLOFF;
if (stats.velo < 0.0f) stats.velo = 0.0f;
}
draw(renderer, texture, &stats);
}
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
return 0;
}
<|endoftext|>
|
<commit_before>#include "mdist.hpp"
#include <cstdlib>
TilesMdist::TilesMdist(FILE *in) : Tiles(in) {
initmd();
initincr();
}
TilesMdist::State TilesMdist::initialstate(void) {
State s;
s.h = 0;
for (unsigned int i = 0; i < Ntiles; i++) {
if (init[i] == 0)
s.b = i;
else
s.h += md[init[i]][i];
s.ts[i] = init[i];
}
return s;
}
void TilesMdist::initmd(void) {
for (unsigned int t = 1; t < Ntiles; t++) {
unsigned int row = goalpos[t] / Width;
unsigned int col = goalpos[t] % Width;
for (int i = 0; i < Ntiles; i++) {
unsigned int r = i / Width;
unsigned int c = i % Width;
md[t][i] = abs(r - row) + abs(c - col);
}
}
}
void TilesMdist::initincr(void) {
for (unsigned int t = 1; t < Ntiles; t++) {
for (unsigned int old = 0; old < Ntiles; old++) {
unsigned int cur = md[t][old];
for (unsigned int n = 0; n <ops[old].n; n++) {
unsigned int nw = ops[old].mvs[n];
incr[t][old][nw] = md[t][nw] - cur;
}
}
}
}<commit_msg>tiles: rename some local varaibles that were named wrong.<commit_after>#include "mdist.hpp"
#include <cstdlib>
TilesMdist::TilesMdist(FILE *in) : Tiles(in) {
initmd();
initincr();
}
TilesMdist::State TilesMdist::initialstate(void) {
State s;
s.h = 0;
for (unsigned int i = 0; i < Ntiles; i++) {
if (init[i] == 0)
s.b = i;
else
s.h += md[init[i]][i];
s.ts[i] = init[i];
}
return s;
}
void TilesMdist::initmd(void) {
for (unsigned int t = 1; t < Ntiles; t++) {
unsigned int row = goalpos[t] / Width;
unsigned int col = goalpos[t] % Width;
for (int i = 0; i < Ntiles; i++) {
unsigned int r = i / Width;
unsigned int c = i % Width;
md[t][i] = abs(r - row) + abs(c - col);
}
}
}
void TilesMdist::initincr(void) {
for (unsigned int t = 1; t < Ntiles; t++) {
for (unsigned int nw = 0; nw < Ntiles; nw++) {
unsigned int next = md[t][nw];
for (unsigned int n = 0; n <ops[nw].n; n++) {
unsigned int old = ops[nw].mvs[n];
incr[t][nw][old] = md[t][old] - next;
}
}
}
}<|endoftext|>
|
<commit_before>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2012 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "module.hh"
#include "agent.hh"
#include "event.hh"
#include "transaction.hh"
#include "apn/pushnotification.h"
#include "apn/pushnotificationservice.h"
using namespace ::std;
class PushNotificationContext {
private:
su_timer_t* mTimer;
PushNotificationService * mPNS;
shared_ptr<PushNotificationRequest> mPushNotificationRequest;
public:
PushNotificationContext(shared_ptr<OutgoingTransaction> &transaction, PushNotificationService * pns, const shared_ptr<PushNotificationRequest> &pnr);
~PushNotificationContext();
void start(int seconds);
void onTimeout();
static void __timer_callback(su_root_magic_t *magic, su_timer_t *t, su_timer_arg_t *arg);
};
PushNotificationContext::PushNotificationContext(shared_ptr<OutgoingTransaction> &transaction, PushNotificationService * pns, const shared_ptr<PushNotificationRequest> &pnr) :
mPNS(pns), mPushNotificationRequest(pnr) {
LOGD("New PushNotificationContext %p", this);
mTimer = su_timer_create(su_root_task(transaction->getAgent()->getRoot()), 0);
}
PushNotificationContext::~PushNotificationContext() {
su_timer_destroy(mTimer);
LOGD("Destroy PushNotificationContext %p", this);
}
void PushNotificationContext::start(int seconds) {
su_timer_set_interval(mTimer, &PushNotificationContext::__timer_callback, this, seconds * 1000);
}
void PushNotificationContext::onTimeout() {
LOGD("PushNotificationContext timeout!");
mPNS->sendRequest(mPushNotificationRequest);
}
void PushNotificationContext::__timer_callback(su_root_magic_t *magic, su_timer_t *t, su_timer_arg_t *arg) {
PushNotificationContext *context = (PushNotificationContext*) arg;
context->onTimeout();
}
class PushNotification: public Module, public ModuleToolbox {
public:
PushNotification(Agent *ag);
virtual ~PushNotification();
void onDeclare(GenericStruct *module_config);
virtual void onTransactionEvent(const shared_ptr<Transaction> &transaction, Transaction::Event event);
virtual void onRequest(std::shared_ptr<RequestSipEvent> &ev);
virtual void onResponse(std::shared_ptr<ResponseSipEvent> &ev);
virtual void onLoad(const GenericStruct *mc);
private:
shared_ptr<PushNotificationRequest> makePushNotification(const shared_ptr<MsgSip> &ms);
static ModuleInfo<PushNotification> sInfo;
int mTimeout;
PushNotificationService *mAPNS;
};
ModuleInfo<PushNotification> PushNotification::sInfo("PushNotification", "This module performs push notifications", ModuleInfoBase::ModuleOid::PushNotification);
PushNotification::PushNotification(Agent *ag) :
Module(ag), mAPNS(NULL) {
}
PushNotification::~PushNotification() {
if (mAPNS != NULL) {
mAPNS->stop();
delete mAPNS;
}
}
void PushNotification::onDeclare(GenericStruct *module_config) {
module_config->get<ConfigBoolean>("enabled")->setDefault("false");
ConfigItemDescriptor items[] = {
{ Integer, "timeout", "Number of second to wait before sending a push notification to device(if <=0 then disabled)", "5" },
{ Boolean, "apple", "Enable push notificaction for apple devices", "true" },
{ String, "apple-certificate-dir", "Path to directory where to find Apple Push Notification service certificates. They should bear the appid of the application, suffixed by the release mode and .pem extension. For example: org.linphone.dev.pem org.linphone.prod.pem com.somephone.dev.pem etc..."
" The files should be .pem format, and made of certificate followed by private key." , "/etc/flexisip/apn" },
config_item_end };
module_config->addChildrenValues(items);
}
void PushNotification::onLoad(const GenericStruct *mc) {
mTimeout = mc->get<ConfigInt>("timeout")->read();
string cafile = mc->get<ConfigString>("apple-ca")->read();
string certdir = mc->get<ConfigString>("apple-certificate-dir")->read();
mAPNS = new PushNotificationService( certdir, cafile);
mAPNS->start();
}
shared_ptr<PushNotificationRequest> PushNotification::makePushNotification(const shared_ptr<MsgSip> &ms){
sip_t *sip=ms->getSip();
if (sip->sip_request->rq_url != NULL && sip->sip_request->rq_url->url_params != NULL){
char type[12];
char deviceToken[65];
char appId[256]={0};
char msg_str[64];
char call_str[64];
char call_snd[64];
char msg_snd[64];
char const *params=sip->sip_request->rq_url->url_params;
/*extract all parameters required to make the push notification */
if (!url_param(params, "pn-type", type, sizeof(type)))
return 0;
if (!url_param(params, "app-id", appId, sizeof(appId)))
return 0;
if (url_param(params, "pn-tok", deviceToken, sizeof(deviceToken)) != sizeof(deviceToken))
return 0;
if (!url_param(params, "pn-msg-str", msg_str, sizeof(msg_str))) {
return 0;
}
if (!url_param(params, "pn-call-str", call_str, sizeof(call_str))){
return 0;
}
if (!url_param(params, "pn-call-snd", call_snd, sizeof(call_snd))){
return 0;
}
if (!url_param(params, "pn-msg-snd", msg_snd, sizeof(msg_snd))){
return 0;
}
string contact;
if(sip->sip_from->a_display != NULL && strlen(sip->sip_from->a_display) > 0) {
contact = sip->sip_from->a_display;
} else {
contact = url_as_string(ms->getHome(), sip->sip_from->a_url);
}
if (strcmp(type,"apple")==0){
return make_shared<ApplePushNotificationRequest>(appId,deviceToken,
(sip->sip_request->rq_method == sip_method_invite) ? call_str : msg_str,
contact,
(sip->sip_request->rq_method == sip_method_invite) ? call_snd : msg_snd);
}else if (strcmp(type,"google")==0){
//TODO
}
}
return 0;
}
void PushNotification::onRequest(std::shared_ptr<RequestSipEvent> &ev) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
sip_t *sip=ms->getSip();
if ((sip->sip_request->rq_method == sip_method_invite ||
sip->sip_request->rq_method == sip_method_message) &&
sip->sip_to && sip->sip_to->a_tag==NULL){
shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(ev->getOutgoingAgent());
if (transaction != NULL) {
sip_t *sip = ms->getSip();
if (sip->sip_request->rq_url != NULL && sip->sip_request->rq_url->url_params != NULL) {
try{
shared_ptr<PushNotificationRequest> request = makePushNotification(ms);
if (request){
shared_ptr<PushNotificationContext> context = make_shared<PushNotificationContext>(transaction, mAPNS, request);
context->start(mTimeout);
transaction->setProperty(getModuleName(), context);
}
}catch(exception &e){
LOGE("Could not create push notification.");
}
}
}
}
}
void PushNotification::onResponse(std::shared_ptr<ResponseSipEvent> &ev) {
shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(ev->getOutgoingAgent());
if (transaction != NULL) {
transaction->removeProperty(getModuleName());
}
}
void PushNotification::onTransactionEvent(const shared_ptr<Transaction> &transaction, Transaction::Event event) {
shared_ptr<OutgoingTransaction> ot = dynamic_pointer_cast<OutgoingTransaction>(transaction);
if (ot != NULL) {
switch (event) {
case Transaction::Destroy:
transaction->removeProperty(getModuleName());
break;
case Transaction::Create:
break;
}
}
}
<commit_msg>fix invalid read of parameter<commit_after>/*
Flexisip, a flexible SIP proxy server with media capabilities.
Copyright (C) 2012 Belledonne Communications SARL.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "module.hh"
#include "agent.hh"
#include "event.hh"
#include "transaction.hh"
#include "apn/pushnotification.h"
#include "apn/pushnotificationservice.h"
using namespace ::std;
class PushNotificationContext {
private:
su_timer_t* mTimer;
PushNotificationService * mPNS;
shared_ptr<PushNotificationRequest> mPushNotificationRequest;
public:
PushNotificationContext(shared_ptr<OutgoingTransaction> &transaction, PushNotificationService * pns, const shared_ptr<PushNotificationRequest> &pnr);
~PushNotificationContext();
void start(int seconds);
void onTimeout();
static void __timer_callback(su_root_magic_t *magic, su_timer_t *t, su_timer_arg_t *arg);
};
PushNotificationContext::PushNotificationContext(shared_ptr<OutgoingTransaction> &transaction, PushNotificationService * pns, const shared_ptr<PushNotificationRequest> &pnr) :
mPNS(pns), mPushNotificationRequest(pnr) {
LOGD("New PushNotificationContext %p", this);
mTimer = su_timer_create(su_root_task(transaction->getAgent()->getRoot()), 0);
}
PushNotificationContext::~PushNotificationContext() {
su_timer_destroy(mTimer);
LOGD("Destroy PushNotificationContext %p", this);
}
void PushNotificationContext::start(int seconds) {
su_timer_set_interval(mTimer, &PushNotificationContext::__timer_callback, this, seconds * 1000);
}
void PushNotificationContext::onTimeout() {
LOGD("PushNotificationContext timeout!");
mPNS->sendRequest(mPushNotificationRequest);
}
void PushNotificationContext::__timer_callback(su_root_magic_t *magic, su_timer_t *t, su_timer_arg_t *arg) {
PushNotificationContext *context = (PushNotificationContext*) arg;
context->onTimeout();
}
class PushNotification: public Module, public ModuleToolbox {
public:
PushNotification(Agent *ag);
virtual ~PushNotification();
void onDeclare(GenericStruct *module_config);
virtual void onTransactionEvent(const shared_ptr<Transaction> &transaction, Transaction::Event event);
virtual void onRequest(std::shared_ptr<RequestSipEvent> &ev);
virtual void onResponse(std::shared_ptr<ResponseSipEvent> &ev);
virtual void onLoad(const GenericStruct *mc);
private:
shared_ptr<PushNotificationRequest> makePushNotification(const shared_ptr<MsgSip> &ms);
static ModuleInfo<PushNotification> sInfo;
int mTimeout;
PushNotificationService *mAPNS;
};
ModuleInfo<PushNotification> PushNotification::sInfo("PushNotification", "This module performs push notifications", ModuleInfoBase::ModuleOid::PushNotification);
PushNotification::PushNotification(Agent *ag) :
Module(ag), mAPNS(NULL) {
}
PushNotification::~PushNotification() {
if (mAPNS != NULL) {
mAPNS->stop();
delete mAPNS;
}
}
void PushNotification::onDeclare(GenericStruct *module_config) {
module_config->get<ConfigBoolean>("enabled")->setDefault("false");
ConfigItemDescriptor items[] = {
{ Integer, "timeout", "Number of second to wait before sending a push notification to device(if <=0 then disabled)", "5" },
{ Boolean, "apple", "Enable push notificaction for apple devices", "true" },
{ String, "apple-certificate-dir", "Path to directory where to find Apple Push Notification service certificates. They should bear the appid of the application, suffixed by the release mode and .pem extension. For example: org.linphone.dev.pem org.linphone.prod.pem com.somephone.dev.pem etc..."
" The files should be .pem format, and made of certificate followed by private key." , "/etc/flexisip/apn" },
config_item_end };
module_config->addChildrenValues(items);
}
void PushNotification::onLoad(const GenericStruct *mc) {
mTimeout = mc->get<ConfigInt>("timeout")->read();
string certdir = mc->get<ConfigString>("apple-certificate-dir")->read();
mAPNS = new PushNotificationService( certdir, "");
mAPNS->start();
}
shared_ptr<PushNotificationRequest> PushNotification::makePushNotification(const shared_ptr<MsgSip> &ms){
sip_t *sip=ms->getSip();
if (sip->sip_request->rq_url != NULL && sip->sip_request->rq_url->url_params != NULL){
char type[12];
char deviceToken[65];
char appId[256]={0};
char msg_str[64];
char call_str[64];
char call_snd[64];
char msg_snd[64];
char const *params=sip->sip_request->rq_url->url_params;
/*extract all parameters required to make the push notification */
if (!url_param(params, "pn-type", type, sizeof(type)))
return 0;
if (!url_param(params, "app-id", appId, sizeof(appId)))
return 0;
if (url_param(params, "pn-tok", deviceToken, sizeof(deviceToken)) != sizeof(deviceToken))
return 0;
if (!url_param(params, "pn-msg-str", msg_str, sizeof(msg_str))) {
return 0;
}
if (!url_param(params, "pn-call-str", call_str, sizeof(call_str))){
return 0;
}
if (!url_param(params, "pn-call-snd", call_snd, sizeof(call_snd))){
return 0;
}
if (!url_param(params, "pn-msg-snd", msg_snd, sizeof(msg_snd))){
return 0;
}
string contact;
if(sip->sip_from->a_display != NULL && strlen(sip->sip_from->a_display) > 0) {
contact = sip->sip_from->a_display;
} else {
contact = url_as_string(ms->getHome(), sip->sip_from->a_url);
}
if (strcmp(type,"apple")==0){
return make_shared<ApplePushNotificationRequest>(appId,deviceToken,
(sip->sip_request->rq_method == sip_method_invite) ? call_str : msg_str,
contact,
(sip->sip_request->rq_method == sip_method_invite) ? call_snd : msg_snd);
}else if (strcmp(type,"google")==0){
//TODO
}
}
return 0;
}
void PushNotification::onRequest(std::shared_ptr<RequestSipEvent> &ev) {
const shared_ptr<MsgSip> &ms = ev->getMsgSip();
sip_t *sip=ms->getSip();
if ((sip->sip_request->rq_method == sip_method_invite ||
sip->sip_request->rq_method == sip_method_message) &&
sip->sip_to && sip->sip_to->a_tag==NULL){
shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(ev->getOutgoingAgent());
if (transaction != NULL) {
sip_t *sip = ms->getSip();
if (sip->sip_request->rq_url != NULL && sip->sip_request->rq_url->url_params != NULL) {
try{
shared_ptr<PushNotificationRequest> request = makePushNotification(ms);
if (request){
shared_ptr<PushNotificationContext> context = make_shared<PushNotificationContext>(transaction, mAPNS, request);
context->start(mTimeout);
transaction->setProperty(getModuleName(), context);
}
}catch(exception &e){
LOGE("Could not create push notification.");
}
}
}
}
}
void PushNotification::onResponse(std::shared_ptr<ResponseSipEvent> &ev) {
shared_ptr<OutgoingTransaction> transaction = dynamic_pointer_cast<OutgoingTransaction>(ev->getOutgoingAgent());
if (transaction != NULL) {
transaction->removeProperty(getModuleName());
}
}
void PushNotification::onTransactionEvent(const shared_ptr<Transaction> &transaction, Transaction::Event event) {
shared_ptr<OutgoingTransaction> ot = dynamic_pointer_cast<OutgoingTransaction>(transaction);
if (ot != NULL) {
switch (event) {
case Transaction::Destroy:
transaction->removeProperty(getModuleName());
break;
case Transaction::Create:
break;
}
}
}
<|endoftext|>
|
<commit_before>#include "openmc/source.h"
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#define HAS_DYNAMIC_LINKING
#endif
#include <algorithm> // for move
#ifdef HAS_DYNAMIC_LINKING
#include <dlfcn.h> // for dlopen, dlsym, dlclose, dlerror
#endif
#include <fmt/core.h>
#include "xtensor/xadapt.hpp"
#include "openmc/bank.h"
#include "openmc/cell.h"
#include "openmc/error.h"
#include "openmc/file_utils.h"
#include "openmc/hdf5_interface.h"
#include "openmc/material.h"
#include "openmc/message_passing.h"
#include "openmc/mgxs_interface.h"
#include "openmc/nuclide.h"
#include "openmc/capi.h"
#include "openmc/random_lcg.h"
#include "openmc/search.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/state_point.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// Global variables
//==============================================================================
namespace model {
std::vector<SourceDistribution> external_sources;
}
namespace {
using sample_t = Particle::Bank (*)(uint64_t* seed);
sample_t custom_source_function;
void* custom_source_library;
}
//==============================================================================
// SourceDistribution implementation
//==============================================================================
SourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy)
: space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { }
SourceDistribution::SourceDistribution(pugi::xml_node node)
{
// Check for particle type
if (check_for_node(node, "particle")) {
auto temp_str = get_node_value(node, "particle", true, true);
if (temp_str == "neutron") {
particle_ = Particle::Type::neutron;
} else if (temp_str == "photon") {
particle_ = Particle::Type::photon;
settings::photon_transport = true;
} else {
fatal_error(std::string("Unknown source particle type: ") + temp_str);
}
}
// Check for source strength
if (check_for_node(node, "strength")) {
strength_ = std::stod(get_node_value(node, "strength"));
}
// Check for external source file
if (check_for_node(node, "file")) {
// Copy path of source file
settings::path_source = get_node_value(node, "file", false, true);
// Check if source file exists
if (!file_exists(settings::path_source)) {
fatal_error(fmt::format("Source file '{}' does not exist.",
settings::path_source));
}
} else if (check_for_node(node, "library")) {
settings::path_source_library = get_node_value(node, "library", false, true);
if (!file_exists(settings::path_source_library)) {
fatal_error(fmt::format("Source library '{}' does not exist.",
settings::path_source_library));
}
} else {
// Spatial distribution for external source
if (check_for_node(node, "space")) {
// Get pointer to spatial distribution
pugi::xml_node node_space = node.child("space");
// Check for type of spatial distribution and read
std::string type;
if (check_for_node(node_space, "type"))
type = get_node_value(node_space, "type", true, true);
if (type == "cartesian") {
space_ = UPtrSpace{new CartesianIndependent(node_space)};
} else if (type == "cylindrical") {
space_ = UPtrSpace{new CylindricalIndependent(node_space)};
} else if (type == "spherical") {
space_ = UPtrSpace{new SphericalIndependent(node_space)};
} else if (type == "box") {
space_ = UPtrSpace{new SpatialBox(node_space)};
} else if (type == "fission") {
space_ = UPtrSpace{new SpatialBox(node_space, true)};
} else if (type == "point") {
space_ = UPtrSpace{new SpatialPoint(node_space)};
} else {
fatal_error(fmt::format(
"Invalid spatial distribution for external source: {}", type));
}
} else {
// If no spatial distribution specified, make it a point source
space_ = UPtrSpace{new SpatialPoint()};
}
// Determine external source angular distribution
if (check_for_node(node, "angle")) {
// Get pointer to angular distribution
pugi::xml_node node_angle = node.child("angle");
// Check for type of angular distribution
std::string type;
if (check_for_node(node_angle, "type"))
type = get_node_value(node_angle, "type", true, true);
if (type == "isotropic") {
angle_ = UPtrAngle{new Isotropic()};
} else if (type == "monodirectional") {
angle_ = UPtrAngle{new Monodirectional(node_angle)};
} else if (type == "mu-phi") {
angle_ = UPtrAngle{new PolarAzimuthal(node_angle)};
} else {
fatal_error(fmt::format(
"Invalid angular distribution for external source: {}", type));
}
} else {
angle_ = UPtrAngle{new Isotropic()};
}
// Determine external source energy distribution
if (check_for_node(node, "energy")) {
pugi::xml_node node_dist = node.child("energy");
energy_ = distribution_from_xml(node_dist);
} else {
// Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)};
}
}
}
Particle::Bank SourceDistribution::sample(uint64_t* seed) const
{
Particle::Bank site;
// Set weight to one by default
site.wgt = 1.0;
// Repeat sampling source location until a good site has been found
bool found = false;
int n_reject = 0;
static int n_accept = 0;
while (!found) {
// Set particle type
site.particle = particle_;
// Sample spatial distribution
site.r = space_->sample(seed);
double xyz[] {site.r.x, site.r.y, site.r.z};
// Now search to see if location exists in geometry
int32_t cell_index, instance;
int err = openmc_find_cell(xyz, &cell_index, &instance);
found = (err != OPENMC_E_GEOMETRY);
// Check if spatial site is in fissionable material
if (found) {
auto space_box = dynamic_cast<SpatialBox*>(space_.get());
if (space_box) {
if (space_box->only_fissionable()) {
// Determine material
const auto& c = model::cells[cell_index];
auto mat_index = c->material_.size() == 1
? c->material_[0] : c->material_[instance];
if (mat_index == MATERIAL_VOID) {
found = false;
} else {
if (!model::materials[mat_index]->fissionable_) found = false;
}
}
}
}
// Check for rejection
if (!found) {
++n_reject;
if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
static_cast<double>(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) {
fatal_error("More than 95% of external source sites sampled were "
"rejected. Please check your external source definition.");
}
}
}
// Increment number of accepted samples
++n_accept;
// Sample angle
site.u = angle_->sample(seed);
// Check for monoenergetic source above maximum particle energy
auto p = static_cast<int>(particle_);
auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
if (energy_ptr) {
auto energies = xt::adapt(energy_ptr->x());
if (xt::any(energies > data::energy_max[p])) {
fatal_error("Source energy above range of energies of at least "
"one cross section table");
} else if (xt::any(energies < data::energy_min[p])) {
fatal_error("Source energy below range of energies of at least "
"one cross section table");
}
}
while (true) {
// Sample energy spectrum
site.E = energy_->sample(seed);
// Resample if energy falls outside minimum or maximum particle energy
if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break;
}
// Set delayed group
site.delayed_group = 0;
return site;
}
//==============================================================================
// Non-member functions
//==============================================================================
void initialize_source()
{
write_message("Initializing source particles...", 5);
if (!settings::path_source.empty()) {
// Read the source from a binary file instead of sampling from some
// assumed source distribution
write_message(fmt::format("Reading source file from {}...",
settings::path_source), 6);
// Open the binary file
hid_t file_id = file_open(settings::path_source, 'r', true);
// Read the file type
std::string filetype;
read_attribute(file_id, "filetype", filetype);
// Check to make sure this is a source file
if (filetype != "source" && filetype != "statepoint") {
fatal_error("Specified starting source file not a source file type.");
}
// Read in the source bank
read_source_bank(file_id);
// Close file
file_close(file_id);
} else if (!settings::path_source_library.empty()) {
write_message(fmt::format("Sampling from library source {}...",
settings::path_source), 6);
fill_source_bank_custom_source();
} else {
// Generation source sites from specified distribution in user input
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = simulation::total_gen*settings::n_particles +
simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample external source distribution
simulation::source_bank[i] = sample_external_source(&seed);
}
}
// Write out initial source
if (settings::write_initial_source) {
write_message("Writing out initial source...", 5);
std::string filename = settings::path_output + "initial_source.h5";
hid_t file_id = file_open(filename, 'w', true);
write_source_bank(file_id);
file_close(file_id);
}
}
Particle::Bank sample_external_source(uint64_t* seed)
{
// return values from custom source if using
if (!settings::path_source_library.empty()) {
return sample_custom_source_library(seed);
}
// Determine total source strength
double total_strength = 0.0;
for (auto& s : model::external_sources)
total_strength += s.strength();
// Sample from among multiple source distributions
int i = 0;
if (model::external_sources.size() > 1) {
double xi = prn(seed)*total_strength;
double c = 0.0;
for (; i < model::external_sources.size(); ++i) {
c += model::external_sources[i].strength();
if (xi < c) break;
}
}
// Sample source site from i-th source distribution
Particle::Bank site {model::external_sources[i].sample(seed)};
// If running in MG, convert site.E to group
if (!settings::run_CE) {
site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
data::mg.rev_energy_bins_.end(), site.E);
site.E = data::mg.num_energy_groups_ - site.E - 1.;
}
return site;
}
void free_memory_source()
{
model::external_sources.clear();
}
void load_custom_source_library()
{
#ifdef HAS_DYNAMIC_LINKING
// Open the library
custom_source_library = dlopen(settings::path_source_library.c_str(), RTLD_LAZY);
if (!custom_source_library) {
fatal_error("Couldn't open source library " + settings::path_source_library);
}
// reset errors
dlerror();
// get the function from the library
using sample_t = Particle::Bank (*)(uint64_t* seed);
custom_source_function = reinterpret_cast<sample_t>(dlsym(custom_source_library, "sample_source"));
// check for any dlsym errors
auto dlsym_error = dlerror();
if (dlsym_error) {
dlclose(custom_source_library);
fatal_error(fmt::format("Couldn't open the sample_source symbol: {}", dlsym_error));
}
#else
fatal_error("Custom source libraries have not yet been implemented for "
"non-POSIX systems");
#endif
}
void close_custom_source_library()
{
#ifdef HAS_DYNAMIC_LINKING
dlclose(custom_source_library);
#else
fatal_error("Custom source libraries have not yet been implemented for "
"non-POSIX systems");
#endif
}
Particle::Bank sample_custom_source_library(uint64_t* seed)
{
return custom_source_function(seed);
}
void fill_source_bank_custom_source()
{
// Load the custom library
load_custom_source_library();
// Generation source sites from specified distribution in the
// library source
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = (simulation::total_gen + overall_generation()) *
settings::n_particles + simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample custom library source
simulation::source_bank[i] = sample_custom_source_library(&seed);
}
// release the library
close_custom_source_library();
}
} // namespace openmc
<commit_msg>Load new serializable form of source function<commit_after>#include "openmc/source.h"
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#define HAS_DYNAMIC_LINKING
#endif
#include <algorithm> // for move
#ifdef HAS_DYNAMIC_LINKING
#include <dlfcn.h> // for dlopen, dlsym, dlclose, dlerror
#endif
#include <fmt/core.h>
#include "xtensor/xadapt.hpp"
#include "openmc/bank.h"
#include "openmc/cell.h"
#include "openmc/error.h"
#include "openmc/file_utils.h"
#include "openmc/hdf5_interface.h"
#include "openmc/material.h"
#include "openmc/message_passing.h"
#include "openmc/mgxs_interface.h"
#include "openmc/nuclide.h"
#include "openmc/capi.h"
#include "openmc/random_lcg.h"
#include "openmc/search.h"
#include "openmc/settings.h"
#include "openmc/simulation.h"
#include "openmc/state_point.h"
#include "openmc/xml_interface.h"
namespace openmc {
//==============================================================================
// Global variables
//==============================================================================
namespace model {
std::vector<SourceDistribution> external_sources;
}
namespace {
using sample_t = Particle::Bank (*)(uint64_t* seed);
sample_t custom_source_function;
std::string serialization;
using serialized_sample_t = Particle::Bank (*)(uint64_t* seed, const char* serialization);
serialized_sample_t custom_serialized_source_function;
void* custom_source_library;
}
//==============================================================================
// SourceDistribution implementation
//==============================================================================
SourceDistribution::SourceDistribution(UPtrSpace space, UPtrAngle angle, UPtrDist energy)
: space_{std::move(space)}, angle_{std::move(angle)}, energy_{std::move(energy)} { }
SourceDistribution::SourceDistribution(pugi::xml_node node)
{
// Check for particle type
if (check_for_node(node, "particle")) {
auto temp_str = get_node_value(node, "particle", true, true);
if (temp_str == "neutron") {
particle_ = Particle::Type::neutron;
} else if (temp_str == "photon") {
particle_ = Particle::Type::photon;
settings::photon_transport = true;
} else {
fatal_error(std::string("Unknown source particle type: ") + temp_str);
}
}
// Check for source strength
if (check_for_node(node, "strength")) {
strength_ = std::stod(get_node_value(node, "strength"));
}
// Check for external source file
if (check_for_node(node, "file")) {
// Copy path of source file
settings::path_source = get_node_value(node, "file", false, true);
// Check if source file exists
if (!file_exists(settings::path_source)) {
fatal_error(fmt::format("Source file '{}' does not exist.",
settings::path_source));
}
} else if (check_for_node(node, "library")) {
settings::path_source_library = get_node_value(node, "library", false, true);
if (!file_exists(settings::path_source_library)) {
fatal_error(fmt::format("Source library '{}' does not exist.",
settings::path_source_library));
}
if (check_for_node(node, "serialization")) {
serialization = get_node_value(node, "serialization", false, true);
}
} else {
// Spatial distribution for external source
if (check_for_node(node, "space")) {
// Get pointer to spatial distribution
pugi::xml_node node_space = node.child("space");
// Check for type of spatial distribution and read
std::string type;
if (check_for_node(node_space, "type"))
type = get_node_value(node_space, "type", true, true);
if (type == "cartesian") {
space_ = UPtrSpace{new CartesianIndependent(node_space)};
} else if (type == "cylindrical") {
space_ = UPtrSpace{new CylindricalIndependent(node_space)};
} else if (type == "spherical") {
space_ = UPtrSpace{new SphericalIndependent(node_space)};
} else if (type == "box") {
space_ = UPtrSpace{new SpatialBox(node_space)};
} else if (type == "fission") {
space_ = UPtrSpace{new SpatialBox(node_space, true)};
} else if (type == "point") {
space_ = UPtrSpace{new SpatialPoint(node_space)};
} else {
fatal_error(fmt::format(
"Invalid spatial distribution for external source: {}", type));
}
} else {
// If no spatial distribution specified, make it a point source
space_ = UPtrSpace{new SpatialPoint()};
}
// Determine external source angular distribution
if (check_for_node(node, "angle")) {
// Get pointer to angular distribution
pugi::xml_node node_angle = node.child("angle");
// Check for type of angular distribution
std::string type;
if (check_for_node(node_angle, "type"))
type = get_node_value(node_angle, "type", true, true);
if (type == "isotropic") {
angle_ = UPtrAngle{new Isotropic()};
} else if (type == "monodirectional") {
angle_ = UPtrAngle{new Monodirectional(node_angle)};
} else if (type == "mu-phi") {
angle_ = UPtrAngle{new PolarAzimuthal(node_angle)};
} else {
fatal_error(fmt::format(
"Invalid angular distribution for external source: {}", type));
}
} else {
angle_ = UPtrAngle{new Isotropic()};
}
// Determine external source energy distribution
if (check_for_node(node, "energy")) {
pugi::xml_node node_dist = node.child("energy");
energy_ = distribution_from_xml(node_dist);
} else {
// Default to a Watt spectrum with parameters 0.988 MeV and 2.249 MeV^-1
energy_ = UPtrDist{new Watt(0.988e6, 2.249e-6)};
}
}
}
Particle::Bank SourceDistribution::sample(uint64_t* seed) const
{
Particle::Bank site;
// Set weight to one by default
site.wgt = 1.0;
// Repeat sampling source location until a good site has been found
bool found = false;
int n_reject = 0;
static int n_accept = 0;
while (!found) {
// Set particle type
site.particle = particle_;
// Sample spatial distribution
site.r = space_->sample(seed);
double xyz[] {site.r.x, site.r.y, site.r.z};
// Now search to see if location exists in geometry
int32_t cell_index, instance;
int err = openmc_find_cell(xyz, &cell_index, &instance);
found = (err != OPENMC_E_GEOMETRY);
// Check if spatial site is in fissionable material
if (found) {
auto space_box = dynamic_cast<SpatialBox*>(space_.get());
if (space_box) {
if (space_box->only_fissionable()) {
// Determine material
const auto& c = model::cells[cell_index];
auto mat_index = c->material_.size() == 1
? c->material_[0] : c->material_[instance];
if (mat_index == MATERIAL_VOID) {
found = false;
} else {
if (!model::materials[mat_index]->fissionable_) found = false;
}
}
}
}
// Check for rejection
if (!found) {
++n_reject;
if (n_reject >= EXTSRC_REJECT_THRESHOLD &&
static_cast<double>(n_accept)/n_reject <= EXTSRC_REJECT_FRACTION) {
fatal_error("More than 95% of external source sites sampled were "
"rejected. Please check your external source definition.");
}
}
}
// Increment number of accepted samples
++n_accept;
// Sample angle
site.u = angle_->sample(seed);
// Check for monoenergetic source above maximum particle energy
auto p = static_cast<int>(particle_);
auto energy_ptr = dynamic_cast<Discrete*>(energy_.get());
if (energy_ptr) {
auto energies = xt::adapt(energy_ptr->x());
if (xt::any(energies > data::energy_max[p])) {
fatal_error("Source energy above range of energies of at least "
"one cross section table");
} else if (xt::any(energies < data::energy_min[p])) {
fatal_error("Source energy below range of energies of at least "
"one cross section table");
}
}
while (true) {
// Sample energy spectrum
site.E = energy_->sample(seed);
// Resample if energy falls outside minimum or maximum particle energy
if (site.E < data::energy_max[p] && site.E > data::energy_min[p]) break;
}
// Set delayed group
site.delayed_group = 0;
return site;
}
//==============================================================================
// Non-member functions
//==============================================================================
void initialize_source()
{
write_message("Initializing source particles...", 5);
if (!settings::path_source.empty()) {
// Read the source from a binary file instead of sampling from some
// assumed source distribution
write_message(fmt::format("Reading source file from {}...",
settings::path_source), 6);
// Open the binary file
hid_t file_id = file_open(settings::path_source, 'r', true);
// Read the file type
std::string filetype;
read_attribute(file_id, "filetype", filetype);
// Check to make sure this is a source file
if (filetype != "source" && filetype != "statepoint") {
fatal_error("Specified starting source file not a source file type.");
}
// Read in the source bank
read_source_bank(file_id);
// Close file
file_close(file_id);
} else if (!settings::path_source_library.empty()) {
write_message(fmt::format("Sampling from library source {}...",
settings::path_source), 6);
fill_source_bank_custom_source();
} else {
// Generation source sites from specified distribution in user input
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = simulation::total_gen*settings::n_particles +
simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample external source distribution
simulation::source_bank[i] = sample_external_source(&seed);
}
}
// Write out initial source
if (settings::write_initial_source) {
write_message("Writing out initial source...", 5);
std::string filename = settings::path_output + "initial_source.h5";
hid_t file_id = file_open(filename, 'w', true);
write_source_bank(file_id);
file_close(file_id);
}
}
Particle::Bank sample_external_source(uint64_t* seed)
{
// return values from custom source if using
if (!settings::path_source_library.empty()) {
return sample_custom_source_library(seed);
}
// Determine total source strength
double total_strength = 0.0;
for (auto& s : model::external_sources)
total_strength += s.strength();
// Sample from among multiple source distributions
int i = 0;
if (model::external_sources.size() > 1) {
double xi = prn(seed)*total_strength;
double c = 0.0;
for (; i < model::external_sources.size(); ++i) {
c += model::external_sources[i].strength();
if (xi < c) break;
}
}
// Sample source site from i-th source distribution
Particle::Bank site {model::external_sources[i].sample(seed)};
// If running in MG, convert site.E to group
if (!settings::run_CE) {
site.E = lower_bound_index(data::mg.rev_energy_bins_.begin(),
data::mg.rev_energy_bins_.end(), site.E);
site.E = data::mg.num_energy_groups_ - site.E - 1.;
}
return site;
}
void free_memory_source()
{
model::external_sources.clear();
}
void load_custom_source_library()
{
#ifdef HAS_DYNAMIC_LINKING
// Open the library
custom_source_library = dlopen(settings::path_source_library.c_str(), RTLD_LAZY);
if (!custom_source_library) {
fatal_error("Couldn't open source library " + settings::path_source_library);
}
// reset errors
dlerror();
if (serialization.empty()) {
// get the function from the library
using sample_t = Particle::Bank (*)(uint64_t* seed);
custom_source_function = reinterpret_cast<sample_t>(dlsym(custom_source_library, "sample_source"));
} else {
// get the function from the library using the provided serialization
using sample_t = Particle::Bank (*)(uint64_t* seed, const char* serialization);
custom_serialized_source_function = reinterpret_cast<sample_t>(dlsym(custom_source_library, "sample_source"));
}
// check for any dlsym errors
auto dlsym_error = dlerror();
if (dlsym_error) {
dlclose(custom_source_library);
fatal_error(fmt::format("Couldn't open the sample_source symbol: {}", dlsym_error));
}
#else
fatal_error("Custom source libraries have not yet been implemented for "
"non-POSIX systems");
#endif
}
void close_custom_source_library()
{
#ifdef HAS_DYNAMIC_LINKING
dlclose(custom_source_library);
#else
fatal_error("Custom source libraries have not yet been implemented for "
"non-POSIX systems");
#endif
}
Particle::Bank sample_custom_source_library(uint64_t* seed)
{
if (serialization.empty()) {
return custom_source_function(seed);
} else {
return custom_serialized_source_function(seed, serialization.c_str());
}
}
void fill_source_bank_custom_source()
{
// Load the custom library
load_custom_source_library();
// Generation source sites from specified distribution in the
// library source
for (int64_t i = 0; i < simulation::work_per_rank; ++i) {
// initialize random number seed
int64_t id = (simulation::total_gen + overall_generation()) *
settings::n_particles + simulation::work_index[mpi::rank] + i + 1;
uint64_t seed = init_seed(id, STREAM_SOURCE);
// sample custom library source
simulation::source_bank[i] = sample_custom_source_library(&seed);
}
// release the library
close_custom_source_library();
}
} // namespace openmc
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string.h>
#include "chrome/browser/chromeos/bluetooth/bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/test/mock_bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/test/mock_bluetooth_device.h"
#include "chrome/browser/chromeos/extensions/bluetooth_event_router.h"
#include "chrome/browser/extensions/api/bluetooth/bluetooth_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/ui/browser.h"
#include "chromeos/dbus/bluetooth_out_of_band_client.h"
#include "testing/gmock/include/gmock/gmock.h"
using extensions::Extension;
namespace utils = extension_function_test_utils;
namespace api = extensions::api;
namespace chromeos {
class BluetoothAdapater;
} // namespace chromeos
namespace {
class BluetoothApiTest : public PlatformAppApiTest {
public:
BluetoothApiTest() : empty_extension_(utils::CreateEmptyExtension()) {}
virtual void SetUpOnMainThread() OVERRIDE {
// The browser will clean this up when it is torn down
mock_adapter_ = new testing::StrictMock<chromeos::MockBluetoothAdapter>;
event_router()->SetAdapterForTest(mock_adapter_);
}
void expectBooleanResult(bool expected,
UIThreadExtensionFunction* function,
const std::string& args) {
scoped_ptr<base::Value> result(
utils::RunFunctionAndReturnResult(function, args, browser()));
ASSERT_TRUE(result.get() != NULL);
ASSERT_EQ(base::Value::TYPE_BOOLEAN, result->GetType());
bool boolean_value;
result->GetAsBoolean(&boolean_value);
EXPECT_EQ(expected, boolean_value);
}
template <class T>
T* setupFunction(T* function) {
function->set_extension(empty_extension_.get());
function->set_has_callback(true);
return function;
}
protected:
testing::StrictMock<chromeos::MockBluetoothAdapter>* mock_adapter_;
private:
chromeos::ExtensionBluetoothEventRouter* event_router() {
return browser()->profile()->GetExtensionService()->
bluetooth_event_router();
}
chromeos::BluetoothAdapter* original_adapter_;
scoped_refptr<Extension> empty_extension_;
};
static const char kOutOfBandPairingDataHash[] = "0123456789ABCDEh";
static const char kOutOfBandPairingDataRandomizer[] = "0123456789ABCDEr";
static chromeos::BluetoothOutOfBandPairingData GetOutOfBandPairingData() {
chromeos::BluetoothOutOfBandPairingData data;
memcpy(&(data.hash), kOutOfBandPairingDataHash,
chromeos::kBluetoothOutOfBandPairingDataSize);
memcpy(&(data.randomizer), kOutOfBandPairingDataRandomizer,
chromeos::kBluetoothOutOfBandPairingDataSize);
return data;
}
static bool CallClosure(const base::Closure& callback) {
callback.Run();
return true;
}
static bool CallOutOfBandPairingDataCallback(
const chromeos::BluetoothAdapter::BluetoothOutOfBandPairingDataCallback&
callback) {
callback.Run(GetOutOfBandPairingData());
return true;
}
} // namespace
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsAvailable) {
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(false));
scoped_refptr<api::BluetoothIsAvailableFunction> is_available;
is_available = setupFunction(new api::BluetoothIsAvailableFunction);
expectBooleanResult(false, is_available, "[]");
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(true));
is_available = setupFunction(new api::BluetoothIsAvailableFunction);
expectBooleanResult(true, is_available, "[]");
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsPowered) {
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(false));
scoped_refptr<api::BluetoothIsPoweredFunction> is_powered;
is_powered = setupFunction(new api::BluetoothIsPoweredFunction);
expectBooleanResult(false, is_powered, "[]");
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(true));
is_powered = setupFunction(new api::BluetoothIsPoweredFunction);
expectBooleanResult(true, is_powered, "[]");
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevices) {
testing::NiceMock<chromeos::MockBluetoothDevice> device1(
mock_adapter_, "d1", "11:12:13:14:15:16",
true /* paired */, false /* bonded */, true /* connected */);
testing::NiceMock<chromeos::MockBluetoothDevice> device2(
mock_adapter_, "d2", "21:22:23:24:25:26",
false /* paired */, true /* bonded */, false /* connected */);
chromeos::BluetoothAdapter::ConstDeviceList devices;
devices.push_back(&device1);
devices.push_back(&device2);
EXPECT_CALL(device1, ProvidesServiceWithUUID("foo"))
.WillOnce(testing::Return(false));
EXPECT_CALL(device2, ProvidesServiceWithUUID("foo"))
.WillOnce(testing::Return(true));
EXPECT_CALL(*mock_adapter_, GetDevices())
.WillOnce(testing::Return(devices));
scoped_refptr<api::BluetoothGetDevicesFunction> get_devices;
get_devices = setupFunction(new api::BluetoothGetDevicesFunction);
scoped_ptr<base::Value> result(utils::RunFunctionAndReturnResult(
get_devices,
"[{\"uuid\":\"foo\"}]",
browser()));
ASSERT_EQ(base::Value::TYPE_LIST, result->GetType());
base::ListValue* list;
ASSERT_TRUE(result->GetAsList(&list));
EXPECT_EQ(1u, list->GetSize());
base::Value* device_value;
EXPECT_TRUE(list->Get(0, &device_value));
EXPECT_EQ(base::Value::TYPE_DICTIONARY, device_value->GetType());
base::DictionaryValue* device;
ASSERT_TRUE(device_value->GetAsDictionary(&device));
std::string name;
ASSERT_TRUE(device->GetString("name", &name));
EXPECT_EQ("d2", name);
std::string address;
ASSERT_TRUE(device->GetString("address", &address));
EXPECT_EQ("21:22:23:24:25:26", address);
bool paired;
ASSERT_TRUE(device->GetBoolean("paired", &paired));
EXPECT_FALSE(paired);
bool bonded;
ASSERT_TRUE(device->GetBoolean("bonded", &bonded));
EXPECT_TRUE(bonded);
bool connected;
ASSERT_TRUE(device->GetBoolean("connected", &connected));
EXPECT_FALSE(connected);
// Try again with no options
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*mock_adapter_, GetDevices())
.WillOnce(testing::Return(devices));
get_devices = setupFunction(new api::BluetoothGetDevicesFunction);
result.reset(
utils::RunFunctionAndReturnResult(get_devices, "[{}]", browser()));
ASSERT_EQ(base::Value::TYPE_LIST, result->GetType());
ASSERT_TRUE(result->GetAsList(&list));
EXPECT_EQ(2u, list->GetSize());
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetLocalOutOfBandPairingData) {
EXPECT_CALL(*mock_adapter_,
ReadLocalOutOfBandPairingData(
testing::Truly(CallOutOfBandPairingDataCallback),
testing::_));
scoped_refptr<api::BluetoothGetLocalOutOfBandPairingDataFunction>
get_oob_function(setupFunction(
new api::BluetoothGetLocalOutOfBandPairingDataFunction));
scoped_ptr<base::Value> result(
utils::RunFunctionAndReturnResult(get_oob_function, "[]", browser()));
base::DictionaryValue* dict;
EXPECT_TRUE(result->GetAsDictionary(&dict));
base::BinaryValue* binary_value;
EXPECT_TRUE(dict->GetBinary("hash", &binary_value));
EXPECT_STREQ(kOutOfBandPairingDataHash,
std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str());
EXPECT_TRUE(dict->GetBinary("randomizer", &binary_value));
EXPECT_STREQ(kOutOfBandPairingDataRandomizer,
std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str());
// Try again with an error
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*mock_adapter_,
ReadLocalOutOfBandPairingData(
testing::_,
testing::Truly(CallClosure)));
get_oob_function =
setupFunction(new api::BluetoothGetLocalOutOfBandPairingDataFunction);
std::string error(
utils::RunFunctionAndReturnError(get_oob_function, "[]", browser()));
EXPECT_FALSE(error.empty());
}
// Fails under ASan, see http://crbug.com/133199.
#if defined(ADDRESS_SANITIZER)
#define MAYBE_SetOutOfBandPairingData DISABLED_SetOutOfBandPairingData
#else
#define MAYBE_SetOutOfBandPairingData SetOutOfBandPairingData
#endif
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, MAYBE_SetOutOfBandPairingData) {
std::string device_address("11:12:13:14:15:16");
testing::NiceMock<chromeos::MockBluetoothDevice> device(
mock_adapter_, "d1", device_address,
true /* paired */, false /* bonded */, true /* connected */);
EXPECT_CALL(*mock_adapter_, GetDevice(device_address))
.WillOnce(testing::Return(&device));
EXPECT_CALL(device,
ClearOutOfBandPairingData(testing::Truly(CallClosure),
testing::_));
char buf[64];
snprintf(buf, sizeof(buf),
"[{\"device_address\":\"%s\"}]", device_address.c_str());
std::string params(buf);
scoped_refptr<api::BluetoothSetOutOfBandPairingDataFunction> set_oob_function;
set_oob_function = setupFunction(
new api::BluetoothSetOutOfBandPairingDataFunction);
// There isn't actually a result.
(void)utils::RunFunctionAndReturnResult(set_oob_function, params, browser());
// Try again with an error
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
testing::Mock::VerifyAndClearExpectations(&device);
EXPECT_CALL(*mock_adapter_, GetDevice(device_address))
.WillOnce(testing::Return(&device));
EXPECT_CALL(device,
ClearOutOfBandPairingData(testing::_,
testing::Truly(CallClosure)));
set_oob_function = setupFunction(
new api::BluetoothSetOutOfBandPairingDataFunction);
std::string error(
utils::RunFunctionAndReturnError(set_oob_function, params, browser()));
EXPECT_FALSE(error.empty());
// TODO(bryeung): Also test setting the data when there is support for
// ArrayBuffers in the arguments to the RunFunctionAnd* methods.
// crbug.com/132796
}
<commit_msg>Revert 142630 - Disable BluetoothApiTest.SetOutOfBandPairingData under ASan.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string.h>
#include "chrome/browser/chromeos/bluetooth/bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/test/mock_bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/test/mock_bluetooth_device.h"
#include "chrome/browser/chromeos/extensions/bluetooth_event_router.h"
#include "chrome/browser/extensions/api/bluetooth/bluetooth_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/ui/browser.h"
#include "chromeos/dbus/bluetooth_out_of_band_client.h"
#include "testing/gmock/include/gmock/gmock.h"
using extensions::Extension;
namespace utils = extension_function_test_utils;
namespace api = extensions::api;
namespace chromeos {
class BluetoothAdapater;
} // namespace chromeos
namespace {
class BluetoothApiTest : public PlatformAppApiTest {
public:
BluetoothApiTest() : empty_extension_(utils::CreateEmptyExtension()) {}
virtual void SetUpOnMainThread() OVERRIDE {
// The browser will clean this up when it is torn down
mock_adapter_ = new testing::StrictMock<chromeos::MockBluetoothAdapter>;
event_router()->SetAdapterForTest(mock_adapter_);
}
void expectBooleanResult(bool expected,
UIThreadExtensionFunction* function,
const std::string& args) {
scoped_ptr<base::Value> result(
utils::RunFunctionAndReturnResult(function, args, browser()));
ASSERT_TRUE(result.get() != NULL);
ASSERT_EQ(base::Value::TYPE_BOOLEAN, result->GetType());
bool boolean_value;
result->GetAsBoolean(&boolean_value);
EXPECT_EQ(expected, boolean_value);
}
template <class T>
T* setupFunction(T* function) {
function->set_extension(empty_extension_.get());
function->set_has_callback(true);
return function;
}
protected:
testing::StrictMock<chromeos::MockBluetoothAdapter>* mock_adapter_;
private:
chromeos::ExtensionBluetoothEventRouter* event_router() {
return browser()->profile()->GetExtensionService()->
bluetooth_event_router();
}
chromeos::BluetoothAdapter* original_adapter_;
scoped_refptr<Extension> empty_extension_;
};
static const char kOutOfBandPairingDataHash[] = "0123456789ABCDEh";
static const char kOutOfBandPairingDataRandomizer[] = "0123456789ABCDEr";
static chromeos::BluetoothOutOfBandPairingData GetOutOfBandPairingData() {
chromeos::BluetoothOutOfBandPairingData data;
memcpy(&(data.hash), kOutOfBandPairingDataHash,
chromeos::kBluetoothOutOfBandPairingDataSize);
memcpy(&(data.randomizer), kOutOfBandPairingDataRandomizer,
chromeos::kBluetoothOutOfBandPairingDataSize);
return data;
}
static bool CallClosure(const base::Closure& callback) {
callback.Run();
return true;
}
static bool CallOutOfBandPairingDataCallback(
const chromeos::BluetoothAdapter::BluetoothOutOfBandPairingDataCallback&
callback) {
callback.Run(GetOutOfBandPairingData());
return true;
}
} // namespace
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsAvailable) {
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(false));
scoped_refptr<api::BluetoothIsAvailableFunction> is_available;
is_available = setupFunction(new api::BluetoothIsAvailableFunction);
expectBooleanResult(false, is_available, "[]");
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*mock_adapter_, IsPresent())
.WillOnce(testing::Return(true));
is_available = setupFunction(new api::BluetoothIsAvailableFunction);
expectBooleanResult(true, is_available, "[]");
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsPowered) {
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(false));
scoped_refptr<api::BluetoothIsPoweredFunction> is_powered;
is_powered = setupFunction(new api::BluetoothIsPoweredFunction);
expectBooleanResult(false, is_powered, "[]");
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*mock_adapter_, IsPowered())
.WillOnce(testing::Return(true));
is_powered = setupFunction(new api::BluetoothIsPoweredFunction);
expectBooleanResult(true, is_powered, "[]");
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevices) {
testing::NiceMock<chromeos::MockBluetoothDevice> device1(
mock_adapter_, "d1", "11:12:13:14:15:16",
true /* paired */, false /* bonded */, true /* connected */);
testing::NiceMock<chromeos::MockBluetoothDevice> device2(
mock_adapter_, "d2", "21:22:23:24:25:26",
false /* paired */, true /* bonded */, false /* connected */);
chromeos::BluetoothAdapter::ConstDeviceList devices;
devices.push_back(&device1);
devices.push_back(&device2);
EXPECT_CALL(device1, ProvidesServiceWithUUID("foo"))
.WillOnce(testing::Return(false));
EXPECT_CALL(device2, ProvidesServiceWithUUID("foo"))
.WillOnce(testing::Return(true));
EXPECT_CALL(*mock_adapter_, GetDevices())
.WillOnce(testing::Return(devices));
scoped_refptr<api::BluetoothGetDevicesFunction> get_devices;
get_devices = setupFunction(new api::BluetoothGetDevicesFunction);
scoped_ptr<base::Value> result(utils::RunFunctionAndReturnResult(
get_devices,
"[{\"uuid\":\"foo\"}]",
browser()));
ASSERT_EQ(base::Value::TYPE_LIST, result->GetType());
base::ListValue* list;
ASSERT_TRUE(result->GetAsList(&list));
EXPECT_EQ(1u, list->GetSize());
base::Value* device_value;
EXPECT_TRUE(list->Get(0, &device_value));
EXPECT_EQ(base::Value::TYPE_DICTIONARY, device_value->GetType());
base::DictionaryValue* device;
ASSERT_TRUE(device_value->GetAsDictionary(&device));
std::string name;
ASSERT_TRUE(device->GetString("name", &name));
EXPECT_EQ("d2", name);
std::string address;
ASSERT_TRUE(device->GetString("address", &address));
EXPECT_EQ("21:22:23:24:25:26", address);
bool paired;
ASSERT_TRUE(device->GetBoolean("paired", &paired));
EXPECT_FALSE(paired);
bool bonded;
ASSERT_TRUE(device->GetBoolean("bonded", &bonded));
EXPECT_TRUE(bonded);
bool connected;
ASSERT_TRUE(device->GetBoolean("connected", &connected));
EXPECT_FALSE(connected);
// Try again with no options
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*mock_adapter_, GetDevices())
.WillOnce(testing::Return(devices));
get_devices = setupFunction(new api::BluetoothGetDevicesFunction);
result.reset(
utils::RunFunctionAndReturnResult(get_devices, "[{}]", browser()));
ASSERT_EQ(base::Value::TYPE_LIST, result->GetType());
ASSERT_TRUE(result->GetAsList(&list));
EXPECT_EQ(2u, list->GetSize());
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetLocalOutOfBandPairingData) {
EXPECT_CALL(*mock_adapter_,
ReadLocalOutOfBandPairingData(
testing::Truly(CallOutOfBandPairingDataCallback),
testing::_));
scoped_refptr<api::BluetoothGetLocalOutOfBandPairingDataFunction>
get_oob_function(setupFunction(
new api::BluetoothGetLocalOutOfBandPairingDataFunction));
scoped_ptr<base::Value> result(
utils::RunFunctionAndReturnResult(get_oob_function, "[]", browser()));
base::DictionaryValue* dict;
EXPECT_TRUE(result->GetAsDictionary(&dict));
base::BinaryValue* binary_value;
EXPECT_TRUE(dict->GetBinary("hash", &binary_value));
EXPECT_STREQ(kOutOfBandPairingDataHash,
std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str());
EXPECT_TRUE(dict->GetBinary("randomizer", &binary_value));
EXPECT_STREQ(kOutOfBandPairingDataRandomizer,
std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str());
// Try again with an error
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
EXPECT_CALL(*mock_adapter_,
ReadLocalOutOfBandPairingData(
testing::_,
testing::Truly(CallClosure)));
get_oob_function =
setupFunction(new api::BluetoothGetLocalOutOfBandPairingDataFunction);
std::string error(
utils::RunFunctionAndReturnError(get_oob_function, "[]", browser()));
EXPECT_FALSE(error.empty());
}
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, SetOutOfBandPairingData) {
std::string device_address("11:12:13:14:15:16");
testing::NiceMock<chromeos::MockBluetoothDevice> device(
mock_adapter_, "d1", device_address,
true /* paired */, false /* bonded */, true /* connected */);
EXPECT_CALL(*mock_adapter_, GetDevice(device_address))
.WillOnce(testing::Return(&device));
EXPECT_CALL(device,
ClearOutOfBandPairingData(testing::Truly(CallClosure),
testing::_));
char buf[64];
snprintf(buf, sizeof(buf),
"[{\"device_address\":\"%s\"}]", device_address.c_str());
std::string params(buf);
scoped_refptr<api::BluetoothSetOutOfBandPairingDataFunction> set_oob_function;
set_oob_function = setupFunction(
new api::BluetoothSetOutOfBandPairingDataFunction);
// There isn't actually a result.
(void)utils::RunFunctionAndReturnResult(set_oob_function, params, browser());
// Try again with an error
testing::Mock::VerifyAndClearExpectations(mock_adapter_);
testing::Mock::VerifyAndClearExpectations(&device);
EXPECT_CALL(*mock_adapter_, GetDevice(device_address))
.WillOnce(testing::Return(&device));
EXPECT_CALL(device,
ClearOutOfBandPairingData(testing::_,
testing::Truly(CallClosure)));
set_oob_function = setupFunction(
new api::BluetoothSetOutOfBandPairingDataFunction);
std::string error(
utils::RunFunctionAndReturnError(set_oob_function, params, browser()));
EXPECT_FALSE(error.empty());
// TODO(bryeung): Also test setting the data when there is support for
// ArrayBuffers in the arguments to the RunFunctionAnd* methods.
// crbug.com/132796
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include "cpu.hpp"
#include "../opcodes.hpp"
CPU::CPU() :
pc(0), mem_size(0), memory(NULL),
flags({false,false,false,false}), extension({NULL})
{}
CPU::~CPU()
{
free(this->memory);
}
bool
CPU::Initialize(u32 mem_size)
{
if ((this->memory = (u32 *)calloc(mem_size, sizeof(u32))))
this->mem_size = mem_size;
return (bool)this->memory;
}
bool
CPU::Load(FILE *input)
{
int byte = '\0';
for (u32 word_index = 0; byte != EOF && word_index < this->mem_size; ++word_index)
for (int shift = 8 * (sizeof(u32) - 1); shift >= 0 && (byte = getc(input)) != EOF; shift -= 8)
memory[word_index] |= byte << shift;
return byte == EOF;
}
CPU::ProgramState
CPU::Tick()
{
if (pc >= mem_size)
return ERR_PC_BOUNDARY;
u32 instruction = this->memory[this->pc++];
u32 data = instruction & ~(0xff << 24);
switch (instruction & (0xff << 24))
{
case OP_NOP:
break;
// TODO: add remaining opcodes
case _OP_SIZE:
if (this->mem_size < data) {
this->extension.required_memory = data;
return _ERR_SIZE;
}
break;
case _OP_DEBUG:
this->extension.debug_info = this->memory + data;
break;
default:
this->set_errored_line();
return ERR_INVALID_OPCODE;
}
return OK;
}
void
CPU::set_errored_line()
{
if (!this->extension.debug_info)
return;
for (
u32 *key = this->extension.debug_info;
key < this->memory + this->mem_size;
key += *key & 0xffff
)
if (this->pc == (*key >> 16))
{
this->extension.errored_line = (char *)(key + 1);
return;
}
else if (pc < (*key >> 16)) // instruction not present in source file
break;
else if (!(*key & 0xffff)) // no more lines follows
break;
this->extension.errored_line = NULL;
}
<commit_msg>Code formatting<commit_after>#include <cstdlib>
#include "cpu.hpp"
#include "../opcodes.hpp"
CPU::CPU() :
pc(0), mem_size(0), memory(NULL),
flags({false, false, false, false}), extension({NULL})
{}
CPU::~CPU()
{
free(this->memory);
}
bool
CPU::Initialize(u32 mem_size)
{
if ((this->memory = (u32 *)calloc(mem_size, sizeof(u32))))
this->mem_size = mem_size;
return (bool)this->memory;
}
bool
CPU::Load(FILE *input)
{
int byte = '\0';
for (
u32 word_index = 0;
byte != EOF && word_index < this->mem_size;
++word_index
)
for (
int shift = 8 * (sizeof(u32) - 1);
shift >= 0 && (byte = getc(input)) != EOF;
shift -= 8
)
memory[word_index] |= byte << shift;
return byte == EOF;
}
CPU::ProgramState
CPU::Tick()
{
if (pc >= mem_size)
return ERR_PC_BOUNDARY;
u32 instruction = this->memory[this->pc++];
u32 data = instruction & ~(0xff << 24);
switch (instruction & (0xff << 24))
{
case OP_NOP:
break;
// TODO: add remaining opcodes
case _OP_SIZE:
if (this->mem_size < data) {
this->extension.required_memory = data;
return _ERR_SIZE;
}
break;
case _OP_DEBUG:
this->extension.debug_info = this->memory + data;
break;
default:
this->set_errored_line();
return ERR_INVALID_OPCODE;
}
return OK;
}
void
CPU::set_errored_line()
{
if (!this->extension.debug_info)
return;
for (
u32 *key = this->extension.debug_info;
key < this->memory + this->mem_size;
key += *key & 0xffff
)
if (this->pc == (*key >> 16))
{
this->extension.errored_line = (char *)(key + 1);
return;
}
else if (pc < (*key >> 16)) // instruction not present in source file
break;
else if (!(*key & 0xffff)) // no more lines follows
break;
this->extension.errored_line = NULL;
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cstring>
#include "cpu.hpp"
#include "../conversion.hpp"
#include "../opcodes.hpp"
#define VALIDATE_ARGS(val1, val2)\
VALIDATE_ARG(val1)\
VALIDATE_ARG(val2)
#define VALIDATE_ARG(value)\
{\
if (((value) & ~0x80) > 0x12)\
return ERR_INVALID_ARG;\
}
#define VALIDATE_PC()\
{\
if (bytes2word(this->pc) >= mem_size)\
return ERR_PC_BOUNDARY;\
}
static inline u32 opcode(u32 instruction)
{
return instruction >> 24;
}
static inline u32 data(u32 instruction)
{
return instruction & 0xffffff;
}
static inline u32 byte(u32 instruction, u8 number)
{
return (instruction >> (8 * (3 - number))) & 0xff;
}
CPU::CPU() :
lc(&this->registers[0x10 * sizeof(u32)]),
sp(&this->registers[0x11 * sizeof(u32)]),
pc(&this->registers[0x12 * sizeof(u32)]),
mem_size(0), memory(NULL),
registers({0}), stack({0}), flags({false, false, false, false}),
extension({0})
{}
CPU::~CPU()
{
free(this->memory);
}
u32
CPU::CurrentInstruction()
{
return bytes2word(this->memory + bytes2word(this->pc) * sizeof(u32));
}
u32
CPU::LastInstruction()
{
return bytes2word(this->memory + (bytes2word(this->pc) - 1) * sizeof(u32));
}
bool
CPU::Initialize(u32 mem_size)
{
if ((this->memory = (u8 *)malloc(mem_size * sizeof(u32))))
this->mem_size = mem_size;
return (bool)this->memory;
}
bool
CPU::Load(FILE *input)
{
int byte;
u32 byte_num = 0;
while ((byte = getc(input)) != EOF && byte_num < this->mem_size * sizeof(u32))
this->memory[byte_num++] = byte;
return byte == EOF;
}
u8*
CPU::WhichRegister(u8 value)
{
u8 *reg_ptr;
reg_ptr = &this->registers[(value & ~0x80) * sizeof(u32)];
if (value & 0x80)
{
if (*reg_ptr < this->mem_size)
return &this->memory[*reg_ptr * sizeof(u32)];
else
return NULL;
}
return reg_ptr;
}
CPU::ProgramState
CPU::Tick()
{
VALIDATE_PC()
u8 *ptr1;
u64 result;
u32 instruction = this->CurrentInstruction();
bytes_add(this->pc, 1);
switch (opcode(instruction))
{
case OP_NOP:
break;
case OP_HCF:
return HALTED;
case OP_MOV:
if (byte(instruction, 3))
{
VALIDATE_ARG(byte(instruction, 1))
VALIDATE_PC()
memcpy(
this->WhichRegister(byte(instruction, 1)),
this->memory + bytes2word(this->pc) * sizeof(u32),
sizeof(u32)
);
bytes_add(this->pc, 1);
}
else
{
VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
word2bytes(
bytes2word(this->WhichRegister(byte(instruction, 2))),
this->WhichRegister(byte(instruction, 1))
);
}
break;
case OP_ADD:
VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
ptr1 = this->WhichRegister(byte(instruction, 1));
result =
(u64)bytes2word(ptr1) +
bytes2word(this->WhichRegister(byte(instruction, 2)));
word2bytes(result, ptr1);
this->flags.carry = (bool)(result != (u32)result);
break;
// TODO: add remaining opcodes
case _OP_SIZE:
if (this->mem_size < data(instruction)) {
this->extension.required_memory = data(instruction);
return _ERR_SIZE;
}
break;
case _OP_DEBUG:
this->extension.debug_info = data(instruction);
break;
default:
this->_SetErroredLine();
return ERR_INVALID_OPCODE;
}
return OK;
}
void
CPU::_SetErroredLine()
{
if (!this->extension.debug_info)
return;
DebugSymbol key;
for (
u32 word_index = this->extension.debug_info;
word_index < this->mem_size;
word_index += key.next()
) {
key.value = bytes2word(this->memory + word_index * sizeof(u32));
if (word_index == bytes2word(this->pc))
{
this->extension.errored_line =
(char *)(this->memory + word_index * sizeof(u32));
return;
}
else if (key.word() > bytes2word(this->pc)) // instruction not present
// in the source file
break;
else if (!key.next()) // no more lines follows
break;
}
this->extension.errored_line = NULL;
}
<commit_msg>Added address boundary checking to MOV and ADD<commit_after>#include <cstdlib>
#include <cstring>
#include "cpu.hpp"
#include "../conversion.hpp"
#include "../opcodes.hpp"
#define VALIDATE_ARGS(val1, val2)\
VALIDATE_ARG(val1)\
VALIDATE_ARG(val2)
#define VALIDATE_ARG(value)\
{\
if (((value) & ~0x80) > 0x12)\
return ERR_INVALID_ARG;\
}
#define VALIDATE_PC()\
{\
if (bytes2word(this->pc) >= mem_size)\
return ERR_PC_BOUNDARY;\
}
static inline u32 opcode(u32 instruction)
{
return instruction >> 24;
}
static inline u32 data(u32 instruction)
{
return instruction & 0xffffff;
}
static inline u32 byte(u32 instruction, u8 number)
{
return (instruction >> (8 * (3 - number))) & 0xff;
}
CPU::CPU() :
lc(&this->registers[0x10 * sizeof(u32)]),
sp(&this->registers[0x11 * sizeof(u32)]),
pc(&this->registers[0x12 * sizeof(u32)]),
mem_size(0), memory(NULL),
registers({0}), stack({0}), flags({false, false, false, false}),
extension({0})
{}
CPU::~CPU()
{
free(this->memory);
}
u32
CPU::CurrentInstruction()
{
return bytes2word(this->memory + bytes2word(this->pc) * sizeof(u32));
}
u32
CPU::LastInstruction()
{
return bytes2word(this->memory + (bytes2word(this->pc) - 1) * sizeof(u32));
}
bool
CPU::Initialize(u32 mem_size)
{
if ((this->memory = (u8 *)malloc(mem_size * sizeof(u32))))
this->mem_size = mem_size;
return (bool)this->memory;
}
bool
CPU::Load(FILE *input)
{
int byte;
u32 byte_num = 0;
while ((byte = getc(input)) != EOF && byte_num < this->mem_size * sizeof(u32))
this->memory[byte_num++] = byte;
return byte == EOF;
}
u8*
CPU::WhichRegister(u8 value)
{
u8 *reg_ptr;
reg_ptr = &this->registers[(value & ~0x80) * sizeof(u32)];
if (value & 0x80)
{
if (*reg_ptr < this->mem_size)
return &this->memory[*reg_ptr * sizeof(u32)];
else
return NULL;
}
return reg_ptr;
}
CPU::ProgramState
CPU::Tick()
{
VALIDATE_PC()
u8 *ptr1, *ptr2;
u64 result;
u32 instruction = this->CurrentInstruction();
bytes_add(this->pc, 1);
switch (opcode(instruction))
{
case OP_NOP:
break;
case OP_HCF:
return HALTED;
case OP_MOV:
if (byte(instruction, 3))
{
VALIDATE_ARG(byte(instruction, 1))
VALIDATE_PC()
ptr1 = this->WhichRegister(byte(instruction, 1));
if (!ptr1)
return ERR_ADDRESS_BOUNDARY;
memcpy(
ptr1,
this->memory + bytes2word(this->pc) * sizeof(u32),
sizeof(u32)
);
bytes_add(this->pc, 1);
}
else
{
VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
ptr1 = this->WhichRegister(byte(instruction, 1));
ptr2 = this->WhichRegister(byte(instruction, 2));
if (!ptr1 || !ptr2)
return ERR_ADDRESS_BOUNDARY;
word2bytes(bytes2word(ptr2), ptr1);
}
break;
case OP_ADD:
VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
ptr1 = this->WhichRegister(byte(instruction, 1));
ptr2 = this->WhichRegister(byte(instruction, 2));
if (!ptr1 || !ptr2)
return ERR_ADDRESS_BOUNDARY;
result = (u64)bytes2word(ptr1) + bytes2word(ptr2);
word2bytes(result, ptr1);
this->flags.carry = (bool)(result != (u32)result);
break;
// TODO: add remaining opcodes
case _OP_SIZE:
if (this->mem_size < data(instruction)) {
this->extension.required_memory = data(instruction);
return _ERR_SIZE;
}
break;
case _OP_DEBUG:
this->extension.debug_info = data(instruction);
break;
default:
this->_SetErroredLine();
return ERR_INVALID_OPCODE;
}
return OK;
}
void
CPU::_SetErroredLine()
{
if (!this->extension.debug_info)
return;
DebugSymbol key;
for (
u32 word_index = this->extension.debug_info;
word_index < this->mem_size;
word_index += key.next()
) {
key.value = bytes2word(this->memory + word_index * sizeof(u32));
if (word_index == bytes2word(this->pc))
{
this->extension.errored_line =
(char *)(this->memory + word_index * sizeof(u32));
return;
}
else if (key.word() > bytes2word(this->pc)) // instruction not present
// in the source file
break;
else if (!key.next()) // no more lines follows
break;
}
this->extension.errored_line = NULL;
}
<|endoftext|>
|
<commit_before><commit_msg>added range operator (start, end) for contour<commit_after><|endoftext|>
|
<commit_before>/*
* 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 "EventLog.h"
#include <stdarg.h>
#include <stdlib.h>
using namespace apache::thrift::concurrency;
namespace {
// Define environment variable DEBUG_EVENTLOG to enable debug logging
// ex: $ DEBUG_EVENTLOG=1 processor_test
static const char * DEBUG_EVENTLOG = getenv("DEBUG_EVENTLOG");
void debug(const char* fmt, ...) {
if (DEBUG_EVENTLOG) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
}
}
namespace apache {
namespace thrift {
namespace test {
uint32_t EventLog::nextId_ = 0;
#define EVENT_TYPE(value) EventType EventLog::value = #value
EVENT_TYPE(ET_LOG_END);
EVENT_TYPE(ET_CONN_CREATED);
EVENT_TYPE(ET_CONN_DESTROYED);
EVENT_TYPE(ET_CALL_STARTED);
EVENT_TYPE(ET_CALL_FINISHED);
EVENT_TYPE(ET_PROCESS);
EVENT_TYPE(ET_PRE_READ);
EVENT_TYPE(ET_POST_READ);
EVENT_TYPE(ET_PRE_WRITE);
EVENT_TYPE(ET_POST_WRITE);
EVENT_TYPE(ET_ASYNC_COMPLETE);
EVENT_TYPE(ET_HANDLER_ERROR);
EVENT_TYPE(ET_CALL_INCREMENT_GENERATION);
EVENT_TYPE(ET_CALL_GET_GENERATION);
EVENT_TYPE(ET_CALL_ADD_STRING);
EVENT_TYPE(ET_CALL_GET_STRINGS);
EVENT_TYPE(ET_CALL_GET_DATA_WAIT);
EVENT_TYPE(ET_CALL_ONEWAY_WAIT);
EVENT_TYPE(ET_CALL_EXCEPTION_WAIT);
EVENT_TYPE(ET_CALL_UNEXPECTED_EXCEPTION_WAIT);
EVENT_TYPE(ET_CALL_SET_VALUE);
EVENT_TYPE(ET_CALL_GET_VALUE);
EVENT_TYPE(ET_WAIT_RETURN);
EventLog::EventLog() {
id_ = nextId_++;
debug("New log: %d", id_);
}
void EventLog::append(EventType type,
uint32_t connectionId,
uint32_t callId,
const std::string& message) {
Synchronized s(monitor_);
debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type, message.c_str());
Event e(type, connectionId, callId, message);
events_.push_back(e);
monitor_.notify();
}
Event EventLog::waitForEvent(int64_t timeout) {
Synchronized s(monitor_);
try {
while (events_.empty()) {
monitor_.wait(timeout);
}
} catch (TimedOutException ex) {
return Event(ET_LOG_END, 0, 0, "");
}
Event event = events_.front();
events_.pop_front();
return event;
}
Event EventLog::waitForConnEvent(uint32_t connId, int64_t timeout) {
Synchronized s(monitor_);
auto it = events_.begin();
while (true) {
try {
// TODO: it would be nicer to honor timeout for the duration of this
// call, rather than restarting it for each call to wait(). It shouldn't
// be a big problem in practice, though.
while (it == events_.end()) {
monitor_.wait(timeout);
}
} catch (TimedOutException ex) {
return Event(ET_LOG_END, 0, 0, "");
}
if (it->connectionId == connId) {
Event event = *it;
events_.erase(it);
return event;
}
}
}
}
}
} // apache::thrift::test
<commit_msg>CPP generator test, catching exceptions by ref instead.<commit_after>/*
* 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 "EventLog.h"
#include <stdarg.h>
#include <stdlib.h>
using namespace apache::thrift::concurrency;
namespace {
// Define environment variable DEBUG_EVENTLOG to enable debug logging
// ex: $ DEBUG_EVENTLOG=1 processor_test
static const char * DEBUG_EVENTLOG = getenv("DEBUG_EVENTLOG");
void debug(const char* fmt, ...) {
if (DEBUG_EVENTLOG) {
va_list ap;
va_start(ap, fmt);
vfprintf(stderr, fmt, ap);
va_end(ap);
fprintf(stderr, "\n");
}
}
}
namespace apache {
namespace thrift {
namespace test {
uint32_t EventLog::nextId_ = 0;
#define EVENT_TYPE(value) EventType EventLog::value = #value
EVENT_TYPE(ET_LOG_END);
EVENT_TYPE(ET_CONN_CREATED);
EVENT_TYPE(ET_CONN_DESTROYED);
EVENT_TYPE(ET_CALL_STARTED);
EVENT_TYPE(ET_CALL_FINISHED);
EVENT_TYPE(ET_PROCESS);
EVENT_TYPE(ET_PRE_READ);
EVENT_TYPE(ET_POST_READ);
EVENT_TYPE(ET_PRE_WRITE);
EVENT_TYPE(ET_POST_WRITE);
EVENT_TYPE(ET_ASYNC_COMPLETE);
EVENT_TYPE(ET_HANDLER_ERROR);
EVENT_TYPE(ET_CALL_INCREMENT_GENERATION);
EVENT_TYPE(ET_CALL_GET_GENERATION);
EVENT_TYPE(ET_CALL_ADD_STRING);
EVENT_TYPE(ET_CALL_GET_STRINGS);
EVENT_TYPE(ET_CALL_GET_DATA_WAIT);
EVENT_TYPE(ET_CALL_ONEWAY_WAIT);
EVENT_TYPE(ET_CALL_EXCEPTION_WAIT);
EVENT_TYPE(ET_CALL_UNEXPECTED_EXCEPTION_WAIT);
EVENT_TYPE(ET_CALL_SET_VALUE);
EVENT_TYPE(ET_CALL_GET_VALUE);
EVENT_TYPE(ET_WAIT_RETURN);
EventLog::EventLog() {
id_ = nextId_++;
debug("New log: %d", id_);
}
void EventLog::append(EventType type,
uint32_t connectionId,
uint32_t callId,
const std::string& message) {
Synchronized s(monitor_);
debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type, message.c_str());
Event e(type, connectionId, callId, message);
events_.push_back(e);
monitor_.notify();
}
Event EventLog::waitForEvent(int64_t timeout) {
Synchronized s(monitor_);
try {
while (events_.empty()) {
monitor_.wait(timeout);
}
} catch (const TimedOutException &) {
return Event(ET_LOG_END, 0, 0, "");
}
Event event = events_.front();
events_.pop_front();
return event;
}
Event EventLog::waitForConnEvent(uint32_t connId, int64_t timeout) {
Synchronized s(monitor_);
auto it = events_.begin();
while (true) {
try {
// TODO: it would be nicer to honor timeout for the duration of this
// call, rather than restarting it for each call to wait(). It shouldn't
// be a big problem in practice, though.
while (it == events_.end()) {
monitor_.wait(timeout);
}
} catch (const TimedOutException &) {
return Event(ET_LOG_END, 0, 0, "");
}
if (it->connectionId == connId) {
Event event = *it;
events_.erase(it);
return event;
}
}
}
}
}
} // apache::thrift::test
<|endoftext|>
|
<commit_before>//
// LayerBuilder.cpp
// G3MiOSSDK
//
// Created by Mari Luz Mateo on 21/12/12.
//
//
#include "LayerBuilder.hpp"
#include "LevelTileCondition.hpp"
#include "LayerSet.hpp"
LayerSet* LayerBuilder::createDefaultSatelliteImagery() {
LayerSet* layerSet = new LayerSet();
WMSLayer* blueMarble = new WMSLayer("bmng200405",
URL("http://www.nasa.network.com/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(0, 6),
TimeInterval::fromDays(30),
true);
layerSet->addLayer(blueMarble);
WMSLayer* i3Landsat = new WMSLayer("esat",
URL("http://data.worldwind.arc.nasa.gov/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(7, 10),
TimeInterval::fromDays(30),
true);
layerSet->addLayer(i3Landsat);
WMSLayer* bing = new WMSLayer("ve",
URL("http://worldwind27.arc.nasa.gov/wms/virtualearth?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(11, 1000),
TimeInterval::fromDays(30),
true);
layerSet->addLayer(bing);
return layerSet;
}
/**
* Returns an array with the names of the layers that make up the default layerSet
*
* @return layersNames: std::vector<std::string>
*/
std::vector<std::string> LayerBuilder::getDefaultLayersNames() {
std::vector<std::string> layersNames;
layersNames.push_back("bmng200405");
layersNames.push_back("esat");
layersNames.push_back("ve");
return layersNames;
}
WMSLayer* LayerBuilder::createBingLayer(bool enabled) {
WMSLayer* bing = new WMSLayer("ve",
URL("http://worldwind27.arc.nasa.gov/wms/virtualearth?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
NULL,
TimeInterval::fromDays(30),
true);
bing->setEnable(enabled);
return bing;
}
WMSLayer* LayerBuilder::createOSMLayer(bool enabled) {
WMSLayer* osm = new WMSLayer("osm_auto:all",
URL("http://129.206.228.72/cached/osm", false),
WMS_1_1_0,
// Sector::fromDegrees(-85.05, -180.0, 85.05, 180.0),
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
NULL,
TimeInterval::fromDays(30),
true);
osm->setEnable(enabled);
return osm;
}
WMSLayer* LayerBuilder::createPNOALayer(bool enabled) {
WMSLayer *pnoa = new WMSLayer("PNOA",
URL("http://www.idee.es/wms/PNOA/PNOA", false),
WMS_1_1_0,
Sector::fromDegrees(21, -18, 45, 6),
"image/png",
"EPSG:4326",
"",
true,
NULL,
TimeInterval::fromDays(30),
true);
pnoa->setEnable(enabled);
return pnoa;
}
WMSLayer* LayerBuilder::createBlueMarbleLayer(bool enabled) {
WMSLayer* blueMarble = new WMSLayer("bmng200405",
URL("http://www.nasa.network.com/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(0, 6),
TimeInterval::fromDays(30),
true);
blueMarble->setEnable(enabled);
return blueMarble;
}
WMSLayer* LayerBuilder::createI3LandSatLayer(bool enabled) {
WMSLayer* i3Landsat = new WMSLayer("esat",
URL("http://data.worldwind.arc.nasa.gov/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(7, 100),
TimeInterval::fromDays(30),
true);
i3Landsat->setEnable(enabled);
return i3Landsat;
}
WMSLayer* LayerBuilder::createPoliticalLayer(bool enabled) {
WMSLayer* political = new WMSLayer("topp:cia",
URL("http://worldwind22.arc.nasa.gov/geoserver/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/png",
"EPSG:4326",
"countryboundaries",
true,
NULL,
TimeInterval::fromDays(30),
true);
political->setEnable(enabled);
return political;
}
<commit_msg>expired-images handling<commit_after>//
// LayerBuilder.cpp
// G3MiOSSDK
//
// Created by Mari Luz Mateo on 21/12/12.
//
//
#include "LayerBuilder.hpp"
#include "LevelTileCondition.hpp"
#include "LayerSet.hpp"
LayerSet* LayerBuilder::createDefaultSatelliteImagery() {
LayerSet* layerSet = new LayerSet();
WMSLayer* blueMarble = new WMSLayer("bmng200405",
URL("http://www.nasa.network.com/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(0, 6),
TimeInterval::fromDays(30),
true);
layerSet->addLayer(blueMarble);
WMSLayer* i3Landsat = new WMSLayer("esat",
URL("http://data.worldwind.arc.nasa.gov/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(7, 10),
TimeInterval::fromDays(30),
true);
layerSet->addLayer(i3Landsat);
WMSLayer* bing = new WMSLayer("ve",
URL("http://worldwind27.arc.nasa.gov/wms/virtualearth?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(11, 1000),
TimeInterval::fromDays(30),
true);
layerSet->addLayer(bing);
return layerSet;
}
/**
* Returns an array with the names of the layers that make up the default layerSet
*
* @return layersNames: std::vector<std::string>
*/
std::vector<std::string> LayerBuilder::getDefaultLayersNames() {
std::vector<std::string> layersNames;
layersNames.push_back("bmng200405");
layersNames.push_back("esat");
layersNames.push_back("ve");
return layersNames;
}
WMSLayer* LayerBuilder::createBingLayer(bool enabled) {
WMSLayer* bing = new WMSLayer("ve",
URL("http://worldwind27.arc.nasa.gov/wms/virtualearth?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
NULL,
TimeInterval::fromDays(30),
true);
bing->setEnable(enabled);
return bing;
}
WMSLayer* LayerBuilder::createOSMLayer(bool enabled) {
WMSLayer* osm = new WMSLayer("osm_auto:all",
URL("http://129.206.228.72/cached/osm", false),
WMS_1_1_0,
// Sector::fromDegrees(-85.05, -180.0, 85.05, 180.0),
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
NULL,
TimeInterval::fromDays(30),
true);
osm->setEnable(enabled);
return osm;
}
WMSLayer* LayerBuilder::createPNOALayer(bool enabled) {
WMSLayer *pnoa = new WMSLayer("PNOA",
URL("http://www.idee.es/wms/PNOA/PNOA", false),
WMS_1_1_0,
Sector::fromDegrees(21, -18, 45, 6),
"image/png",
"EPSG:4326",
"",
true,
NULL,
TimeInterval::fromDays(30),
true);
pnoa->setEnable(enabled);
return pnoa;
}
WMSLayer* LayerBuilder::createBlueMarbleLayer(bool enabled) {
WMSLayer* blueMarble = new WMSLayer("bmng200405",
URL("http://www.nasa.network.com/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(0, 6),
TimeInterval::fromDays(30),
true);
blueMarble->setEnable(enabled);
return blueMarble;
}
WMSLayer* LayerBuilder::createI3LandSatLayer(bool enabled) {
WMSLayer* i3Landsat = new WMSLayer("esat",
URL("http://data.worldwind.arc.nasa.gov/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/jpeg",
"EPSG:4326",
"",
false,
new LevelTileCondition(7, 100),
TimeInterval::fromDays(30),
true);
i3Landsat->setEnable(enabled);
return i3Landsat;
}
WMSLayer* LayerBuilder::createPoliticalLayer(bool enabled) {
WMSLayer* political = new WMSLayer("topp:cia",
URL("http://worldwind22.arc.nasa.gov/geoserver/wms?", false),
WMS_1_1_0,
Sector::fullSphere(),
"image/png",
"EPSG:4326",
"countryboundaries",
true,
NULL,
TimeInterval::fromDays(30),
true);
political->setEnable(enabled);
return political;
}
<|endoftext|>
|
<commit_before><commit_msg>Automated merge with http://hg.secondlife.com/viewer-development<commit_after><|endoftext|>
|
<commit_before>#pragma once
#include <vector>
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/Point3f.hpp"
namespace dai {
struct Extrinsics {
std::vector<std::vector<float>> rotationMatrix;
/**
* (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket obtained through calibration
*/
Point3f translation;
/**
* (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket measured through CAD design
*/
Point3f specTranslation;
CameraBoardSocket toCameraSocket = CameraBoardSocket::AUTO;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Extrinsics, rotationMatrix, translation, specTranslation, toCameraSocket);
};
} // namespace dai<commit_msg>Update 3<commit_after>#pragma once
#include <vector>
#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/Point3f.hpp"
namespace dai {
/// Extrinsics structure
struct Extrinsics {
std::vector<std::vector<float>> rotationMatrix;
/**
* (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket obtained through calibration
*/
Point3f translation;
/**
* (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket measured through CAD design
*/
Point3f specTranslation;
CameraBoardSocket toCameraSocket = CameraBoardSocket::AUTO;
NLOHMANN_DEFINE_TYPE_INTRUSIVE(Extrinsics, rotationMatrix, translation, specTranslation, toCameraSocket);
};
} // namespace dai<|endoftext|>
|
<commit_before>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/
#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkKnownDriverIds.inl"
using namespace vk;
namespace vkt
{
namespace api
{
namespace
{
enum TestType
{
TEST_TYPE_DRIVER_ID_MATCH = 0,
TEST_TYPE_NAME_IS_NOT_EMPTY,
TEST_TYPE_NAME_ZERO_TERMINATED,
TEST_TYPE_INFO_ZERO_TERMINATED,
TEST_TYPE_VERSION,
};
static const VkConformanceVersionKHR knownConformanceVersions[] =
{
makeConformanceVersion(1, 2, 6, 1),
makeConformanceVersion(1, 2, 6, 0),
makeConformanceVersion(1, 2, 5, 2),
makeConformanceVersion(1, 2, 5, 1),
makeConformanceVersion(1, 2, 5, 0),
makeConformanceVersion(1, 2, 4, 1),
makeConformanceVersion(1, 2, 4, 0),
makeConformanceVersion(1, 2, 3, 3),
makeConformanceVersion(1, 2, 3, 2),
makeConformanceVersion(1, 2, 3, 1),
makeConformanceVersion(1, 2, 3, 0),
makeConformanceVersion(1, 2, 2, 2),
makeConformanceVersion(1, 2, 2, 1),
makeConformanceVersion(1, 2, 2, 0),
makeConformanceVersion(1, 2, 1, 2),
makeConformanceVersion(1, 2, 1, 1),
makeConformanceVersion(1, 2, 1, 0),
makeConformanceVersion(1, 2, 0, 2),
makeConformanceVersion(1, 2, 0, 1),
makeConformanceVersion(1, 2, 0, 0),
makeConformanceVersion(1, 1, 6, 3),
makeConformanceVersion(1, 1, 6, 2),
makeConformanceVersion(1, 1, 6, 1),
makeConformanceVersion(1, 1, 6, 0),
makeConformanceVersion(1, 1, 5, 2),
makeConformanceVersion(1, 1, 5, 1),
makeConformanceVersion(1, 1, 5, 0),
makeConformanceVersion(1, 1, 4, 3),
makeConformanceVersion(1, 1, 4, 2),
makeConformanceVersion(1, 1, 4, 1),
makeConformanceVersion(1, 1, 4, 0),
makeConformanceVersion(1, 1, 3, 3),
makeConformanceVersion(1, 1, 3, 2),
makeConformanceVersion(1, 1, 3, 1),
makeConformanceVersion(1, 1, 3, 0),
};
DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
return deStrnlen(str, maxSize) < maxSize;
}
DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
return ((a.major == b.major) &&
(a.minor == b.minor) &&
(a.subminor == b.subminor) &&
(a.patch == b.patch));
}
void checkSupport (Context& context, const TestType config)
{
DE_UNREF(config);
context.requireDeviceFunctionality("VK_KHR_driver_properties");
}
void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)
{
if (deviceDriverProperties.driverID == driverIds[driverNdx].id)
return;
}
TCU_FAIL("Driver ID did not match any known driver");
}
void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (deviceDriverProperties.driverName[0] == 0)
TCU_FAIL("Driver name is empty");
}
void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
TCU_FAIL("Driver name is not a null-terminated string");
}
void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
TCU_FAIL("Driver info is not a null-terminated string");
}
void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);
const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);
if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
{
TCU_FAIL("Wrong driver conformance version (older than used API version)");
}
for (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions;
pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
++pConformanceVersion)
{
if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
return;
}
TCU_FAIL("Wrong driver conformance version (not known)");
}
tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
// Query the driver properties
const VkPhysicalDevice physDevice = context.getPhysicalDevice();
const int memsetPattern = 0xaa;
VkPhysicalDeviceProperties2 deviceProperties2;
VkPhysicalDeviceDriverProperties deviceDriverProperties;
deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
deviceDriverProperties.pNext = DE_NULL;
deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
deviceProperties2.pNext = &deviceDriverProperties;
context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);
// Verify the returned values
switch (testType)
{
case TEST_TYPE_DRIVER_ID_MATCH: testDriverMatch (deviceDriverProperties); break;
case TEST_TYPE_NAME_IS_NOT_EMPTY: testNameIsNotEmpty (deviceDriverProperties); break;
case TEST_TYPE_NAME_ZERO_TERMINATED: testNameZeroTerminated (deviceDriverProperties); break;
case TEST_TYPE_INFO_ZERO_TERMINATED: testInfoZeroTerminated (deviceDriverProperties); break;
case TEST_TYPE_VERSION: testVersion (deviceDriverProperties, context.getUsedApiVersion()); break;
default: TCU_THROW(InternalError, "Unknown test type specified");
}
return tcu::TestStatus::pass("Pass");
}
void createTestCases (tcu::TestCaseGroup* group)
{
addFunctionCase(group, "driver_id_match", "Check driverID is supported", checkSupport, testQueryProperties, TEST_TYPE_DRIVER_ID_MATCH);
addFunctionCase(group, "name_is_not_empty", "Check name field is not empty", checkSupport, testQueryProperties, TEST_TYPE_NAME_IS_NOT_EMPTY);
addFunctionCase(group, "name_zero_terminated", "Check name field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_NAME_ZERO_TERMINATED);
addFunctionCase(group, "info_zero_terminated", "Check info field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_INFO_ZERO_TERMINATED);
addFunctionCase(group, "conformance_version", "Check conformanceVersion reported by driver", checkSupport, testQueryProperties, TEST_TYPE_VERSION);
}
} // anonymous
tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx)
{
return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}
} // api
} // vkt
<commit_msg>Allow Vulkan CTS 1.2.6.2<commit_after>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/
#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkKnownDriverIds.inl"
using namespace vk;
namespace vkt
{
namespace api
{
namespace
{
enum TestType
{
TEST_TYPE_DRIVER_ID_MATCH = 0,
TEST_TYPE_NAME_IS_NOT_EMPTY,
TEST_TYPE_NAME_ZERO_TERMINATED,
TEST_TYPE_INFO_ZERO_TERMINATED,
TEST_TYPE_VERSION,
};
static const VkConformanceVersionKHR knownConformanceVersions[] =
{
makeConformanceVersion(1, 2, 6, 2),
makeConformanceVersion(1, 2, 6, 1),
makeConformanceVersion(1, 2, 6, 0),
makeConformanceVersion(1, 2, 5, 2),
makeConformanceVersion(1, 2, 5, 1),
makeConformanceVersion(1, 2, 5, 0),
makeConformanceVersion(1, 2, 4, 1),
makeConformanceVersion(1, 2, 4, 0),
makeConformanceVersion(1, 2, 3, 3),
makeConformanceVersion(1, 2, 3, 2),
makeConformanceVersion(1, 2, 3, 1),
makeConformanceVersion(1, 2, 3, 0),
makeConformanceVersion(1, 2, 2, 2),
makeConformanceVersion(1, 2, 2, 1),
makeConformanceVersion(1, 2, 2, 0),
makeConformanceVersion(1, 2, 1, 2),
makeConformanceVersion(1, 2, 1, 1),
makeConformanceVersion(1, 2, 1, 0),
makeConformanceVersion(1, 2, 0, 2),
makeConformanceVersion(1, 2, 0, 1),
makeConformanceVersion(1, 2, 0, 0),
makeConformanceVersion(1, 1, 6, 3),
makeConformanceVersion(1, 1, 6, 2),
makeConformanceVersion(1, 1, 6, 1),
makeConformanceVersion(1, 1, 6, 0),
makeConformanceVersion(1, 1, 5, 2),
makeConformanceVersion(1, 1, 5, 1),
makeConformanceVersion(1, 1, 5, 0),
makeConformanceVersion(1, 1, 4, 3),
makeConformanceVersion(1, 1, 4, 2),
makeConformanceVersion(1, 1, 4, 1),
makeConformanceVersion(1, 1, 4, 0),
makeConformanceVersion(1, 1, 3, 3),
makeConformanceVersion(1, 1, 3, 2),
makeConformanceVersion(1, 1, 3, 1),
makeConformanceVersion(1, 1, 3, 0),
};
DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
return deStrnlen(str, maxSize) < maxSize;
}
DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
return ((a.major == b.major) &&
(a.minor == b.minor) &&
(a.subminor == b.subminor) &&
(a.patch == b.patch));
}
void checkSupport (Context& context, const TestType config)
{
DE_UNREF(config);
context.requireDeviceFunctionality("VK_KHR_driver_properties");
}
void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)
{
if (deviceDriverProperties.driverID == driverIds[driverNdx].id)
return;
}
TCU_FAIL("Driver ID did not match any known driver");
}
void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (deviceDriverProperties.driverName[0] == 0)
TCU_FAIL("Driver name is empty");
}
void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
TCU_FAIL("Driver name is not a null-terminated string");
}
void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
TCU_FAIL("Driver info is not a null-terminated string");
}
void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);
const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);
if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
{
TCU_FAIL("Wrong driver conformance version (older than used API version)");
}
for (const VkConformanceVersionKHR* pConformanceVersion = knownConformanceVersions;
pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
++pConformanceVersion)
{
if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
return;
}
TCU_FAIL("Wrong driver conformance version (not known)");
}
tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
// Query the driver properties
const VkPhysicalDevice physDevice = context.getPhysicalDevice();
const int memsetPattern = 0xaa;
VkPhysicalDeviceProperties2 deviceProperties2;
VkPhysicalDeviceDriverProperties deviceDriverProperties;
deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
deviceDriverProperties.pNext = DE_NULL;
deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
deviceProperties2.pNext = &deviceDriverProperties;
context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);
// Verify the returned values
switch (testType)
{
case TEST_TYPE_DRIVER_ID_MATCH: testDriverMatch (deviceDriverProperties); break;
case TEST_TYPE_NAME_IS_NOT_EMPTY: testNameIsNotEmpty (deviceDriverProperties); break;
case TEST_TYPE_NAME_ZERO_TERMINATED: testNameZeroTerminated (deviceDriverProperties); break;
case TEST_TYPE_INFO_ZERO_TERMINATED: testInfoZeroTerminated (deviceDriverProperties); break;
case TEST_TYPE_VERSION: testVersion (deviceDriverProperties, context.getUsedApiVersion()); break;
default: TCU_THROW(InternalError, "Unknown test type specified");
}
return tcu::TestStatus::pass("Pass");
}
void createTestCases (tcu::TestCaseGroup* group)
{
addFunctionCase(group, "driver_id_match", "Check driverID is supported", checkSupport, testQueryProperties, TEST_TYPE_DRIVER_ID_MATCH);
addFunctionCase(group, "name_is_not_empty", "Check name field is not empty", checkSupport, testQueryProperties, TEST_TYPE_NAME_IS_NOT_EMPTY);
addFunctionCase(group, "name_zero_terminated", "Check name field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_NAME_ZERO_TERMINATED);
addFunctionCase(group, "info_zero_terminated", "Check info field is zero-terminated", checkSupport, testQueryProperties, TEST_TYPE_INFO_ZERO_TERMINATED);
addFunctionCase(group, "conformance_version", "Check conformanceVersion reported by driver", checkSupport, testQueryProperties, TEST_TYPE_VERSION);
}
} // anonymous
tcu::TestCaseGroup* createDriverPropertiesTests(tcu::TestContext& testCtx)
{
return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}
} // api
} // vkt
<|endoftext|>
|
<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <cstddef>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <windows.h>
#include <winnt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/pelib/nt_headers.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/pelib/tls_dir.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/read.hpp>
#include <hadesmem/write.hpp>
// TODO: Handle forwarded imports.
// TODO: Handle bound imports (both new way and old way).
// TODO: This should really be called ImportDescriptor.
namespace hadesmem
{
class ImportDir
{
public:
explicit ImportDir(Process const& process,
PeFile const& pe_file,
PIMAGE_IMPORT_DESCRIPTOR imp_desc)
: process_(&process),
pe_file_(&pe_file),
base_(reinterpret_cast<PBYTE>(imp_desc)),
data_(),
is_virtual_beg_(false)
{
if (!base_)
{
NtHeaders nt_headers(process, pe_file);
DWORD const import_dir_rva =
nt_headers.GetDataDirectoryVirtualAddress(PeDataDir::Import);
// Windows will load images which don't specify a size for the import
// directory.
if (!import_dir_rva)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Import directory is invalid."));
}
base_ = static_cast<PBYTE>(RvaToVa(process, pe_file, import_dir_rva));
if (!base_)
{
// Try to detect import dirs with a partially virtual descriptor
// (overlapped at the beginning). Up to the first 3 DWORDS can be
// overlapped (because they're allowed to be zero without invalidating
// the entry).
// Sample: imports_virtdesc.exe (Corkami PE Corpus)
void* desc_raw_beg = nullptr;
int i = 3;
do
{
auto const new_rva =
static_cast<DWORD>(import_dir_rva + sizeof(DWORD) * i);
auto const new_va = RvaToVa(process, pe_file, new_rva);
if (!new_va)
{
break;
}
desc_raw_beg = new_va;
} while (--i);
if (desc_raw_beg)
{
auto const offset = sizeof(DWORD) * (i + 1);
auto const len = sizeof(IMAGE_IMPORT_DESCRIPTOR) - offset;
auto const buf =
ReadVector<std::uint8_t>(*process_, desc_raw_beg, len);
auto const data_beg =
reinterpret_cast<std::uint8_t*>(&data_) + offset;
ZeroMemory(&data_, sizeof(data_));
std::copy(std::begin(buf), std::end(buf), data_beg);
base_ = static_cast<std::uint8_t*>(desc_raw_beg) - offset;
is_virtual_beg_ = true;
}
else
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Import directory is invalid."));
}
}
}
UpdateRead();
}
PVOID GetBase() const HADESMEM_DETAIL_NOEXCEPT
{
return base_;
}
void UpdateRead()
{
data_ = Read<IMAGE_IMPORT_DESCRIPTOR>(*process_, base_);
}
void UpdateWrite()
{
Write(*process_, base_, data_);
}
// Check for virtual descriptor overlap trick.
bool IsVirtualBegin() const
{
return is_virtual_beg_;
}
// Check for virtual termination trick.
// TODO: Think about what the best way to solve this is... Currently we're
// forcing the user to thunk about it, which may not be ideal.
bool IsVirtualTerminated() const
{
// It's possible for the last entry to be in virtual space, because it only
// needs to have its Name or FirstThunk null.
// Sample: imports_vterm.exe (Corkami PE Corpus)
// TODO: Fix this for cases where a virtual descriptor is 'real', rather
// than just used as a terminator.
if (pe_file_->GetType() == PeFileType::Data &&
(base_ + sizeof(IMAGE_IMPORT_DESCRIPTOR)) >=
static_cast<PBYTE>(pe_file_->GetBase()) + pe_file_->GetSize())
{
return true;
}
return false;
}
// Check for TLS AOI trick.
// Sample: manyimportsW7.exe (Corkami PE Corpus)
// TODO: Think about what the best way to solve this is... Currently we're
// forcing the user to thunk about it, which may not be ideal.
bool IsTlsAoiTerminated() const
{
try
{
TlsDir tls_dir(*process_, *pe_file_);
ULONG_PTR const image_base = GetRuntimeBase(*process_, *pe_file_);
auto const address_of_index_raw =
RvaToVa(*process_,
*pe_file_,
static_cast<DWORD>(tls_dir.GetAddressOfIndex() - image_base));
return (address_of_index_raw ==
base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, Name) ||
address_of_index_raw ==
base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, FirstThunk));
}
catch (std::exception const& /*e*/)
{
return false;
}
}
DWORD GetOriginalFirstThunk() const
{
return data_.OriginalFirstThunk;
}
DWORD GetTimeDateStamp() const
{
return data_.TimeDateStamp;
}
DWORD GetForwarderChain() const
{
return data_.ForwarderChain;
}
DWORD GetNameRaw() const
{
return data_.Name;
}
std::string GetName() const
{
DWORD const name_rva = GetNameRaw();
if (!name_rva)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Name RVA is invalid."));
}
auto name_va =
static_cast<std::uint8_t*>(RvaToVa(*process_, *pe_file_, name_rva));
// It's possible for the RVA to be invalid on disk because it's fixed by
// relocations.
// TODO: Handle this case.
// Sample: imports_relocW7.exe
if (!name_va)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Name VA is invalid."));
}
if (pe_file_->GetType() == PeFileType::Image)
{
return ReadString<char>(*process_, name_va);
}
else if (pe_file_->GetType() == PeFileType::Data)
{
std::string name;
// Handle EOF termination.
// Sample: maxsecXP.exe (Corkami PE Corpus)
// TODO: Fix the perf of this.
// TODO: Detect and handle the case where the string is terminated
// virtually.
void const* const file_end =
static_cast<std::uint8_t const*>(pe_file_->GetBase()) +
pe_file_->GetSize();
while (name_va < file_end)
{
if (char const c = Read<char>(*process_, name_va++))
{
name.push_back(c);
}
else
{
break;
}
}
return name;
}
else
{
HADESMEM_DETAIL_ASSERT(false);
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Unknown PE file type."));
}
}
DWORD GetFirstThunk() const
{
return data_.FirstThunk;
}
void SetOriginalFirstThunk(DWORD original_first_thunk)
{
data_.OriginalFirstThunk = original_first_thunk;
}
void SetTimeDateStamp(DWORD time_date_stamp)
{
data_.TimeDateStamp = time_date_stamp;
}
void SetForwarderChain(DWORD forwarder_chain)
{
data_.ForwarderChain = forwarder_chain;
}
void SetNameRaw(DWORD name)
{
data_.Name = name;
}
void SetName(std::string const& name)
{
DWORD name_rva =
Read<DWORD>(*process_, base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, Name));
if (!name_rva)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Name RVA is null."));
}
PVOID name_ptr = RvaToVa(*process_, *pe_file_, name_rva);
if (!name_ptr)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Name VA is null."));
}
std::string const cur_name = ReadString<char>(*process_, name_ptr);
// TODO: Support allocating space for a new name rather than just
// overwriting the existing one.
if (name.size() > cur_name.size())
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("New name longer than existing name."));
}
return WriteString(*process_, name_ptr, name);
}
void SetFirstThunk(DWORD first_thunk)
{
data_.FirstThunk = first_thunk;
}
private:
Process const* process_;
PeFile const* pe_file_;
PBYTE base_;
IMAGE_IMPORT_DESCRIPTOR data_;
bool is_virtual_beg_;
};
inline bool operator==(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() == rhs.GetBase();
}
inline bool operator!=(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return !(lhs == rhs);
}
inline bool operator<(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() < rhs.GetBase();
}
inline bool operator<=(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() <= rhs.GetBase();
}
inline bool operator>(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() > rhs.GetBase();
}
inline bool operator>=(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() >= rhs.GetBase();
}
inline std::ostream& operator<<(std::ostream& lhs, ImportDir const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << rhs.GetBase();
lhs.imbue(old);
return lhs;
}
inline std::wostream& operator<<(std::wostream& lhs, ImportDir const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << rhs.GetBase();
lhs.imbue(old);
return lhs;
}
}
<commit_msg>* [ImportDir] Note to self.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.
#pragma once
#include <cstddef>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <string>
#include <utility>
#include <windows.h>
#include <winnt.h>
#include <hadesmem/config.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/pelib/nt_headers.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/pelib/tls_dir.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/read.hpp>
#include <hadesmem/write.hpp>
// TODO: Handle forwarded imports.
// TODO: Handle bound imports (both new way and old way).
// TODO: This should really be called ImportDescriptor.
namespace hadesmem
{
class ImportDir
{
public:
explicit ImportDir(Process const& process,
PeFile const& pe_file,
PIMAGE_IMPORT_DESCRIPTOR imp_desc)
: process_(&process),
pe_file_(&pe_file),
base_(reinterpret_cast<PBYTE>(imp_desc)),
data_(),
is_virtual_beg_(false)
{
if (!base_)
{
NtHeaders nt_headers(process, pe_file);
DWORD const import_dir_rva =
nt_headers.GetDataDirectoryVirtualAddress(PeDataDir::Import);
// Windows will load images which don't specify a size for the import
// directory.
if (!import_dir_rva)
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Import directory is invalid."));
}
base_ = static_cast<PBYTE>(RvaToVa(process, pe_file, import_dir_rva));
if (!base_)
{
// Try to detect import dirs with a partially virtual descriptor
// (overlapped at the beginning). Up to the first 3 DWORDS can be
// overlapped (because they're allowed to be zero without invalidating
// the entry).
// Sample: imports_virtdesc.exe (Corkami PE Corpus)
void* desc_raw_beg = nullptr;
int i = 3;
do
{
auto const new_rva =
static_cast<DWORD>(import_dir_rva + sizeof(DWORD) * i);
auto const new_va = RvaToVa(process, pe_file, new_rva);
if (!new_va)
{
break;
}
desc_raw_beg = new_va;
} while (--i);
if (desc_raw_beg)
{
auto const offset = sizeof(DWORD) * (i + 1);
auto const len = sizeof(IMAGE_IMPORT_DESCRIPTOR) - offset;
auto const buf =
ReadVector<std::uint8_t>(*process_, desc_raw_beg, len);
auto const data_beg =
reinterpret_cast<std::uint8_t*>(&data_) + offset;
ZeroMemory(&data_, sizeof(data_));
std::copy(std::begin(buf), std::end(buf), data_beg);
base_ = static_cast<std::uint8_t*>(desc_raw_beg) - offset;
is_virtual_beg_ = true;
}
else
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("Import directory is invalid."));
}
}
}
UpdateRead();
}
PVOID GetBase() const HADESMEM_DETAIL_NOEXCEPT
{
return base_;
}
// TODO: Support virtual overlap trick properly, because currently we're
// reading garbage memory.
// TODO: Support virtual termination trick properly, because currently we're
// reading garbage memory.
void UpdateRead()
{
data_ = Read<IMAGE_IMPORT_DESCRIPTOR>(*process_, base_);
}
void UpdateWrite()
{
Write(*process_, base_, data_);
}
// Check for virtual descriptor overlap trick.
bool IsVirtualBegin() const
{
return is_virtual_beg_;
}
// Check for virtual termination trick.
// TODO: Think about what the best way to solve this is... Currently we're
// forcing the user to thunk about it, which may not be ideal.
bool IsVirtualTerminated() const
{
// It's possible for the last entry to be in virtual space, because it only
// needs to have its Name or FirstThunk null.
// Sample: imports_vterm.exe (Corkami PE Corpus)
if (pe_file_->GetType() == PeFileType::Data &&
(base_ + sizeof(IMAGE_IMPORT_DESCRIPTOR)) >=
static_cast<PBYTE>(pe_file_->GetBase()) + pe_file_->GetSize())
{
return true;
}
return false;
}
// Check for TLS AOI trick.
// Sample: manyimportsW7.exe (Corkami PE Corpus)
// TODO: Think about what the best way to solve this is... Currently we're
// forcing the user to thunk about it, which may not be ideal.
bool IsTlsAoiTerminated() const
{
try
{
TlsDir tls_dir(*process_, *pe_file_);
ULONG_PTR const image_base = GetRuntimeBase(*process_, *pe_file_);
auto const address_of_index_raw =
RvaToVa(*process_,
*pe_file_,
static_cast<DWORD>(tls_dir.GetAddressOfIndex() - image_base));
return (address_of_index_raw ==
base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, Name) ||
address_of_index_raw ==
base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, FirstThunk));
}
catch (std::exception const& /*e*/)
{
return false;
}
}
DWORD GetOriginalFirstThunk() const
{
return data_.OriginalFirstThunk;
}
DWORD GetTimeDateStamp() const
{
return data_.TimeDateStamp;
}
DWORD GetForwarderChain() const
{
return data_.ForwarderChain;
}
DWORD GetNameRaw() const
{
return data_.Name;
}
std::string GetName() const
{
DWORD const name_rva = GetNameRaw();
if (!name_rva)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Name RVA is invalid."));
}
auto name_va =
static_cast<std::uint8_t*>(RvaToVa(*process_, *pe_file_, name_rva));
// It's possible for the RVA to be invalid on disk because it's fixed by
// relocations.
// TODO: Handle this case.
// Sample: imports_relocW7.exe
if (!name_va)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Name VA is invalid."));
}
if (pe_file_->GetType() == PeFileType::Image)
{
return ReadString<char>(*process_, name_va);
}
else if (pe_file_->GetType() == PeFileType::Data)
{
std::string name;
// Handle EOF termination.
// Sample: maxsecXP.exe (Corkami PE Corpus)
// TODO: Fix the perf of this.
// TODO: Detect and handle the case where the string is terminated
// virtually.
void const* const file_end =
static_cast<std::uint8_t const*>(pe_file_->GetBase()) +
pe_file_->GetSize();
while (name_va < file_end)
{
if (char const c = Read<char>(*process_, name_va++))
{
name.push_back(c);
}
else
{
break;
}
}
return name;
}
else
{
HADESMEM_DETAIL_ASSERT(false);
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Unknown PE file type."));
}
}
DWORD GetFirstThunk() const
{
return data_.FirstThunk;
}
void SetOriginalFirstThunk(DWORD original_first_thunk)
{
data_.OriginalFirstThunk = original_first_thunk;
}
void SetTimeDateStamp(DWORD time_date_stamp)
{
data_.TimeDateStamp = time_date_stamp;
}
void SetForwarderChain(DWORD forwarder_chain)
{
data_.ForwarderChain = forwarder_chain;
}
void SetNameRaw(DWORD name)
{
data_.Name = name;
}
void SetName(std::string const& name)
{
DWORD name_rva =
Read<DWORD>(*process_, base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, Name));
if (!name_rva)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Name RVA is null."));
}
PVOID name_ptr = RvaToVa(*process_, *pe_file_, name_rva);
if (!name_ptr)
{
HADESMEM_DETAIL_THROW_EXCEPTION(Error()
<< ErrorString("Name VA is null."));
}
std::string const cur_name = ReadString<char>(*process_, name_ptr);
// TODO: Support allocating space for a new name rather than just
// overwriting the existing one.
if (name.size() > cur_name.size())
{
HADESMEM_DETAIL_THROW_EXCEPTION(
Error() << ErrorString("New name longer than existing name."));
}
return WriteString(*process_, name_ptr, name);
}
void SetFirstThunk(DWORD first_thunk)
{
data_.FirstThunk = first_thunk;
}
private:
Process const* process_;
PeFile const* pe_file_;
PBYTE base_;
IMAGE_IMPORT_DESCRIPTOR data_;
bool is_virtual_beg_;
};
inline bool operator==(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() == rhs.GetBase();
}
inline bool operator!=(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return !(lhs == rhs);
}
inline bool operator<(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() < rhs.GetBase();
}
inline bool operator<=(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() <= rhs.GetBase();
}
inline bool operator>(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() > rhs.GetBase();
}
inline bool operator>=(ImportDir const& lhs, ImportDir const& rhs)
HADESMEM_DETAIL_NOEXCEPT
{
return lhs.GetBase() >= rhs.GetBase();
}
inline std::ostream& operator<<(std::ostream& lhs, ImportDir const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << rhs.GetBase();
lhs.imbue(old);
return lhs;
}
inline std::wostream& operator<<(std::wostream& lhs, ImportDir const& rhs)
{
std::locale const old = lhs.imbue(std::locale::classic());
lhs << rhs.GetBase();
lhs.imbue(old);
return lhs;
}
}
<|endoftext|>
|
<commit_before><commit_msg>Added missing <limits> header<commit_after><|endoftext|>
|
<commit_before>#ifndef SIMDIFY_STRUCTURE_OF_ARRAYS
#define SIMDIFY_STRUCTURE_OF_ARRAYS
#include "../simdify.hpp"
#include "../containers.hpp"
#include "../util/inline.hpp"
#include "named_array.hpp"
namespace simd {
template <typename Simd_t, id... Ids>
struct structure_of_arrays;
template <typename Mm_t, typename F_t, typename Simd_t, id...Ids>
struct structure_of_arrays<simd_base<Mm_t, F_t, Simd_t>, Ids...> {
static constexpr std::size_t N = sizeof...(Ids);
using simd_t = Simd_t;
using f_t = F_t;
using mm_t = Mm_t;
template <typename T>
struct iterator_base : named_array<T, Ids...> {};
struct iterator : iterator_base<simd_t> {};
struct const_iterator : iterator_base<const simd_t> {};
template <typename T>
struct tail_iterator_base : named_array<T, Ids...> {};
struct tail_iterator : tail_iterator_base<f_t&> {};
struct const_tail_iterator : tail_iterator_base<const f_t&> {};
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
const_iterator cbegin() const;
const_iterator cend() const;
iterator bodybegin();
iterator bodyend();
const_iterator bodybegin() const;
const_iterator bodyend() const;
const_iterator bodycbegin() const;
const_iterator bodycend() const;
tail_iterator tailbegin();
tail_iterator tailend();
const_tail_iterator tailbegin() const;
const_tail_iterator tailend() const;
const_tail_iterator tailcbegin() const;
const_tail_iterator tailcend() const;
};
}
#endif // SIMDIFY_STRUCTURE_OF_ARRAYS
<commit_msg>Iterators for structure_of_arrays (work in progress)<commit_after>#ifndef SIMDIFY_STRUCTURE_OF_ARRAYS
#define SIMDIFY_STRUCTURE_OF_ARRAYS
#include "../simdify.hpp"
#include "../containers.hpp"
#include "../util/inline.hpp"
#include "../util/malloc.hpp"
#include "expr.hpp"
#include "named_array.hpp"
#include <array>
#include <vector>
namespace simd {
template <typename Simd_t, id... Ids>
struct structure_of_arrays;
template <typename Mm_t, typename F_t, typename Simd_t, id...Ids>
struct structure_of_arrays<simd_base<Mm_t, F_t, Simd_t>, Ids...> {
using simd_t = Simd_t;
using f_t = F_t;
using mm_t = Mm_t;
enum : std::size_t { N = sizeof...(Ids), W = simd_t::W };
struct iterator {
using buffer_t = named_array<expr::aligned<f_t>, Ids...>;
template <typename Func>
struct TransformItem {
iterator& m_it;
Func m_f;
SIMDIFY_FORCE_INLINE constexpr TransformItem(iterator& it, Func&& f) :
m_it(it), m_f(std::move(f)) {}
template <std::size_t I>
SIMDIFY_FORCE_INLINE constexpr void perform() const {
m_f(simd::get<I>(m_it.m_buf).ptr);
}
};
iterator(structure_of_arrays& from, std::size_t index) {
detail::ForEach(N)::perform(TransformItem(*this, [&from, index](f_t*& ptr) {
ptr = std::get<N>(from.m_data).data() + from;
}));
}
iterator& operator++() {
detail::ForEach(N)::perform(TransformItem(*this, [](f_t*& ptr) {
ptr += W;
}));
return *this;
}
bool operator==(const iterator& rhs) { return simd::get<0>(m_buf).ptr == simd::get<0>(rhs.m_buf).ptr; }
bool operator!=(const iterator& rhs) { return simd::get<0>(m_buf).ptr != simd::get<0>(rhs.m_buf).ptr; }
buffer_t& operator*() const { return m_buf; }
buffer_t& operator->() const { return m_buf; }
private:
buffer_t m_buf;
};
//iterator begin();
//iterator end();
//const_iterator begin() const;
//const_iterator end() const;
//const_iterator cbegin() const;
//const_iterator cend() const;
//iterator bodybegin();
//iterator bodyend();
//const_iterator bodybegin() const;
//const_iterator bodyend() const;
//const_iterator bodycbegin() const;
//const_iterator bodycend() const;
//tail_iterator tailbegin();
//tail_iterator tailend();
//const_tail_iterator tailbegin() const;
//const_tail_iterator tailend() const;
//const_tail_iterator tailcbegin() const;
//const_tail_iterator tailcend() const;
private:
std::array<std::vector<f_t, aligned_allocator<f_t, alignof(mm_t)>>, N> m_data;
};
}
#endif // SIMDIFY_STRUCTURE_OF_ARRAYS
<|endoftext|>
|
<commit_before>
#ifndef INTERCOM_CPP_POSIX_IUNKNOWN_H
#define INTERCOM_CPP_POSIX_IUNKNOWN_H
#include "../callingconvention.hpp"
#include "../datatypes.hpp"
#include "../error_codes.hpp"
#include "../guiddef.hpp"
// MIDL_INTERFACE("00000000-0000-0000-C000-000000000046")
struct ISupportErrorInfo
{
public:
virtual intercom::HRESULT INTERCOM_CC InterfaceSupportsErrorInfo(
intercom::REFIID riid
) = 0;
};
static const intercom::IID IID_ISupportErrorInfo = { 0xDF0B3D60, 0x548F, 0x101B, { 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19 } };
#endif
<commit_msg>Add IErrorInfo definition to posix<commit_after>
#ifndef INTERCOM_CPP_POSIX_ISUPPORTERRORINFO_H
#define INTERCOM_CPP_POSIX_ISUPPORTERRORINFO_H
#include "../callingconvention.hpp"
#include "../datatypes.hpp"
#include "../error_codes.hpp"
#include "../guiddef.hpp"
#include "datatypes.hpp"
// MIDL_INTERFACE("1CF2B120-547D-101B-8E65-08002B2BD119")
struct IErrorInfo : public IUnknown
{
public:
virtual intercom::HRESULT INTERCOM_CC GetGUID(
intercom::GUID *pGUID) = 0;
virtual intercom::HRESULT INTERCOM_CC GetSource(
intercom::BSTR *pBstrSource) = 0;
virtual intercom::HRESULT INTERCOM_CC GetDescription(
intercom::BSTR *pBstrDescription) = 0;
virtual intercom::HRESULT INTERCOM_CC GetHelpFile(
intercom::BSTR *pBstrHelpFile) = 0;
virtual intercom::HRESULT INTERCOM_CC GetHelpContext(
intercom::DWORD *pdwHelpContext) = 0;
};
static const intercom::IID IID_IErrorInfo = {
0x1CF2B120, 0x547D, 0x101B,
{ 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19 } };
// MIDL_INTERFACE("DF0B3D60-548F-101B-8E65-08002B2BD119" )
struct ISupportErrorInfo : public IUnknown
{
public:
virtual intercom::HRESULT INTERCOM_CC InterfaceSupportsErrorInfo(
intercom::REFIID riid
) = 0;
};
static const intercom::IID IID_ISupportErrorInfo = { 0xDF0B3D60, 0x548F, 0x101B, { 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19 } };
#endif
<|endoftext|>
|
<commit_before>/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/***************************************************************************
testContentDict16.cpp - description
-------------------
begin : lun jun 2 2003
copyright : (C) 2003 by Olivier Mesnard
email : olivier.mesnard@cea.fr
***************************************************************************/
/***************************************************************************
* *
* compact dictionnary based on finite state automata *
* implemented with Boost Graph library *
* *
***************************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "common/LimaCommon.h"
#include "common/time/traceUtils.h"
// string and file handling Utilities
#include "common/Data/strwstrtools.h"
#include "common/FsaAccess/FsaAccessSpare16.h"
#include "common/StringMap/IndirectDataDico.h"
#include "common/StringMap/SimpleDataDico.h"
#include <QtCore/QCoreApplication>
//#include "common/linguisticData/linguisticData.h"
using namespace Lima;
using namespace Lima::Common;
using namespace Lima::Common::FsaAccess;
using namespace Lima::Common::StringMap;
//using namespace Lima::Common::LinguisticData;
// options
typedef struct ParamStruct {
std::string key;
int offset;
std::string keyFileName;
std::string dataFileName;
std::string accessMethod;
bool withAssert;
std::string contentType;
} Param;
void testSimpleDataDico(const Param& param );
void testAnalysisDico(const Param& param );
#include "common/tools/LimaMainTaskRunner.h"
#include "common/AbstractFactoryPattern/AmosePluginsManager.h"
#include <QtCore/QTimer>
int run(int aargc,char** aargv);
int main(int argc, char **argv)
{
QCoreApplication a(argc, argv);
// Task parented to the application so that it
// will be deleted by the application.
LimaMainTaskRunner* task = new LimaMainTaskRunner(argc, argv, run, &a);
// This will cause the application to exit when
// the task signals finished.
QObject::connect(task, SIGNAL(finished(int)), &a, SLOT(quit()));
// This will run the task from the application event loop.
QTimer::singleShot(0, task, SLOT(run()));
return a.exec();
}
int run(int argc,char** argv)
{
QsLogging::initQsLog();
// Necessary to initialize factories
Lima::AmosePluginsManager::single();
cerr << "testContentDict16 begin..." << endl;
setlocale(LC_ALL, "");
#ifdef DEBUG_CD
FSAALOGINIT;
LDEBUG << "testContentDict16 begin...";
#endif
// options reading
Param param = {
std::string(), // key
0, // offset
std::string(), // keyFileName
std::string(), // dataFileName
std::string(), // accessMethod
false, // withAssert
std::string() // contentType
};
for (int i = 1 ; i < argc; i++) {
std::string arg(argv[i]);
std::string::size_type pos = std::string::npos;
if (arg == "--help")
{
std::cerr << "usage: " << argv[0]
<< " --help" << std::endl;
std::cerr << " " << argv[0]
<< " [--key=<word>]"
<< " [--offset=<int>]"
<< " [--keyFileName=<filename>]"
<< " [--dataFileName=<filename>]"
<< " [--accessMethod=Fsa|Tree]"
<< " [--contentType=simple|indirect]"
<< " [--codetaFileName=<filename>]"
<< " [--language=fre|eng]"
<< " [--withAssert]"
<< std::endl;
return 0;
}
else if ( (pos = arg.find("--keyFileName=")) != std::string::npos ){
param.keyFileName = arg.substr(pos+14);
}
else if ( (pos = arg.find("--dataFileName=")) != std::string::npos ){
param.dataFileName = arg.substr(pos+15);
}
else if ( (pos = arg.find("--key=")) != std::string::npos ){
param.key = arg.substr(pos+6);
}
else if ( (pos = arg.find("--offset=")) != std::string::npos ){
param.offset = atoi( (arg.substr(pos+9)).c_str() );
}
else if ( arg.compare("--withAssert") == 0 ){
param.withAssert = true;
}
else if ( (pos = arg.find("--accessMethod=")) != std::string::npos ){
param.accessMethod = arg.substr(pos+15);
}
else if ( (pos = arg.find("--contentType=")) != std::string::npos ){
std::cerr << "arg = " << arg << std::endl;
param.contentType = arg.substr(pos+14);
}
}
cerr << "testContentDict16: ";
if(param.keyFileName.size()) {
cerr << "--keyFileName='" << param.keyFileName << "' ";
}
if(param.dataFileName.size()) {
cerr << "--dataFileName='" << param.dataFileName << "' ";
}
if(param.withAssert) {
cerr << "--withAssert ";
}
if(param.accessMethod.size()) {
cerr << "--accessMethod='" << param.accessMethod << "' ";
}
if(param.contentType.size()) {
cerr << "--contentType='" << param.contentType << "' ";
}
cerr << "--key="<< param.key << " ";
cerr << "--offset="<< param.offset << " ";
cerr << endl;
if( !param.contentType.compare(std::string("simple")) ) {
// Test dictionnaire simple (type dictionnaire de fr�uence)
testSimpleDataDico(param);
}
if( !param.contentType.compare(std::string("indirect")) ) {
// Test dictionnaire d'analyse
testAnalysisDico( param );
}
return EXIT_SUCCESS;
}
void testSimpleDataDico(const Param& param ) {
typedef int simpleDataElement;
typedef std::vector<simpleDataElement> simpleStoredSet;
typedef Lima::Common::FsaAccess::FsaAccessSpare16 accessMethod;
typedef Lima::Common::StringMap::SimpleDataDico<accessMethod, simpleDataElement,simpleStoredSet> SimpleDicoType;
SimpleDicoType* dico = new SimpleDicoType(-1);
dico->parseAccessMethod(param.keyFileName);
dico->parseData(param.dataFileName);
dico->getSize();
Lima::LimaString limaKey(Misc::utf8stdstring2limastring(param.key));
simpleDataElement val = dico->getElement(limaKey);
std::cout << "simpleDico->getElement(" << param.key << ") =" << val << std::endl;
}
typedef unsigned char* analysisDataElement;
typedef FsaAccessSpare16 accessMethod;
typedef IndirectDataDico<accessMethod,analysisDataElement> MyAnalysisBaseDico;
class MyAnalysisDico : public MyAnalysisBaseDico {
public:
MyAnalysisDico(const analysisDataElement& defaultValue)
: MyAnalysisBaseDico(defaultValue) {}
analysisDataElement getEntry( const Lima::LimaString& word) const;
};
analysisDataElement MyAnalysisDico::getEntry(
const Lima::LimaString& word) const{
int64_t index = -1;
std::cerr << "MyAnalysisDico::getEntry().." << std::endl;
#ifdef DEBUG_CD
STRINGMAPLOGINIT;
const LimaString & basicWord = word;
LDEBUG << "MyAnalysisDico::getEntry("
<< Lima::Common::Misc::convertString(basicWord) << ")";
#endif
// Look in FsaDictionary (or tree or..)
index = m_accessMethod.getIndex(word);
#ifdef DEBUG_CD
LDEBUG << "index = " << index;
#endif
index = m_accessMethod.getIndex(word);
// if( index > 0 ) ???
if( index >= 0 )
{
#ifdef DEBUG_CD
LDEBUG << "index = " << index;
#endif
analysisDataElement entry = m_data + m_index2Data[index];
return entry;
// return analysisDataElement(word, m_index2Data[index], m_dicoCode );
}
else
return m_emptyElement;
}
void testAnalysisDico(const Param& param ) {
string resourcesPath=getenv("LIMA_RESOURCES")==0?"/usr/share/apps/lima/resources":string(getenv("LIMA_RESOURCES"));
string commonConfigFile=string("lima-common.xml");
string configDir=getenv("LIMA_CONF")==0?"/usr/share/config/lima":string(getenv("LIMA_CONF"));
MyAnalysisDico* dico = new MyAnalysisDico(analysisDataElement(0));
dico->parseAccessMethod(param.keyFileName);
dico->parseData(param.dataFileName);
dico->getSize();
Lima::LimaString limaKey(Misc::utf8stdstring2limastring(param.key));
analysisDataElement entry = dico->getEntry(limaKey);
int v1 = *entry;
int v2 = *(entry+1);
std::cout << "analysisDico->getElement(" << param.key << ") ="
<< std::setbase(16) << v1 << "," << v2 << std::setbase(10) << std::endl;
}
<commit_msg>Correct a compile error<commit_after>/*
Copyright 2002-2013 CEA LIST
This file is part of LIMA.
LIMA is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LIMA is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with LIMA. If not, see <http://www.gnu.org/licenses/>
*/
/***************************************************************************
testContentDict16.cpp - description
-------------------
begin : lun jun 2 2003
copyright : (C) 2003 by Olivier Mesnard
email : olivier.mesnard@cea.fr
***************************************************************************/
/***************************************************************************
* *
* compact dictionnary based on finite state automata *
* implemented with Boost Graph library *
* *
***************************************************************************/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
#include "common/LimaCommon.h"
#include "common/time/traceUtils.h"
// string and file handling Utilities
#include "common/Data/strwstrtools.h"
#include "common/FsaAccess/FsaAccessSpare16.h"
#include "common/StringMap/IndirectDataDico.h"
#include "common/StringMap/SimpleDataDico.h"
#include <QtCore/QCoreApplication>
//#include "common/linguisticData/linguisticData.h"
using namespace Lima;
using namespace Lima::Common;
using namespace Lima::Common::FsaAccess;
using namespace Lima::Common::StringMap;
//using namespace Lima::Common::LinguisticData;
// options
typedef struct ParamStruct {
std::string key;
int offset;
std::string keyFileName;
std::string dataFileName;
std::string accessMethod;
bool withAssert;
std::string contentType;
} Param;
void testSimpleDataDico(const Param& param );
void testAnalysisDico(const Param& param );
#include "common/tools/LimaMainTaskRunner.h"
#include "common/AbstractFactoryPattern/AmosePluginsManager.h"
#include <QtCore/QTimer>
int run(int aargc,char** aargv);
int main(int argc, char **argv)
{
QCoreApplication a(argc, argv);
// Task parented to the application so that it
// will be deleted by the application.
LimaMainTaskRunner* task = new LimaMainTaskRunner(argc, argv, run, &a);
// This will cause the application to exit when
// the task signals finished.
QObject::connect(task, SIGNAL(finished(int)), &a, SLOT(quit()));
// This will run the task from the application event loop.
QTimer::singleShot(0, task, SLOT(run()));
return a.exec();
}
int run(int argc,char** argv)
{
QsLogging::initQsLog();
// Necessary to initialize factories
Lima::AmosePluginsManager::single();
cerr << "testContentDict16 begin..." << endl;
setlocale(LC_ALL, "");
#ifdef DEBUG_CD
FSAALOGINIT;
LDEBUG << "testContentDict16 begin...";
#endif
// options reading
Param param = {
std::string(), // key
0, // offset
std::string(), // keyFileName
std::string(), // dataFileName
std::string(), // accessMethod
false, // withAssert
std::string() // contentType
};
for (int i = 1 ; i < argc; i++) {
std::string arg(argv[i]);
std::string::size_type pos = std::string::npos;
if (arg == "--help")
{
std::cerr << "usage: " << argv[0]
<< " --help" << std::endl;
std::cerr << " " << argv[0]
<< " [--key=<word>]"
<< " [--offset=<int>]"
<< " [--keyFileName=<filename>]"
<< " [--dataFileName=<filename>]"
<< " [--accessMethod=Fsa|Tree]"
<< " [--contentType=simple|indirect]"
<< " [--codetaFileName=<filename>]"
<< " [--language=fre|eng]"
<< " [--withAssert]"
<< std::endl;
return 0;
}
else if ( (pos = arg.find("--keyFileName=")) != std::string::npos ){
param.keyFileName = arg.substr(pos+14);
}
else if ( (pos = arg.find("--dataFileName=")) != std::string::npos ){
param.dataFileName = arg.substr(pos+15);
}
else if ( (pos = arg.find("--key=")) != std::string::npos ){
param.key = arg.substr(pos+6);
}
else if ( (pos = arg.find("--offset=")) != std::string::npos ){
param.offset = atoi( (arg.substr(pos+9)).c_str() );
}
else if ( arg.compare("--withAssert") == 0 ){
param.withAssert = true;
}
else if ( (pos = arg.find("--accessMethod=")) != std::string::npos ){
param.accessMethod = arg.substr(pos+15);
}
else if ( (pos = arg.find("--contentType=")) != std::string::npos ){
std::cerr << "arg = " << arg << std::endl;
param.contentType = arg.substr(pos+14);
}
}
cerr << "testContentDict16: ";
if(param.keyFileName.size()) {
cerr << "--keyFileName='" << param.keyFileName << "' ";
}
if(param.dataFileName.size()) {
cerr << "--dataFileName='" << param.dataFileName << "' ";
}
if(param.withAssert) {
cerr << "--withAssert ";
}
if(param.accessMethod.size()) {
cerr << "--accessMethod='" << param.accessMethod << "' ";
}
if(param.contentType.size()) {
cerr << "--contentType='" << param.contentType << "' ";
}
cerr << "--key="<< param.key << " ";
cerr << "--offset="<< param.offset << " ";
cerr << endl;
if( !param.contentType.compare(std::string("simple")) ) {
// Test dictionnaire simple (type dictionnaire de fr�uence)
testSimpleDataDico(param);
}
if( !param.contentType.compare(std::string("indirect")) ) {
// Test dictionnaire d'analyse
testAnalysisDico( param );
}
return EXIT_SUCCESS;
}
void testSimpleDataDico(const Param& param ) {
typedef int simpleDataElement;
typedef std::vector<simpleDataElement> simpleStoredSet;
typedef Lima::Common::FsaAccess::FsaAccessSpare16 accessMethod;
typedef Lima::Common::StringMap::SimpleDataDico<accessMethod, simpleDataElement,simpleStoredSet> SimpleDicoType;
SimpleDicoType* dico = new SimpleDicoType(-1);
dico->parseAccessMethod(param.keyFileName);
dico->parseData(param.dataFileName);
dico->getSize();
Lima::LimaString limaKey(Misc::utf8stdstring2limastring(param.key));
simpleDataElement val = dico->getElement(limaKey);
std::cout << "simpleDico->getElement(" << param.key << ") =" << val << std::endl;
}
typedef unsigned char* analysisDataElement;
typedef FsaAccessSpare16 accessMethod;
typedef IndirectDataDico<accessMethod,analysisDataElement> MyAnalysisBaseDico;
class MyAnalysisDico : public MyAnalysisBaseDico {
public:
MyAnalysisDico(const analysisDataElement& defaultValue)
: MyAnalysisBaseDico(defaultValue) {}
analysisDataElement getEntry( const Lima::LimaString& word) const;
};
analysisDataElement MyAnalysisDico::getEntry(
const Lima::LimaString& word) const{
int64_t index = -1;
std::cerr << "MyAnalysisDico::getEntry().." << std::endl;
#ifdef DEBUG_CD
STRINGMAPLOGINIT;
LDEBUG << "MyAnalysisDico::getEntry(" << word << ")";
#endif
// Look in FsaDictionary (or tree or..)
index = m_accessMethod.getIndex(word);
#ifdef DEBUG_CD
LDEBUG << "index = " << index;
#endif
index = m_accessMethod.getIndex(word);
// if( index > 0 ) ???
if( index >= 0 )
{
#ifdef DEBUG_CD
LDEBUG << "index = " << index;
#endif
analysisDataElement entry = m_data + m_index2Data[index];
return entry;
// return analysisDataElement(word, m_index2Data[index], m_dicoCode );
}
else
return m_emptyElement;
}
void testAnalysisDico(const Param& param ) {
string resourcesPath=getenv("LIMA_RESOURCES")==0?"/usr/share/apps/lima/resources":string(getenv("LIMA_RESOURCES"));
string commonConfigFile=string("lima-common.xml");
string configDir=getenv("LIMA_CONF")==0?"/usr/share/config/lima":string(getenv("LIMA_CONF"));
MyAnalysisDico* dico = new MyAnalysisDico(analysisDataElement(0));
dico->parseAccessMethod(param.keyFileName);
dico->parseData(param.dataFileName);
dico->getSize();
Lima::LimaString limaKey(Misc::utf8stdstring2limastring(param.key));
analysisDataElement entry = dico->getEntry(limaKey);
int v1 = *entry;
int v2 = *(entry+1);
std::cout << "analysisDico->getElement(" << param.key << ") ="
<< std::setbase(16) << v1 << "," << v2 << std::setbase(10) << std::endl;
}
<|endoftext|>
|
<commit_before>// ConfigFile.cpp
#include "ConfigFile.h"
using std::string;
ConfigFile::ConfigFile( string filename, string delimiter,
string comment, string sentry )
: myDelimiter(delimiter), myComment(comment), mySentry(sentry)
{
// Construct a ConfigFile, getting keys and values from given file
std::ifstream in( filename.c_str() );
if( !in ) throw file_not_found( filename );
in >> (*this);
}
ConfigFile::ConfigFile()
: myDelimiter( string(1,'=') ), myComment( string(1,'#') )
{
// Construct a ConfigFile without a file; empty
}
void ConfigFile::remove( const string& key )
{
// Remove key and its value
myContents.erase( myContents.find( key ) );
return;
}
bool ConfigFile::keyExists( const string& key ) const
{
// Indicate whether key is found
mapci p = myContents.find( key );
return ( p != myContents.end() );
}
/* static */
void ConfigFile::trim( string& s )
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase( 0, s.find_first_not_of(whitespace) );
s.erase( s.find_last_not_of(whitespace) + 1U );
}
std::ostream& operator<<( std::ostream& os, const ConfigFile& cf )
{
// Save a ConfigFile to os
for( ConfigFile::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p )
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
std::istream& operator>>( std::istream& is, ConfigFile& cf )
{
// Load a ConfigFile from is
// Read in keys and values, keeping internal whitespace
typedef string::size_type pos;
const string& delim = cf.myDelimiter; // separator
const string& comm = cf.myComment; // comment
const string& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
string nextline = ""; // might need to read ahead to see where value ends
while( is || nextline.length() > 0 )
{
// Read an entire line at a time
string line;
if( nextline.length() > 0 )
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline( is, line );
}
// Ignore comments
line = line.substr( 0, line.find(comm) );
// Check for end of file sentry
if( sentry != "" && line.find(sentry) != string::npos ) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find( delim );
if( delimPos < string::npos )
{
// Extract the key
string key = line.substr( 0, delimPos );
line.replace( 0, delimPos+skip, "" );
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while( !terminate && is )
{
std::getline( is, nextline );
terminate = true;
string nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy == "" ) continue;
nextline = nextline.substr( 0, nextline.find(comm) );
if( nextline.find(delim) != string::npos )
continue;
if( sentry != "" && nextline.find(sentry) != string::npos )
continue;
nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy != "" ) line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
ConfigFile::trim(key);
ConfigFile::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
<commit_msg>oops forgot to change the reference to configfile here<commit_after>// ConfigFile.cpp
#include "configfile.hpp"
using std::string;
ConfigFile::ConfigFile( string filename, string delimiter,
string comment, string sentry )
: myDelimiter(delimiter), myComment(comment), mySentry(sentry)
{
// Construct a ConfigFile, getting keys and values from given file
std::ifstream in( filename.c_str() );
if( !in ) throw file_not_found( filename );
in >> (*this);
}
ConfigFile::ConfigFile()
: myDelimiter( string(1,'=') ), myComment( string(1,'#') )
{
// Construct a ConfigFile without a file; empty
}
void ConfigFile::remove( const string& key )
{
// Remove key and its value
myContents.erase( myContents.find( key ) );
return;
}
bool ConfigFile::keyExists( const string& key ) const
{
// Indicate whether key is found
mapci p = myContents.find( key );
return ( p != myContents.end() );
}
/* static */
void ConfigFile::trim( string& s )
{
// Remove leading and trailing whitespace
static const char whitespace[] = " \n\t\v\r\f";
s.erase( 0, s.find_first_not_of(whitespace) );
s.erase( s.find_last_not_of(whitespace) + 1U );
}
std::ostream& operator<<( std::ostream& os, const ConfigFile& cf )
{
// Save a ConfigFile to os
for( ConfigFile::mapci p = cf.myContents.begin();
p != cf.myContents.end();
++p )
{
os << p->first << " " << cf.myDelimiter << " ";
os << p->second << std::endl;
}
return os;
}
std::istream& operator>>( std::istream& is, ConfigFile& cf )
{
// Load a ConfigFile from is
// Read in keys and values, keeping internal whitespace
typedef string::size_type pos;
const string& delim = cf.myDelimiter; // separator
const string& comm = cf.myComment; // comment
const string& sentry = cf.mySentry; // end of file sentry
const pos skip = delim.length(); // length of separator
string nextline = ""; // might need to read ahead to see where value ends
while( is || nextline.length() > 0 )
{
// Read an entire line at a time
string line;
if( nextline.length() > 0 )
{
line = nextline; // we read ahead; use it now
nextline = "";
}
else
{
std::getline( is, line );
}
// Ignore comments
line = line.substr( 0, line.find(comm) );
// Check for end of file sentry
if( sentry != "" && line.find(sentry) != string::npos ) return is;
// Parse the line if it contains a delimiter
pos delimPos = line.find( delim );
if( delimPos < string::npos )
{
// Extract the key
string key = line.substr( 0, delimPos );
line.replace( 0, delimPos+skip, "" );
// See if value continues on the next line
// Stop at blank line, next line with a key, end of stream,
// or end of file sentry
bool terminate = false;
while( !terminate && is )
{
std::getline( is, nextline );
terminate = true;
string nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy == "" ) continue;
nextline = nextline.substr( 0, nextline.find(comm) );
if( nextline.find(delim) != string::npos )
continue;
if( sentry != "" && nextline.find(sentry) != string::npos )
continue;
nlcopy = nextline;
ConfigFile::trim(nlcopy);
if( nlcopy != "" ) line += "\n";
line += nextline;
terminate = false;
}
// Store key and value
ConfigFile::trim(key);
ConfigFile::trim(line);
cf.myContents[key] = line; // overwrites if key is repeated
}
}
return is;
}
<|endoftext|>
|
<commit_before>#ifndef MJOLNIR_POTENTIAL_GLOBAL_EXCLUDED_VOLUME_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_GLOBAL_EXCLUDED_VOLUME_POTENTIAL_HPP
#include <mjolnir/forcefield/global/ParameterList.hpp>
#include <mjolnir/core/ExclusionList.hpp>
#include <mjolnir/core/System.hpp>
#include <mjolnir/math/math.hpp>
#include <algorithm>
#include <numeric>
#include <memory>
#include <cmath>
namespace mjolnir
{
// excluded volume potential.
// This class contains radii of the particles and calculates energy and
// derivative of the potential function.
// This class is an implementation of the excluded volume term used in
// Clementi's off-lattice Go-like model (Clement et al., 2000) and AICG2+ model
// (Li et al., 2014)
//
// Note: When ExcludedVolume is used with GlobalPairInteraction, `calc_force`
// and `calc_energy` implemented here will not be used because we can
// optimize the runtime efficiency by specializing GlobalPairInteraction.
// See mjolnir/forcefield/GlobalExcludedVolumeInteraction.hpp for detail.
template<typename realT>
class ExcludedVolumePotential
{
public:
using real_type = realT;
struct parameter_type
{
real_type radius;
};
static constexpr real_type default_cutoff() noexcept
{
return real_type(2.0);
}
public:
ExcludedVolumePotential(
const real_type cutoff, const real_type epsilon) noexcept
: epsilon_(epsilon), cutoff_ratio_(cutoff),
coef_at_cutoff_(std::pow(real_type(1) / cutoff, 12))
{}
~ExcludedVolumePotential() = default;
ExcludedVolumePotential(const ExcludedVolumePotential&) = default;
ExcludedVolumePotential(ExcludedVolumePotential&&) = default;
ExcludedVolumePotential& operator=(const ExcludedVolumePotential&) = default;
ExcludedVolumePotential& operator=(ExcludedVolumePotential&&) = default;
real_type potential(const real_type r, const parameter_type& params) const noexcept
{
if(params.radius * this->cutoff_ratio_ < r){return 0;}
const real_type d_r = params.radius / r;
const real_type dr3 = d_r * d_r * d_r;
const real_type dr6 = dr3 * dr3;
return this->epsilon_ * (dr6 * dr6 - this->coef_at_cutoff_);
}
real_type derivative(const real_type r, const parameter_type& params) const noexcept
{
if(params.radius * this->cutoff_ratio_ < r){return 0;}
const real_type rinv = real_type(1) / r;
const real_type d_r = params.radius * rinv;
const real_type dr3 = d_r * d_r * d_r;
const real_type dr6 = dr3 * dr3;
return real_type(-12.0) * this->epsilon_ * dr6 * dr6 * rinv;
}
template<typename T>
void initialize(const System<T>&) noexcept {return;}
template<typename T>
void update(const System<T>&) noexcept {return;}
// ------------------------------------------------------------------------
// It takes per-particle parameters and return the maximum cutoff length.
// CombinationRule normally uses this.
// Note that, pair-parameter and per-particle parameter can differ from
// each other. Lorentz-Bertherot uses the same parameter_type because it is
// for L-J and L-J-like potentials that has {sigma, epsilon} for each
// particle and also for each pair of particles.
template<typename InputIterator>
real_type max_cutoff(const InputIterator first, const InputIterator last) const noexcept
{
static_assert(std::is_same<
typename std::iterator_traits<InputIterator>::value_type,
parameter_type>::value, "");
if(first == last) {return 1;}
real_type max_radius = 0;
for(auto iter = first; iter != last; ++iter)
{
const auto& parameter = *iter;
max_radius = std::max(max_radius, parameter.radius);
}
return max_radius * cutoff_ratio_;
}
// It returns absolute cutoff length using pair-parameter.
// `CombinationTable` uses this.
real_type absolute_cutoff(const parameter_type& params) const noexcept
{
return params.radius * cutoff_ratio_;
}
// ------------------------------------------------------------------------
// used by Observer.
static const char* name() noexcept {return "ExcludedVolume";}
// ------------------------------------------------------------------------
// the following accessers would be used in tests.
real_type& epsilon() noexcept {return this->epsilon_;}
real_type epsilon() const noexcept {return this->epsilon_;}
real_type cutoff_ratio() const noexcept {return cutoff_ratio_;}
real_type coef_at_cutoff() const noexcept {return coef_at_cutoff_;}
private:
real_type epsilon_;
real_type cutoff_ratio_;
real_type coef_at_cutoff_;
};
// Normally, this potential use the same epsilon value for all the pairs.
// Moreover, this potential takes a "radius", not a "diameter", as a paraemter.
// So we don't divide sigma_i + sigma_j by two. Since they are radii, just take
// the sum of them.
template<typename traitsT>
class ExcludedVolumeParameterList final
: public ParameterListBase<traitsT, ExcludedVolumePotential<typename traitsT::real_type>>
{
public:
using traits_type = traitsT;
using real_type = typename traits_type::real_type;
using potential_type = ExcludedVolumePotential<real_type>;
using base_type = ParameterListBase<traits_type, potential_type>;
// `pair_parameter_type` is a parameter for an interacting pair.
// Although it is the same type as `parameter_type` in this potential,
// it can be different from normal parameter for each particle.
// This enables NeighborList to cache a value to calculate forces between
// the particles, e.g. by having qi * qj for pair of particles i and j.
using parameter_type = typename potential_type::parameter_type;
using pair_parameter_type = typename potential_type::parameter_type;
using container_type = std::vector<parameter_type>;
// topology stuff
using system_type = System<traits_type>;
using topology_type = Topology;
using molecule_id_type = typename topology_type::molecule_id_type;
using group_id_type = typename topology_type::group_id_type;
using connection_kind_type = typename topology_type::connection_kind_type;
using ignore_molecule_type = IgnoreMolecule<molecule_id_type>;
using ignore_group_type = IgnoreGroup <group_id_type>;
using exclusion_list_type = ExclusionList<traits_type>;
public:
ExcludedVolumeParameterList(
const std::vector<std::pair<std::size_t, parameter_type>>& parameters,
const std::map<connection_kind_type, std::size_t>& exclusions,
ignore_molecule_type ignore_mol, ignore_group_type ignore_grp)
: exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp))
{
this->parameters_ .reserve(parameters.size());
this->participants_.reserve(parameters.size());
for(const auto& idxp : parameters)
{
const auto idx = idxp.first;
this->participants_.push_back(idx);
if(idx >= this->parameters_.size())
{
this->parameters_.resize(idx+1, parameter_type{real_type(0)});
}
this->parameters_.at(idx) = idxp.second;
}
}
~ExcludedVolumeParameterList() = default;
pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept override
{
return pair_parameter_type{parameters_[i].radius + parameters_[j].radius};
}
real_type max_cutoff_length() const noexcept override
{
return this->max_cutoff_length_;
}
void initialize(const system_type& sys, const topology_type& topol,
const potential_type& pot) noexcept override
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
this->update(sys, topol, pot); // calc parameters
return;
}
// for temperature/ionic concentration changes...
void update(const system_type& sys, const topology_type& topol,
const potential_type& pot) noexcept override
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
this->max_cutoff_length_ = pot.max_cutoff(parameters_.begin(), parameters_.end());
this->exclusion_list_.make(sys, topol);
return;
}
// -----------------------------------------------------------------------
// for spatial partitions
//
// Here, the default implementation uses Newton's 3rd law to reduce
// calculation. For an interacting pair (i, j), forces applied to i and j
// are equal in magnitude and opposite in direction. So, if a pair (i, j) is
// listed, (j, i) is not needed.
// See implementation of VerletList, CellList and GlobalPairInteraction
// for more details about the usage of these functions.
std::vector<std::size_t> const& participants() const noexcept override
{
return participants_;
}
range<typename std::vector<std::size_t>::const_iterator>
leading_participants() const noexcept override
{
return make_range(participants_.begin(), std::prev(participants_.end()));
}
range<typename std::vector<std::size_t>::const_iterator>
possible_partners_of(const std::size_t participant_idx,
const std::size_t /*particle_idx*/) const noexcept override
{
return make_range(participants_.begin() + participant_idx + 1,
participants_.end());
}
bool has_interaction(const std::size_t i, const std::size_t j) const noexcept override
{
return (i < j) && !exclusion_list_.is_excluded(i, j);
}
exclusion_list_type const& exclusion_list() const noexcept override
{
return exclusion_list_; // for testing
}
// ------------------------------------------------------------------------
// used by Observer.
static const char* name() noexcept {return "ExcludedVolume";}
// ------------------------------------------------------------------------
// the following accessers would be used in tests.
// access to the parameters.
std::vector<parameter_type>& parameters() noexcept {return parameters_;}
std::vector<parameter_type> const& parameters() const noexcept {return parameters_;}
base_type* clone() const override
{
return new ExcludedVolumeParameterList(*this);
}
private:
real_type max_cutoff_length_;
container_type parameters_;
std::vector<std::size_t> participants_;
exclusion_list_type exclusion_list_;
};
} // mjolnir
#ifdef MJOLNIR_SEPARATE_BUILD
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
namespace mjolnir
{
extern template class ExcludedVolumeParameterList<SimulatorTraits<double, UnlimitedBoundary> >;
extern template class ExcludedVolumeParameterList<SimulatorTraits<float, UnlimitedBoundary> >;
extern template class ExcludedVolumeParameterList<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class ExcludedVolumeParameterList<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
} // mjolnir
#endif// MJOLNIR_SEPARATE_BUILD
#endif /* MJOLNIR_EXCLUDED_VOLUME_POTENTIAL */
<commit_msg>fix: fix cutoff calculation in Exv<commit_after>#ifndef MJOLNIR_POTENTIAL_GLOBAL_EXCLUDED_VOLUME_POTENTIAL_HPP
#define MJOLNIR_POTENTIAL_GLOBAL_EXCLUDED_VOLUME_POTENTIAL_HPP
#include <mjolnir/forcefield/global/ParameterList.hpp>
#include <mjolnir/core/ExclusionList.hpp>
#include <mjolnir/core/System.hpp>
#include <mjolnir/math/math.hpp>
#include <algorithm>
#include <numeric>
#include <memory>
#include <cmath>
namespace mjolnir
{
// excluded volume potential.
// This class contains radii of the particles and calculates energy and
// derivative of the potential function.
// This class is an implementation of the excluded volume term used in
// Clementi's off-lattice Go-like model (Clement et al., 2000) and AICG2+ model
// (Li et al., 2014)
//
// Note: When ExcludedVolume is used with GlobalPairInteraction, `calc_force`
// and `calc_energy` implemented here will not be used because we can
// optimize the runtime efficiency by specializing GlobalPairInteraction.
// See mjolnir/forcefield/GlobalExcludedVolumeInteraction.hpp for detail.
template<typename realT>
class ExcludedVolumePotential
{
public:
using real_type = realT;
struct parameter_type
{
real_type radius;
};
static constexpr real_type default_cutoff() noexcept
{
return real_type(2.0);
}
public:
ExcludedVolumePotential(
const real_type cutoff, const real_type epsilon) noexcept
: epsilon_(epsilon), cutoff_ratio_(cutoff),
coef_at_cutoff_(std::pow(real_type(1) / cutoff, 12))
{}
~ExcludedVolumePotential() = default;
ExcludedVolumePotential(const ExcludedVolumePotential&) = default;
ExcludedVolumePotential(ExcludedVolumePotential&&) = default;
ExcludedVolumePotential& operator=(const ExcludedVolumePotential&) = default;
ExcludedVolumePotential& operator=(ExcludedVolumePotential&&) = default;
real_type potential(const real_type r, const parameter_type& params) const noexcept
{
if(params.radius * this->cutoff_ratio_ < r){return 0;}
const real_type d_r = params.radius / r;
const real_type dr3 = d_r * d_r * d_r;
const real_type dr6 = dr3 * dr3;
return this->epsilon_ * (dr6 * dr6 - this->coef_at_cutoff_);
}
real_type derivative(const real_type r, const parameter_type& params) const noexcept
{
if(params.radius * this->cutoff_ratio_ < r){return 0;}
const real_type rinv = real_type(1) / r;
const real_type d_r = params.radius * rinv;
const real_type dr3 = d_r * d_r * d_r;
const real_type dr6 = dr3 * dr3;
return real_type(-12.0) * this->epsilon_ * dr6 * dr6 * rinv;
}
template<typename T>
void initialize(const System<T>&) noexcept {return;}
template<typename T>
void update(const System<T>&) noexcept {return;}
// ------------------------------------------------------------------------
// It takes per-particle parameters and return the maximum cutoff length.
// CombinationRule normally uses this.
// Note that, pair-parameter and per-particle parameter can differ from
// each other. Lorentz-Bertherot uses the same parameter_type because it is
// for L-J and L-J-like potentials that has {sigma, epsilon} for each
// particle and also for each pair of particles.
template<typename InputIterator>
real_type max_cutoff(const InputIterator first, const InputIterator last) const noexcept
{
static_assert(std::is_same<
typename std::iterator_traits<InputIterator>::value_type,
parameter_type>::value, "");
if(first == last) {return 1;}
real_type max_radius = 0;
for(auto iter = first; iter != last; ++iter)
{
const auto& parameter = *iter;
max_radius = std::max(max_radius, parameter.radius);
}
return max_radius * 2 * cutoff_ratio_;
}
// It returns absolute cutoff length using pair-parameter.
// `CombinationTable` uses this.
real_type absolute_cutoff(const parameter_type& params) const noexcept
{
return params.radius * cutoff_ratio_;
}
// ------------------------------------------------------------------------
// used by Observer.
static const char* name() noexcept {return "ExcludedVolume";}
// ------------------------------------------------------------------------
// the following accessers would be used in tests.
real_type& epsilon() noexcept {return this->epsilon_;}
real_type epsilon() const noexcept {return this->epsilon_;}
real_type cutoff_ratio() const noexcept {return cutoff_ratio_;}
real_type coef_at_cutoff() const noexcept {return coef_at_cutoff_;}
private:
real_type epsilon_;
real_type cutoff_ratio_;
real_type coef_at_cutoff_;
};
// Normally, this potential use the same epsilon value for all the pairs.
// Moreover, this potential takes a "radius", not a "diameter", as a paraemter.
// So we don't divide sigma_i + sigma_j by two. Since they are radii, just take
// the sum of them.
template<typename traitsT>
class ExcludedVolumeParameterList final
: public ParameterListBase<traitsT, ExcludedVolumePotential<typename traitsT::real_type>>
{
public:
using traits_type = traitsT;
using real_type = typename traits_type::real_type;
using potential_type = ExcludedVolumePotential<real_type>;
using base_type = ParameterListBase<traits_type, potential_type>;
// `pair_parameter_type` is a parameter for an interacting pair.
// Although it is the same type as `parameter_type` in this potential,
// it can be different from normal parameter for each particle.
// This enables NeighborList to cache a value to calculate forces between
// the particles, e.g. by having qi * qj for pair of particles i and j.
using parameter_type = typename potential_type::parameter_type;
using pair_parameter_type = typename potential_type::parameter_type;
using container_type = std::vector<parameter_type>;
// topology stuff
using system_type = System<traits_type>;
using topology_type = Topology;
using molecule_id_type = typename topology_type::molecule_id_type;
using group_id_type = typename topology_type::group_id_type;
using connection_kind_type = typename topology_type::connection_kind_type;
using ignore_molecule_type = IgnoreMolecule<molecule_id_type>;
using ignore_group_type = IgnoreGroup <group_id_type>;
using exclusion_list_type = ExclusionList<traits_type>;
public:
ExcludedVolumeParameterList(
const std::vector<std::pair<std::size_t, parameter_type>>& parameters,
const std::map<connection_kind_type, std::size_t>& exclusions,
ignore_molecule_type ignore_mol, ignore_group_type ignore_grp)
: exclusion_list_(exclusions, std::move(ignore_mol), std::move(ignore_grp))
{
this->parameters_ .reserve(parameters.size());
this->participants_.reserve(parameters.size());
for(const auto& idxp : parameters)
{
const auto idx = idxp.first;
this->participants_.push_back(idx);
if(idx >= this->parameters_.size())
{
this->parameters_.resize(idx+1, parameter_type{real_type(0)});
}
this->parameters_.at(idx) = idxp.second;
}
}
~ExcludedVolumeParameterList() = default;
pair_parameter_type prepare_params(std::size_t i, std::size_t j) const noexcept override
{
return pair_parameter_type{parameters_[i].radius + parameters_[j].radius};
}
real_type max_cutoff_length() const noexcept override
{
return this->max_cutoff_length_;
}
void initialize(const system_type& sys, const topology_type& topol,
const potential_type& pot) noexcept override
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
this->update(sys, topol, pot); // calc parameters
return;
}
// for temperature/ionic concentration changes...
void update(const system_type& sys, const topology_type& topol,
const potential_type& pot) noexcept override
{
MJOLNIR_GET_DEFAULT_LOGGER();
MJOLNIR_LOG_FUNCTION();
this->max_cutoff_length_ = pot.max_cutoff(parameters_.begin(), parameters_.end());
this->exclusion_list_.make(sys, topol);
return;
}
// -----------------------------------------------------------------------
// for spatial partitions
//
// Here, the default implementation uses Newton's 3rd law to reduce
// calculation. For an interacting pair (i, j), forces applied to i and j
// are equal in magnitude and opposite in direction. So, if a pair (i, j) is
// listed, (j, i) is not needed.
// See implementation of VerletList, CellList and GlobalPairInteraction
// for more details about the usage of these functions.
std::vector<std::size_t> const& participants() const noexcept override
{
return participants_;
}
range<typename std::vector<std::size_t>::const_iterator>
leading_participants() const noexcept override
{
return make_range(participants_.begin(), std::prev(participants_.end()));
}
range<typename std::vector<std::size_t>::const_iterator>
possible_partners_of(const std::size_t participant_idx,
const std::size_t /*particle_idx*/) const noexcept override
{
return make_range(participants_.begin() + participant_idx + 1,
participants_.end());
}
bool has_interaction(const std::size_t i, const std::size_t j) const noexcept override
{
return (i < j) && !exclusion_list_.is_excluded(i, j);
}
exclusion_list_type const& exclusion_list() const noexcept override
{
return exclusion_list_; // for testing
}
// ------------------------------------------------------------------------
// used by Observer.
static const char* name() noexcept {return "ExcludedVolume";}
// ------------------------------------------------------------------------
// the following accessers would be used in tests.
// access to the parameters.
std::vector<parameter_type>& parameters() noexcept {return parameters_;}
std::vector<parameter_type> const& parameters() const noexcept {return parameters_;}
base_type* clone() const override
{
return new ExcludedVolumeParameterList(*this);
}
private:
real_type max_cutoff_length_;
container_type parameters_;
std::vector<std::size_t> participants_;
exclusion_list_type exclusion_list_;
};
} // mjolnir
#ifdef MJOLNIR_SEPARATE_BUILD
#include <mjolnir/core/SimulatorTraits.hpp>
#include <mjolnir/core/BoundaryCondition.hpp>
namespace mjolnir
{
extern template class ExcludedVolumeParameterList<SimulatorTraits<double, UnlimitedBoundary> >;
extern template class ExcludedVolumeParameterList<SimulatorTraits<float, UnlimitedBoundary> >;
extern template class ExcludedVolumeParameterList<SimulatorTraits<double, CuboidalPeriodicBoundary>>;
extern template class ExcludedVolumeParameterList<SimulatorTraits<float, CuboidalPeriodicBoundary>>;
} // mjolnir
#endif// MJOLNIR_SEPARATE_BUILD
#endif /* MJOLNIR_EXCLUDED_VOLUME_POTENTIAL */
<|endoftext|>
|
<commit_before>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/core/behavior/BaseMechanicalState.h>
namespace sofa
{
namespace core
{
namespace behavior
{
BaseMechanicalState::BaseMechanicalState()
: useMask(initData(&useMask, true, "useMask", "Usage of a mask to optimize the computation of the system, highly reducing the passage through the mappings"))
, forceMask(&useMask)
{
}
BaseMechanicalState::~BaseMechanicalState()
{
}
/// Perform a sequence of linear vector accumulation operation $r_i = sum_j (v_j*f_{ij})$
///
/// This is used to compute in on steps operations such as $v = v + a*dt, x = x + v*dt$.
/// Note that if the result vector appears inside the expression, it must be the first operand.
/// By default this method decompose the computation into multiple vOp calls.
void BaseMechanicalState::vMultiOp(const ExecParams* params /* PARAMS FIRST */, const VMultiOp& ops)
{
for(VMultiOp::const_iterator it = ops.begin(), itend = ops.end(); it != itend; ++it)
{
VecId r = it->first.getId(this);
const helper::vector< std::pair< ConstMultiVecId, double > >& operands = it->second;
int nop = operands.size();
if (nop==0)
{
vOp(params, r);
}
else if (nop==1)
{
if (operands[0].second == 1.0)
vOp( params, r, operands[0].first.getId(this));
else
vOp( params, r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second);
}
else
{
int i;
if (operands[0].second == 1.0)
{
vOp( params, r, operands[0].first.getId(this), operands[1].first.getId(this), operands[1].second);
i = 2;
}
else
{
vOp( params, r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second);
i = 1;
}
for (; i<nop; ++i)
vOp( params, r, r, operands[i].first.getId(this), operands[i].second);
}
}
}
/// Handle state Changes from a given Topology
void BaseMechanicalState::handleStateChange(core::topology::Topology* t)
{
if (t == this->getContext()->getTopology())
handleStateChange();
}
void BaseMechanicalState::writeState( std::ostream& )
{ }
} // namespace behavior
} // namespace core
} // namespace sofa
<commit_msg>r9972/sofa-dev : WARNING: Change BaseMechanicalState::useMask default value to falo false, because the default use of masks complicates visitors and solvers and introduces hard to understand bugs... The previous behavior can be obtained by activating SOFA_USE_MASK_BY_DEFAULT flag in sofa-local.cfg, but it is better to instead update affected simulations by adding useMask="true" to the MechanicalObject where it is useful. This is one of the last complex behaviors in visitors that is still present (after removing complex prefetching mechanisms used for merging kernels on GPU). As Visitors and solvers are currently undocumented, and rather difficult to use and understand, it is much better to favor simplicity over optimal performances by default (specially since the optimized mechanisms can still be enabled when required).<commit_after>/******************************************************************************
* SOFA, Simulation Open-Framework Architecture, version 1.0 beta 4 *
* (c) 2006-2009 MGH, INRIA, USTL, UJF, CNRS *
* *
* This library is free software; you can redistribute it and/or modify it *
* under the terms of the GNU Lesser General Public License as published by *
* the Free Software Foundation; either version 2.1 of the License, or (at *
* your option) any later version. *
* *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. *
*******************************************************************************
* SOFA :: Framework *
* *
* Authors: M. Adam, J. Allard, B. Andre, P-J. Bensoussan, S. Cotin, C. Duriez,*
* H. Delingette, F. Falipou, F. Faure, S. Fonteneau, L. Heigeas, C. Mendoza, *
* M. Nesme, P. Neumann, J-P. de la Plata Alcade, F. Poyer and F. Roy *
* *
* Contact information: contact@sofa-framework.org *
******************************************************************************/
#include <sofa/core/behavior/BaseMechanicalState.h>
namespace sofa
{
namespace core
{
namespace behavior
{
BaseMechanicalState::BaseMechanicalState()
: useMask(initData(&useMask,
#ifdef SOFA_USE_MASK_BY_DEFAULT
true,
#else
false,
#endif
"useMask", "Usage of a mask to optimize the computation of the system, highly reducing the passage through the mappings"))
, forceMask(&useMask)
{
}
BaseMechanicalState::~BaseMechanicalState()
{
}
/// Perform a sequence of linear vector accumulation operation $r_i = sum_j (v_j*f_{ij})$
///
/// This is used to compute in on steps operations such as $v = v + a*dt, x = x + v*dt$.
/// Note that if the result vector appears inside the expression, it must be the first operand.
/// By default this method decompose the computation into multiple vOp calls.
void BaseMechanicalState::vMultiOp(const ExecParams* params /* PARAMS FIRST */, const VMultiOp& ops)
{
for(VMultiOp::const_iterator it = ops.begin(), itend = ops.end(); it != itend; ++it)
{
VecId r = it->first.getId(this);
const helper::vector< std::pair< ConstMultiVecId, double > >& operands = it->second;
int nop = operands.size();
if (nop==0)
{
vOp(params, r);
}
else if (nop==1)
{
if (operands[0].second == 1.0)
vOp( params, r, operands[0].first.getId(this));
else
vOp( params, r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second);
}
else
{
int i;
if (operands[0].second == 1.0)
{
vOp( params, r, operands[0].first.getId(this), operands[1].first.getId(this), operands[1].second);
i = 2;
}
else
{
vOp( params, r, ConstVecId::null(), operands[0].first.getId(this), operands[0].second);
i = 1;
}
for (; i<nop; ++i)
vOp( params, r, r, operands[i].first.getId(this), operands[i].second);
}
}
}
/// Handle state Changes from a given Topology
void BaseMechanicalState::handleStateChange(core::topology::Topology* t)
{
if (t == this->getContext()->getTopology())
handleStateChange();
}
void BaseMechanicalState::writeState( std::ostream& )
{ }
} // namespace behavior
} // namespace core
} // namespace sofa
<|endoftext|>
|
<commit_before>#include "lexerTest.h"
#include <QtCore/QDebug>
#include <plugins/generationRulesTool/tokenTypes.h>
using namespace qrTest;
void LexerTest::SetUp() {
mErrors.clear();
mLexer.reset(new simpleParser::Lexer(mErrors));
}
void LexerTest::TearDown() {
mErrors.clear();
}
TEST_F(LexerTest, lexerTestForForeachExample) {
QString stream = "'enum State {'\n"
"foreach (State) {\n"
"State.name ',' \n"
"newline \n"
"} \n"
"StartState.name ',' newline \n"
"EndState.name newline \n"
"'}' \n";
auto lexerResult = mLexer->tokenize(stream);
ASSERT_EQ(lexerResult.length(), 22);
for (qrtext::core::Token<simpleParser::TokenTypes> token : lexerResult) {
qDebug() << token.token();
}
EXPECT_EQ(simpleParser::TokenTypes::text, lexerResult[0].token());
EXPECT_EQ(simpleParser::TokenTypes::foreachKeyword, lexerResult[1].token());
EXPECT_EQ(simpleParser::TokenTypes::openingBracket, lexerResult[2].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[3].token());
EXPECT_EQ(simpleParser::TokenTypes::closingBracket, lexerResult[4].token());
EXPECT_EQ(simpleParser::TokenTypes::openingCurlyBracket, lexerResult[5].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[6].token());
EXPECT_EQ(simpleParser::TokenTypes::dot, lexerResult[7].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[8].token());
EXPECT_EQ(simpleParser::TokenTypes::text, lexerResult[9].token());
EXPECT_EQ(simpleParser::TokenTypes::newlineKeyword, lexerResult[10].token());
EXPECT_EQ(simpleParser::TokenTypes::closingCurlyBracket, lexerResult[11].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[12].token());
EXPECT_EQ(simpleParser::TokenTypes::dot, lexerResult[13].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[14].token());
EXPECT_EQ(simpleParser::TokenTypes::text, lexerResult[15].token());
EXPECT_EQ(simpleParser::TokenTypes::newlineKeyword, lexerResult[16].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[17].token());
EXPECT_EQ(simpleParser::TokenTypes::dot, lexerResult[18].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[19].token());
EXPECT_EQ(simpleParser::TokenTypes::newlineKeyword, lexerResult[20].token());
EXPECT_EQ(simpleParser::TokenTypes::text, lexerResult[21].token());
}
<commit_msg>removed qDebug<commit_after>#include "lexerTest.h"
#include <plugins/generationRulesTool/tokenTypes.h>
using namespace qrTest;
void LexerTest::SetUp() {
mErrors.clear();
mLexer.reset(new simpleParser::Lexer(mErrors));
}
void LexerTest::TearDown() {
mErrors.clear();
}
TEST_F(LexerTest, lexerTestForForeachExample) {
QString stream = "'enum State {'\n"
"foreach (State) {\n"
"State.name ',' \n"
"newline \n"
"} \n"
"StartState.name ',' newline \n"
"EndState.name newline \n"
"'}' \n";
auto lexerResult = mLexer->tokenize(stream);
ASSERT_EQ(lexerResult.length(), 22);
EXPECT_EQ(simpleParser::TokenTypes::text, lexerResult[0].token());
EXPECT_EQ(simpleParser::TokenTypes::foreachKeyword, lexerResult[1].token());
EXPECT_EQ(simpleParser::TokenTypes::openingBracket, lexerResult[2].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[3].token());
EXPECT_EQ(simpleParser::TokenTypes::closingBracket, lexerResult[4].token());
EXPECT_EQ(simpleParser::TokenTypes::openingCurlyBracket, lexerResult[5].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[6].token());
EXPECT_EQ(simpleParser::TokenTypes::dot, lexerResult[7].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[8].token());
EXPECT_EQ(simpleParser::TokenTypes::text, lexerResult[9].token());
EXPECT_EQ(simpleParser::TokenTypes::newlineKeyword, lexerResult[10].token());
EXPECT_EQ(simpleParser::TokenTypes::closingCurlyBracket, lexerResult[11].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[12].token());
EXPECT_EQ(simpleParser::TokenTypes::dot, lexerResult[13].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[14].token());
EXPECT_EQ(simpleParser::TokenTypes::text, lexerResult[15].token());
EXPECT_EQ(simpleParser::TokenTypes::newlineKeyword, lexerResult[16].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[17].token());
EXPECT_EQ(simpleParser::TokenTypes::dot, lexerResult[18].token());
EXPECT_EQ(simpleParser::TokenTypes::identifier, lexerResult[19].token());
EXPECT_EQ(simpleParser::TokenTypes::newlineKeyword, lexerResult[20].token());
EXPECT_EQ(simpleParser::TokenTypes::text, lexerResult[21].token());
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/extensions/renderer/xwalk_extension_module.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "content/public/renderer/v8_value_converter.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebScopedMicrotaskSuppression.h"
#include "xwalk/extensions/renderer/xwalk_extension_render_view_handler.h"
namespace xwalk {
namespace extensions {
namespace {
// This is the key used in the data object passed to our callbacks to store a
// pointer back to XWalkExtensionModule.
const char* kXWalkExtensionModule = "kXWalkExtensionModule";
} // namespace
XWalkExtensionModule::XWalkExtensionModule(
v8::Handle<v8::Context> context,
const std::string& extension_name,
const std::string& extension_code)
: extension_name_(extension_name),
extension_code_(extension_code),
converter_(content::V8ValueConverter::create()) {
v8::Isolate* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
function_data_ = v8::Persistent<v8::Object>::New(isolate, v8::Object::New());
function_data_->Set(v8::String::New(kXWalkExtensionModule),
v8::External::New(this));
object_template_ =
v8::Persistent<v8::ObjectTemplate>(isolate, v8::ObjectTemplate::New());
SetFunction("postMessage", PostMessageCallback);
SetFunction("sendSyncMessage", SendSyncMessageCallback);
SetFunction("setMessageListener", SetMessageListenerCallback);
}
XWalkExtensionModule::~XWalkExtensionModule() {
// Deleting the data will disable the functions, they'll return early. We do
// this because it might be the case that the JS objects we created outlive
// this object, even if we destroy the references we have.
// TODO(cmarcelo): Add a test for this case.
function_data_->Delete(v8::String::New(kXWalkExtensionModule));
v8::Isolate* isolate = v8::Isolate::GetCurrent();
object_template_.Dispose(isolate);
object_template_.Clear();
function_data_.Dispose(isolate);
function_data_.Clear();
message_listener_.Dispose(isolate);
message_listener_.Clear();
}
void XWalkExtensionModule::DispatchMessageToListener(
v8::Handle<v8::Context> context, const base::Value& msg) {
if (message_listener_.IsEmpty())
return;
v8::HandleScope handle_scope(context->GetIsolate());
v8::Context::Scope context_scope(context);
v8::Handle<v8::Value> v8_value(converter_->ToV8Value(&msg, context));
WebKit::WebScopedMicrotaskSuppression suppression;
v8::TryCatch try_catch;
message_listener_->Call(context->Global(), 1, &v8_value);
if (try_catch.HasCaught())
LOG(WARNING) << "Exception when running message listener";
}
namespace {
std::string CodeToEnsureNamespace(const std::string& extension_name) {
std::string result;
size_t pos = 0;
while (true) {
pos = extension_name.find('.', pos);
if (pos == std::string::npos) {
result += extension_name + " = {};";
break;
}
std::string ns = extension_name.substr(0, pos);
result += ns + " = " + ns + " || {}; ";
pos++;
}
return result;
}
// Wrap API code into a callable form that takes extension object as parameter.
std::string WrapAPICode(const std::string& extension_code,
const std::string& extension_name) {
// FIXME(cmarcelo): For now sync messaging is disabled on Windows because we
// jump through the UI process and this is not supported in that platform. See
// issue https://github.com/otcshare/crosswalk/issues/268 for details.
// We take care here to make sure that line numbering for api_code after
// wrapping doesn't change, so that syntax errors point to the correct line.
return base::StringPrintf(
"var %s; (function(extension, requireNative) { "
"extension._setupExtensionInternal = function() {"
" xwalk._setupExtensionInternal(extension);"
"};"
#if !defined(OS_WIN)
"extension.internal = {};"
"extension.internal.sendSyncMessage = extension.sendSyncMessage;"
#endif
"delete extension.sendSyncMessage;"
"return (function(exports) {'use strict'; %s\n})(%s); });",
CodeToEnsureNamespace(extension_name).c_str(),
extension_code.c_str(),
extension_name.c_str());
}
v8::Handle<v8::Value> RunString(const std::string& code,
const std::string& name) {
v8::HandleScope handle_scope;
v8::Handle<v8::String> v8_code(v8::String::New(code.c_str()));
v8::Handle<v8::String> v8_name(v8::String::New(name.c_str()));
WebKit::WebScopedMicrotaskSuppression suppression;
v8::TryCatch try_catch;
v8::Handle<v8::Script> script(v8::Script::New(v8_code, v8_name));
if (try_catch.HasCaught()) {
LOG(WARNING) << "Exception while parsing " << name;
return v8::Undefined();
}
v8::Handle<v8::Value> result = script->Run();
if (try_catch.HasCaught()) {
LOG(WARNING) << "Exception while running " << name;
return v8::Undefined();
}
return handle_scope.Close(result);
}
} // namespace
void XWalkExtensionModule::LoadExtensionCode(
v8::Handle<v8::Context> context, v8::Handle<v8::Function> requireNative) {
std::string wrapped_api_code = WrapAPICode(extension_code_, extension_name_);
v8::Handle<v8::Value> result =
RunString(wrapped_api_code, "JS API code for " + extension_name_);
if (!result->IsFunction())
return;
v8::Handle<v8::Function> callable_api_code =
v8::Handle<v8::Function>::Cast(result);
const int argc = 2;
v8::Handle<v8::Value> argv[argc] = {
object_template_->NewInstance(),
requireNative
};
WebKit::WebScopedMicrotaskSuppression suppression;
v8::TryCatch try_catch;
callable_api_code->Call(context->Global(), argc, argv);
if (try_catch.HasCaught())
LOG(WARNING) << "Exception when running JS API code for "
<< extension_name_;
}
// static
v8::Handle<v8::Value> XWalkExtensionModule::PostMessageCallback(
const v8::Arguments& args) {
XWalkExtensionModule* module = GetExtensionModuleFromArgs(args);
if (!module)
return v8::False();
if (args.Length() != 1)
return v8::False();
v8::Handle<v8::Context> context = args.GetIsolate()->GetCurrentContext();
scoped_ptr<base::Value> value(
module->converter_->FromV8Value(args[0], context));
WebKit::WebFrame* frame = WebKit::WebFrame::frameForContext(context);
XWalkExtensionRenderViewHandler* handler =
XWalkExtensionRenderViewHandler::GetForFrame(frame);
if (!handler->PostMessageToExtension(
frame->identifier(), module->extension_name_, value.Pass()))
return v8::False();
return v8::True();
}
// static
v8::Handle<v8::Value> XWalkExtensionModule::SendSyncMessageCallback(
const v8::Arguments& args) {
XWalkExtensionModule* module = GetExtensionModuleFromArgs(args);
if (!module)
return v8::False();
if (args.Length() != 1)
return v8::False();
v8::Handle<v8::Context> context = args.GetIsolate()->GetCurrentContext();
scoped_ptr<base::Value> value(
module->converter_->FromV8Value(args[0], context));
WebKit::WebFrame* frame = WebKit::WebFrame::frameForContext(context);
XWalkExtensionRenderViewHandler* handler =
XWalkExtensionRenderViewHandler::GetForFrame(frame);
scoped_ptr<base::Value> reply(handler->SendSyncMessageToExtension(
frame->identifier(), module->extension_name_, value.Pass()));
return module->converter_->ToV8Value(reply.get(), context);
}
// static
v8::Handle<v8::Value> XWalkExtensionModule::SetMessageListenerCallback(
const v8::Arguments& args) {
XWalkExtensionModule* module = GetExtensionModuleFromArgs(args);
if (!module)
return v8::False();
if (args.Length() != 1)
return v8::False();
if (!args[0]->IsFunction() && !args[0]->IsUndefined()) {
LOG(WARNING) << "Trying to set message listener with invalid value.";
return v8::False();
}
v8::Isolate* isolate = args.GetIsolate();
if (args[0]->IsUndefined()) {
module->message_listener_.Dispose(isolate);
module->message_listener_.Clear();
} else {
module->message_listener_.Dispose(isolate);
module->message_listener_ =
v8::Persistent<v8::Function>::New(isolate, args[0].As<v8::Function>());
}
return v8::True();
}
// static
XWalkExtensionModule* XWalkExtensionModule::GetExtensionModuleFromArgs(
const v8::Arguments& args) {
v8::HandleScope handle_scope(args.GetIsolate());
v8::Local<v8::Object> data = args.Data().As<v8::Object>();
v8::Local<v8::Value> module =
data->Get(v8::String::New(kXWalkExtensionModule));
if (module.IsEmpty() || module->IsUndefined()) {
LOG(WARNING) << "Trying to use extension from already destroyed context!";
return NULL;
}
CHECK(module->IsExternal());
return static_cast<XWalkExtensionModule*>(module.As<v8::External>()->Value());
}
void XWalkExtensionModule::SetFunction(const char* name,
v8::InvocationCallback callback) {
object_template_->Set(
name, v8::FunctionTemplate::New(callback, function_data_));
}
} // namespace extensions
} // namespace xwalk
<commit_msg>Improve error handling when loading extensions<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "xwalk/extensions/renderer/xwalk_extension_module.h"
#include "base/logging.h"
#include "base/stringprintf.h"
#include "base/values.h"
#include "content/public/renderer/v8_value_converter.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebFrame.h"
#include "third_party/WebKit/Source/WebKit/chromium/public/WebScopedMicrotaskSuppression.h"
#include "xwalk/extensions/renderer/xwalk_extension_render_view_handler.h"
namespace xwalk {
namespace extensions {
namespace {
// This is the key used in the data object passed to our callbacks to store a
// pointer back to XWalkExtensionModule.
const char* kXWalkExtensionModule = "kXWalkExtensionModule";
} // namespace
XWalkExtensionModule::XWalkExtensionModule(
v8::Handle<v8::Context> context,
const std::string& extension_name,
const std::string& extension_code)
: extension_name_(extension_name),
extension_code_(extension_code),
converter_(content::V8ValueConverter::create()) {
v8::Isolate* isolate = context->GetIsolate();
v8::HandleScope handle_scope(isolate);
function_data_ = v8::Persistent<v8::Object>::New(isolate, v8::Object::New());
function_data_->Set(v8::String::New(kXWalkExtensionModule),
v8::External::New(this));
object_template_ =
v8::Persistent<v8::ObjectTemplate>(isolate, v8::ObjectTemplate::New());
SetFunction("postMessage", PostMessageCallback);
SetFunction("sendSyncMessage", SendSyncMessageCallback);
SetFunction("setMessageListener", SetMessageListenerCallback);
}
XWalkExtensionModule::~XWalkExtensionModule() {
// Deleting the data will disable the functions, they'll return early. We do
// this because it might be the case that the JS objects we created outlive
// this object, even if we destroy the references we have.
// TODO(cmarcelo): Add a test for this case.
function_data_->Delete(v8::String::New(kXWalkExtensionModule));
v8::Isolate* isolate = v8::Isolate::GetCurrent();
object_template_.Dispose(isolate);
object_template_.Clear();
function_data_.Dispose(isolate);
function_data_.Clear();
message_listener_.Dispose(isolate);
message_listener_.Clear();
}
void XWalkExtensionModule::DispatchMessageToListener(
v8::Handle<v8::Context> context, const base::Value& msg) {
if (message_listener_.IsEmpty())
return;
v8::HandleScope handle_scope(context->GetIsolate());
v8::Context::Scope context_scope(context);
v8::Handle<v8::Value> v8_value(converter_->ToV8Value(&msg, context));
WebKit::WebScopedMicrotaskSuppression suppression;
v8::TryCatch try_catch;
message_listener_->Call(context->Global(), 1, &v8_value);
if (try_catch.HasCaught())
LOG(WARNING) << "Exception when running message listener";
}
namespace {
std::string CodeToEnsureNamespace(const std::string& extension_name) {
std::string result;
size_t pos = 0;
while (true) {
pos = extension_name.find('.', pos);
if (pos == std::string::npos) {
result += extension_name + " = {};";
break;
}
std::string ns = extension_name.substr(0, pos);
result += ns + " = " + ns + " || {}; ";
pos++;
}
return result;
}
// Wrap API code into a callable form that takes extension object as parameter.
std::string WrapAPICode(const std::string& extension_code,
const std::string& extension_name) {
// FIXME(cmarcelo): For now sync messaging is disabled on Windows because we
// jump through the UI process and this is not supported in that platform. See
// issue https://github.com/otcshare/crosswalk/issues/268 for details.
// We take care here to make sure that line numbering for api_code after
// wrapping doesn't change, so that syntax errors point to the correct line.
return base::StringPrintf(
"var %s; (function(extension, requireNative) { "
"extension._setupExtensionInternal = function() {"
" xwalk._setupExtensionInternal(extension);"
"};"
#if !defined(OS_WIN)
"extension.internal = {};"
"extension.internal.sendSyncMessage = extension.sendSyncMessage;"
#endif
"delete extension.sendSyncMessage;"
"return (function(exports) {'use strict'; %s\n})(%s); });",
CodeToEnsureNamespace(extension_name).c_str(),
extension_code.c_str(),
extension_name.c_str());
}
v8::Handle<v8::Value> RunString(const std::string& code,
const std::string& name) {
v8::HandleScope handle_scope;
v8::Handle<v8::String> v8_code(v8::String::New(code.c_str()));
v8::Handle<v8::String> v8_name(v8::String::New(name.c_str()));
WebKit::WebScopedMicrotaskSuppression suppression;
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
v8::Handle<v8::Script> script(v8::Script::New(v8_code, v8_name));
if (try_catch.HasCaught())
return v8::Undefined();
v8::Handle<v8::Value> result = script->Run();
if (try_catch.HasCaught())
return v8::Undefined();
return handle_scope.Close(result);
}
} // namespace
void XWalkExtensionModule::LoadExtensionCode(
v8::Handle<v8::Context> context, v8::Handle<v8::Function> requireNative) {
std::string wrapped_api_code = WrapAPICode(extension_code_, extension_name_);
v8::Handle<v8::Value> result =
RunString(wrapped_api_code, "JS API code for " + extension_name_);
if (!result->IsFunction()) {
LOG(WARNING) << "Couldn't load JS API code for " << extension_name_;
return;
}
v8::Handle<v8::Function> callable_api_code =
v8::Handle<v8::Function>::Cast(result);
const int argc = 2;
v8::Handle<v8::Value> argv[argc] = {
object_template_->NewInstance(),
requireNative
};
WebKit::WebScopedMicrotaskSuppression suppression;
v8::TryCatch try_catch;
try_catch.SetVerbose(true);
callable_api_code->Call(context->Global(), argc, argv);
if (try_catch.HasCaught()) {
LOG(WARNING) << "Exception while loading JS API code for "
<< extension_name_;
}
}
// static
v8::Handle<v8::Value> XWalkExtensionModule::PostMessageCallback(
const v8::Arguments& args) {
XWalkExtensionModule* module = GetExtensionModuleFromArgs(args);
if (!module)
return v8::False();
if (args.Length() != 1)
return v8::False();
v8::Handle<v8::Context> context = args.GetIsolate()->GetCurrentContext();
scoped_ptr<base::Value> value(
module->converter_->FromV8Value(args[0], context));
WebKit::WebFrame* frame = WebKit::WebFrame::frameForContext(context);
XWalkExtensionRenderViewHandler* handler =
XWalkExtensionRenderViewHandler::GetForFrame(frame);
if (!handler->PostMessageToExtension(
frame->identifier(), module->extension_name_, value.Pass()))
return v8::False();
return v8::True();
}
// static
v8::Handle<v8::Value> XWalkExtensionModule::SendSyncMessageCallback(
const v8::Arguments& args) {
XWalkExtensionModule* module = GetExtensionModuleFromArgs(args);
if (!module)
return v8::False();
if (args.Length() != 1)
return v8::False();
v8::Handle<v8::Context> context = args.GetIsolate()->GetCurrentContext();
scoped_ptr<base::Value> value(
module->converter_->FromV8Value(args[0], context));
WebKit::WebFrame* frame = WebKit::WebFrame::frameForContext(context);
XWalkExtensionRenderViewHandler* handler =
XWalkExtensionRenderViewHandler::GetForFrame(frame);
scoped_ptr<base::Value> reply(handler->SendSyncMessageToExtension(
frame->identifier(), module->extension_name_, value.Pass()));
return module->converter_->ToV8Value(reply.get(), context);
}
// static
v8::Handle<v8::Value> XWalkExtensionModule::SetMessageListenerCallback(
const v8::Arguments& args) {
XWalkExtensionModule* module = GetExtensionModuleFromArgs(args);
if (!module)
return v8::False();
if (args.Length() != 1)
return v8::False();
if (!args[0]->IsFunction() && !args[0]->IsUndefined()) {
LOG(WARNING) << "Trying to set message listener with invalid value.";
return v8::False();
}
v8::Isolate* isolate = args.GetIsolate();
if (args[0]->IsUndefined()) {
module->message_listener_.Dispose(isolate);
module->message_listener_.Clear();
} else {
module->message_listener_.Dispose(isolate);
module->message_listener_ =
v8::Persistent<v8::Function>::New(isolate, args[0].As<v8::Function>());
}
return v8::True();
}
// static
XWalkExtensionModule* XWalkExtensionModule::GetExtensionModuleFromArgs(
const v8::Arguments& args) {
v8::HandleScope handle_scope(args.GetIsolate());
v8::Local<v8::Object> data = args.Data().As<v8::Object>();
v8::Local<v8::Value> module =
data->Get(v8::String::New(kXWalkExtensionModule));
if (module.IsEmpty() || module->IsUndefined()) {
LOG(WARNING) << "Trying to use extension from already destroyed context!";
return NULL;
}
CHECK(module->IsExternal());
return static_cast<XWalkExtensionModule*>(module.As<v8::External>()->Value());
}
void XWalkExtensionModule::SetFunction(const char* name,
v8::InvocationCallback callback) {
object_template_->Set(
name, v8::FunctionTemplate::New(callback, function_data_));
}
} // namespace extensions
} // namespace xwalk
<|endoftext|>
|
<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2018 INRIA.
*
* 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 "Lagrangian2d2DR.hpp"
#include "Interaction.hpp"
#include "BlockVector.hpp"
#include <boost/math/quaternion.hpp>
// #define DEBUG_NOCOLOR
// #define DEBUG_STDOUT
// #define DEBUG_MESSAGES
#include "debug.h"
void Lagrangian2d2DR::initialize(Interaction& inter)
{
LagrangianR::initialize(inter);
//proj_with_q _jachqProj.reset(new SimpleMatrix(_jachq->size(0),_jachq->size(1)));
if ((inter.getSizeOfDS() !=3) and (inter.getSizeOfDS() !=6 ))
{
RuntimeException::selfThrow("Lagrangian2d2DR::initialize(Interaction& inter). The size of ds must of size 3");
}
unsigned int qSize = 3 * (inter.getSizeOfDS() / 3);
_jachq.reset(new SimpleMatrix(2, qSize));
}
void Lagrangian2d2DR::computeJachq(SiconosVector& q, SiconosVector& z)
{
DEBUG_BEGIN("Lagrangian2d2DR::computeJachq(Interaction& inter, SP::BlockVector q0 \n");
double Nx = _Nc->getValue(0);
double Ny = _Nc->getValue(1);
double Px = _Pc1->getValue(0);
double Py = _Pc1->getValue(1);
double G1x = q.getValue(0);
double G1y = q.getValue(1);
/* construct tangent vector */
double Tx = Ny;
double Ty = - Nx;
_jachq->setValue(0,0,Nx);
_jachq->setValue(0,1,Ny);
_jachq->setValue(0,2,(G1y-Py)*Nx - (G1x-Px)*Ny);
_jachq->setValue(1,0,Tx);
_jachq->setValue(1,1,Ty);
_jachq->setValue(1,2,(G1y-Py)*Tx - (G1x-Px)*Ty);
if (q.size() ==6)
{
DEBUG_PRINT("take into account second ds\n");
double G2x = q.getValue(3);
double G2y = q.getValue(4);
_jachq->setValue(0,3,-Nx);
_jachq->setValue(0,4,-Ny);
_jachq->setValue(0,5,- ((G2y-Py)*Nx - (G2x-Px)*Ny));
_jachq->setValue(1,3,-Tx);
_jachq->setValue(1,4,-Ty);
_jachq->setValue(1,5,-(G1y-Py)*Tx + (G1x-Px)*Ty);
}
DEBUG_EXPR(_jachq->display(););
DEBUG_END("Lagrangian2d2DR::computeJachq(Interaction& inter, SP::BlockVector q0) \n");
}
double Lagrangian2d2DR::distance() const
{
DEBUG_BEGIN("Lagrangian2d2DR::distance(...)\n")
SiconosVector dpc(*_Pc2 - *_Pc1);
DEBUG_EXPR(_Pc1->display(););
DEBUG_EXPR(_Pc2->display(););
DEBUG_EXPR(dpc.display(););
DEBUG_END("Lagrangian2d2DR::distance(...)\n")
return dpc.norm2() * (inner_prod(*_Nc, dpc) >= 0 ? -1 : 1);
}
void Lagrangian2d2DR::computeh(SiconosVector& q, SiconosVector& z, SiconosVector& y)
{
DEBUG_BEGIN("Lagrangian2d2DR::computeh(...)\n");
DEBUG_EXPR(q.display());
// Contact points and normal are stored as relative to q1 and q2, if
// no q2 then pc2 and normal are absolute.
// Update pc1 based on q and relPc1
double angle= q(2);
DEBUG_PRINTF("angle = %e\n", angle);
(*_Pc1)(0) = q(0) + cos(angle) * (*_relPc1)(0)- sin(angle) * (*_relPc1)(1);
(*_Pc1)(1) = q(1) + sin(angle) * (*_relPc1)(0)+ cos(angle) * (*_relPc1)(1);
if (q.size() == 6)
{
// To be checked
DEBUG_PRINT("take into account second ds\n");
angle = q(5);
(*_Pc2)(0) = q(3) + cos(angle) * (*_relPc2)(0)- sin(angle) * (*_relPc2)(1);
(*_Pc2)(1) = q(4) + sin(angle) * (*_relPc2)(0)+ cos(angle) * (*_relPc2)(1);
(*_Nc)(0) = cos(angle) * (*_relNc)(0)+ sin(angle) * (*_relNc)(1);
(*_Nc)(1) = sin(angle) * (*_relNc)(0)+ cos(angle) * (*_relNc)(1);
}
else
{
*_Pc2 = *_relPc2;
*_Nc = *_relNc;
}
// SP::SiconosVector q1 = (q0.getAllVect())[0];
// ::boost::math::quaternion<double> qq1((*q1)(3), (*q1)(4), (*q1)(5), (*q1)(6));
// ::boost::math::quaternion<double> qpc1(0,(*_relPc1)(0),(*_relPc1)(1),(*_relPc1)(2));
// // apply q1 rotation and add
// qpc1 = qq1 * qpc1 / qq1;
// (*_Pc1)(0) = qpc1.R_component_2() + (*q1)(0);
// (*_Pc1)(1) = qpc1.R_component_3() + (*q1)(1);
// (*_Pc1)(2) = qpc1.R_component_4() + (*q1)(2);
// if (q0.numberOfBlocks() > 1)
// {
// // Update pc2 based on q0 and relPc2
// SP::SiconosVector q2 = (q0.getAllVect())[1];
// ::boost::math::quaternion<double> qq2((*q2)(3), (*q2)(4), (*q2)(5), (*q2)(6));
// ::boost::math::quaternion<double> qpc2(0,(*_relPc2)(0),(*_relPc2)(1),(*_relPc2)(2));
// // apply q2 rotation and add
// qpc2 = qq2 * qpc2 / qq2;
// (*_Pc2)(0) = qpc2.R_component_2() + (*q2)(0);
// (*_Pc2)(1) = qpc2.R_component_3() + (*q2)(1);
// (*_Pc2)(2) = qpc2.R_component_4() + (*q2)(2);
// // same for normal
// ::boost::math::quaternion<double> qnc(0, (*_relNc)(0), (*_relNc)(1), (*_relNc)(2));
// qnc = qq2 * qnc / qq2;
// (*_Nc)(0) = qnc.R_component_2();
// (*_Nc)(1) = qnc.R_component_3();
// (*_Nc)(2) = qnc.R_component_4();
// }
// else
// {
// *_Pc2 = *_relPc2;
// *_Nc = *_relNc;
// }
LagrangianScleronomousR::computeh(q, z, y);
y.setValue(0, distance());
DEBUG_EXPR(y.display(););
DEBUG_EXPR(display(););
DEBUG_END("Lagrangian2d2DR::computeh(...)\n")
}
void Lagrangian2d2DR::display() const
{
LagrangianR::display();
std::cout << " _Pc1 :" << std::endl;
if(_Pc1)
_Pc1->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _Pc2 :" << std::endl;
if(_Pc2)
_Pc2->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relPc1 :" << std::endl;
if(_relPc1)
_relPc1->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relPc2 :" << std::endl;
if(_relPc2)
_relPc2->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _Nc :" << std::endl;
if(_Nc)
_Nc->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relNc :" << std::endl;
if(_relNc)
_relNc->display();
else
std::cout << " NULL :" << std::endl;
}
<commit_msg>[kernel] fix bug in rotation of normal with 2 ds<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
* of non smooth dynamical systems.
*
* Copyright 2018 INRIA.
*
* 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 "Lagrangian2d2DR.hpp"
#include "Interaction.hpp"
#include "BlockVector.hpp"
#include <boost/math/quaternion.hpp>
// #define DEBUG_NOCOLOR
// #define DEBUG_STDOUT
// #define DEBUG_MESSAGES
#include "debug.h"
void Lagrangian2d2DR::initialize(Interaction& inter)
{
LagrangianR::initialize(inter);
//proj_with_q _jachqProj.reset(new SimpleMatrix(_jachq->size(0),_jachq->size(1)));
if ((inter.getSizeOfDS() !=3) and (inter.getSizeOfDS() !=6 ))
{
RuntimeException::selfThrow("Lagrangian2d2DR::initialize(Interaction& inter). The size of ds must of size 3");
}
unsigned int qSize = 3 * (inter.getSizeOfDS() / 3);
_jachq.reset(new SimpleMatrix(2, qSize));
}
void Lagrangian2d2DR::computeJachq(SiconosVector& q, SiconosVector& z)
{
DEBUG_BEGIN("Lagrangian2d2DR::computeJachq(Interaction& inter, SP::BlockVector q0 \n");
double Nx = _Nc->getValue(0);
double Ny = _Nc->getValue(1);
double Px = _Pc1->getValue(0);
double Py = _Pc1->getValue(1);
double G1x = q.getValue(0);
double G1y = q.getValue(1);
/* construct tangent vector */
double Tx = Ny;
double Ty = - Nx;
_jachq->setValue(0,0,Nx);
_jachq->setValue(0,1,Ny);
_jachq->setValue(0,2,(G1y-Py)*Nx - (G1x-Px)*Ny);
_jachq->setValue(1,0,Tx);
_jachq->setValue(1,1,Ty);
_jachq->setValue(1,2,(G1y-Py)*Tx - (G1x-Px)*Ty);
if (q.size() ==6)
{
DEBUG_PRINT("take into account second ds\n");
double G2x = q.getValue(3);
double G2y = q.getValue(4);
_jachq->setValue(0,3,-Nx);
_jachq->setValue(0,4,-Ny);
_jachq->setValue(0,5,- ((G2y-Py)*Nx - (G2x-Px)*Ny));
_jachq->setValue(1,3,-Tx);
_jachq->setValue(1,4,-Ty);
_jachq->setValue(1,5,-(G1y-Py)*Tx + (G1x-Px)*Ty);
}
DEBUG_EXPR(_jachq->display(););
DEBUG_END("Lagrangian2d2DR::computeJachq(Interaction& inter, SP::BlockVector q0) \n");
}
double Lagrangian2d2DR::distance() const
{
DEBUG_BEGIN("Lagrangian2d2DR::distance(...)\n")
SiconosVector dpc(*_Pc2 - *_Pc1);
DEBUG_EXPR(_Pc1->display(););
DEBUG_EXPR(_Pc2->display(););
DEBUG_EXPR(dpc.display(););
DEBUG_END("Lagrangian2d2DR::distance(...)\n")
return dpc.norm2() * (inner_prod(*_Nc, dpc) >= 0 ? -1 : 1);
}
void Lagrangian2d2DR::computeh(SiconosVector& q, SiconosVector& z, SiconosVector& y)
{
DEBUG_BEGIN("Lagrangian2d2DR::computeh(...)\n");
DEBUG_EXPR(q.display());
// Contact points and normal are stored as relative to q1 and q2, if
// no q2 then pc2 and normal are absolute.
// Update pc1 based on q and relPc1
double angle= q(2);
DEBUG_PRINTF("angle (ds1)= %e\n", angle);
(*_Pc1)(0) = q(0) + cos(angle) * (*_relPc1)(0)- sin(angle) * (*_relPc1)(1);
(*_Pc1)(1) = q(1) + sin(angle) * (*_relPc1)(0)+ cos(angle) * (*_relPc1)(1);
if (q.size() == 6)
{
// To be checked
DEBUG_PRINT("take into account second ds\n");
angle = q(5);
DEBUG_PRINTF("angle (ds2) = %e\n", angle);
(*_Pc2)(0) = q(3) + cos(angle) * (*_relPc2)(0)- sin(angle) * (*_relPc2)(1);
(*_Pc2)(1) = q(4) + sin(angle) * (*_relPc2)(0)+ cos(angle) * (*_relPc2)(1);
(*_Nc)(0) = cos(angle) * (*_relNc)(0)- sin(angle) * (*_relNc)(1);
(*_Nc)(1) = sin(angle) * (*_relNc)(0)+ cos(angle) * (*_relNc)(1);
}
else
{
*_Pc2 = *_relPc2;
*_Nc = *_relNc;
}
DEBUG_EXPR(_Pc1->display(););
DEBUG_EXPR(_Pc2->display(););
DEBUG_EXPR(_Nc->display(););
// SP::SiconosVector q1 = (q0.getAllVect())[0];
// ::boost::math::quaternion<double> qq1((*q1)(3), (*q1)(4), (*q1)(5), (*q1)(6));
// ::boost::math::quaternion<double> qpc1(0,(*_relPc1)(0),(*_relPc1)(1),(*_relPc1)(2));
// // apply q1 rotation and add
// qpc1 = qq1 * qpc1 / qq1;
// (*_Pc1)(0) = qpc1.R_component_2() + (*q1)(0);
// (*_Pc1)(1) = qpc1.R_component_3() + (*q1)(1);
// (*_Pc1)(2) = qpc1.R_component_4() + (*q1)(2);
// if (q0.numberOfBlocks() > 1)
// {
// // Update pc2 based on q0 and relPc2
// SP::SiconosVector q2 = (q0.getAllVect())[1];
// ::boost::math::quaternion<double> qq2((*q2)(3), (*q2)(4), (*q2)(5), (*q2)(6));
// ::boost::math::quaternion<double> qpc2(0,(*_relPc2)(0),(*_relPc2)(1),(*_relPc2)(2));
// // apply q2 rotation and add
// qpc2 = qq2 * qpc2 / qq2;
// (*_Pc2)(0) = qpc2.R_component_2() + (*q2)(0);
// (*_Pc2)(1) = qpc2.R_component_3() + (*q2)(1);
// (*_Pc2)(2) = qpc2.R_component_4() + (*q2)(2);
// // same for normal
// ::boost::math::quaternion<double> qnc(0, (*_relNc)(0), (*_relNc)(1), (*_relNc)(2));
// qnc = qq2 * qnc / qq2;
// (*_Nc)(0) = qnc.R_component_2();
// (*_Nc)(1) = qnc.R_component_3();
// (*_Nc)(2) = qnc.R_component_4();
// }
// else
// {
// *_Pc2 = *_relPc2;
// *_Nc = *_relNc;
// }
LagrangianScleronomousR::computeh(q, z, y);
y.setValue(0, distance());
DEBUG_EXPR(y.display(););
DEBUG_EXPR(display(););
DEBUG_END("Lagrangian2d2DR::computeh(...)\n")
}
void Lagrangian2d2DR::display() const
{
LagrangianR::display();
std::cout << " _Pc1 :" << std::endl;
if(_Pc1)
_Pc1->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _Pc2 :" << std::endl;
if(_Pc2)
_Pc2->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relPc1 :" << std::endl;
if(_relPc1)
_relPc1->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relPc2 :" << std::endl;
if(_relPc2)
_relPc2->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _Nc :" << std::endl;
if(_Nc)
_Nc->display();
else
std::cout << " NULL :" << std::endl;
std::cout << " _relNc :" << std::endl;
if(_relNc)
_relNc->display();
else
std::cout << " NULL :" << std::endl;
}
<|endoftext|>
|
<commit_before>
#include <iterator>
#include "Representations/Infrastructure/JointData.h"
#include "Tools/Math/Common.h"
#include "PlatformInterface/Platform.h"
#include "Tools/Debug/NaoTHAssert.h"
#include "Messages/Framework-Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>
using namespace naoth;
using namespace std;
double JointData::min[JointData::numOfJoint];
double JointData::max[JointData::numOfJoint];
JointData::JointData()
{
for (int i = 0; i < numOfJoint; i++)
{
position[i] = 0;
dp[i] = 0;
ddp[i] = 0;
stiffness[i] = 0.0;
}
}
void JointData::loadJointLimitsFromConfig()
{
const Configuration& cfg = Platform::getInstance().theConfiguration;
for (int i = 0; i < JointData::numOfJoint; i++)
{
string jointName = JointData::getJointName((JointData::JointID)i);
if (cfg.hasKey("joints", jointName + "Max"))
{
double maxDeg = cfg.getDouble("joints", jointName + "Max");
max[i] = Math::fromDegrees(maxDeg);
} else
{
THROW("JointData: can not get " + jointName + " max angle");
}
if (cfg.hasKey("joints", jointName + "Min"))
{
double minDeg = cfg.getDouble("joints", jointName + "Min");
min[i] = Math::fromDegrees(minDeg);
} else
{
THROW("JointData: can not get " + jointName + " min angle");
}
}//enf for
}//end init
string JointData::getJointName(JointID joint)
{
switch (joint)
{
case HeadPitch: return string("HeadPitch");
case HeadYaw: return string("HeadYaw");
case RShoulderRoll: return string("RShoulderRoll");
case LShoulderRoll: return string("LShoulderRoll");
case RShoulderPitch: return string("RShoulderPitch");
case LShoulderPitch: return string("LShoulderPitch");
case RElbowRoll: return string("RElbowRoll");
case LElbowRoll: return string("LElbowRoll");
case RElbowYaw: return string("RElbowYaw");
case LElbowYaw: return string("LElbowYaw");
case LHipYawPitch: return string("LHipYawPitch");
case RHipYawPitch: return string("RHipYawPitch");
case RHipPitch: return string("RHipPitch");
case LHipPitch: return string("LHipPitch");
case RHipRoll: return string("RHipRoll");
case LHipRoll: return string("LHipRoll");
case RKneePitch: return string("RKneePitch");
case LKneePitch: return string("LKneePitch");
case RAnklePitch: return string("RAnklePitch");
case LAnklePitch: return string("LAnklePitch");
case RAnkleRoll: return string("RAnkleRoll");
case LAnkleRoll: return string("LAnkleRoll");
default: return string("Unknown Joint");
}//end switch
}//end getJointName
double JointData::mirrorData(JointID joint) const
{
switch (joint)
{
// Head (don't mirror)
case HeadYaw: return -position[HeadYaw];
case HeadPitch: return position[HeadPitch];
// Arms
case RShoulderPitch: return position[LShoulderPitch];
case RShoulderRoll: return -position[LShoulderRoll];
case RElbowYaw: return -position[LElbowYaw];
case RElbowRoll: return -position[LElbowRoll];
case LShoulderPitch: return position[RShoulderPitch];
case LShoulderRoll: return -position[RShoulderRoll];
case LElbowYaw: return -position[RElbowYaw];
case LElbowRoll: return -position[RElbowRoll];
// Legs
case RHipYawPitch: return position[LHipYawPitch];
case RHipPitch: return position[LHipPitch];
case RHipRoll: return -position[LHipRoll];
case RKneePitch: return position[LKneePitch];
case RAnklePitch: return position[LAnklePitch];
case RAnkleRoll: return -position[LAnkleRoll];
case LHipYawPitch: return position[RHipYawPitch];
case LHipPitch: return position[RHipPitch];
case LHipRoll: return -position[RHipRoll];
case LKneePitch: return position[RKneePitch];
case LAnklePitch: return position[RAnklePitch];
case LAnkleRoll: return -position[RAnkleRoll];
default: return position[joint];
}
}//end mirrorData
JointData::JointID JointData::jointIDFromName(std::string name)
{
for (int i = 0; i < numOfJoint; i++) {
if (name == getJointName((JointID) i)) return (JointID) i;
}//end for
return numOfJoint;
}//end getJointName
void JointData::mirrorFrom(const JointData& jointData)
{
for (int i = 0; i < numOfJoint; i++)
position[i] = jointData.mirrorData((JointID) i);
}//end mirror
void JointData::mirror()
{
JointData tmp = *this;
mirrorFrom(tmp);
}
void JointData::clamp(JointID id)
{
position[id] = Math::clamp(position[id], min[id], max[id]);
}
void JointData::clamp()
{
for( int i=0; i<numOfJoint; i++)
{
clamp((JointID)i);
}
}
bool JointData::isInRange(JointData::JointID id, double ang) const
{
return ang <= max[id] && ang >= min[id];
}
bool JointData::isInRange(JointData::JointID id) const
{
return isInRange(id, position[id]);
}
void JointData::updateSpeed(const JointData& lastData, double dt)
{
const double* lastPose = lastData.position;
double idt = 1 / dt;
for ( int i=0; i<JointData::numOfJoint; i++)
{
dp[i] = (position[i] - lastPose[i]) * idt;
}
}
void JointData::updateAcceleration(const JointData& lastData, double dt)
{
const double* lastSpeed = lastData.dp;
double idt = 1 / dt;
for (int i = 0; i < JointData::numOfJoint; i++)
{
ddp[i] = (dp[i] - lastSpeed[i]) * idt;
}
}
bool JointData::isLegStiffnessOn() const
{
for ( int i=JointData::RHipYawPitch; i<JointData::numOfJoint; i++)
{
if ( stiffness[i] < 0 ) return false;
}
return true;
}
int JointData::checkStiffness() const
{
for(int i=0; i<JointData::numOfJoint; i++)
{
double v = stiffness[i];
if ( v > 1 || v < -1 )
{
return i;
//THROW("Get ILLEGAL Stiffness: "<<getJointName(JointData::JointID(i))<<" = "<<v);
}
}
return -1;
}
SensorJointData::SensorJointData()
: timestamp(0)
{
for (int i = 0; i < numOfJoint; i++)
{
electricCurrent[i] = 0.0;
temperature[i] = 0.0;
}//end for
}
void SensorJointData::print(ostream& stream) const
{
stream << "Timestamp: " << timestamp << endl;
stream << "Joint [pos(deg), stiffness, temperature,current]" << endl;
stream << "------------------------" << endl;
for (int i = 0; i < numOfJoint; i++)
{
stream.precision(4);
stream << getJointName((JointData::JointID) i) << "\t[" << fixed << Math::toDegrees(position[i]) << ", " << stiffness[i] << ", ";
stream.precision(0);
stream << temperature[i] << ", ";
stream.precision(3);
stream << electricCurrent[i] << "]" << endl;
}//end for
}//end print
SensorJointData::~SensorJointData()
{
}
MotorJointData::MotorJointData()
{
}
MotorJointData::~MotorJointData()
{
}
void MotorJointData::print(ostream& stream) const
{
stream << "Joint [pos, stiffness]" << endl;
stream << "------------------------" << endl;
for (int i = 0; i < numOfJoint; i++) {
stream << getJointName((JointData::JointID) i) << "[" << position[i] << ", " << stiffness[i] << "]" << endl;
}//end for
}//end print
void Serializer<SensorJointData>::serialize(const SensorJointData& representation, std::ostream& stream)
{
naothmessages::SensorJointData message;
for(int i=0; i < JointData::numOfJoint; i++)
{
message.add_electriccurrent(representation.electricCurrent[i]);
message.add_temperature(representation.temperature[i]);
message.mutable_jointdata()->add_position(representation.position[i]);
message.mutable_jointdata()->add_stiffness(representation.stiffness[i]);
message.mutable_jointdata()->add_dp(representation.dp[i]);
message.mutable_jointdata()->add_ddp(representation.ddp[i]);
}
google::protobuf::io::OstreamOutputStream buf(&stream);
message.SerializeToZeroCopyStream(&buf);
}
void Serializer<SensorJointData>::deserialize(std::istream& stream, SensorJointData& representation)
{
naothmessages::SensorJointData message;
google::protobuf::io::IstreamInputStream buf(&stream);
message.ParseFromZeroCopyStream(&buf);
// assure the integrity of the message
ASSERT(message.electriccurrent().size() == JointData::numOfJoint);
ASSERT(message.temperature().size() == JointData::numOfJoint);
ASSERT(message.jointdata().position().size() == JointData::numOfJoint);
ASSERT(message.jointdata().stiffness().size() == JointData::numOfJoint);
ASSERT(message.jointdata().dp().size() == JointData::numOfJoint);
ASSERT(message.jointdata().ddp().size() == JointData::numOfJoint);
for (int i = 0; i < JointData::numOfJoint; i++)
{
representation.electricCurrent[i] = message.electriccurrent(i);
representation.temperature[i] = message.temperature(i);
// joint data
representation.position[i] = message.jointdata().position(i);
representation.stiffness[i] = message.jointdata().stiffness(i);
representation.dp[i] = message.jointdata().dp(i);
representation.ddp[i] = message.jointdata().ddp(i);
}
}
void Serializer<MotorJointData>::serialize(const MotorJointData& representation, std::ostream& stream)
{
naothmessages::JointData message;
for(int i=0; i < JointData::numOfJoint; i++)
{
message.add_position(representation.position[i]);
message.add_stiffness(representation.stiffness[i]);
message.add_dp(representation.dp[i]);
message.add_ddp(representation.ddp[i]);
}
google::protobuf::io::OstreamOutputStream buf(&stream);
message.SerializeToZeroCopyStream(&buf);
}
void Serializer<MotorJointData>::deserialize(std::istream& stream, MotorJointData& representation)
{
naothmessages::JointData message;
google::protobuf::io::IstreamInputStream buf(&stream);
message.ParseFromZeroCopyStream(&buf);
// assure the integrity of the message
ASSERT(message.position().size() == JointData::numOfJoint);
ASSERT(message.stiffness().size() == JointData::numOfJoint);
ASSERT(message.dp().size() == JointData::numOfJoint);
ASSERT(message.ddp().size() == JointData::numOfJoint);
for(int i=0; i < JointData::numOfJoint; i++)
{
representation.position[i] = message.position(i);
representation.stiffness[i] = message.stiffness(i);
representation.dp[i] = message.dp(i);
representation.ddp[i] = message.ddp(i);
}
}
<commit_msg>little cleanup<commit_after>
#include <iterator>
#include "Representations/Infrastructure/JointData.h"
#include "Tools/Math/Common.h"
#include "PlatformInterface/Platform.h"
#include "Tools/Debug/NaoTHAssert.h"
#include "Messages/Framework-Representations.pb.h"
#include <google/protobuf/io/zero_copy_stream_impl.h>
using namespace naoth;
using namespace std;
double JointData::min[JointData::numOfJoint];
double JointData::max[JointData::numOfJoint];
JointData::JointData()
{
// init the arrays
for (int i = 0; i < numOfJoint; i++)
{
position[i] = 0.0;
dp[i] = 0.0;
ddp[i] = 0.0;
stiffness[i] = 0.0;
}
}
void JointData::loadJointLimitsFromConfig()
{
const Configuration& cfg = Platform::getInstance().theConfiguration;
for (int i = 0; i < JointData::numOfJoint; i++)
{
string jointName = JointData::getJointName((JointData::JointID)i);
if (cfg.hasKey("joints", jointName + "Max")) {
max[i] = Math::fromDegrees(cfg.getDouble("joints", jointName + "Max"));
} else {
THROW("JointData: can not get " + jointName + " max angle");
}
if (cfg.hasKey("joints", jointName + "Min")) {
min[i] = Math::fromDegrees(cfg.getDouble("joints", jointName + "Min"));
} else {
THROW("JointData: can not get " + jointName + " min angle");
}
}//enf for
}//end init
string JointData::getJointName(JointID joint)
{
switch (joint)
{
case HeadPitch: return string("HeadPitch");
case HeadYaw: return string("HeadYaw");
case RShoulderRoll: return string("RShoulderRoll");
case LShoulderRoll: return string("LShoulderRoll");
case RShoulderPitch: return string("RShoulderPitch");
case LShoulderPitch: return string("LShoulderPitch");
case RElbowRoll: return string("RElbowRoll");
case LElbowRoll: return string("LElbowRoll");
case RElbowYaw: return string("RElbowYaw");
case LElbowYaw: return string("LElbowYaw");
case LHipYawPitch: return string("LHipYawPitch");
case RHipYawPitch: return string("RHipYawPitch");
case RHipPitch: return string("RHipPitch");
case LHipPitch: return string("LHipPitch");
case RHipRoll: return string("RHipRoll");
case LHipRoll: return string("LHipRoll");
case RKneePitch: return string("RKneePitch");
case LKneePitch: return string("LKneePitch");
case RAnklePitch: return string("RAnklePitch");
case LAnklePitch: return string("LAnklePitch");
case RAnkleRoll: return string("RAnkleRoll");
case LAnkleRoll: return string("LAnkleRoll");
default: return string("Unknown Joint");
}//end switch
}//end getJointName
double JointData::mirrorData(JointID joint) const
{
switch (joint)
{
// Head (don't mirror)
case HeadYaw: return -position[HeadYaw];
case HeadPitch: return position[HeadPitch];
// Arms
case RShoulderPitch: return position[LShoulderPitch];
case RShoulderRoll: return -position[LShoulderRoll];
case RElbowYaw: return -position[LElbowYaw];
case RElbowRoll: return -position[LElbowRoll];
case LShoulderPitch: return position[RShoulderPitch];
case LShoulderRoll: return -position[RShoulderRoll];
case LElbowYaw: return -position[RElbowYaw];
case LElbowRoll: return -position[RElbowRoll];
// Legs
case RHipYawPitch: return position[LHipYawPitch];
case RHipPitch: return position[LHipPitch];
case RHipRoll: return -position[LHipRoll];
case RKneePitch: return position[LKneePitch];
case RAnklePitch: return position[LAnklePitch];
case RAnkleRoll: return -position[LAnkleRoll];
case LHipYawPitch: return position[RHipYawPitch];
case LHipPitch: return position[RHipPitch];
case LHipRoll: return -position[RHipRoll];
case LKneePitch: return position[RKneePitch];
case LAnklePitch: return position[RAnklePitch];
case LAnkleRoll: return -position[RAnkleRoll];
default: return position[joint];
}
}//end mirrorData
JointData::JointID JointData::jointIDFromName(std::string name)
{
for (int i = 0; i < numOfJoint; i++) {
if (name == getJointName((JointID) i)) return (JointID) i;
}
return numOfJoint;
}//end getJointName
void JointData::mirrorFrom(const JointData& jointData)
{
for (int i = 0; i < numOfJoint; i++) {
position[i] = jointData.mirrorData((JointID) i);
}
}//end mirror
void JointData::mirror()
{
JointData tmp = *this;
mirrorFrom(tmp);
}
void JointData::clamp(JointID id)
{
position[id] = Math::clamp(position[id], min[id], max[id]);
}
void JointData::clamp()
{
for( int i=0; i<numOfJoint; i++) {
clamp((JointID)i);
}
}
bool JointData::isInRange(JointData::JointID id, double ang) const
{
return ang <= max[id] && ang >= min[id];
}
bool JointData::isInRange(JointData::JointID id) const
{
return isInRange(id, position[id]);
}
void JointData::updateSpeed(const JointData& lastData, double dt)
{
const double* lastPose = lastData.position;
double idt = 1 / dt;
for ( int i=0; i<JointData::numOfJoint; i++)
{
dp[i] = (position[i] - lastPose[i]) * idt;
}
}
void JointData::updateAcceleration(const JointData& lastData, double dt)
{
const double* lastSpeed = lastData.dp;
double idt = 1 / dt;
for (int i = 0; i < JointData::numOfJoint; i++)
{
ddp[i] = (dp[i] - lastSpeed[i]) * idt;
}
}
bool JointData::isLegStiffnessOn() const
{
for ( int i=JointData::RHipYawPitch; i<JointData::numOfJoint; i++)
{
if ( stiffness[i] < 0 ) return false;
}
return true;
}
int JointData::checkStiffness() const
{
for(int i=0; i<JointData::numOfJoint; i++)
{
double v = stiffness[i];
if ( v > 1 || v < -1 )
{
return i;
//THROW("Get ILLEGAL Stiffness: "<<getJointName(JointData::JointID(i))<<" = "<<v);
}
}
return -1;
}
SensorJointData::SensorJointData()
: timestamp(0)
{
for (int i = 0; i < numOfJoint; i++)
{
electricCurrent[i] = 0.0;
temperature[i] = 0.0;
}
}
void SensorJointData::print(ostream& stream) const
{
stream << "Timestamp: " << timestamp << endl;
stream << "Joint [pos(deg), stiffness, temperature,current]" << endl;
stream << "------------------------" << endl;
for (int i = 0; i < numOfJoint; i++)
{
stream.precision(4);
stream << getJointName((JointData::JointID) i) << "\t[" << fixed << Math::toDegrees(position[i]) << ", " << stiffness[i] << ", ";
stream.precision(0);
stream << temperature[i] << ", ";
stream.precision(3);
stream << electricCurrent[i] << "]" << endl;
}
}//end print
SensorJointData::~SensorJointData()
{
}
MotorJointData::MotorJointData()
{
}
MotorJointData::~MotorJointData()
{
}
void MotorJointData::print(ostream& stream) const
{
stream << "Joint [pos, stiffness]" << endl;
stream << "------------------------" << endl;
for (int i = 0; i < numOfJoint; i++) {
stream << getJointName((JointData::JointID) i) << "[" << position[i] << ", " << stiffness[i] << "]" << endl;
}
}//end print
void Serializer<SensorJointData>::serialize(const SensorJointData& representation, std::ostream& stream)
{
naothmessages::SensorJointData message;
for(int i=0; i < JointData::numOfJoint; i++)
{
message.add_electriccurrent(representation.electricCurrent[i]);
message.add_temperature(representation.temperature[i]);
message.mutable_jointdata()->add_position(representation.position[i]);
message.mutable_jointdata()->add_stiffness(representation.stiffness[i]);
message.mutable_jointdata()->add_dp(representation.dp[i]);
message.mutable_jointdata()->add_ddp(representation.ddp[i]);
}
google::protobuf::io::OstreamOutputStream buf(&stream);
message.SerializeToZeroCopyStream(&buf);
}
void Serializer<SensorJointData>::deserialize(std::istream& stream, SensorJointData& representation)
{
naothmessages::SensorJointData message;
google::protobuf::io::IstreamInputStream buf(&stream);
message.ParseFromZeroCopyStream(&buf);
// assure the integrity of the message
ASSERT(message.electriccurrent().size() == JointData::numOfJoint);
ASSERT(message.temperature().size() == JointData::numOfJoint);
ASSERT(message.jointdata().position().size() == JointData::numOfJoint);
ASSERT(message.jointdata().stiffness().size() == JointData::numOfJoint);
ASSERT(message.jointdata().dp().size() == JointData::numOfJoint);
ASSERT(message.jointdata().ddp().size() == JointData::numOfJoint);
for (int i = 0; i < JointData::numOfJoint; i++)
{
representation.electricCurrent[i] = message.electriccurrent(i);
representation.temperature[i] = message.temperature(i);
// joint data
representation.position[i] = message.jointdata().position(i);
representation.stiffness[i] = message.jointdata().stiffness(i);
representation.dp[i] = message.jointdata().dp(i);
representation.ddp[i] = message.jointdata().ddp(i);
}
}
void Serializer<MotorJointData>::serialize(const MotorJointData& representation, std::ostream& stream)
{
naothmessages::JointData message;
for(int i=0; i < JointData::numOfJoint; i++)
{
message.add_position(representation.position[i]);
message.add_stiffness(representation.stiffness[i]);
message.add_dp(representation.dp[i]);
message.add_ddp(representation.ddp[i]);
}
google::protobuf::io::OstreamOutputStream buf(&stream);
message.SerializeToZeroCopyStream(&buf);
}
void Serializer<MotorJointData>::deserialize(std::istream& stream, MotorJointData& representation)
{
naothmessages::JointData message;
google::protobuf::io::IstreamInputStream buf(&stream);
message.ParseFromZeroCopyStream(&buf);
// assure the integrity of the message
ASSERT(message.position().size() == JointData::numOfJoint);
ASSERT(message.stiffness().size() == JointData::numOfJoint);
ASSERT(message.dp().size() == JointData::numOfJoint);
ASSERT(message.ddp().size() == JointData::numOfJoint);
for(int i=0; i < JointData::numOfJoint; i++)
{
representation.position[i] = message.position(i);
representation.stiffness[i] = message.stiffness(i);
representation.dp[i] = message.dp(i);
representation.ddp[i] = message.ddp(i);
}
}
<|endoftext|>
|
<commit_before>// StoryMaster Simulator
// Bryan DeGrendel (c) 2014
//
// See LICENSE for licensing information.
//
// simulator.cpp - Main file for the sample StoryMaster simulator.
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <storymaster.h>
using namespace std;
int main(int argc, const char *argv[])
{
cout << "Operating over [examples/dialog.scene.lua] with runtime " SM_VERSION_STRING << endl;
sm_core *core = (sm_core *)(malloc(sizeof(sm_core)));
sm_session *session = (sm_session *)(malloc(sizeof(sm_session)));
sm_scene *scene = (sm_scene *)(malloc(sizeof(sm_scene)));
// TODO: Check return valuez and all that
sm_core_init(core);
sm_session_init(session, core, "common");
sm_scene_init(scene, session, "dialog");
sm_scene_load_from_file(scene, "examples/dialog.scene.lua");
sm_scene_execute(scene);
sm_scene_deinit(scene);
sm_session_deinit(session);
sm_core_deinit(core);
free(scene);
free(core);
return 0;
}
<commit_msg>Updated the simulator to the latest API.<commit_after>// StoryMaster Simulator
// Bryan DeGrendel (c) 2014
//
// See LICENSE for licensing information.
//
// simulator.cpp - Main file for the sample StoryMaster simulator.
#include <cstdlib>
#include <cstdio>
#include <iostream>
#include <storymaster.h>
using namespace std;
int main(int argc, const char *argv[])
{
cout << "Operating over [examples/dialog.scene.lua] with runtime " SM_VERSION_STRING << endl;
sm_core *core = (sm_core *)(malloc(sizeof(sm_core)));
sm_session *session = (sm_session *)(malloc(sizeof(sm_session)));
sm_scene *scene = (sm_scene *)(malloc(sizeof(sm_scene)));
// TODO: Check return valuez and all that
sm_core_init(core);
sm_session_init(session, core, "common");
sm_scene_init_from_file(scene, session, "dialog", "example/dialog.lua");
sm_scene_execute(scene);
sm_scene_deinit(scene);
sm_session_deinit(session);
sm_core_deinit(core);
free(scene);
free(core);
return 0;
}
<|endoftext|>
|
<commit_before>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5cpp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA 02110-1301 USA
// ===========================================================================
//
// Author: Eugen Wintersberger <eugen.wintersberger@desy.de>
// Created on: Aug 16, 2017
//
#include <stdexcept>
#include <h5cpp/property/file_creation.hpp>
namespace hdf5 {
namespace property{
FileCreationList::FileCreationList():
GroupCreationList(kFileCreate)
{
}
FileCreationList::~FileCreationList()
{}
hsize_t FileCreationList::user_block() const
{
hsize_t buffer;
if(0 > H5Pget_userblock(static_cast<hid_t>(*this), &buffer))
{
throw std::runtime_error("Cannot retrieve user block size from file creation property list!");
}
return buffer;
}
void FileCreationList::user_block(hsize_t size) const
{
if(0 > H5Pset_userblock(static_cast<hid_t>(*this), size))
{
throw std::runtime_error("Cannot set user block size for file creation property list!");
}
}
void FileCreationList::object_offset_size(size_t size) const
{
if(0 > H5Pset_sizes(static_cast<hid_t>(*this), size, 0))
{
throw std::runtime_error("Failure setting object offset size to file creation property list!");
}
}
size_t FileCreationList::object_offset_size() const
{
size_t offset_size = 0,
length_size = 0;
if(0 > H5Pget_sizes(static_cast<hid_t>(*this), &offset_size, &length_size))
{
throw std::runtime_error("Failure retrieving object offset size from file creation property list!");
}
return offset_size;
}
void FileCreationList::object_length_size(size_t size) const
{
if(0 > H5Pset_sizes(static_cast<hid_t>(*this), 0, size))
{
throw std::runtime_error("Failure setting object length size in file creation property list!");
}
}
size_t FileCreationList::object_length_size() const
{
size_t offset_size = 0,
length_size = 0;
if(0 > H5Pget_sizes(static_cast<hid_t>(*this), &offset_size, &length_size))
{
throw std::runtime_error("Failure retrieving object length size from file creation property list!");
}
return length_size;
}
void FileCreationList::btree_rank(unsigned ik)
{
if(0 > H5Pset_sym_k(static_cast<hid_t>(*this), ik, 0))
{
throw std::runtime_error("Failure setting rank parameter for symbol table nodes!");
}
}
unsigned FileCreationList::btree_rank() const
{
unsigned ret;
if(0 > H5Pget_sym_k(static_cast<hid_t>(*this), &ret, NULL))
{
throw std::runtime_error("Failure retrieving rank parameter for symbol table nodes!");
}
return ret;
}
void FileCreationList::btree_symbols(unsigned lk)
{
if(0 > H5Pset_sym_k(static_cast<hid_t>(*this), 0, lk))
{
throw std::runtime_error("Failure setting symbol size parameter for symbol table nodes!");
}
}
unsigned FileCreationList::btree_symbols() const
{
unsigned ret;
if(0 > H5Pget_sym_k(static_cast<hid_t>(*this), NULL, &ret))
{
throw std::runtime_error("Failure retrieving symbol size parameter for symbol table nodes!");
}
return ret;
}
} // namespace property
} // namespace hdf5
<commit_msg>some simplification of sizes functions, variable nomenclature changes; updates #98'<commit_after>//
// (c) Copyright 2017 DESY,ESS
//
// This file is part of h5cpp.
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published
// by the Free Software Foundation; either version 2.1 of the License, or
// (at your option) any later version.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty ofMERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
// License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the
// Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor
// Boston, MA 02110-1301 USA
// ===========================================================================
//
// Author: Eugen Wintersberger <eugen.wintersberger@desy.de>
// Created on: Aug 16, 2017
//
#include <stdexcept>
#include <h5cpp/property/file_creation.hpp>
namespace hdf5 {
namespace property{
FileCreationList::FileCreationList():
GroupCreationList(kFileCreate)
{
}
FileCreationList::~FileCreationList()
{}
hsize_t FileCreationList::user_block() const
{
hsize_t buffer;
if(0 > H5Pget_userblock(static_cast<hid_t>(*this), &buffer))
{
throw std::runtime_error("Cannot retrieve user block size from file creation property list!");
}
return buffer;
}
void FileCreationList::user_block(hsize_t size) const
{
if(0 > H5Pset_userblock(static_cast<hid_t>(*this), size))
{
throw std::runtime_error("Cannot set user block size for file creation property list!");
}
}
void FileCreationList::object_offset_size(size_t size) const
{
if(0 > H5Pset_sizes(static_cast<hid_t>(*this), size, 0))
{
throw std::runtime_error("Failure setting object offset size to file creation property list!");
}
}
size_t FileCreationList::object_offset_size() const
{
size_t offset_size {0};
if(0 > H5Pget_sizes(static_cast<hid_t>(*this), &offset_size, NULL))
{
throw std::runtime_error("Failure retrieving object offset size from file creation property list!");
}
return offset_size;
}
void FileCreationList::object_length_size(size_t size) const
{
if(0 > H5Pset_sizes(static_cast<hid_t>(*this), 0, size))
{
throw std::runtime_error("Failure setting object length size in file creation property list!");
}
}
size_t FileCreationList::object_length_size() const
{
size_t length_size {0};
if(0 > H5Pget_sizes(static_cast<hid_t>(*this), NULL, &length_size))
{
throw std::runtime_error("Failure retrieving object length size from file creation property list!");
}
return length_size;
}
void FileCreationList::btree_rank(unsigned ik)
{
if(0 > H5Pset_sym_k(static_cast<hid_t>(*this), ik, 0))
{
throw std::runtime_error("Failure setting rank parameter for symbol table nodes!");
}
}
unsigned FileCreationList::btree_rank() const
{
unsigned ik {0};
if(0 > H5Pget_sym_k(static_cast<hid_t>(*this), &ik, NULL))
{
throw std::runtime_error("Failure retrieving rank parameter for symbol table nodes!");
}
return ik;
}
void FileCreationList::btree_symbols(unsigned lk)
{
if(0 > H5Pset_sym_k(static_cast<hid_t>(*this), 0, lk))
{
throw std::runtime_error("Failure setting symbol size parameter for symbol table nodes!");
}
}
unsigned FileCreationList::btree_symbols() const
{
unsigned lk {0};
if(0 > H5Pget_sym_k(static_cast<hid_t>(*this), NULL, &lk))
{
throw std::runtime_error("Failure retrieving symbol size parameter for symbol table nodes!");
}
return lk;
}
} // namespace property
} // namespace hdf5
<|endoftext|>
|
<commit_before>/*************************************************************************
*
* $RCSfile: so_main.cxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2004-08-20 10:08:44 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef UNIX
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif //end of UNIX
#ifdef WNT
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#endif //end of WNT
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "ns_debug.hxx"
#include "so_msg.hxx"
#include "so_instance.hxx"
#include "so_env.hxx"
#include "nsp_func.hxx"
#define MAX_NODE_NUM 1024
SoPluginInstance* lpInstance[MAX_NODE_NUM];
long int NSP_ReadFromPipe(NSP_PIPE_FD fp, void* buf, unsigned long int len)
{
unsigned long int len_unix = 0, len_wnt = 0;
len_unix = NSP_Read_Pipe(fp, buf, len, &len_wnt);
#ifdef UNIX
return len_unix;
#endif //end of UNIX
#ifdef WNT
return len_wnt;
#endif //end of WNT
}
int find_free_node()
{
for(int i=0; i<MAX_NODE_NUM; i++)
{
if(NULL == lpInstance[i])
return i;
}
return -1;
}
int find_cur_node(sal_Int32 cur_id)
{
for(int i=0; i<MAX_NODE_NUM; i++)
{
if(lpInstance[i] == NULL)
continue;
if(cur_id == lpInstance[i]->GetParent())
return i;
}
return -1;
}
sal_Bool dump_plugin_message(PLUGIN_MSG* pMsg)
{
if (!pMsg)
return sal_False;
debug_fprintf(NSP_LOG_APPEND, "NSPlugin Message: msg_id:%d; instance_id:%d;wnd_id:%d;wnd_x:%d;wnd_y:%d;wnd_w:%d;wnd_h:%d; url:%s\n",
pMsg->msg_id, pMsg->instance_id, pMsg->wnd_id,
pMsg->wnd_x, pMsg->wnd_y, pMsg->wnd_w, pMsg->wnd_h, pMsg->url);
return sal_True;
}
int prepareEnviron()
{
// if child process inherit the chdir() property from parent process, if yes, no getNewLibraryPath() needed
const char* pNewLibraryPath = getNewLibraryPath();
putenv( (char*) pNewLibraryPath );
SoPluginInstance::SetSODir((char *)findProgramDir());
return 0;
}
int Set_Window(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int cur_no;
if( -1 == (cur_no = find_cur_node(pMsg->instance_id)))
return -1;
if(lpInstance[cur_no]->SetWindow(pMsg->wnd_id,
pMsg->wnd_x, pMsg->wnd_y, pMsg->wnd_w, pMsg->wnd_h))
return 0;
else
return -1;
}
int Set_URL(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int cur_no;
if( -1 == (cur_no = find_cur_node(pMsg->instance_id)))
return -1;
if(lpInstance[cur_no]->SetURL(pMsg->url))
return 0;
else
return -1;
}
int New_Instance(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int free_no;
if( -1 == (free_no = find_free_node()))
return -1;
lpInstance[free_no] = new SoPluginInstance(pMsg->instance_id);
return 0;
}
int Destroy(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int cur_no;
if( -1 == (cur_no = find_cur_node(pMsg->instance_id)))
return -1;
if(lpInstance[cur_no] != NULL)
{
lpInstance[cur_no]->Destroy();
debug_fprintf(NSP_LOG_APPEND, "print by Nsplugin, begin delete.\n");
delete(lpInstance[cur_no]);
lpInstance[cur_no] = NULL;
}
return 0;
}
int Print(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int cur_no;
if( -1 == (cur_no = find_cur_node(pMsg->instance_id)))
return -1;
if(lpInstance[cur_no] != NULL)
{
lpInstance[cur_no]->Print();
}
return 0;
}
int Shutdown()
{
for(int cur_no=0; cur_no<MAX_NODE_NUM; cur_no++)
{
if(lpInstance[cur_no] == NULL)
continue;
lpInstance[cur_no]->Destroy();
debug_fprintf(NSP_LOG_APPEND, "print by Nsplugin, begin delete.\n");
delete(lpInstance[cur_no]);
lpInstance[cur_no] = NULL;
}
return -1;
}
int dispatchMsg(PLUGIN_MSG* pMsg)
{
switch(pMsg->msg_id)
{
case SO_SET_WINDOW:
return Set_Window(pMsg);
case SO_NEW_INSTANCE:
return New_Instance(pMsg);
case SO_SET_URL:
return Set_URL(pMsg);
case SO_DESTROY:
return Destroy(pMsg);
case SO_SHUTDOWN:
Shutdown();
return -1;
case SO_PRINT:
Print(pMsg);
return 0;
default:
return -1;
break;
}
}
sal_Bool start_office(NSP_PIPE_FD read_fd)
{
int my_sock;
struct sockaddr_in dst_addr;
#ifdef WNT
{
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD(2,0);
if(WSAStartup(wVersionRequested, &wsaData))
{
NSP_Close_Pipe(read_fd);
debug_fprintf(NSP_LOG_APPEND, "Can not init socket in Windows.\n");
return sal_False;
}
}
#endif //end of WNT
memset(&dst_addr, 0, sizeof(dst_addr));
dst_addr.sin_family = AF_INET;
dst_addr.sin_port = htons(SO_SERVER_PORT);
dst_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int count = 0;
int ret = 0;
my_sock=socket(PF_INET, SOCK_STREAM, 0);
// if Star Office has been stared, we need not to start it again
ret = connect(my_sock, (struct sockaddr *)&dst_addr, sizeof(dst_addr));
if(ret == 0)
{
NSP_CloseSocket(my_sock);
debug_fprintf(NSP_LOG_APPEND, "Staroffice already start\n");
return sal_True;
}
{
debug_fprintf(NSP_LOG_APPEND, "try to star Staroffice\n");
char para[128] = {0};
sprintf(para, "-accept=socket,host=0,port=%d;urp", SO_SERVER_PORT);
#ifdef UNIX
int nChildPID = fork();
if( ! nChildPID ) // child process
{
NSP_CloseSocket(my_sock);
NSP_Close_Pipe(read_fd);
execl("/bin/sh", "/bin/sh", "soffice", "-nologo", "-nodefault", para, NULL);
_exit(255);
}
#endif //end of UNIX
#ifdef WNT
STARTUPINFO NSP_StarInfo;
memset((void*) &NSP_StarInfo, 0, sizeof(STARTUPINFO));
NSP_StarInfo.cb = sizeof(STARTUPINFO);
PROCESS_INFORMATION NSP_ProcessInfo;
memset((void*)&NSP_ProcessInfo, 0, sizeof(PROCESS_INFORMATION));
sprintf(para, " -nologo -nodefault -accept=socket,host=0,port=%d;urp", SO_SERVER_PORT);
SECURITY_ATTRIBUTES NSP_access = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE};
CreateProcess(findSofficeExecutable(), para, NULL, NULL, FALSE,
0 , NULL, NULL, &NSP_StarInfo, &NSP_ProcessInfo);
#endif //end of WNT
}
// try to connect to background SO, thus judge if it is ready
while(0 > connect(my_sock, (struct sockaddr *)&dst_addr, sizeof(dst_addr)))
{
NSP_Sleep(1);
if (count++ >= 120)
{
NSP_CloseSocket(my_sock);
debug_fprintf(NSP_LOG_APPEND, "print by nsplugin, con star remote StarOffice\n");
return sal_False;
}
debug_fprintf(NSP_LOG_APPEND, "print by nsplugin, Current count: %d\n", count);
}
NSP_CloseSocket(my_sock);
NSP_Sleep(5);
prepareEnviron();
return sal_True;
}
static NSP_PIPE_FD la_read_fd = 0;
int main(int argc, char** argv)
{
// Sleep(20*1000);
debug_fprintf(NSP_LOG_APPEND, "start of main\n");
memset(lpInstance, 0, sizeof(lpInstance));
char readbuf[NPP_BUFFER_SIZE];
NSP_PIPE_FD fd_pipe[2];
int iPipe[2];
#ifdef UNIX
if(argc < 3)
{
debug_fprintf(NSP_LOG_APPEND, "print by nsplugin, command error; too little argument to start plugin exec\n");
return sal_False;
}
iPipe[0] = atoi(argv[1]);
iPipe[1] = atoi(argv[2]);
#endif //end of UNIX
#ifdef WNT
//sscanf( GetCommandLine(), "%d %d", &iPipe[0], &iPipe[1] );
iPipe[0] = atoi(argv[0]);
iPipe[1] = atoi(argv[1]);
#endif //end of WNT
// fd_pipe[0]: read, fd_pipe[0]: write
fd_pipe[0] = (NSP_PIPE_FD) iPipe[0] ;
fd_pipe[1] = (NSP_PIPE_FD) iPipe[1] ;
NSP_Close_Pipe(fd_pipe[1]);
la_read_fd = fd_pipe[0];
if(la_read_fd < 0)
{
debug_fprintf(NSP_LOG_APPEND, "print by nsplugin, command error: bad read file id:%s \n", la_read_fd);
return 0;
}
if(!start_office(la_read_fd))
{
NSP_Close_Pipe(la_read_fd);
return -1;
}
PLUGIN_MSG nMsg;
int len;
while(1)
{
memset(&nMsg, 0, sizeof(PLUGIN_MSG));
len = NSP_ReadFromPipe(la_read_fd, (char*)&nMsg, sizeof(PLUGIN_MSG));
if(len != sizeof(PLUGIN_MSG))
break;
debug_fprintf(NSP_LOG_APPEND, "Read message from pipe type %d \n", nMsg.msg_id);
if(-1 == dispatchMsg(&nMsg))
{
debug_fprintf(NSP_LOG_APPEND, "plugin will shutdown\n");
break;
}
}
NSP_Close_Pipe(la_read_fd);
_exit(0);
}
extern "C"{
sal_Bool restart_office(void){
return start_office(la_read_fd);
}
}
<commit_msg>INTEGRATION: CWS nsplugin3 (1.2.32); FILE MERGED 2004/11/12 02:01:02 jmeng 1.2.32.1: change paramater of CreateProcess in Windows to pass correct __argv to SO<commit_after>/*************************************************************************
*
* $RCSfile: so_main.cxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: kz $ $Date: 2004-11-26 16:02:22 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRUNTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRUNTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc..
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifdef UNIX
#include <sys/stat.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#endif //end of UNIX
#ifdef WNT
#pragma once
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <winsock2.h>
#include <stdlib.h>
#include <malloc.h>
#include <memory.h>
#include <tchar.h>
#endif //end of WNT
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include "ns_debug.hxx"
#include "so_msg.hxx"
#include "so_instance.hxx"
#include "so_env.hxx"
#include "nsp_func.hxx"
#define MAX_NODE_NUM 1024
SoPluginInstance* lpInstance[MAX_NODE_NUM];
long int NSP_ReadFromPipe(NSP_PIPE_FD fp, void* buf, unsigned long int len)
{
unsigned long int len_unix = 0, len_wnt = 0;
len_unix = NSP_Read_Pipe(fp, buf, len, &len_wnt);
#ifdef UNIX
return len_unix;
#endif //end of UNIX
#ifdef WNT
return len_wnt;
#endif //end of WNT
}
int find_free_node()
{
for(int i=0; i<MAX_NODE_NUM; i++)
{
if(NULL == lpInstance[i])
return i;
}
return -1;
}
int find_cur_node(sal_Int32 cur_id)
{
for(int i=0; i<MAX_NODE_NUM; i++)
{
if(lpInstance[i] == NULL)
continue;
if(cur_id == lpInstance[i]->GetParent())
return i;
}
return -1;
}
sal_Bool dump_plugin_message(PLUGIN_MSG* pMsg)
{
if (!pMsg)
return sal_False;
debug_fprintf(NSP_LOG_APPEND, "NSPlugin Message: msg_id:%d; instance_id:%d;wnd_id:%d;wnd_x:%d;wnd_y:%d;wnd_w:%d;wnd_h:%d; url:%s\n",
pMsg->msg_id, pMsg->instance_id, pMsg->wnd_id,
pMsg->wnd_x, pMsg->wnd_y, pMsg->wnd_w, pMsg->wnd_h, pMsg->url);
return sal_True;
}
int prepareEnviron()
{
// if child process inherit the chdir() property from parent process, if yes, no getNewLibraryPath() needed
const char* pNewLibraryPath = getNewLibraryPath();
putenv( (char*) pNewLibraryPath );
SoPluginInstance::SetSODir((char *)findProgramDir());
return 0;
}
int Set_Window(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int cur_no;
if( -1 == (cur_no = find_cur_node(pMsg->instance_id)))
return -1;
if(lpInstance[cur_no]->SetWindow(pMsg->wnd_id,
pMsg->wnd_x, pMsg->wnd_y, pMsg->wnd_w, pMsg->wnd_h))
return 0;
else
return -1;
}
int Set_URL(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int cur_no;
if( -1 == (cur_no = find_cur_node(pMsg->instance_id)))
return -1;
if(lpInstance[cur_no]->SetURL(pMsg->url))
return 0;
else
return -1;
}
int New_Instance(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int free_no;
if( -1 == (free_no = find_free_node()))
return -1;
lpInstance[free_no] = new SoPluginInstance(pMsg->instance_id);
return 0;
}
int Destroy(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int cur_no;
if( -1 == (cur_no = find_cur_node(pMsg->instance_id)))
return -1;
if(lpInstance[cur_no] != NULL)
{
lpInstance[cur_no]->Destroy();
debug_fprintf(NSP_LOG_APPEND, "print by Nsplugin, begin delete.\n");
delete(lpInstance[cur_no]);
lpInstance[cur_no] = NULL;
}
return 0;
}
int Print(PLUGIN_MSG* pMsg)
{
dump_plugin_message(pMsg);
int cur_no;
if( -1 == (cur_no = find_cur_node(pMsg->instance_id)))
return -1;
if(lpInstance[cur_no] != NULL)
{
lpInstance[cur_no]->Print();
}
return 0;
}
int Shutdown()
{
for(int cur_no=0; cur_no<MAX_NODE_NUM; cur_no++)
{
if(lpInstance[cur_no] == NULL)
continue;
lpInstance[cur_no]->Destroy();
debug_fprintf(NSP_LOG_APPEND, "print by Nsplugin, begin delete.\n");
delete(lpInstance[cur_no]);
lpInstance[cur_no] = NULL;
}
return -1;
}
int dispatchMsg(PLUGIN_MSG* pMsg)
{
switch(pMsg->msg_id)
{
case SO_SET_WINDOW:
return Set_Window(pMsg);
case SO_NEW_INSTANCE:
return New_Instance(pMsg);
case SO_SET_URL:
return Set_URL(pMsg);
case SO_DESTROY:
return Destroy(pMsg);
case SO_SHUTDOWN:
Shutdown();
return -1;
case SO_PRINT:
Print(pMsg);
return 0;
default:
return -1;
break;
}
}
sal_Bool start_office(NSP_PIPE_FD read_fd)
{
int my_sock;
struct sockaddr_in dst_addr;
char sCommand[NPP_PATH_MAX];
sCommand[0] = 0;
#ifdef WNT
{
WSADATA wsaData;
WORD wVersionRequested;
wVersionRequested = MAKEWORD(2,0);
if(WSAStartup(wVersionRequested, &wsaData))
{
NSP_Close_Pipe(read_fd);
debug_fprintf(NSP_LOG_APPEND, "Can not init socket in Windows.\n");
return sal_False;
}
}
#endif //end of WNT
memset(&dst_addr, 0, sizeof(dst_addr));
dst_addr.sin_family = AF_INET;
dst_addr.sin_port = htons(SO_SERVER_PORT);
dst_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int count = 0;
int ret = 0;
my_sock=socket(PF_INET, SOCK_STREAM, 0);
// if Star Office has been stared, we need not to start it again
ret = connect(my_sock, (struct sockaddr *)&dst_addr, sizeof(dst_addr));
if(ret == 0)
{
NSP_CloseSocket(my_sock);
debug_fprintf(NSP_LOG_APPEND, "Staroffice already start\n");
return sal_True;
}
{
debug_fprintf(NSP_LOG_APPEND, "try to star Staroffice\n");
char para[128] = {0};
sprintf(para, "-accept=socket,host=0,port=%d;urp", SO_SERVER_PORT);
#ifdef UNIX
int nChildPID = fork();
if( ! nChildPID ) // child process
{
NSP_CloseSocket(my_sock);
NSP_Close_Pipe(read_fd);
sprintf(sCommand, "/bin/sh soffice -nologo -nodefault %s", para);
debug_fprintf(NSP_LOG_APPEND,"StarOffice will be started by command: %s\n",sCommand);
execl("/bin/sh", "/bin/sh", "soffice", "-nologo", "-nodefault", para, NULL);
_exit(255);
}
#endif //end of UNIX
#ifdef WNT
STARTUPINFO NSP_StarInfo;
memset((void*) &NSP_StarInfo, 0, sizeof(STARTUPINFO));
NSP_StarInfo.cb = sizeof(STARTUPINFO);
PROCESS_INFORMATION NSP_ProcessInfo;
memset((void*)&NSP_ProcessInfo, 0, sizeof(PROCESS_INFORMATION));
sprintf(para, " -nologo -nodefault -accept=socket,host=0,port=%d;urp", SO_SERVER_PORT);
//sprintf(para, " -accept=socket,host=0,port=%d;urp\n", SO_SERVER_PORT);
SECURITY_ATTRIBUTES NSP_access = { sizeof(SECURITY_ATTRIBUTES), NULL, FALSE};
sprintf(sCommand, "\"%s\" %s", findSofficeExecutable(), para);
debug_fprintf(NSP_LOG_APPEND,"StarOffice will be started by command: %s",sCommand);
BOOL ret = false;
ret = CreateProcess(findSofficeExecutable(), sCommand, NULL, NULL, FALSE,
0 , NULL, NULL, &NSP_StarInfo, &NSP_ProcessInfo);
if(ret==false){
debug_fprintf(NSP_LOG_APPEND,"run staroffice error: %u \n",
GetLastError());
}
else debug_fprintf(NSP_LOG_APPEND,"run staroffice success\n");
#endif //end of WNT
}
NSP_Sleep(5);
// try to connect to background SO, thus judge if it is ready
while(0 > connect(my_sock, (struct sockaddr *)&dst_addr, sizeof(dst_addr)))
{
NSP_Sleep(1);
if (count++ >= 120)
{
NSP_CloseSocket(my_sock);
debug_fprintf(NSP_LOG_APPEND, "print by nsplugin, con star remote StarOffice\n");
return sal_False;
}
debug_fprintf(NSP_LOG_APPEND, "print by nsplugin, Current count: %d\n", count);
}
NSP_CloseSocket(my_sock);
NSP_Sleep(5);
prepareEnviron();
return sal_True;
}
static NSP_PIPE_FD la_read_fd = 0;
int main(int argc, char** argv)
{
// Sleep(20*1000);
debug_fprintf(NSP_LOG_APPEND, "start of main\n");
memset(lpInstance, 0, sizeof(lpInstance));
char readbuf[NPP_BUFFER_SIZE];
NSP_PIPE_FD fd_pipe[2];
int iPipe[2];
#ifdef UNIX
if(argc < 3)
{
debug_fprintf(NSP_LOG_APPEND, "print by nsplugin, command error; too little argument to start plugin exec\n");
return sal_False;
}
iPipe[0] = atoi(argv[1]);
iPipe[1] = atoi(argv[2]);
#endif //end of UNIX
#ifdef WNT
//sscanf( GetCommandLine(), "%d %d", &iPipe[0], &iPipe[1] );
iPipe[0] = atoi(argv[0]);
iPipe[1] = atoi(argv[1]);
#endif //end of WNT
// fd_pipe[0]: read, fd_pipe[0]: write
fd_pipe[0] = (NSP_PIPE_FD) iPipe[0] ;
fd_pipe[1] = (NSP_PIPE_FD) iPipe[1] ;
NSP_Close_Pipe(fd_pipe[1]);
la_read_fd = fd_pipe[0];
if(la_read_fd < 0)
{
debug_fprintf(NSP_LOG_APPEND, "print by nsplugin, command error: bad read file id:%s \n", la_read_fd);
return 0;
}
if(!start_office(la_read_fd))
{
NSP_Close_Pipe(la_read_fd);
return -1;
}
PLUGIN_MSG nMsg;
int len;
while(1)
{
memset(&nMsg, 0, sizeof(PLUGIN_MSG));
len = NSP_ReadFromPipe(la_read_fd, (char*)&nMsg, sizeof(PLUGIN_MSG));
if(len != sizeof(PLUGIN_MSG))
break;
debug_fprintf(NSP_LOG_APPEND, "Read message from pipe type %d \n", nMsg.msg_id);
if(-1 == dispatchMsg(&nMsg))
{
debug_fprintf(NSP_LOG_APPEND, "plugin will shutdown\n");
break;
}
}
NSP_Close_Pipe(la_read_fd);
_exit(0);
}
extern "C"{
sal_Bool restart_office(void){
return start_office(la_read_fd);
}
}
<|endoftext|>
|
<commit_before>/*
addcontactwizard.cpp - Kopete's Add Contact Wizard
Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org>
Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qlayout.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <klineeditdlg.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <klistview.h>
#include "addcontactpage.h"
#include "addcontactwizard.h"
#include "kopetegroup.h"
#include "kopetecontactlist.h"
#include "kopeteprotocol.h"
#include "kopetemetacontact.h"
#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopeteprotocol.h"
AddContactWizard::AddContactWizard( QWidget *parent, const char *name )
: AddContactWizard_Base( parent, name )
{
QStringList groups = KopeteContactList::contactList()->groups().toStringList();
QStringList::ConstIterator it = groups.begin();
for( ; it != groups.end(); ++it )
{
QString groupname = *it;
if ( !groupname.isNull() )
new QCheckListItem( groupList, groupname, QCheckListItem::CheckBox);
}
protocolListView->clear();
m_accountItems.clear();
QCheckListItem* accountLVI=0L;
QPtrList<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts();
for(KopeteAccount *i=accounts.first() ; i; i=accounts.next() )
{
accountLVI= new QCheckListItem( protocolListView, i->accountId(), QCheckListItem::CheckBox);
accountLVI->setText(1,i->protocol()->displayName() + QString::fromLatin1(" ") );
accountLVI->setPixmap( 1, SmallIcon( i->protocol()->pluginIcon() ) );
m_accountItems.insert(accountLVI,i);
}
if ( accounts.count() == 1 )
{
accountLVI->setOn( true );
setAppropriate( selectService, false );
}
setNextEnabled(selectService, (accounts.count() == 1));
setFinishEnabled(finis, true);
connect( addGroupButton, SIGNAL(clicked()) , SLOT(slotAddGroupClicked()) );
connect( protocolListView, SIGNAL(clicked(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *)));
}
AddContactWizard::~AddContactWizard()
{
}
void AddContactWizard::slotProtocolListClicked( QListViewItem *)
{
// Just makes sure a protocol is selected before allowing the user to continue
bool oneIsChecked = false;
for (QListViewItemIterator it(protocolListView); it.current(); ++it)
{
QCheckListItem *check = dynamic_cast<QCheckListItem *>(it.current());
if (check && check->isOn())
{
oneIsChecked = true;
break;
}
}
setNextEnabled(selectService, oneIsChecked);
}
void AddContactWizard::slotGroupListClicked( QListViewItem *)
{
//top-level contacts are allowed
/*
bool oneIsChecked = false;
for (QListViewItem *listItem = groupList->firstChild(); listItem != 0; listItem = listItem->itemBelow())
{
QCheckListItem *check = dynamic_cast<QCheckListItem *>(listItem);
if (!check)
{
kdDebug(14000) << "WARNING : AddContactWizard::slotGroupListClicked : one listItem is not a CheckListItem" << endl;
}
else if (check->isOn())
{
oneIsChecked = true;
break;
}
}
setNextEnabled(page2,oneIsChecked);
*/
}
void AddContactWizard::slotAddGroupClicked()
{
bool ok;
QString groupName = KLineEditDlg::getText(
i18n( "New Group - Kopete" ),
i18n( "Please enter the name for the new group:" ),
QString::null, &ok );
if ( !groupName.isNull() && ok)
new QCheckListItem( groupList, groupName, QCheckListItem::CheckBox);
}
void AddContactWizard::slotRemoveGroupClicked()
{
}
void AddContactWizard::accept()
{
KopeteMetaContact *m = new KopeteMetaContact();
bool topLevel = true;
for (QListViewItemIterator it(groupList); it.current(); ++it)
{
QCheckListItem *check = dynamic_cast<QCheckListItem *>(it.current());
if (check && check->isOn())
{
m->addToGroup(KopeteContactList::contactList()->getGroup(check->text()));
topLevel = false;
}
}
m->setTopLevel(topLevel);
QMap <KopeteAccount*,AddContactPage*>::Iterator it;
for ( it = protocolPages.begin(); it != protocolPages.end(); ++it )
{
it.data()->apply(it.key(),m);
}
KopeteContactList::contactList()->addMetaContact(m);
delete(this);
}
void AddContactWizard::next()
{
if (currentPage() == selectService ||
(currentPage() == intro && !appropriate( selectService )))
{
QMap <KopeteAccount*,AddContactPage*>::Iterator it;
for ( it = protocolPages.begin(); it != protocolPages.end(); ++it )
{
delete it.data();
}
protocolPages.clear();
// We don't keep track of this pointer because it gets deleted when the wizard does (which is what we want)
for (QListViewItemIterator it(protocolListView); it.current(); ++it)
{
QCheckListItem *item = dynamic_cast<QCheckListItem *>(it.current());
if (item && item->isOn())
{
// this shouldn't happen either, but I hate crashes
if (!m_accountItems[item]) continue;
AddContactPage *addPage = m_accountItems[item]->protocol()->createAddContactWidget(this, m_accountItems[item] );
if (!addPage) continue;
QString title = i18n( "The account name is prepended here",
"%1 contact information" )
.arg( item->text(0) );
addPage->show();
insertPage( addPage, title, indexOf( selectGroup) );
protocolPages.insert( m_accountItems[item] , addPage );
}
}
QWizard::next();
return;
}
if (currentPage() != intro &&
currentPage() != selectService &&
currentPage() != selectGroup &&
currentPage() != finis)
{
AddContactPage *ePage = dynamic_cast<AddContactPage *>(currentPage());
if (!ePage || !ePage->validateData())
return;
}
QWizard::next();
}
#include "addcontactwizard.moc"
// vim: set noet ts=4 sts=4 sw=4:
<commit_msg>Remove the metacontact created by the add contact wizzard if the contact creation fail<commit_after>/*
addcontactwizard.cpp - Kopete's Add Contact Wizard
Copyright (c) 2002 by Nick Betcher <nbetcher@kde.org>
Copyright (c) 2002 by Duncan Mac-Vicar Prett <duncan@kde.org>
Kopete (c) 2002 by the Kopete developers <kopete-devel@kde.org>
*************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*************************************************************************
*/
#include <qlayout.h>
#include <kglobal.h>
#include <klocale.h>
#include <kiconloader.h>
#include <klineeditdlg.h>
#include <kpushbutton.h>
#include <kstandarddirs.h>
#include <kdebug.h>
#include <klistview.h>
#include "addcontactpage.h"
#include "addcontactwizard.h"
#include "kopetegroup.h"
#include "kopetecontactlist.h"
#include "kopeteprotocol.h"
#include "kopetemetacontact.h"
#include "kopeteaccountmanager.h"
#include "kopeteaccount.h"
#include "kopeteprotocol.h"
AddContactWizard::AddContactWizard( QWidget *parent, const char *name )
: AddContactWizard_Base( parent, name )
{
QStringList groups = KopeteContactList::contactList()->groups().toStringList();
QStringList::ConstIterator it = groups.begin();
for( ; it != groups.end(); ++it )
{
QString groupname = *it;
if ( !groupname.isNull() )
new QCheckListItem( groupList, groupname, QCheckListItem::CheckBox);
}
protocolListView->clear();
m_accountItems.clear();
QCheckListItem* accountLVI=0L;
QPtrList<KopeteAccount> accounts = KopeteAccountManager::manager()->accounts();
for(KopeteAccount *i=accounts.first() ; i; i=accounts.next() )
{
accountLVI= new QCheckListItem( protocolListView, i->accountId(), QCheckListItem::CheckBox);
accountLVI->setText(1,i->protocol()->displayName() + QString::fromLatin1(" ") );
accountLVI->setPixmap( 1, SmallIcon( i->protocol()->pluginIcon() ) );
m_accountItems.insert(accountLVI,i);
}
if ( accounts.count() == 1 )
{
accountLVI->setOn( true );
setAppropriate( selectService, false );
}
setNextEnabled(selectService, (accounts.count() == 1));
setFinishEnabled(finis, true);
connect( addGroupButton, SIGNAL(clicked()) , SLOT(slotAddGroupClicked()) );
connect( protocolListView, SIGNAL(clicked(QListViewItem *)), this, SLOT(slotProtocolListClicked(QListViewItem *)));
}
AddContactWizard::~AddContactWizard()
{
}
void AddContactWizard::slotProtocolListClicked( QListViewItem *)
{
// Just makes sure a protocol is selected before allowing the user to continue
bool oneIsChecked = false;
for (QListViewItemIterator it(protocolListView); it.current(); ++it)
{
QCheckListItem *check = dynamic_cast<QCheckListItem *>(it.current());
if (check && check->isOn())
{
oneIsChecked = true;
break;
}
}
setNextEnabled(selectService, oneIsChecked);
}
void AddContactWizard::slotGroupListClicked( QListViewItem *)
{
//top-level contacts are allowed
/*
bool oneIsChecked = false;
for (QListViewItem *listItem = groupList->firstChild(); listItem != 0; listItem = listItem->itemBelow())
{
QCheckListItem *check = dynamic_cast<QCheckListItem *>(listItem);
if (!check)
{
kdDebug(14000) << "WARNING : AddContactWizard::slotGroupListClicked : one listItem is not a CheckListItem" << endl;
}
else if (check->isOn())
{
oneIsChecked = true;
break;
}
}
setNextEnabled(page2,oneIsChecked);
*/
}
void AddContactWizard::slotAddGroupClicked()
{
bool ok;
QString groupName = KLineEditDlg::getText(
i18n( "New Group - Kopete" ),
i18n( "Please enter the name for the new group:" ),
QString::null, &ok );
if ( !groupName.isNull() && ok)
new QCheckListItem( groupList, groupName, QCheckListItem::CheckBox);
}
void AddContactWizard::slotRemoveGroupClicked()
{
}
void AddContactWizard::accept()
{
KopeteMetaContact *m = new KopeteMetaContact();
bool topLevel = true;
for (QListViewItemIterator it(groupList); it.current(); ++it)
{
QCheckListItem *check = dynamic_cast<QCheckListItem *>(it.current());
if (check && check->isOn())
{
m->addToGroup(KopeteContactList::contactList()->getGroup(check->text()));
topLevel = false;
}
}
m->setTopLevel(topLevel);
bool ok=false;
QMap <KopeteAccount*,AddContactPage*>::Iterator it;
for ( it = protocolPages.begin(); it != protocolPages.end(); ++it )
{
ok |= it.data()->apply(it.key(),m);
}
if(ok)
KopeteContactList::contactList()->addMetaContact(m);
else
delete m;
delete this;
}
void AddContactWizard::next()
{
if (currentPage() == selectService ||
(currentPage() == intro && !appropriate( selectService )))
{
QMap <KopeteAccount*,AddContactPage*>::Iterator it;
for ( it = protocolPages.begin(); it != protocolPages.end(); ++it )
{
delete it.data();
}
protocolPages.clear();
// We don't keep track of this pointer because it gets deleted when the wizard does (which is what we want)
for (QListViewItemIterator it(protocolListView); it.current(); ++it)
{
QCheckListItem *item = dynamic_cast<QCheckListItem *>(it.current());
if (item && item->isOn())
{
// this shouldn't happen either, but I hate crashes
if (!m_accountItems[item]) continue;
AddContactPage *addPage = m_accountItems[item]->protocol()->createAddContactWidget(this, m_accountItems[item] );
if (!addPage) continue;
QString title = i18n( "The account name is prepended here",
"%1 contact information" )
.arg( item->text(0) );
addPage->show();
insertPage( addPage, title, indexOf( selectGroup) );
protocolPages.insert( m_accountItems[item] , addPage );
}
}
QWizard::next();
return;
}
if (currentPage() != intro &&
currentPage() != selectService &&
currentPage() != selectGroup &&
currentPage() != finis)
{
AddContactPage *ePage = dynamic_cast<AddContactPage *>(currentPage());
if (!ePage || !ePage->validateData())
return;
}
QWizard::next();
}
#include "addcontactwizard.moc"
// vim: set noet ts=4 sts=4 sw=4:
<|endoftext|>
|
<commit_before>#ifndef __MODEL_CLIENT_HPP__
#define __MODEL_CLIENT_HPP__
#include <map>
#include <boost/shared_ptr.hpp>
#include "urdf/model.h"
#include <lcm/lcm.h>
#include "lcmtypes/model_pub_robot_urdf_t.h"
#include <fstream>
class ModelClient
{
public:
ModelClient (lcm_t* lcm_, int keep_updated);
ModelClient(lcm_t* lcm_, std::string model_channel_, int keep_updated_);
// Get the model client directly from the specified file:
// robot name isn't important
ModelClient(std::string urdf_filename);
~ModelClient() {}
void doModelClient();
static void robot_urdf_handler_aux(const lcm_recv_buf_t* rbuf, const char* channel,
const model_pub_robot_urdf_t* msg, void* user_data){
((ModelClient *) user_data)->robot_urdf_handler(channel, msg);
}
void robot_urdf_handler(const char* channel, const model_pub_robot_urdf_t *msg);
// Returns false if urdf isn't an XML string:
bool readURDFFromFile(std::string);
void parseURDFString();
// determine which hands are connected to the robot and store that info
// this information is higher level than just the string as it assumes an lcmtype
void setHandConfiguration();
std::string getURDFString(){ return urdf_xml_string_; }
std::string getRobotName(){ return robot_name_; }
std::vector<std::string> getJointNames(){ return joint_names_; };
int8_t getLeftHand(){ return left_hand_; };
int8_t getRightHand(){ return right_hand_; };
private:
lcm_t* lcm_;
lcm::Subscription *_urdf_subscription; //valid as long as _urdf_parsed == false
bool urdf_parsed_;
std::string model_channel_;
std::string robot_name_;
std::string urdf_xml_string_;
std::vector<std::string> joint_names_;
std::map<std::string, boost::shared_ptr<urdf::Link> > links_map_;
int keep_updated_;
int8_t left_hand_, right_hand_;
bool file_read_success_;
};
#endif
<commit_msg>add cpp include<commit_after>#ifndef __MODEL_CLIENT_HPP__
#define __MODEL_CLIENT_HPP__
#include <map>
#include <boost/shared_ptr.hpp>
#include "urdf/model.h"
#include <lcm/lcm.h>
#include <lcm/lcm-cpp.hpp>
#include "lcmtypes/model_pub_robot_urdf_t.h"
#include <fstream>
class ModelClient
{
public:
ModelClient (lcm_t* lcm_, int keep_updated);
ModelClient(lcm_t* lcm_, std::string model_channel_, int keep_updated_);
// Get the model client directly from the specified file:
// robot name isn't important
ModelClient(std::string urdf_filename);
~ModelClient() {}
void doModelClient();
static void robot_urdf_handler_aux(const lcm_recv_buf_t* rbuf, const char* channel,
const model_pub_robot_urdf_t* msg, void* user_data){
((ModelClient *) user_data)->robot_urdf_handler(channel, msg);
}
void robot_urdf_handler(const char* channel, const model_pub_robot_urdf_t *msg);
// Returns false if urdf isn't an XML string:
bool readURDFFromFile(std::string);
void parseURDFString();
// determine which hands are connected to the robot and store that info
// this information is higher level than just the string as it assumes an lcmtype
void setHandConfiguration();
std::string getURDFString(){ return urdf_xml_string_; }
std::string getRobotName(){ return robot_name_; }
std::vector<std::string> getJointNames(){ return joint_names_; };
int8_t getLeftHand(){ return left_hand_; };
int8_t getRightHand(){ return right_hand_; };
private:
lcm_t* lcm_;
lcm::Subscription *_urdf_subscription; //valid as long as _urdf_parsed == false
bool urdf_parsed_;
std::string model_channel_;
std::string robot_name_;
std::string urdf_xml_string_;
std::vector<std::string> joint_names_;
std::map<std::string, boost::shared_ptr<urdf::Link> > links_map_;
int keep_updated_;
int8_t left_hand_, right_hand_;
bool file_read_success_;
};
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (C) 2012-2013 Matt Broadstone
* Contact: http://bitbucket.org/devonit/qjsonrpc
*
* This file is part of the QJsonRpc Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include <QEventLoop>
#include <QTimer>
#include <QDebug>
#if QT_VERSION >= 0x050000
#include <QJsonDocument>
#else
#include "json/qjsondocument.h"
#endif
#include "qjsonrpcsocket_p.h"
#include "qjsonrpcservicereply_p.h"
#include "qjsonrpchttpclient.h"
class QJsonRpcHttpReplyPrivate : public QJsonRpcServiceReplyPrivate
{
public:
QJsonRpcMessage request;
QNetworkReply *reply;
};
class QJsonRpcHttpReply : public QJsonRpcServiceReply
{
Q_OBJECT
public:
QJsonRpcHttpReply(const QJsonRpcMessage &request,
QNetworkReply *reply, QObject *parent = 0)
: QJsonRpcServiceReply(*new QJsonRpcHttpReplyPrivate, parent)
{
Q_D(QJsonRpcHttpReply);
d->request = request;
d->reply = reply;
connect(d->reply, SIGNAL(finished()), this, SLOT(networkReplyFinished()));
connect(d->reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(networkReplyError(QNetworkReply::NetworkError)));
}
virtual ~QJsonRpcHttpReply() {}
private Q_SLOTS:
void networkReplyFinished()
{
Q_D(QJsonRpcHttpReply);
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
qJsonRpcDebug() << Q_FUNC_INFO << "invalid reply";
return;
}
if (reply->error() != QNetworkReply::NoError) {
// this should be handled by the networkReplyError slot
} else {
QByteArray data = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(data);
if (doc.isEmpty() || doc.isNull() || !doc.isObject()) {
d->response =
d->request.createErrorResponse(QJsonRpc::ParseError,
"unable to process incoming JSON data",
QString::fromUtf8(data));
} else {
qJsonRpcDebug() << "received: " << doc.toJson();
QJsonRpcMessage response = QJsonRpcMessage::fromObject(doc.object());
if (d->request.type() == QJsonRpcMessage::Request &&
d->request.id() != response.id()) {
d->response =
d->request.createErrorResponse(QJsonRpc::InternalError,
"invalid response id",
QString::fromUtf8(data));
} else {
d->response = response;
}
}
}
Q_EMIT finished();
}
void networkReplyError(QNetworkReply::NetworkError code)
{
Q_D(QJsonRpcHttpReply);
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
qJsonRpcDebug() << Q_FUNC_INFO << "invalid reply";
return;
}
if (code == QNetworkReply::NoError)
return;
d->response = d->request.createErrorResponse(QJsonRpc::InternalError,
"error with http request",
reply->errorString());
Q_EMIT finished();
}
private:
Q_DISABLE_COPY(QJsonRpcHttpReply)
Q_DECLARE_PRIVATE(QJsonRpcHttpReply)
};
class QJsonRpcHttpClientPrivate : public QJsonRpcAbstractSocketPrivate
{
public:
void initializeNetworkAccessManager(QJsonRpcHttpClient *client) {
QObject::connect(networkAccessManager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
client, SLOT(handleAuthenticationRequired(QNetworkReply*,QAuthenticator*)));
QObject::connect(networkAccessManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
client, SLOT(handleSslErrors(QNetworkReply*,QList<QSslError>)));
}
QNetworkReply *writeMessage(const QJsonRpcMessage &message) {
QNetworkRequest request(endPoint);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Accept", "application/json-rpc");
if (!sslConfiguration.isNull())
request.setSslConfiguration(sslConfiguration);
QByteArray data = message.toJson();
qJsonRpcDebug() << "sending: " << data;
return networkAccessManager->post(request, data);
}
QUrl endPoint;
QNetworkAccessManager *networkAccessManager;
QSslConfiguration sslConfiguration;
};
QJsonRpcHttpClient::QJsonRpcHttpClient(QObject *parent)
: QJsonRpcAbstractSocket(*new QJsonRpcHttpClientPrivate, parent)
{
Q_D(QJsonRpcHttpClient);
d->networkAccessManager = new QNetworkAccessManager(this);
d->initializeNetworkAccessManager(this);
}
QJsonRpcHttpClient::QJsonRpcHttpClient(QNetworkAccessManager *manager, QObject *parent)
: QJsonRpcAbstractSocket(*new QJsonRpcHttpClientPrivate, parent)
{
Q_D(QJsonRpcHttpClient);
d->networkAccessManager = manager;
d->initializeNetworkAccessManager(this);
}
QJsonRpcHttpClient::QJsonRpcHttpClient(const QString &endPoint, QObject *parent)
: QJsonRpcAbstractSocket(*new QJsonRpcHttpClientPrivate, parent)
{
Q_D(QJsonRpcHttpClient);
d->endPoint = QUrl::fromUserInput(endPoint);
d->networkAccessManager = new QNetworkAccessManager(this);
d->initializeNetworkAccessManager(this);
}
QJsonRpcHttpClient::~QJsonRpcHttpClient()
{
}
bool QJsonRpcHttpClient::isValid() const
{
Q_D(const QJsonRpcHttpClient);
return d->networkAccessManager && !d->endPoint.isEmpty() && d->endPoint.isValid();
}
QUrl QJsonRpcHttpClient::endPoint() const
{
Q_D(const QJsonRpcHttpClient);
return d->endPoint;
}
void QJsonRpcHttpClient::setEndPoint(const QUrl &endPoint)
{
Q_D(QJsonRpcHttpClient);
d->endPoint = endPoint;
}
void QJsonRpcHttpClient::setEndPoint(const QString &endPoint)
{
Q_D(QJsonRpcHttpClient);
d->endPoint = QUrl::fromUserInput(endPoint);
}
QSslConfiguration QJsonRpcHttpClient::sslConfiguration() const
{
Q_D(const QJsonRpcHttpClient);
return d->sslConfiguration;
}
void QJsonRpcHttpClient::setSslConfiguration(const QSslConfiguration &sslConfiguration)
{
Q_D(QJsonRpcHttpClient);
d->sslConfiguration = sslConfiguration;
}
QNetworkAccessManager *QJsonRpcHttpClient::networkAccessManager()
{
Q_D(QJsonRpcHttpClient);
return d->networkAccessManager;
}
void QJsonRpcHttpClient::notify(const QJsonRpcMessage &message)
{
Q_D(QJsonRpcHttpClient);
if (d->endPoint.isEmpty()) {
qJsonRpcDebug() << Q_FUNC_INFO << "invalid endpoint specified";
return;
}
QNetworkReply *reply = d->writeMessage(message);
connect(reply, SIGNAL(finished()), reply, SLOT(deleteLater()));
// NOTE: we might want to connect this to a local slot to track errors
// for debugging later?
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), reply, SLOT(deleteLater()));
}
QJsonRpcServiceReply *QJsonRpcHttpClient::sendMessage(const QJsonRpcMessage &message)
{
Q_D(QJsonRpcHttpClient);
if (d->endPoint.isEmpty()) {
qJsonRpcDebug() << Q_FUNC_INFO << "invalid endpoint specified";
return 0;
}
QNetworkReply *reply = d->writeMessage(message);
return new QJsonRpcHttpReply(message, reply);
}
QJsonRpcMessage QJsonRpcHttpClient::sendMessageBlocking(const QJsonRpcMessage &message, int msecs)
{
QJsonRpcServiceReply *reply = sendMessage(message);
QScopedPointer<QJsonRpcServiceReply> replyPtr(reply);
QEventLoop responseLoop;
connect(reply, SIGNAL(finished()), &responseLoop, SLOT(quit()));
QTimer::singleShot(msecs, &responseLoop, SLOT(quit()));
responseLoop.exec();
if (!reply->response().isValid())
return message.createErrorResponse(QJsonRpc::TimeoutError, "request timed out");
return reply->response();
}
void QJsonRpcHttpClient::handleAuthenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator)
{
Q_UNUSED(reply)
Q_UNUSED(authenticator)
}
void QJsonRpcHttpClient::handleSslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
{
Q_UNUSED(errors)
reply->ignoreSslErrors();
}
#include "qjsonrpchttpclient.moc"
<commit_msg>remove duplicate request member in QJsonRpcHttpReply<commit_after>/*
* Copyright (C) 2012-2013 Matt Broadstone
* Contact: http://bitbucket.org/devonit/qjsonrpc
*
* This file is part of the QJsonRpc Library.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*/
#include <QEventLoop>
#include <QTimer>
#include <QDebug>
#if QT_VERSION >= 0x050000
#include <QJsonDocument>
#else
#include "json/qjsondocument.h"
#endif
#include "qjsonrpcsocket_p.h"
#include "qjsonrpcservicereply_p.h"
#include "qjsonrpchttpclient.h"
class QJsonRpcHttpReplyPrivate : public QJsonRpcServiceReplyPrivate
{
public:
QNetworkReply *reply;
};
class QJsonRpcHttpReply : public QJsonRpcServiceReply
{
Q_OBJECT
public:
QJsonRpcHttpReply(const QJsonRpcMessage &request,
QNetworkReply *reply, QObject *parent = 0)
: QJsonRpcServiceReply(*new QJsonRpcHttpReplyPrivate, parent)
{
Q_D(QJsonRpcHttpReply);
d->request = request;
d->reply = reply;
connect(d->reply, SIGNAL(finished()), this, SLOT(networkReplyFinished()));
connect(d->reply, SIGNAL(error(QNetworkReply::NetworkError)),
this, SLOT(networkReplyError(QNetworkReply::NetworkError)));
}
virtual ~QJsonRpcHttpReply() {}
private Q_SLOTS:
void networkReplyFinished()
{
Q_D(QJsonRpcHttpReply);
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
qJsonRpcDebug() << Q_FUNC_INFO << "invalid reply";
return;
}
if (reply->error() != QNetworkReply::NoError) {
// this should be handled by the networkReplyError slot
} else {
QByteArray data = reply->readAll();
QJsonDocument doc = QJsonDocument::fromJson(data);
if (doc.isEmpty() || doc.isNull() || !doc.isObject()) {
d->response =
d->request.createErrorResponse(QJsonRpc::ParseError,
"unable to process incoming JSON data",
QString::fromUtf8(data));
} else {
qJsonRpcDebug() << "received: " << doc.toJson();
QJsonRpcMessage response = QJsonRpcMessage::fromObject(doc.object());
if (d->request.type() == QJsonRpcMessage::Request &&
d->request.id() != response.id()) {
d->response =
d->request.createErrorResponse(QJsonRpc::InternalError,
"invalid response id",
QString::fromUtf8(data));
} else {
d->response = response;
}
}
}
Q_EMIT finished();
}
void networkReplyError(QNetworkReply::NetworkError code)
{
Q_D(QJsonRpcHttpReply);
QNetworkReply *reply = qobject_cast<QNetworkReply*>(sender());
if (!reply) {
qJsonRpcDebug() << Q_FUNC_INFO << "invalid reply";
return;
}
if (code == QNetworkReply::NoError)
return;
d->response = d->request.createErrorResponse(QJsonRpc::InternalError,
"error with http request",
reply->errorString());
Q_EMIT finished();
}
private:
Q_DISABLE_COPY(QJsonRpcHttpReply)
Q_DECLARE_PRIVATE(QJsonRpcHttpReply)
};
class QJsonRpcHttpClientPrivate : public QJsonRpcAbstractSocketPrivate
{
public:
void initializeNetworkAccessManager(QJsonRpcHttpClient *client) {
QObject::connect(networkAccessManager, SIGNAL(authenticationRequired(QNetworkReply*,QAuthenticator*)),
client, SLOT(handleAuthenticationRequired(QNetworkReply*,QAuthenticator*)));
QObject::connect(networkAccessManager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)),
client, SLOT(handleSslErrors(QNetworkReply*,QList<QSslError>)));
}
QNetworkReply *writeMessage(const QJsonRpcMessage &message) {
QNetworkRequest request(endPoint);
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
request.setRawHeader("Accept", "application/json-rpc");
if (!sslConfiguration.isNull())
request.setSslConfiguration(sslConfiguration);
QByteArray data = message.toJson();
qJsonRpcDebug() << "sending: " << data;
return networkAccessManager->post(request, data);
}
QUrl endPoint;
QNetworkAccessManager *networkAccessManager;
QSslConfiguration sslConfiguration;
};
QJsonRpcHttpClient::QJsonRpcHttpClient(QObject *parent)
: QJsonRpcAbstractSocket(*new QJsonRpcHttpClientPrivate, parent)
{
Q_D(QJsonRpcHttpClient);
d->networkAccessManager = new QNetworkAccessManager(this);
d->initializeNetworkAccessManager(this);
}
QJsonRpcHttpClient::QJsonRpcHttpClient(QNetworkAccessManager *manager, QObject *parent)
: QJsonRpcAbstractSocket(*new QJsonRpcHttpClientPrivate, parent)
{
Q_D(QJsonRpcHttpClient);
d->networkAccessManager = manager;
d->initializeNetworkAccessManager(this);
}
QJsonRpcHttpClient::QJsonRpcHttpClient(const QString &endPoint, QObject *parent)
: QJsonRpcAbstractSocket(*new QJsonRpcHttpClientPrivate, parent)
{
Q_D(QJsonRpcHttpClient);
d->endPoint = QUrl::fromUserInput(endPoint);
d->networkAccessManager = new QNetworkAccessManager(this);
d->initializeNetworkAccessManager(this);
}
QJsonRpcHttpClient::~QJsonRpcHttpClient()
{
}
bool QJsonRpcHttpClient::isValid() const
{
Q_D(const QJsonRpcHttpClient);
return d->networkAccessManager && !d->endPoint.isEmpty() && d->endPoint.isValid();
}
QUrl QJsonRpcHttpClient::endPoint() const
{
Q_D(const QJsonRpcHttpClient);
return d->endPoint;
}
void QJsonRpcHttpClient::setEndPoint(const QUrl &endPoint)
{
Q_D(QJsonRpcHttpClient);
d->endPoint = endPoint;
}
void QJsonRpcHttpClient::setEndPoint(const QString &endPoint)
{
Q_D(QJsonRpcHttpClient);
d->endPoint = QUrl::fromUserInput(endPoint);
}
QSslConfiguration QJsonRpcHttpClient::sslConfiguration() const
{
Q_D(const QJsonRpcHttpClient);
return d->sslConfiguration;
}
void QJsonRpcHttpClient::setSslConfiguration(const QSslConfiguration &sslConfiguration)
{
Q_D(QJsonRpcHttpClient);
d->sslConfiguration = sslConfiguration;
}
QNetworkAccessManager *QJsonRpcHttpClient::networkAccessManager()
{
Q_D(QJsonRpcHttpClient);
return d->networkAccessManager;
}
void QJsonRpcHttpClient::notify(const QJsonRpcMessage &message)
{
Q_D(QJsonRpcHttpClient);
if (d->endPoint.isEmpty()) {
qJsonRpcDebug() << Q_FUNC_INFO << "invalid endpoint specified";
return;
}
QNetworkReply *reply = d->writeMessage(message);
connect(reply, SIGNAL(finished()), reply, SLOT(deleteLater()));
// NOTE: we might want to connect this to a local slot to track errors
// for debugging later?
connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), reply, SLOT(deleteLater()));
}
QJsonRpcServiceReply *QJsonRpcHttpClient::sendMessage(const QJsonRpcMessage &message)
{
Q_D(QJsonRpcHttpClient);
if (d->endPoint.isEmpty()) {
qJsonRpcDebug() << Q_FUNC_INFO << "invalid endpoint specified";
return 0;
}
QNetworkReply *reply = d->writeMessage(message);
return new QJsonRpcHttpReply(message, reply);
}
QJsonRpcMessage QJsonRpcHttpClient::sendMessageBlocking(const QJsonRpcMessage &message, int msecs)
{
QJsonRpcServiceReply *reply = sendMessage(message);
QScopedPointer<QJsonRpcServiceReply> replyPtr(reply);
QEventLoop responseLoop;
connect(reply, SIGNAL(finished()), &responseLoop, SLOT(quit()));
QTimer::singleShot(msecs, &responseLoop, SLOT(quit()));
responseLoop.exec();
if (!reply->response().isValid())
return message.createErrorResponse(QJsonRpc::TimeoutError, "request timed out");
return reply->response();
}
void QJsonRpcHttpClient::handleAuthenticationRequired(QNetworkReply *reply, QAuthenticator *authenticator)
{
Q_UNUSED(reply)
Q_UNUSED(authenticator)
}
void QJsonRpcHttpClient::handleSslErrors(QNetworkReply *reply, const QList<QSslError> &errors)
{
Q_UNUSED(errors)
reply->ignoreSslErrors();
}
#include "qjsonrpchttpclient.moc"
<|endoftext|>
|
<commit_before>#include <ecl/thread/semaphore.hpp>
#include <array>
#include <thread>
#include <atomic>
#include <algorithm>
#include <functional>
#include <CppUTest/TestHarness.h>
#include <CppUTest/CommandLineTestRunner.h>
// Error code helper
// TODO: move it to 'utils' headers and protect with check of
// current test state (enabled or disabled)
static SimpleString StringFrom(ecl::err err)
{
return SimpleString{ecl::err_to_str(err)};
}
// Helpers
template< class Container, class Func >
static void test_for_each(Container &cont, Func fn)
{
std::for_each(cont.begin(), cont.end(), fn);
}
static void test_delay(unsigned msecs = 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(msecs));
}
constexpr auto threads_count = 10;
TEST_GROUP(semaphore)
{
void setup()
{
}
void teardown()
{
}
};
TEST(semaphore, signal_wait_no_hang)
{
// Should complete without a hang
ecl::semaphore sem;
sem.signal();
sem.wait();
}
TEST(semaphore, try_wait)
{
// Should complete without a hang
ecl::semaphore sem;
sem.signal();
auto rc = sem.try_wait();
CHECK_EQUAL(ecl::err::ok, rc);
rc = sem.try_wait();
CHECK_EQUAL(ecl::err::again, rc);
rc = sem.try_wait();
CHECK_EQUAL(ecl::err::again, rc);
// Signal same semaphore again
// to make sure counter is in valid state
sem.signal();
rc = sem.try_wait();
CHECK_EQUAL(ecl::err::ok, rc);
rc = sem.try_wait();
CHECK_EQUAL(ecl::err::again, rc);
}
TEST(semaphore, one_semaphore_few_threads)
{
// Preparation
// Counts how many threads completed
int counter = 0;
// Counts how many signals sent
int signalled = 0;
// Semaphore itself
ecl::semaphore semaphore;
auto single_thread = [&counter, &semaphore]() {
semaphore.wait();
counter++;
};
std::array< std::thread, threads_count > threads;
// Test itself
// Start threads
test_for_each(threads, [&single_thread](auto &thread) {
thread = std::thread(single_thread);
});
// Let them wait on semaphore
test_delay(20);
// Threads are started and should wait for orders
CHECK_EQUAL(0, counter);
// Unblock threads one by one
test_for_each(threads, [&](auto &thread) {
(void) thread; // We don't need this
semaphore.signal();
signalled++;
test_delay(50); // Let some thread finish its work
CHECK_EQUAL(signalled, counter); // Check that only one thread is finished
});
// Wait for threads to finish
test_for_each(threads, [](auto &thread) { thread.join(); });
}
TEST(semaphore, multiple_threads)
{
// Preparation
// Object associated with a thread
struct test_object
{
ecl::semaphore semaphore;
std::thread thread;
volatile bool flag;
};
std::array< test_object, threads_count > objs;
auto single_thread = [](auto *obj) {
obj->semaphore.wait();
obj->flag = true; // Rise a flag only if semaphore signaled
};
// Test itself
// Start threads
test_for_each(objs, [&single_thread](auto &obj) {
obj.flag = false;
obj.thread = std::thread(single_thread, &obj);
});
// Let them wait on semaphore
test_delay(100);
// Threads are started and should wait for orders
test_for_each(objs, [](auto &obj) { CHECK(!obj.flag); } );
// Unblock threads
test_for_each(objs, [](auto &obj) { obj.semaphore.signal(); });
// Let threads do the work
test_delay(100);
// Check that work is done
test_for_each(objs, [](auto &obj) { CHECK(obj.flag); });
// Wait for threads to finish
test_for_each(objs, [](auto &obj) { obj.thread.join(); });
}
int main(int argc, char *argv[])
{
return CommandLineTestRunner::RunAllTests(argc, argv);
}
<commit_msg>Fix semaphore test by introducing increased delays<commit_after>#include <ecl/thread/semaphore.hpp>
#include <array>
#include <thread>
#include <atomic>
#include <algorithm>
#include <functional>
#include <CppUTest/TestHarness.h>
#include <CppUTest/CommandLineTestRunner.h>
// TODO: remove ugly sleep-programming
// Error code helper
// TODO: move it to 'utils' headers and protect with check of
// current test state (enabled or disabled)
static SimpleString StringFrom(ecl::err err)
{
return SimpleString{ecl::err_to_str(err)};
}
// Helpers
template< class Container, class Func >
static void test_for_each(Container &cont, Func fn)
{
std::for_each(cont.begin(), cont.end(), fn);
}
static void test_delay(unsigned msecs = 1000)
{
std::this_thread::sleep_for(std::chrono::milliseconds(msecs));
}
constexpr auto threads_count = 10;
TEST_GROUP(semaphore)
{
void setup()
{
}
void teardown()
{
}
};
TEST(semaphore, signal_wait_no_hang)
{
// Should complete without a hang
ecl::semaphore sem;
sem.signal();
sem.wait();
}
TEST(semaphore, try_wait)
{
// Should complete without a hang
ecl::semaphore sem;
sem.signal();
auto rc = sem.try_wait();
CHECK_EQUAL(ecl::err::ok, rc);
rc = sem.try_wait();
CHECK_EQUAL(ecl::err::again, rc);
rc = sem.try_wait();
CHECK_EQUAL(ecl::err::again, rc);
// Signal same semaphore again
// to make sure counter is in valid state
sem.signal();
rc = sem.try_wait();
CHECK_EQUAL(ecl::err::ok, rc);
rc = sem.try_wait();
CHECK_EQUAL(ecl::err::again, rc);
}
TEST(semaphore, one_semaphore_few_threads)
{
// Preparation
// Counts how many threads completed
int counter = 0;
// Counts how many signals sent
int signalled = 0;
// Semaphore itself
ecl::semaphore semaphore;
auto single_thread = [&counter, &semaphore]() {
semaphore.wait();
counter++;
};
std::array< std::thread, threads_count > threads;
// Test itself
// Start threads
test_for_each(threads, [&single_thread](auto &thread) {
thread = std::thread(single_thread);
});
// Let them wait on semaphore
test_delay(20);
// Threads are started and should wait for orders
CHECK_EQUAL(0, counter);
// Unblock threads one by one
test_for_each(threads, [&](auto &thread) {
(void) thread; // We don't need this
semaphore.signal();
signalled++;
test_delay(100); // Let some thread finish its work
CHECK_EQUAL(signalled, counter); // Check that only one thread is finished
});
// Wait for threads to finish
test_for_each(threads, [](auto &thread) { thread.join(); });
}
TEST(semaphore, multiple_threads)
{
// Preparation
// Object associated with a thread
struct test_object
{
ecl::semaphore semaphore;
std::thread thread;
volatile bool flag;
};
std::array< test_object, threads_count > objs;
auto single_thread = [](auto *obj) {
obj->semaphore.wait();
obj->flag = true; // Rise a flag only if semaphore signaled
};
// Test itself
// Start threads
test_for_each(objs, [&single_thread](auto &obj) {
obj.flag = false;
obj.thread = std::thread(single_thread, &obj);
});
// Let them wait on semaphore
test_delay(100);
// Threads are started and should wait for orders
test_for_each(objs, [](auto &obj) { CHECK(!obj.flag); } );
// Unblock threads
test_for_each(objs, [](auto &obj) { obj.semaphore.signal(); });
// Let threads do the work
test_delay(100);
// Check that work is done
test_for_each(objs, [](auto &obj) { CHECK(obj.flag); });
// Wait for threads to finish
test_for_each(objs, [](auto &obj) { obj.thread.join(); });
}
int main(int argc, char *argv[])
{
return CommandLineTestRunner::RunAllTests(argc, argv);
}
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
*
* Quadra, an action puzzle game
* Copyright (C) 1998-2000 Ludus Design
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
const char *keynames[256] = {
"", "Escape", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "0", "-", "=", "Backspace", "Tab",
"Q", "W", "E", "R", "T", "Y", "U", "I",
"O", "P", "[", "]", "Enter", "Ctrl", "A", "S",
"D", "F", "G", "H", "J", "K", "L", ";",
"'", "`", "Left shift", "\\", "Z", "X", "C", "V",
"B", "N", "M", ",", ".", "/", "Right shift", "Pad *",
"Alt", "Space", "Caps lock", "F1", "F2", "F3", "F4", "F5",
"F6", "F7", "F8", "F9", "F10", "Num lock", "Scrl lock", "Pad 7",
"Pad 8", "Pad 9", "Pad -", "Pad 4", "Pad 5", "Pad 6", "Pad +",
"Pad 1", "Pad 2", "Pad 3", "Pad 0", "Pad .", "Print scrn", "",
"<", "F11", "F12", "", "", "", "", "", "", "","Pad Enter",
"Right Ctrl", "Pad /", "PrintScrn", "Alt Char", "Pause",
"Home", "Up", "Page Up", "Left", "Right", "End", "Down",
"Page Down", "Insert", "Delete",
"", "", "", "", "", "", "", "Pause",
"", "", "", "", "", "Win left", "Win right", "Win popup",
"", "Pause", "", "", "", "", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "Pad Enter", "2nd Ctrl", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "Pad /", "", "",
"2nd Alt", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "Home",
"Up", "Page up", "", "Left", "", "Right", "", "End",
"Down", "Page down", "Insert", "Del", "", "", "", "",
"", "", "", "Win left", "Win right", "Win popup", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "Macro",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", ""
};
#ifdef UGS_LINUX_SVGA
RCSID("$Id$")
#include "wraplib.h"
#include "video.h"
#include "input_svga.h"
static Svgalib* lib;
Input_Svgalib::Input_Svgalib() {
struct sigaction newsignals;
lib = getSvgalib();
tty_fd = 0;
pause = false;
clear_key();
mouse.dx = mouse.dy = mouse.dz = 0;
restore_mouse();
tcgetattr(0, &termattr);
israw = false;
reraw();
newsignals.sa_handler = Input_Svgalib::signal_handler;
sigemptyset(&newsignals.sa_mask);
newsignals.sa_flags = 0;
newsignals.sa_restorer = NULL;
sigaction(SIGUSR2, &newsignals, &oldsignals);
}
Input_Svgalib::~Input_Svgalib() {
sigaction(SIGUSR2, &oldsignals, NULL);
lib->mouse_close();
deraw();
tcsetattr(0, TCSANOW, &termattr);
}
void Input_Svgalib::clear_key() {
shift_key = 0;
quel_key = -1;
key_pending = 0;
for(int i=0; i<256; i++)
keys[i] = 0;
if(israw)
lib->keyboard_clearstate();
}
void Input_Svgalib::check() {
if(video) {
if(mouse_reinit) {
video->restore();
restore_mouse();
}
}
process_key();
process_mouse();
}
void Input_Svgalib::deraw() {
if(israw) {
lib->keyboard_close();
israw=false;
}
}
void Input_Svgalib::reraw() {
if(!israw) {
lib->keyboard_init();
lib->keyboard_seteventhandler(Input_Svgalib::keyboard_handler);
lib->keyboard_translatekeys(8 /* DONT_CATCH_CTRLC */);
israw=true;
}
}
void Input_Svgalib::process_key() {
int thekey;
if(israw)
lib->keyboard_update();
else {
fflush(stdin);
thekey = lib->vga_getkey();
if(thekey) {
switch (thekey) {
case 27:
quel_key = KEY_ESCAPE;
break;
case 13:
case 10:
quel_key = KEY_ENTER;
break;
default:
if(key_pending < MAXKEY) {
key_buf[key_pending].c = thekey;
key_buf[key_pending].special = false;
key_pending++;
}
}
}
}
}
void Input_Svgalib::process_mouse() {
mouse.dx = mouse.dy = mouse.dz = 0;
lib->mouse_update();
}
void Input_Svgalib::restore_mouse() {
mouse_reinit = false;
lib->mouse_seteventhandler((void*) Input_Svgalib::mouse_handler);
mouse.quel = -1;
for(int i=0; i<4; i++)
mouse.button[i] = RELEASED;
}
void Input_Svgalib::mouse_handler(int button,
int dx, int dy, int dz,
int drx, int dry, int drz) {
input->mouse.dx += dx;
input->mouse.dy += dy;
input->mouse.dz += dz;
if(input->mouse.button[0] == RELEASED && button & 4)
input->mouse.quel = 0;
if(input->mouse.button[1] == RELEASED && button & 2)
input->mouse.quel = 1;
if(input->mouse.button[2] == RELEASED && button & 1)
input->mouse.quel = 2;
input->mouse.button[0] = (Byte) ((button & 4) ? PRESSED:RELEASED);
input->mouse.button[1] = (Byte) ((button & 2) ? PRESSED:RELEASED);
input->mouse.button[2] = (Byte) ((button & 1) ? PRESSED:RELEASED);
}
void Input_Svgalib::keyboard_handler(int scancode, int press) {
if(press) {
input->keys[scancode] |= PRESSED;
switch(scancode) {
case KEY_RSHIFT:
case KEY_LSHIFT:
input->shift_key |= SHIFT;
break;
case KEY_RALT:
case KEY_LALT:
input->shift_key |= ALT;
break;
case KEY_RCTRL:
case KEY_LCTRL:
input->shift_key |= CONTROL;
break;
case 101:
case 119:
input->pause = true;
break;
default:
input->quel_key = scancode;
}
} else {
input->keys[scancode] = RELEASED;
switch(scancode) {
case KEY_RSHIFT:
case KEY_LSHIFT:
input->shift_key &= ~SHIFT;
break;
case KEY_RALT:
case KEY_LALT:
input->shift_key &= ~ALT;
break;
case KEY_RCTRL:
case KEY_LCTRL:
input->shift_key &= ~CONTROL;
break;
}
}
}
void Input_Svgalib::signal_handler(int signal) {
/* indique que la souris devra etre re-initer au prochain refresh */
((Input_Svgalib*)input)->mouse_reinit = true;
((Input_Svgalib*)input)->oldsignals.sa_handler(signal);
}
#endif /* UGS_LINUX_SVGA */
<commit_msg>Using a macro before including the file that uses it is not good, fixed it.<commit_after>/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-
*
* Quadra, an action puzzle game
* Copyright (C) 1998-2000 Ludus Design
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
const char *keynames[256] = {
"", "Escape", "1", "2", "3", "4", "5", "6",
"7", "8", "9", "0", "-", "=", "Backspace", "Tab",
"Q", "W", "E", "R", "T", "Y", "U", "I",
"O", "P", "[", "]", "Enter", "Ctrl", "A", "S",
"D", "F", "G", "H", "J", "K", "L", ";",
"'", "`", "Left shift", "\\", "Z", "X", "C", "V",
"B", "N", "M", ",", ".", "/", "Right shift", "Pad *",
"Alt", "Space", "Caps lock", "F1", "F2", "F3", "F4", "F5",
"F6", "F7", "F8", "F9", "F10", "Num lock", "Scrl lock", "Pad 7",
"Pad 8", "Pad 9", "Pad -", "Pad 4", "Pad 5", "Pad 6", "Pad +",
"Pad 1", "Pad 2", "Pad 3", "Pad 0", "Pad .", "Print scrn", "",
"<", "F11", "F12", "", "", "", "", "", "", "","Pad Enter",
"Right Ctrl", "Pad /", "PrintScrn", "Alt Char", "Pause",
"Home", "Up", "Page Up", "Left", "Right", "End", "Down",
"Page Down", "Insert", "Delete",
"", "", "", "", "", "", "", "Pause",
"", "", "", "", "", "Win left", "Win right", "Win popup",
"", "Pause", "", "", "", "", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "Pad Enter", "2nd Ctrl", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "Pad /", "", "",
"2nd Alt", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "Home",
"Up", "Page up", "", "Left", "", "Right", "", "End",
"Down", "Page down", "Insert", "Del", "", "", "", "",
"", "", "", "Win left", "Win right", "Win popup", "", "",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", "Macro",
"", "", "", "", "", "", "", "",
"", "", "", "", "", "", "", ""
};
#ifdef UGS_LINUX_SVGA
#include "wraplib.h"
#include "video.h"
#include "input_svga.h"
RCSID("$Id$")
static Svgalib* lib;
Input_Svgalib::Input_Svgalib() {
struct sigaction newsignals;
lib = getSvgalib();
tty_fd = 0;
pause = false;
clear_key();
mouse.dx = mouse.dy = mouse.dz = 0;
restore_mouse();
tcgetattr(0, &termattr);
israw = false;
reraw();
newsignals.sa_handler = Input_Svgalib::signal_handler;
sigemptyset(&newsignals.sa_mask);
newsignals.sa_flags = 0;
newsignals.sa_restorer = NULL;
sigaction(SIGUSR2, &newsignals, &oldsignals);
}
Input_Svgalib::~Input_Svgalib() {
sigaction(SIGUSR2, &oldsignals, NULL);
lib->mouse_close();
deraw();
tcsetattr(0, TCSANOW, &termattr);
}
void Input_Svgalib::clear_key() {
shift_key = 0;
quel_key = -1;
key_pending = 0;
for(int i=0; i<256; i++)
keys[i] = 0;
if(israw)
lib->keyboard_clearstate();
}
void Input_Svgalib::check() {
if(video) {
if(mouse_reinit) {
video->restore();
restore_mouse();
}
}
process_key();
process_mouse();
}
void Input_Svgalib::deraw() {
if(israw) {
lib->keyboard_close();
israw=false;
}
}
void Input_Svgalib::reraw() {
if(!israw) {
lib->keyboard_init();
lib->keyboard_seteventhandler(Input_Svgalib::keyboard_handler);
lib->keyboard_translatekeys(8 /* DONT_CATCH_CTRLC */);
israw=true;
}
}
void Input_Svgalib::process_key() {
int thekey;
if(israw)
lib->keyboard_update();
else {
fflush(stdin);
thekey = lib->vga_getkey();
if(thekey) {
switch (thekey) {
case 27:
quel_key = KEY_ESCAPE;
break;
case 13:
case 10:
quel_key = KEY_ENTER;
break;
default:
if(key_pending < MAXKEY) {
key_buf[key_pending].c = thekey;
key_buf[key_pending].special = false;
key_pending++;
}
}
}
}
}
void Input_Svgalib::process_mouse() {
mouse.dx = mouse.dy = mouse.dz = 0;
lib->mouse_update();
}
void Input_Svgalib::restore_mouse() {
mouse_reinit = false;
lib->mouse_seteventhandler((void*) Input_Svgalib::mouse_handler);
mouse.quel = -1;
for(int i=0; i<4; i++)
mouse.button[i] = RELEASED;
}
void Input_Svgalib::mouse_handler(int button,
int dx, int dy, int dz,
int drx, int dry, int drz) {
input->mouse.dx += dx;
input->mouse.dy += dy;
input->mouse.dz += dz;
if(input->mouse.button[0] == RELEASED && button & 4)
input->mouse.quel = 0;
if(input->mouse.button[1] == RELEASED && button & 2)
input->mouse.quel = 1;
if(input->mouse.button[2] == RELEASED && button & 1)
input->mouse.quel = 2;
input->mouse.button[0] = (Byte) ((button & 4) ? PRESSED:RELEASED);
input->mouse.button[1] = (Byte) ((button & 2) ? PRESSED:RELEASED);
input->mouse.button[2] = (Byte) ((button & 1) ? PRESSED:RELEASED);
}
void Input_Svgalib::keyboard_handler(int scancode, int press) {
if(press) {
input->keys[scancode] |= PRESSED;
switch(scancode) {
case KEY_RSHIFT:
case KEY_LSHIFT:
input->shift_key |= SHIFT;
break;
case KEY_RALT:
case KEY_LALT:
input->shift_key |= ALT;
break;
case KEY_RCTRL:
case KEY_LCTRL:
input->shift_key |= CONTROL;
break;
case 101:
case 119:
input->pause = true;
break;
default:
input->quel_key = scancode;
}
} else {
input->keys[scancode] = RELEASED;
switch(scancode) {
case KEY_RSHIFT:
case KEY_LSHIFT:
input->shift_key &= ~SHIFT;
break;
case KEY_RALT:
case KEY_LALT:
input->shift_key &= ~ALT;
break;
case KEY_RCTRL:
case KEY_LCTRL:
input->shift_key &= ~CONTROL;
break;
}
}
}
void Input_Svgalib::signal_handler(int signal) {
/* indique que la souris devra etre re-initer au prochain refresh */
((Input_Svgalib*)input)->mouse_reinit = true;
((Input_Svgalib*)input)->oldsignals.sa_handler(signal);
}
#endif /* UGS_LINUX_SVGA */
<|endoftext|>
|
<commit_before>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Prague/Sys/Tracer.hh>
#include <Prague/Sys/SHM.hh>
#include <Fresco/config.hh>
#include <Fresco/Transform.hh>
#include <Fresco/DrawTraversal.hh>
#include <Fresco/DrawingKit.hh>
#include <Berlin/Logger.hh>
#include "VisualImpl.hh"
#include <sys/ipc.h>
#include <strstream.h>
using namespace Prague;
using namespace Fresco;
GGIDrawableFactory *VisualImpl::_factory = 0;
VisualImpl::VisualImpl(PixelCoord w, PixelCoord h)
: ControllerImpl(false), _width(w), _height(h)
{
Trace trace("VisualImpl::VisualImpl");
Console *console = Console::instance();
if (!_factory) _factory = console->get_extension<GGIDrawableFactory>("GGIDrawableFactory");
Fresco::Drawable::PixelFormat format = Console::instance()->drawable()->pixel_format();
/*
* the drawable plus some memory for the event queue
*/
size_t size = w * h * format.size + 64*1024;
_shm = SHM::allocate(size);
std::ostrstream oss;
_ggi = _factory->create_drawable(_shm, w, h, 3);
_drawable = console->activate_drawable(_ggi);
ggi_mode mode = _ggi->mode();
char buffer[256];
ggiSPrintMode(buffer, &mode);
_mode = buffer;
}
VisualImpl::~VisualImpl()
{
Trace trace("VisualImpl::~VisualImpl");
SHM::deallocate(_shm);
}
char *VisualImpl::name()
{
std::cout << _ggi->name() << std::endl;
return CORBA::string_dup(_ggi->name().c_str());
}
char *VisualImpl::mode()
{
return CORBA::string_dup(_mode.c_str());
}
void VisualImpl::request(Fresco::Graphic::Requisition &requisition)
{
Trace trace("VisualImpl::request");
requisition.x.defined = true;
requisition.x.natural = requisition.x.maximum = requisition.x.minimum = _width * 10;// / _drawable->resolution(xaxis);
requisition.x.align = 0.;
requisition.y.defined = true;
requisition.y.natural = requisition.y.maximum = requisition.y.minimum = _height * 10;// / _drawable->resolution(yaxis);
requisition.y.align = 0.;
requisition.z.defined = false;
}
void VisualImpl::draw(DrawTraversal_ptr traversal)
{
Trace trace("VisualImpl::draw");
DrawingKit_var drawing = traversal->drawing();
drawing->copy_drawable(_drawable, 0, 0, _width, _height);
}
void VisualImpl::extension(const Allocation::Info &info, Region_ptr region)
{
Trace trace("VisualImpl::extension");
GraphicImpl::extension(info, region);
}
CORBA::Boolean VisualImpl::handle_positional(PickTraversal_ptr traversal, const Fresco::Input::Event &event)
{
Trace trace("VisualImpl::handle_positional");
ControllerImpl::handle_positional(traversal, event);
}
CORBA::Boolean VisualImpl::handle_non_positional(const Fresco::Input::Event &event)
{
Trace trace("VisualImpl::handle_non_positional");
std::cout << "VisualImpl::handle_non_positional" << std::endl;
/*
* FIXME !: we assume a lot about the (berlin) event layout here. Make that more flexible...
*/
Input::Toggle toggle = event[0].attr.selection();
ggi_event ggi;
// giiEventSend will discard events without this field filled in
// I'm not sure if the actual value should depend on the source of the
// event, or what (there's ggi.any.source for that, but that's filled in
// as being a fake event by EventSend; this seems to be about which of the
// input queues are handed the event.
ggi.any.target = GII_EV_TARGET_ALL;
if (toggle.actuation == Input::Toggle::press) ggi.any.type = evKeyPress;
else if (toggle.actuation == Input::Toggle::hold) ggi.any.type = evKeyRepeat;
else if (toggle.actuation == Input::Toggle::release) ggi.any.type = evKeyRelease; // not generated actually
ggi.key.sym = toggle.number;
/*
* FIXME !: the ggi_event structure is quite incomplete here. The real structure looks so:
typedef struct {
COMMON_DATA;
uint32 modifiers; current modifiers in effect
uint32 sym; meaning of key
uint32 label; label on key
uint32 button; button number
} gii_key_event;
* and we need to figure out a way to fill the remaining members, i.e. reconstruct them from the sym
* given that this is the only information we conserve in the berlin key event...
*/
forward_event(ggi);
}
void VisualImpl::forward_event(const ggi_event &event)
{
Trace trace("VisualImpl::forward_event");
// giiEventSend(ggiJoinInputs(_ggi->visual(), 0), const_cast<ggi_event *>(&event));
ggiEventSend(_ggi->visual(), const_cast<ggi_event *>(&event));
}
<commit_msg>Removed unused strstream<commit_after>/*$Id$
*
* This source file is a part of the Fresco Project.
* Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org>
* http://www.fresco.org
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
* MA 02139, USA.
*/
#include <Prague/Sys/Tracer.hh>
#include <Prague/Sys/SHM.hh>
#include <Fresco/config.hh>
#include <Fresco/Transform.hh>
#include <Fresco/DrawTraversal.hh>
#include <Fresco/DrawingKit.hh>
#include <Berlin/Logger.hh>
#include "VisualImpl.hh"
#include <sys/ipc.h>
using namespace Prague;
using namespace Fresco;
GGIDrawableFactory *VisualImpl::_factory = 0;
VisualImpl::VisualImpl(PixelCoord w, PixelCoord h)
: ControllerImpl(false), _width(w), _height(h)
{
Trace trace("VisualImpl::VisualImpl");
Console *console = Console::instance();
if (!_factory) _factory = console->get_extension<GGIDrawableFactory>("GGIDrawableFactory");
Fresco::Drawable::PixelFormat format = Console::instance()->drawable()->pixel_format();
/*
* the drawable plus some memory for the event queue
*/
size_t size = w * h * format.size + 64*1024;
_shm = SHM::allocate(size);
_ggi = _factory->create_drawable(_shm, w, h, 3);
_drawable = console->activate_drawable(_ggi);
ggi_mode mode = _ggi->mode();
char buffer[256];
ggiSPrintMode(buffer, &mode);
_mode = buffer;
}
VisualImpl::~VisualImpl()
{
Trace trace("VisualImpl::~VisualImpl");
SHM::deallocate(_shm);
}
char *VisualImpl::name()
{
std::cout << _ggi->name() << std::endl;
return CORBA::string_dup(_ggi->name().c_str());
}
char *VisualImpl::mode()
{
return CORBA::string_dup(_mode.c_str());
}
void VisualImpl::request(Fresco::Graphic::Requisition &requisition)
{
Trace trace("VisualImpl::request");
requisition.x.defined = true;
requisition.x.natural = requisition.x.maximum = requisition.x.minimum = _width * 10;// / _drawable->resolution(xaxis);
requisition.x.align = 0.;
requisition.y.defined = true;
requisition.y.natural = requisition.y.maximum = requisition.y.minimum = _height * 10;// / _drawable->resolution(yaxis);
requisition.y.align = 0.;
requisition.z.defined = false;
}
void VisualImpl::draw(DrawTraversal_ptr traversal)
{
Trace trace("VisualImpl::draw");
DrawingKit_var drawing = traversal->drawing();
drawing->copy_drawable(_drawable, 0, 0, _width, _height);
}
void VisualImpl::extension(const Allocation::Info &info, Region_ptr region)
{
Trace trace("VisualImpl::extension");
GraphicImpl::extension(info, region);
}
CORBA::Boolean VisualImpl::handle_positional(PickTraversal_ptr traversal, const Fresco::Input::Event &event)
{
Trace trace("VisualImpl::handle_positional");
ControllerImpl::handle_positional(traversal, event);
}
CORBA::Boolean VisualImpl::handle_non_positional(const Fresco::Input::Event &event)
{
Trace trace("VisualImpl::handle_non_positional");
std::cout << "VisualImpl::handle_non_positional" << std::endl;
/*
* FIXME !: we assume a lot about the (berlin) event layout here. Make that more flexible...
*/
Input::Toggle toggle = event[0].attr.selection();
ggi_event ggi;
// giiEventSend will discard events without this field filled in
// I'm not sure if the actual value should depend on the source of the
// event, or what (there's ggi.any.source for that, but that's filled in
// as being a fake event by EventSend; this seems to be about which of the
// input queues are handed the event.
ggi.any.target = GII_EV_TARGET_ALL;
if (toggle.actuation == Input::Toggle::press) ggi.any.type = evKeyPress;
else if (toggle.actuation == Input::Toggle::hold) ggi.any.type = evKeyRepeat;
else if (toggle.actuation == Input::Toggle::release) ggi.any.type = evKeyRelease; // not generated actually
ggi.key.sym = toggle.number;
/*
* FIXME !: the ggi_event structure is quite incomplete here. The real structure looks so:
typedef struct {
COMMON_DATA;
uint32 modifiers; current modifiers in effect
uint32 sym; meaning of key
uint32 label; label on key
uint32 button; button number
} gii_key_event;
* and we need to figure out a way to fill the remaining members, i.e. reconstruct them from the sym
* given that this is the only information we conserve in the berlin key event...
*/
forward_event(ggi);
}
void VisualImpl::forward_event(const ggi_event &event)
{
Trace trace("VisualImpl::forward_event");
// giiEventSend(ggiJoinInputs(_ggi->visual(), 0), const_cast<ggi_event *>(&event));
ggiEventSend(_ggi->visual(), const_cast<ggi_event *>(&event));
}
<|endoftext|>
|
<commit_before>#ifndef _VKREF_HPP
#define _VKREF_HPP
/*-------------------------------------------------------------------------
* Vulkan CTS Framework
* --------------------
*
* Copyright (c) 2015 Google Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and/or associated documentation files (the
* "Materials"), to deal in the Materials without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Materials, and to
* permit persons to whom the Materials are furnished to do so, subject to
* the following conditions:
*
* The above copyright notice(s) and this permission notice shall be
* included in all copies or substantial portions of the Materials.
*
* The Materials are Confidential Information as defined by the
* Khronos Membership Agreement until designated non-confidential by
* Khronos, at which point this condition clause shall be removed.
*
* THE MATERIALS ARE 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
* MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*
*//*!
* \file
* \brief Vulkan object reference holder.
*//*--------------------------------------------------------------------*/
#include "vkDefs.hpp"
#include "vkStrUtil.hpp"
#include "deUniquePtr.hpp"
#include "deMeta.hpp"
#include <algorithm>
namespace vk
{
namespace refdetails
{
using std::swap;
template<typename T>
struct Checked
{
explicit inline Checked (T object_) : object(object_) {}
T object;
};
//! Check that object is not null
template<typename T>
inline Checked<T> check (T object)
{
if (!object)
throw tcu::TestError("Object check() failed", (std::string(getTypeName<T>()) + " = 0").c_str(), __FILE__, __LINE__);
return Checked<T>(object);
}
//! Declare object as checked earlier
template<typename T>
inline Checked<T> notNull (T object)
{
if (!object)
throw tcu::InternalError("Null object was given to notNull()", (std::string(getTypeName<T>()) + " = 0").c_str(), __FILE__, __LINE__);
return Checked<T>(object);
}
//! Allow null object
template<typename T>
inline Checked<T> allowNull (T object)
{
return Checked<T>(object);
}
template<typename T>
class Deleter
{
public:
Deleter (const DeviceInterface& deviceIface, VkDevice device)
: m_deviceIface (&deviceIface)
, m_device (device)
{}
Deleter (void)
: m_deviceIface (DE_NULL)
, m_device (DE_NULL)
{}
void operator() (T obj) const;
private:
const DeviceInterface* m_deviceIface;
VkDevice m_device;
};
template<>
class Deleter<VkInstance>
{
public:
Deleter (const PlatformInterface& platformIface, VkInstance instance)
: m_destroyInstance((DestroyInstanceFunc)platformIface.getInstanceProcAddr(instance, "vkDestroyInstance"))
{}
Deleter (void)
: m_destroyInstance((DestroyInstanceFunc)DE_NULL)
{}
void operator() (VkInstance obj) const { DE_TEST_ASSERT(m_destroyInstance(obj) == VK_SUCCESS); }
private:
DestroyInstanceFunc m_destroyInstance;
};
template<>
class Deleter<VkDevice>
{
public:
Deleter (const InstanceInterface& instanceIface, VkDevice device)
: m_destroyDevice((DestroyDeviceFunc)instanceIface.getDeviceProcAddr(device, "vkDestroyDevice"))
{}
Deleter (void)
: m_destroyDevice((DestroyDeviceFunc)DE_NULL)
{}
void operator() (VkDevice obj) const { DE_TEST_ASSERT(m_destroyDevice(obj) == VK_SUCCESS); }
private:
DestroyDeviceFunc m_destroyDevice;
};
template<typename T>
struct RefData
{
RefData (T object_, Deleter<T> deleter_)
: object (object_)
, deleter (deleter_)
{}
RefData (void)
: object (0)
{}
T object;
Deleter<T> deleter;
};
template<typename T>
class RefBase
{
public:
~RefBase (void);
inline const T& get (void) const throw() { return m_data.object; }
inline const T& operator* (void) const throw() { return get(); }
inline operator bool (void) const throw() { return !!get(); }
protected:
RefBase (RefData<T> data) : m_data(data) {}
void reset (void); //!< Release previous object, set to null.
RefData<T> disown (void) throw(); //!< Disown and return object (ownership transferred to caller).
void assign (RefData<T> data); //!< Set new pointer, release previous pointer.
private:
RefData<T> m_data;
};
template<typename T>
inline RefBase<T>::~RefBase (void)
{
this->reset();
}
template<typename T>
inline void RefBase<T>::reset (void)
{
if (!!m_data.object)
m_data.deleter(m_data.object);
m_data = RefData<T>();
}
template<typename T>
inline RefData<T> RefBase<T>::disown (void) throw()
{
RefData<T> tmp;
swap(m_data, tmp);
return tmp;
}
template<typename T>
inline void RefBase<T>::assign (RefData<T> data)
{
this->reset();
m_data = data;
}
/*--------------------------------------------------------------------*//*!
* \brief Movable Vulkan object reference.
*
* Similar to de::MovePtr.
*//*--------------------------------------------------------------------*/
template<typename T>
class Move : public RefBase<T>
{
public:
template<typename U>
Move (Checked<U> object, Deleter<U> deleter)
: RefBase<T>(RefData<T>(object.object, deleter))
{}
Move (RefData<T> data)
: RefBase<T>(data)
{}
Move (void)
: RefBase<T>(RefData<T>())
{}
Move<T>& operator= (Move<T>& other);
Move<T>& operator= (RefData<T> data);
operator RefData<T> (void) { return this->disown(); }
};
template<typename T>
inline Move<T>& Move<T>::operator= (Move<T>& other)
{
if (this != &other)
this->assign(other.disown());
return *this;
}
template<typename T>
inline Move<T>& Move<T>::operator= (RefData<T> data)
{
this->assign(data);
return *this;
}
/*--------------------------------------------------------------------*//*!
* \brief Unique Vulkan object reference.
*
* Similar to de::UniquePtr.
*//*--------------------------------------------------------------------*/
template<typename T>
class Unique : public RefBase<T>
{
public:
template<typename U>
Unique (Checked<U> object, Deleter<U> deleter)
: RefBase<T>(RefData<T>(object.object, deleter))
{}
Unique (RefData<T> data)
: RefBase<T>(data)
{}
};
} // refdetails
using refdetails::Move;
using refdetails::Unique;
using refdetails::Deleter;
using refdetails::check;
using refdetails::notNull;
using refdetails::allowNull;
#include "vkRefUtil.inl"
Move<VkPipeline> createGraphicsPipeline (const DeviceInterface& vk, VkDevice device, VkPipelineCache pipelineCache, const VkGraphicsPipelineCreateInfo* pCreateInfo);
Move<VkPipeline> createComputePipeline (const DeviceInterface& vk, VkDevice device, VkPipelineCache pipelineCache, const VkComputePipelineCreateInfo* pCreateInfo);
} // vk
#endif // _VKREF_HPP
<commit_msg>Fixes to vk::Move<> and vk::Unique<><commit_after>#ifndef _VKREF_HPP
#define _VKREF_HPP
/*-------------------------------------------------------------------------
* Vulkan CTS Framework
* --------------------
*
* Copyright (c) 2015 Google Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and/or associated documentation files (the
* "Materials"), to deal in the Materials without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Materials, and to
* permit persons to whom the Materials are furnished to do so, subject to
* the following conditions:
*
* The above copyright notice(s) and this permission notice shall be
* included in all copies or substantial portions of the Materials.
*
* The Materials are Confidential Information as defined by the
* Khronos Membership Agreement until designated non-confidential by
* Khronos, at which point this condition clause shall be removed.
*
* THE MATERIALS ARE 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
* MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
*
*//*!
* \file
* \brief Vulkan object reference holder.
*//*--------------------------------------------------------------------*/
#include "vkDefs.hpp"
#include "vkStrUtil.hpp"
#include "deUniquePtr.hpp"
#include "deMeta.hpp"
#include <algorithm>
namespace vk
{
namespace refdetails
{
using std::swap;
template<typename T>
struct Checked
{
explicit inline Checked (T object_) : object(object_) {}
T object;
};
//! Check that object is not null
template<typename T>
inline Checked<T> check (T object)
{
if (!object)
throw tcu::TestError("Object check() failed", (std::string(getTypeName<T>()) + " = 0").c_str(), __FILE__, __LINE__);
return Checked<T>(object);
}
//! Declare object as checked earlier
template<typename T>
inline Checked<T> notNull (T object)
{
if (!object)
throw tcu::InternalError("Null object was given to notNull()", (std::string(getTypeName<T>()) + " = 0").c_str(), __FILE__, __LINE__);
return Checked<T>(object);
}
//! Allow null object
template<typename T>
inline Checked<T> allowNull (T object)
{
return Checked<T>(object);
}
template<typename T>
class Deleter
{
public:
Deleter (const DeviceInterface& deviceIface, VkDevice device)
: m_deviceIface (&deviceIface)
, m_device (device)
{}
Deleter (void)
: m_deviceIface (DE_NULL)
, m_device (DE_NULL)
{}
void operator() (T obj) const;
private:
const DeviceInterface* m_deviceIface;
VkDevice m_device;
};
template<>
class Deleter<VkInstance>
{
public:
Deleter (const PlatformInterface& platformIface, VkInstance instance)
: m_destroyInstance((DestroyInstanceFunc)platformIface.getInstanceProcAddr(instance, "vkDestroyInstance"))
{}
Deleter (void)
: m_destroyInstance((DestroyInstanceFunc)DE_NULL)
{}
void operator() (VkInstance obj) const { DE_TEST_ASSERT(m_destroyInstance(obj) == VK_SUCCESS); }
private:
DestroyInstanceFunc m_destroyInstance;
};
template<>
class Deleter<VkDevice>
{
public:
Deleter (const InstanceInterface& instanceIface, VkDevice device)
: m_destroyDevice((DestroyDeviceFunc)instanceIface.getDeviceProcAddr(device, "vkDestroyDevice"))
{}
Deleter (void)
: m_destroyDevice((DestroyDeviceFunc)DE_NULL)
{}
void operator() (VkDevice obj) const { DE_TEST_ASSERT(m_destroyDevice(obj) == VK_SUCCESS); }
private:
DestroyDeviceFunc m_destroyDevice;
};
template<typename T>
struct RefData
{
RefData (T object_, Deleter<T> deleter_)
: object (object_)
, deleter (deleter_)
{}
RefData (void)
: object (0)
{}
T object;
Deleter<T> deleter;
};
template<typename T>
class RefBase
{
public:
~RefBase (void);
inline const T& get (void) const throw() { return m_data.object; }
inline const T& operator* (void) const throw() { return get(); }
inline operator bool (void) const throw() { return !!get(); }
protected:
RefBase (RefData<T> data) : m_data(data) {}
void reset (void); //!< Release previous object, set to null.
RefData<T> disown (void) throw(); //!< Disown and return object (ownership transferred to caller).
void assign (RefData<T> data); //!< Set new pointer, release previous pointer.
private:
RefData<T> m_data;
};
template<typename T>
inline RefBase<T>::~RefBase (void)
{
this->reset();
}
template<typename T>
inline void RefBase<T>::reset (void)
{
if (!!m_data.object)
m_data.deleter(m_data.object);
m_data = RefData<T>();
}
template<typename T>
inline RefData<T> RefBase<T>::disown (void) throw()
{
RefData<T> tmp;
swap(m_data, tmp);
return tmp;
}
template<typename T>
inline void RefBase<T>::assign (RefData<T> data)
{
this->reset();
m_data = data;
}
/*--------------------------------------------------------------------*//*!
* \brief Movable Vulkan object reference.
*
* Similar to de::MovePtr.
*//*--------------------------------------------------------------------*/
template<typename T>
class Move : public RefBase<T>
{
public:
template<typename U>
Move (Checked<U> object, Deleter<U> deleter)
: RefBase<T>(RefData<T>(object.object, deleter))
{}
Move (RefData<T> data)
: RefBase<T>(data)
{}
Move (Move<T>& other)
: RefBase<T>(other.disown())
{}
Move (void)
: RefBase<T>(RefData<T>())
{}
Move<T>& operator= (Move<T>& other);
Move<T>& operator= (RefData<T> data);
operator RefData<T> (void) { return this->disown(); }
};
template<typename T>
inline Move<T>& Move<T>::operator= (Move<T>& other)
{
if (this != &other)
this->assign(other.disown());
return *this;
}
template<typename T>
inline Move<T>& Move<T>::operator= (RefData<T> data)
{
this->assign(data);
return *this;
}
/*--------------------------------------------------------------------*//*!
* \brief Unique Vulkan object reference.
*
* Similar to de::UniquePtr.
*//*--------------------------------------------------------------------*/
template<typename T>
class Unique : public RefBase<T>
{
public:
template<typename U>
Unique (Checked<U> object, Deleter<U> deleter)
: RefBase<T>(RefData<T>(object.object, deleter))
{}
Unique (RefData<T> data)
: RefBase<T>(data)
{}
private:
Unique (const Unique<T>&);
Unique<T>& operator= (const Unique<T>&);
};
} // refdetails
using refdetails::Move;
using refdetails::Unique;
using refdetails::Deleter;
using refdetails::check;
using refdetails::notNull;
using refdetails::allowNull;
#include "vkRefUtil.inl"
Move<VkPipeline> createGraphicsPipeline (const DeviceInterface& vk, VkDevice device, VkPipelineCache pipelineCache, const VkGraphicsPipelineCreateInfo* pCreateInfo);
Move<VkPipeline> createComputePipeline (const DeviceInterface& vk, VkDevice device, VkPipelineCache pipelineCache, const VkComputePipelineCreateInfo* pCreateInfo);
} // vk
#endif // _VKREF_HPP
<|endoftext|>
|
<commit_before>#include <cthun-agent/agent.hpp>
#include <cthun-agent/errors.hpp>
#include <cthun-agent/uuid.hpp>
#include <cthun-agent/string_utils.hpp>
#include <cthun-agent/external_module.hpp>
#include <cthun-agent/modules/echo.hpp>
#include <cthun-agent/modules/inventory.hpp>
#include <cthun-agent/modules/ping.hpp>
#include <cthun-agent/modules/status.hpp>
#include <cthun-client/connector/errors.hpp>
#include <cthun-client/data_container/data_container.hpp>
#include <cthun-client/validator/validator.hpp> // Validator
#define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.cthun_agent.agent"
#include <leatherman/logging/logging.hpp>
#include <vector>
#include <memory>
namespace CthunAgent {
namespace fs = boost::filesystem;
//
// Constants
//
static const std::string AGENT_CLIENT_TYPE { "agent" };
static const std::string CTHUN_REQUEST_SCHEMA_NAME { "http://puppetlabs.com/cnc_request" };
static const std::string CTHUN_RESPONSE_SCHEMA_NAME { "http://puppetlabs.com/cnc_response" };
static const int DEFAULT_MSG_TIMEOUT_SEC { 10 };
//
// Agent
//
Agent::Agent(const std::string& modules_dir,
const std::string& server_url,
const std::string& ca,
const std::string& crt,
const std::string& key)
try
: connector_ { server_url, AGENT_CLIENT_TYPE, ca, crt, key },
modules_ {} {
// NB: certificate paths are validated by HW
loadInternalModules();
if (!modules_dir.empty()) {
loadExternalModulesFrom(modules_dir);
} else {
LOG_INFO("The modules directory was not provided; no external module "
"will be loaded");
}
logLoadedModules();
} catch (CthunClient::connection_config_error& e) {
throw fatal_error { std::string("failed to configure the agent: ")
+ e.what() };
}
void Agent::start() {
connector_.registerMessageCallback(
getCncRequestSchema(),
[this](const CthunClient::ParsedChunks& parsed_chunks) {
cncRequestCallback(parsed_chunks);
});
try {
connector_.connect();
} catch (CthunClient::connection_config_error& e) {
LOG_ERROR("Failed to configure the underlying communications layer: %1%",
e.what());
throw fatal_error { "failed to configure the underlying communications"
"layer" };
} catch (CthunClient::connection_fatal_error& e) {
LOG_ERROR("Failed to connect: %1%", e.what());
throw fatal_error { "failed to connect" };
}
// The agent is now connected and the request handlers are set;
// we can now call the monitoring method that will block this
// thread of execution.
// Note that, in case the underlying connection drops, the
// connector will keep trying to re-establish it indefinitely
// (the max_connect_attempts is 0 by default).
try {
connector_.monitorConnection();
} catch (CthunClient::connection_fatal_error) {
throw fatal_error { "failed to reconnect" };
}
// TODO(ale): wait for the associate session response, once the
// associated state is exposed by Connector
}
//
// Agent - private interface
//
void Agent::loadInternalModules() {
modules_["echo"] = std::shared_ptr<Module>(new Modules::Echo);
modules_["inventory"] = std::shared_ptr<Module>(new Modules::Inventory);
modules_["ping"] = std::shared_ptr<Module>(new Modules::Ping);
modules_["status"] = std::shared_ptr<Module>(new Modules::Status);
}
void Agent::loadExternalModulesFrom(fs::path dir_path) {
LOG_INFO("Loading external modules from %1%", dir_path.string());
if (fs::is_directory(dir_path)) {
fs::directory_iterator end;
for (auto f = fs::directory_iterator(dir_path); f != end; ++f) {
if (!fs::is_directory(f->status())) {
auto f_p = f->path().string();
try {
ExternalModule* e_m = new ExternalModule(f_p);
modules_[e_m->module_name] = std::shared_ptr<Module>(e_m);
} catch (module_error& e) {
LOG_ERROR("Failed to load %1%; %2%", f_p, e.what());
} catch (std::exception& e) {
LOG_ERROR("Unexpected error when loading %1%; %2%",
f_p, e.what());
} catch (...) {
LOG_ERROR("Unexpected error when loading %1%", f_p);
}
}
}
} else {
LOG_WARNING("Failed to locate the modules directory; external modules "
"will not be loaded");
}
}
void Agent::logLoadedModules() const {
for (auto& module : modules_) {
std::string txt { "found no action" };
std::string actions_list { "" };
for (auto& action : module.second->actions) {
if (actions_list.empty()) {
txt = "action";
actions_list += ": ";
} else {
actions_list += ", ";
}
actions_list += action.first;
}
auto txt_suffix = StringUtils::plural(module.second->actions.size());
LOG_INFO("Loaded '%1%' module - %2%%3%%4%",
module.first, txt, txt_suffix, actions_list);
}
}
CthunClient::Schema Agent::getCncRequestSchema() const {
CthunClient::Schema schema { CTHUN_REQUEST_SCHEMA_NAME,
CthunClient::ContentType::Json };
using T_C = CthunClient::TypeConstraint;
schema.addConstraint("module", T_C::String, true);
schema.addConstraint("action", T_C::String, true);
// TODO(ale): evaluate changing params; ambiguous
schema.addConstraint("params", T_C::Object, false);
return schema;
}
void Agent::cncRequestCallback(const CthunClient::ParsedChunks& parsed_chunks) {
auto request_id = parsed_chunks.envelope.get<std::string>("id");
auto requester_endpoint = parsed_chunks.envelope.get<std::string>("sender");
LOG_INFO("Received message %1% from %2%", request_id, requester_endpoint);
LOG_DEBUG("Message %1%:\n%2%", request_id, parsed_chunks.toString());
try {
// Inspect envelope
if (!parsed_chunks.has_data) {
throw request_validation_error { "no data" };
}
if (parsed_chunks.data_type != CthunClient::ContentType::Json) {
throw request_validation_error { "data is not in JSON format" };
}
// Inspect data
auto module_name = parsed_chunks.data.get<std::string>("module");
auto action_name = parsed_chunks.data.get<std::string>("action");
if (modules_.find(module_name) == modules_.end()) {
throw request_validation_error { "unknown module: " + module_name };
}
// Perform the requested action
auto module_ptr = modules_.at(module_name);
auto data_json = module_ptr->performRequest(action_name, parsed_chunks);
// Wrap debug data
std::vector<CthunClient::DataContainer> debug {};
for (auto& debug_entry : parsed_chunks.debug) {
debug.push_back(debug_entry);
}
try {
connector_.send(std::vector<std::string> { requester_endpoint },
CTHUN_RESPONSE_SCHEMA_NAME,
DEFAULT_MSG_TIMEOUT_SEC,
data_json,
debug);
} catch (CthunClient::connection_error& e) {
// We failed to send the response; it's up to the
// requester to ask again
LOG_ERROR("Failed to reply to the %1% request from %2%: %3%",
request_id, requester_endpoint, e.what());
}
} catch (request_error& e) {
LOG_ERROR("Failed to process message %1% from %2%: %3%",
request_id, requester_endpoint, e.what());
CthunClient::DataContainer error_data_json;
// TODO(ale): make error handling consistent in our protocol
// specs; we should have an error schema
// TODO(ale): we should specify the id of the request; more in
// general, we should specify the request id in every response
error_data_json.set<std::string>("error", e.what());
try {
connector_.send(std::vector<std::string> { requester_endpoint },
CTHUN_RESPONSE_SCHEMA_NAME,
DEFAULT_MSG_TIMEOUT_SEC,
error_data_json);
} catch (CthunClient::connection_error& e) {
LOG_ERROR("Failed send an error response to the %1% request "
"from %2%: %3%", request_id, requester_endpoint, e.what());
}
}
}
} // namespace CthunAgent
<commit_msg>(CTH-214) Send a cnc error message in case of failure<commit_after>#include <cthun-agent/agent.hpp>
#include <cthun-agent/errors.hpp>
#include <cthun-agent/uuid.hpp>
#include <cthun-agent/string_utils.hpp>
#include <cthun-agent/external_module.hpp>
#include <cthun-agent/modules/echo.hpp>
#include <cthun-agent/modules/inventory.hpp>
#include <cthun-agent/modules/ping.hpp>
#include <cthun-agent/modules/status.hpp>
#include <cthun-client/connector/errors.hpp>
#include <cthun-client/data_container/data_container.hpp>
#include <cthun-client/validator/validator.hpp> // Validator
#define LEATHERMAN_LOGGING_NAMESPACE "puppetlabs.cthun_agent.agent"
#include <leatherman/logging/logging.hpp>
#include <vector>
#include <memory>
namespace CthunAgent {
namespace fs = boost::filesystem;
//
// Constants
//
static const std::string AGENT_CLIENT_TYPE { "agent" };
static const std::string CTHUN_REQUEST_SCHEMA_NAME { "http://puppetlabs.com/cnc_request" };
static const std::string CTHUN_RESPONSE_SCHEMA_NAME { "http://puppetlabs.com/cnc_response" };
static const std::string CTHUN_ERROR_SCHEMA_NAME { "http://puppetlabs.com/cnc_error_message" };
static const int DEFAULT_MSG_TIMEOUT_SEC { 10 };
//
// Agent
//
Agent::Agent(const std::string& modules_dir,
const std::string& server_url,
const std::string& ca,
const std::string& crt,
const std::string& key)
try
: connector_ { server_url, AGENT_CLIENT_TYPE, ca, crt, key },
modules_ {} {
// NB: certificate paths are validated by HW
loadInternalModules();
if (!modules_dir.empty()) {
loadExternalModulesFrom(modules_dir);
} else {
LOG_INFO("The modules directory was not provided; no external module "
"will be loaded");
}
logLoadedModules();
} catch (CthunClient::connection_config_error& e) {
throw fatal_error { std::string("failed to configure the agent: ")
+ e.what() };
}
void Agent::start() {
connector_.registerMessageCallback(
getCncRequestSchema(),
[this](const CthunClient::ParsedChunks& parsed_chunks) {
cncRequestCallback(parsed_chunks);
});
try {
connector_.connect();
} catch (CthunClient::connection_config_error& e) {
LOG_ERROR("Failed to configure the underlying communications layer: %1%",
e.what());
throw fatal_error { "failed to configure the underlying communications"
"layer" };
} catch (CthunClient::connection_fatal_error& e) {
LOG_ERROR("Failed to connect: %1%", e.what());
throw fatal_error { "failed to connect" };
}
// The agent is now connected and the request handlers are set;
// we can now call the monitoring method that will block this
// thread of execution.
// Note that, in case the underlying connection drops, the
// connector will keep trying to re-establish it indefinitely
// (the max_connect_attempts is 0 by default).
try {
connector_.monitorConnection();
} catch (CthunClient::connection_fatal_error) {
throw fatal_error { "failed to reconnect" };
}
// TODO(ale): wait for the associate session response, once the
// associated state is exposed by Connector
}
//
// Agent - private interface
//
void Agent::loadInternalModules() {
modules_["echo"] = std::shared_ptr<Module>(new Modules::Echo);
modules_["inventory"] = std::shared_ptr<Module>(new Modules::Inventory);
modules_["ping"] = std::shared_ptr<Module>(new Modules::Ping);
modules_["status"] = std::shared_ptr<Module>(new Modules::Status);
}
void Agent::loadExternalModulesFrom(fs::path dir_path) {
LOG_INFO("Loading external modules from %1%", dir_path.string());
if (fs::is_directory(dir_path)) {
fs::directory_iterator end;
for (auto f = fs::directory_iterator(dir_path); f != end; ++f) {
if (!fs::is_directory(f->status())) {
auto f_p = f->path().string();
try {
ExternalModule* e_m = new ExternalModule(f_p);
modules_[e_m->module_name] = std::shared_ptr<Module>(e_m);
} catch (module_error& e) {
LOG_ERROR("Failed to load %1%; %2%", f_p, e.what());
} catch (std::exception& e) {
LOG_ERROR("Unexpected error when loading %1%; %2%",
f_p, e.what());
} catch (...) {
LOG_ERROR("Unexpected error when loading %1%", f_p);
}
}
}
} else {
LOG_WARNING("Failed to locate the modules directory; external modules "
"will not be loaded");
}
}
void Agent::logLoadedModules() const {
for (auto& module : modules_) {
std::string txt { "found no action" };
std::string actions_list { "" };
for (auto& action : module.second->actions) {
if (actions_list.empty()) {
txt = "action";
actions_list += ": ";
} else {
actions_list += ", ";
}
actions_list += action.first;
}
auto txt_suffix = StringUtils::plural(module.second->actions.size());
LOG_INFO("Loaded '%1%' module - %2%%3%%4%",
module.first, txt, txt_suffix, actions_list);
}
}
CthunClient::Schema Agent::getCncRequestSchema() const {
CthunClient::Schema schema { CTHUN_REQUEST_SCHEMA_NAME,
CthunClient::ContentType::Json };
using T_C = CthunClient::TypeConstraint;
schema.addConstraint("module", T_C::String, true);
schema.addConstraint("action", T_C::String, true);
// TODO(ale): evaluate changing params; ambiguous
schema.addConstraint("params", T_C::Object, false);
return schema;
}
void Agent::cncRequestCallback(const CthunClient::ParsedChunks& parsed_chunks) {
auto request_id = parsed_chunks.envelope.get<std::string>("id");
auto requester_endpoint = parsed_chunks.envelope.get<std::string>("sender");
LOG_INFO("Received message %1% from %2%", request_id, requester_endpoint);
LOG_DEBUG("Message %1%:\n%2%", request_id, parsed_chunks.toString());
try {
// Inspect envelope
if (!parsed_chunks.has_data) {
throw request_validation_error { "no data" };
}
if (parsed_chunks.data_type != CthunClient::ContentType::Json) {
throw request_validation_error { "data is not in JSON format" };
}
// Inspect data
auto module_name = parsed_chunks.data.get<std::string>("module");
auto action_name = parsed_chunks.data.get<std::string>("action");
if (modules_.find(module_name) == modules_.end()) {
throw request_validation_error { "unknown module: " + module_name };
}
// Perform the requested action
auto module_ptr = modules_.at(module_name);
auto data_json = module_ptr->performRequest(action_name, parsed_chunks);
// Wrap debug data
std::vector<CthunClient::DataContainer> debug {};
for (auto& debug_entry : parsed_chunks.debug) {
debug.push_back(debug_entry);
}
try {
connector_.send(std::vector<std::string> { requester_endpoint },
CTHUN_RESPONSE_SCHEMA_NAME,
DEFAULT_MSG_TIMEOUT_SEC,
data_json,
debug);
} catch (CthunClient::connection_error& e) {
// We failed to send the response; it's up to the
// requester to ask again
LOG_ERROR("Failed to reply to the %1% request from %2%: %3%",
request_id, requester_endpoint, e.what());
}
} catch (request_error& e) {
LOG_ERROR("Failed to process message %1% from %2%: %3%",
request_id, requester_endpoint, e.what());
CthunClient::DataContainer error_data_json;
error_data_json.set<std::string>("description", e.what());
error_data_json.set<std::string>("id", request_id);
try {
connector_.send(std::vector<std::string> { requester_endpoint },
CTHUN_ERROR_SCHEMA_NAME,
DEFAULT_MSG_TIMEOUT_SEC,
error_data_json);
LOG_INFO("Replied to message %1% from %2% with an error message",
request_id, requester_endpoint);
} catch (CthunClient::connection_error& e) {
LOG_ERROR("Failed send an error response to the %1% request "
"from %2%: %3%", request_id, requester_endpoint, e.what());
}
}
}
} // namespace CthunAgent
<|endoftext|>
|
<commit_before>/*
Copyright (c) 2006, MassaRoddel, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
namespace libtorrent { namespace
{
const char extension_name[] = "ut_pex";
enum
{
extension_index = 1,
max_peer_entries = 100
};
bool send_peer(peer_connection const& p)
{
// don't send out peers that we haven't connected to
// (that have connected to us)
if (!p.is_local()) return false;
// don't send out peers that we haven't successfully connected to
if (p.is_connecting()) return false;
return true;
}
struct ut_pex_plugin: torrent_plugin
{
ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(0) {}
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc);
std::vector<char>& get_ut_pex_msg()
{
return m_ut_pex_msg;
}
// the second tick of the torrent
// each minute the new lists of "added" + "added.f" and "dropped"
// are calculated here and the pex message is created
// each peer connection will use this message
// max_peer_entries limits the packet size
virtual void tick()
{
if (++m_1_minute < 60) return;
m_1_minute = 0;
entry pex;
std::string& pla = pex["added"].string();
std::string& pld = pex["dropped"].string();
std::string& plf = pex["added.f"].string();
std::string& pla6 = pex["added6"].string();
std::string& pld6 = pex["dropped6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> pld_out(pld);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> pld6_out(pld6);
std::back_insert_iterator<std::string> plf6_out(plf6);
std::set<tcp::endpoint> dropped;
m_old_peers.swap(dropped);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
tcp::endpoint const& remote = peer->remote();
m_old_peers.insert(remote);
std::set<tcp::endpoint>::iterator di = dropped.find(remote);
if (di == dropped.end())
{
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
else
{
// this was in the previous message
// so, it wasn't dropped
dropped.erase(di);
}
}
for (std::set<tcp::endpoint>::const_iterator i = dropped.begin()
, end(dropped.end()); i != end; ++i)
{
if (i->address().is_v4())
detail::write_endpoint(*i, pld_out);
else
detail::write_endpoint(*i, pld6_out);
}
m_ut_pex_msg.clear();
bencode(std::back_inserter(m_ut_pex_msg), pex);
}
private:
torrent& m_torrent;
std::set<tcp::endpoint> m_old_peers;
int m_1_minute;
std::vector<char> m_ut_pex_msg;
};
struct ut_pex_peer_plugin : peer_plugin
{
ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp)
: m_torrent(t)
, m_pc(pc)
, m_tp(tp)
, m_1_minute(0)
, m_message_index(0)
, m_first_time(true)
{}
virtual void add_handshake(entry& h)
{
entry& messages = h["m"];
messages[extension_name] = extension_index;
}
virtual bool on_extension_handshake(entry const& h)
{
entry const& messages = h["m"];
if (entry const* index = messages.find_key(extension_name))
{
m_message_index = index->integer();
return true;
}
else
{
m_message_index = 0;
return false;
}
}
virtual bool on_extended(int length, int msg, buffer::const_interval body)
{
if (msg != extension_index) return false;
if (m_message_index == 0) return false;
if (length > 500 * 1024)
throw protocol_error("uT peer exchange message larger than 500 kB");
if (body.left() < length) return true;
try
{
entry pex_msg = bdecode(body.begin, body.end);
std::string const& peers = pex_msg["added"].string();
std::string const& peer_flags = pex_msg["added.f"].string();
int num_peers = peers.length() / 6;
char const* in = peers.c_str();
char const* fin = peer_flags.c_str();
if (int(peer_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
if (entry const* p6 = pex_msg.find_key("added6"))
{
std::string const& peers6 = p6->string();
std::string const& peer6_flags = pex_msg["added6.f"].string();
int num_peers = peers6.length() / 18;
char const* in = peers6.c_str();
char const* fin = peer6_flags.c_str();
if (int(peer6_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v6_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
}
catch (std::exception&)
{
throw protocol_error("invalid uT peer exchange message");
}
return true;
}
// the peers second tick
// every minute we send a pex message
virtual void tick()
{
if (!m_message_index) return; // no handshake yet
if (++m_1_minute <= 60) return;
if (m_first_time)
{
send_ut_peer_list();
m_first_time = false;
}
else
{
send_ut_peer_diff();
}
m_1_minute = 0;
}
private:
void send_ut_peer_diff()
{
std::vector<char> const& pex_msg = m_tp.get_ut_pex_msg();
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
void send_ut_peer_list()
{
entry pex;
// leave the dropped string empty
pex["dropped"].string();
std::string& pla = pex["added"].string();
std::string& plf = pex["added.f"].string();
pex["dropped6"].string();
std::string& pla6 = pex["added6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> plf6_out(plf6);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
tcp::endpoint const& remote = peer->remote();
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
std::vector<char> pex_msg;
bencode(std::back_inserter(pex_msg), pex);
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
torrent& m_torrent;
peer_connection& m_pc;
ut_pex_plugin& m_tp;
int m_1_minute;
int m_message_index;
// this is initialized to true, and set to
// false after the first pex message has been sent.
// it is used to know if a diff message or a full
// message should be sent.
bool m_first_time;
};
boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc)
{
bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc);
if (!c) return boost::shared_ptr<peer_plugin>();
return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent
, *pc, *this));
}
}}
namespace libtorrent
{
boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t, void*)
{
if (t->torrent_file().priv())
{
return boost::shared_ptr<torrent_plugin>();
}
return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t));
}
}
<commit_msg>ut_pex sends peers sooner<commit_after>/*
Copyright (c) 2006, MassaRoddel, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#include "libtorrent/pch.hpp"
#ifdef _MSC_VER
#pragma warning(push, 1)
#endif
#include <boost/shared_ptr.hpp>
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#include "libtorrent/peer_connection.hpp"
#include "libtorrent/bt_peer_connection.hpp"
#include "libtorrent/bencode.hpp"
#include "libtorrent/torrent.hpp"
#include "libtorrent/extensions.hpp"
#include "libtorrent/extensions/ut_pex.hpp"
namespace libtorrent { namespace
{
const char extension_name[] = "ut_pex";
enum
{
extension_index = 1,
max_peer_entries = 100
};
bool send_peer(peer_connection const& p)
{
// don't send out peers that we haven't connected to
// (that have connected to us)
if (!p.is_local()) return false;
// don't send out peers that we haven't successfully connected to
if (p.is_connecting()) return false;
return true;
}
struct ut_pex_plugin: torrent_plugin
{
ut_pex_plugin(torrent& t): m_torrent(t), m_1_minute(55) {}
virtual boost::shared_ptr<peer_plugin> new_connection(peer_connection* pc);
std::vector<char>& get_ut_pex_msg()
{
return m_ut_pex_msg;
}
// the second tick of the torrent
// each minute the new lists of "added" + "added.f" and "dropped"
// are calculated here and the pex message is created
// each peer connection will use this message
// max_peer_entries limits the packet size
virtual void tick()
{
if (++m_1_minute < 60) return;
m_1_minute = 0;
entry pex;
std::string& pla = pex["added"].string();
std::string& pld = pex["dropped"].string();
std::string& plf = pex["added.f"].string();
std::string& pla6 = pex["added6"].string();
std::string& pld6 = pex["dropped6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> pld_out(pld);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> pld6_out(pld6);
std::back_insert_iterator<std::string> plf6_out(plf6);
std::set<tcp::endpoint> dropped;
m_old_peers.swap(dropped);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
tcp::endpoint const& remote = peer->remote();
m_old_peers.insert(remote);
std::set<tcp::endpoint>::iterator di = dropped.find(remote);
if (di == dropped.end())
{
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
else
{
// this was in the previous message
// so, it wasn't dropped
dropped.erase(di);
}
}
for (std::set<tcp::endpoint>::const_iterator i = dropped.begin()
, end(dropped.end()); i != end; ++i)
{
if (i->address().is_v4())
detail::write_endpoint(*i, pld_out);
else
detail::write_endpoint(*i, pld6_out);
}
m_ut_pex_msg.clear();
bencode(std::back_inserter(m_ut_pex_msg), pex);
}
private:
torrent& m_torrent;
std::set<tcp::endpoint> m_old_peers;
int m_1_minute;
std::vector<char> m_ut_pex_msg;
};
struct ut_pex_peer_plugin : peer_plugin
{
ut_pex_peer_plugin(torrent& t, peer_connection& pc, ut_pex_plugin& tp)
: m_torrent(t)
, m_pc(pc)
, m_tp(tp)
, m_1_minute(55)
, m_message_index(0)
, m_first_time(true)
{}
virtual void add_handshake(entry& h)
{
entry& messages = h["m"];
messages[extension_name] = extension_index;
}
virtual bool on_extension_handshake(entry const& h)
{
entry const& messages = h["m"];
if (entry const* index = messages.find_key(extension_name))
{
m_message_index = index->integer();
return true;
}
else
{
m_message_index = 0;
return false;
}
}
virtual bool on_extended(int length, int msg, buffer::const_interval body)
{
if (msg != extension_index) return false;
if (m_message_index == 0) return false;
if (length > 500 * 1024)
throw protocol_error("uT peer exchange message larger than 500 kB");
if (body.left() < length) return true;
try
{
entry pex_msg = bdecode(body.begin, body.end);
std::string const& peers = pex_msg["added"].string();
std::string const& peer_flags = pex_msg["added.f"].string();
int num_peers = peers.length() / 6;
char const* in = peers.c_str();
char const* fin = peer_flags.c_str();
if (int(peer_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v4_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
if (entry const* p6 = pex_msg.find_key("added6"))
{
std::string const& peers6 = p6->string();
std::string const& peer6_flags = pex_msg["added6.f"].string();
int num_peers = peers6.length() / 18;
char const* in = peers6.c_str();
char const* fin = peer6_flags.c_str();
if (int(peer6_flags.size()) != num_peers)
return true;
peer_id pid(0);
policy& p = m_torrent.get_policy();
for (int i = 0; i < num_peers; ++i)
{
tcp::endpoint adr = detail::read_v6_endpoint<tcp::endpoint>(in);
char flags = detail::read_uint8(fin);
p.peer_from_tracker(adr, pid, peer_info::pex, flags);
}
}
}
catch (std::exception&)
{
throw protocol_error("invalid uT peer exchange message");
}
return true;
}
// the peers second tick
// every minute we send a pex message
virtual void tick()
{
if (!m_message_index) return; // no handshake yet
if (++m_1_minute <= 60) return;
if (m_first_time)
{
send_ut_peer_list();
m_first_time = false;
}
else
{
send_ut_peer_diff();
}
m_1_minute = 0;
}
private:
void send_ut_peer_diff()
{
std::vector<char> const& pex_msg = m_tp.get_ut_pex_msg();
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
void send_ut_peer_list()
{
entry pex;
// leave the dropped string empty
pex["dropped"].string();
std::string& pla = pex["added"].string();
std::string& plf = pex["added.f"].string();
pex["dropped6"].string();
std::string& pla6 = pex["added6"].string();
std::string& plf6 = pex["added6.f"].string();
std::back_insert_iterator<std::string> pla_out(pla);
std::back_insert_iterator<std::string> plf_out(plf);
std::back_insert_iterator<std::string> pla6_out(pla6);
std::back_insert_iterator<std::string> plf6_out(plf6);
int num_added = 0;
for (torrent::peer_iterator i = m_torrent.begin()
, end(m_torrent.end()); i != end; ++i)
{
peer_connection* peer = *i;
if (!send_peer(*peer)) continue;
// don't write too big of a package
if (num_added >= max_peer_entries) break;
// only send proper bittorrent peers
bt_peer_connection* p = dynamic_cast<bt_peer_connection*>(peer);
if (!p) continue;
// no supported flags to set yet
// 0x01 - peer supports encryption
// 0x02 - peer is a seed
int flags = p->is_seed() ? 2 : 0;
#ifndef TORRENT_DISABLE_ENCRYPTION
flags |= p->supports_encryption() ? 1 : 0;
#endif
tcp::endpoint const& remote = peer->remote();
// i->first was added since the last time
if (remote.address().is_v4())
{
detail::write_endpoint(remote, pla_out);
detail::write_uint8(flags, plf_out);
}
else
{
detail::write_endpoint(remote, pla6_out);
detail::write_uint8(flags, plf6_out);
}
++num_added;
}
std::vector<char> pex_msg;
bencode(std::back_inserter(pex_msg), pex);
buffer::interval i = m_pc.allocate_send_buffer(6 + pex_msg.size());
detail::write_uint32(1 + 1 + pex_msg.size(), i.begin);
detail::write_uint8(bt_peer_connection::msg_extended, i.begin);
detail::write_uint8(m_message_index, i.begin);
std::copy(pex_msg.begin(), pex_msg.end(), i.begin);
i.begin += pex_msg.size();
TORRENT_ASSERT(i.begin == i.end);
m_pc.setup_send();
}
torrent& m_torrent;
peer_connection& m_pc;
ut_pex_plugin& m_tp;
int m_1_minute;
int m_message_index;
// this is initialized to true, and set to
// false after the first pex message has been sent.
// it is used to know if a diff message or a full
// message should be sent.
bool m_first_time;
};
boost::shared_ptr<peer_plugin> ut_pex_plugin::new_connection(peer_connection* pc)
{
bt_peer_connection* c = dynamic_cast<bt_peer_connection*>(pc);
if (!c) return boost::shared_ptr<peer_plugin>();
return boost::shared_ptr<peer_plugin>(new ut_pex_peer_plugin(m_torrent
, *pc, *this));
}
}}
namespace libtorrent
{
boost::shared_ptr<torrent_plugin> create_ut_pex_plugin(torrent* t, void*)
{
if (t->torrent_file().priv())
{
return boost::shared_ptr<torrent_plugin>();
}
return boost::shared_ptr<torrent_plugin>(new ut_pex_plugin(*t));
}
}
<|endoftext|>
|
<commit_before>#include "cmm_socket_receiver.h"
#include "cmm_socket_sender.h"
#include <pthread.h>
#include "debug.h"
#include <vector>
using std::vector;
class ReadyIROB {
public:
bool operator()(PendingIROB *pi) {
assert(pi);
PendingReceiverIROB *pirob = static_cast<PendingReceiverIROB*>(pi);
assert(pirob);
return (pirob->is_complete() && pirob->is_released());
}
};
CMMSocketReceiver::CMMSocketReceiver(CMMSocketImpl *sk_)
: sk(sk_)
{
handle(CMM_CONTROL_MSG_BEGIN_IROB, this,
&CMMSocketReceiver::do_begin_irob);
handle(CMM_CONTROL_MSG_END_IROB, this, &CMMSocketReceiver::do_end_irob);
handle(CMM_CONTROL_MSG_IROB_CHUNK, this,
&CMMSocketReceiver::do_irob_chunk);
handle(CMM_CONTROL_MSG_NEW_INTERFACE, this,
&CMMSocketReceiver::do_new_interface);
handle(CMM_CONTROL_MSG_DOWN_INTERFACE, this,
&CMMSocketReceiver::do_down_interface);
handle(CMM_CONTROL_MSG_ACK, this, &CMMSocketReceiver::do_ack);
}
CMMSocketReceiver::~CMMSocketReceiver()
{
PendingIROBHash::accessor ac;
while (pending_irobs.any(ac)) {
PendingIROB *victim = ac->second;
pending_irobs.erase(ac);
delete victim;
ac.release();
}
}
void
CMMSocketReceiver::dispatch(struct CMMSocketControlHdr hdr)
{
dbgprintf("Got request\n%s\n", hdr.describe().c_str());
CMMSocketScheduler<struct CMMSocketControlHdr>::dispatch(hdr);
}
void
CMMSocketReceiver::do_begin_irob(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_BEGIN_IROB);
if (hdr.op.begin_irob.numdeps > 0) {
assert(hdr.op.begin_irob.deps);
}
PendingIROB *pirob = new PendingReceiverIROB(hdr.op.begin_irob);
PendingIROBHash::accessor ac;
if (!pending_irobs.insert(ac, pirob)) {
delete pirob;
throw Exception::make("Tried to begin IROB that already exists",
hdr);
}
if (hdr.op.begin_irob.numdeps > 0) {
delete [] hdr.op.begin_irob.deps;
}
}
void
CMMSocketReceiver::do_end_irob(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_END_IROB);
PendingIROBHash::accessor ac;
irob_id_t id = ntohl(hdr.op.end_irob.id);
if (!pending_irobs.find(ac, id)) {
if (pending_irobs.past_irob_exists(id)) {
throw Exception::make("Tried to end committed IROB", hdr);
} else {
throw Exception::make("Tried to end nonexistent IROB", hdr);
}
}
PendingIROB *pirob = ac->second;
assert(pirob);
if (!pirob->finish()) {
throw Exception::make("Tried to end already-done IROB", hdr);
}
PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob);
pending_irobs.release_if_ready(prirob, ReadyIROB());
}
void
CMMSocketReceiver::do_irob_chunk(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_IROB_CHUNK);
PendingIROBHash::accessor ac;
irob_id_t id = ntohl(hdr.op.irob_chunk.id);
if (!pending_irobs.find(ac, id)) {
if (pending_irobs.past_irob_exists(id)) {
throw Exception::make("Tried to add to committed IROB", hdr);
} else {
throw Exception::make("Tried to add to nonexistent IROB", hdr);
}
}
struct irob_chunk_data chunk;
chunk.id = id;
chunk.seqno = ntohl(hdr.op.irob_chunk.seqno);
chunk.datalen = ntohl(hdr.op.irob_chunk.datalen);
chunk.data = hdr.op.irob_chunk.data;
PendingIROB *pirob = ac->second;
assert(pirob);
PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob);
assert(prirob);
if (!pirob->add_chunk(chunk)) {
throw Exception::make("Tried to add to completed IROB", hdr);
} else {
dbgprintf("Successfully added chunk %d to IROB %d\n",
chunk.seqno, id);
}
}
void
CMMSocketReceiver::do_new_interface(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_NEW_INTERFACE);
struct net_interface iface = {hdr.op.new_interface.ip_addr,
hdr.op.new_interface.labels};
sk->setup(iface, false);
}
void
CMMSocketReceiver::do_down_interface(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_DOWN_INTERFACE);
struct net_interface iface = {hdr.op.down_interface.ip_addr};
sk->teardown(iface, false);
}
void
CMMSocketReceiver::do_ack(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_ACK);
sk->sendr->ack_received(ntohl(hdr.op.ack.id), ntohl(hdr.op.ack.seqno));
}
/* This is where all the scheduling logic happens.
* This function decides how to pass IROB data to the application.
*
* Additionally, this function is the only place we need
* to worry about race conditions with the Receiver thread.
* Thus, the locking discipline of that thread will be informed
* by whatever reads and writes are necessary here.
*
* Initial stab at requirements:
* This thread definitely needs to read from the pending_irobs
* data structure, to figure out what data to pass to the
* application. It also needs to update this data structure
* and the past_irobs set as IROBs are committed.
* Thought: we could make this function read-only by using the
* msg_queue to cause the Receiver thread to do any needed updates.
*/
/* TODO: nonblocking mode */
ssize_t
CMMSocketReceiver::recv(void *bufp, size_t len, int flags, u_long *recv_labels)
{
vector<PendingReceiverIROB *> pirobs;
char *buf = (char*)bufp;
ssize_t bytes_ready = 0;
while ((size_t)bytes_ready < len) {
PendingReceiverIROB *pirob = pending_irobs.get_ready_irob();
assert(pirob); /* XXX: nonblocking version could return NULL */
/* after the IROB is returned here, no other thread will
* unsafely modify it.
* XXX: this will not be true if we allow get_next_irob
* to return released, incomplete IROBs.
* We could fix that by simply having a sentinel chunk
* on the concurrent_queue of chunks. */
assert(pirob->is_released());
assert(pirob->is_complete()); /* XXX: see get_next_irob */
ssize_t bytes = pirob->numbytes();
assert(bytes > 0);
bytes_ready += bytes;
pirobs.push_back(pirob);
if (!pirob->is_complete()) {
break;
}
}
ssize_t bytes_passed = 0;
bool partial_irob = false;
for (size_t i = 0; i < pirobs.size(); i++) {
PendingIROBHash::accessor ac;
PendingReceiverIROB *pirob = pirobs[i];
if (!pending_irobs.find(ac, pirob->id)) {
assert(0);
}
assert(pirob == ac->second);
if (i == 0) {
if (recv_labels) {
*recv_labels = pirob->send_labels;
}
}
bytes_passed += pirob->read_data(buf + bytes_passed,
len - bytes_passed);
if (pirob->is_complete() && pirob->numbytes() == 0) {
pending_irobs.erase(ac);
pending_irobs.release_dependents(pirob, ReadyIROB());
delete pirob;
} else {
if (!pirob->is_complete()) {
/* This should still be the last one in the list,
* since it MUST finish before any IROB can be
* passed to the application. */
}
/* this should be true for at most the last IROB
* in the vector */
assert(!partial_irob);
partial_irob = true;
pending_irobs.partially_read(pirob);
}
}
return bytes_passed;
}
<commit_msg>d'oh, missed the variable name. prirob != pirob.<commit_after>#include "cmm_socket_receiver.h"
#include "cmm_socket_sender.h"
#include <pthread.h>
#include "debug.h"
#include <vector>
using std::vector;
class ReadyIROB {
public:
bool operator()(PendingIROB *pi) {
assert(pi);
PendingReceiverIROB *pirob = static_cast<PendingReceiverIROB*>(pi);
assert(pirob);
return (pirob->is_complete() && pirob->is_released());
}
};
CMMSocketReceiver::CMMSocketReceiver(CMMSocketImpl *sk_)
: sk(sk_)
{
handle(CMM_CONTROL_MSG_BEGIN_IROB, this,
&CMMSocketReceiver::do_begin_irob);
handle(CMM_CONTROL_MSG_END_IROB, this, &CMMSocketReceiver::do_end_irob);
handle(CMM_CONTROL_MSG_IROB_CHUNK, this,
&CMMSocketReceiver::do_irob_chunk);
handle(CMM_CONTROL_MSG_NEW_INTERFACE, this,
&CMMSocketReceiver::do_new_interface);
handle(CMM_CONTROL_MSG_DOWN_INTERFACE, this,
&CMMSocketReceiver::do_down_interface);
handle(CMM_CONTROL_MSG_ACK, this, &CMMSocketReceiver::do_ack);
}
CMMSocketReceiver::~CMMSocketReceiver()
{
PendingIROBHash::accessor ac;
while (pending_irobs.any(ac)) {
PendingIROB *victim = ac->second;
pending_irobs.erase(ac);
delete victim;
ac.release();
}
}
void
CMMSocketReceiver::dispatch(struct CMMSocketControlHdr hdr)
{
dbgprintf("Got request\n%s\n", hdr.describe().c_str());
CMMSocketScheduler<struct CMMSocketControlHdr>::dispatch(hdr);
}
void
CMMSocketReceiver::do_begin_irob(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_BEGIN_IROB);
if (hdr.op.begin_irob.numdeps > 0) {
assert(hdr.op.begin_irob.deps);
}
PendingIROB *pirob = new PendingReceiverIROB(hdr.op.begin_irob);
PendingIROBHash::accessor ac;
if (!pending_irobs.insert(ac, pirob)) {
delete pirob;
throw Exception::make("Tried to begin IROB that already exists",
hdr);
}
if (hdr.op.begin_irob.numdeps > 0) {
delete [] hdr.op.begin_irob.deps;
}
}
void
CMMSocketReceiver::do_end_irob(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_END_IROB);
PendingIROBHash::accessor ac;
irob_id_t id = ntohl(hdr.op.end_irob.id);
if (!pending_irobs.find(ac, id)) {
if (pending_irobs.past_irob_exists(id)) {
throw Exception::make("Tried to end committed IROB", hdr);
} else {
throw Exception::make("Tried to end nonexistent IROB", hdr);
}
}
PendingIROB *pirob = ac->second;
assert(pirob);
if (!pirob->finish()) {
throw Exception::make("Tried to end already-done IROB", hdr);
}
PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob);
pending_irobs.release_if_ready(prirob, ReadyIROB());
}
void
CMMSocketReceiver::do_irob_chunk(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_IROB_CHUNK);
PendingIROBHash::accessor ac;
irob_id_t id = ntohl(hdr.op.irob_chunk.id);
if (!pending_irobs.find(ac, id)) {
if (pending_irobs.past_irob_exists(id)) {
throw Exception::make("Tried to add to committed IROB", hdr);
} else {
throw Exception::make("Tried to add to nonexistent IROB", hdr);
}
}
struct irob_chunk_data chunk;
chunk.id = id;
chunk.seqno = ntohl(hdr.op.irob_chunk.seqno);
chunk.datalen = ntohl(hdr.op.irob_chunk.datalen);
chunk.data = hdr.op.irob_chunk.data;
PendingIROB *pirob = ac->second;
assert(pirob);
PendingReceiverIROB *prirob = static_cast<PendingReceiverIROB*>(pirob);
assert(prirob);
if (!prirob->add_chunk(chunk)) {
throw Exception::make("Tried to add to completed IROB", hdr);
} else {
dbgprintf("Successfully added chunk %d to IROB %d\n",
chunk.seqno, id);
}
}
void
CMMSocketReceiver::do_new_interface(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_NEW_INTERFACE);
struct net_interface iface = {hdr.op.new_interface.ip_addr,
hdr.op.new_interface.labels};
sk->setup(iface, false);
}
void
CMMSocketReceiver::do_down_interface(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_DOWN_INTERFACE);
struct net_interface iface = {hdr.op.down_interface.ip_addr};
sk->teardown(iface, false);
}
void
CMMSocketReceiver::do_ack(struct CMMSocketControlHdr hdr)
{
assert(ntohs(hdr.type) == CMM_CONTROL_MSG_ACK);
sk->sendr->ack_received(ntohl(hdr.op.ack.id), ntohl(hdr.op.ack.seqno));
}
/* This is where all the scheduling logic happens.
* This function decides how to pass IROB data to the application.
*
* Additionally, this function is the only place we need
* to worry about race conditions with the Receiver thread.
* Thus, the locking discipline of that thread will be informed
* by whatever reads and writes are necessary here.
*
* Initial stab at requirements:
* This thread definitely needs to read from the pending_irobs
* data structure, to figure out what data to pass to the
* application. It also needs to update this data structure
* and the past_irobs set as IROBs are committed.
* Thought: we could make this function read-only by using the
* msg_queue to cause the Receiver thread to do any needed updates.
*/
/* TODO: nonblocking mode */
ssize_t
CMMSocketReceiver::recv(void *bufp, size_t len, int flags, u_long *recv_labels)
{
vector<PendingReceiverIROB *> pirobs;
char *buf = (char*)bufp;
ssize_t bytes_ready = 0;
while ((size_t)bytes_ready < len) {
PendingReceiverIROB *pirob = pending_irobs.get_ready_irob();
assert(pirob); /* XXX: nonblocking version could return NULL */
/* after the IROB is returned here, no other thread will
* unsafely modify it.
* XXX: this will not be true if we allow get_next_irob
* to return released, incomplete IROBs.
* We could fix that by simply having a sentinel chunk
* on the concurrent_queue of chunks. */
assert(pirob->is_released());
assert(pirob->is_complete()); /* XXX: see get_next_irob */
ssize_t bytes = pirob->numbytes();
assert(bytes > 0);
bytes_ready += bytes;
pirobs.push_back(pirob);
if (!pirob->is_complete()) {
break;
}
}
ssize_t bytes_passed = 0;
bool partial_irob = false;
for (size_t i = 0; i < pirobs.size(); i++) {
PendingIROBHash::accessor ac;
PendingReceiverIROB *pirob = pirobs[i];
if (!pending_irobs.find(ac, pirob->id)) {
assert(0);
}
assert(pirob == ac->second);
if (i == 0) {
if (recv_labels) {
*recv_labels = pirob->send_labels;
}
}
bytes_passed += pirob->read_data(buf + bytes_passed,
len - bytes_passed);
if (pirob->is_complete() && pirob->numbytes() == 0) {
pending_irobs.erase(ac);
pending_irobs.release_dependents(pirob, ReadyIROB());
delete pirob;
} else {
if (!pirob->is_complete()) {
/* This should still be the last one in the list,
* since it MUST finish before any IROB can be
* passed to the application. */
}
/* this should be true for at most the last IROB
* in the vector */
assert(!partial_irob);
partial_irob = true;
pending_irobs.partially_read(pirob);
}
}
return bytes_passed;
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*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 "mkldnn.hpp"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"
#include "paddle/fluid/operators/sum_op.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/mkldnn_helper.h"
namespace paddle {
namespace operators {
using framework::DataLayout;
using mkldnn::memory;
using mkldnn::primitive;
using mkldnn::reorder;
using mkldnn::stream;
using mkldnn::sum;
using paddle::framework::Tensor;
using paddle::platform::CPUDeviceContext;
using paddle::platform::MKLDNNDeviceContext;
using platform::to_void_cast;
template <typename T>
class SumMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
public:
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
"It must use CPUPlace.");
auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
const auto& mkldnn_engine = dev_ctx.GetEngine();
auto in_vars = ctx.MultiInputVar("X");
const int N = in_vars.size();
auto out_var = ctx.OutputVar("Out");
bool in_place = out_var == in_vars[0];
if (out_var->IsType<framework::LoDTensor>()) {
LoDTensor* output = ctx.Output<LoDTensor>("Out");
T* output_data = output->mutable_data<T>(ctx.GetPlace());
std::vector<int> dst_tz = framework::vectorize2int(output->dims());
auto src_tz = dst_tz;
memory::format output_format{memory::format::format_undef};
std::vector<float> scales;
std::vector<memory::primitive_desc> srcs_mpd;
std::vector<mkldnn::memory> srcs_mem;
PADDLE_ENFORCE(in_vars[0]->IsType<LoDTensor>(),
"Input[0] must be LoDTensors");
auto& input0 = in_vars[0]->Get<LoDTensor>();
PADDLE_ENFORCE(input0.layout() == DataLayout::kMKLDNN &&
input0.format() != memory::format::format_undef,
"Wrong layout/format for inputs[0]");
memory::format input_format = input0.format();
if (src_tz.size() == 1 && (input_format == memory::format::nchw ||
input_format == memory::format::nhwc)) {
input_format = memory::format::x;
}
if (src_tz.size() == 2 && (input_format == memory::format::nchw ||
input_format == memory::format::nhwc)) {
input_format = memory::format::nc;
}
for (int i = 0; i < N; i++) {
PADDLE_ENFORCE(in_vars[i]->IsType<LoDTensor>(),
"all inputs must be all LoDTensors");
auto& input = in_vars[i]->Get<LoDTensor>();
PADDLE_ENFORCE(input.layout() == DataLayout::kMKLDNN &&
input.format() != memory::format::format_undef,
"Wrong layout/format for inputs");
if (input.numel() == 0) {
continue;
}
const T* input_data = input.data<T>();
auto src_md =
memory::desc(src_tz, memory::data_type::f32, input_format);
auto src_mpd = memory::primitive_desc(src_md, mkldnn_engine);
auto src_mem = memory(src_mpd, to_void_cast(input_data));
srcs_mpd.push_back(src_mpd);
srcs_mem.push_back(src_mem);
scales.push_back(1.0);
}
auto dst_md =
memory::desc(dst_tz, memory::data_type::f32, memory::format::any);
auto sum_pd = sum::primitive_desc(dst_md, scales, srcs_mpd);
std::shared_ptr<memory> dst_mem;
if (in_place) {
dst_mem.reset(new memory(sum_pd.dst_primitive_desc()));
} else {
dst_mem.reset(new memory(sum_pd.dst_primitive_desc(), output_data));
}
std::vector<mkldnn::primitive::at> inputs;
for (size_t i = 0; i < srcs_mem.size(); ++i) {
inputs.push_back(srcs_mem[i]);
}
auto sum_prim = mkldnn::sum(sum_pd, inputs, *dst_mem);
output_format = (memory::format)platform::GetMKLDNNFormat(sum_pd);
primitive reorder_prim;
std::shared_ptr<memory> target_mem;
if (in_place) {
output_format = input_format;
target_mem.reset(new memory(
{{{src_tz}, memory::data_type::f32, output_format}, mkldnn_engine},
output_data));
reorder_prim = reorder(*dst_mem, *target_mem);
}
std::vector<primitive> pipeline;
pipeline.push_back(sum_prim);
if (in_place) pipeline.push_back(reorder_prim);
stream(stream::kind::eager).submit(pipeline).wait();
output->set_layout(DataLayout::kMKLDNN);
output->set_format(output_format);
} else if (out_var->IsType<framework::SelectedRows>()) {
// TODO(@mozga-intel) Add MKLDNN SelectedRows support
std::unique_ptr<framework::SelectedRows> in0;
if (in_place) {
// If is in_place, we store the input[0] to in0
auto& in_sel0 = in_vars[0]->Get<SelectedRows>();
auto& rows = in_sel0.rows();
in0.reset(new framework::SelectedRows(rows, in_sel0.height()));
in0->mutable_value()->ShareDataWith(in_sel0.value());
}
auto get_selected_row = [&](size_t i) -> const SelectedRows& {
if (i == 0 && in0) {
return *in0;
} else {
return in_vars[i]->Get<SelectedRows>();
}
};
auto* out = ctx.Output<SelectedRows>("Out");
out->mutable_rows()->clear();
auto* out_value = out->mutable_value();
// Runtime InferShape
size_t first_dim = 0;
for (int i = 0; i < N; i++) {
auto& sel_row = get_selected_row(i);
first_dim += sel_row.rows().size();
}
std::vector<int64_t> in_dim;
for (int i = 0; i < N; i++) {
auto& sel_row = get_selected_row(i);
if (sel_row.rows().size() > 0) {
in_dim = framework::vectorize(sel_row.value().dims());
break;
}
}
if (in_dim.empty()) {
VLOG(3) << "WARNING: all the inputs are empty";
in_dim = framework::vectorize(get_selected_row(N - 1).value().dims());
} else {
in_dim[0] = static_cast<int64_t>(first_dim);
}
in_dim[0] = static_cast<int64_t>(first_dim);
out_value->Resize(framework::make_ddim(in_dim));
out_value->mutable_data<T>(ctx.GetPlace());
// if all the input sparse vars are empty, no need to
// merge these vars.
if (first_dim == 0UL) {
return;
}
math::SelectedRowsAddTo<CPUDeviceContext, T> functor;
int64_t offset = 0;
for (int i = 0; i < N; i++) {
auto& sel_row = get_selected_row(i);
if (sel_row.rows().size() == 0) {
continue;
}
PADDLE_ENFORCE_EQ(out->height(), sel_row.height());
functor(ctx.template device_context<CPUDeviceContext>(), sel_row,
offset, out);
offset += sel_row.value().numel();
}
} else if (out_var->IsType<framework::LoDTensorArray>()) {
// TODO(@mozga-intel) Add MKLDNN LoDTensorArray support
auto& out_array = *out_var->GetMutable<framework::LoDTensorArray>();
for (size_t i = in_place ? 1 : 0; i < in_vars.size(); ++i) {
PADDLE_ENFORCE(in_vars[i]->IsType<framework::LoDTensorArray>(),
"Only support all inputs are TensorArray");
auto& in_array = in_vars[i]->Get<framework::LoDTensorArray>();
for (size_t i = 0; i < in_array.size(); ++i) {
if (in_array[i].numel() != 0) {
if (i >= out_array.size()) {
out_array.resize(i + 1);
}
if (out_array[i].numel() == 0) {
framework::TensorCopy(in_array[i], in_array[i].place(),
ctx.device_context(), &out_array[i]);
out_array[i].set_lod(in_array[i].lod());
} else {
PADDLE_ENFORCE(out_array[i].lod() == in_array[i].lod());
auto in = EigenVector<T>::Flatten(in_array[i]);
auto result = EigenVector<T>::Flatten(out_array[i]);
result.device(*ctx.template device_context<MKLDNNDeviceContext>()
.eigen_device()) = result + in;
}
}
}
}
} else {
PADDLE_THROW("Unexpected branch, output variable type is %s",
framework::ToTypeName(out_var->Type()));
}
}
};
} // namespace operators
} // namespace paddle
REGISTER_OP_KERNEL(sum, MKLDNN, ::paddle::platform::CPUPlace,
paddle::operators::SumMKLDNNOpKernel<float>);
<commit_msg>Improve code reuse at MKL-DNN sum<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/*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 "mkldnn.hpp"
#include "paddle/fluid/framework/tensor.h"
#include "paddle/fluid/operators/math/selected_rows_functor.h"
#include "paddle/fluid/operators/sum_op.h"
#include "paddle/fluid/platform/device_context.h"
#include "paddle/fluid/platform/mkldnn_helper.h"
namespace paddle {
namespace operators {
using framework::DataLayout;
using mkldnn::memory;
using mkldnn::primitive;
using mkldnn::reorder;
using mkldnn::stream;
using mkldnn::sum;
using paddle::framework::Tensor;
using paddle::platform::CPUDeviceContext;
using paddle::platform::MKLDNNDeviceContext;
using platform::to_void_cast;
template <typename T>
class SumMKLDNNOpKernel : public paddle::framework::OpKernel<T> {
public:
void Compute(const paddle::framework::ExecutionContext& ctx) const override {
PADDLE_ENFORCE(paddle::platform::is_cpu_place(ctx.GetPlace()),
"It must use CPUPlace.");
auto& dev_ctx = ctx.template device_context<MKLDNNDeviceContext>();
const auto& mkldnn_engine = dev_ctx.GetEngine();
auto in_vars = ctx.MultiInputVar("X");
const int N = in_vars.size();
auto out_var = ctx.OutputVar("Out");
bool in_place = out_var == in_vars[0];
if (out_var->IsType<framework::LoDTensor>()) {
LoDTensor* output = ctx.Output<LoDTensor>("Out");
T* output_data = output->mutable_data<T>(ctx.GetPlace());
std::vector<int> dst_tz = framework::vectorize2int(output->dims());
auto src_tz = dst_tz;
memory::format output_format{memory::format::format_undef};
std::vector<float> scales;
std::vector<memory::primitive_desc> srcs_mpd;
std::vector<mkldnn::memory> srcs_mem;
PADDLE_ENFORCE(in_vars[0]->IsType<LoDTensor>(),
"Input[0] must be LoDTensors");
auto& input0 = in_vars[0]->Get<LoDTensor>();
PADDLE_ENFORCE(input0.layout() == DataLayout::kMKLDNN &&
input0.format() != memory::format::format_undef,
"Wrong layout/format for inputs[0]");
memory::format input_format = input0.format();
for (int i = 0; i < N; i++) {
PADDLE_ENFORCE(in_vars[i]->IsType<LoDTensor>(),
"all inputs must be all LoDTensors");
auto& input = in_vars[i]->Get<LoDTensor>();
PADDLE_ENFORCE(input.layout() == DataLayout::kMKLDNN &&
input.format() != memory::format::format_undef,
"Wrong layout/format for inputs");
if (input.numel() == 0) {
continue;
}
const T* input_data = input.data<T>();
auto src_md =
memory::desc(src_tz, memory::data_type::f32, input_format);
auto src_mpd = memory::primitive_desc(src_md, mkldnn_engine);
auto src_mem = memory(src_mpd, to_void_cast(input_data));
srcs_mpd.push_back(src_mpd);
srcs_mem.push_back(src_mem);
scales.push_back(1.0);
}
auto dst_md =
memory::desc(dst_tz, memory::data_type::f32, memory::format::any);
auto sum_pd = sum::primitive_desc(dst_md, scales, srcs_mpd);
std::shared_ptr<memory> dst_mem;
if (in_place) {
dst_mem.reset(new memory(sum_pd.dst_primitive_desc()));
} else {
dst_mem.reset(new memory(sum_pd.dst_primitive_desc(), output_data));
}
std::vector<mkldnn::primitive::at> inputs;
for (size_t i = 0; i < srcs_mem.size(); ++i) {
inputs.push_back(srcs_mem[i]);
}
auto sum_prim = mkldnn::sum(sum_pd, inputs, *dst_mem);
output_format = (memory::format)platform::GetMKLDNNFormat(sum_pd);
primitive reorder_prim;
std::shared_ptr<memory> target_mem;
if (in_place) {
output_format = input_format;
target_mem.reset(new memory(
{{{src_tz}, memory::data_type::f32, output_format}, mkldnn_engine},
output_data));
reorder_prim = reorder(*dst_mem, *target_mem);
}
std::vector<primitive> pipeline;
pipeline.push_back(sum_prim);
if (in_place) pipeline.push_back(reorder_prim);
stream(stream::kind::eager).submit(pipeline).wait();
output->set_layout(DataLayout::kMKLDNN);
output->set_format(output_format);
} else { // Fallback to naive version
// TODO(@mozga-intel) Add MKLDNN SelectedRows & LoDTensorArray support
SumKernel<CPUDeviceContext, T> reference_kernel;
reference_kernel.Compute(ctx);
}
}
};
} // namespace operators
} // namespace paddle
REGISTER_OP_KERNEL(sum, MKLDNN, ::paddle::platform::CPUPlace,
paddle::operators::SumMKLDNNOpKernel<float>);
<|endoftext|>
|
<commit_before>#include "EntityManager.hpp"
#ifndef KENGINE_MAX_SAVE_PATH_LENGTH
# define KENGINE_MAX_SAVE_PATH_LENGTH 64
#endif
#ifndef KENGINE_MAX_COMPONENT_NAME_LENGTH
# define KENGINE_MAX_COMPONENT_NAME_LENGTH 64
#endif
namespace kengine {
Entity EntityManager::getEntity(Entity::ID id) {
detail::ReadLock l(_entitiesMutex);
return Entity(id, _entities[id].mask, this);
}
EntityView EntityManager::getEntity(Entity::ID id) const {
detail::ReadLock l(_entitiesMutex);
return EntityView(id, _entities[id].mask);
}
void EntityManager::removeEntity(EntityView e) {
removeEntity(e.id);
}
void EntityManager::removeEntity(Entity::ID id) {
detail::WriteLock l(_updatesMutex);
if (_updatesLocked) {
_removals.push_back({ id });
}
else
doRemove(id);
}
void EntityManager::setEntityActive(EntityView e, bool active) {
setEntityActive(e.id, active);
}
void EntityManager::setEntityActive(Entity::ID id, bool active) {
detail::WriteLock l(_entitiesMutex);
_entities[id].active = active;
_entities[id].shouldActivateAfterInit = active;
}
struct ComponentIDSave {
size_t id;
putils::string<KENGINE_MAX_COMPONENT_NAME_LENGTH> name;
};
void EntityManager::load(const char * directory) {
{
detail::WriteLock l(_archetypesMutex);
_archetypes.clear();
}
{
detail::WriteLock l(_toReuseMutex);
_toReuse.clear();
}
for (auto & e : getEntities())
SystemManager::removeEntity(e);
{
detail::ReadLock l(_components.mutex);
for (const auto &[_, meta] : _components.map)
meta->load(directory);
}
size_t idMap[KENGINE_COMPONENT_COUNT]; // index = new, value = old
for (auto & i : idMap)
i = (size_t)-1;
{
detail::ReadLock l(_components.mutex);
std::ifstream f(putils::string<KENGINE_MAX_SAVE_PATH_LENGTH>("%s/components.bin", directory), std::ifstream::binary);
assert(f);
size_t size;
f.read((char *)&size, sizeof(size));
for (size_t i = 0; i < size; ++i) {
ComponentIDSave save;
f.read((char *)&save, sizeof(save));
assert(f.gcount() == sizeof(save));
for (const auto & [_, meta] : _components.map)
if (meta->funcs.name == save.name) {
idMap[meta->id] = save.id;
break;
}
}
}
std::ifstream f(putils::string<KENGINE_MAX_SAVE_PATH_LENGTH>("%s/entities.bin", directory), std::ifstream::binary);
assert(f);
size_t size;
f.read((char *)&size, sizeof(size));
{
detail::WriteLock l(_entitiesMutex);
_entities.resize(size);
f.read((char *)_entities.data(), size * sizeof(_entities[0]));
}
for (auto & e : getEntities()) {
if (e.componentMask != 0) { // Adjust for Components with new IDs since save
Entity::Mask tmp = 0;
for (size_t i = 0; i < KENGINE_COMPONENT_COUNT; ++i) {
const auto oldId = idMap[i];
tmp[i] = oldId == (size_t)-1 ? false : e.componentMask[oldId];
}
e.componentMask = tmp;
if (e.componentMask != 0)
updateMask(e.id, e.componentMask, true);
}
else {
detail::WriteLock l(_toReuseMutex);
_toReuse.emplace_back(e.id);
}
}
for (auto & e : getEntities())
SystemManager::registerEntity(e);
SystemManager::load(directory);
}
void EntityManager::save(const char * directory) const {
SystemManager::save(directory);
putils::vector<bool, KENGINE_COMPONENT_COUNT> serializable;
{
detail::ReadLock l(_components.mutex);
serializable.resize(_components.map.size());
for (const auto &[_, meta] : _components.map)
serializable[meta->id] = meta->save(directory);
// Save Component IDs
std::ofstream f(putils::string<KENGINE_MAX_SAVE_PATH_LENGTH>("%s/components.bin", directory), std::ofstream::binary);
const size_t size = _components.map.size();
f.write((const char *)&size, sizeof(size));
for (const auto &[_, meta] : _components.map) {
ComponentIDSave save;
save.id = meta->id;
save.name = meta->funcs.name;
f.write((const char *)&save, sizeof(save));
}
}
std::ofstream f(putils::string<KENGINE_MAX_SAVE_PATH_LENGTH>("%s/entities.bin", directory), std::ofstream::binary);
assert(f);
{
detail::ReadLock l(_entitiesMutex);
const auto size = _entities.size();
f.write((const char *)&size, sizeof(size));
for (EntityMetadata e : _entities) {
for (size_t i = 0; i < serializable.size(); ++i)
e.mask[i] = e.mask[i] && serializable[i];
f.write((const char *)&e, sizeof(e));
}
}
}
Entity EntityManager::alloc() {
{
detail::ReadLock l(_toReuseMutex);
if (_toReuse.empty()) {
detail::WriteLock l(_entitiesMutex);
const auto id = _entities.size();
_entities.push_back({ false, 0 });
return Entity(id, 0, this);
}
}
Entity::ID id;
{
detail::WriteLock l(_toReuseMutex);
if (!_toReuseSorted) {
std::sort(_toReuse.begin(), _toReuse.end(), std::greater<Entity::ID>());
_toReuseSorted = true;
}
id = _toReuse.back();
_toReuse.pop_back();
}
#ifndef NDEBUG
{
detail::ReadLock l(_archetypesMutex);
for (const auto & archetype : _archetypes) {
detail::ReadLock l(archetype.mutex);
assert(std::find(archetype.entities.begin(), archetype.entities.end(), id) == archetype.entities.end());
}
}
{
detail::ReadLock l(_entitiesMutex);
assert(id < _entities.size());
}
#endif
return Entity(id, 0, this);
}
void EntityManager::addComponent(Entity::ID id, size_t component) {
updateHasComponent(id, component, true);
}
void EntityManager::removeComponent(Entity::ID id, size_t component) {
updateHasComponent(id, component, false);
}
void EntityManager::updateHasComponent(Entity::ID id, size_t component, bool newHasComponent) {
{
detail::WriteLock l(_updatesMutex);
for (auto & update : _updates)
if (update.id == id) {
std::unique_lock<std::mutex> l(update.mutex);
update.newMask[component] = newHasComponent;
return;
}
}
Entity::Mask currentMask;
{
detail::ReadLock l(_entitiesMutex);
currentMask = _entities[id].mask;
}
auto updatedMask = currentMask;
updatedMask[component] = newHasComponent;
updateMask(id, updatedMask);
}
void EntityManager::updateMask(Entity::ID id, Entity::Mask newMask, bool ignoreOldMask) {
detail::WriteLock l(_updatesMutex);
if (_updatesLocked == 0)
doUpdateMask(id, newMask, ignoreOldMask);
else {
Update update;
update.id = id;
update.newMask = newMask;
update.ignoreOldMask = ignoreOldMask;
_updates.push_back(std::move(update));
}
}
void EntityManager::doAllUpdates() {
// _updatesMutex already locked
for (const auto & update : _updates)
doUpdateMask(update.id, update.newMask, update.ignoreOldMask);
_updates.clear();
for (const auto removal : _removals)
doRemove(removal.id);
_removals.clear();
}
void EntityManager::doUpdateMask(Entity::ID id, Entity::Mask newMask, bool ignoreOldMask) {
// _updatesMutex already locked
const auto oldMask = ignoreOldMask ? 0 : _entities[id].mask;
assert(newMask != oldMask);
bool removeDone = oldMask == 0;
bool addDone = newMask == 0;
{
detail::WriteLock l(_archetypesMutex);
for (auto & collection : _archetypes) {
if (removeDone && addDone)
break;
if (collection.mask == oldMask) {
const auto size = collection.entities.size();
if (size > 1) {
const auto it = std::find(collection.entities.begin(), collection.entities.end(), id);
std::iter_swap(it, collection.entities.begin() + size - 1);
}
collection.entities.pop_back();
collection.sorted = false;
removeDone = true;
}
if (collection.mask == newMask) {
collection.entities.emplace_back(id);
collection.sorted = false;
addDone = true;
}
}
if (!addDone)
_archetypes.emplace_back(newMask, id);
}
detail::WriteLock l(_entitiesMutex);
_entities[id].mask = newMask;
}
void EntityManager::doRemove(Entity::ID id) {
Entity::Mask mask;
{
detail::ReadLock entities(_entitiesMutex);
mask = _entities[id].mask;
}
SystemManager::removeEntity(EntityView(id, mask));
{
detail::ReadLock entities(_entitiesMutex);
mask = _entities[id].mask;
}
{
detail::ReadLock archetypes(_archetypesMutex);
for (auto & collection : _archetypes) {
if (collection.mask == mask) {
detail::WriteLock archetype(collection.mutex);
const auto tmp = std::find(collection.entities.begin(), collection.entities.end(), id);
if (collection.entities.size() > 1) {
std::swap(*tmp, collection.entities.back());
collection.sorted = false;
}
collection.entities.pop_back();
break;
}
}
}
{
detail::WriteLock entities(_entitiesMutex);
_entities[id].mask = 0;
_entities[id].active = false;
_entities[id].shouldActivateAfterInit = true;
}
detail::WriteLock l(_toReuseMutex);
_toReuse.emplace_back(id);
_toReuseSorted = false;
}
/*
** Collection
*/
EntityManager::EntityCollection EntityManager::getEntities() {
return EntityCollection{ *this };
}
EntityManager::EntityCollection::EntityIterator & EntityManager::EntityCollection::EntityIterator::operator++() {
++index;
detail::ReadLock l(em._entitiesMutex);
while (index < em._entities.size() && (em._entities[index].mask == 0 || !em._entities[index].active))
++index;
return *this;
}
bool EntityManager::EntityCollection::EntityIterator::operator!=(const EntityIterator & rhs) const {
// Use `<` as it will only be compared with `end()`, and there is a risk that new entities have been added since `end()` was called
return index < rhs.index;
}
Entity EntityManager::EntityCollection::EntityIterator::operator*() const {
detail::ReadLock l(em._entitiesMutex);
return Entity(index, em._entities[index].mask, &em);
}
EntityManager::EntityCollection::EntityIterator EntityManager::EntityCollection::begin() const {
size_t i = 0;
detail::ReadLock l(em._entitiesMutex);
while (i < em._entities.size() && (em._entities[i].mask == 0 || !em._entities[i].active))
++i;
return EntityIterator{ i, em };
}
EntityManager::EntityCollection::EntityIterator EntityManager::EntityCollection::end() const {
detail::ReadLock l(em._entitiesMutex);
return EntityIterator{ em._entities.size(), em };
}
EntityManager::EntityCollection::EntityCollection(EntityManager & em) : em(em) {
detail::WriteLock l(em._updatesMutex);
++em._updatesLocked;
}
EntityManager::EntityCollection::~EntityCollection() {
detail::WriteLock l(em._updatesMutex);
assert(em._updatesLocked != 0);
--em._updatesLocked;
if (em._updatesLocked == 0)
em.doAllUpdates();
}
}<commit_msg>fix toReuse not being populated on load<commit_after>#include "EntityManager.hpp"
#ifndef KENGINE_MAX_SAVE_PATH_LENGTH
# define KENGINE_MAX_SAVE_PATH_LENGTH 64
#endif
#ifndef KENGINE_MAX_COMPONENT_NAME_LENGTH
# define KENGINE_MAX_COMPONENT_NAME_LENGTH 64
#endif
namespace kengine {
Entity EntityManager::getEntity(Entity::ID id) {
detail::ReadLock l(_entitiesMutex);
return Entity(id, _entities[id].mask, this);
}
EntityView EntityManager::getEntity(Entity::ID id) const {
detail::ReadLock l(_entitiesMutex);
return EntityView(id, _entities[id].mask);
}
void EntityManager::removeEntity(EntityView e) {
removeEntity(e.id);
}
void EntityManager::removeEntity(Entity::ID id) {
detail::WriteLock l(_updatesMutex);
if (_updatesLocked) {
_removals.push_back({ id });
}
else
doRemove(id);
}
void EntityManager::setEntityActive(EntityView e, bool active) {
setEntityActive(e.id, active);
}
void EntityManager::setEntityActive(Entity::ID id, bool active) {
detail::WriteLock l(_entitiesMutex);
_entities[id].active = active;
_entities[id].shouldActivateAfterInit = active;
}
struct ComponentIDSave {
size_t id;
putils::string<KENGINE_MAX_COMPONENT_NAME_LENGTH> name;
};
void EntityManager::load(const char * directory) {
{
detail::WriteLock l(_archetypesMutex);
_archetypes.clear();
}
{
detail::WriteLock l(_toReuseMutex);
_toReuse.clear();
}
for (auto & e : getEntities())
SystemManager::removeEntity(e);
{
detail::ReadLock l(_components.mutex);
for (const auto &[_, meta] : _components.map)
meta->load(directory);
}
size_t idMap[KENGINE_COMPONENT_COUNT]; // index = new, value = old
for (auto & i : idMap)
i = (size_t)-1;
{
detail::ReadLock l(_components.mutex);
std::ifstream f(putils::string<KENGINE_MAX_SAVE_PATH_LENGTH>("%s/components.bin", directory), std::ifstream::binary);
assert(f);
size_t size;
f.read((char *)&size, sizeof(size));
for (size_t i = 0; i < size; ++i) {
ComponentIDSave save;
f.read((char *)&save, sizeof(save));
assert(f.gcount() == sizeof(save));
for (const auto & [_, meta] : _components.map)
if (meta->funcs.name == save.name) {
idMap[meta->id] = save.id;
break;
}
}
}
std::ifstream f(putils::string<KENGINE_MAX_SAVE_PATH_LENGTH>("%s/entities.bin", directory), std::ifstream::binary);
assert(f);
size_t size;
f.read((char *)&size, sizeof(size));
{
detail::WriteLock l(_entitiesMutex);
_entities.resize(size);
f.read((char *)_entities.data(), size * sizeof(_entities[0]));
}
for (auto & e : getEntities()) {
Entity::Mask tmp = 0;
for (size_t i = 0; i < KENGINE_COMPONENT_COUNT; ++i) {
const auto oldId = idMap[i];
tmp[i] = oldId == (size_t)-1 ? false : e.componentMask[oldId];
}
updateMask(e.id, tmp, true);
}
{
detail::ReadLock l(_entitiesMutex);
size_t id = 0;
for (const auto & e : _entities) {
if (e.mask == 0) {
detail::WriteLock l(_toReuseMutex);
_toReuse.emplace_back(id);
}
++id;
}
}
for (auto & e : getEntities())
SystemManager::registerEntity(e);
SystemManager::load(directory);
}
void EntityManager::save(const char * directory) const {
SystemManager::save(directory);
putils::vector<bool, KENGINE_COMPONENT_COUNT> serializable;
{
detail::ReadLock l(_components.mutex);
serializable.resize(_components.map.size());
for (const auto &[_, meta] : _components.map)
serializable[meta->id] = meta->save(directory);
// Save Component IDs
std::ofstream f(putils::string<KENGINE_MAX_SAVE_PATH_LENGTH>("%s/components.bin", directory), std::ofstream::binary);
const size_t size = _components.map.size();
f.write((const char *)&size, sizeof(size));
for (const auto &[_, meta] : _components.map) {
ComponentIDSave save;
save.id = meta->id;
save.name = meta->funcs.name;
f.write((const char *)&save, sizeof(save));
}
}
std::ofstream f(putils::string<KENGINE_MAX_SAVE_PATH_LENGTH>("%s/entities.bin", directory), std::ofstream::binary);
assert(f);
{
detail::ReadLock l(_entitiesMutex);
const auto size = _entities.size();
f.write((const char *)&size, sizeof(size));
for (EntityMetadata e : _entities) {
for (size_t i = 0; i < serializable.size(); ++i)
e.mask[i] = e.mask[i] && serializable[i];
f.write((const char *)&e, sizeof(e));
}
}
}
Entity EntityManager::alloc() {
{
detail::ReadLock l(_toReuseMutex);
if (_toReuse.empty()) {
detail::WriteLock l(_entitiesMutex);
const auto id = _entities.size();
_entities.push_back({ false, 0 });
return Entity(id, 0, this);
}
}
Entity::ID id;
{
detail::WriteLock l(_toReuseMutex);
if (!_toReuseSorted) {
std::sort(_toReuse.begin(), _toReuse.end(), std::greater<Entity::ID>());
_toReuseSorted = true;
}
id = _toReuse.back();
_toReuse.pop_back();
}
#ifndef NDEBUG
{
detail::ReadLock l(_archetypesMutex);
for (const auto & archetype : _archetypes) {
detail::ReadLock l(archetype.mutex);
assert(std::find(archetype.entities.begin(), archetype.entities.end(), id) == archetype.entities.end());
}
}
{
detail::ReadLock l(_entitiesMutex);
assert(id < _entities.size());
}
#endif
return Entity(id, 0, this);
}
void EntityManager::addComponent(Entity::ID id, size_t component) {
updateHasComponent(id, component, true);
}
void EntityManager::removeComponent(Entity::ID id, size_t component) {
updateHasComponent(id, component, false);
}
void EntityManager::updateHasComponent(Entity::ID id, size_t component, bool newHasComponent) {
{
detail::WriteLock l(_updatesMutex);
for (auto & update : _updates)
if (update.id == id) {
std::unique_lock<std::mutex> l(update.mutex);
update.newMask[component] = newHasComponent;
return;
}
}
Entity::Mask currentMask;
{
detail::ReadLock l(_entitiesMutex);
currentMask = _entities[id].mask;
}
auto updatedMask = currentMask;
updatedMask[component] = newHasComponent;
updateMask(id, updatedMask);
}
void EntityManager::updateMask(Entity::ID id, Entity::Mask newMask, bool ignoreOldMask) {
detail::WriteLock l(_updatesMutex);
if (_updatesLocked == 0)
doUpdateMask(id, newMask, ignoreOldMask);
else {
Update update;
update.id = id;
update.newMask = newMask;
update.ignoreOldMask = ignoreOldMask;
_updates.push_back(std::move(update));
}
}
void EntityManager::doAllUpdates() {
// _updatesMutex already locked
for (const auto & update : _updates)
doUpdateMask(update.id, update.newMask, update.ignoreOldMask);
_updates.clear();
for (const auto removal : _removals)
doRemove(removal.id);
_removals.clear();
}
void EntityManager::doUpdateMask(Entity::ID id, Entity::Mask newMask, bool ignoreOldMask) {
// _updatesMutex already locked
const auto oldMask = ignoreOldMask ? 0 : _entities[id].mask;
assert(newMask != oldMask);
bool removeDone = oldMask == 0;
bool addDone = newMask == 0;
{
detail::WriteLock l(_archetypesMutex);
for (auto & collection : _archetypes) {
if (removeDone && addDone)
break;
if (collection.mask == oldMask) {
const auto size = collection.entities.size();
if (size > 1) {
const auto it = std::find(collection.entities.begin(), collection.entities.end(), id);
std::iter_swap(it, collection.entities.begin() + size - 1);
}
collection.entities.pop_back();
collection.sorted = false;
removeDone = true;
}
if (collection.mask == newMask) {
collection.entities.emplace_back(id);
collection.sorted = false;
addDone = true;
}
}
if (!addDone)
_archetypes.emplace_back(newMask, id);
}
detail::WriteLock l(_entitiesMutex);
_entities[id].mask = newMask;
}
void EntityManager::doRemove(Entity::ID id) {
Entity::Mask mask;
{
detail::ReadLock entities(_entitiesMutex);
mask = _entities[id].mask;
}
SystemManager::removeEntity(EntityView(id, mask));
{
detail::ReadLock entities(_entitiesMutex);
mask = _entities[id].mask;
}
{
detail::ReadLock archetypes(_archetypesMutex);
for (auto & collection : _archetypes) {
if (collection.mask == mask) {
detail::WriteLock archetype(collection.mutex);
const auto tmp = std::find(collection.entities.begin(), collection.entities.end(), id);
if (collection.entities.size() > 1) {
std::swap(*tmp, collection.entities.back());
collection.sorted = false;
}
collection.entities.pop_back();
break;
}
}
}
{
detail::WriteLock entities(_entitiesMutex);
_entities[id].mask = 0;
_entities[id].active = false;
_entities[id].shouldActivateAfterInit = true;
}
detail::WriteLock l(_toReuseMutex);
_toReuse.emplace_back(id);
_toReuseSorted = false;
}
/*
** Collection
*/
EntityManager::EntityCollection EntityManager::getEntities() {
return EntityCollection{ *this };
}
EntityManager::EntityCollection::EntityIterator & EntityManager::EntityCollection::EntityIterator::operator++() {
++index;
detail::ReadLock l(em._entitiesMutex);
while (index < em._entities.size() && (em._entities[index].mask == 0 || !em._entities[index].active))
++index;
return *this;
}
bool EntityManager::EntityCollection::EntityIterator::operator!=(const EntityIterator & rhs) const {
// Use `<` as it will only be compared with `end()`, and there is a risk that new entities have been added since `end()` was called
return index < rhs.index;
}
Entity EntityManager::EntityCollection::EntityIterator::operator*() const {
detail::ReadLock l(em._entitiesMutex);
return Entity(index, em._entities[index].mask, &em);
}
EntityManager::EntityCollection::EntityIterator EntityManager::EntityCollection::begin() const {
size_t i = 0;
detail::ReadLock l(em._entitiesMutex);
while (i < em._entities.size() && (em._entities[i].mask == 0 || !em._entities[i].active))
++i;
return EntityIterator{ i, em };
}
EntityManager::EntityCollection::EntityIterator EntityManager::EntityCollection::end() const {
detail::ReadLock l(em._entitiesMutex);
return EntityIterator{ em._entities.size(), em };
}
EntityManager::EntityCollection::EntityCollection(EntityManager & em) : em(em) {
detail::WriteLock l(em._updatesMutex);
++em._updatesLocked;
}
EntityManager::EntityCollection::~EntityCollection() {
detail::WriteLock l(em._updatesMutex);
assert(em._updatesLocked != 0);
--em._updatesLocked;
if (em._updatesLocked == 0)
em.doAllUpdates();
}
}<|endoftext|>
|
<commit_before>#include "common.h"
#include "watcher.h"
#include <stdlib.h>
#include <stdio.h>
#include <Psapi.h>
#pragma comment (lib, "psapi.lib")
namespace NodeJudger {
#define EXCEPTION_WX86_BREAKPOINT 0x4000001F
#define MAX_TIME_LIMIT_DELAY 200
const bool __WATCHER_PRINT_DEBUG = (GetEnvironmentVar("JUDGE_DEBUG") == "true");
#define MAX(a, b) ((a) > (b) ? (a) : (b)
inline __int64 GetRunTime_(HANDLE process)
{
_FILETIME create_time, exit_time, kernel_time, user_time;
__int64* ut;
if(GetProcessTimes(process, &create_time, &exit_time, &kernel_time, &user_time))
{
ut = reinterpret_cast<__int64*>(&user_time);
return (__int64)((*ut) / 10000);
}
return -1;
}
__int64 GetRunMemo_(HANDLE process)
{
PROCESS_MEMORY_COUNTERS memo_counter;
memo_counter.cb = sizeof(PROCESS_MEMORY_COUNTERS);
if(GetProcessMemoryInfo(process, &memo_counter, sizeof(PROCESS_MEMORY_COUNTERS)))
{
return memo_counter.PagefileUsage / 1024;
}
return -1;
}
void ExitAndSetError(HANDLE process, CodeState& code_state, StateEnum state_enum, const char* code = NULL)
{
DWORD process_id = GetProcessId(process);
if(process_id) DebugActiveProcessStop(process_id);
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=vs.85).aspx
//
// TerminateProcess is asynchronous; it initiates termination and returns immediately. If you
// need to be sure the process has terminated, call the WaitForSingleObject function with a
// handle to the process.
TerminateProcess(process, 4);
WaitForSingleObject(process, 2000);
code_state.state = state_enum;
if(code && strlen(code) != 0)
{
strcpy(code_state.error_code, code);
}
}
void SetRuntimeErrorCode_(CodeState& code_state, DWORD code)
{
switch(code)
{
case EXCEPTION_ACCESS_VIOLATION:
{
strcpy(code_state.error_code, "ACCESS_VIOLATION");
break;
}
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
{
strcpy(code_state.error_code, "ARRAY_BOUNDS_EXCEEDED");
break;
}
case EXCEPTION_FLT_DENORMAL_OPERAND:
{
strcpy(code_state.error_code, "FLOAT_DENORMAL_OPERAND");
break;
}
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
{
strcpy(code_state.error_code, "FLOAT_DIVIDE_BY_ZERO");
break;
}
case EXCEPTION_FLT_OVERFLOW:
{
strcpy(code_state.error_code, "FLOAT_OVERFLOW");
break;
}
case EXCEPTION_FLT_UNDERFLOW:
{
strcpy(code_state.error_code, "FLOAT_UNDERFLOW");
break;
}
case EXCEPTION_INT_DIVIDE_BY_ZERO:
{
strcpy(code_state.error_code, "INTEGER_DIVIDE_BY_ZERO");
break;
}
case EXCEPTION_INT_OVERFLOW:
{
strcpy(code_state.error_code, "INTEGER_OVERFLOW");
break;
}
case EXCEPTION_STACK_OVERFLOW:
{
strcpy(code_state.error_code, "STACK_OVERFLOW");
break;
}
default:
{
char temp[32];
sprintf(temp, "OTHER_ERRORS_0x%.8X", code);
strcpy(code_state.error_code, temp);
break;
}
}
}
bool WatchProcess(const HANDLE process,
const __int64 time_limit,
const __size memo_limit,
CodeState& code_state)
{
__int64 run_time = 0;
__size run_memo = 0;
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms679308(v=vs.85).aspx
//
// Describes a debugging event.
//
// typedef struct _DEBUG_EVENT {
// DWORD dwDebugEventCode;
// DWORD dwProcessId;
// DWORD dwThreadId;
// union {
// EXCEPTION_DEBUG_INFO Exception;
// CREATE_THREAD_DEBUG_INFO CreateThread;
// CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
// EXIT_THREAD_DEBUG_INFO ExitThread;
// EXIT_PROCESS_DEBUG_INFO ExitProcess;
// LOAD_DLL_DEBUG_INFO LoadDll;
// UNLOAD_DLL_DEBUG_INFO UnloadDll;
// OUTPUT_DEBUG_STRING_INFO DebugString;
// RIP_INFO RipInfo;
// } u;
// } DEBUG_EVENT, *LPDEBUG_EVENT;
DEBUG_EVENT dbe;
while(true)
{
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms681423(v=vs.85).aspx
//
// Waits for a debugging event to occur in a process being debugged.
//
// If the function succeeds, the return value is nonzero.
// If the function fails, the return value is zero.To get extended error information, call GetLastError.
BOOL flag = WaitForDebugEvent(&dbe, (DWORD)time_limit + MAX_TIME_LIMIT_DELAY - run_time);
if(!flag)
{
std::string error = "Cannot wait for debug event: " + GetLastErrorAsString();
code_state.exe_time = time_limit + MAX_TIME_LIMIT_DELAY;
code_state.exe_memory = MAX(GetRunMemo_(process), code_state.exe_memory);
ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_2, error.c_str());
return false;
}
// refer to http://www.debuginfo.com/examples/src/DebugEvents.cpp
//
// close some handles inside dbe
switch(dbe.dwDebugEventCode)
{
case CREATE_PROCESS_DEBUG_EVENT:
if(__WATCHER_PRINT_DEBUG)
{
printf("Event: Process creation\n");
printf(" CREATE_PROCESS_DEBUG_INFO members:\n");
printf(" hFile: %08p\n", dbe.u.CreateProcessInfo.hFile);
printf(" hProcess: %08p\n", dbe.u.CreateProcessInfo.hProcess);
printf(" hThread %08p\n", dbe.u.CreateProcessInfo.hThread);
}
// With this event, the debugger receives the following handles:
// CREATE_PROCESS_DEBUG_INFO.hProcess - debuggee process handle
// CREATE_PROCESS_DEBUG_INFO.hThread - handle to the initial thread of the debuggee process
// CREATE_PROCESS_DEBUG_INFO.hFile - handle to the executable file that was
// used to create the debuggee process (.EXE file)
//
// hProcess and hThread handles will be closed by the operating system
// when the debugger calls ContinueDebugEvent after receiving
// EXIT_PROCESS_DEBUG_EVENT for the given process
//
// hFile handle should be closed by the debugger, when the handle
// is no longer needed
SAFE_CLOSE_HANDLE(dbe.u.CreateProcessInfo.hFile);
break;
case CREATE_THREAD_DEBUG_EVENT:
// With this event, the debugger receives the following handle:
// CREATE_THREAD_DEBUG_INFO.hThread - handle to the thread that has been created
//
// This handle will be closed by the operating system
// when the debugger calls ContinueDebugEvent after receiving
// EXIT_THREAD_DEBUG_EVENT for the given thread
break;
case LOAD_DLL_DEBUG_EVENT:
{
std::string dll_name = GetDLLNameFromDebug(dbe.u.LoadDll);
if(__WATCHER_PRINT_DEBUG)
{
printf("Event: DLL loaded\n");
printf(" LOAD_DLL_DEBUG_INFO members:\n");
printf(" hFile: %08p\n", dbe.u.LoadDll.hFile);
printf(" lpBaseOfDll: %08p\n", dbe.u.LoadDll.lpBaseOfDll);
printf(" DLLName: %s\n", dll_name.c_str());
}
// With this event, the debugger receives the following handle:
// LOAD_DLL_DEBUG_INFO.hFile - handle to the DLL file
//
// This handle should be closed by the debugger, when the handle
// is no longer needed
SAFE_CLOSE_HANDLE(dbe.u.LoadDll.hFile);
// And what's more
// users are not allowed to load DLL
if(dll_name.find("\\ntdll.dll") == std::string::npos &&
dll_name.find("\\kernel32.dll") == std::string::npos &&
dll_name.find("\\KernelBase.dll") == std::string::npos &&
dll_name.find("\\msvcrt.dll") == std::string::npos &&
dll_name.find("\\wow64.dll") == std::string::npos &&
dll_name.find("\\wow64win.dll") == std::string::npos &&
dll_name.find("\\wow64cpu.dll") == std::string::npos &&
dll_name.find("\\user32.dll") == std::string::npos)
{
std::string error = "Code is up to load DLL.";
code_state.exe_time = 0;
code_state.exe_memory = 0;
ExitAndSetError(process, code_state, DANGEROUS_CODE, error.c_str());
return false;
}
}
default: break;
}
// get the run time
run_time = GetRunTime_(process);
if(-1 == run_time)
{
std::string error = "Cannot get running time: " + GetLastErrorAsString();
code_state.exe_time = 0;
code_state.exe_memory = MAX(GetRunMemo_(process), code_state.exe_memory);
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
return false;
}
// get the run memory
run_memo = GetRunMemo_(process);
if(-1 == run_memo)
{
std::string error = "Cannot get occupied memory: " + GetLastErrorAsString();
code_state.exe_time = run_time;
code_state.exe_memory = 0;
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
return false;
}
code_state.exe_time = run_time;
code_state.exe_memory = MAX(code_state.exe_memory, run_memo);
if(run_time > time_limit)
{
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_1);
return false;
}
if(run_memo > memo_limit)
{
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, MEMORY_LIMIT_EXCEEDED);
return false;
}
// do some reaction via each DEBUG_EVENT
switch(dbe.dwDebugEventCode)
{
case EXIT_PROCESS_DEBUG_EVENT:
code_state.state = FINISHED;
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
return true;
case EXCEPTION_DEBUG_EVENT:
if(dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT &&
dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_WX86_BREAKPOINT)
{
SetRuntimeErrorCode_(code_state, dbe.u.Exception.ExceptionRecord.ExceptionCode);
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_EXCEPTION_NOT_HANDLED);
ExitAndSetError(process, code_state, RUNTIME_ERROR);
return false;
}
break;
default: break;
}
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
code_state.state = CONTINUE;
}
}
};<commit_msg>fix: a missing bracket<commit_after>#include "common.h"
#include "watcher.h"
#include <stdlib.h>
#include <stdio.h>
#include <Psapi.h>
#pragma comment (lib, "psapi.lib")
namespace NodeJudger {
#define EXCEPTION_WX86_BREAKPOINT 0x4000001F
#define MAX_TIME_LIMIT_DELAY 200
const bool __WATCHER_PRINT_DEBUG = (GetEnvironmentVar("JUDGE_DEBUG") == "true");
#define MAX(a, b) ((a) > (b) ? (a) : (b))
inline __int64 GetRunTime_(HANDLE process)
{
_FILETIME create_time, exit_time, kernel_time, user_time;
__int64* ut;
if(GetProcessTimes(process, &create_time, &exit_time, &kernel_time, &user_time))
{
ut = reinterpret_cast<__int64*>(&user_time);
return (__int64)((*ut) / 10000);
}
return -1;
}
__int64 GetRunMemo_(HANDLE process)
{
PROCESS_MEMORY_COUNTERS memo_counter;
memo_counter.cb = sizeof(PROCESS_MEMORY_COUNTERS);
if(GetProcessMemoryInfo(process, &memo_counter, sizeof(PROCESS_MEMORY_COUNTERS)))
{
return memo_counter.PagefileUsage / 1024;
}
return -1;
}
void ExitAndSetError(HANDLE process, CodeState& code_state, StateEnum state_enum, const char* code = NULL)
{
DWORD process_id = GetProcessId(process);
if(process_id) DebugActiveProcessStop(process_id);
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms686714(v=vs.85).aspx
//
// TerminateProcess is asynchronous; it initiates termination and returns immediately. If you
// need to be sure the process has terminated, call the WaitForSingleObject function with a
// handle to the process.
TerminateProcess(process, 4);
WaitForSingleObject(process, 2000);
code_state.state = state_enum;
if(code && strlen(code) != 0)
{
strcpy(code_state.error_code, code);
}
}
void SetRuntimeErrorCode_(CodeState& code_state, DWORD code)
{
switch(code)
{
case EXCEPTION_ACCESS_VIOLATION:
{
strcpy(code_state.error_code, "ACCESS_VIOLATION");
break;
}
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
{
strcpy(code_state.error_code, "ARRAY_BOUNDS_EXCEEDED");
break;
}
case EXCEPTION_FLT_DENORMAL_OPERAND:
{
strcpy(code_state.error_code, "FLOAT_DENORMAL_OPERAND");
break;
}
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
{
strcpy(code_state.error_code, "FLOAT_DIVIDE_BY_ZERO");
break;
}
case EXCEPTION_FLT_OVERFLOW:
{
strcpy(code_state.error_code, "FLOAT_OVERFLOW");
break;
}
case EXCEPTION_FLT_UNDERFLOW:
{
strcpy(code_state.error_code, "FLOAT_UNDERFLOW");
break;
}
case EXCEPTION_INT_DIVIDE_BY_ZERO:
{
strcpy(code_state.error_code, "INTEGER_DIVIDE_BY_ZERO");
break;
}
case EXCEPTION_INT_OVERFLOW:
{
strcpy(code_state.error_code, "INTEGER_OVERFLOW");
break;
}
case EXCEPTION_STACK_OVERFLOW:
{
strcpy(code_state.error_code, "STACK_OVERFLOW");
break;
}
default:
{
char temp[32];
sprintf(temp, "OTHER_ERRORS_0x%.8X", code);
strcpy(code_state.error_code, temp);
break;
}
}
}
bool WatchProcess(const HANDLE process,
const __int64 time_limit,
const __size memo_limit,
CodeState& code_state)
{
__int64 run_time = 0;
__size run_memo = 0;
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms679308(v=vs.85).aspx
//
// Describes a debugging event.
//
// typedef struct _DEBUG_EVENT {
// DWORD dwDebugEventCode;
// DWORD dwProcessId;
// DWORD dwThreadId;
// union {
// EXCEPTION_DEBUG_INFO Exception;
// CREATE_THREAD_DEBUG_INFO CreateThread;
// CREATE_PROCESS_DEBUG_INFO CreateProcessInfo;
// EXIT_THREAD_DEBUG_INFO ExitThread;
// EXIT_PROCESS_DEBUG_INFO ExitProcess;
// LOAD_DLL_DEBUG_INFO LoadDll;
// UNLOAD_DLL_DEBUG_INFO UnloadDll;
// OUTPUT_DEBUG_STRING_INFO DebugString;
// RIP_INFO RipInfo;
// } u;
// } DEBUG_EVENT, *LPDEBUG_EVENT;
DEBUG_EVENT dbe;
while(true)
{
// refer to https://msdn.microsoft.com/en-us/library/windows/desktop/ms681423(v=vs.85).aspx
//
// Waits for a debugging event to occur in a process being debugged.
//
// If the function succeeds, the return value is nonzero.
// If the function fails, the return value is zero.To get extended error information, call GetLastError.
BOOL flag = WaitForDebugEvent(&dbe, (DWORD)time_limit + MAX_TIME_LIMIT_DELAY - run_time);
if(!flag)
{
std::string error = "Cannot wait for debug event: " + GetLastErrorAsString();
code_state.exe_time = time_limit + MAX_TIME_LIMIT_DELAY;
code_state.exe_memory = MAX(GetRunMemo_(process), code_state.exe_memory);
ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_2, error.c_str());
return false;
}
// refer to http://www.debuginfo.com/examples/src/DebugEvents.cpp
//
// close some handles inside dbe
switch(dbe.dwDebugEventCode)
{
case CREATE_PROCESS_DEBUG_EVENT:
if(__WATCHER_PRINT_DEBUG)
{
printf("Event: Process creation\n");
printf(" CREATE_PROCESS_DEBUG_INFO members:\n");
printf(" hFile: %08p\n", dbe.u.CreateProcessInfo.hFile);
printf(" hProcess: %08p\n", dbe.u.CreateProcessInfo.hProcess);
printf(" hThread %08p\n", dbe.u.CreateProcessInfo.hThread);
}
// With this event, the debugger receives the following handles:
// CREATE_PROCESS_DEBUG_INFO.hProcess - debuggee process handle
// CREATE_PROCESS_DEBUG_INFO.hThread - handle to the initial thread of the debuggee process
// CREATE_PROCESS_DEBUG_INFO.hFile - handle to the executable file that was
// used to create the debuggee process (.EXE file)
//
// hProcess and hThread handles will be closed by the operating system
// when the debugger calls ContinueDebugEvent after receiving
// EXIT_PROCESS_DEBUG_EVENT for the given process
//
// hFile handle should be closed by the debugger, when the handle
// is no longer needed
SAFE_CLOSE_HANDLE(dbe.u.CreateProcessInfo.hFile);
break;
case CREATE_THREAD_DEBUG_EVENT:
// With this event, the debugger receives the following handle:
// CREATE_THREAD_DEBUG_INFO.hThread - handle to the thread that has been created
//
// This handle will be closed by the operating system
// when the debugger calls ContinueDebugEvent after receiving
// EXIT_THREAD_DEBUG_EVENT for the given thread
break;
case LOAD_DLL_DEBUG_EVENT:
{
std::string dll_name = GetDLLNameFromDebug(dbe.u.LoadDll);
if(__WATCHER_PRINT_DEBUG)
{
printf("Event: DLL loaded\n");
printf(" LOAD_DLL_DEBUG_INFO members:\n");
printf(" hFile: %08p\n", dbe.u.LoadDll.hFile);
printf(" lpBaseOfDll: %08p\n", dbe.u.LoadDll.lpBaseOfDll);
printf(" DLLName: %s\n", dll_name.c_str());
}
// With this event, the debugger receives the following handle:
// LOAD_DLL_DEBUG_INFO.hFile - handle to the DLL file
//
// This handle should be closed by the debugger, when the handle
// is no longer needed
SAFE_CLOSE_HANDLE(dbe.u.LoadDll.hFile);
// And what's more
// users are not allowed to load DLL
if(dll_name.find("\\ntdll.dll") == std::string::npos &&
dll_name.find("\\kernel32.dll") == std::string::npos &&
dll_name.find("\\KernelBase.dll") == std::string::npos &&
dll_name.find("\\msvcrt.dll") == std::string::npos &&
dll_name.find("\\wow64.dll") == std::string::npos &&
dll_name.find("\\wow64win.dll") == std::string::npos &&
dll_name.find("\\wow64cpu.dll") == std::string::npos &&
dll_name.find("\\user32.dll") == std::string::npos)
{
std::string error = "Code is up to load DLL.";
code_state.exe_time = 0;
code_state.exe_memory = 0;
ExitAndSetError(process, code_state, DANGEROUS_CODE, error.c_str());
return false;
}
}
default: break;
}
// get the run time
run_time = GetRunTime_(process);
if(-1 == run_time)
{
std::string error = "Cannot get running time: " + GetLastErrorAsString();
code_state.exe_time = 0;
code_state.exe_memory = MAX(GetRunMemo_(process), code_state.exe_memory);
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
return false;
}
// get the run memory
run_memo = GetRunMemo_(process);
if(-1 == run_memo)
{
std::string error = "Cannot get occupied memory: " + GetLastErrorAsString();
code_state.exe_time = run_time;
code_state.exe_memory = 0;
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, SYSTEM_ERROR, error.c_str());
return false;
}
code_state.exe_time = run_time;
code_state.exe_memory = MAX(code_state.exe_memory, run_memo);
if(run_time > time_limit)
{
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, TIME_LIMIT_EXCEEDED_1);
return false;
}
if(run_memo > memo_limit)
{
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
ExitAndSetError(process, code_state, MEMORY_LIMIT_EXCEEDED);
return false;
}
// do some reaction via each DEBUG_EVENT
switch(dbe.dwDebugEventCode)
{
case EXIT_PROCESS_DEBUG_EVENT:
code_state.state = FINISHED;
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
return true;
case EXCEPTION_DEBUG_EVENT:
if(dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT &&
dbe.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_WX86_BREAKPOINT)
{
SetRuntimeErrorCode_(code_state, dbe.u.Exception.ExceptionRecord.ExceptionCode);
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_EXCEPTION_NOT_HANDLED);
ExitAndSetError(process, code_state, RUNTIME_ERROR);
return false;
}
break;
default: break;
}
ContinueDebugEvent(dbe.dwProcessId, dbe.dwThreadId, DBG_CONTINUE);
code_state.state = CONTINUE;
}
}
};<|endoftext|>
|
<commit_before>/* Generated automatically by ppremake 1.11 from Sources.pp. */
/* ################################# DO NOT EDIT ########################### */
#include "fmod_audio_composite1.cxx"
<commit_msg>remove accidentally committed file<commit_after><|endoftext|>
|
<commit_before>#include <boost/function.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/assert.hpp>
#include <math.h>
#include <moveit/robot_state/conversions.h>
#include <moveit/trajectory_processing/iterative_time_parameterization.h>
#include <moveit_cartesian_plan_plugin/generate_cartesian_path.h>
#include <moveit/planning_interface/planning_interface.h>
#include <moveit/planning_scene/planning_scene.h>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit_msgs/PlanningScene.h>
#include <ros/ros.h>
#include <geometry_msgs/PoseArray.h>
GenerateCartesianPath::GenerateCartesianPath(QObject *parent)
{
//to add initializations
init();
}
GenerateCartesianPath::~GenerateCartesianPath()
{
/*! The destructor resets the moveit_group_ and the kinematic_state of the robot.
*/
moveit_group_.reset();
kinematic_state.reset();
robot_model_loader.reset();
kmodel.reset();
}
void GenerateCartesianPath::init()
{
/*! Initialize the MoveIt parameters:
- MoveIt group
- Kinematic State is the current kinematic congiguration of the Robot
- Robot model which handles getting the Robot Model
- Joint Model group which are necessary for checking if Way-Point is outside the IK Solution
.
*/
selected_plan_group = 0;
robot_model_loader = RobotModelLoaderPtr(new robot_model_loader::RobotModelLoader("robot_description"));
kmodel = robot_model_loader->getModel();
//kmodel = robot_model::RobotModelConstPtr(new moveit::core::RobotModel(robot_model_loader->getModel()));
//group_names = kmodel->getJointModelGroupNames();
end_eff_joint_groups = kmodel->getEndEffectors();
ROS_INFO_STREAM("size of the end effectors is: "<<end_eff_joint_groups.size());
if (end_eff_joint_groups.empty())
{
group_names = kmodel->getJointModelGroupNames();
}
else
{
for(int i=0;i<end_eff_joint_groups.size();i++)
{
// const std::pair< std::string, std::string > & parent_group_name = end_eff_joint_groups.at(i)->getEndEffectorParentGroup();
if(end_eff_joint_groups.at(i)->isChain())
{
const std::string& parent_group_name = end_eff_joint_groups.at(i)->getName();
group_names.push_back(parent_group_name);
ROS_INFO_STREAM("Group name:"<< group_names.at(i));
}
else
{
ROS_INFO_STREAM("This group is not a chain. Find the parent of the group");
const std::pair< std::string, std::string > & parent_group_name = end_eff_joint_groups.at(i)->getEndEffectorParentGroup();
group_names.push_back(parent_group_name.first);
}
}
}
ROS_INFO_STREAM("Group name:"<< group_names[selected_plan_group]);
moveit_group_ = MoveGroupPtr(new move_group_interface::MoveGroup(group_names[selected_plan_group]));
kinematic_state = moveit::core::RobotStatePtr(new robot_state::RobotState(kmodel));
kinematic_state->setToDefaultValues();
joint_model_group = kmodel->getJointModelGroup(group_names[selected_plan_group]);
}
void GenerateCartesianPath::setCartParams(double plan_time_,double cart_step_size_, double cart_jump_thresh_, bool moveit_replan_,bool avoid_collisions_)
{
/*! Set the necessary parameters for the MoveIt and the Cartesian Path Planning.
These parameters correspond to the ones that the user has entered or the default ones before the execution of the Cartesian Path Planner.
*/
ROS_INFO_STREAM("MoveIt and Cartesian Path parameters from UI:\n MoveIt Plan Time:"<<plan_time_
<<"\n Cartesian Path Step Size:"<<cart_step_size_
<<"\n Jump Threshold:"<<cart_jump_thresh_
<<"\n Replanning:"<<moveit_replan_
<<"\n Avoid Collisions:"<<avoid_collisions_);
PLAN_TIME_ = plan_time_;
MOVEIT_REPLAN_ = moveit_replan_;
CART_STEP_SIZE_ = cart_step_size_;
CART_JUMP_THRESH_ = cart_jump_thresh_;
AVOID_COLLISIONS_ = avoid_collisions_;
}
void GenerateCartesianPath::moveToPose(std::vector<geometry_msgs::Pose> waypoints)
{
/*!
*/
Q_EMIT cartesianPathExecuteStarted();
moveit_group_->setPlanningTime(PLAN_TIME_);
moveit_group_->allowReplanning (MOVEIT_REPLAN_);
move_group_interface::MoveGroup::Plan plan;
moveit_msgs::RobotTrajectory trajectory_;
double fraction = moveit_group_->computeCartesianPath(waypoints,CART_STEP_SIZE_,CART_JUMP_THRESH_,trajectory_,AVOID_COLLISIONS_);
robot_trajectory::RobotTrajectory rt(kmodel, group_names[selected_plan_group]);
rt.setRobotTrajectoryMsg(*kinematic_state, trajectory_);
ROS_INFO_STREAM("Pose reference frame: " << moveit_group_->getPoseReferenceFrame ());
// Thrid create a IterativeParabolicTimeParameterization object
trajectory_processing::IterativeParabolicTimeParameterization iptp;
bool success = iptp.computeTimeStamps(rt);
ROS_INFO("Computed time stamp %s",success?"SUCCEDED":"FAILED");
// Get RobotTrajectory_msg from RobotTrajectory
rt.getRobotTrajectoryMsg(trajectory_);
// Finally plan and execute the trajectory
plan.trajectory_ = trajectory_;
ROS_INFO("Visualizing plan (cartesian path) (%.2f%% acheived)",fraction * 100.0);
Q_EMIT cartesianPathCompleted(fraction);
moveit_group_->execute(plan);
kinematic_state = moveit_group_->getCurrentState();
Q_EMIT cartesianPathExecuteFinished();
}
void GenerateCartesianPath::cartesianPathHandler(std::vector<geometry_msgs::Pose> waypoints)
{
/*! Since the execution of the Cartesian path is time consuming and can lead to locking up of the Plugin and the RViz enviroment the function for executing the Cartesian Path Plan has been placed in a separtate thread.
This prevents the RViz and the Plugin to lock.
*/
ROS_INFO("Starting concurrent process for Cartesian Path");
QFuture<void> future = QtConcurrent::run(this, &GenerateCartesianPath::moveToPose, waypoints);
}
void GenerateCartesianPath::checkWayPointValidity(const geometry_msgs::Pose& waypoint,const int point_number)
{
/*! This function is called every time the user updates the pose of the Way-Point and checks if the Way-Point is within the valid IK solution for the Robot.
In the case when a point is outside the valid IK solution this function send a signal to the RViz enviroment to update the color of the Way-Point.
*/
bool found_ik = kinematic_state->setFromIK(joint_model_group, waypoint, 3, 0.006);
if(found_ik)
{
Q_EMIT wayPointOutOfIK(point_number,0);
}
else
{
// ROS_INFO("Did not find IK solution for waypoint %d",point_number);
Q_EMIT wayPointOutOfIK(point_number,1);
}
}
void GenerateCartesianPath::initRviz_done()
{
/*! Once the initialization of the RViz is has finished, this function sends the pose of the robot end-effector and the name of the base frame to the RViz enviroment.
The RViz enviroment sets the User Interactive Marker pose and Add New Way-Point RQT Layout default values based on the end-effector starting position.
The transformation frame of the InteractiveMarker is set based on the robot PoseReferenceFrame.
*/
ROS_INFO("RViz is done now we need to emit the signal");
if(moveit_group_->getEndEffectorLink().empty())
{
ROS_INFO("End effector link is empty");
const std::vector< std::string > & joint_names = joint_model_group->getLinkModelNames();
for(int i=0;i<joint_names.size();i++)
{
ROS_INFO_STREAM("Link " << i << " name: "<< joint_names.at(i));
}
const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform(joint_names.at(0));
//tf::Transform end_effector;
tf::transformEigenToTF(end_effector_state, end_effector);
Q_EMIT getRobotModelFrame_signal(moveit_group_->getPoseReferenceFrame(),end_effector);
}
else
{
ROS_INFO("End effector link is not empty");
const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform(moveit_group_->getEndEffectorLink());
//tf::Transform end_effector;
tf::transformEigenToTF(end_effector_state, end_effector);
Q_EMIT getRobotModelFrame_signal(moveit_group_->getPoseReferenceFrame(),end_effector);
}
Q_EMIT sendCartPlanGroup(group_names);
}
void GenerateCartesianPath::moveToHome()
{
geometry_msgs::Pose home_pose;
tf::poseTFToMsg(end_effector,home_pose);
std::vector<geometry_msgs::Pose> waypoints;
waypoints.push_back(home_pose);
cartesianPathHandler(waypoints);
}
void GenerateCartesianPath::getSelectedGroupIndex(int index)
{
selected_plan_group = index;
ROS_INFO_STREAM("selected name is:"<<group_names[selected_plan_group]);
moveit_group_.reset();
kinematic_state.reset();
moveit_group_ = MoveGroupPtr(new move_group_interface::MoveGroup(group_names[selected_plan_group]));
kinematic_state = moveit::core::RobotStatePtr(new robot_state::RobotState(kmodel));
kinematic_state->setToDefaultValues();
joint_model_group = kmodel->getJointModelGroup(group_names[selected_plan_group]);
if(moveit_group_->getEndEffectorLink().empty())
{
ROS_INFO("End effector link is empty");
const std::vector< std::string > & joint_names = joint_model_group->getLinkModelNames();
for(int i=0;i<joint_names.size();i++)
{
ROS_INFO_STREAM("Link " << i << " name: "<< joint_names.at(i));
}
const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform(joint_names.at(0));
//tf::Transform end_effector;
tf::transformEigenToTF(end_effector_state, end_effector);
Q_EMIT getRobotModelFrame_signal(moveit_group_->getPoseReferenceFrame(),end_effector);
}
else
{
ROS_INFO("End effector link is not empty");
const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform(moveit_group_->getEndEffectorLink());
//tf::Transform end_effector;
tf::transformEigenToTF(end_effector_state, end_effector);
Q_EMIT getRobotModelFrame_signal(moveit_group_->getPoseReferenceFrame(),end_effector);
}
}<commit_msg>Further imporvement of setting up starting group for different moveit configuration robots. Checking for end effectors and setting planning group only if the end-effector is a kinematic chain.<commit_after>#include <boost/function.hpp>
#include <boost/assign/list_of.hpp>
#include <boost/assert.hpp>
#include <math.h>
#include <moveit/robot_state/conversions.h>
#include <moveit/trajectory_processing/iterative_time_parameterization.h>
#include <moveit_cartesian_plan_plugin/generate_cartesian_path.h>
#include <moveit/planning_interface/planning_interface.h>
#include <moveit/planning_scene/planning_scene.h>
#include <moveit/kinematic_constraints/utils.h>
#include <moveit_msgs/DisplayTrajectory.h>
#include <moveit_msgs/PlanningScene.h>
#include <ros/ros.h>
#include <geometry_msgs/PoseArray.h>
GenerateCartesianPath::GenerateCartesianPath(QObject *parent)
{
//to add initializations
init();
}
GenerateCartesianPath::~GenerateCartesianPath()
{
/*! The destructor resets the moveit_group_ and the kinematic_state of the robot.
*/
moveit_group_.reset();
kinematic_state.reset();
robot_model_loader.reset();
kmodel.reset();
}
void GenerateCartesianPath::init()
{
/*! Initialize the MoveIt parameters:
- MoveIt group
- Kinematic State is the current kinematic congiguration of the Robot
- Robot model which handles getting the Robot Model
- Joint Model group which are necessary for checking if Way-Point is outside the IK Solution
.
*/
selected_plan_group = 0;
robot_model_loader = RobotModelLoaderPtr(new robot_model_loader::RobotModelLoader("robot_description"));
kmodel = robot_model_loader->getModel();
//kmodel = robot_model::RobotModelConstPtr(new moveit::core::RobotModel(robot_model_loader->getModel()));
//group_names = kmodel->getJointModelGroupNames();
end_eff_joint_groups = kmodel->getEndEffectors();
ROS_INFO_STREAM("size of the end effectors is: "<<end_eff_joint_groups.size());
if (end_eff_joint_groups.empty())
{
std::vector< std::string > group_names_tmp_;
const moveit::core::JointModelGroup * end_eff_joint_groups_tmp_;
group_names_tmp_ = kmodel->getJointModelGroupNames();
for(int i=0;i<group_names_tmp_.size();i++)
{
end_eff_joint_groups_tmp_ = kmodel->getJointModelGroup(group_names_tmp_.at(i));
if(end_eff_joint_groups_tmp_->isChain())
{
group_names.push_back(group_names_tmp_.at(i));
}
else
{
ROS_INFO_STREAM("The group:" << end_eff_joint_groups_tmp_->getName() <<" is not a Chain. Depreciate it!!");
}
}
}
else
{
for(int i=0;i<end_eff_joint_groups.size();i++)
{
// const std::pair< std::string, std::string > & parent_group_name = end_eff_joint_groups.at(i)->getEndEffectorParentGroup();
if(end_eff_joint_groups.at(i)->isChain())
{
const std::string& parent_group_name = end_eff_joint_groups.at(i)->getName();
group_names.push_back(parent_group_name);
ROS_INFO_STREAM("Group name:"<< group_names.at(i));
}
else
{
ROS_INFO_STREAM("This group is not a chain. Find the parent of the group");
const std::pair< std::string, std::string > & parent_group_name = end_eff_joint_groups.at(i)->getEndEffectorParentGroup();
group_names.push_back(parent_group_name.first);
}
}
}
ROS_INFO_STREAM("Group name:"<< group_names[selected_plan_group]);
moveit_group_ = MoveGroupPtr(new move_group_interface::MoveGroup(group_names[selected_plan_group]));
kinematic_state = moveit::core::RobotStatePtr(new robot_state::RobotState(kmodel));
kinematic_state->setToDefaultValues();
joint_model_group = kmodel->getJointModelGroup(group_names[selected_plan_group]);
}
void GenerateCartesianPath::setCartParams(double plan_time_,double cart_step_size_, double cart_jump_thresh_, bool moveit_replan_,bool avoid_collisions_)
{
/*! Set the necessary parameters for the MoveIt and the Cartesian Path Planning.
These parameters correspond to the ones that the user has entered or the default ones before the execution of the Cartesian Path Planner.
*/
ROS_INFO_STREAM("MoveIt and Cartesian Path parameters from UI:\n MoveIt Plan Time:"<<plan_time_
<<"\n Cartesian Path Step Size:"<<cart_step_size_
<<"\n Jump Threshold:"<<cart_jump_thresh_
<<"\n Replanning:"<<moveit_replan_
<<"\n Avoid Collisions:"<<avoid_collisions_);
PLAN_TIME_ = plan_time_;
MOVEIT_REPLAN_ = moveit_replan_;
CART_STEP_SIZE_ = cart_step_size_;
CART_JUMP_THRESH_ = cart_jump_thresh_;
AVOID_COLLISIONS_ = avoid_collisions_;
}
void GenerateCartesianPath::moveToPose(std::vector<geometry_msgs::Pose> waypoints)
{
/*!
*/
Q_EMIT cartesianPathExecuteStarted();
moveit_group_->setPlanningTime(PLAN_TIME_);
moveit_group_->allowReplanning (MOVEIT_REPLAN_);
move_group_interface::MoveGroup::Plan plan;
moveit_msgs::RobotTrajectory trajectory_;
double fraction = moveit_group_->computeCartesianPath(waypoints,CART_STEP_SIZE_,CART_JUMP_THRESH_,trajectory_,AVOID_COLLISIONS_);
robot_trajectory::RobotTrajectory rt(kmodel, group_names[selected_plan_group]);
rt.setRobotTrajectoryMsg(*kinematic_state, trajectory_);
ROS_INFO_STREAM("Pose reference frame: " << moveit_group_->getPoseReferenceFrame ());
// Thrid create a IterativeParabolicTimeParameterization object
trajectory_processing::IterativeParabolicTimeParameterization iptp;
bool success = iptp.computeTimeStamps(rt);
ROS_INFO("Computed time stamp %s",success?"SUCCEDED":"FAILED");
// Get RobotTrajectory_msg from RobotTrajectory
rt.getRobotTrajectoryMsg(trajectory_);
// Finally plan and execute the trajectory
plan.trajectory_ = trajectory_;
ROS_INFO("Visualizing plan (cartesian path) (%.2f%% acheived)",fraction * 100.0);
Q_EMIT cartesianPathCompleted(fraction);
moveit_group_->execute(plan);
kinematic_state = moveit_group_->getCurrentState();
Q_EMIT cartesianPathExecuteFinished();
}
void GenerateCartesianPath::cartesianPathHandler(std::vector<geometry_msgs::Pose> waypoints)
{
/*! Since the execution of the Cartesian path is time consuming and can lead to locking up of the Plugin and the RViz enviroment the function for executing the Cartesian Path Plan has been placed in a separtate thread.
This prevents the RViz and the Plugin to lock.
*/
ROS_INFO("Starting concurrent process for Cartesian Path");
QFuture<void> future = QtConcurrent::run(this, &GenerateCartesianPath::moveToPose, waypoints);
}
void GenerateCartesianPath::checkWayPointValidity(const geometry_msgs::Pose& waypoint,const int point_number)
{
/*! This function is called every time the user updates the pose of the Way-Point and checks if the Way-Point is within the valid IK solution for the Robot.
In the case when a point is outside the valid IK solution this function send a signal to the RViz enviroment to update the color of the Way-Point.
*/
bool found_ik = kinematic_state->setFromIK(joint_model_group, waypoint, 3, 0.006);
if(found_ik)
{
Q_EMIT wayPointOutOfIK(point_number,0);
}
else
{
// ROS_INFO("Did not find IK solution for waypoint %d",point_number);
Q_EMIT wayPointOutOfIK(point_number,1);
}
}
void GenerateCartesianPath::initRviz_done()
{
/*! Once the initialization of the RViz is has finished, this function sends the pose of the robot end-effector and the name of the base frame to the RViz enviroment.
The RViz enviroment sets the User Interactive Marker pose and Add New Way-Point RQT Layout default values based on the end-effector starting position.
The transformation frame of the InteractiveMarker is set based on the robot PoseReferenceFrame.
*/
ROS_INFO("RViz is done now we need to emit the signal");
if(moveit_group_->getEndEffectorLink().empty())
{
ROS_INFO("End effector link is empty");
const std::vector< std::string > & joint_names = joint_model_group->getLinkModelNames();
for(int i=0;i<joint_names.size();i++)
{
ROS_INFO_STREAM("Link " << i << " name: "<< joint_names.at(i));
}
const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform(joint_names.at(0));
//tf::Transform end_effector;
tf::transformEigenToTF(end_effector_state, end_effector);
Q_EMIT getRobotModelFrame_signal(moveit_group_->getPoseReferenceFrame(),end_effector);
}
else
{
ROS_INFO("End effector link is not empty");
const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform(moveit_group_->getEndEffectorLink());
//tf::Transform end_effector;
tf::transformEigenToTF(end_effector_state, end_effector);
Q_EMIT getRobotModelFrame_signal(moveit_group_->getPoseReferenceFrame(),end_effector);
}
Q_EMIT sendCartPlanGroup(group_names);
}
void GenerateCartesianPath::moveToHome()
{
geometry_msgs::Pose home_pose;
tf::poseTFToMsg(end_effector,home_pose);
std::vector<geometry_msgs::Pose> waypoints;
waypoints.push_back(home_pose);
cartesianPathHandler(waypoints);
}
void GenerateCartesianPath::getSelectedGroupIndex(int index)
{
selected_plan_group = index;
ROS_INFO_STREAM("selected name is:"<<group_names[selected_plan_group]);
moveit_group_.reset();
kinematic_state.reset();
moveit_group_ = MoveGroupPtr(new move_group_interface::MoveGroup(group_names[selected_plan_group]));
kinematic_state = moveit::core::RobotStatePtr(new robot_state::RobotState(kmodel));
kinematic_state->setToDefaultValues();
joint_model_group = kmodel->getJointModelGroup(group_names[selected_plan_group]);
//for debugging only. This will be left out after some testing
// if(moveit_group_->getEndEffectorLink().empty())
// {
// ROS_INFO("End effector link is empty");
// const std::vector< std::string > & joint_names = joint_model_group->getLinkModelNames();
// for(int i=0;i<joint_names.size();i++)
// {
// ROS_INFO_STREAM("Link " << i << " name: "<< joint_names.at(i));
// }
// const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform(joint_names.at(0));
// //tf::Transform end_effector;
// tf::transformEigenToTF(end_effector_state, end_effector);
// Q_EMIT getRobotModelFrame_signal(moveit_group_->getPoseReferenceFrame(),end_effector);
// }
// else
// {
ROS_INFO("End effector link is not empty");
const Eigen::Affine3d &end_effector_state = kinematic_state->getGlobalLinkTransform(moveit_group_->getEndEffectorLink());
//tf::Transform end_effector;
tf::transformEigenToTF(end_effector_state, end_effector);
Q_EMIT getRobotModelFrame_signal(moveit_group_->getPoseReferenceFrame(),end_effector);
//}
}<|endoftext|>
|
<commit_before>/* Copyright 2007-2015 QReal Research Group
*
* 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 "kitBase/blocksBase/common/waitForEncoderBlock.h"
#include "kitBase/robotModel/robotParts/encoderSensor.h"
#include "kitBase/robotModel/robotModelUtils.h"
using namespace kitBase;
using namespace blocksBase::common;
using namespace robotModel;
WaitForEncoderBlock::WaitForEncoderBlock(RobotModelInterface &robotModel)
: WaitForSensorBlock(robotModel)
{
}
void WaitForEncoderBlock::responseSlot(int reading)
{
const int result = eval<int>("TachoLimit");
if (!errorsOccured()) {
processResponce(reading, result);
}
}
DeviceInfo WaitForEncoderBlock::device() const
{
return DeviceInfo::create<robotParts::EncoderSensor>();
}
<commit_msg>Reduced active waiting timeout for encoder block<commit_after>/* Copyright 2007-2015 QReal Research Group
*
* 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 "kitBase/blocksBase/common/waitForEncoderBlock.h"
#include "kitBase/robotModel/robotParts/encoderSensor.h"
#include "kitBase/robotModel/robotModelUtils.h"
using namespace kitBase;
using namespace blocksBase::common;
using namespace robotModel;
WaitForEncoderBlock::WaitForEncoderBlock(RobotModelInterface &robotModel)
: WaitForSensorBlock(robotModel)
{
mActiveWaitingTimer.setInterval(1);
}
void WaitForEncoderBlock::responseSlot(int reading)
{
const int result = eval<int>("TachoLimit");
if (!errorsOccured()) {
processResponce(reading, result);
}
}
DeviceInfo WaitForEncoderBlock::device() const
{
return DeviceInfo::create<robotParts::EncoderSensor>();
}
<|endoftext|>
|
<commit_before>
#include "Globals.h"
#include "IncrementalRedstoneSimulator.h"
#include "../../Chunk.h"
#include "CommandBlockHandler.h"
#include "DoorHandler.h"
#include "RedstoneTorchHandler.h"
#include "RedstoneWireHandler.h"
#include "RedstoneRepeaterHandler.h"
#include "RedstoneToggleHandler.h"
#include "SolidBlockHandler.h"
#include "RedstoneLampHandler.h"
#include "RedstoneBlockHandler.h"
#include "PistonHandler.h"
#include "SmallGateHandler.h"
#include "NoteBlockHandler.h"
#include "ObserverHandler.h"
#include "TNTHandler.h"
#include "PoweredRailHandler.h"
#include "PressurePlateHandler.h"
#include "TripwireHookHandler.h"
#include "DropSpenserHandler.h"
#include "RedstoneComparatorHandler.h"
#include "TrappedChestHandler.h"
#include "HopperHandler.h"
const cRedstoneHandler * cIncrementalRedstoneSimulator::GetComponentHandler(BLOCKTYPE a_BlockType)
{
struct sComponents :
public std::array<std::unique_ptr<cRedstoneHandler>, 256>
{
sComponents()
{
for (size_t i = 0; i != 256; ++i)
{
(*this)[i] = cIncrementalRedstoneSimulator::CreateComponent(static_cast<BLOCKTYPE>(i));
}
}
};
static sComponents Components;
return Components[a_BlockType].get();
}
std::unique_ptr<cRedstoneHandler> cIncrementalRedstoneSimulator::CreateComponent(BLOCKTYPE a_BlockType)
{
switch (a_BlockType)
{
case E_BLOCK_ACTIVATOR_RAIL:
case E_BLOCK_DETECTOR_RAIL:
case E_BLOCK_POWERED_RAIL: return cpp14::make_unique<cPoweredRailHandler>();
case E_BLOCK_ACTIVE_COMPARATOR:
case E_BLOCK_INACTIVE_COMPARATOR: return cpp14::make_unique<cRedstoneComparatorHandler>();
case E_BLOCK_DISPENSER:
case E_BLOCK_DROPPER: return cpp14::make_unique<cDropSpenserHandler>();
case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE:
case E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE:
case E_BLOCK_STONE_PRESSURE_PLATE:
case E_BLOCK_WOODEN_PRESSURE_PLATE: return cpp14::make_unique<cPressurePlateHandler>();
case E_BLOCK_ACACIA_FENCE_GATE:
case E_BLOCK_BIRCH_FENCE_GATE:
case E_BLOCK_DARK_OAK_FENCE_GATE:
case E_BLOCK_FENCE_GATE:
case E_BLOCK_IRON_TRAPDOOR:
case E_BLOCK_JUNGLE_FENCE_GATE:
case E_BLOCK_SPRUCE_FENCE_GATE:
case E_BLOCK_TRAPDOOR: return cpp14::make_unique<cSmallGateHandler>();
case E_BLOCK_REDSTONE_LAMP_OFF:
case E_BLOCK_REDSTONE_LAMP_ON: return cpp14::make_unique<cRedstoneLampHandler>();
case E_BLOCK_REDSTONE_REPEATER_OFF:
case E_BLOCK_REDSTONE_REPEATER_ON: return cpp14::make_unique<cRedstoneRepeaterHandler>();
case E_BLOCK_REDSTONE_TORCH_OFF:
case E_BLOCK_REDSTONE_TORCH_ON: return cpp14::make_unique<cRedstoneTorchHandler>();
case E_BLOCK_OBSERVER: return cpp14::make_unique<cObserverHandler>();
case E_BLOCK_PISTON:
case E_BLOCK_STICKY_PISTON: return cpp14::make_unique<cPistonHandler>();
case E_BLOCK_LEVER:
case E_BLOCK_STONE_BUTTON:
case E_BLOCK_WOODEN_BUTTON: return cpp14::make_unique<cRedstoneToggleHandler>();
case E_BLOCK_BLOCK_OF_REDSTONE: return cpp14::make_unique<cRedstoneBlockHandler>();
case E_BLOCK_COMMAND_BLOCK: return cpp14::make_unique<cCommandBlockHandler>();
case E_BLOCK_HOPPER: return cpp14::make_unique<cHopperHandler>();
case E_BLOCK_NOTE_BLOCK: return cpp14::make_unique<cNoteBlockHandler>();
case E_BLOCK_REDSTONE_WIRE: return cpp14::make_unique<cRedstoneWireHandler>();
case E_BLOCK_TNT: return cpp14::make_unique<cTNTHandler>();
case E_BLOCK_TRAPPED_CHEST: return cpp14::make_unique<cTrappedChestHandler>();
case E_BLOCK_TRIPWIRE_HOOK: return cpp14::make_unique<cTripwireHookHandler>();
default:
{
if (cBlockDoorHandler::IsDoorBlockType(a_BlockType))
{
return cpp14::make_unique<cDoorHandler>();
}
if (cBlockInfo::FullyOccupiesVoxel(a_BlockType))
{
return cpp14::make_unique<cSolidBlockHandler>();
}
return nullptr;
}
}
}
void cIncrementalRedstoneSimulator::SimulateChunk(std::chrono::milliseconds a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk)
{
auto & ChunkData = *static_cast<cIncrementalRedstoneSimulatorChunkData *>(a_Chunk->GetRedstoneSimulatorData());
for (auto & DelayInfo : ChunkData.m_MechanismDelays)
{
if ((--DelayInfo.second.first) == 0)
{
ChunkData.WakeUp(DelayInfo.first);
}
}
// Build our work queue
auto & WorkQueue = ChunkData.GetActiveBlocks();
// Process the work queue
while (!WorkQueue.empty())
{
// Grab the first element and remove it from the list
Vector3i CurrentLocation = WorkQueue.top();
WorkQueue.pop();
const auto NeighbourChunk = a_Chunk->GetRelNeighborChunkAdjustCoords(CurrentLocation);
if ((NeighbourChunk == nullptr) || !NeighbourChunk->IsValid())
{
return;
}
ProcessWorkItem(*NeighbourChunk, *a_Chunk, CurrentLocation);
}
for (const auto Position : ChunkData.AlwaysTickedPositions)
{
ChunkData.WakeUp(Position);
}
}
void cIncrementalRedstoneSimulator::ProcessWorkItem(cChunk & Chunk, cChunk & TickingSource, const Vector3i Position)
{
auto & ChunkData = *static_cast<cIncrementalRedstoneSimulatorChunkData *>(Chunk.GetRedstoneSimulatorData());
BLOCKTYPE CurrentBlock;
NIBBLETYPE CurrentMeta;
Chunk.GetBlockTypeMeta(Position, CurrentBlock, CurrentMeta);
auto CurrentHandler = GetComponentHandler(CurrentBlock);
if (CurrentHandler == nullptr) // Block at CurrentPosition doesn't have a corresponding redstone handler
{
// Clean up cached PowerData for CurrentPosition
ChunkData.ErasePowerData(Position);
return;
}
PoweringData Power;
CurrentHandler->ForValidSourcePositions(Chunk, Position, CurrentBlock, CurrentMeta, [&Chunk, Position, CurrentBlock, &Power](Vector3i Location)
{
if (!cChunk::IsValidHeight(Location.y))
{
return;
}
const auto NeighbourChunk = Chunk.GetRelNeighborChunkAdjustCoords(Location);
if ((NeighbourChunk == nullptr) || !NeighbourChunk->IsValid())
{
return;
}
BLOCKTYPE PotentialBlock;
NIBBLETYPE PotentialMeta;
NeighbourChunk->GetBlockTypeMeta(Location, PotentialBlock, PotentialMeta);
auto PotentialSourceHandler = GetComponentHandler(PotentialBlock);
if (PotentialSourceHandler == nullptr)
{
return;
}
const PoweringData PotentialPower(
PotentialBlock,
PotentialSourceHandler->GetPowerDeliveredToPosition(
*NeighbourChunk, Location, PotentialBlock, PotentialMeta,
cIncrementalRedstoneSimulatorChunkData::RebaseRelativePosition(Chunk, *NeighbourChunk, Position), CurrentBlock
)
);
Power = std::max(Power, PotentialPower);
});
// Inform the handler to update
CurrentHandler->Update(Chunk, TickingSource, Position, CurrentBlock, CurrentMeta, Power);
}
void cIncrementalRedstoneSimulator::AddBlock(Vector3i a_Block, cChunk * a_Chunk)
{
// Can't inspect block, ignore:
if ((a_Chunk == nullptr) || (!a_Chunk->IsValid()))
{
return;
}
auto & ChunkData = *static_cast<cIncrementalRedstoneSimulatorChunkData *>(a_Chunk->GetRedstoneSimulatorData());
const auto Relative = cChunkDef::AbsoluteToRelative(a_Block, a_Chunk->GetPos());
const auto CurrentBlock = a_Chunk->GetBlock(Relative);
// Always update redstone devices
if (IsRedstone(CurrentBlock))
{
if (IsAlwaysTicked(CurrentBlock))
{
ChunkData.AlwaysTickedPositions.emplace(Relative);
}
ChunkData.WakeUp(Relative);
return;
}
// Never update blocks without a handler
if (GetComponentHandler(CurrentBlock) == nullptr)
{
ChunkData.ErasePowerData(Relative);
return;
}
// Only update others if there is a redstone device nearby
for (int x = -1; x < 2; ++x)
{
for (int y = -1; y < 2; ++y)
{
if (!cChunkDef::IsValidHeight(Relative.y + y))
{
continue;
}
for (int z = -1; z < 2; ++z)
{
auto CheckPos = Relative + Vector3i{x, y, z};
BLOCKTYPE Block;
NIBBLETYPE Meta;
// If we can't read the block, assume it is a mechanism
if (
!a_Chunk->UnboundedRelGetBlock(CheckPos, Block, Meta) ||
IsRedstone(Block)
)
{
ChunkData.WakeUp(Relative);
return;
}
}
}
}
}
<commit_msg>Remove redundant ErasePowerData call<commit_after>
#include "Globals.h"
#include "IncrementalRedstoneSimulator.h"
#include "../../Chunk.h"
#include "CommandBlockHandler.h"
#include "DoorHandler.h"
#include "RedstoneTorchHandler.h"
#include "RedstoneWireHandler.h"
#include "RedstoneRepeaterHandler.h"
#include "RedstoneToggleHandler.h"
#include "SolidBlockHandler.h"
#include "RedstoneLampHandler.h"
#include "RedstoneBlockHandler.h"
#include "PistonHandler.h"
#include "SmallGateHandler.h"
#include "NoteBlockHandler.h"
#include "ObserverHandler.h"
#include "TNTHandler.h"
#include "PoweredRailHandler.h"
#include "PressurePlateHandler.h"
#include "TripwireHookHandler.h"
#include "DropSpenserHandler.h"
#include "RedstoneComparatorHandler.h"
#include "TrappedChestHandler.h"
#include "HopperHandler.h"
const cRedstoneHandler * cIncrementalRedstoneSimulator::GetComponentHandler(BLOCKTYPE a_BlockType)
{
struct sComponents :
public std::array<std::unique_ptr<cRedstoneHandler>, 256>
{
sComponents()
{
for (size_t i = 0; i != 256; ++i)
{
(*this)[i] = cIncrementalRedstoneSimulator::CreateComponent(static_cast<BLOCKTYPE>(i));
}
}
};
static sComponents Components;
return Components[a_BlockType].get();
}
std::unique_ptr<cRedstoneHandler> cIncrementalRedstoneSimulator::CreateComponent(BLOCKTYPE a_BlockType)
{
switch (a_BlockType)
{
case E_BLOCK_ACTIVATOR_RAIL:
case E_BLOCK_DETECTOR_RAIL:
case E_BLOCK_POWERED_RAIL: return cpp14::make_unique<cPoweredRailHandler>();
case E_BLOCK_ACTIVE_COMPARATOR:
case E_BLOCK_INACTIVE_COMPARATOR: return cpp14::make_unique<cRedstoneComparatorHandler>();
case E_BLOCK_DISPENSER:
case E_BLOCK_DROPPER: return cpp14::make_unique<cDropSpenserHandler>();
case E_BLOCK_HEAVY_WEIGHTED_PRESSURE_PLATE:
case E_BLOCK_LIGHT_WEIGHTED_PRESSURE_PLATE:
case E_BLOCK_STONE_PRESSURE_PLATE:
case E_BLOCK_WOODEN_PRESSURE_PLATE: return cpp14::make_unique<cPressurePlateHandler>();
case E_BLOCK_ACACIA_FENCE_GATE:
case E_BLOCK_BIRCH_FENCE_GATE:
case E_BLOCK_DARK_OAK_FENCE_GATE:
case E_BLOCK_FENCE_GATE:
case E_BLOCK_IRON_TRAPDOOR:
case E_BLOCK_JUNGLE_FENCE_GATE:
case E_BLOCK_SPRUCE_FENCE_GATE:
case E_BLOCK_TRAPDOOR: return cpp14::make_unique<cSmallGateHandler>();
case E_BLOCK_REDSTONE_LAMP_OFF:
case E_BLOCK_REDSTONE_LAMP_ON: return cpp14::make_unique<cRedstoneLampHandler>();
case E_BLOCK_REDSTONE_REPEATER_OFF:
case E_BLOCK_REDSTONE_REPEATER_ON: return cpp14::make_unique<cRedstoneRepeaterHandler>();
case E_BLOCK_REDSTONE_TORCH_OFF:
case E_BLOCK_REDSTONE_TORCH_ON: return cpp14::make_unique<cRedstoneTorchHandler>();
case E_BLOCK_OBSERVER: return cpp14::make_unique<cObserverHandler>();
case E_BLOCK_PISTON:
case E_BLOCK_STICKY_PISTON: return cpp14::make_unique<cPistonHandler>();
case E_BLOCK_LEVER:
case E_BLOCK_STONE_BUTTON:
case E_BLOCK_WOODEN_BUTTON: return cpp14::make_unique<cRedstoneToggleHandler>();
case E_BLOCK_BLOCK_OF_REDSTONE: return cpp14::make_unique<cRedstoneBlockHandler>();
case E_BLOCK_COMMAND_BLOCK: return cpp14::make_unique<cCommandBlockHandler>();
case E_BLOCK_HOPPER: return cpp14::make_unique<cHopperHandler>();
case E_BLOCK_NOTE_BLOCK: return cpp14::make_unique<cNoteBlockHandler>();
case E_BLOCK_REDSTONE_WIRE: return cpp14::make_unique<cRedstoneWireHandler>();
case E_BLOCK_TNT: return cpp14::make_unique<cTNTHandler>();
case E_BLOCK_TRAPPED_CHEST: return cpp14::make_unique<cTrappedChestHandler>();
case E_BLOCK_TRIPWIRE_HOOK: return cpp14::make_unique<cTripwireHookHandler>();
default:
{
if (cBlockDoorHandler::IsDoorBlockType(a_BlockType))
{
return cpp14::make_unique<cDoorHandler>();
}
if (cBlockInfo::FullyOccupiesVoxel(a_BlockType))
{
return cpp14::make_unique<cSolidBlockHandler>();
}
return nullptr;
}
}
}
void cIncrementalRedstoneSimulator::SimulateChunk(std::chrono::milliseconds a_Dt, int a_ChunkX, int a_ChunkZ, cChunk * a_Chunk)
{
auto & ChunkData = *static_cast<cIncrementalRedstoneSimulatorChunkData *>(a_Chunk->GetRedstoneSimulatorData());
for (auto & DelayInfo : ChunkData.m_MechanismDelays)
{
if ((--DelayInfo.second.first) == 0)
{
ChunkData.WakeUp(DelayInfo.first);
}
}
// Build our work queue
auto & WorkQueue = ChunkData.GetActiveBlocks();
// Process the work queue
while (!WorkQueue.empty())
{
// Grab the first element and remove it from the list
Vector3i CurrentLocation = WorkQueue.top();
WorkQueue.pop();
const auto NeighbourChunk = a_Chunk->GetRelNeighborChunkAdjustCoords(CurrentLocation);
if ((NeighbourChunk == nullptr) || !NeighbourChunk->IsValid())
{
continue;
}
ProcessWorkItem(*NeighbourChunk, *a_Chunk, CurrentLocation);
}
for (const auto Position : ChunkData.AlwaysTickedPositions)
{
ChunkData.WakeUp(Position);
}
}
void cIncrementalRedstoneSimulator::ProcessWorkItem(cChunk & Chunk, cChunk & TickingSource, const Vector3i Position)
{
BLOCKTYPE CurrentBlock;
NIBBLETYPE CurrentMeta;
Chunk.GetBlockTypeMeta(Position, CurrentBlock, CurrentMeta);
auto CurrentHandler = GetComponentHandler(CurrentBlock);
if (CurrentHandler == nullptr)
{
// Block at Position doesn't have a corresponding redstone handler
// ErasePowerData will have been called in AddBlock
return;
}
PoweringData Power;
CurrentHandler->ForValidSourcePositions(Chunk, Position, CurrentBlock, CurrentMeta, [&Chunk, Position, CurrentBlock, &Power](Vector3i Location)
{
if (!cChunk::IsValidHeight(Location.y))
{
return;
}
const auto NeighbourChunk = Chunk.GetRelNeighborChunkAdjustCoords(Location);
if ((NeighbourChunk == nullptr) || !NeighbourChunk->IsValid())
{
return;
}
BLOCKTYPE PotentialBlock;
NIBBLETYPE PotentialMeta;
NeighbourChunk->GetBlockTypeMeta(Location, PotentialBlock, PotentialMeta);
auto PotentialSourceHandler = GetComponentHandler(PotentialBlock);
if (PotentialSourceHandler == nullptr)
{
return;
}
const PoweringData PotentialPower(
PotentialBlock,
PotentialSourceHandler->GetPowerDeliveredToPosition(
*NeighbourChunk, Location, PotentialBlock, PotentialMeta,
cIncrementalRedstoneSimulatorChunkData::RebaseRelativePosition(Chunk, *NeighbourChunk, Position), CurrentBlock
)
);
Power = std::max(Power, PotentialPower);
});
// Inform the handler to update
CurrentHandler->Update(Chunk, TickingSource, Position, CurrentBlock, CurrentMeta, Power);
}
void cIncrementalRedstoneSimulator::AddBlock(Vector3i a_Block, cChunk * a_Chunk)
{
// Can't inspect block, ignore:
if ((a_Chunk == nullptr) || !a_Chunk->IsValid())
{
return;
}
auto & ChunkData = *static_cast<cIncrementalRedstoneSimulatorChunkData *>(a_Chunk->GetRedstoneSimulatorData());
const auto Relative = cChunkDef::AbsoluteToRelative(a_Block, a_Chunk->GetPos());
const auto CurrentBlock = a_Chunk->GetBlock(Relative);
// Always update redstone devices
if (IsRedstone(CurrentBlock))
{
if (IsAlwaysTicked(CurrentBlock))
{
ChunkData.AlwaysTickedPositions.emplace(Relative);
}
ChunkData.WakeUp(Relative);
return;
}
// Never update blocks without a handler
if (GetComponentHandler(CurrentBlock) == nullptr)
{
ChunkData.ErasePowerData(Relative);
return;
}
// Only update others if there is a redstone device nearby
for (int x = -1; x < 2; ++x)
{
for (int y = -1; y < 2; ++y)
{
if (!cChunkDef::IsValidHeight(Relative.y + y))
{
continue;
}
for (int z = -1; z < 2; ++z)
{
auto CheckPos = Relative + Vector3i{x, y, z};
BLOCKTYPE Block;
NIBBLETYPE Meta;
// If we can't read the block, assume it is a mechanism
if (
!a_Chunk->UnboundedRelGetBlock(CheckPos, Block, Meta) ||
IsRedstone(Block)
)
{
ChunkData.WakeUp(Relative);
return;
}
}
}
}
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "support/allocators/secure.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old passphrase and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR TERRACOIN</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("%1 will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your bitcoins from being stolen by malware infecting your computer.").arg(tr(PACKAGE_NAME)) +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
static void SecureClearQLineEdit(QLineEdit* edit)
{
// Attempt to overwrite text so that they do not linger around in memory
edit->setText(QString(" ").repeated(edit->text().size()));
edit->clear();
}
void AskPassphraseDialog::secureClearPassFields()
{
SecureClearQLineEdit(ui->passEdit1);
SecureClearQLineEdit(ui->passEdit2);
SecureClearQLineEdit(ui->passEdit3);
}
<commit_msg>Fixed bitcoin to terracoin<commit_after>// Copyright (c) 2011-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#if defined(HAVE_CONFIG_H)
#include "config/bitcoin-config.h"
#endif
#include "askpassphrasedialog.h"
#include "ui_askpassphrasedialog.h"
#include "guiconstants.h"
#include "walletmodel.h"
#include "support/allocators/secure.h"
#include <QKeyEvent>
#include <QMessageBox>
#include <QPushButton>
AskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :
QDialog(parent),
ui(new Ui::AskPassphraseDialog),
mode(mode),
model(0),
fCapsLock(false)
{
ui->setupUi(this);
ui->passEdit1->setMinimumSize(ui->passEdit1->sizeHint());
ui->passEdit2->setMinimumSize(ui->passEdit2->sizeHint());
ui->passEdit3->setMinimumSize(ui->passEdit3->sizeHint());
ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);
ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);
// Setup Caps Lock detection.
ui->passEdit1->installEventFilter(this);
ui->passEdit2->installEventFilter(this);
ui->passEdit3->installEventFilter(this);
switch(mode)
{
case Encrypt: // Ask passphrase x2
ui->warningLabel->setText(tr("Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>."));
ui->passLabel1->hide();
ui->passEdit1->hide();
setWindowTitle(tr("Encrypt wallet"));
break;
case Unlock: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to unlock the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Unlock wallet"));
break;
case Decrypt: // Ask passphrase
ui->warningLabel->setText(tr("This operation needs your wallet passphrase to decrypt the wallet."));
ui->passLabel2->hide();
ui->passEdit2->hide();
ui->passLabel3->hide();
ui->passEdit3->hide();
setWindowTitle(tr("Decrypt wallet"));
break;
case ChangePass: // Ask old passphrase + new passphrase x2
setWindowTitle(tr("Change passphrase"));
ui->warningLabel->setText(tr("Enter the old passphrase and new passphrase to the wallet."));
break;
}
textChanged();
connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));
}
AskPassphraseDialog::~AskPassphraseDialog()
{
secureClearPassFields();
delete ui;
}
void AskPassphraseDialog::setModel(WalletModel *model)
{
this->model = model;
}
void AskPassphraseDialog::accept()
{
SecureString oldpass, newpass1, newpass2;
if(!model)
return;
oldpass.reserve(MAX_PASSPHRASE_SIZE);
newpass1.reserve(MAX_PASSPHRASE_SIZE);
newpass2.reserve(MAX_PASSPHRASE_SIZE);
// TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)
// Alternately, find a way to make this input mlock()'d to begin with.
oldpass.assign(ui->passEdit1->text().toStdString().c_str());
newpass1.assign(ui->passEdit2->text().toStdString().c_str());
newpass2.assign(ui->passEdit3->text().toStdString().c_str());
secureClearPassFields();
switch(mode)
{
case Encrypt: {
if(newpass1.empty() || newpass2.empty())
{
// Cannot encrypt with empty passphrase
break;
}
QMessageBox::StandardButton retval = QMessageBox::question(this, tr("Confirm wallet encryption"),
tr("Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR TERRACOIN</b>!") + "<br><br>" + tr("Are you sure you wish to encrypt your wallet?"),
QMessageBox::Yes|QMessageBox::Cancel,
QMessageBox::Cancel);
if(retval == QMessageBox::Yes)
{
if(newpass1 == newpass2)
{
if(model->setWalletEncrypted(true, newpass1))
{
QMessageBox::warning(this, tr("Wallet encrypted"),
"<qt>" +
tr("%1 will close now to finish the encryption process. "
"Remember that encrypting your wallet cannot fully protect "
"your terracoins from being stolen by malware infecting your computer.").arg(tr(PACKAGE_NAME)) +
"<br><br><b>" +
tr("IMPORTANT: Any previous backups you have made of your wallet file "
"should be replaced with the newly generated, encrypted wallet file. "
"For security reasons, previous backups of the unencrypted wallet file "
"will become useless as soon as you start using the new, encrypted wallet.") +
"</b></qt>");
QApplication::quit();
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("Wallet encryption failed due to an internal error. Your wallet was not encrypted."));
}
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
}
else
{
QDialog::reject(); // Cancelled
}
} break;
case Unlock:
if(!model->setWalletLocked(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet unlock failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case Decrypt:
if(!model->setWalletEncrypted(false, oldpass))
{
QMessageBox::critical(this, tr("Wallet decryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
else
{
QDialog::accept(); // Success
}
break;
case ChangePass:
if(newpass1 == newpass2)
{
if(model->changePassphrase(oldpass, newpass1))
{
QMessageBox::information(this, tr("Wallet encrypted"),
tr("Wallet passphrase was successfully changed."));
QDialog::accept(); // Success
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The passphrase entered for the wallet decryption was incorrect."));
}
}
else
{
QMessageBox::critical(this, tr("Wallet encryption failed"),
tr("The supplied passphrases do not match."));
}
break;
}
}
void AskPassphraseDialog::textChanged()
{
// Validate input, set Ok button to enabled when acceptable
bool acceptable = false;
switch(mode)
{
case Encrypt: // New passphrase x2
acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
case Unlock: // Old passphrase x1
case Decrypt:
acceptable = !ui->passEdit1->text().isEmpty();
break;
case ChangePass: // Old passphrase x1, new passphrase x2
acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();
break;
}
ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);
}
bool AskPassphraseDialog::event(QEvent *event)
{
// Detect Caps Lock key press.
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
if (ke->key() == Qt::Key_CapsLock) {
fCapsLock = !fCapsLock;
}
if (fCapsLock) {
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else {
ui->capsLabel->clear();
}
}
return QWidget::event(event);
}
bool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)
{
/* Detect Caps Lock.
* There is no good OS-independent way to check a key state in Qt, but we
* can detect Caps Lock by checking for the following condition:
* Shift key is down and the result is a lower case character, or
* Shift key is not down and the result is an upper case character.
*/
if (event->type() == QEvent::KeyPress) {
QKeyEvent *ke = static_cast<QKeyEvent *>(event);
QString str = ke->text();
if (str.length() != 0) {
const QChar *psz = str.unicode();
bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;
if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {
fCapsLock = true;
ui->capsLabel->setText(tr("Warning: The Caps Lock key is on!"));
} else if (psz->isLetter()) {
fCapsLock = false;
ui->capsLabel->clear();
}
}
}
return QDialog::eventFilter(object, event);
}
static void SecureClearQLineEdit(QLineEdit* edit)
{
// Attempt to overwrite text so that they do not linger around in memory
edit->setText(QString(" ").repeated(edit->text().size()));
edit->clear();
}
void AskPassphraseDialog::secureClearPassFields()
{
SecureClearQLineEdit(ui->passEdit1);
SecureClearQLineEdit(ui->passEdit2);
SecureClearQLineEdit(ui->passEdit3);
}
<|endoftext|>
|
<commit_before>#include <iostream>
#include <string>
#include <sstream>
#include "ladybug.h"
#include "ladybugstream.h"
#include <stdexcept>
#include <unistd.h>
#include <signal.h>
#include <ros/ros.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_datatypes.h>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include "ladybug.h"
using namespace std;
static volatile int running_ = 1;
LadybugContext m_context;
LadybugDataFormat m_dataFormat;
//camera config settings
float m_frameRate;
bool m_isFrameRateAuto;
unsigned int m_jpegQualityPercentage;
ros::Publisher pub[LADYBUG_NUM_CAMERAS + 1];
static void signalHandler(int)
{
running_ = 0;
ros::shutdown();
}
void parseCameraInfo(const cv::Mat &camMat,
const cv::Mat &disCoeff,
const cv::Size &imgSize,
sensor_msgs::CameraInfo &msg)
{
msg.header.frame_id = "camera";
msg.height = imgSize.height;
msg.width = imgSize.width;
for (int row=0; row<3; row++)
{
for (int col=0; col<3; col++)
{
msg.K[row * 3 + col] = camMat.at<double>(row, col);
}
}
for (int row=0; row<3; row++)
{
for (int col=0; col<4; col++)
{
if (col == 3)
{
msg.P[row * 4 + col] = 0.0f;
} else
{
msg.P[row * 4 + col] = camMat.at<double>(row, col);
}
}
}
for (int row=0; row<disCoeff.rows; row++)
{
for (int col=0; col<disCoeff.cols; col++)
{
msg.D.push_back(disCoeff.at<double>(row, col));
}
}
}
void GetMatricesFromFile(ros::NodeHandle nh, sensor_msgs::CameraInfo &camerainfo_msg)
{
//////////////////CAMERA INFO/////////////////////////////////////////
cv::Mat cameraExtrinsicMat;
cv::Mat cameraMat;
cv::Mat distCoeff;
cv::Size imageSize;
std::string filename;
if (nh.getParam("calibrationfile", filename) && filename!="")
{
ROS_INFO("Trying to parse calibrationfile :");
ROS_INFO("> %s", filename.c_str());
}
else
{
ROS_INFO("No calibrationfile param was received");
return;
}
cv::FileStorage fs(filename, cv::FileStorage::READ);
if (!fs.isOpened())
{
ROS_INFO("Cannot open %s", filename.c_str());;
return;
}
else
{
fs["CameraMat"] >> cameraMat;
fs["DistCoeff"] >> distCoeff;
fs["ImageSize"] >> imageSize;
}
parseCameraInfo(cameraMat, distCoeff, imageSize, camerainfo_msg);
}
void publishImage(cv::Mat& image, ros::Publisher& image_pub, long int& count)
{
sensor_msgs::Image msg;
//publish*******************
msg.header.seq = count;
msg.header.frame_id = "camera";
msg.header.stamp.sec = ros::Time::now().sec; msg.header.stamp.nsec = ros::Time::now().nsec;
msg.height = image.size().height; msg.width = image.size().width;
msg.encoding = "rgb8";
msg.step = image.cols * image.elemSize();
size_t image_size = image.rows * image.cols * image.elemSize();
msg.data.resize(image_size);
memcpy(msg.data.data(), image.data, image_size);
image_pub.publish(msg);
}
LadybugError init_camera()
{
LadybugError error;
error = ladybugCreateContext(&m_context);
if (error != LADYBUG_OK)
{
throw std::runtime_error("Unable to create Ladybug context.");
}
LadybugCameraInfo enumeratedCameras[16];
unsigned int numCameras = 16;
error = ladybugBusEnumerateCameras(m_context, enumeratedCameras, &numCameras);
if (error != LADYBUG_OK)
{
return error;
}
cout << "Cameras detected: " << numCameras << endl << endl;
if (numCameras == 0)
{
ROS_INFO("Insufficient number of cameras detected. ");
return LADYBUG_FAILED;
}
error = ladybugInitializeFromIndex(m_context, 0);
if (error != LADYBUG_OK)
{
return error;
}
LadybugCameraInfo camInfo;
error = ladybugGetCameraInfo(m_context, &camInfo);
if (error != LADYBUG_OK)
{
return error;
}
ROS_INFO("Camera information: ");
ROS_INFO("Base s/n: %d", camInfo.serialBase );
ROS_INFO("Head s/n: %d", camInfo.serialHead );
ROS_INFO("Model: %s", camInfo.pszModelName );
ROS_INFO("Sensor: %s", camInfo.pszSensorInfo);
ROS_INFO("Vendor: %s", camInfo.pszVendorName);
ROS_INFO("Bus / Node: %d ,%d" , camInfo.iBusNum , camInfo.iNodeNum );
switch (camInfo.deviceType)
{
case LADYBUG_DEVICE_LADYBUG3:
{
m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
m_frameRate = 16.0f;
m_isFrameRateAuto = true;
m_jpegQualityPercentage = 80;
}
break;
case LADYBUG_DEVICE_LADYBUG5:
{
m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
m_frameRate = 10.0f;
m_isFrameRateAuto = true;
m_jpegQualityPercentage = 80;
}
break;
default: assert(false); break;
}
return error;
}
LadybugError start_camera()
{
LadybugError error;
error = ladybugStartLockNext(m_context, m_dataFormat);
if (error != LADYBUG_OK)
{
return error;
}
error = ladybugSetAbsPropertyEx(m_context, LADYBUG_FRAME_RATE, false, true, m_isFrameRateAuto, m_frameRate);
if (error != LADYBUG_OK)
{
return error;
}
error = ladybugSetJPEGQuality(m_context, m_jpegQualityPercentage);
if (error != LADYBUG_OK)
{
return error;
}
// Perform a quick test to make sure images can be successfully acquired
for (int i=0; i < 10; i++)
{
LadybugImage tempImage;
error = ladybugLockNext(m_context, &tempImage);
}
error = ladybugUnlockAll(m_context);
if (error != LADYBUG_OK)
{
return error;
}
return error;
}
LadybugError stop_camera()
{
const LadybugError cameraError = ladybugStop(m_context);
if (cameraError != LADYBUG_OK)
{
ROS_INFO("Error: Unable to stop camera (%s)", ladybugErrorToString(cameraError) );
}
return cameraError;
}
LadybugError acquire_image( LadybugImage& image )
{
return ladybugLockNext(m_context, &image);
}
LadybugError unlock_image( unsigned int bufferIndex )
{
return ladybugUnlock(m_context, bufferIndex);
}
int main (int argc, char **argv)
{
////ROS STUFF
ros::init(argc, argv, "ladybug_camera");
ros::NodeHandle n;
ros::NodeHandle private_nh("~");
signal(SIGTERM, signalHandler);//detect closing
/////////////////////////////
//Config camera
m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
m_frameRate = 10;
m_isFrameRateAuto = true;
m_jpegQualityPercentage = 80;
// Initialize ladybug camera
const LadybugError grabberInitError = init_camera();
if (LADYBUG_OK != init_camera())
{
ROS_INFO("Error: Failed to initialize camera (%s). Terminating...", ladybugErrorToString(grabberInitError) );
return -1;
}
LadybugCameraInfo camInfo;
if (LADYBUG_OK != ladybugGetCameraInfo(m_context, &camInfo))
{
ROS_INFO("Error: Failed to get camera information. Terminating...");
return -1;
}
const LadybugError startError = start_camera();
if (startError != LADYBUG_OK)
{
ROS_INFO("Error: Failed to start camera (%s). Terminating...", ladybugErrorToString(startError) );
return -1;
}
/////////////////////
//ROS
// Get the camera information
///////calibration data
sensor_msgs::CameraInfo camerainfo_msg;
GetMatricesFromFile(private_nh, camerainfo_msg);
int image_scale = 100;
if (private_nh.getParam("scale", image_scale) && image_scale>0 && image_scale<100)
{
ROS_INFO("Ladybug ImageScale > %i%%", image_scale);
}
else
{
ROS_INFO("Ladybug ImageScale scale must be (0,100]. Defaulting to 20 ");
image_scale=20;
}
ros::Publisher camera_info_pub;
camera_info_pub = n.advertise<sensor_msgs::CameraInfo>("/camera/camera_info", 1, true);
ROS_INFO("Successfully started ladybug camera and stream");
for (int i = 0; i < LADYBUG_NUM_CAMERAS + 1; i++) {
std::string topic(std::string("image_raw"));
topic = "camera" + std::to_string(i) + "/" + topic;
pub[i] = n.advertise<sensor_msgs::Image>(topic, 100);
ROS_INFO("Publishing.. %s", topic.c_str());
}
//////////////////
//start camera
ros::Rate loop_rate(10); // Hz Ladybug works at 10fps
long int count = 0;
while (running_ && ros::ok())
{
LadybugImage currentImage;
const LadybugError acquisitionError = acquire_image(currentImage);
if (acquisitionError != LADYBUG_OK)
{
ROS_INFO("Failed to acquire image. Error (%s). Trying to continue..", ladybugErrorToString(acquisitionError) );
continue;
}
// convert to OpenCV Mat
//receive Bayer Image, convert to Color 3 channels
cv::Size size(currentImage.uiFullCols, currentImage.uiFullRows);
cv::Mat full_size;
for(size_t i =0;i<LADYBUG_NUM_CAMERAS; i++)
{
std::ostringstream out;
out << "image" << i;
cv::Mat rawImage(size, CV_8UC1, currentImage.pData + (i * size.width*size.height));
cv::Mat image(size, CV_8UC3);
cv::cvtColor(rawImage, image, cv::COLOR_BayerBG2RGB);
cv::resize(image,image,cv::Size(size.width*image_scale/100, size.height*image_scale/100));
//
cv::transpose(image, image);
if (i==0)
image.copyTo(full_size);
else
cv::hconcat(image, full_size, full_size);
unlock_image(currentImage.uiBufferIndex);
publishImage(image, pub[LADYBUG_NUM_CAMERAS - i], count);
}
//publish stitched one
publishImage(full_size, pub[0], count);
ros::spinOnce();
loop_rate.sleep();
count++;
}
cout << "Stopping ladybug_camera..." << endl;
// Shutdown
stop_camera();
ROS_INFO("ladybug_camera stopped");
return 0;
}
<commit_msg>Fixed mirrored images on Ladybug camera (#906)<commit_after>#include <iostream>
#include <string>
#include <sstream>
#include "ladybug.h"
#include "ladybugstream.h"
#include <stdexcept>
#include <unistd.h>
#include <signal.h>
#include <ros/ros.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/CameraInfo.h>
#include <tf/transform_broadcaster.h>
#include <tf/transform_datatypes.h>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <opencv2/imgproc/imgproc.hpp>
#include "ladybug.h"
using namespace std;
static volatile int running_ = 1;
LadybugContext m_context;
LadybugDataFormat m_dataFormat;
//camera config settings
float m_frameRate;
bool m_isFrameRateAuto;
unsigned int m_jpegQualityPercentage;
ros::Publisher pub[LADYBUG_NUM_CAMERAS + 1];
static void signalHandler(int)
{
running_ = 0;
ros::shutdown();
}
void parseCameraInfo(const cv::Mat &camMat,
const cv::Mat &disCoeff,
const cv::Size &imgSize,
sensor_msgs::CameraInfo &msg)
{
msg.header.frame_id = "camera";
msg.height = imgSize.height;
msg.width = imgSize.width;
for (int row=0; row<3; row++)
{
for (int col=0; col<3; col++)
{
msg.K[row * 3 + col] = camMat.at<double>(row, col);
}
}
for (int row=0; row<3; row++)
{
for (int col=0; col<4; col++)
{
if (col == 3)
{
msg.P[row * 4 + col] = 0.0f;
} else
{
msg.P[row * 4 + col] = camMat.at<double>(row, col);
}
}
}
for (int row=0; row<disCoeff.rows; row++)
{
for (int col=0; col<disCoeff.cols; col++)
{
msg.D.push_back(disCoeff.at<double>(row, col));
}
}
}
void GetMatricesFromFile(ros::NodeHandle nh, sensor_msgs::CameraInfo &camerainfo_msg)
{
//////////////////CAMERA INFO/////////////////////////////////////////
cv::Mat cameraExtrinsicMat;
cv::Mat cameraMat;
cv::Mat distCoeff;
cv::Size imageSize;
std::string filename;
if (nh.getParam("calibrationfile", filename) && filename!="")
{
ROS_INFO("Trying to parse calibrationfile :");
ROS_INFO("> %s", filename.c_str());
}
else
{
ROS_INFO("No calibrationfile param was received");
return;
}
cv::FileStorage fs(filename, cv::FileStorage::READ);
if (!fs.isOpened())
{
ROS_INFO("Cannot open %s", filename.c_str());;
return;
}
else
{
fs["CameraMat"] >> cameraMat;
fs["DistCoeff"] >> distCoeff;
fs["ImageSize"] >> imageSize;
}
parseCameraInfo(cameraMat, distCoeff, imageSize, camerainfo_msg);
}
void publishImage(cv::Mat& image, ros::Publisher& image_pub, long int& count)
{
sensor_msgs::Image msg;
//publish*******************
msg.header.seq = count;
msg.header.frame_id = "camera";
msg.header.stamp.sec = ros::Time::now().sec; msg.header.stamp.nsec = ros::Time::now().nsec;
msg.height = image.size().height; msg.width = image.size().width;
msg.encoding = "rgb8";
msg.step = image.cols * image.elemSize();
size_t image_size = image.rows * image.cols * image.elemSize();
msg.data.resize(image_size);
memcpy(msg.data.data(), image.data, image_size);
image_pub.publish(msg);
}
LadybugError init_camera()
{
LadybugError error;
error = ladybugCreateContext(&m_context);
if (error != LADYBUG_OK)
{
throw std::runtime_error("Unable to create Ladybug context.");
}
LadybugCameraInfo enumeratedCameras[16];
unsigned int numCameras = 16;
error = ladybugBusEnumerateCameras(m_context, enumeratedCameras, &numCameras);
if (error != LADYBUG_OK)
{
return error;
}
cout << "Cameras detected: " << numCameras << endl << endl;
if (numCameras == 0)
{
ROS_INFO("Insufficient number of cameras detected. ");
return LADYBUG_FAILED;
}
error = ladybugInitializeFromIndex(m_context, 0);
if (error != LADYBUG_OK)
{
return error;
}
LadybugCameraInfo camInfo;
error = ladybugGetCameraInfo(m_context, &camInfo);
if (error != LADYBUG_OK)
{
return error;
}
ROS_INFO("Camera information: ");
ROS_INFO("Base s/n: %d", camInfo.serialBase );
ROS_INFO("Head s/n: %d", camInfo.serialHead );
ROS_INFO("Model: %s", camInfo.pszModelName );
ROS_INFO("Sensor: %s", camInfo.pszSensorInfo);
ROS_INFO("Vendor: %s", camInfo.pszVendorName);
ROS_INFO("Bus / Node: %d ,%d" , camInfo.iBusNum , camInfo.iNodeNum );
switch (camInfo.deviceType)
{
case LADYBUG_DEVICE_LADYBUG3:
{
m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
m_frameRate = 16.0f;
m_isFrameRateAuto = true;
m_jpegQualityPercentage = 80;
}
break;
case LADYBUG_DEVICE_LADYBUG5:
{
m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
m_frameRate = 10.0f;
m_isFrameRateAuto = true;
m_jpegQualityPercentage = 80;
}
break;
default: assert(false); break;
}
return error;
}
LadybugError start_camera()
{
LadybugError error;
error = ladybugStartLockNext(m_context, m_dataFormat);
if (error != LADYBUG_OK)
{
return error;
}
error = ladybugSetAbsPropertyEx(m_context, LADYBUG_FRAME_RATE, false, true, m_isFrameRateAuto, m_frameRate);
if (error != LADYBUG_OK)
{
return error;
}
error = ladybugSetJPEGQuality(m_context, m_jpegQualityPercentage);
if (error != LADYBUG_OK)
{
return error;
}
// Perform a quick test to make sure images can be successfully acquired
for (int i=0; i < 10; i++)
{
LadybugImage tempImage;
error = ladybugLockNext(m_context, &tempImage);
}
error = ladybugUnlockAll(m_context);
if (error != LADYBUG_OK)
{
return error;
}
return error;
}
LadybugError stop_camera()
{
const LadybugError cameraError = ladybugStop(m_context);
if (cameraError != LADYBUG_OK)
{
ROS_INFO("Error: Unable to stop camera (%s)", ladybugErrorToString(cameraError) );
}
return cameraError;
}
LadybugError acquire_image( LadybugImage& image )
{
return ladybugLockNext(m_context, &image);
}
LadybugError unlock_image( unsigned int bufferIndex )
{
return ladybugUnlock(m_context, bufferIndex);
}
int main (int argc, char **argv)
{
////ROS STUFF
ros::init(argc, argv, "ladybug_camera");
ros::NodeHandle n;
ros::NodeHandle private_nh("~");
signal(SIGTERM, signalHandler);//detect closing
/////////////////////////////
//Config camera
m_dataFormat = LADYBUG_DATAFORMAT_RAW8;
m_frameRate = 10;
m_isFrameRateAuto = true;
m_jpegQualityPercentage = 80;
// Initialize ladybug camera
const LadybugError grabberInitError = init_camera();
if (LADYBUG_OK != init_camera())
{
ROS_INFO("Error: Failed to initialize camera (%s). Terminating...", ladybugErrorToString(grabberInitError) );
return -1;
}
LadybugCameraInfo camInfo;
if (LADYBUG_OK != ladybugGetCameraInfo(m_context, &camInfo))
{
ROS_INFO("Error: Failed to get camera information. Terminating...");
return -1;
}
const LadybugError startError = start_camera();
if (startError != LADYBUG_OK)
{
ROS_INFO("Error: Failed to start camera (%s). Terminating...", ladybugErrorToString(startError) );
return -1;
}
/////////////////////
//ROS
// Get the camera information
///////calibration data
sensor_msgs::CameraInfo camerainfo_msg;
GetMatricesFromFile(private_nh, camerainfo_msg);
int image_scale = 100;
if (private_nh.getParam("scale", image_scale) && image_scale>0 && image_scale<100)
{
ROS_INFO("Ladybug ImageScale > %i%%", image_scale);
}
else
{
ROS_INFO("Ladybug ImageScale scale must be (0,100]. Defaulting to 20 ");
image_scale=20;
}
ros::Publisher camera_info_pub;
camera_info_pub = n.advertise<sensor_msgs::CameraInfo>("/camera/camera_info", 1, true);
ROS_INFO("Successfully started ladybug camera and stream");
for (int i = 0; i < LADYBUG_NUM_CAMERAS + 1; i++) {
std::string topic(std::string("image_raw"));
topic = "camera" + std::to_string(i) + "/" + topic;
pub[i] = n.advertise<sensor_msgs::Image>(topic, 100);
ROS_INFO("Publishing.. %s", topic.c_str());
}
//////////////////
//start camera
ros::Rate loop_rate(10); // Hz Ladybug works at 10fps
long int count = 0;
while (running_ && ros::ok())
{
LadybugImage currentImage;
const LadybugError acquisitionError = acquire_image(currentImage);
if (acquisitionError != LADYBUG_OK)
{
ROS_INFO("Failed to acquire image. Error (%s). Trying to continue..", ladybugErrorToString(acquisitionError) );
continue;
}
// convert to OpenCV Mat
//receive Bayer Image, convert to Color 3 channels
cv::Size size(currentImage.uiFullCols, currentImage.uiFullRows);
cv::Mat full_size;
for(size_t i =0;i<LADYBUG_NUM_CAMERAS; i++)
{
std::ostringstream out;
out << "image" << i;
cv::Mat rawImage(size, CV_8UC1, currentImage.pData + (i * size.width*size.height));
cv::Mat image(size, CV_8UC3);
cv::cvtColor(rawImage, image, cv::COLOR_BayerBG2RGB);
cv::resize(image,image,cv::Size(size.width*image_scale/100, size.height*image_scale/100));
//
cv::transpose(image, image);
cv::flip(image, image, 1);
if (i==0)
image.copyTo(full_size);
else
cv::hconcat(image, full_size, full_size);
unlock_image(currentImage.uiBufferIndex);
publishImage(image, pub[LADYBUG_NUM_CAMERAS - i], count);
}
//publish stitched one
publishImage(full_size, pub[0], count);
ros::spinOnce();
loop_rate.sleep();
count++;
}
cout << "Stopping ladybug_camera..." << endl;
// Shutdown
stop_camera();
ROS_INFO("ladybug_camera stopped");
return 0;
}
<|endoftext|>
|
<commit_before>/** @file
Implementation of the Layout class.
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "libts.h"
#include "I_Layout.h"
static Layout *layout = NULL;
Layout *
Layout::get()
{
if (layout == NULL) {
ink_assert("need to call create_default_layout before accessing" "default_layout()");
}
return layout;
}
void
Layout::create(const char *prefix)
{
if (layout == NULL) {
layout = NEW(new Layout(prefix));
}
}
static char *
layout_relative(const char *root, const char *file)
{
char path[PATH_NAME_MAX];
if (ink_filepath_merge(path, PATH_NAME_MAX, root, file, INK_FILEPATH_TRUENAME)) {
int err = errno;
// Log error
if (err == EACCES) {
ink_error("Cannot merge path '%s' above the root '%s'\n", file, root);
} else if (err == E2BIG) {
ink_error("Excedding file name length limit of %d characters\n", PATH_NAME_MAX);
}
else {
// TODO: Make some pretty errors.
ink_error("Cannot merge '%s' with '%s' error=%d\n", file, root, err);
}
return NULL;
}
return ats_strdup(path);
}
char *
Layout::relative(const char *file)
{
return layout_relative(prefix, file);
}
void
Layout::relative(char *buf, size_t bufsz, const char *file)
{
char path[PATH_NAME_MAX];
if (ink_filepath_merge(path, PATH_NAME_MAX, prefix, file,
INK_FILEPATH_TRUENAME)) {
int err = errno;
// Log error
if (err == EACCES) {
ink_error("Cannot merge path '%s' above the root '%s'\n", file, prefix);
} else if (err == E2BIG) {
ink_error("Excedding file name length limit of %d characters\n", PATH_NAME_MAX);
}
else {
// TODO: Make some pretty errors.
ink_error("Cannot merge '%s' with '%s' error=%d\n", file, prefix, err);
}
return;
}
size_t path_len = strlen(path) + 1;
if (path_len > bufsz) {
ink_error("Provided buffer is too small: %d, required %d\n", bufsz, path_len);
}
else {
ink_strlcpy(buf, path, bufsz);
}
}
char *
Layout::relative_to(const char *dir, const char *file)
{
return layout_relative(dir, file);
}
void
Layout::relative_to(char *buf, size_t bufsz, const char *dir, const char *file)
{
char path[PATH_NAME_MAX];
if (ink_filepath_merge(path, PATH_NAME_MAX, dir, file, INK_FILEPATH_TRUENAME)) {
int err = errno;
// Log error
if (err == EACCES) {
ink_error("Cannot merge path '%s' above the root '%s'\n", file, dir);
} else if (err == E2BIG) {
ink_error("Excedding file name length limit of %d characters\n", PATH_NAME_MAX);
}
else {
// TODO: Make some pretty errors.
ink_error("Cannot merge '%s' with '%s' error=%d\n", file, dir, err);
}
return;
}
size_t path_len = strlen(path) + 1;
if (path_len > bufsz) {
ink_error("Provided buffer is too small: %d, required %d\n", bufsz, path_len);
}
else {
ink_strlcpy(buf, path, bufsz);
}
}
Layout::Layout(const char *_prefix)
{
if (_prefix) {
prefix = ats_strdup(_prefix);
} else {
char *env_path;
char path[PATH_NAME_MAX];
int len;
if ((env_path = getenv("TS_ROOT"))) {
len = strlen(env_path);
if ((len + 1) > PATH_NAME_MAX) {
ink_error("TS_ROOT environment variable is too big: %d, max %d\n", len, PATH_NAME_MAX -1);
return;
}
ink_strlcpy(path, env_path, sizeof(path));
while (len > 1 && path[len - 1] == '/') {
path[len - 1] = '\0';
--len;
}
} else {
// Use compile time --prefix
ink_strlcpy(path, TS_BUILD_PREFIX, sizeof(path));
}
if (access(path, R_OK) == -1) {
ink_error("unable to access() TS_ROOT '%s': %d, %s\n", path, errno, strerror(errno));
return;
}
prefix = ats_strdup(path);
}
exec_prefix = layout_relative(prefix, TS_BUILD_EXEC_PREFIX);
bindir = layout_relative(prefix, TS_BUILD_BINDIR);
sbindir = layout_relative(prefix, TS_BUILD_SBINDIR);
sysconfdir = layout_relative(prefix, TS_BUILD_SYSCONFDIR);
datadir = layout_relative(prefix, TS_BUILD_DATADIR);
includedir = layout_relative(prefix, TS_BUILD_INCLUDEDIR);
libdir = layout_relative(prefix, TS_BUILD_LIBDIR);
libexecdir = layout_relative(prefix, TS_BUILD_LIBEXECDIR);
localstatedir = layout_relative(prefix, TS_BUILD_LOCALSTATEDIR);
runtimedir = layout_relative(prefix, TS_BUILD_RUNTIMEDIR);
logdir = layout_relative(prefix, TS_BUILD_LOGDIR);
mandir = layout_relative(prefix, TS_BUILD_MANDIR);
infodir = layout_relative(prefix, TS_BUILD_INFODIR);
cachedir = layout_relative(prefix, TS_BUILD_CACHEDIR);
#ifdef DEBUG
// TODO: Use a propper Debug logging
//
#define PrintSTR(var) \
fprintf(stdout, "%18s = '%s'\n", "--" #var, (var == NULL? "NULL" : var));
fprintf(stdout, "Layout configuration\n");
PrintSTR(prefix);
PrintSTR(exec_prefix);
PrintSTR(bindir);
PrintSTR(sbindir);
PrintSTR(sysconfdir);
PrintSTR(datadir);
PrintSTR(includedir);
PrintSTR(libdir);
PrintSTR(libexecdir);
PrintSTR(localstatedir);
PrintSTR(runtimedir);
PrintSTR(logdir);
PrintSTR(mandir);
PrintSTR(infodir);
PrintSTR(cachedir);
#endif
}
Layout::~Layout()
{
ats_free(prefix);
ats_free(exec_prefix);
ats_free(bindir);
ats_free(sbindir);
ats_free(sysconfdir);
ats_free(datadir);
ats_free(includedir);
ats_free(libdir);
ats_free(libexecdir);
ats_free(localstatedir);
ats_free(runtimedir);
ats_free(logdir);
ats_free(mandir);
ats_free(infodir);
ats_free(cachedir);
}
<commit_msg>Fix typos, no code change<commit_after>/** @file
Implementation of the Layout class.
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "libts.h"
#include "I_Layout.h"
static Layout *layout = NULL;
Layout *
Layout::get()
{
if (layout == NULL) {
ink_assert("need to call create_default_layout before accessing" "default_layout()");
}
return layout;
}
void
Layout::create(const char *prefix)
{
if (layout == NULL) {
layout = NEW(new Layout(prefix));
}
}
static char *
layout_relative(const char *root, const char *file)
{
char path[PATH_NAME_MAX];
if (ink_filepath_merge(path, PATH_NAME_MAX, root, file, INK_FILEPATH_TRUENAME)) {
int err = errno;
// Log error
if (err == EACCES) {
ink_error("Cannot merge path '%s' above the root '%s'\n", file, root);
} else if (err == E2BIG) {
ink_error("Exceeding file name length limit of %d characters\n", PATH_NAME_MAX);
}
else {
// TODO: Make some pretty errors.
ink_error("Cannot merge '%s' with '%s' error=%d\n", file, root, err);
}
return NULL;
}
return ats_strdup(path);
}
char *
Layout::relative(const char *file)
{
return layout_relative(prefix, file);
}
void
Layout::relative(char *buf, size_t bufsz, const char *file)
{
char path[PATH_NAME_MAX];
if (ink_filepath_merge(path, PATH_NAME_MAX, prefix, file,
INK_FILEPATH_TRUENAME)) {
int err = errno;
// Log error
if (err == EACCES) {
ink_error("Cannot merge path '%s' above the root '%s'\n", file, prefix);
} else if (err == E2BIG) {
ink_error("Exceeding file name length limit of %d characters\n", PATH_NAME_MAX);
}
else {
// TODO: Make some pretty errors.
ink_error("Cannot merge '%s' with '%s' error=%d\n", file, prefix, err);
}
return;
}
size_t path_len = strlen(path) + 1;
if (path_len > bufsz) {
ink_error("Provided buffer is too small: %d, required %d\n", bufsz, path_len);
}
else {
ink_strlcpy(buf, path, bufsz);
}
}
char *
Layout::relative_to(const char *dir, const char *file)
{
return layout_relative(dir, file);
}
void
Layout::relative_to(char *buf, size_t bufsz, const char *dir, const char *file)
{
char path[PATH_NAME_MAX];
if (ink_filepath_merge(path, PATH_NAME_MAX, dir, file, INK_FILEPATH_TRUENAME)) {
int err = errno;
// Log error
if (err == EACCES) {
ink_error("Cannot merge path '%s' above the root '%s'\n", file, dir);
} else if (err == E2BIG) {
ink_error("Exceeding file name length limit of %d characters\n", PATH_NAME_MAX);
}
else {
// TODO: Make some pretty errors.
ink_error("Cannot merge '%s' with '%s' error=%d\n", file, dir, err);
}
return;
}
size_t path_len = strlen(path) + 1;
if (path_len > bufsz) {
ink_error("Provided buffer is too small: %d, required %d\n", bufsz, path_len);
}
else {
ink_strlcpy(buf, path, bufsz);
}
}
Layout::Layout(const char *_prefix)
{
if (_prefix) {
prefix = ats_strdup(_prefix);
} else {
char *env_path;
char path[PATH_NAME_MAX];
int len;
if ((env_path = getenv("TS_ROOT"))) {
len = strlen(env_path);
if ((len + 1) > PATH_NAME_MAX) {
ink_error("TS_ROOT environment variable is too big: %d, max %d\n", len, PATH_NAME_MAX -1);
return;
}
ink_strlcpy(path, env_path, sizeof(path));
while (len > 1 && path[len - 1] == '/') {
path[len - 1] = '\0';
--len;
}
} else {
// Use compile time --prefix
ink_strlcpy(path, TS_BUILD_PREFIX, sizeof(path));
}
if (access(path, R_OK) == -1) {
ink_error("unable to access() TS_ROOT '%s': %d, %s\n", path, errno, strerror(errno));
return;
}
prefix = ats_strdup(path);
}
exec_prefix = layout_relative(prefix, TS_BUILD_EXEC_PREFIX);
bindir = layout_relative(prefix, TS_BUILD_BINDIR);
sbindir = layout_relative(prefix, TS_BUILD_SBINDIR);
sysconfdir = layout_relative(prefix, TS_BUILD_SYSCONFDIR);
datadir = layout_relative(prefix, TS_BUILD_DATADIR);
includedir = layout_relative(prefix, TS_BUILD_INCLUDEDIR);
libdir = layout_relative(prefix, TS_BUILD_LIBDIR);
libexecdir = layout_relative(prefix, TS_BUILD_LIBEXECDIR);
localstatedir = layout_relative(prefix, TS_BUILD_LOCALSTATEDIR);
runtimedir = layout_relative(prefix, TS_BUILD_RUNTIMEDIR);
logdir = layout_relative(prefix, TS_BUILD_LOGDIR);
mandir = layout_relative(prefix, TS_BUILD_MANDIR);
infodir = layout_relative(prefix, TS_BUILD_INFODIR);
cachedir = layout_relative(prefix, TS_BUILD_CACHEDIR);
#ifdef DEBUG
// TODO: Use a propper Debug logging
//
#define PrintSTR(var) \
fprintf(stdout, "%18s = '%s'\n", "--" #var, (var == NULL? "NULL" : var));
fprintf(stdout, "Layout configuration\n");
PrintSTR(prefix);
PrintSTR(exec_prefix);
PrintSTR(bindir);
PrintSTR(sbindir);
PrintSTR(sysconfdir);
PrintSTR(datadir);
PrintSTR(includedir);
PrintSTR(libdir);
PrintSTR(libexecdir);
PrintSTR(localstatedir);
PrintSTR(runtimedir);
PrintSTR(logdir);
PrintSTR(mandir);
PrintSTR(infodir);
PrintSTR(cachedir);
#endif
}
Layout::~Layout()
{
ats_free(prefix);
ats_free(exec_prefix);
ats_free(bindir);
ats_free(sbindir);
ats_free(sysconfdir);
ats_free(datadir);
ats_free(includedir);
ats_free(libdir);
ats_free(libexecdir);
ats_free(localstatedir);
ats_free(runtimedir);
ats_free(logdir);
ats_free(mandir);
ats_free(infodir);
ats_free(cachedir);
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File Stdexpansion.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Definition of methods in class StdExpansion which is
// the base class to all expansion shapes
//
///////////////////////////////////////////////////////////////////////////////
#include <StdRegions/StdExpansion.h>
namespace Nektar
{
namespace StdRegions
{
/** define list of number of vertices corresponding to each ShapeType */
const int g_shapenverts[SIZE_ShapeType] = {0,2,3,4,4,5,6,8};
/** define list of number of edges corresponding to each ShapeType */
const int g_shapenedges[SIZE_ShapeType] = {0,1,3,4,6,8,9,12};
/** define list of number of faces corresponding to each ShapeType */
const int g_shapenfaces[SIZE_ShapeType] = {0,0,0,0,4,5,5,6};
StdExpansion::StdExpansion(void):
m_numbases(0),
m_ncoeffs(0)
{
}
StdExpansion::StdExpansion(int numbases,
const LibUtilities::BasisKey &Ba,
const LibUtilities::BasisKey &Bb,
const LibUtilities::BasisKey &Bc,
int numcoeffs):
m_numbases(numbases)
{
m_base = MemoryManager::AllocateArray<LibUtilities::BasisSharedPtr>(m_numbases);
switch(m_numbases)
{
case 3:
ASSERTL2(Bc==LibUtilities::NullBasisKey,
"NULL Basis attempting to be used.");
m_base[2] = LibUtilities::BasisManager()[Bc];
case 2:
ASSERTL2(Bb==LibUtilities::NullBasisKey,
"NULL Basis attempting to be used.");
m_base[1] = LibUtilities::BasisManager()[Bb];
case 1:
ASSERTL2(Ba==LibUtilities::NullBasisKey,
"NULL Basis attempting to be used.");
m_base[0] = LibUtilities::BasisManager()[Ba];
break;
default:
ASSERTL0(false, "numbases incorrectly specified");
};
//allocate memory for coeffs
m_ncoeffs = numcoeffs;
m_coeffs = MemoryManager::AllocateSharedArray<double>(m_ncoeffs);
Vmath::Zero(m_ncoeffs,&m_coeffs[0],1);
//allocate memory for phys
m_phys = MemoryManager::AllocateSharedArray<double>(GetTotPoints());
//allocate memory for phys
m_phys = MemoryManager::AllocateSharedArray<double>(GetTotPoints());
} //end constructor
StdExpansion::StdExpansion(const StdExpansion &T):
m_numbases(T.m_numbases)
{
int i,j;
m_base = MemoryManager::AllocateArray<LibUtilities::BasisSharedPtr>(m_numbases);
for(j=0; j<m_numbases; j++)
{
m_base[j] = T.m_base[j];
}
// NOTE: Copy Constructor produces a deep copy
// allocate memory for coeffs
// need to check allocation for variable order.
m_ncoeffs = T.m_ncoeffs;
m_coeffs = MemoryManager::AllocateSharedArray<double>(m_ncoeffs);
for(i=0; i<m_ncoeffs; i++)
{
m_coeffs[i] = T.m_coeffs[i];
}
//allocate memory for phys
int numphys = GetTotPoints();
m_phys = MemoryManager::AllocateSharedArray<double>(GetTotPoints());
for(j=0; j < numphys; j++)
{
m_phys[j] = T.m_phys[j];
}
}
StdExpansion::~StdExpansion()
{
}
double StdExpansion::Linf(const double *sol)
{
int ntot;
double val;
double *tmp;
BstShrDArray wsp;
ntot = GetTotPoints();
wsp = GetDoubleTmpSpace(ntot);
tmp = wsp.get();
Vmath::Vsub(ntot,sol,1,&m_phys[0],1,tmp,1);
Vmath::Vabs(ntot,tmp,1,tmp,1);
val = Vmath::Vamax(ntot,tmp,1);
return val;
}
double StdExpansion::Linf()
{
return Vmath::Vamax(GetTotPoints(),&m_phys[0],1);
}
double StdExpansion::L2(const double *sol)
{
int ntot = GetTotPoints();
double val;
double *tmp;
BstShrDArray wsp;
wsp = GetDoubleTmpSpace(ntot);
tmp = wsp.get();
Vmath::Vsub(ntot, sol, 1, &m_phys[0], 1, tmp, 1);
Vmath::Vmul(ntot, tmp, 1, tmp, 1, tmp, 1);
val = sqrt(v_Integral(tmp));
return val;
}
double StdExpansion::L2()
{
int ntot = GetTotPoints();
double val;
double *tmp;
BstShrDArray wsp;
wsp = GetDoubleTmpSpace(ntot);
tmp = wsp.get();
Vmath::Vmul(ntot, &m_phys[0], 1, &m_phys[0], 1, tmp, 1);
val = sqrt(v_Integral(tmp));
return val;
}
DNekMatSharedPtr StdExpansion::GenerateMassMatrix()
{
int i;
BstShrDArray store = GetDoubleTmpSpace(m_ncoeffs);
BstShrDArray tmp = GetDoubleTmpSpace(GetTotPoints());
DNekMatSharedPtr Mat;
Mat = MemoryManager::AllocateSharedPtr<DNekMat>(m_ncoeffs,m_ncoeffs);
Blas::Dcopy(m_ncoeffs,&m_coeffs[0],1,&store[0],1);
for(i=0; i<m_ncoeffs; ++i)
{
v_FillMode(i, &tmp[0]);
v_IProductWRTBase(&tmp[0], &((*Mat).GetPtr())[0]+i*m_ncoeffs);
}
Blas::Dcopy(m_ncoeffs,&store[0],1,&m_coeffs[0],1);
return Mat;
}
// 2D Interpolation
void StdExpansion::Interp2D(const LibUtilities::BasisKey *fbasis0,
const LibUtilities::BasisKey *fbasis1, const double *from,
const LibUtilities::BasisKey *tbasis0,
const LibUtilities::BasisKey* tbasis1, double *to)
{
DNekMatSharedPtr I0,I1;
double *tmp;
BstShrDArray wsp = GetDoubleTmpSpace(tbasis1->GetNumPoints()*
fbasis0->GetNumPoints());
tmp = wsp.get();
I0 = LibUtilities::PointsManager()[fbasis0->GetPointsKey()]
->GetI(tbasis0->GetPointsKey());
I1 = LibUtilities::PointsManager()[fbasis1->GetPointsKey()]
->GetI(tbasis1->GetPointsKey());
Blas::Dgemm('T', 'T', tbasis1->GetNumPoints(), fbasis0->GetNumPoints(),
fbasis1->GetNumPoints(), 1.0, &((*I1).GetPtr())[0],
fbasis1->GetNumPoints(),
(double *) from,fbasis0->GetNumPoints(), 0.0, tmp,
tbasis1->GetNumPoints());
Blas::Dgemm('T', 'T',tbasis0->GetNumPoints(),tbasis1->GetNumPoints(),
fbasis0->GetNumPoints(),1.0,&((*I0).GetPtr())[0],
fbasis0->GetNumPoints(),tmp, tbasis1->GetNumPoints(),
0.0,to, tbasis0->GetNumPoints());
}
// 1D Interpolation
void StdExpansion::Interp1D(const LibUtilities::BasisKey *fbasis0, const double *from,
const LibUtilities::BasisKey *tbasis0, double *to)
{
DNekMatSharedPtr I0;
I0 = LibUtilities::PointsManager()[fbasis0->GetPointsKey()]
->GetI(tbasis0->GetPointsKey());
Blas::Dgemv('T', fbasis0->GetNumPoints(), tbasis0->GetNumPoints(),
1.0, &((*I0).GetPtr())[0], fbasis0->GetNumPoints(),
from, 1, 0.0, to, 1);
}
// I/O routine
void StdExpansion::WriteCoeffsToFile(std::ofstream &outfile)
{
int i;
for(i=0; i<m_ncoeffs; ++i)
{
outfile << m_coeffs[i] << std::endl;
}
}
}//end namespace
}//end namespace
/**
* $Log: StdExpansion.cpp,v $
* Revision 1.13 2007/02/07 12:51:52 sherwin
* Compiling version of Project1D
*
* Revision 1.12 2007/02/06 02:23:28 jfrazier
* Minor cleanup.
*
* Revision 1.11 2007/01/30 20:01:35 sherwin
* Update for first compiling Project1D routine
*
* Revision 1.10 2007/01/29 15:04:53 sherwin
* StdBasis.h moved to LibUtilities. Other minor mods
*
* Revision 1.9 2007/01/28 18:34:18 sherwin
* More modifications to make Demo Project1D compile
*
* Revision 1.8 2007/01/23 23:20:20 sherwin
* New version after Jan 07 update
*
* Revision 1.7 2007/01/20 22:35:20 sherwin
* Version with StdExpansion compiling
*
* Revision 1.6 2007/01/15 11:08:37 pvos
* Updating doxygen documentation
*
* Revision 1.5 2006/12/10 19:00:54 sherwin
* Modifications to handle nodal expansions
*
* Revision 1.4 2006/08/05 19:03:48 sherwin
* Update to make the multiregions 2D expansion in connected regions work
*
* Revision 1.3 2006/06/01 14:46:16 kirby
* *** empty log message ***
*
* Revision 1.2 2006/05/29 19:03:08 sherwin
* Modifications to wrap geometric information in shared_ptr
*
* Revision 1.1 2006/05/04 18:58:31 kirby
* *** empty log message ***
*
* Revision 1.54 2006/04/25 20:23:33 jfrazier
* Various fixes to correct bugs, calls to ASSERT, etc.
*
* Revision 1.53 2006/04/01 21:59:26 sherwin
* Sorted new definition of ASSERT
*
* Revision 1.52 2006/03/21 09:21:31 sherwin
* Introduced NekMemoryManager
*
* Revision 1.51 2006/03/12 14:20:44 sherwin
*
* First compiling version of SpatialDomains and associated modifications
*
* Revision 1.50 2006/03/06 12:39:59 sherwin
*
* Added NekConstants class for all constants in this library
*
* Revision 1.49 2006/03/05 22:11:02 sherwin
*
* Sorted out Project1D, Project2D and Project_Diff2D as well as some test scripts
*
* Revision 1.48 2006/03/03 23:04:54 sherwin
*
* Corrected Mistake in StdBasis.cpp to do with eModified_B
*
* Revision 1.47 2006/03/02 16:20:20 sherwin
*
* Introduced method GetPointsTot
*
* Revision 1.46 2006/03/01 08:25:03 sherwin
*
* First compiling version of StdRegions
*
* Revision 1.45 2006/02/26 23:37:29 sherwin
*
* Updates and compiling checks upto StdExpansions1D
*
* Revision 1.44 2006/02/26 21:23:20 bnelson
* Fixed a variety of compiler errors caused by updates to the coding standard.
*
* Revision 1.43 2006/02/15 08:06:36 sherwin
*
* Put files into coding standard (although they do not compile)
*
* Revision 1.42 2006/02/12 21:51:42 sherwin
*
* Added licence
*
* Revision 1.41 2006/02/10 16:44:10 sherwin
*
* Updated to comply with coding standard
*
**/
<commit_msg>Corrected an error in the code<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File Stdexpansion.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Definition of methods in class StdExpansion which is
// the base class to all expansion shapes
//
///////////////////////////////////////////////////////////////////////////////
#include <StdRegions/StdExpansion.h>
namespace Nektar
{
namespace StdRegions
{
/** define list of number of vertices corresponding to each ShapeType */
const int g_shapenverts[SIZE_ShapeType] = {0,2,3,4,4,5,6,8};
/** define list of number of edges corresponding to each ShapeType */
const int g_shapenedges[SIZE_ShapeType] = {0,1,3,4,6,8,9,12};
/** define list of number of faces corresponding to each ShapeType */
const int g_shapenfaces[SIZE_ShapeType] = {0,0,0,0,4,5,5,6};
StdExpansion::StdExpansion(void):
m_numbases(0),
m_ncoeffs(0)
{
}
StdExpansion::StdExpansion(int numbases,
const LibUtilities::BasisKey &Ba,
const LibUtilities::BasisKey &Bb,
const LibUtilities::BasisKey &Bc,
int numcoeffs):
m_numbases(numbases)
{
m_base = MemoryManager::AllocateArray<LibUtilities::BasisSharedPtr>(m_numbases);
switch(m_numbases)
{
case 3:
ASSERTL2(Bc==LibUtilities::NullBasisKey,
"NULL Basis attempting to be used.");
m_base[2] = LibUtilities::BasisManager()[Bc];
case 2:
ASSERTL2(Bb==LibUtilities::NullBasisKey,
"NULL Basis attempting to be used.");
m_base[1] = LibUtilities::BasisManager()[Bb];
case 1:
ASSERTL2(Ba==LibUtilities::NullBasisKey,
"NULL Basis attempting to be used.");
m_base[0] = LibUtilities::BasisManager()[Ba];
break;
default:
ASSERTL0(false, "numbases incorrectly specified");
};
//allocate memory for coeffs
m_ncoeffs = numcoeffs;
m_coeffs = MemoryManager::AllocateSharedArray<double>(m_ncoeffs);
Vmath::Zero(m_ncoeffs,&m_coeffs[0],1);
//allocate memory for phys
m_phys = MemoryManager::AllocateSharedArray<double>(GetTotPoints());
} //end constructor
StdExpansion::StdExpansion(const StdExpansion &T):
m_numbases(T.m_numbases)
{
int i,j;
m_base = MemoryManager::AllocateArray<LibUtilities::BasisSharedPtr>(m_numbases);
for(j=0; j<m_numbases; j++)
{
m_base[j] = T.m_base[j];
}
// NOTE: Copy Constructor produces a deep copy
// allocate memory for coeffs
// need to check allocation for variable order.
m_ncoeffs = T.m_ncoeffs;
m_coeffs = MemoryManager::AllocateSharedArray<double>(m_ncoeffs);
for(i=0; i<m_ncoeffs; i++)
{
m_coeffs[i] = T.m_coeffs[i];
}
//allocate memory for phys
int numphys = GetTotPoints();
m_phys = MemoryManager::AllocateSharedArray<double>(GetTotPoints());
for(j=0; j < numphys; j++)
{
m_phys[j] = T.m_phys[j];
}
}
StdExpansion::~StdExpansion()
{
}
double StdExpansion::Linf(const double *sol)
{
int ntot;
double val;
double *tmp;
BstShrDArray wsp;
ntot = GetTotPoints();
wsp = GetDoubleTmpSpace(ntot);
tmp = wsp.get();
Vmath::Vsub(ntot,sol,1,&m_phys[0],1,tmp,1);
Vmath::Vabs(ntot,tmp,1,tmp,1);
val = Vmath::Vamax(ntot,tmp,1);
return val;
}
double StdExpansion::Linf()
{
return Vmath::Vamax(GetTotPoints(),&m_phys[0],1);
}
double StdExpansion::L2(const double *sol)
{
int ntot = GetTotPoints();
double val;
double *tmp;
BstShrDArray wsp;
wsp = GetDoubleTmpSpace(ntot);
tmp = wsp.get();
Vmath::Vsub(ntot, sol, 1, &m_phys[0], 1, tmp, 1);
Vmath::Vmul(ntot, tmp, 1, tmp, 1, tmp, 1);
val = sqrt(v_Integral(tmp));
return val;
}
double StdExpansion::L2()
{
int ntot = GetTotPoints();
double val;
double *tmp;
BstShrDArray wsp;
wsp = GetDoubleTmpSpace(ntot);
tmp = wsp.get();
Vmath::Vmul(ntot, &m_phys[0], 1, &m_phys[0], 1, tmp, 1);
val = sqrt(v_Integral(tmp));
return val;
}
DNekMatSharedPtr StdExpansion::GenerateMassMatrix()
{
int i;
BstShrDArray store = GetDoubleTmpSpace(m_ncoeffs);
BstShrDArray tmp = GetDoubleTmpSpace(GetTotPoints());
DNekMatSharedPtr Mat;
Mat = MemoryManager::AllocateSharedPtr<DNekMat>(m_ncoeffs,m_ncoeffs);
Blas::Dcopy(m_ncoeffs,&m_coeffs[0],1,&store[0],1);
for(i=0; i<m_ncoeffs; ++i)
{
v_FillMode(i, &tmp[0]);
v_IProductWRTBase(&tmp[0], &((*Mat).GetPtr())[0]+i*m_ncoeffs);
}
Blas::Dcopy(m_ncoeffs,&store[0],1,&m_coeffs[0],1);
return Mat;
}
// 2D Interpolation
void StdExpansion::Interp2D(const LibUtilities::BasisKey *fbasis0,
const LibUtilities::BasisKey *fbasis1, const double *from,
const LibUtilities::BasisKey *tbasis0,
const LibUtilities::BasisKey* tbasis1, double *to)
{
DNekMatSharedPtr I0,I1;
double *tmp;
BstShrDArray wsp = GetDoubleTmpSpace(tbasis1->GetNumPoints()*
fbasis0->GetNumPoints());
tmp = wsp.get();
I0 = LibUtilities::PointsManager()[fbasis0->GetPointsKey()]
->GetI(tbasis0->GetPointsKey());
I1 = LibUtilities::PointsManager()[fbasis1->GetPointsKey()]
->GetI(tbasis1->GetPointsKey());
Blas::Dgemm('T', 'T', tbasis1->GetNumPoints(), fbasis0->GetNumPoints(),
fbasis1->GetNumPoints(), 1.0, &((*I1).GetPtr())[0],
fbasis1->GetNumPoints(),
(double *) from,fbasis0->GetNumPoints(), 0.0, tmp,
tbasis1->GetNumPoints());
Blas::Dgemm('T', 'T',tbasis0->GetNumPoints(),tbasis1->GetNumPoints(),
fbasis0->GetNumPoints(),1.0,&((*I0).GetPtr())[0],
fbasis0->GetNumPoints(),tmp, tbasis1->GetNumPoints(),
0.0,to, tbasis0->GetNumPoints());
}
// 1D Interpolation
void StdExpansion::Interp1D(const LibUtilities::BasisKey *fbasis0, const double *from,
const LibUtilities::BasisKey *tbasis0, double *to)
{
DNekMatSharedPtr I0;
I0 = LibUtilities::PointsManager()[fbasis0->GetPointsKey()]
->GetI(tbasis0->GetPointsKey());
Blas::Dgemv('T', fbasis0->GetNumPoints(), tbasis0->GetNumPoints(),
1.0, &((*I0).GetPtr())[0], fbasis0->GetNumPoints(),
from, 1, 0.0, to, 1);
}
// I/O routine
void StdExpansion::WriteCoeffsToFile(std::ofstream &outfile)
{
int i;
for(i=0; i<m_ncoeffs; ++i)
{
outfile << m_coeffs[i] << std::endl;
}
}
}//end namespace
}//end namespace
/**
* $Log: StdExpansion.cpp,v $
* Revision 1.14 2007/02/13 09:52:27 sherwin
* Updates to fix mass matrix inverse issues
*
* Revision 1.13 2007/02/07 12:51:52 sherwin
* Compiling version of Project1D
*
* Revision 1.12 2007/02/06 02:23:28 jfrazier
* Minor cleanup.
*
* Revision 1.11 2007/01/30 20:01:35 sherwin
* Update for first compiling Project1D routine
*
* Revision 1.10 2007/01/29 15:04:53 sherwin
* StdBasis.h moved to LibUtilities. Other minor mods
*
* Revision 1.9 2007/01/28 18:34:18 sherwin
* More modifications to make Demo Project1D compile
*
* Revision 1.8 2007/01/23 23:20:20 sherwin
* New version after Jan 07 update
*
* Revision 1.7 2007/01/20 22:35:20 sherwin
* Version with StdExpansion compiling
*
* Revision 1.6 2007/01/15 11:08:37 pvos
* Updating doxygen documentation
*
* Revision 1.5 2006/12/10 19:00:54 sherwin
* Modifications to handle nodal expansions
*
* Revision 1.4 2006/08/05 19:03:48 sherwin
* Update to make the multiregions 2D expansion in connected regions work
*
* Revision 1.3 2006/06/01 14:46:16 kirby
* *** empty log message ***
*
* Revision 1.2 2006/05/29 19:03:08 sherwin
* Modifications to wrap geometric information in shared_ptr
*
* Revision 1.1 2006/05/04 18:58:31 kirby
* *** empty log message ***
*
* Revision 1.54 2006/04/25 20:23:33 jfrazier
* Various fixes to correct bugs, calls to ASSERT, etc.
*
* Revision 1.53 2006/04/01 21:59:26 sherwin
* Sorted new definition of ASSERT
*
* Revision 1.52 2006/03/21 09:21:31 sherwin
* Introduced NekMemoryManager
*
* Revision 1.51 2006/03/12 14:20:44 sherwin
*
* First compiling version of SpatialDomains and associated modifications
*
* Revision 1.50 2006/03/06 12:39:59 sherwin
*
* Added NekConstants class for all constants in this library
*
* Revision 1.49 2006/03/05 22:11:02 sherwin
*
* Sorted out Project1D, Project2D and Project_Diff2D as well as some test scripts
*
* Revision 1.48 2006/03/03 23:04:54 sherwin
*
* Corrected Mistake in StdBasis.cpp to do with eModified_B
*
* Revision 1.47 2006/03/02 16:20:20 sherwin
*
* Introduced method GetPointsTot
*
* Revision 1.46 2006/03/01 08:25:03 sherwin
*
* First compiling version of StdRegions
*
* Revision 1.45 2006/02/26 23:37:29 sherwin
*
* Updates and compiling checks upto StdExpansions1D
*
* Revision 1.44 2006/02/26 21:23:20 bnelson
* Fixed a variety of compiler errors caused by updates to the coding standard.
*
* Revision 1.43 2006/02/15 08:06:36 sherwin
*
* Put files into coding standard (although they do not compile)
*
* Revision 1.42 2006/02/12 21:51:42 sherwin
*
* Added licence
*
* Revision 1.41 2006/02/10 16:44:10 sherwin
*
* Updated to comply with coding standard
*
**/
<|endoftext|>
|
<commit_before>#include <QMessageBox>
#include <iostream>
#include <QByteArray>
#include "ltr_gui.h"
#include "webcam_ft_prefs.h"
#include "wc_driver_prefs.h"
#include "webcam_info.h"
#include "ltr_gui_prefs.h"
static QString currentId = QString("None");
static QString currentSection = QString();
void WebcamFtPrefs::Connect()
{
QObject::connect(gui.WebcamFtFormats, SIGNAL(activated(int)),
this, SLOT(on_WebcamFtFormats_activated(int)));
QObject::connect(gui.WebcamFtResolutions, SIGNAL(activated(int)),
this, SLOT(on_WebcamFtResolutions_activated(int)));
QObject::connect(gui.FindCascade, SIGNAL(pressed()),
this, SLOT(on_FindCascade_pressed()));
QObject::connect(gui.CascadePath, SIGNAL(editingFinished()),
this, SLOT(on_CascadePath_editingFinished()));
QObject::connect(gui.ExpFilterFactor, SIGNAL(valueChanged(int)),
this, SLOT(on_ExpFilterFactor_valueChanged(int)));
QObject::connect(gui.OptimLevel, SIGNAL(valueChanged(int)),
this, SLOT(on_OptimLevel_valueChanged(int)));
}
WebcamFtPrefs::WebcamFtPrefs(const Ui::LinuxtrackMainForm &ui) : gui(ui)
{
Connect();
}
WebcamFtPrefs::~WebcamFtPrefs()
{
}
static WebcamInfo *wc_info = NULL;
void WebcamFtPrefs::on_WebcamFtFormats_activated(int index)
{
gui.WebcamFtResolutions->clear();
if(currentId == "None"){
std::cout<<"None!"<<std::endl;
return;
}
gui.WebcamFtResolutions->addItems(wc_info->getResolutions(index));
int res_index = 0;
int res_x, res_y;
int fps_num, fps_den;
if(ltr_int_wc_get_resolution(&res_x, &res_y) &&
ltr_int_wc_get_fps(&fps_num, &fps_den)){
res_index = wc_info->findRes(res_x, res_y, fps_num, fps_den,
wc_info->getFourcc(index));
gui.WebcamFtResolutions->setCurrentIndex(res_index);
}
on_WebcamFtResolutions_activated(res_index);
}
void WebcamFtPrefs::on_WebcamFtResolutions_activated(int index)
{
if(gui.WebcamFtFormats->currentIndex() == -1){
return;
}
QString res, fps, fmt;
if(wc_info->findFmtSpecs(gui.WebcamFtFormats->currentIndex(),
index, res, fps, fmt)){
int x,y, num, den;
WebcamInfo::decodeRes(res, x, y);
WebcamInfo::decodeFps(fps, num, den);
if(!initializing){
ltr_int_wc_set_pixfmt(fmt.toAscii().data());
ltr_int_wc_set_resolution(x, y);
ltr_int_wc_set_fps(num, den);
}
}
}
bool WebcamFtPrefs::Activate(const QString &ID, bool init)
{
bool res = false;
QString sec;
initializing = init;
if(PREF.getFirstDeviceSection(QString("Webcam-face"), ID, sec)){
if(!initializing) PREF.activateDevice(sec);
currentSection = sec;
}else{
sec = "Webcam-face";
if(PREF.createSection(sec)){
PREF.addKeyVal(sec, (char *)"Capture-device", (char *)"Webcam-face");
PREF.addKeyVal(sec, (char *)"Capture-device-id", ID);
PREF.addKeyVal(sec, (char *)"Pixel-format", (char *)"");
PREF.addKeyVal(sec, (char *)"Resolution", (char *)"");
PREF.addKeyVal(sec, (char *)"Fps", (char *)"");
PREF.activateDevice(sec);
currentSection = sec;
}else{
initializing = false;
return false;
}
}
if(!ltr_int_wc_init_prefs()){
initializing = false;
return false;
}
currentId = ID;
gui.WebcamFtFormats->clear();
gui.WebcamFtResolutions->clear();
if((currentId != "None") && (currentId.size() != 0)){
if(wc_info != NULL){
delete(wc_info);
}
wc_info = new WebcamInfo(currentId);
gui.WebcamFtFormats->addItems(wc_info->getFormats());
QString fourcc, thres, bmin, bmax, res, fps, flip;
int fmt_index = 0;
const char *tmp = ltr_int_wc_get_pixfmt();
if(tmp != NULL){
fourcc = tmp;
fmt_index = wc_info->findFourcc(fourcc);
gui.WebcamFtFormats->setCurrentIndex(fmt_index);
}
on_WebcamFtFormats_activated(fmt_index);
const char *cascade = ltr_int_wc_get_cascade();
QString cascadePath;
if(cascade == NULL){
cascadePath = PrefProxy::getDataPath("haarcascade_frontalface_alt2.xml");
}else{
cascadePath = cascade;
}
gui.CascadePath->setText(cascadePath);
int n = (2.0 / ltr_int_wc_get_eff()) - 2;
gui.ExpFilterFactor->setValue(n);
on_ExpFilterFactor_valueChanged(n);
gui.OptimLevel->setValue(ltr_int_wc_get_optim_level());
}
initializing = false;
return res;
}
bool WebcamFtPrefs::AddAvailableDevices(QComboBox &combo)
{
bool res = false;
QString id;
deviceType_t dt;
bool webcam_selected = false;
if(PREF.getActiveDevice(dt,id) && (dt == WEBCAM_FT)){
webcam_selected = true;
std::cout<<"Facetracker selected!"<<std::endl;
}
QStringList &webcams = WebcamInfo::EnumerateWebcams();
QStringList::iterator i;
PrefsLink *pl;
QVariant v;
for(i = webcams.begin(); i != webcams.end(); ++i){
pl = new PrefsLink(WEBCAM_FT, *i);
v.setValue(*pl);
combo.addItem((*i)+" face tracker", v);
if(webcam_selected && (*i == id)){
combo.setCurrentIndex(combo.count() - 1);
res = true;
}
}
delete(&webcams);
return res;
}
void WebcamFtPrefs::on_FindCascade_pressed()
{
QString path = gui.CascadePath->text();
if(path.isEmpty()){
path = "/";
}else{
QDir tmp(path);
path = tmp.filePath(path);
}
QString fileName = QFileDialog::getOpenFileName(NULL,
"Find Harr/LBP cascade", path, "xml Files (*.xml)");
gui.CascadePath->setText(fileName);
on_CascadePath_editingFinished();
}
void WebcamFtPrefs::on_CascadePath_editingFinished()
{
if(!initializing){
ltr_int_wc_set_cascade(gui.CascadePath->text().toAscii().data());
}
}
void WebcamFtPrefs::on_ExpFilterFactor_valueChanged(int value)
{
float a = 2 / (value + 2.0); //EWMA window size
gui.ExpFiltFactorVal->setText(QString("%1").arg(a, 0, 'g', 2));
if(!initializing){
ltr_int_wc_set_eff(a);
}
}
void WebcamFtPrefs::on_OptimLevel_valueChanged(int value)
{
if(!initializing){
ltr_int_wc_set_optim_level(value);
}
}
<commit_msg>Fixed problem with cascade initialization that was causing segfaults.<commit_after>#include <QMessageBox>
#include <iostream>
#include <QByteArray>
#include "ltr_gui.h"
#include "webcam_ft_prefs.h"
#include "wc_driver_prefs.h"
#include "webcam_info.h"
#include "ltr_gui_prefs.h"
static QString currentId = QString("None");
static QString currentSection = QString();
void WebcamFtPrefs::Connect()
{
QObject::connect(gui.WebcamFtFormats, SIGNAL(activated(int)),
this, SLOT(on_WebcamFtFormats_activated(int)));
QObject::connect(gui.WebcamFtResolutions, SIGNAL(activated(int)),
this, SLOT(on_WebcamFtResolutions_activated(int)));
QObject::connect(gui.FindCascade, SIGNAL(pressed()),
this, SLOT(on_FindCascade_pressed()));
QObject::connect(gui.CascadePath, SIGNAL(editingFinished()),
this, SLOT(on_CascadePath_editingFinished()));
QObject::connect(gui.ExpFilterFactor, SIGNAL(valueChanged(int)),
this, SLOT(on_ExpFilterFactor_valueChanged(int)));
QObject::connect(gui.OptimLevel, SIGNAL(valueChanged(int)),
this, SLOT(on_OptimLevel_valueChanged(int)));
}
WebcamFtPrefs::WebcamFtPrefs(const Ui::LinuxtrackMainForm &ui) : gui(ui)
{
Connect();
}
WebcamFtPrefs::~WebcamFtPrefs()
{
}
static WebcamInfo *wc_info = NULL;
void WebcamFtPrefs::on_WebcamFtFormats_activated(int index)
{
gui.WebcamFtResolutions->clear();
if(currentId == "None"){
std::cout<<"None!"<<std::endl;
return;
}
gui.WebcamFtResolutions->addItems(wc_info->getResolutions(index));
int res_index = 0;
int res_x, res_y;
int fps_num, fps_den;
if(ltr_int_wc_get_resolution(&res_x, &res_y) &&
ltr_int_wc_get_fps(&fps_num, &fps_den)){
res_index = wc_info->findRes(res_x, res_y, fps_num, fps_den,
wc_info->getFourcc(index));
gui.WebcamFtResolutions->setCurrentIndex(res_index);
}
on_WebcamFtResolutions_activated(res_index);
}
void WebcamFtPrefs::on_WebcamFtResolutions_activated(int index)
{
if(gui.WebcamFtFormats->currentIndex() == -1){
return;
}
QString res, fps, fmt;
if(wc_info->findFmtSpecs(gui.WebcamFtFormats->currentIndex(),
index, res, fps, fmt)){
int x,y, num, den;
WebcamInfo::decodeRes(res, x, y);
WebcamInfo::decodeFps(fps, num, den);
if(!initializing){
ltr_int_wc_set_pixfmt(fmt.toAscii().data());
ltr_int_wc_set_resolution(x, y);
ltr_int_wc_set_fps(num, den);
}
}
}
bool WebcamFtPrefs::Activate(const QString &ID, bool init)
{
bool res = false;
QString sec;
initializing = init;
if(PREF.getFirstDeviceSection(QString("Webcam-face"), ID, sec)){
if(!initializing) PREF.activateDevice(sec);
currentSection = sec;
}else{
sec = "Webcam-face";
if(PREF.createSection(sec)){
PREF.addKeyVal(sec, (char *)"Capture-device", (char *)"Webcam-face");
PREF.addKeyVal(sec, (char *)"Capture-device-id", ID);
PREF.addKeyVal(sec, (char *)"Pixel-format", (char *)"");
PREF.addKeyVal(sec, (char *)"Resolution", (char *)"");
PREF.addKeyVal(sec, (char *)"Fps", (char *)"");
QString cascadePath = PrefProxy::getDataPath("haarcascade_frontalface_alt2.xml");
QFileInfo finf = QFileInfo(cascadePath);
PREF.addKeyVal(sec, (char *)"Cascade", qPrintable(finf.canonicalFilePath()));
PREF.activateDevice(sec);
currentSection = sec;
}else{
initializing = false;
return false;
}
}
if(!ltr_int_wc_init_prefs()){
initializing = false;
return false;
}
currentId = ID;
gui.WebcamFtFormats->clear();
gui.WebcamFtResolutions->clear();
if((currentId != "None") && (currentId.size() != 0)){
if(wc_info != NULL){
delete(wc_info);
}
wc_info = new WebcamInfo(currentId);
gui.WebcamFtFormats->addItems(wc_info->getFormats());
QString fourcc, thres, bmin, bmax, res, fps, flip;
int fmt_index = 0;
const char *tmp = ltr_int_wc_get_pixfmt();
if(tmp != NULL){
fourcc = tmp;
fmt_index = wc_info->findFourcc(fourcc);
gui.WebcamFtFormats->setCurrentIndex(fmt_index);
}
on_WebcamFtFormats_activated(fmt_index);
const char *cascade = ltr_int_wc_get_cascade();
QString cascadePath = QString(cascade);
gui.CascadePath->setText(cascadePath);
int n = (2.0 / ltr_int_wc_get_eff()) - 2;
gui.ExpFilterFactor->setValue(n);
on_ExpFilterFactor_valueChanged(n);
gui.OptimLevel->setValue(ltr_int_wc_get_optim_level());
}
initializing = false;
return res;
}
bool WebcamFtPrefs::AddAvailableDevices(QComboBox &combo)
{
bool res = false;
QString id;
deviceType_t dt;
bool webcam_selected = false;
if(PREF.getActiveDevice(dt,id) && (dt == WEBCAM_FT)){
webcam_selected = true;
std::cout<<"Facetracker selected!"<<std::endl;
}
QStringList &webcams = WebcamInfo::EnumerateWebcams();
QStringList::iterator i;
PrefsLink *pl;
QVariant v;
for(i = webcams.begin(); i != webcams.end(); ++i){
pl = new PrefsLink(WEBCAM_FT, *i);
v.setValue(*pl);
combo.addItem((*i)+" face tracker", v);
if(webcam_selected && (*i == id)){
combo.setCurrentIndex(combo.count() - 1);
res = true;
}
}
delete(&webcams);
return res;
}
void WebcamFtPrefs::on_FindCascade_pressed()
{
QString path = gui.CascadePath->text();
if(path.isEmpty()){
path = "/";
}else{
QDir tmp(path);
path = tmp.filePath(path);
}
QString fileName = QFileDialog::getOpenFileName(NULL,
"Find Harr/LBP cascade", path, "xml Files (*.xml)");
gui.CascadePath->setText(fileName);
on_CascadePath_editingFinished();
}
void WebcamFtPrefs::on_CascadePath_editingFinished()
{
if(!initializing){
ltr_int_wc_set_cascade(gui.CascadePath->text().toAscii().data());
}
}
void WebcamFtPrefs::on_ExpFilterFactor_valueChanged(int value)
{
float a = 2 / (value + 2.0); //EWMA window size
gui.ExpFiltFactorVal->setText(QString("%1").arg(a, 0, 'g', 2));
if(!initializing){
ltr_int_wc_set_eff(a);
}
}
void WebcamFtPrefs::on_OptimLevel_valueChanged(int value)
{
if(!initializing){
ltr_int_wc_set_optim_level(value);
}
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <cstring>
#include "cpu.hpp"
#include "../conversion.hpp"
#include "../opcodes.hpp"
#define VALIDATE_ARGS(val1, val2)\
VALIDATE_ARG(val1)\
VALIDATE_ARG(val2)
#define VALIDATE_ARG(value)\
{\
if (((value) & ~0x80) > 0x12)\
return ERR_INVALID_ARG;\
}
#define VALIDATE_PC()\
{\
if (bytes2word(this->pc) >= mem_size)\
return ERR_PC_BOUNDARY;\
}
static inline u32 opcode(u32 instruction)
{
return instruction >> 24;
}
static inline u32 data(u32 instruction)
{
return instruction & 0xffffff;
}
static inline u32 byte(u32 instruction, u8 number)
{
return (instruction >> (8 * (3 - number))) & 0xff;
}
CPU::CPU() :
lc(&this->registers[0x10 * sizeof(u32)]),
sp(&this->registers[0x11 * sizeof(u32)]),
pc(&this->registers[0x12 * sizeof(u32)]),
mem_size(0), memory(NULL),
registers({0}), stack({0}), flags({false, false, false, false}),
extension({0})
{}
CPU::~CPU()
{
free(this->memory);
}
u32
CPU::CurrentInstruction()
{
return bytes2word(this->memory + bytes2word(this->pc) * sizeof(u32));
}
u32
CPU::LastInstruction()
{
return bytes2word(this->memory + (bytes2word(this->pc) - 1) * sizeof(u32));
}
bool
CPU::Initialize(u32 mem_size)
{
if ((this->memory = (u8 *)malloc(mem_size * sizeof(u32))))
this->mem_size = mem_size;
return (bool)this->memory;
}
bool
CPU::Load(FILE *input)
{
int byte;
u32 byte_num = 0;
while ((byte = getc(input)) != EOF && byte_num < this->mem_size * sizeof(u32))
this->memory[byte_num++] = byte;
return byte == EOF;
}
u8*
CPU::WhichRegister(u8 value)
{
u8 *reg_ptr;
reg_ptr = &this->registers[(value & ~0x80) * sizeof(u32)];
if (value & 0x80)
{
if (*reg_ptr < this->mem_size)
return &this->memory[*reg_ptr * sizeof(u32)];
else
return NULL;
}
return reg_ptr;
}
CPU::ProgramState
CPU::Tick()
{
VALIDATE_PC()
u8 *ptr1, *ptr2;
s64 result;
u32 instruction = this->CurrentInstruction();
bytes_add(this->pc, 1);
switch (opcode(instruction))
{
case OP_NOP:
break;
case OP_HCF:
return HALTED;
case OP_MOV:
if (byte(instruction, 3))
{
VALIDATE_ARG(byte(instruction, 1))
VALIDATE_PC()
ptr1 = this->WhichRegister(byte(instruction, 1));
if (!ptr1)
return ERR_ADDRESS_BOUNDARY;
memcpy(
ptr1,
this->memory + bytes2word(this->pc) * sizeof(u32),
sizeof(u32)
);
bytes_add(this->pc, 1);
}
else
{
VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
ptr1 = this->WhichRegister(byte(instruction, 1));
ptr2 = this->WhichRegister(byte(instruction, 2));
if (!ptr1 || !ptr2)
return ERR_ADDRESS_BOUNDARY;
word2bytes(bytes2word(ptr2), ptr1);
}
break;
case OP_ADD:
VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
ptr1 = this->WhichRegister(byte(instruction, 1));
ptr2 = this->WhichRegister(byte(instruction, 2));
if (!ptr1 || !ptr2)
return ERR_ADDRESS_BOUNDARY;
result = (s64)(s32)bytes2word(ptr1) + (s32)bytes2word(ptr2);
word2bytes(result, ptr1);
this->flags.carry = (bool)(result != (s32)result);
break;
// TODO: add remaining opcodes
case _OP_SIZE:
if (this->mem_size < data(instruction)) {
this->extension.required_memory = data(instruction);
return _ERR_SIZE;
}
break;
case _OP_DEBUG:
this->extension.debug_info = data(instruction);
break;
default:
this->_SetErroredLine();
return ERR_INVALID_OPCODE;
}
return OK;
}
void
CPU::_SetErroredLine()
{
if (!this->extension.debug_info)
return;
DebugSymbol key;
for (
u32 word_index = this->extension.debug_info;
word_index < this->mem_size;
word_index += key.next()
) {
key.value = bytes2word(this->memory + word_index * sizeof(u32));
if (word_index == bytes2word(this->pc))
{
this->extension.errored_line =
(char *)(this->memory + word_index * sizeof(u32));
return;
}
else if (key.word() > bytes2word(this->pc)) // instruction not present
// in the source file
break;
else if (!key.next()) // no more lines follows
break;
}
this->extension.errored_line = NULL;
}
<commit_msg>vm: Conformed ADD to the documentation<commit_after>#include <cstdlib>
#include <cstring>
#include "cpu.hpp"
#include "../conversion.hpp"
#include "../opcodes.hpp"
#define VALIDATE_ARGS(val1, val2)\
VALIDATE_ARG(val1)\
VALIDATE_ARG(val2)
#define VALIDATE_ARG(value)\
{\
if (((value) & ~0x80) > 0x12)\
return ERR_INVALID_ARG;\
}
#define VALIDATE_PC()\
{\
if (bytes2word(this->pc) >= mem_size)\
return ERR_PC_BOUNDARY;\
}
static inline u32 opcode(u32 instruction)
{
return instruction >> 24;
}
static inline u32 data(u32 instruction)
{
return instruction & 0xffffff;
}
static inline u32 byte(u32 instruction, u8 number)
{
return (instruction >> (8 * (3 - number))) & 0xff;
}
CPU::CPU() :
lc(&this->registers[0x10 * sizeof(u32)]),
sp(&this->registers[0x11 * sizeof(u32)]),
pc(&this->registers[0x12 * sizeof(u32)]),
mem_size(0), memory(NULL),
registers({0}), stack({0}), flags({false, false, false, false}),
extension({0})
{}
CPU::~CPU()
{
free(this->memory);
}
u32
CPU::CurrentInstruction()
{
return bytes2word(this->memory + bytes2word(this->pc) * sizeof(u32));
}
u32
CPU::LastInstruction()
{
return bytes2word(this->memory + (bytes2word(this->pc) - 1) * sizeof(u32));
}
bool
CPU::Initialize(u32 mem_size)
{
if ((this->memory = (u8 *)malloc(mem_size * sizeof(u32))))
this->mem_size = mem_size;
return (bool)this->memory;
}
bool
CPU::Load(FILE *input)
{
int byte;
u32 byte_num = 0;
while ((byte = getc(input)) != EOF && byte_num < this->mem_size * sizeof(u32))
this->memory[byte_num++] = byte;
return byte == EOF;
}
u8*
CPU::WhichRegister(u8 value)
{
u8 *reg_ptr;
reg_ptr = &this->registers[(value & ~0x80) * sizeof(u32)];
if (value & 0x80)
{
if (*reg_ptr < this->mem_size)
return &this->memory[*reg_ptr * sizeof(u32)];
else
return NULL;
}
return reg_ptr;
}
CPU::ProgramState
CPU::Tick()
{
VALIDATE_PC()
u8 *ptr1, *ptr2;
s64 result;
u32 instruction = this->CurrentInstruction();
bytes_add(this->pc, 1);
switch (opcode(instruction))
{
case OP_NOP:
break;
case OP_HCF:
return HALTED;
case OP_MOV:
if (byte(instruction, 3))
{
VALIDATE_ARG(byte(instruction, 1))
VALIDATE_PC()
ptr1 = this->WhichRegister(byte(instruction, 1));
if (!ptr1)
return ERR_ADDRESS_BOUNDARY;
memcpy(
ptr1,
this->memory + bytes2word(this->pc) * sizeof(u32),
sizeof(u32)
);
bytes_add(this->pc, 1);
}
else
{
VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
ptr1 = this->WhichRegister(byte(instruction, 1));
ptr2 = this->WhichRegister(byte(instruction, 2));
if (!ptr1 || !ptr2)
return ERR_ADDRESS_BOUNDARY;
word2bytes(bytes2word(ptr2), ptr1);
}
break;
case OP_ADD:
VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
ptr1 = this->WhichRegister(byte(instruction, 1));
ptr2 = this->WhichRegister(byte(instruction, 2));
if (!ptr1 || !ptr2)
return ERR_ADDRESS_BOUNDARY;
result = (s64)(s32)bytes2word(ptr1) + (s32)bytes2word(ptr2);
word2bytes(result, ptr1);
this->flags.carry =
(bool)(result != (s32)result && (u64)result != (u32)result);
break;
// TODO: add remaining opcodes
case _OP_SIZE:
if (this->mem_size < data(instruction)) {
this->extension.required_memory = data(instruction);
return _ERR_SIZE;
}
break;
case _OP_DEBUG:
this->extension.debug_info = data(instruction);
break;
default:
this->_SetErroredLine();
return ERR_INVALID_OPCODE;
}
return OK;
}
void
CPU::_SetErroredLine()
{
if (!this->extension.debug_info)
return;
DebugSymbol key;
for (
u32 word_index = this->extension.debug_info;
word_index < this->mem_size;
word_index += key.next()
) {
key.value = bytes2word(this->memory + word_index * sizeof(u32));
if (word_index == bytes2word(this->pc))
{
this->extension.errored_line =
(char *)(this->memory + word_index * sizeof(u32));
return;
}
else if (key.word() > bytes2word(this->pc)) // instruction not present
// in the source file
break;
else if (!key.next()) // no more lines follows
break;
}
this->extension.errored_line = NULL;
}
<|endoftext|>
|
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: testNekMatrix.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Tests NekMatrix functionality.
//
///////////////////////////////////////////////////////////////////////////////
#include <UnitTests/testNekMatrix.h>
#include <LibUtilities/NekMatrix.hpp>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/progress.hpp>
namespace Nektar
{
namespace UnitTests
{
using namespace Nektar::LibUtilities;
void testNekMatrixConstruction()
{
{
double buf[] = { 1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0,
10.0, 11.0, 12.0 };
NekMatrix<double> static_matrix(4, 3);
}
// Basic, dense matrix construction.
{
double buf[] = { 1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0,
10.0, 11.0, 12.0 };
NekMatrix<double> static_matrix(4, 3);
NekMatrix<double> dynamic_matrix(buf, 4, 3);
BOOST_CHECK(static_matrix.rows() == 4);
BOOST_CHECK(static_matrix.columns() == 3);
BOOST_CHECK(dynamic_matrix.rows() == 4);
BOOST_CHECK(dynamic_matrix.columns() == 3);
for(unsigned int i = 0; i < 4; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
BOOST_CHECK(static_matrix(i,j) == buf[4*i + j]);
BOOST_CHECK(dynamic_matrix(i,j) == buf[4*i + j]);
}
}
}
{
NekMatrix<float, 7, 3> static_matrix(7.8);
NekMatrix<float> dynamic_matrix(7.8, 7, 3);
for(unsigned int i = 0; i < 7; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
BOOST_CHECK(static_matrix(i,j) == 7.8);
BOOST_CHECK(dynamic_matrix(i,j) == 7.8);
}
}
}
}
void testNekMatrixAccess()
{
// We need to be able to access any element in the matrix, and
// assign into the matrix at any location.
NekMatrix<unsigned int, 3, 3> static_matrix;
// Test read access.
for(unsigned int i = 0; i < 3; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
BOOST_CHECK(static_matrix(i,j) == 0.0);
}
}
for(unsigned int i = 0; i < 3; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
static_matrix(i,j) = 10*i + j;
}
}
for(unsigned int i = 0; i < 3; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
static_matrix(i,j) == 10*i + j;
}
}
// Invalid access is an unrecoverable error.
BOOST_CHECK_THROW(static_matrix(3,2), OutOfBoundsError);
BOOST_CHECK_THROW(static_matrix(2,3), OutOfBoundsError);
BOOST_CHECK_NO_THROW(static_matrix(2,2));
}
void testNekMatrixBasicMath()
{
// // Addition tests.
// {
// double buf[] = {1.0, 2.0, 3.0,
// 4.0, 5.0, 6.0,
// 7.0, 8.0, 9.0 };
//
// NekMatrix<double, 3, 3> m1(buf);
// NekMatrix<double, 3, 3> m2(buf);
// NekMatrix<double, 3, 3> m3 = m1 + m2;
//
// for(unsigned int i = 0; i < 3; ++i)
// {
// for(unsigned int j = 0; j < 3; ++j)
// {
// BOOST_CHECK(m3(i,j) == buf[3*i+j] + buf[3*i+j]);
// }
// }
//
// NekMatrix<double> m4(buf, 3, 3);
// NekMatrix<double> m5(buf, 3, 3);
// NekMatrix<double> m6 = m4+m5;
//
// for(unsigned int i = 0; i < 3; ++i)
// {
// for(unsigned int j = 0; j < 3; ++j)
// {
// BOOST_CHECK(m6(i,j) == buf[3*i+j] + buf[3*i+j]);
// }
// }
//
// // Do a couple of tests that shouldn't compile.
// NekMatrix<double, 3, 3> m7(buf);
// NekMatrix<double, 2, 2> m8(buf);
// NekMatrix<double> m9 = m7 + m8; // This line should fail.
// NekMatrix<double, 3, 3> m10 = m7 + m8; // This line should fail.
//
// // Mixed mode.
// NekMatrix<double> m11 = m7 + m4;
// NekMatrix<double, 3, 3> m12 = m7 + m4;
// BOOST_CHECK(m11 == m12);
// BOOST_CHECK(m11 == m3);
// }
// Multiply
// Transpose
// Determinant.
// Invert/Check for singularity.
// Eigenvalues/vectors
// Condition number wrt various norms.
// Various norm computations.
// LU Decomposition? More appropriate in LinAlg?
}
}
}
/**
$Log: testNekMatrix.cpp,v $
Revision 1.2 2006/05/14 21:33:58 bnelson
*** empty log message ***
Revision 1.1 2006/05/07 21:10:09 bnelson
*** empty log message ***
**/
<commit_msg>Added addition tests.<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: testNekMatrix.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description: Tests NekMatrix functionality.
//
///////////////////////////////////////////////////////////////////////////////
#include <UnitTests/testNekMatrix.h>
#include <LibUtilities/NekMatrix.hpp>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/progress.hpp>
namespace Nektar
{
namespace UnitTests
{
using namespace Nektar::LibUtilities;
void testNekMatrixConstruction()
{
// Basic, dense matrix construction.
{
double buf[] = { 1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0,
10.0, 11.0, 12.0 };
NekMatrix<double, 4, 3> static_matrix(buf);
NekMatrix<double> dynamic_matrix(buf, 4, 3);
BOOST_CHECK(static_matrix.rows() == 4);
BOOST_CHECK(static_matrix.columns() == 3);
BOOST_CHECK(dynamic_matrix.rows() == 4);
BOOST_CHECK(dynamic_matrix.columns() == 3);
for(unsigned int i = 0; i < 4; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
BOOST_CHECK(static_matrix(i,j) == buf[3*i + j]);
BOOST_CHECK(dynamic_matrix(i,j) == buf[3*i + j]);
}
}
}
{
NekMatrix<float, 7, 3> static_matrix(7.8);
NekMatrix<float> dynamic_matrix(7.8, 7, 3);
for(unsigned int i = 0; i < 7; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
BOOST_CHECK(static_matrix(i,j) == 7.8);
BOOST_CHECK(dynamic_matrix(i,j) == 7.8);
}
}
}
}
void testNekMatrixAccess()
{
// We need to be able to access any element in the matrix, and
// assign into the matrix at any location.
NekMatrix<unsigned int, 3, 3> static_matrix;
for(unsigned int i = 0; i < 3; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
static_matrix(i,j) = 10*i + j;
}
}
for(unsigned int i = 0; i < 3; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
BOOST_CHECK(static_matrix(i,j) == 10*i + j);
}
}
// Invalid access is an unrecoverable error.
BOOST_CHECK_THROW(static_matrix(3,2), OutOfBoundsError);
BOOST_CHECK_THROW(static_matrix(2,3), OutOfBoundsError);
BOOST_CHECK_NO_THROW(static_matrix(2,2));
}
void testNekMatrixBasicMath()
{
// Addition tests.
{
double buf[] = {1.0, 2.0, 3.0,
4.0, 5.0, 6.0,
7.0, 8.0, 9.0 };
NekMatrix<double, 3, 3> m1(buf);
NekMatrix<double, 3, 3> m2(buf);
NekMatrix<double, 3, 3> m3 = m1 + m2;
for(unsigned int i = 0; i < 3; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
BOOST_CHECK(m3(i,j) == buf[3*i+j] + buf[3*i+j]);
}
}
NekMatrix<double> m4(buf, 3, 3);
NekMatrix<double> m5(buf, 3, 3);
NekMatrix<double> m6 = m4+m5;
for(unsigned int i = 0; i < 3; ++i)
{
for(unsigned int j = 0; j < 3; ++j)
{
BOOST_CHECK(m6(i,j) == buf[3*i+j] + buf[3*i+j]);
}
}
}
//
// // Do a couple of tests that shouldn't compile.
// NekMatrix<double, 3, 3> m7(buf);
// NekMatrix<double, 2, 2> m8(buf);
// NekMatrix<double> m9 = m7 + m8; // This line should fail.
// NekMatrix<double, 3, 3> m10 = m7 + m8; // This line should fail.
//
// // Mixed mode.
// NekMatrix<double> m11 = m7 + m4;
// NekMatrix<double, 3, 3> m12 = m7 + m4;
// BOOST_CHECK(m11 == m12);
// BOOST_CHECK(m11 == m3);
// }
// Multiply
// Transpose
// Determinant.
// Invert/Check for singularity.
// Eigenvalues/vectors
// Condition number wrt various norms.
// Various norm computations.
// LU Decomposition? More appropriate in LinAlg?
}
}
}
/**
$Log: testNekMatrix.cpp,v $
Revision 1.3 2006/05/15 04:10:35 bnelson
no message
Revision 1.2 2006/05/14 21:33:58 bnelson
*** empty log message ***
Revision 1.1 2006/05/07 21:10:09 bnelson
*** empty log message ***
**/
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <iostream>
#include "dla.hpp"
int main(int argc, char *argv[]) {
int grid_width = std::atoi(argv[1]);
int grid_height = std::atoi(argv[2]);
char *outfile = argv[3];
Dla dla = Dla(grid_width, grid_height, true);
dla.simulate();
//dla.print_grid();
dla.write_grid_to_file(outfile);
return 0;
}
<commit_msg>Prints usage if args not all given<commit_after>#include <cstdlib>
#include <iostream>
#include "dla.hpp"
void print_usage();
int main(int argc, char *argv[]) {
if (argc < 4) {
print_usage();
exit(0);
}
int grid_width = std::atoi(argv[1]);
int grid_height = std::atoi(argv[2]);
char *outfile = argv[3];
Dla dla = Dla(grid_width, grid_height, false);
dla.simulate();
//dla.print_grid();
dla.write_grid_to_file(outfile);
return 0;
}
void print_usage() {
std::cout << "Usage: ./simulate grid_width grid_height output_file\n";
}
<|endoftext|>
|
<commit_before>#include <QtGui>
#include <QApplication>
#include <QDesktopServices>
#include <QFileDialog>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QSpacerItem>
#include <QProcess>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "window.h"
#include "screenshot.h"
#include "upload.h"
QString puushUrl = "https://puush.me/api/";
Window::Window() {
setDefaults();
createGroupBoxes();
createActions();
createTrayIcon();
connect(trayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked()));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
setTrayIcon(":/images/icon.svg.png");
setAppIcon(":/images/icon.svg.png");
resetButton = new QPushButton(tr("Reset Settings"));
resetButton->setDefault(true);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(authGroupBox);
mainLayout->addWidget(puushGroupBox);
mainLayout->addWidget(saveGroupBox);
mainLayout->addWidget(resetButton);
setLayout(mainLayout);
createSettingsSlots();
trayIcon->show();
setWindowTitle(tr("puush-qt"));
resize(400, 300);
}
void Window::setDefaults() {
if (!s.contains("key"))
s.setValue("key", "");
if (!s.contains("quality"))
s.setValue("quality", 90);
if (!s.contains("save-path"))
s.setValue("save-path", QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
if (!s.contains("save-name"))
s.setValue("save-name", "Screenshot-yyyy-MM-dd_hh-mm-ss");
}
void Window::setVisible(bool visible) {
QDialog::setVisible(visible);
}
void Window::closeEvent(QCloseEvent *event) {
if (trayIcon->isVisible()) {
hide();
event->ignore();
}
}
void Window::setTrayIcon(QString image) {
QIcon icon = QIcon(image), tr("Icon");
trayIcon->setIcon(icon);
}
void Window::setAppIcon(QString image) {
QIcon icon = QIcon(image), tr("Icon");
setWindowIcon(icon);
}
void Window::iconActivated(QSystemTrayIcon::ActivationReason reason) {
switch (reason) {
case QSystemTrayIcon::Trigger:
trayIconMenu->popup(QCursor::pos());
break;
default:
break;
}
}
void Window::submitInfo() {
s.setValue("email", emailEdit->text());
QString email = emailEdit->text();
QString password = passwordEdit->text();
QNetworkAccessManager *nm = new QNetworkAccessManager(this);
QUrlQuery postData;
postData.addQueryItem("e", QUrl::toPercentEncoding(email));
postData.addQueryItem("p", QUrl::toPercentEncoding(password));
QNetworkRequest request(QUrl(puushUrl + "auth"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
authReply = nm->post(request, postData.toString().toUtf8());
connect(authReply, SIGNAL(finished()), this, SLOT(authDone()));
}
void Window::logout(){
s.setValue("key", "");
authMessage->setText(tr("Logged out"));
}
void Window::authDone() {
if(authReply->error() != QNetworkReply::NoError){
authMessage->setText(tr("Error sending auth info: ") + authReply->errorString());
return;
}
QString output = authReply->readAll();
authReply->deleteLater();
if (output == "-1") {
authMessage->setText(tr("Invalid credentials or error sending them!"));
} else {
authMessage->setText(tr("Authentication sucesssful!"));
QStringList pieces = output.split(",");
if(pieces.length() > 1){
QString key = pieces[1];
s.setValue("key", key);
} else {
authMessage->setText(tr("Error: Malformed response from Puush"));
}
}
}
void Window::messageClicked() {
bool response = QDesktopServices::openUrl(lastUrl);
if (!response) {
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Error!"), tr("There was an issue opening the URL. Is your default browser set?"), icon);
}
}
void Window::createGroupBoxes() {
authGroupBox = new QGroupBox(tr("Authentication"));
puushGroupBox = new QGroupBox(tr("Puush Settings"));
saveGroupBox = new QGroupBox(tr("Local Save Settings"));
// Auth Settings
emailEdit = new QLineEdit(s.value("email", "").toString());
passwordEdit = new QLineEdit();
passwordEdit->setEchoMode(QLineEdit::Password);
authMessage = new QLabel();
submitButton = new QPushButton(tr("Submit"));
submitButton->setDefault(true);
logoutButton = new QPushButton(tr("Logout"));
logoutButton->setDefault(true);
QHBoxLayout *buttonPair = new QHBoxLayout();
buttonPair->addWidget(logoutButton);
buttonPair->addWidget(submitButton);
QFormLayout *authLayout = new QFormLayout();
authLayout->addRow(tr("Email:"), emailEdit);
authLayout->addRow(tr("Password:"), passwordEdit);
authLayout->addRow(authMessage);
authLayout->addRow(buttonPair);
// Puush settings
qualitySlider = new QSlider(Qt::Horizontal);
qualitySlider->setRange(0, 100);
qualitySlider->setTickPosition(QSlider::TicksBelow);
qualitySlider->setTickInterval(10);
qualitySlider->setValue(s.value("quality", 90).toInt());
QFormLayout *puushLayout = new QFormLayout();
puushLayout->addRow(tr("Quality:"), qualitySlider);
// Save settings
saveEnabled = new QCheckBox("Save screenshot to file");
savePathEdit = new QLineEdit(s.value("save-path").toString());
saveNameEdit = new QLineEdit(s.value("save-name").toString());
saveEnabled->setCheckState(s.value("save-enabled").toBool() ? Qt::Checked : Qt::Unchecked);
savePathEdit->setEnabled(s.value("save-enabled").toBool());
// saveNameEdit->setEnabled(s.value("save-enabled").toBool()); // disabled because NYI
saveNameEdit->setEnabled(false);
QFormLayout *saveLayout = new QFormLayout();
saveLayout->addRow(saveEnabled);
saveLayout->addRow(tr("Location:"), savePathEdit);
saveLayout->addRow(tr("File Name:"), saveNameEdit);
authGroupBox->setLayout( authLayout);
puushGroupBox->setLayout(puushLayout);
saveGroupBox->setLayout( saveLayout);
}
void Window::createActions() {
uploadAction = new QAction(tr("&Upload..."), this);
connect(uploadAction, SIGNAL(triggered()), this, SLOT(uploadFile()));
fullScreenAction = new QAction(tr("&Full screen"), this);
connect(fullScreenAction, SIGNAL(triggered()), this, SLOT(fullScreenScreenshot()));
selectAreaAction = new QAction(tr("&Select area"), this);
connect(selectAreaAction, SIGNAL(triggered()), this, SLOT(selectAreaScreenshot()));
activeAction = new QAction(tr("&Active window"), this);
connect(activeAction, SIGNAL(triggered()), this, SLOT(activeWindowScreenshot()));
settingsAction = new QAction(tr("S&ettings..."), this);
connect(settingsAction, SIGNAL(triggered()), this, SLOT(openSettings()));
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
openSaveDirectoryAction = new QAction(tr("&Open screenshot directory"), this);
connect(openSaveDirectoryAction, SIGNAL(triggered()), this, SLOT(openSaveDirectory()));
}
void Window::createSettingsSlots(){
connect(submitButton, SIGNAL(clicked()), this, SLOT(submitInfo()));
connect(logoutButton, SIGNAL(clicked()), this, SLOT(logout()));
connect(qualitySlider, SIGNAL(valueChanged(int)), this, SLOT(qualityChanged(int)));
connect(saveEnabled, SIGNAL(stateChanged(int)), this, SLOT(saveEnabledChanged(int)));
connect(savePathEdit, SIGNAL(editingFinished()), this, SLOT(savePathChanged()));
connect(saveNameEdit, SIGNAL(editingFinished()), this, SLOT(saveNameChanged()));
connect(resetButton, SIGNAL(clicked()), this, SLOT(resetSettings()));
}
void Window::createTrayIcon() {
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(uploadAction);
trayIconMenu->addAction(fullScreenAction);
trayIconMenu->addAction(selectAreaAction);
trayIconMenu->addAction(activeAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(settingsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(openSaveDirectoryAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
if(s.value("save-path").toString().isEmpty())
openSaveDirectoryAction->setDisabled(true);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
}
void Window::openSettings() {
showNormal();
// if it's already open, it won't raise, so we force it.
raise();
}
bool Window::isLoggedIn() {
if (s.value("key", "") != "")
return true;
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("API Key Not Set"), tr("Have you authenticated?"), icon);
return false;
}
void Window::uploadFile() {
if (!isLoggedIn()) return;
QString fileName = QFileDialog::getOpenFileName(this, tr("Upload file"));
if (fileName == "") return;
Upload *u = new Upload(fileName);
connect(u, SIGNAL(started()), this, SLOT(puushStarted()));
connect(u, SIGNAL(finished(int, QString)), this, SLOT(puushDone(int, QString)));
}
QString Window::getFileName() {
return "/tmp/ss-" + QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss") + ".png";
}
QString Window::getSavePath(){
QString path = s.value("save-path").toString();
if(path.startsWith('~')){
path.remove(0, 1); // remove "~"
path = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + path; // add "/home/user"
}
return path;
}
QString Window::getSaveName() {
QString saveName = "Screenshot-";
saveName += QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss") + ".png";
return getSavePath() + "/" + saveName;
}
void Window::fullScreenScreenshot() {
if (!isLoggedIn()) return;
QString fileName = getFileName();
Screenshot *ss = new Screenshot(fileName);
connect(ss, SIGNAL(finished(int, QString, QString)), this, SLOT(screenshotDone(int, QString, QString)));
ss->fullScreen();
}
void Window::selectAreaScreenshot() {
if (!isLoggedIn()) return;
QString fileName = getFileName();
Screenshot *ss = new Screenshot(fileName);
connect(ss, SIGNAL(finished(int, QString, QString)), this, SLOT(screenshotDone(int, QString, QString)));
ss->selectArea();
}
void Window::activeWindowScreenshot() {
if (!isLoggedIn()) return;
numTime = 5;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateActiveMessage()));
timer->start(1000);
}
void Window::updateActiveMessage() {
if (numTime < 1) {
timer->stop();
QString fileName = getFileName();
Screenshot *ss = new Screenshot(fileName);
connect(ss, SIGNAL(finished(int, QString, QString)), this, SLOT(screenshotDone(int, QString, QString)));
ss->activeWindow();
return;
}
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Select a window"), tr("Taking a screenshot in ") + QString::number(numTime), icon);
--numTime;
}
// note: this fails with ~user
void Window::openSaveDirectory() {
bool response = true;
if(s.contains("save-path")){
QString path = getSavePath();
response = QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}
if (!response) {
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Error!"), tr("Error opening save directory"), icon);
}
}
void Window::puushStarted() {
setTrayIcon(":/images/icon-uploading.svg.png");
}
void Window::screenshotDone(int returnCode, QString fileName, QString output) {
if (returnCode != 0) {
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Error!"), output, icon);
return;
}
Upload *u = new Upload(fileName);
connect(u, SIGNAL(started()), this, SLOT(puushStarted()));
connect(u, SIGNAL(finished(int, QString)), this, SLOT(puushDone(int, QString)));
QFile::copy(fileName, getSaveName());
}
void Window::puushDone(int returnCode, QString output) {
if (returnCode != 0) {
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Error!"), output, icon);
return;
}
QStringList pieces = output.split(",");
QString code = pieces[0];
QString url = "";
if (pieces.length() > 1)
url = pieces[1];
setTrayIcon(":/images/icon.svg.png");
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
// show error to user
if (code == "-1") {
trayIcon->showMessage(tr("Error!"), tr("Uploading failed. Have you authenticated?"), icon);
return;
} else if (code == "-2") {
trayIcon->showMessage(tr("Error!"), tr("Uploading failed. This might be a bug with puush-qt."), icon);
return;
} else {
trayIcon->showMessage(tr("Error!"), tr("Uploading failed due to unknown reason."), icon);
return;
}
QClipboard *clipboard = QApplication::clipboard();
lastUrl = QUrl(url);
clipboard->setText(url);
trayIcon->showMessage(tr("Success!"), url + tr("\nThe url was copied to your clipboard!"), icon);
}
void Window::qualityChanged(int val){
s.setValue("quality", val);
}
void Window::saveEnabledChanged(int val){
// 0 = unchecked, 1 = unchecked & disabled?, 2 = checked, 3 = checked & disabled?
s.setValue("save-enabled", val == 2);
savePathEdit->setEnabled(val == 2);
// saveNameEdit->setEnabled(val == 2); // disabled because NYI
}
void Window::savePathChanged(){
s.setValue("save-path", savePathEdit->text());
}
void Window::saveNameChanged(){
// s.setValue("save-name", saveNameEdit->text()); //disabled because NYI
}
void Window::resetSettings(){
s.setValue("quality", 90);
s.setValue("save-enabled", true);
s.setValue("save-path", QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
s.setValue("save-name", "Screenshot-yyyy-MM-dd_hh-mm-ss");
qualitySlider->setValue(s.value("quality").toInt());
saveEnabled->setChecked(s.value("save-enabled").toBool() ? Qt::Checked : Qt::Unchecked);
savePathEdit->setText(s.value("save-path").toString());
saveNameEdit->setText(s.value("save-name").toString());
}
<commit_msg>Fixed throwing error on success, fixed isLoggedIn, fixed creating path to save file if directory does not exist. Changed "Screenshot-..." back to "ss-..."<commit_after>#include <QtGui>
#include <QApplication>
#include <QDesktopServices>
#include <QFileDialog>
#include <QFormLayout>
#include <QHBoxLayout>
#include <QSpacerItem>
#include <QProcess>
#include <QNetworkRequest>
#include <QNetworkReply>
#include "window.h"
#include "screenshot.h"
#include "upload.h"
QString puushUrl = "https://puush.me/api/";
Window::Window() {
setDefaults();
createGroupBoxes();
createActions();
createTrayIcon();
connect(trayIcon, SIGNAL(messageClicked()), this, SLOT(messageClicked()));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(iconActivated(QSystemTrayIcon::ActivationReason)));
setTrayIcon(":/images/icon.svg.png");
setAppIcon(":/images/icon.svg.png");
resetButton = new QPushButton(tr("Reset Settings"));
resetButton->setDefault(true);
QVBoxLayout *mainLayout = new QVBoxLayout;
mainLayout->addWidget(authGroupBox);
mainLayout->addWidget(puushGroupBox);
mainLayout->addWidget(saveGroupBox);
mainLayout->addWidget(resetButton);
setLayout(mainLayout);
createSettingsSlots();
trayIcon->show();
setWindowTitle(tr("puush-qt"));
resize(400, 300);
}
void Window::setDefaults() {
if (!s.contains("key"))
s.setValue("key", "");
if (!s.contains("quality"))
s.setValue("quality", 90);
if (!s.contains("save-path"))
s.setValue("save-path", QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
if (!s.contains("save-name"))
s.setValue("save-name", "ss-yyyy-MM-dd_hh-mm-ss");
}
void Window::setVisible(bool visible) {
QDialog::setVisible(visible);
}
void Window::closeEvent(QCloseEvent *event) {
if (trayIcon->isVisible()) {
hide();
event->ignore();
}
}
void Window::setTrayIcon(QString image) {
QIcon icon = QIcon(image), tr("Icon");
trayIcon->setIcon(icon);
}
void Window::setAppIcon(QString image) {
QIcon icon = QIcon(image), tr("Icon");
setWindowIcon(icon);
}
void Window::iconActivated(QSystemTrayIcon::ActivationReason reason) {
switch (reason) {
case QSystemTrayIcon::Trigger:
trayIconMenu->popup(QCursor::pos());
break;
default:
break;
}
}
void Window::submitInfo() {
s.setValue("email", emailEdit->text());
QString email = emailEdit->text();
QString password = passwordEdit->text();
QNetworkAccessManager *nm = new QNetworkAccessManager(this);
QUrlQuery postData;
postData.addQueryItem("e", QUrl::toPercentEncoding(email));
postData.addQueryItem("p", QUrl::toPercentEncoding(password));
QNetworkRequest request(QUrl(puushUrl + "auth"));
request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");
authReply = nm->post(request, postData.toString().toUtf8());
connect(authReply, SIGNAL(finished()), this, SLOT(authDone()));
}
void Window::logout(){
s.setValue("key", "");
authMessage->setText(tr("Logged out"));
}
void Window::authDone() {
if(authReply->error() != QNetworkReply::NoError){
authMessage->setText(tr("Error sending auth info: ") + authReply->errorString());
return;
}
QString output = authReply->readAll();
authReply->deleteLater();
if (output == "-1") {
authMessage->setText(tr("Invalid credentials or error sending them!"));
} else {
authMessage->setText(tr("Authentication sucesssful!"));
QStringList pieces = output.split(",");
if(pieces.length() > 1){
QString key = pieces[1];
s.setValue("key", key);
} else {
authMessage->setText(tr("Error: Malformed response from Puush"));
}
}
}
void Window::messageClicked() {
bool response = QDesktopServices::openUrl(lastUrl);
if (!response) {
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Error!"), tr("There was an issue opening the URL. Is your default browser set?"), icon);
}
}
void Window::createGroupBoxes() {
authGroupBox = new QGroupBox(tr("Authentication"));
puushGroupBox = new QGroupBox(tr("Puush Settings"));
saveGroupBox = new QGroupBox(tr("Local Save Settings"));
// Auth Settings
emailEdit = new QLineEdit(s.value("email", "").toString());
passwordEdit = new QLineEdit();
passwordEdit->setEchoMode(QLineEdit::Password);
authMessage = new QLabel();
if(s.value("key") == "")
authMessage->setText("Not logged in");
submitButton = new QPushButton(tr("Submit"));
submitButton->setDefault(true);
logoutButton = new QPushButton(tr("Logout"));
logoutButton->setDefault(true);
QHBoxLayout *buttonPair = new QHBoxLayout();
buttonPair->addWidget(logoutButton);
buttonPair->addWidget(submitButton);
QFormLayout *authLayout = new QFormLayout();
authLayout->addRow(tr("Email:"), emailEdit);
authLayout->addRow(tr("Password:"), passwordEdit);
authLayout->addRow(authMessage);
authLayout->addRow(buttonPair);
// Puush settings
qualitySlider = new QSlider(Qt::Horizontal);
qualitySlider->setRange(0, 100);
qualitySlider->setTickPosition(QSlider::TicksBelow);
qualitySlider->setTickInterval(10);
qualitySlider->setValue(s.value("quality", 90).toInt());
QFormLayout *puushLayout = new QFormLayout();
puushLayout->addRow(tr("Quality:"), qualitySlider);
// Save settings
saveEnabled = new QCheckBox("Save screenshot to file");
savePathEdit = new QLineEdit(s.value("save-path").toString());
saveNameEdit = new QLineEdit(s.value("save-name").toString());
saveEnabled->setCheckState(s.value("save-enabled").toBool() ? Qt::Checked : Qt::Unchecked);
savePathEdit->setEnabled(s.value("save-enabled").toBool());
// saveNameEdit->setEnabled(s.value("save-enabled").toBool()); // disabled because NYI
saveNameEdit->setEnabled(false);
QFormLayout *saveLayout = new QFormLayout();
saveLayout->addRow(saveEnabled);
saveLayout->addRow(tr("Location:"), savePathEdit);
saveLayout->addRow(tr("File Name:"), saveNameEdit);
authGroupBox->setLayout( authLayout);
puushGroupBox->setLayout(puushLayout);
saveGroupBox->setLayout( saveLayout);
}
void Window::createActions() {
uploadAction = new QAction(tr("&Upload..."), this);
connect(uploadAction, SIGNAL(triggered()), this, SLOT(uploadFile()));
fullScreenAction = new QAction(tr("&Full screen"), this);
connect(fullScreenAction, SIGNAL(triggered()), this, SLOT(fullScreenScreenshot()));
selectAreaAction = new QAction(tr("&Select area"), this);
connect(selectAreaAction, SIGNAL(triggered()), this, SLOT(selectAreaScreenshot()));
activeAction = new QAction(tr("&Active window"), this);
connect(activeAction, SIGNAL(triggered()), this, SLOT(activeWindowScreenshot()));
settingsAction = new QAction(tr("S&ettings..."), this);
connect(settingsAction, SIGNAL(triggered()), this, SLOT(openSettings()));
quitAction = new QAction(tr("&Quit"), this);
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
openSaveDirectoryAction = new QAction(tr("&Open screenshot directory"), this);
connect(openSaveDirectoryAction, SIGNAL(triggered()), this, SLOT(openSaveDirectory()));
}
void Window::createSettingsSlots(){
connect(submitButton, SIGNAL(clicked()), this, SLOT(submitInfo()));
connect(logoutButton, SIGNAL(clicked()), this, SLOT(logout()));
connect(qualitySlider, SIGNAL(valueChanged(int)), this, SLOT(qualityChanged(int)));
connect(saveEnabled, SIGNAL(stateChanged(int)), this, SLOT(saveEnabledChanged(int)));
connect(savePathEdit, SIGNAL(editingFinished()), this, SLOT(savePathChanged()));
connect(saveNameEdit, SIGNAL(editingFinished()), this, SLOT(saveNameChanged()));
connect(resetButton, SIGNAL(clicked()), this, SLOT(resetSettings()));
}
void Window::createTrayIcon() {
trayIconMenu = new QMenu(this);
trayIconMenu->addAction(uploadAction);
trayIconMenu->addAction(fullScreenAction);
trayIconMenu->addAction(selectAreaAction);
trayIconMenu->addAction(activeAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(settingsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(openSaveDirectoryAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
if(s.value("save-path").toString().isEmpty())
openSaveDirectoryAction->setDisabled(true);
trayIcon = new QSystemTrayIcon(this);
trayIcon->setContextMenu(trayIconMenu);
}
void Window::openSettings() {
showNormal();
// if it's already open, it won't raise, so we force it.
raise();
}
bool Window::isLoggedIn() {
if (s.value("key", "") != "")
return true;
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("API Key Not Set"), tr("Have you authenticated?"), icon);
return false;
}
void Window::uploadFile() {
if (!isLoggedIn()) return;
QString fileName = QFileDialog::getOpenFileName(this, tr("Upload file"));
if (fileName == "") return;
Upload *u = new Upload(fileName);
connect(u, SIGNAL(started()), this, SLOT(puushStarted()));
connect(u, SIGNAL(finished(int, QString)), this, SLOT(puushDone(int, QString)));
}
QString Window::getFileName() {
return "/tmp/ss-" + QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss") + ".png";
}
QString Window::getSavePath(){
QString path = s.value("save-path").toString();
if(path.startsWith('~')){
path.remove(0, 1); // remove "~"
path = QStandardPaths::writableLocation(QStandardPaths::HomeLocation) + path; // add "/home/user"
}
return path;
}
QString Window::getSaveName() {
QString saveName = "ss-";
saveName += QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss") + ".png";
return getSavePath() + "/" + saveName;
}
void Window::fullScreenScreenshot() {
if (!isLoggedIn()) return;
QString fileName = getFileName();
Screenshot *ss = new Screenshot(fileName);
connect(ss, SIGNAL(finished(int, QString, QString)), this, SLOT(screenshotDone(int, QString, QString)));
ss->fullScreen();
}
void Window::selectAreaScreenshot() {
if (!isLoggedIn()) return;
QString fileName = getFileName();
Screenshot *ss = new Screenshot(fileName);
connect(ss, SIGNAL(finished(int, QString, QString)), this, SLOT(screenshotDone(int, QString, QString)));
ss->selectArea();
}
void Window::activeWindowScreenshot() {
if (!isLoggedIn()) return;
numTime = 5;
timer = new QTimer(this);
connect(timer, SIGNAL(timeout()), this, SLOT(updateActiveMessage()));
timer->start(1000);
}
void Window::updateActiveMessage() {
if (numTime < 1) {
timer->stop();
QString fileName = getFileName();
Screenshot *ss = new Screenshot(fileName);
connect(ss, SIGNAL(finished(int, QString, QString)), this, SLOT(screenshotDone(int, QString, QString)));
ss->activeWindow();
return;
}
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Select a window"), tr("Taking a screenshot in ") + QString::number(numTime), icon);
--numTime;
}
// note: this fails with ~user
void Window::openSaveDirectory() {
bool response = true;
if(s.contains("save-path")){
QString path = getSavePath();
response = QDesktopServices::openUrl(QUrl::fromLocalFile(path));
}
if (!response) {
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Error!"), tr("Error opening save directory"), icon);
}
}
void Window::puushStarted() {
setTrayIcon(":/images/icon-uploading.svg.png");
}
void Window::screenshotDone(int returnCode, QString fileName, QString output) {
if (returnCode != 0) {
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Error!"), output, icon);
return;
}
Upload *u = new Upload(fileName);
connect(u, SIGNAL(started()), this, SLOT(puushStarted()));
connect(u, SIGNAL(finished(int, QString)), this, SLOT(puushDone(int, QString)));
QDir::mkpath(getSavePath());
QFile::copy(fileName, getSaveName());
}
void Window::puushDone(int returnCode, QString output) {
if (returnCode != 0) {
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
trayIcon->showMessage(tr("Error!"), output, icon);
return;
}
QStringList pieces = output.split(",");
QString code = pieces[0];
QString url = "";
if (pieces.length() > 1)
url = pieces[1];
setTrayIcon(":/images/icon.svg.png");
QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon();
// code can only be 0 = success, or these errors.
if (code == "-1") {
trayIcon->showMessage(tr("Error!"), tr("Uploading failed. Have you authenticated?"), icon);
return;
} else if (code == "-2") {
trayIcon->showMessage(tr("Error!"), tr("Uploading failed. This might be a bug with puush-qt."), icon);
return;
} else if(code == "-3"){
trayIcon->showMessage(tr("Error!"), tr("Uploading failed due invalid md5."), icon);
return;
}
QClipboard *clipboard = QApplication::clipboard();
lastUrl = QUrl(url);
clipboard->setText(url);
trayIcon->showMessage(tr("Success!"), url + tr("\nThe url was copied to your clipboard!"), icon);
}
void Window::qualityChanged(int val){
s.setValue("quality", val);
}
void Window::saveEnabledChanged(int val){
// 0 = unchecked, 1 = unchecked & disabled?, 2 = checked, 3 = checked & disabled?
s.setValue("save-enabled", val == 2);
savePathEdit->setEnabled(val == 2);
// saveNameEdit->setEnabled(val == 2); // disabled because NYI
}
void Window::savePathChanged(){
s.setValue("save-path", savePathEdit->text());
}
void Window::saveNameChanged(){
// s.setValue("save-name", saveNameEdit->text()); //disabled because NYI
}
void Window::resetSettings(){
s.setValue("quality", 90);
s.setValue("save-enabled", true);
s.setValue("save-path", QStandardPaths::writableLocation(QStandardPaths::PicturesLocation));
s.setValue("save-name", "ss-yyyy-MM-dd_hh-mm-ss");
qualitySlider->setValue(s.value("quality").toInt());
saveEnabled->setChecked(s.value("save-enabled").toBool() ? Qt::Checked : Qt::Unchecked);
savePathEdit->setText(s.value("save-path").toString());
saveNameEdit->setText(s.value("save-name").toString());
}
<|endoftext|>
|
<commit_before>#include <cstdlib>
#include <iostream>
#include "dla.hpp"
void print_usage();
int main(int argc, char *argv[]) {
if (argc < 4) {
print_usage();
exit(0);
}
int grid_width = std::atoi(argv[1]);
int grid_height = std::atoi(argv[2]);
char *outfile = argv[3];
Dla dla = Dla(grid_width, grid_height, false);
dla.simulate();
//dla.print_grid();
dla.write_grid_to_file(outfile);
return 0;
}
void print_usage() {
std::cout << "Usage: ./simulate grid_width grid_height output_file\n";
}
<commit_msg>Parse arguments with getopt<commit_after>#include <getopt.h>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include "dla.hpp"
void print_usage();
int main(int argc, char *argv[]) {
if (argc < 4) {
print_usage();
return 0;
}
int c;
int grid_width, grid_height;
char *outfile;
bool verbose = false;
// Parse args
opterr = 0;
while ((c = getopt(argc, argv, "w:h:o:v")) != EOF) {
switch (c) {
case 'w':
grid_width = std::atoi(optarg);
break;
case 'h':
grid_height = std::atoi(optarg);
break;
case 'o':
outfile = optarg;
break;
case 'v':
verbose = true;
break;
default:
print_usage();
return 1;
}
}
std::cout << "Grid width : " << grid_width << "\n";
std::cout << "Grid height : " << grid_height << "\n";
std::cout << "Output filename : " << outfile << "\n";
Dla dla = Dla(grid_width, grid_height, verbose);
dla.simulate();
//dla.print_grid();
dla.write_grid_to_file(outfile);
return 0;
}
void print_usage() {
std::cout << "Usage: ./simulate -w grid_width -h grid_height -o output_filename [-v]\n";
}
<|endoftext|>
|
<commit_before>// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/raw_object_fields.h"
namespace dart {
#if defined(DART_PRECOMPILER)
#define RAW_CLASSES_AND_FIELDS(F) \
F(Class, name_) \
F(Class, user_name_) \
F(Class, functions_) \
F(Class, functions_hash_table_) \
F(Class, fields_) \
F(Class, offset_in_words_to_field_) \
F(Class, interfaces_) \
F(Class, script_) \
F(Class, library_) \
F(Class, type_parameters_) \
F(Class, super_type_) \
F(Class, mixin_) \
F(Class, signature_function_) \
F(Class, constants_) \
F(Class, canonical_type_) \
F(Class, invocation_dispatcher_cache_) \
F(Class, allocation_stub_) \
F(Class, direct_implementors_) \
F(Class, direct_subclasses_) \
F(Class, dependent_code_) \
F(PatchClass, patched_class_) \
F(PatchClass, origin_class_) \
F(PatchClass, script_) \
F(PatchClass, library_kernel_data_) \
F(Function, name_) \
F(Function, owner_) \
F(Function, result_type_) \
F(Function, parameter_types_) \
F(Function, parameter_names_) \
F(Function, type_parameters_) \
F(Function, data_) \
F(Function, ic_data_array_) \
F(Function, code_) \
F(ClosureData, context_scope_) \
F(ClosureData, parent_function_) \
F(ClosureData, signature_type_) \
F(ClosureData, closure_) \
F(SignatureData, parent_function_) \
F(SignatureData, signature_type_) \
F(RedirectionData, type_) \
F(RedirectionData, identifier_) \
F(RedirectionData, target_) \
F(Field, name_) \
F(Field, owner_) \
F(Field, type_) \
F(Field, guarded_list_length_) \
F(Field, dependent_code_) \
F(Field, type_test_cache_) \
F(Script, url_) \
F(Script, resolved_url_) \
F(Script, compile_time_constants_) \
F(Script, line_starts_) \
F(Script, debug_positions_) \
F(Script, yield_positions_) \
F(Script, kernel_program_info_) \
F(Script, source_) \
F(Library, name_) \
F(Library, url_) \
F(Library, private_key_) \
F(Library, dictionary_) \
F(Library, metadata_) \
F(Library, toplevel_class_) \
F(Library, patch_classes_) \
F(Library, imports_) \
F(Library, exports_) \
F(Library, load_error_) \
F(Library, kernel_data_) \
F(Library, resolved_names_) \
F(Library, exported_names_) \
F(Library, loaded_scripts_) \
F(Namespace, library_) \
F(Namespace, show_names_) \
F(Namespace, hide_names_) \
F(Namespace, metadata_field_) \
F(KernelProgramInfo, string_offsets_) \
F(KernelProgramInfo, string_data_) \
F(KernelProgramInfo, canonical_names_) \
F(KernelProgramInfo, metadata_payloads_) \
F(KernelProgramInfo, metadata_mappings_) \
F(KernelProgramInfo, scripts_) \
F(KernelProgramInfo, constants_) \
F(KernelProgramInfo, potential_natives_) \
F(KernelProgramInfo, potential_pragma_functions_) \
F(KernelProgramInfo, constants_table_) \
F(KernelProgramInfo, libraries_cache_) \
F(KernelProgramInfo, classes_cache_) \
F(Code, object_pool_) \
F(Code, instructions_) \
F(Code, owner_) \
F(Code, exception_handlers_) \
F(Code, pc_descriptors_) \
F(Code, stackmaps_) \
F(Code, inlined_id_to_function_) \
F(Code, code_source_map_) \
F(Bytecode, object_pool_) \
F(Bytecode, instructions_) \
F(Bytecode, function_) \
F(Bytecode, exception_handlers_) \
F(Bytecode, pc_descriptors_) \
F(ExceptionHandlers, handled_types_data_) \
F(Context, parent_) \
F(SingleTargetCache, target_) \
F(UnlinkedCall, target_name_) \
F(UnlinkedCall, args_descriptor_) \
F(ICData, ic_data_) \
F(ICData, target_name_) \
F(ICData, args_descriptor_) \
F(ICData, owner_) \
F(MegamorphicCache, buckets_) \
F(MegamorphicCache, mask_) \
F(MegamorphicCache, target_name_) \
F(MegamorphicCache, args_descriptor_) \
F(SubtypeTestCache, cache_) \
F(ApiError, message_) \
F(LanguageError, previous_error_) \
F(LanguageError, script_) \
F(LanguageError, message_) \
F(LanguageError, formatted_message_) \
F(UnhandledException, exception_) \
F(UnhandledException, stacktrace_) \
F(UnwindError, message_) \
F(LibraryPrefix, name_) \
F(LibraryPrefix, importer_) \
F(LibraryPrefix, imports_) \
F(LibraryPrefix, dependent_code_) \
F(TypeArguments, instantiations_) \
F(TypeArguments, length_) \
F(TypeArguments, hash_) \
F(Type, type_class_id_) \
F(Type, arguments_) \
F(Type, hash_) \
F(TypeRef, type_) \
F(TypeParameter, name_) \
F(TypeParameter, hash_) \
F(TypeParameter, bound_) \
F(TypeParameter, parameterized_function_) \
F(BoundedType, type_) \
F(BoundedType, bound_) \
F(BoundedType, hash_) \
F(BoundedType, type_parameter_) \
F(MixinAppType, super_type_) \
F(MixinAppType, mixin_types_) \
F(Closure, instantiator_type_arguments_) \
F(Closure, function_type_arguments_) \
F(Closure, delayed_type_arguments_) \
F(Closure, function_) \
F(Closure, context_) \
F(Closure, hash_) \
F(String, length_) \
F(String, hash_) \
F(Array, type_arguments_) \
F(Array, length_) \
F(GrowableObjectArray, type_arguments_) \
F(GrowableObjectArray, length_) \
F(GrowableObjectArray, data_) \
F(LinkedHashMap, type_arguments_) \
F(LinkedHashMap, index_) \
F(LinkedHashMap, hash_mask_) \
F(LinkedHashMap, data_) \
F(LinkedHashMap, used_data_) \
F(LinkedHashMap, deleted_keys_) \
F(TypedData, length_) \
F(ExternalTypedData, length_) \
F(ReceivePort, send_port_) \
F(ReceivePort, handler_) \
F(StackTrace, async_link_) \
F(StackTrace, code_array_) \
F(StackTrace, pc_offset_array_) \
F(RegExp, num_bracket_expressions_) \
F(RegExp, pattern_) \
F(RegExp, external_one_byte_function_) \
F(RegExp, external_two_byte_function_) \
F(RegExp, external_one_byte_sticky_function_) \
F(RegExp, external_two_byte_sticky_function_) \
F(WeakProperty, key_) \
F(WeakProperty, value_) \
F(MirrorReference, referent_) \
F(UserTag, label_)
OffsetsTable::OffsetsTable(Zone* zone) : cached_offsets_(zone) {
for (intptr_t i = 0; offsets_table[i].class_id != -1; ++i) {
OffsetsTableEntry entry = offsets_table[i];
cached_offsets_.Insert({{entry.class_id, entry.offset}, entry.field_name});
}
}
const char* OffsetsTable::FieldNameForOffset(intptr_t class_id,
intptr_t offset) {
return cached_offsets_.LookupValue({class_id, offset});
}
#define DEFINE_OFFSETS_TABLE_ENTRY(class_name, field_name) \
{class_name::kClassId, #field_name, OFFSET_OF(Raw##class_name, field_name)},
// clang-format off
OffsetsTable::OffsetsTableEntry OffsetsTable::offsets_table[] = {
RAW_CLASSES_AND_FIELDS(DEFINE_OFFSETS_TABLE_ENTRY)
{-1, nullptr, -1}
};
// clang-format on
#undef DEFINE_OFFSETS_TABLE_ENTRY
#endif
} // namespace dart
<commit_msg>Add KPI::bytecode_component_ to raw_object_fields.cc<commit_after>// Copyright (c) 2018, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/raw_object_fields.h"
namespace dart {
#if defined(DART_PRECOMPILER)
#define RAW_CLASSES_AND_FIELDS(F) \
F(Class, name_) \
F(Class, user_name_) \
F(Class, functions_) \
F(Class, functions_hash_table_) \
F(Class, fields_) \
F(Class, offset_in_words_to_field_) \
F(Class, interfaces_) \
F(Class, script_) \
F(Class, library_) \
F(Class, type_parameters_) \
F(Class, super_type_) \
F(Class, mixin_) \
F(Class, signature_function_) \
F(Class, constants_) \
F(Class, canonical_type_) \
F(Class, invocation_dispatcher_cache_) \
F(Class, allocation_stub_) \
F(Class, direct_implementors_) \
F(Class, direct_subclasses_) \
F(Class, dependent_code_) \
F(PatchClass, patched_class_) \
F(PatchClass, origin_class_) \
F(PatchClass, script_) \
F(PatchClass, library_kernel_data_) \
F(Function, name_) \
F(Function, owner_) \
F(Function, result_type_) \
F(Function, parameter_types_) \
F(Function, parameter_names_) \
F(Function, type_parameters_) \
F(Function, data_) \
F(Function, ic_data_array_) \
F(Function, code_) \
F(ClosureData, context_scope_) \
F(ClosureData, parent_function_) \
F(ClosureData, signature_type_) \
F(ClosureData, closure_) \
F(SignatureData, parent_function_) \
F(SignatureData, signature_type_) \
F(RedirectionData, type_) \
F(RedirectionData, identifier_) \
F(RedirectionData, target_) \
F(Field, name_) \
F(Field, owner_) \
F(Field, type_) \
F(Field, guarded_list_length_) \
F(Field, dependent_code_) \
F(Field, type_test_cache_) \
F(Script, url_) \
F(Script, resolved_url_) \
F(Script, compile_time_constants_) \
F(Script, line_starts_) \
F(Script, debug_positions_) \
F(Script, yield_positions_) \
F(Script, kernel_program_info_) \
F(Script, source_) \
F(Library, name_) \
F(Library, url_) \
F(Library, private_key_) \
F(Library, dictionary_) \
F(Library, metadata_) \
F(Library, toplevel_class_) \
F(Library, patch_classes_) \
F(Library, imports_) \
F(Library, exports_) \
F(Library, load_error_) \
F(Library, kernel_data_) \
F(Library, resolved_names_) \
F(Library, exported_names_) \
F(Library, loaded_scripts_) \
F(Namespace, library_) \
F(Namespace, show_names_) \
F(Namespace, hide_names_) \
F(Namespace, metadata_field_) \
F(KernelProgramInfo, string_offsets_) \
F(KernelProgramInfo, string_data_) \
F(KernelProgramInfo, canonical_names_) \
F(KernelProgramInfo, metadata_payloads_) \
F(KernelProgramInfo, metadata_mappings_) \
F(KernelProgramInfo, scripts_) \
F(KernelProgramInfo, constants_) \
F(KernelProgramInfo, bytecode_component_) \
F(KernelProgramInfo, potential_natives_) \
F(KernelProgramInfo, potential_pragma_functions_) \
F(KernelProgramInfo, constants_table_) \
F(KernelProgramInfo, libraries_cache_) \
F(KernelProgramInfo, classes_cache_) \
F(Code, object_pool_) \
F(Code, instructions_) \
F(Code, owner_) \
F(Code, exception_handlers_) \
F(Code, pc_descriptors_) \
F(Code, stackmaps_) \
F(Code, inlined_id_to_function_) \
F(Code, code_source_map_) \
F(Bytecode, object_pool_) \
F(Bytecode, instructions_) \
F(Bytecode, function_) \
F(Bytecode, exception_handlers_) \
F(Bytecode, pc_descriptors_) \
F(ExceptionHandlers, handled_types_data_) \
F(Context, parent_) \
F(SingleTargetCache, target_) \
F(UnlinkedCall, target_name_) \
F(UnlinkedCall, args_descriptor_) \
F(ICData, ic_data_) \
F(ICData, target_name_) \
F(ICData, args_descriptor_) \
F(ICData, owner_) \
F(MegamorphicCache, buckets_) \
F(MegamorphicCache, mask_) \
F(MegamorphicCache, target_name_) \
F(MegamorphicCache, args_descriptor_) \
F(SubtypeTestCache, cache_) \
F(ApiError, message_) \
F(LanguageError, previous_error_) \
F(LanguageError, script_) \
F(LanguageError, message_) \
F(LanguageError, formatted_message_) \
F(UnhandledException, exception_) \
F(UnhandledException, stacktrace_) \
F(UnwindError, message_) \
F(LibraryPrefix, name_) \
F(LibraryPrefix, importer_) \
F(LibraryPrefix, imports_) \
F(LibraryPrefix, dependent_code_) \
F(TypeArguments, instantiations_) \
F(TypeArguments, length_) \
F(TypeArguments, hash_) \
F(Type, type_class_id_) \
F(Type, arguments_) \
F(Type, hash_) \
F(TypeRef, type_) \
F(TypeParameter, name_) \
F(TypeParameter, hash_) \
F(TypeParameter, bound_) \
F(TypeParameter, parameterized_function_) \
F(BoundedType, type_) \
F(BoundedType, bound_) \
F(BoundedType, hash_) \
F(BoundedType, type_parameter_) \
F(MixinAppType, super_type_) \
F(MixinAppType, mixin_types_) \
F(Closure, instantiator_type_arguments_) \
F(Closure, function_type_arguments_) \
F(Closure, delayed_type_arguments_) \
F(Closure, function_) \
F(Closure, context_) \
F(Closure, hash_) \
F(String, length_) \
F(String, hash_) \
F(Array, type_arguments_) \
F(Array, length_) \
F(GrowableObjectArray, type_arguments_) \
F(GrowableObjectArray, length_) \
F(GrowableObjectArray, data_) \
F(LinkedHashMap, type_arguments_) \
F(LinkedHashMap, index_) \
F(LinkedHashMap, hash_mask_) \
F(LinkedHashMap, data_) \
F(LinkedHashMap, used_data_) \
F(LinkedHashMap, deleted_keys_) \
F(TypedData, length_) \
F(ExternalTypedData, length_) \
F(ReceivePort, send_port_) \
F(ReceivePort, handler_) \
F(StackTrace, async_link_) \
F(StackTrace, code_array_) \
F(StackTrace, pc_offset_array_) \
F(RegExp, num_bracket_expressions_) \
F(RegExp, pattern_) \
F(RegExp, external_one_byte_function_) \
F(RegExp, external_two_byte_function_) \
F(RegExp, external_one_byte_sticky_function_) \
F(RegExp, external_two_byte_sticky_function_) \
F(WeakProperty, key_) \
F(WeakProperty, value_) \
F(MirrorReference, referent_) \
F(UserTag, label_)
OffsetsTable::OffsetsTable(Zone* zone) : cached_offsets_(zone) {
for (intptr_t i = 0; offsets_table[i].class_id != -1; ++i) {
OffsetsTableEntry entry = offsets_table[i];
cached_offsets_.Insert({{entry.class_id, entry.offset}, entry.field_name});
}
}
const char* OffsetsTable::FieldNameForOffset(intptr_t class_id,
intptr_t offset) {
return cached_offsets_.LookupValue({class_id, offset});
}
#define DEFINE_OFFSETS_TABLE_ENTRY(class_name, field_name) \
{class_name::kClassId, #field_name, OFFSET_OF(Raw##class_name, field_name)},
// clang-format off
OffsetsTable::OffsetsTableEntry OffsetsTable::offsets_table[] = {
RAW_CLASSES_AND_FIELDS(DEFINE_OFFSETS_TABLE_ENTRY)
{-1, nullptr, -1}
};
// clang-format on
#undef DEFINE_OFFSETS_TABLE_ENTRY
#endif
} // namespace dart
<|endoftext|>
|
<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "save_load.hpp"
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <glog/logging.h>
#include "jubatus/util/lang/cast.h"
#include "jubatus/core/common/exception.hpp"
#include "jubatus/core/common/big_endian.hpp"
#include "jubatus/core/common/crc32.hpp"
#include "jubatus/core/framework/mixable.hpp"
using jubatus::core::common::write_big_endian;
using jubatus::core::common::read_big_endian;
using std::string;
using jubatus::util::lang::lexical_cast;
namespace jubatus {
namespace server {
namespace framework {
namespace {
const char magic_number[8] = "jubatus";
const uint64_t format_version = 1;
uint32_t jubatus_version_major = -1;
uint32_t jubatus_version_minor = -1;
uint32_t jubatus_version_maintenance = -1;
// TODO(gintenlabo): remove sscanf
void init_versions() {
if (jubatus_version_major == static_cast<uint32_t>(-1)) {
int major, minor, maintenance;
std::sscanf(JUBATUS_VERSION, "%d.%d.%d", &major, &minor, &maintenance); // NOLINT
jubatus_version_major = major;
jubatus_version_minor = minor;
jubatus_version_maintenance = maintenance;
}
}
const uint64_t system_data_container_version = 1;
struct system_data_container {
uint64_t version;
time_t timestamp;
std::string type;
std::string id;
std::string config;
system_data_container()
: version(), timestamp(), type(), id(), config() {
}
system_data_container(const server_base& server, const std::string& id_)
: version(system_data_container_version),
timestamp(std::time(NULL)),
type(server.argv().type), id(id_),
config(server.get_config()) {
}
MSGPACK_DEFINE(version, timestamp, type, id, config);
};
uint32_t calc_crc32(const char* header, // header size is 28 (fixed)
const char* system_data, uint64_t system_data_size,
const char* user_data, uint64_t user_data_size) {
uint32_t crc32 = core::common::calc_crc32(header, 28);
crc32 = core::common::calc_crc32(&header[32], 16, crc32);
crc32 = core::common::calc_crc32(system_data, system_data_size, crc32);
crc32 = core::common::calc_crc32(user_data, user_data_size, crc32);
return crc32;
}
} // namespace
void save_server(std::ostream& os,
const server_base& server, const std::string& id) {
if (id == "") {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("empty id is not allowed"));
}
init_versions();
msgpack::sbuffer system_data_buf;
msgpack::pack(&system_data_buf, system_data_container(server, id));
msgpack::sbuffer user_data_buf;
{
msgpack::packer<msgpack::sbuffer> packer(user_data_buf);
packer.pack_array(2);
uint64_t user_data_version = server.user_data_version();
packer.pack(user_data_version);
server.get_mixable_holder()->pack(packer);
}
char header_buf[48];
std::memcpy(header_buf, magic_number, 8);
write_big_endian(format_version, &header_buf[8]);
write_big_endian(jubatus_version_major, &header_buf[16]);
write_big_endian(jubatus_version_minor, &header_buf[20]);
write_big_endian(jubatus_version_maintenance, &header_buf[24]);
// write_big_endian(crc32, &header_buf[28]); // skipped
write_big_endian(static_cast<uint64_t>(system_data_buf.size()),
&header_buf[32]);
write_big_endian(static_cast<uint64_t>(user_data_buf.size()),
&header_buf[40]);
uint32_t crc32 = calc_crc32(header_buf,
system_data_buf.data(), system_data_buf.size(),
user_data_buf.data(), user_data_buf.size());
write_big_endian(crc32, &header_buf[28]);
os.write(header_buf, 48);
os.write(system_data_buf.data(), system_data_buf.size());
os.write(user_data_buf.data(), user_data_buf.size());
}
void load_server(std::istream& is,
server_base& server, const std::string& id) {
init_versions();
char header_buf[48];
is.read(header_buf, 48);
if (std::memcmp(header_buf, magic_number, 8) != 0) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("invalid file format"));
}
uint64_t format_version_read = read_big_endian<uint64_t>(&header_buf[8]);
if (format_version_read != format_version) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"invalid format version: " +
lexical_cast<string>(format_version_read) +
", expected " +
lexical_cast<string>(format_version)));
}
uint32_t jubatus_major_read = read_big_endian<uint32_t>(&header_buf[16]);
uint32_t jubatus_minor_read = read_big_endian<uint32_t>(&header_buf[20]);
uint32_t jubatus_maintenance_read =
read_big_endian<uint32_t>(&header_buf[24]);
if (jubatus_major_read != jubatus_version_major ||
jubatus_minor_read != jubatus_version_minor ||
jubatus_maintenance_read != jubatus_version_maintenance) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"jubatus version mismatched: current version: " JUBATUS_VERSION
", saved version: " +
lexical_cast<std::string>(jubatus_major_read) + "." +
lexical_cast<std::string>(jubatus_minor_read) + "." +
lexical_cast<std::string>(jubatus_maintenance_read)));
}
uint32_t crc32_expected = read_big_endian<uint32_t>(&header_buf[28]);
uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
std::vector<char> system_data_buf(system_data_size);
is.read(&system_data_buf[0], system_data_size);
std::vector<char> user_data_buf(user_data_size);
is.read(&user_data_buf[0], user_data_size);
uint32_t crc32_actual = calc_crc32(header_buf,
&system_data_buf[0], system_data_size,
&user_data_buf[0], user_data_size);
if (crc32_actual != crc32_expected) {
std::ostringstream ss;
ss << "invalid crc32 checksum: " << std::hex << crc32_actual;
ss << ", read " << crc32_expected;
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(ss.str()));
}
system_data_container system_data_actual;
{
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, &system_data_buf[0], system_data_size);
unpacked.get().convert(&system_data_actual);
}
system_data_container system_data_expected(server, id);
if (system_data_actual.version != system_data_expected.version) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"invalid system data version: saved version: " +
lexical_cast<string>(system_data_actual.version) +
", expected " +
lexical_cast<string>(system_data_expected.version)));
}
if (system_data_actual.type != system_data_expected.type) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server type mismatched: " + system_data_actual.type +
", expected " + system_data_expected.type));
}
if (id != "" && system_data_actual.id != system_data_expected.id) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server id mismatched: " + system_data_actual.type +
", expected " + system_data_expected.type));
}
if (system_data_actual.config != system_data_expected.config) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server config mismatched" + system_data_actual.config +
", expected " + system_data_expected.config));
}
{
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, &user_data_buf[0], user_data_size);
std::vector<msgpack::object> objs;
unpacked.get().convert(&objs);
if (objs.size() != 2) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("invalid user container"));
}
uint64_t user_data_version_expected = server.user_data_version();
uint64_t user_data_version_actual;
objs[0].convert(&user_data_version_actual);
if (user_data_version_actual != user_data_version_expected) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"user data version mismatched: " +
lexical_cast<string>(user_data_version_actual) +
", expected " +
lexical_cast<string>(user_data_version_expected)));
}
server.get_mixable_holder()->unpack(objs[1]);
}
}
} // namespace framework
} // namespace server
} // namespace jubatus
<commit_msg>disable checking ID when loading models (fix #679)<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#include "save_load.hpp"
#include <ctime>
#include <fstream>
#include <string>
#include <vector>
#include <glog/logging.h>
#include "jubatus/util/lang/cast.h"
#include "jubatus/core/common/exception.hpp"
#include "jubatus/core/common/big_endian.hpp"
#include "jubatus/core/common/crc32.hpp"
#include "jubatus/core/framework/mixable.hpp"
using jubatus::core::common::write_big_endian;
using jubatus::core::common::read_big_endian;
using std::string;
using jubatus::util::lang::lexical_cast;
namespace jubatus {
namespace server {
namespace framework {
namespace {
const char magic_number[8] = "jubatus";
const uint64_t format_version = 1;
uint32_t jubatus_version_major = -1;
uint32_t jubatus_version_minor = -1;
uint32_t jubatus_version_maintenance = -1;
// TODO(gintenlabo): remove sscanf
void init_versions() {
if (jubatus_version_major == static_cast<uint32_t>(-1)) {
int major, minor, maintenance;
std::sscanf(JUBATUS_VERSION, "%d.%d.%d", &major, &minor, &maintenance); // NOLINT
jubatus_version_major = major;
jubatus_version_minor = minor;
jubatus_version_maintenance = maintenance;
}
}
const uint64_t system_data_container_version = 1;
struct system_data_container {
uint64_t version;
time_t timestamp;
std::string type;
std::string id;
std::string config;
system_data_container()
: version(), timestamp(), type(), id(), config() {
}
system_data_container(const server_base& server, const std::string& id_)
: version(system_data_container_version),
timestamp(std::time(NULL)),
type(server.argv().type), id(id_),
config(server.get_config()) {
}
MSGPACK_DEFINE(version, timestamp, type, id, config);
};
uint32_t calc_crc32(const char* header, // header size is 28 (fixed)
const char* system_data, uint64_t system_data_size,
const char* user_data, uint64_t user_data_size) {
uint32_t crc32 = core::common::calc_crc32(header, 28);
crc32 = core::common::calc_crc32(&header[32], 16, crc32);
crc32 = core::common::calc_crc32(system_data, system_data_size, crc32);
crc32 = core::common::calc_crc32(user_data, user_data_size, crc32);
return crc32;
}
} // namespace
void save_server(std::ostream& os,
const server_base& server, const std::string& id) {
if (id == "") {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("empty id is not allowed"));
}
init_versions();
msgpack::sbuffer system_data_buf;
msgpack::pack(&system_data_buf, system_data_container(server, id));
msgpack::sbuffer user_data_buf;
{
msgpack::packer<msgpack::sbuffer> packer(user_data_buf);
packer.pack_array(2);
uint64_t user_data_version = server.user_data_version();
packer.pack(user_data_version);
server.get_mixable_holder()->pack(packer);
}
char header_buf[48];
std::memcpy(header_buf, magic_number, 8);
write_big_endian(format_version, &header_buf[8]);
write_big_endian(jubatus_version_major, &header_buf[16]);
write_big_endian(jubatus_version_minor, &header_buf[20]);
write_big_endian(jubatus_version_maintenance, &header_buf[24]);
// write_big_endian(crc32, &header_buf[28]); // skipped
write_big_endian(static_cast<uint64_t>(system_data_buf.size()),
&header_buf[32]);
write_big_endian(static_cast<uint64_t>(user_data_buf.size()),
&header_buf[40]);
uint32_t crc32 = calc_crc32(header_buf,
system_data_buf.data(), system_data_buf.size(),
user_data_buf.data(), user_data_buf.size());
write_big_endian(crc32, &header_buf[28]);
os.write(header_buf, 48);
os.write(system_data_buf.data(), system_data_buf.size());
os.write(user_data_buf.data(), user_data_buf.size());
}
void load_server(std::istream& is,
server_base& server, const std::string& id) {
init_versions();
char header_buf[48];
is.read(header_buf, 48);
if (std::memcmp(header_buf, magic_number, 8) != 0) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("invalid file format"));
}
uint64_t format_version_read = read_big_endian<uint64_t>(&header_buf[8]);
if (format_version_read != format_version) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"invalid format version: " +
lexical_cast<string>(format_version_read) +
", expected " +
lexical_cast<string>(format_version)));
}
uint32_t jubatus_major_read = read_big_endian<uint32_t>(&header_buf[16]);
uint32_t jubatus_minor_read = read_big_endian<uint32_t>(&header_buf[20]);
uint32_t jubatus_maintenance_read =
read_big_endian<uint32_t>(&header_buf[24]);
if (jubatus_major_read != jubatus_version_major ||
jubatus_minor_read != jubatus_version_minor ||
jubatus_maintenance_read != jubatus_version_maintenance) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"jubatus version mismatched: current version: " JUBATUS_VERSION
", saved version: " +
lexical_cast<std::string>(jubatus_major_read) + "." +
lexical_cast<std::string>(jubatus_minor_read) + "." +
lexical_cast<std::string>(jubatus_maintenance_read)));
}
uint32_t crc32_expected = read_big_endian<uint32_t>(&header_buf[28]);
uint64_t system_data_size = read_big_endian<uint64_t>(&header_buf[32]);
uint64_t user_data_size = read_big_endian<uint64_t>(&header_buf[40]);
std::vector<char> system_data_buf(system_data_size);
is.read(&system_data_buf[0], system_data_size);
std::vector<char> user_data_buf(user_data_size);
is.read(&user_data_buf[0], user_data_size);
uint32_t crc32_actual = calc_crc32(header_buf,
&system_data_buf[0], system_data_size,
&user_data_buf[0], user_data_size);
if (crc32_actual != crc32_expected) {
std::ostringstream ss;
ss << "invalid crc32 checksum: " << std::hex << crc32_actual;
ss << ", read " << crc32_expected;
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(ss.str()));
}
system_data_container system_data_actual;
{
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, &system_data_buf[0], system_data_size);
unpacked.get().convert(&system_data_actual);
}
system_data_container system_data_expected(server, id);
if (system_data_actual.version != system_data_expected.version) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"invalid system data version: saved version: " +
lexical_cast<string>(system_data_actual.version) +
", expected " +
lexical_cast<string>(system_data_expected.version)));
}
if (system_data_actual.type != system_data_expected.type) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server type mismatched: " + system_data_actual.type +
", expected " + system_data_expected.type));
}
if (system_data_actual.config != system_data_expected.config) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"server config mismatched" + system_data_actual.config +
", expected " + system_data_expected.config));
}
{
msgpack::unpacked unpacked;
msgpack::unpack(&unpacked, &user_data_buf[0], user_data_size);
std::vector<msgpack::object> objs;
unpacked.get().convert(&objs);
if (objs.size() != 2) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error("invalid user container"));
}
uint64_t user_data_version_expected = server.user_data_version();
uint64_t user_data_version_actual;
objs[0].convert(&user_data_version_actual);
if (user_data_version_actual != user_data_version_expected) {
throw JUBATUS_EXCEPTION(
core::common::exception::runtime_error(
"user data version mismatched: " +
lexical_cast<string>(user_data_version_actual) +
", expected " +
lexical_cast<string>(user_data_version_expected)));
}
server.get_mixable_holder()->unpack(objs[1]);
}
}
} // namespace framework
} // namespace server
} // namespace jubatus
<|endoftext|>
|
<commit_before>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "rdb_protocol/stream.hpp"
#include "btree/keys.hpp"
#include "rdb_protocol/ql2.hpp"
#include "rdb_protocol/transform_visitors.hpp"
namespace query_language {
boost::shared_ptr<json_stream_t> json_stream_t::add_transformation(const rdb_protocol_details::transform_variant_t &t, ql::env_t *ql_env, const backtrace_t &backtrace) {
rdb_protocol_details::transform_t transform;
transform.push_back(rdb_protocol_details::transform_atom_t(t, backtrace));
return boost::make_shared<transform_stream_t>(shared_from_this(), ql_env, transform);
}
result_t json_stream_t::apply_terminal(
const rdb_protocol_details::terminal_variant_t &_t,
ql::env_t *ql_env,
const backtrace_t &backtrace) {
rdb_protocol_details::terminal_variant_t t = _t;
result_t res;
terminal_initialize(ql_env, backtrace, &t, &res);
boost::shared_ptr<scoped_cJSON_t> json;
while ((json = next())) {
terminal_apply(ql_env, backtrace, json, &t, &res);
}
return res;
}
in_memory_stream_t::in_memory_stream_t(json_array_iterator_t it) {
while (cJSON *json = it.next()) {
data.push_back(boost::shared_ptr<scoped_cJSON_t>(new scoped_cJSON_t(cJSON_DeepCopy(json))));
}
}
in_memory_stream_t::in_memory_stream_t(boost::shared_ptr<json_stream_t> stream) {
while (boost::shared_ptr<scoped_cJSON_t> json = stream->next()) {
data.push_back(json);
}
}
boost::shared_ptr<scoped_cJSON_t> in_memory_stream_t::next() {
if (data.empty()) {
return boost::shared_ptr<scoped_cJSON_t>();
} else {
boost::shared_ptr<scoped_cJSON_t> ret = data.front();
data.pop_front();
return ret;
}
}
transform_stream_t::transform_stream_t(boost::shared_ptr<json_stream_t> _stream,
ql::env_t *_ql_env,
const rdb_protocol_details::transform_t &tr) :
stream(_stream),
ql_env(_ql_env),
transform(tr) { }
boost::shared_ptr<scoped_cJSON_t> transform_stream_t::next() {
while (data.empty()) {
boost::shared_ptr<scoped_cJSON_t> input = stream->next();
if (!input) {
// End of stream reached.
return boost::shared_ptr<scoped_cJSON_t>();
}
json_list_t accumulator;
accumulator.push_back(input);
//Apply transforms to the data
typedef rdb_protocol_details::transform_t::iterator tit_t;
for (tit_t it = transform.begin();
it != transform.end();
++it) {
json_list_t tmp;
for (json_list_t::iterator jt = accumulator.begin();
jt != accumulator.end();
++jt) {
transform_apply(ql_env, it->backtrace, *jt, &it->variant, &tmp);
}
accumulator.swap(tmp);
}
data.swap(accumulator);
}
boost::shared_ptr<scoped_cJSON_t> datum = data.front();
data.pop_front();
return datum;
}
boost::shared_ptr<json_stream_t> transform_stream_t::add_transformation(const rdb_protocol_details::transform_variant_t &t, UNUSED ql::env_t *ql_env2, const backtrace_t &backtrace) {
transform.push_back(rdb_protocol_details::transform_atom_t(t, backtrace));
return shared_from_this();
}
batched_rget_stream_t::batched_rget_stream_t(
const namespace_repo_t<rdb_protocol_t>::access_t &_ns_access,
signal_t *_interruptor,
counted_t<const ql::datum_t> left_bound,
counted_t<const ql::datum_t> right_bound,
const std::map<std::string, ql::wire_func_t> &_optargs,
bool _use_outdated, sorting_t _sorting)
: ns_access(_ns_access), interruptor(_interruptor),
finished(false), started(false), optargs(_optargs), use_outdated(_use_outdated),
range(key_range_t::closed,
left_bound.has()
? store_key_t(left_bound->print_primary())
: store_key_t::min(),
key_range_t::closed,
right_bound.has()
? store_key_t(right_bound->print_primary())
: store_key_t::max()),
table_scan_backtrace(),
sorting(_sorting)
{ }
batched_rget_stream_t::batched_rget_stream_t(
const namespace_repo_t<rdb_protocol_t>::access_t &_ns_access,
signal_t *_interruptor, const std::string &_sindex_id,
const std::map<std::string, ql::wire_func_t> &_optargs,
bool _use_outdated,
counted_t<const ql::datum_t> _sindex_start_value,
counted_t<const ql::datum_t> _sindex_end_value,
sorting_t _sorting)
: ns_access(_ns_access),
interruptor(_interruptor),
sindex_id(_sindex_id),
finished(false),
started(false),
optargs(_optargs),
use_outdated(_use_outdated),
sindex_start_value(_sindex_start_value),
sindex_end_value(_sindex_end_value),
range(rdb_protocol_t::sindex_key_range(
_sindex_start_value != NULL
? _sindex_start_value->truncated_secondary()
: store_key_t::min(),
_sindex_end_value != NULL
? _sindex_end_value->truncated_secondary()
: store_key_t::max())),
table_scan_backtrace(),
sorting(_sorting)
{ }
boost::optional<rget_item_t> batched_rget_stream_t::head() {
started = true;
if (data.empty()) {
if (finished) {
return boost::optional<rget_item_t>();
}
read_more();
if (data.empty()) {
finished = true;
return boost::optional<rget_item_t>();
}
}
return data.front();
}
void batched_rget_stream_t::pop() {
guarantee(!data.empty());
data.pop_front();
}
bool rget_item_sindex_key_less(const rget_item_t &left, const rget_item_t &right) {
return json_cmp(left.sindex_key->get(), right.sindex_key->get()) < 0;
}
boost::shared_ptr<scoped_cJSON_t> batched_rget_stream_t::next() {
if (!sorting_buffer.empty()) {
boost::shared_ptr<scoped_cJSON_t> datum = sorting_buffer.front().data;
sorting_buffer.pop_front();
return datum;
} else {
for (;;) {
boost::optional<rget_item_t> item = head();
if (!item) {
break;
} else if (!ql::datum_t::key_is_truncated(item->key)) {
if (sorting_buffer.empty()) {
pop();
return item->data;
} else {
break;
}
} else {
pop();
sorting_buffer.push_back(*item);
}
}
}
/* The sorting buffer should now have unsorted data in it. Time to sort it. */
if (sorting_buffer.empty()) {
/* Nothing in the sorting buffer, this means we don't have any data to
* return so we return nothing. */
return boost::shared_ptr<scoped_cJSON_t>();
} else {
/* There's data in the sorting_buffer time to sort it. */
debugf("Doing some sorting of %zd values.\n", sorting_buffer.size());
std::sort(sorting_buffer.begin(), sorting_buffer.end(),
&rget_item_sindex_key_less);
boost::shared_ptr<scoped_cJSON_t> datum = sorting_buffer.front().data;
sorting_buffer.pop_front();
return datum;
}
}
boost::shared_ptr<json_stream_t> batched_rget_stream_t::add_transformation(const rdb_protocol_details::transform_variant_t &t, UNUSED ql::env_t *ql_env2, const backtrace_t &per_op_backtrace) {
guarantee(!started);
transform.push_back(rdb_protocol_details::transform_atom_t(t, per_op_backtrace));
return shared_from_this();
}
result_t batched_rget_stream_t::apply_terminal(
const rdb_protocol_details::terminal_variant_t &t,
UNUSED ql::env_t *ql_env,
const backtrace_t &per_op_backtrace) {
rdb_protocol_t::rget_read_t rget_read = get_rget();
rget_read.terminal = rdb_protocol_details::terminal_t(t, per_op_backtrace);
rdb_protocol_t::read_t read(rget_read);
try {
rdb_protocol_t::read_response_t res;
if (use_outdated) {
ns_access.get_namespace_if()->read_outdated(read, &res, interruptor);
} else {
ns_access.get_namespace_if()->read(read, &res, order_token_t::ignore, interruptor);
}
rdb_protocol_t::rget_read_response_t *p_res = boost::get<rdb_protocol_t::rget_read_response_t>(&res.response);
guarantee(p_res);
/* Re throw an exception if we got one. */
if (runtime_exc_t *e = boost::get<runtime_exc_t>(&p_res->result)) {
throw *e;
} else if (ql::exc_t *e2 = boost::get<ql::exc_t>(&p_res->result)) {
throw *e2;
} else if (ql::datum_exc_t *e3 = boost::get<ql::datum_exc_t>(&p_res->result)) {
throw *e3;
}
return p_res->result;
} catch (const cannot_perform_query_exc_t &e) {
if (table_scan_backtrace) {
throw runtime_exc_t("cannot perform read: " + std::string(e.what()), *table_scan_backtrace);
} else {
// No backtrace for these.
rfail_toplevel(ql::base_exc_t::GENERIC,
"cannot perform read: %s", e.what());
}
}
}
rdb_protocol_t::rget_read_t batched_rget_stream_t::get_rget() {
if (!sindex_id) {
return rdb_protocol_t::rget_read_t(rdb_protocol_t::region_t(range),
transform,
optargs,
sorting);
} else {
return rdb_protocol_t::rget_read_t(rdb_protocol_t::region_t(range),
*sindex_id,
sindex_start_value,
sindex_end_value,
transform,
optargs,
sorting);
}
}
void batched_rget_stream_t::read_more() {
rdb_protocol_t::read_t read(get_rget());
try {
guarantee(ns_access.get_namespace_if());
rdb_protocol_t::read_response_t res;
if (use_outdated) {
ns_access.get_namespace_if()->read_outdated(read, &res, interruptor);
} else {
ns_access.get_namespace_if()->read(read, &res, order_token_t::ignore, interruptor);
}
rdb_protocol_t::rget_read_response_t *p_res = boost::get<rdb_protocol_t::rget_read_response_t>(&res.response);
guarantee(p_res);
/* Re throw an exception if we got one. */
if (auto e = boost::get<runtime_exc_t>(&p_res->result)) {
throw *e;
} else if (auto e2 = boost::get<ql::exc_t>(&p_res->result)) {
throw *e2;
} else if (auto e3 = boost::get<ql::datum_exc_t>(&p_res->result)) {
throw *e3;
}
// todo: just do a straight copy?
typedef rdb_protocol_t::rget_read_response_t::stream_t stream_t;
stream_t *stream = boost::get<stream_t>(&p_res->result);
guarantee(stream);
for (stream_t::iterator i = stream->begin(); i != stream->end(); ++i) {
guarantee(i->data);
data.push_back(*i);
}
if (forward(sorting)) {
range.left = p_res->last_considered_key;
} else {
range.right = key_range_t::right_bound_t(p_res->last_considered_key);
}
if (forward(sorting) &&
(!range.left.increment() ||
(!range.right.unbounded && (range.right.key < range.left)))) {
finished = true;
} else if (backward(sorting)) {
guarantee(!range.right.unbounded);
if (!range.right.key.decrement() ||
range.right.key < range.left) {
finished = true;
}
}
} catch (const cannot_perform_query_exc_t &e) {
if (table_scan_backtrace) {
throw runtime_exc_t("cannot perform read: " + std::string(e.what()), *table_scan_backtrace);
} else {
// No backtrace.
rfail_toplevel(ql::base_exc_t::GENERIC,
"cannot perform read: %s", e.what());
}
}
}
} //namespace query_language
<commit_msg>Remove an unneeded debugf.<commit_after>// Copyright 2010-2012 RethinkDB, all rights reserved.
#include "rdb_protocol/stream.hpp"
#include "btree/keys.hpp"
#include "rdb_protocol/ql2.hpp"
#include "rdb_protocol/transform_visitors.hpp"
namespace query_language {
boost::shared_ptr<json_stream_t> json_stream_t::add_transformation(const rdb_protocol_details::transform_variant_t &t, ql::env_t *ql_env, const backtrace_t &backtrace) {
rdb_protocol_details::transform_t transform;
transform.push_back(rdb_protocol_details::transform_atom_t(t, backtrace));
return boost::make_shared<transform_stream_t>(shared_from_this(), ql_env, transform);
}
result_t json_stream_t::apply_terminal(
const rdb_protocol_details::terminal_variant_t &_t,
ql::env_t *ql_env,
const backtrace_t &backtrace) {
rdb_protocol_details::terminal_variant_t t = _t;
result_t res;
terminal_initialize(ql_env, backtrace, &t, &res);
boost::shared_ptr<scoped_cJSON_t> json;
while ((json = next())) {
terminal_apply(ql_env, backtrace, json, &t, &res);
}
return res;
}
in_memory_stream_t::in_memory_stream_t(json_array_iterator_t it) {
while (cJSON *json = it.next()) {
data.push_back(boost::shared_ptr<scoped_cJSON_t>(new scoped_cJSON_t(cJSON_DeepCopy(json))));
}
}
in_memory_stream_t::in_memory_stream_t(boost::shared_ptr<json_stream_t> stream) {
while (boost::shared_ptr<scoped_cJSON_t> json = stream->next()) {
data.push_back(json);
}
}
boost::shared_ptr<scoped_cJSON_t> in_memory_stream_t::next() {
if (data.empty()) {
return boost::shared_ptr<scoped_cJSON_t>();
} else {
boost::shared_ptr<scoped_cJSON_t> ret = data.front();
data.pop_front();
return ret;
}
}
transform_stream_t::transform_stream_t(boost::shared_ptr<json_stream_t> _stream,
ql::env_t *_ql_env,
const rdb_protocol_details::transform_t &tr) :
stream(_stream),
ql_env(_ql_env),
transform(tr) { }
boost::shared_ptr<scoped_cJSON_t> transform_stream_t::next() {
while (data.empty()) {
boost::shared_ptr<scoped_cJSON_t> input = stream->next();
if (!input) {
// End of stream reached.
return boost::shared_ptr<scoped_cJSON_t>();
}
json_list_t accumulator;
accumulator.push_back(input);
//Apply transforms to the data
typedef rdb_protocol_details::transform_t::iterator tit_t;
for (tit_t it = transform.begin();
it != transform.end();
++it) {
json_list_t tmp;
for (json_list_t::iterator jt = accumulator.begin();
jt != accumulator.end();
++jt) {
transform_apply(ql_env, it->backtrace, *jt, &it->variant, &tmp);
}
accumulator.swap(tmp);
}
data.swap(accumulator);
}
boost::shared_ptr<scoped_cJSON_t> datum = data.front();
data.pop_front();
return datum;
}
boost::shared_ptr<json_stream_t> transform_stream_t::add_transformation(const rdb_protocol_details::transform_variant_t &t, UNUSED ql::env_t *ql_env2, const backtrace_t &backtrace) {
transform.push_back(rdb_protocol_details::transform_atom_t(t, backtrace));
return shared_from_this();
}
batched_rget_stream_t::batched_rget_stream_t(
const namespace_repo_t<rdb_protocol_t>::access_t &_ns_access,
signal_t *_interruptor,
counted_t<const ql::datum_t> left_bound,
counted_t<const ql::datum_t> right_bound,
const std::map<std::string, ql::wire_func_t> &_optargs,
bool _use_outdated, sorting_t _sorting)
: ns_access(_ns_access), interruptor(_interruptor),
finished(false), started(false), optargs(_optargs), use_outdated(_use_outdated),
range(key_range_t::closed,
left_bound.has()
? store_key_t(left_bound->print_primary())
: store_key_t::min(),
key_range_t::closed,
right_bound.has()
? store_key_t(right_bound->print_primary())
: store_key_t::max()),
table_scan_backtrace(),
sorting(_sorting)
{ }
batched_rget_stream_t::batched_rget_stream_t(
const namespace_repo_t<rdb_protocol_t>::access_t &_ns_access,
signal_t *_interruptor, const std::string &_sindex_id,
const std::map<std::string, ql::wire_func_t> &_optargs,
bool _use_outdated,
counted_t<const ql::datum_t> _sindex_start_value,
counted_t<const ql::datum_t> _sindex_end_value,
sorting_t _sorting)
: ns_access(_ns_access),
interruptor(_interruptor),
sindex_id(_sindex_id),
finished(false),
started(false),
optargs(_optargs),
use_outdated(_use_outdated),
sindex_start_value(_sindex_start_value),
sindex_end_value(_sindex_end_value),
range(rdb_protocol_t::sindex_key_range(
_sindex_start_value != NULL
? _sindex_start_value->truncated_secondary()
: store_key_t::min(),
_sindex_end_value != NULL
? _sindex_end_value->truncated_secondary()
: store_key_t::max())),
table_scan_backtrace(),
sorting(_sorting)
{ }
boost::optional<rget_item_t> batched_rget_stream_t::head() {
started = true;
if (data.empty()) {
if (finished) {
return boost::optional<rget_item_t>();
}
read_more();
if (data.empty()) {
finished = true;
return boost::optional<rget_item_t>();
}
}
return data.front();
}
void batched_rget_stream_t::pop() {
guarantee(!data.empty());
data.pop_front();
}
bool rget_item_sindex_key_less(const rget_item_t &left, const rget_item_t &right) {
return json_cmp(left.sindex_key->get(), right.sindex_key->get()) < 0;
}
boost::shared_ptr<scoped_cJSON_t> batched_rget_stream_t::next() {
if (!sorting_buffer.empty()) {
boost::shared_ptr<scoped_cJSON_t> datum = sorting_buffer.front().data;
sorting_buffer.pop_front();
return datum;
} else {
for (;;) {
boost::optional<rget_item_t> item = head();
if (!item) {
break;
} else if (!ql::datum_t::key_is_truncated(item->key)) {
if (sorting_buffer.empty()) {
pop();
return item->data;
} else {
break;
}
} else {
pop();
sorting_buffer.push_back(*item);
}
}
}
/* The sorting buffer should now have unsorted data in it. Time to sort it. */
if (sorting_buffer.empty()) {
/* Nothing in the sorting buffer, this means we don't have any data to
* return so we return nothing. */
return boost::shared_ptr<scoped_cJSON_t>();
} else {
/* There's data in the sorting_buffer time to sort it. */
std::sort(sorting_buffer.begin(), sorting_buffer.end(),
&rget_item_sindex_key_less);
boost::shared_ptr<scoped_cJSON_t> datum = sorting_buffer.front().data;
sorting_buffer.pop_front();
return datum;
}
}
boost::shared_ptr<json_stream_t> batched_rget_stream_t::add_transformation(const rdb_protocol_details::transform_variant_t &t, UNUSED ql::env_t *ql_env2, const backtrace_t &per_op_backtrace) {
guarantee(!started);
transform.push_back(rdb_protocol_details::transform_atom_t(t, per_op_backtrace));
return shared_from_this();
}
result_t batched_rget_stream_t::apply_terminal(
const rdb_protocol_details::terminal_variant_t &t,
UNUSED ql::env_t *ql_env,
const backtrace_t &per_op_backtrace) {
rdb_protocol_t::rget_read_t rget_read = get_rget();
rget_read.terminal = rdb_protocol_details::terminal_t(t, per_op_backtrace);
rdb_protocol_t::read_t read(rget_read);
try {
rdb_protocol_t::read_response_t res;
if (use_outdated) {
ns_access.get_namespace_if()->read_outdated(read, &res, interruptor);
} else {
ns_access.get_namespace_if()->read(read, &res, order_token_t::ignore, interruptor);
}
rdb_protocol_t::rget_read_response_t *p_res = boost::get<rdb_protocol_t::rget_read_response_t>(&res.response);
guarantee(p_res);
/* Re throw an exception if we got one. */
if (runtime_exc_t *e = boost::get<runtime_exc_t>(&p_res->result)) {
throw *e;
} else if (ql::exc_t *e2 = boost::get<ql::exc_t>(&p_res->result)) {
throw *e2;
} else if (ql::datum_exc_t *e3 = boost::get<ql::datum_exc_t>(&p_res->result)) {
throw *e3;
}
return p_res->result;
} catch (const cannot_perform_query_exc_t &e) {
if (table_scan_backtrace) {
throw runtime_exc_t("cannot perform read: " + std::string(e.what()), *table_scan_backtrace);
} else {
// No backtrace for these.
rfail_toplevel(ql::base_exc_t::GENERIC,
"cannot perform read: %s", e.what());
}
}
}
rdb_protocol_t::rget_read_t batched_rget_stream_t::get_rget() {
if (!sindex_id) {
return rdb_protocol_t::rget_read_t(rdb_protocol_t::region_t(range),
transform,
optargs,
sorting);
} else {
return rdb_protocol_t::rget_read_t(rdb_protocol_t::region_t(range),
*sindex_id,
sindex_start_value,
sindex_end_value,
transform,
optargs,
sorting);
}
}
void batched_rget_stream_t::read_more() {
rdb_protocol_t::read_t read(get_rget());
try {
guarantee(ns_access.get_namespace_if());
rdb_protocol_t::read_response_t res;
if (use_outdated) {
ns_access.get_namespace_if()->read_outdated(read, &res, interruptor);
} else {
ns_access.get_namespace_if()->read(read, &res, order_token_t::ignore, interruptor);
}
rdb_protocol_t::rget_read_response_t *p_res = boost::get<rdb_protocol_t::rget_read_response_t>(&res.response);
guarantee(p_res);
/* Re throw an exception if we got one. */
if (auto e = boost::get<runtime_exc_t>(&p_res->result)) {
throw *e;
} else if (auto e2 = boost::get<ql::exc_t>(&p_res->result)) {
throw *e2;
} else if (auto e3 = boost::get<ql::datum_exc_t>(&p_res->result)) {
throw *e3;
}
// todo: just do a straight copy?
typedef rdb_protocol_t::rget_read_response_t::stream_t stream_t;
stream_t *stream = boost::get<stream_t>(&p_res->result);
guarantee(stream);
for (stream_t::iterator i = stream->begin(); i != stream->end(); ++i) {
guarantee(i->data);
data.push_back(*i);
}
if (forward(sorting)) {
range.left = p_res->last_considered_key;
} else {
range.right = key_range_t::right_bound_t(p_res->last_considered_key);
}
if (forward(sorting) &&
(!range.left.increment() ||
(!range.right.unbounded && (range.right.key < range.left)))) {
finished = true;
} else if (backward(sorting)) {
guarantee(!range.right.unbounded);
if (!range.right.key.decrement() ||
range.right.key < range.left) {
finished = true;
}
}
} catch (const cannot_perform_query_exc_t &e) {
if (table_scan_backtrace) {
throw runtime_exc_t("cannot perform read: " + std::string(e.what()), *table_scan_backtrace);
} else {
// No backtrace.
rfail_toplevel(ql::base_exc_t::GENERIC,
"cannot perform read: %s", e.what());
}
}
}
} //namespace query_language
<|endoftext|>
|
<commit_before>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/operators/detail/safe_ref.h"
#include "paddle/fluid/operators/reader/reader_op_registry.h"
namespace paddle {
namespace operators {
namespace reader {
class MultiPassReader : public framework::DecoratedReader {
public:
MultiPassReader(ReaderBase* reader, int pass_num)
: DecoratedReader(reader), pass_num_(pass_num), pass_count_(0) {}
void ReadNext(std::vector<framework::LoDTensor>* out) override {
if (!HasNext()) {
PADDLE_THROW("There is no next data!");
}
reader_->ReadNext(out);
}
bool HasNext() const override {
if (reader_->HasNext()) {
return true;
} else {
++pass_count_;
if (pass_count_ >= pass_num_) {
return false;
} else {
reader_->ReInit();
return true;
}
}
}
void ReInit() override {
pass_count_ = 0;
reader_->ReInit();
}
private:
int pass_num_;
mutable int pass_count_;
};
class CreateMultiPassReaderOp : public framework::OperatorBase {
public:
using framework::OperatorBase::OperatorBase;
private:
void RunImpl(const framework::Scope& scope,
const platform::Place& dev_place) const override {
const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader"))
->Get<framework::ReaderHolder>();
auto& out = detail::Ref(scope.FindVar(Output("Out")));
int pass_num = Attr<int>("pass_num");
out.GetMutable<framework::ReaderHolder>()->Reset(
new MultiPassReader(underlying_reader.Get(), pass_num));
}
};
class CreateMultiPassReaderOpMaker : public DecoratedReaderMakerBase {
public:
CreateMultiPassReaderOpMaker(OpProto* op_proto, OpAttrChecker* op_checker)
: DecoratedReaderMakerBase(op_proto, op_checker) {
AddAttr<int>("pass_num", "The number of pass to run.").GreaterThan(0);
AddComment(R"DOC(
CreateMultiPassReader Operator
This operator creates a multi-pass reader. A multi-pass reader
is used to yield data for several pass training continuously.
It takes the the number of pass to run as one of its attributes
('pass_num'), and maintains a pass counter to record how many
passes it has completed. When the underlying reader reach the EOF,
the multi-pass reader checks whether it has completed training
of the given number of pass. If not, the underlying reader will
be re-initialized and starts a new pass automatically.
)DOC");
}
};
} // namespace reader
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators::reader;
REGISTER_DECORATED_READER_OPERATOR(create_multi_pass_reader,
ops::CreateMultiPassReaderOp,
ops::CreateMultiPassReaderOpMaker);
<commit_msg>refine MultiPassReader's doc string<commit_after>// Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "paddle/fluid/operators/detail/safe_ref.h"
#include "paddle/fluid/operators/reader/reader_op_registry.h"
namespace paddle {
namespace operators {
namespace reader {
class MultiPassReader : public framework::DecoratedReader {
public:
MultiPassReader(ReaderBase* reader, int pass_num)
: DecoratedReader(reader), pass_num_(pass_num), pass_count_(0) {}
void ReadNext(std::vector<framework::LoDTensor>* out) override {
if (!HasNext()) {
PADDLE_THROW("There is no next data!");
}
reader_->ReadNext(out);
}
bool HasNext() const override {
if (reader_->HasNext()) {
return true;
} else {
++pass_count_;
if (pass_count_ >= pass_num_) {
return false;
} else {
reader_->ReInit();
return true;
}
}
}
void ReInit() override {
pass_count_ = 0;
reader_->ReInit();
}
private:
int pass_num_;
mutable int pass_count_;
};
class CreateMultiPassReaderOp : public framework::OperatorBase {
public:
using framework::OperatorBase::OperatorBase;
private:
void RunImpl(const framework::Scope& scope,
const platform::Place& dev_place) const override {
const auto& underlying_reader = scope.FindVar(Input("UnderlyingReader"))
->Get<framework::ReaderHolder>();
auto& out = detail::Ref(scope.FindVar(Output("Out")));
int pass_num = Attr<int>("pass_num");
out.GetMutable<framework::ReaderHolder>()->Reset(
new MultiPassReader(underlying_reader.Get(), pass_num));
}
};
class CreateMultiPassReaderOpMaker : public DecoratedReaderMakerBase {
public:
CreateMultiPassReaderOpMaker(OpProto* op_proto, OpAttrChecker* op_checker)
: DecoratedReaderMakerBase(op_proto, op_checker) {
AddAttr<int>("pass_num", "The number of pass to run.").GreaterThan(0);
AddComment(R"DOC(
CreateMultiPassReader Operator
This operator creates a multi-pass reader. A multi-pass reader
is used to yield data for several pass training continuously.
It takes the number of passes to run as one of its attributes
('pass_num'), and maintains a pass counter to record how many
passes it has completed. When the underlying reader reaches the
EOF, the multi-pass reader checks whether it has completed training
of the given number of pass. If not, the underlying reader will
be re-initialized and starts a new pass automatically.
)DOC");
}
};
} // namespace reader
} // namespace operators
} // namespace paddle
namespace ops = paddle::operators::reader;
REGISTER_DECORATED_READER_OPERATOR(create_multi_pass_reader,
ops::CreateMultiPassReaderOp,
ops::CreateMultiPassReaderOpMaker);
<|endoftext|>
|
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "alloc_impl.hxx"
#include "rtl/alloc.h"
#include <sal/macros.h>
#include <cassert>
#include <string.h>
#include <stdio.h>
#include "internal/rtllifecycle.h"
AllocMode alloc_mode = AMode_UNSET;
#if !defined(FORCE_SYSALLOC)
static void determine_alloc_mode()
{
assert(alloc_mode == AMode_UNSET);
alloc_mode = (getenv("G_SLICE") == NULL ? AMode_CUSTOM : AMode_SYSTEM);
}
/* ================================================================= *
*
* custom allocator includes.
*
* ================================================================= */
#include "sal/macros.h"
/* ================================================================= *
*
* custom allocator internals.
*
* ================================================================= */
static const sal_Size g_alloc_sizes[] =
{
/* powers of 2**(1/4) */
4 * 4, 6 * 4,
4 * 8, 5 * 8, 6 * 8, 7 * 8,
4 * 16, 5 * 16, 6 * 16, 7 * 16,
4 * 32, 5 * 32, 6 * 32, 7 * 32,
4 * 64, 5 * 64, 6 * 64, 7 * 64,
4 * 128, 5 * 128, 6 * 128, 7 * 128,
4 * 256, 5 * 256, 6 * 256, 7 * 256,
4 * 512, 5 * 512, 6 * 512, 7 * 512,
4 * 1024, 5 * 1024, 6 * 1024, 7 * 1024,
4 * 2048, 5 * 2048, 6 * 2048, 7 * 2048,
4 * 4096
};
#define RTL_MEMORY_CACHED_LIMIT 4 * 4096
#define RTL_MEMORY_CACHED_SIZES (SAL_N_ELEMENTS(g_alloc_sizes))
static rtl_cache_type * g_alloc_caches[RTL_MEMORY_CACHED_SIZES] =
{
0,
};
#define RTL_MEMALIGN 8
#define RTL_MEMALIGN_SHIFT 3
static rtl_cache_type * g_alloc_table[RTL_MEMORY_CACHED_LIMIT >> RTL_MEMALIGN_SHIFT] =
{
0,
};
static rtl_arena_type * gp_alloc_arena = 0;
/* ================================================================= *
*
* custom allocator implemenation.
*
* ================================================================= */
void *
SAL_CALL rtl_allocateMemory_CUSTOM (sal_Size n) SAL_THROW_EXTERN_C()
{
void * p = 0;
if (n > 0)
{
char * addr;
sal_Size size = RTL_MEMORY_ALIGN(n + RTL_MEMALIGN, RTL_MEMALIGN);
assert(RTL_MEMALIGN >= sizeof(sal_Size));
if (n >= SAL_MAX_SIZE - (RTL_MEMALIGN + RTL_MEMALIGN - 1))
{
/* requested size too large for roundup alignment */
return 0;
}
try_alloc:
if (size <= RTL_MEMORY_CACHED_LIMIT)
addr = (char*)rtl_cache_alloc(g_alloc_table[(size - 1) >> RTL_MEMALIGN_SHIFT]);
else
addr = (char*)rtl_arena_alloc (gp_alloc_arena, &size);
if (addr != 0)
{
((sal_Size*)(addr))[0] = size;
p = addr + RTL_MEMALIGN;
}
else if (gp_alloc_arena == 0)
{
ensureMemorySingleton();
if (gp_alloc_arena)
{
/* try again */
goto try_alloc;
}
}
}
return (p);
}
/* ================================================================= */
void SAL_CALL rtl_freeMemory_CUSTOM (void * p) SAL_THROW_EXTERN_C()
{
if (p != 0)
{
char * addr = (char*)(p) - RTL_MEMALIGN;
sal_Size size = ((sal_Size*)(addr))[0];
if (size <= RTL_MEMORY_CACHED_LIMIT)
rtl_cache_free(g_alloc_table[(size - 1) >> RTL_MEMALIGN_SHIFT], addr);
else
rtl_arena_free (gp_alloc_arena, addr, size);
}
}
/* ================================================================= */
void * SAL_CALL rtl_reallocateMemory_CUSTOM (void * p, sal_Size n) SAL_THROW_EXTERN_C()
{
if (n > 0)
{
if (p != 0)
{
void * p_old = p;
sal_Size n_old = ((sal_Size*)( (char*)(p) - RTL_MEMALIGN ))[0] - RTL_MEMALIGN;
p = rtl_allocateMemory (n);
if (p != 0)
{
memcpy (p, p_old, SAL_MIN(n, n_old));
rtl_freeMemory (p_old);
}
}
else
{
p = rtl_allocateMemory (n);
}
}
else if (p != 0)
{
rtl_freeMemory (p), p = 0;
}
return (p);
}
#endif
/* ================================================================= *
*
* custom allocator initialization / finalization.
*
* ================================================================= */
void rtl_memory_init()
{
#if !defined(FORCE_SYSALLOC)
{
/* global memory arena */
assert(gp_alloc_arena == 0);
gp_alloc_arena = rtl_arena_create (
"rtl_alloc_arena",
2048, /* quantum */
0, /* w/o quantum caching */
0, /* default source */
rtl_arena_alloc,
rtl_arena_free,
0 /* flags */
);
assert(gp_alloc_arena != 0);
}
{
sal_Size size;
int i, n = RTL_MEMORY_CACHED_SIZES;
for (i = 0; i < n; i++)
{
char name[RTL_CACHE_NAME_LENGTH + 1];
(void) snprintf (name, sizeof(name), "rtl_alloc_%lu", g_alloc_sizes[i]);
g_alloc_caches[i] = rtl_cache_create (name, g_alloc_sizes[i], 0, NULL, NULL, NULL, NULL, NULL, 0);
}
size = RTL_MEMALIGN;
for (i = 0; i < n; i++)
{
while (size <= g_alloc_sizes[i])
{
g_alloc_table[(size - 1) >> RTL_MEMALIGN_SHIFT] = g_alloc_caches[i];
size += RTL_MEMALIGN;
}
}
}
#endif
// SAL_INFO("sal", "rtl_memory_init completed");
}
/* ================================================================= */
void rtl_memory_fini()
{
#if !defined(FORCE_SYSALLOC)
int i, n;
/* clear g_alloc_table */
memset (g_alloc_table, 0, sizeof(g_alloc_table));
/* cleanup g_alloc_caches */
for (i = 0, n = RTL_MEMORY_CACHED_SIZES; i < n; i++)
{
if (g_alloc_caches[i] != 0)
{
rtl_cache_destroy (g_alloc_caches[i]);
g_alloc_caches[i] = 0;
}
}
/* cleanup gp_alloc_arena */
if (gp_alloc_arena != 0)
{
rtl_arena_destroy (gp_alloc_arena);
gp_alloc_arena = 0;
}
#endif
// SAL_INFO("sal", "rtl_memory_fini completed");
}
/* ================================================================= *
*
* system allocator implemenation.
*
* ================================================================= */
void * SAL_CALL rtl_allocateMemory_SYSTEM (sal_Size n)
{
return malloc (n);
}
/* ================================================================= */
void SAL_CALL rtl_freeMemory_SYSTEM (void * p)
{
free (p);
}
/* ================================================================= */
void * SAL_CALL rtl_reallocateMemory_SYSTEM (void * p, sal_Size n)
{
return realloc (p, n);
}
/* ================================================================= */
void* SAL_CALL rtl_allocateMemory (sal_Size n) SAL_THROW_EXTERN_C()
{
#if !defined(FORCE_SYSALLOC)
while (1)
{
if (alloc_mode == AMode_CUSTOM)
{
return rtl_allocateMemory_CUSTOM(n);
}
if (alloc_mode == AMode_SYSTEM)
{
return rtl_allocateMemory_SYSTEM(n);
}
determine_alloc_mode();
}
#else
return rtl_allocateMemory_SYSTEM(n);
#endif
}
void* SAL_CALL rtl_reallocateMemory (void * p, sal_Size n) SAL_THROW_EXTERN_C()
{
#if !defined(FORCE_SYSALLOC)
while (1)
{
if (alloc_mode == AMode_CUSTOM)
{
return rtl_reallocateMemory_CUSTOM(p,n);
}
if (alloc_mode == AMode_SYSTEM)
{
return rtl_reallocateMemory_SYSTEM(p,n);
}
determine_alloc_mode();
}
#else
return rtl_reallocateMemory_SYSTEM(p,n);
#endif
}
void SAL_CALL rtl_freeMemory (void * p) SAL_THROW_EXTERN_C()
{
#if !defined(FORCE_SYSALLOC)
while (1)
{
if (alloc_mode == AMode_CUSTOM)
{
rtl_freeMemory_CUSTOM(p);
return;
}
if (alloc_mode == AMode_SYSTEM)
{
rtl_freeMemory_SYSTEM(p);
return;
}
determine_alloc_mode();
}
#else
rtl_freeMemory_SYSTEM(p);
#endif
}
/* ================================================================= *
*
* rtl_(allocate|free)ZeroMemory() implemenation.
*
* ================================================================= */
void * SAL_CALL rtl_allocateZeroMemory (sal_Size n) SAL_THROW_EXTERN_C()
{
void * p = rtl_allocateMemory (n);
if (p != 0)
memset (p, 0, n);
return (p);
}
/* ================================================================= */
void SAL_CALL rtl_freeZeroMemory (void * p, sal_Size n) SAL_THROW_EXTERN_C()
{
if (p != 0)
{
memset (p, 0, n);
rtl_freeMemory (p);
}
}
/* ================================================================= */
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>warn about massive allocs<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2000, 2010 Oracle and/or its affiliates.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "alloc_impl.hxx"
#include "rtl/alloc.h"
#include <sal/log.hxx>
#include <sal/macros.h>
#include <cassert>
#include <string.h>
#include <stdio.h>
#include "internal/rtllifecycle.h"
AllocMode alloc_mode = AMode_UNSET;
#if !defined(FORCE_SYSALLOC)
static void determine_alloc_mode()
{
assert(alloc_mode == AMode_UNSET);
alloc_mode = (getenv("G_SLICE") == NULL ? AMode_CUSTOM : AMode_SYSTEM);
}
/* ================================================================= *
*
* custom allocator includes.
*
* ================================================================= */
#include "sal/macros.h"
/* ================================================================= *
*
* custom allocator internals.
*
* ================================================================= */
static const sal_Size g_alloc_sizes[] =
{
/* powers of 2**(1/4) */
4 * 4, 6 * 4,
4 * 8, 5 * 8, 6 * 8, 7 * 8,
4 * 16, 5 * 16, 6 * 16, 7 * 16,
4 * 32, 5 * 32, 6 * 32, 7 * 32,
4 * 64, 5 * 64, 6 * 64, 7 * 64,
4 * 128, 5 * 128, 6 * 128, 7 * 128,
4 * 256, 5 * 256, 6 * 256, 7 * 256,
4 * 512, 5 * 512, 6 * 512, 7 * 512,
4 * 1024, 5 * 1024, 6 * 1024, 7 * 1024,
4 * 2048, 5 * 2048, 6 * 2048, 7 * 2048,
4 * 4096
};
#define RTL_MEMORY_CACHED_LIMIT 4 * 4096
#define RTL_MEMORY_CACHED_SIZES (SAL_N_ELEMENTS(g_alloc_sizes))
static rtl_cache_type * g_alloc_caches[RTL_MEMORY_CACHED_SIZES] =
{
0,
};
#define RTL_MEMALIGN 8
#define RTL_MEMALIGN_SHIFT 3
static rtl_cache_type * g_alloc_table[RTL_MEMORY_CACHED_LIMIT >> RTL_MEMALIGN_SHIFT] =
{
0,
};
static rtl_arena_type * gp_alloc_arena = 0;
/* ================================================================= *
*
* custom allocator implemenation.
*
* ================================================================= */
void *
SAL_CALL rtl_allocateMemory_CUSTOM (sal_Size n) SAL_THROW_EXTERN_C()
{
void * p = 0;
if (n > 0)
{
char * addr;
sal_Size size = RTL_MEMORY_ALIGN(n + RTL_MEMALIGN, RTL_MEMALIGN);
assert(RTL_MEMALIGN >= sizeof(sal_Size));
if (n >= SAL_MAX_SIZE - (RTL_MEMALIGN + RTL_MEMALIGN - 1))
{
/* requested size too large for roundup alignment */
return 0;
}
try_alloc:
if (size <= RTL_MEMORY_CACHED_LIMIT)
addr = (char*)rtl_cache_alloc(g_alloc_table[(size - 1) >> RTL_MEMALIGN_SHIFT]);
else
addr = (char*)rtl_arena_alloc (gp_alloc_arena, &size);
if (addr != 0)
{
((sal_Size*)(addr))[0] = size;
p = addr + RTL_MEMALIGN;
}
else if (gp_alloc_arena == 0)
{
ensureMemorySingleton();
if (gp_alloc_arena)
{
/* try again */
goto try_alloc;
}
}
}
return (p);
}
/* ================================================================= */
void SAL_CALL rtl_freeMemory_CUSTOM (void * p) SAL_THROW_EXTERN_C()
{
if (p != 0)
{
char * addr = (char*)(p) - RTL_MEMALIGN;
sal_Size size = ((sal_Size*)(addr))[0];
if (size <= RTL_MEMORY_CACHED_LIMIT)
rtl_cache_free(g_alloc_table[(size - 1) >> RTL_MEMALIGN_SHIFT], addr);
else
rtl_arena_free (gp_alloc_arena, addr, size);
}
}
/* ================================================================= */
void * SAL_CALL rtl_reallocateMemory_CUSTOM (void * p, sal_Size n) SAL_THROW_EXTERN_C()
{
if (n > 0)
{
if (p != 0)
{
void * p_old = p;
sal_Size n_old = ((sal_Size*)( (char*)(p) - RTL_MEMALIGN ))[0] - RTL_MEMALIGN;
p = rtl_allocateMemory (n);
if (p != 0)
{
memcpy (p, p_old, SAL_MIN(n, n_old));
rtl_freeMemory (p_old);
}
}
else
{
p = rtl_allocateMemory (n);
}
}
else if (p != 0)
{
rtl_freeMemory (p), p = 0;
}
return (p);
}
#endif
/* ================================================================= *
*
* custom allocator initialization / finalization.
*
* ================================================================= */
void rtl_memory_init()
{
#if !defined(FORCE_SYSALLOC)
{
/* global memory arena */
assert(gp_alloc_arena == 0);
gp_alloc_arena = rtl_arena_create (
"rtl_alloc_arena",
2048, /* quantum */
0, /* w/o quantum caching */
0, /* default source */
rtl_arena_alloc,
rtl_arena_free,
0 /* flags */
);
assert(gp_alloc_arena != 0);
}
{
sal_Size size;
int i, n = RTL_MEMORY_CACHED_SIZES;
for (i = 0; i < n; i++)
{
char name[RTL_CACHE_NAME_LENGTH + 1];
(void) snprintf (name, sizeof(name), "rtl_alloc_%lu", g_alloc_sizes[i]);
g_alloc_caches[i] = rtl_cache_create (name, g_alloc_sizes[i], 0, NULL, NULL, NULL, NULL, NULL, 0);
}
size = RTL_MEMALIGN;
for (i = 0; i < n; i++)
{
while (size <= g_alloc_sizes[i])
{
g_alloc_table[(size - 1) >> RTL_MEMALIGN_SHIFT] = g_alloc_caches[i];
size += RTL_MEMALIGN;
}
}
}
#endif
// SAL_INFO("sal", "rtl_memory_init completed");
}
/* ================================================================= */
void rtl_memory_fini()
{
#if !defined(FORCE_SYSALLOC)
int i, n;
/* clear g_alloc_table */
memset (g_alloc_table, 0, sizeof(g_alloc_table));
/* cleanup g_alloc_caches */
for (i = 0, n = RTL_MEMORY_CACHED_SIZES; i < n; i++)
{
if (g_alloc_caches[i] != 0)
{
rtl_cache_destroy (g_alloc_caches[i]);
g_alloc_caches[i] = 0;
}
}
/* cleanup gp_alloc_arena */
if (gp_alloc_arena != 0)
{
rtl_arena_destroy (gp_alloc_arena);
gp_alloc_arena = 0;
}
#endif
// SAL_INFO("sal", "rtl_memory_fini completed");
}
/* ================================================================= *
*
* system allocator implemenation.
*
* ================================================================= */
void * SAL_CALL rtl_allocateMemory_SYSTEM (sal_Size n)
{
return malloc (n);
}
/* ================================================================= */
void SAL_CALL rtl_freeMemory_SYSTEM (void * p)
{
free (p);
}
/* ================================================================= */
void * SAL_CALL rtl_reallocateMemory_SYSTEM (void * p, sal_Size n)
{
return realloc (p, n);
}
/* ================================================================= */
void* SAL_CALL rtl_allocateMemory (sal_Size n) SAL_THROW_EXTERN_C()
{
SAL_WARN_IF(
n >= SAL_MAX_INT32, "sal",
"suspicious massive alloc " << n);
#if !defined(FORCE_SYSALLOC)
while (1)
{
if (alloc_mode == AMode_CUSTOM)
{
return rtl_allocateMemory_CUSTOM(n);
}
if (alloc_mode == AMode_SYSTEM)
{
return rtl_allocateMemory_SYSTEM(n);
}
determine_alloc_mode();
}
#else
return rtl_allocateMemory_SYSTEM(n);
#endif
}
void* SAL_CALL rtl_reallocateMemory (void * p, sal_Size n) SAL_THROW_EXTERN_C()
{
SAL_WARN_IF(
n >= SAL_MAX_INT32, "sal",
"suspicious massive alloc " << n);
#if !defined(FORCE_SYSALLOC)
while (1)
{
if (alloc_mode == AMode_CUSTOM)
{
return rtl_reallocateMemory_CUSTOM(p,n);
}
if (alloc_mode == AMode_SYSTEM)
{
return rtl_reallocateMemory_SYSTEM(p,n);
}
determine_alloc_mode();
}
#else
return rtl_reallocateMemory_SYSTEM(p,n);
#endif
}
void SAL_CALL rtl_freeMemory (void * p) SAL_THROW_EXTERN_C()
{
#if !defined(FORCE_SYSALLOC)
while (1)
{
if (alloc_mode == AMode_CUSTOM)
{
rtl_freeMemory_CUSTOM(p);
return;
}
if (alloc_mode == AMode_SYSTEM)
{
rtl_freeMemory_SYSTEM(p);
return;
}
determine_alloc_mode();
}
#else
rtl_freeMemory_SYSTEM(p);
#endif
}
/* ================================================================= *
*
* rtl_(allocate|free)ZeroMemory() implemenation.
*
* ================================================================= */
void * SAL_CALL rtl_allocateZeroMemory (sal_Size n) SAL_THROW_EXTERN_C()
{
void * p = rtl_allocateMemory (n);
if (p != 0)
memset (p, 0, n);
return (p);
}
/* ================================================================= */
void SAL_CALL rtl_freeZeroMemory (void * p, sal_Size n) SAL_THROW_EXTERN_C()
{
if (p != 0)
{
memset (p, 0, n);
rtl_freeMemory (p);
}
}
/* ================================================================= */
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|>
|
<commit_before>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W, N;
ll f;
int sx, sy, gx, gy;
int a[70010];
int b[70010];
char c[70010];
int d[70010];
ll e[70010];
typedef tuple<ll, int> pass;
vector<pass> V[100010];
int main () {
cin >> H >> W >> N >> f;
cin >> sx >> sy >> gx >> gy;
sx--; sy--; gx--; gy--;
for (auto i = 0; i < N; ++i) {
cin >> a[i] >> b[i] >> c[i] >> d[i] >> e[i];
a[i]--; b[i]--;
if (c[i] == 'W') d[i] = -1 * d[i];
}
assert(H == 1);
for (auto i = 0; i < W-1; ++i) {
V[i].push_back(pass(f, i+1));
V[i+1].push_back(pass(f, i));
}
for (auto i = 0; i < N; ++i) {
V[a[i]].push_back(pass(0, b[i]+d[i]));
int gyaku = a[i]-d[i];
if (0 <= gyaku && gyaku < W) {
V[a[i]].push_back(pass(e[i], gyaku));
}
}
priority_queue<pass, vector<pass>, greater<pass> > Q;
Q.push(pass(0, sy));
int visited[100010];
fill(visited, visited+100010, -1);
while (!Q.empty()) {
ll cost = get<0>(Q.top());
int now = get<1>(Q.top());
Q.pop();
if (visited[now] == -1) {
visited[now] = cost;
if (now == gy) {
cout << cost << endl;
return 0;
}
for (auto x : V[now]) {
ll newcost = cost + get<0>(x);
int dst = get<1>(x);
if (visited[dst] == -1) {
Q.push(pass(newcost, dst));
}
}
}
}
}
<commit_msg>submit F.cpp to 'F - Find the Route!' (s8pc-4) [C++14 (GCC 5.4.1)]<commit_after>#include <iostream>
#include <iomanip> // << fixed << setprecision(xxx)
#include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ;
#include <vector>
#include <string> // to_string(nnn) // substr(m, n) // stoi(nnn)
#include <complex>
#include <tuple> // get<n>(xxx)
#include <queue>
#include <stack>
#include <map> // if (M.find(key) != M.end()) { }
#include <set> // S.insert(M);
// if (S.find(key) != S.end()) { }
// for (auto it=S.begin(); it != S.end(); it++) { }
// auto it = S.lower_bound(M);
#include <random> // random_device rd; mt19937 mt(rd());
#include <cctype>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstdlib> // atoi(xxx)
using namespace std;
#define DEBUG 0 // change 0 -> 1 if we need debug.
// insert #if<tab> by my emacs. #if DEBUG == 1 ... #end
typedef long long ll;
// const int dx[4] = {1, 0, -1, 0};
// const int dy[4] = {0, 1, 0, -1};
// const int C = 1e6+10;
// const ll M = 1000000007;
int H, W, N;
ll f;
int sx, sy, gx, gy;
int a[70010];
int b[70010];
char c[70010];
int d[70010];
ll e[70010];
typedef tuple<ll, int> pass;
vector<pass> V[100010];
int main () {
cin >> H >> W >> N >> f;
cin >> sx >> sy >> gx >> gy;
sx--; sy--; gx--; gy--;
for (auto i = 0; i < N; ++i) {
cin >> a[i] >> b[i] >> c[i] >> d[i] >> e[i];
a[i]--; b[i]--;
if (c[i] == 'E') d[i] = -1 * d[i];
}
assert(H == 1);
for (auto i = 0; i < W-1; ++i) {
V[i].push_back(pass(f, i+1));
V[i+1].push_back(pass(f, i));
}
for (auto i = 0; i < N; ++i) {
V[a[i]].push_back(pass(0, b[i]+d[i]));
int gyaku = a[i]-d[i];
if (0 <= gyaku && gyaku < W) {
V[a[i]].push_back(pass(e[i], gyaku));
}
}
priority_queue<pass, vector<pass>, greater<pass> > Q;
Q.push(pass(0, sy));
int visited[100010];
fill(visited, visited+100010, -1);
while (!Q.empty()) {
ll cost = get<0>(Q.top());
int now = get<1>(Q.top());
Q.pop();
if (visited[now] == -1) {
visited[now] = cost;
if (now == gy) {
cout << cost << endl;
return 0;
}
for (auto x : V[now]) {
ll newcost = cost + get<0>(x);
int dst = get<1>(x);
if (visited[dst] == -1) {
Q.push(pass(newcost, dst));
}
}
}
}
}
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2011, Ben Noordhuis <info@bnoordhuis.nl>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include "v8.h"
#include "node.h"
using namespace v8;
using namespace node;
namespace {
typedef struct proxy_container {
Persistent<Object> proxy;
Persistent<Object> target;
Persistent<Array> callbacks;
} proxy_container;
Persistent<ObjectTemplate> proxyClass;
bool IsDead(Handle<Object> proxy) {
assert(proxy->InternalFieldCount() == 1);
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
return cont == NULL || cont->target.IsEmpty();
}
Handle<Object> Unwrap(Handle<Object> proxy) {
assert(!IsDead(proxy));
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
return cont->target;
}
Handle<Array> GetCallbacks(Handle<Object> proxy) {
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
return cont->callbacks;
}
#define UNWRAP \
HandleScope scope; \
Handle<Object> obj; \
const bool dead = IsDead(info.This()); \
if (!dead) obj = Unwrap(info.This()); \
Handle<Value> WeakNamedPropertyGetter(Local<String> property,
const AccessorInfo& info) {
UNWRAP
return dead ? Local<Value>() : obj->Get(property);
}
Handle<Value> WeakNamedPropertySetter(Local<String> property,
Local<Value> value,
const AccessorInfo& info) {
UNWRAP
if (!dead) obj->Set(property, value);
return value;
}
Handle<Integer> WeakNamedPropertyQuery(Local<String> property,
const AccessorInfo& info) {
return HandleScope().Close(Integer::New(None));
}
Handle<Boolean> WeakNamedPropertyDeleter(Local<String> property,
const AccessorInfo& info) {
UNWRAP
return Boolean::New(!dead && obj->Delete(property));
}
Handle<Value> WeakIndexedPropertyGetter(uint32_t index,
const AccessorInfo& info) {
UNWRAP
return dead ? Local<Value>() : obj->Get(index);
}
Handle<Value> WeakIndexedPropertySetter(uint32_t index,
Local<Value> value,
const AccessorInfo& info) {
UNWRAP
if (!dead) obj->Set(index, value);
return value;
}
Handle<Integer> WeakIndexedPropertyQuery(uint32_t index,
const AccessorInfo& info) {
return HandleScope().Close(Integer::New(None));
}
Handle<Boolean> WeakIndexedPropertyDeleter(uint32_t index,
const AccessorInfo& info) {
UNWRAP
return Boolean::New(!dead && obj->Delete(index));
}
Handle<Array> WeakPropertyEnumerator(const AccessorInfo& info) {
UNWRAP
return HandleScope().Close(dead ? Array::New(0) : obj->GetPropertyNames());
}
void AddCallback(Handle<Object> proxy, Handle<Function> callback) {
Handle<Array> callbacks = GetCallbacks(proxy);
callbacks->Set(Integer::New(callbacks->Length()), callback);
}
void TargetCallback(Persistent<Value> target, void* arg) {
HandleScope scope;
assert(target.IsNearDeath());
proxy_container *cont = reinterpret_cast<proxy_container*>(arg);
// invoke any listening callbacks
uint32_t len = cont->callbacks->Length();
Handle<Value> argv[1];
argv[0] = target;
for (uint32_t i=0; i<len; i++) {
Handle<Function> cb = Handle<Function>::Cast(
cont->callbacks->Get(Integer::New(i)));
TryCatch try_catch;
cb->Call(target->ToObject(), 1, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
}
cont->proxy->SetPointerInInternalField(0, NULL);
cont->proxy.Dispose();
cont->proxy.Clear();
cont->target.Dispose();
cont->target.Clear();
cont->callbacks.Dispose();
cont->callbacks.Clear();
free(cont);
}
Handle<Value> Create(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()) {
Local<String> message = String::New("Object expected");
return ThrowException(Exception::TypeError(message));
}
proxy_container *cont = (proxy_container *)
malloc(sizeof(proxy_container));
cont->target = Persistent<Object>::New(args[0]->ToObject());
cont->callbacks = Persistent<Array>::New(Array::New());
cont->proxy = Persistent<Object>::New(proxyClass->NewInstance());
cont->proxy->SetPointerInInternalField(0, cont);
cont->target.MakeWeak(cont, TargetCallback);
if (args.Length() >= 2) {
AddCallback(cont->proxy, Handle<Function>::Cast(args[1]));
}
return cont->proxy;
}
/**
* TODO: Make this better.
*/
bool isWeakRef (Handle<Value> val) {
return val->IsObject() && val->ToObject()->InternalFieldCount() == 1;
}
Handle<Value> IsWeakRef (const Arguments& args) {
HandleScope scope;
return Boolean::New(isWeakRef(args[0]));
}
Handle<Value> Get(const Arguments& args) {
HandleScope scope;
if (!isWeakRef(args[0])) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
const bool dead = IsDead(proxy);
if (dead) return Undefined();
Handle<Object> obj = Unwrap(proxy);
return scope.Close(obj);
}
Handle<Value> IsNearDeath(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
Handle<Boolean> rtn = Boolean::New(cont->target.IsNearDeath());
return scope.Close(rtn);
}
Handle<Value> IsDead(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
const bool dead = IsDead(proxy);
return Boolean::New(dead);
}
Handle<Value> AddCallback(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
AddCallback(proxy, Handle<Function>::Cast(args[1]));
return Undefined();
}
Handle<Value> Callbacks(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()
|| args[0]->ToObject()->InternalFieldCount() != 1) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
assert(proxy->InternalFieldCount() == 1);
return scope.Close(GetCallbacks(proxy));
}
void Initialize(Handle<Object> target) {
HandleScope scope;
proxyClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
proxyClass->SetNamedPropertyHandler(WeakNamedPropertyGetter,
WeakNamedPropertySetter,
WeakNamedPropertyQuery,
WeakNamedPropertyDeleter,
WeakPropertyEnumerator);
proxyClass->SetIndexedPropertyHandler(WeakIndexedPropertyGetter,
WeakIndexedPropertySetter,
WeakIndexedPropertyQuery,
WeakIndexedPropertyDeleter,
WeakPropertyEnumerator);
proxyClass->SetInternalFieldCount(1);
NODE_SET_METHOD(target, "get", Get);
NODE_SET_METHOD(target, "create", Create);
NODE_SET_METHOD(target, "isWeakRef", IsWeakRef);
NODE_SET_METHOD(target, "isNearDeath", IsNearDeath);
NODE_SET_METHOD(target, "isDead", IsDead);
NODE_SET_METHOD(target, "callbacks", Callbacks);
NODE_SET_METHOD(target, "addCallback", AddCallback);
}
} // anonymous namespace
NODE_MODULE(weakref, Initialize);
<commit_msg>Use isWeakRef() internally.<commit_after>/*
* Copyright (c) 2011, Ben Noordhuis <info@bnoordhuis.nl>
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <stdlib.h>
#include "v8.h"
#include "node.h"
using namespace v8;
using namespace node;
namespace {
typedef struct proxy_container {
Persistent<Object> proxy;
Persistent<Object> target;
Persistent<Array> callbacks;
} proxy_container;
Persistent<ObjectTemplate> proxyClass;
bool IsDead(Handle<Object> proxy) {
assert(proxy->InternalFieldCount() == 1);
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
return cont == NULL || cont->target.IsEmpty();
}
Handle<Object> Unwrap(Handle<Object> proxy) {
assert(!IsDead(proxy));
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
return cont->target;
}
Handle<Array> GetCallbacks(Handle<Object> proxy) {
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
return cont->callbacks;
}
#define UNWRAP \
HandleScope scope; \
Handle<Object> obj; \
const bool dead = IsDead(info.This()); \
if (!dead) obj = Unwrap(info.This()); \
Handle<Value> WeakNamedPropertyGetter(Local<String> property,
const AccessorInfo& info) {
UNWRAP
return dead ? Local<Value>() : obj->Get(property);
}
Handle<Value> WeakNamedPropertySetter(Local<String> property,
Local<Value> value,
const AccessorInfo& info) {
UNWRAP
if (!dead) obj->Set(property, value);
return value;
}
Handle<Integer> WeakNamedPropertyQuery(Local<String> property,
const AccessorInfo& info) {
return HandleScope().Close(Integer::New(None));
}
Handle<Boolean> WeakNamedPropertyDeleter(Local<String> property,
const AccessorInfo& info) {
UNWRAP
return Boolean::New(!dead && obj->Delete(property));
}
Handle<Value> WeakIndexedPropertyGetter(uint32_t index,
const AccessorInfo& info) {
UNWRAP
return dead ? Local<Value>() : obj->Get(index);
}
Handle<Value> WeakIndexedPropertySetter(uint32_t index,
Local<Value> value,
const AccessorInfo& info) {
UNWRAP
if (!dead) obj->Set(index, value);
return value;
}
Handle<Integer> WeakIndexedPropertyQuery(uint32_t index,
const AccessorInfo& info) {
return HandleScope().Close(Integer::New(None));
}
Handle<Boolean> WeakIndexedPropertyDeleter(uint32_t index,
const AccessorInfo& info) {
UNWRAP
return Boolean::New(!dead && obj->Delete(index));
}
Handle<Array> WeakPropertyEnumerator(const AccessorInfo& info) {
UNWRAP
return HandleScope().Close(dead ? Array::New(0) : obj->GetPropertyNames());
}
void AddCallback(Handle<Object> proxy, Handle<Function> callback) {
Handle<Array> callbacks = GetCallbacks(proxy);
callbacks->Set(Integer::New(callbacks->Length()), callback);
}
void TargetCallback(Persistent<Value> target, void* arg) {
HandleScope scope;
assert(target.IsNearDeath());
proxy_container *cont = reinterpret_cast<proxy_container*>(arg);
// invoke any listening callbacks
uint32_t len = cont->callbacks->Length();
Handle<Value> argv[1];
argv[0] = target;
for (uint32_t i=0; i<len; i++) {
Handle<Function> cb = Handle<Function>::Cast(
cont->callbacks->Get(Integer::New(i)));
TryCatch try_catch;
cb->Call(target->ToObject(), 1, argv);
if (try_catch.HasCaught()) {
FatalException(try_catch);
}
}
cont->proxy->SetPointerInInternalField(0, NULL);
cont->proxy.Dispose();
cont->proxy.Clear();
cont->target.Dispose();
cont->target.Clear();
cont->callbacks.Dispose();
cont->callbacks.Clear();
free(cont);
}
Handle<Value> Create(const Arguments& args) {
HandleScope scope;
if (!args[0]->IsObject()) {
Local<String> message = String::New("Object expected");
return ThrowException(Exception::TypeError(message));
}
proxy_container *cont = (proxy_container *)
malloc(sizeof(proxy_container));
cont->target = Persistent<Object>::New(args[0]->ToObject());
cont->callbacks = Persistent<Array>::New(Array::New());
cont->proxy = Persistent<Object>::New(proxyClass->NewInstance());
cont->proxy->SetPointerInInternalField(0, cont);
cont->target.MakeWeak(cont, TargetCallback);
if (args.Length() >= 2) {
AddCallback(cont->proxy, Handle<Function>::Cast(args[1]));
}
return cont->proxy;
}
/**
* TODO: Make this better.
*/
bool isWeakRef (Handle<Value> val) {
return val->IsObject() && val->ToObject()->InternalFieldCount() == 1;
}
Handle<Value> IsWeakRef (const Arguments& args) {
HandleScope scope;
return Boolean::New(isWeakRef(args[0]));
}
Handle<Value> Get(const Arguments& args) {
HandleScope scope;
if (!isWeakRef(args[0])) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
const bool dead = IsDead(proxy);
if (dead) return Undefined();
Handle<Object> obj = Unwrap(proxy);
return scope.Close(obj);
}
Handle<Value> IsNearDeath(const Arguments& args) {
HandleScope scope;
if (!isWeakRef(args[0])) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
proxy_container *cont = reinterpret_cast<proxy_container*>(
proxy->GetPointerFromInternalField(0));
assert(cont != NULL);
Handle<Boolean> rtn = Boolean::New(cont->target.IsNearDeath());
return scope.Close(rtn);
}
Handle<Value> IsDead(const Arguments& args) {
HandleScope scope;
if (!isWeakRef(args[0])) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
const bool dead = IsDead(proxy);
return Boolean::New(dead);
}
Handle<Value> AddCallback(const Arguments& args) {
HandleScope scope;
if (!isWeakRef(args[0])) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
AddCallback(proxy, Handle<Function>::Cast(args[1]));
return Undefined();
}
Handle<Value> Callbacks(const Arguments& args) {
HandleScope scope;
if (!isWeakRef(args[0])) {
Local<String> message = String::New("Weakref instance expected");
return ThrowException(Exception::TypeError(message));
}
Local<Object> proxy = args[0]->ToObject();
return scope.Close(GetCallbacks(proxy));
}
void Initialize(Handle<Object> target) {
HandleScope scope;
proxyClass = Persistent<ObjectTemplate>::New(ObjectTemplate::New());
proxyClass->SetNamedPropertyHandler(WeakNamedPropertyGetter,
WeakNamedPropertySetter,
WeakNamedPropertyQuery,
WeakNamedPropertyDeleter,
WeakPropertyEnumerator);
proxyClass->SetIndexedPropertyHandler(WeakIndexedPropertyGetter,
WeakIndexedPropertySetter,
WeakIndexedPropertyQuery,
WeakIndexedPropertyDeleter,
WeakPropertyEnumerator);
proxyClass->SetInternalFieldCount(1);
NODE_SET_METHOD(target, "get", Get);
NODE_SET_METHOD(target, "create", Create);
NODE_SET_METHOD(target, "isWeakRef", IsWeakRef);
NODE_SET_METHOD(target, "isNearDeath", IsNearDeath);
NODE_SET_METHOD(target, "isDead", IsDead);
NODE_SET_METHOD(target, "callbacks", Callbacks);
NODE_SET_METHOD(target, "addCallback", AddCallback);
}
} // anonymous namespace
NODE_MODULE(weakref, Initialize);
<|endoftext|>
|
<commit_before>/**
* ros_control node for commanding K.H.A.N. via Python
* \author: Jason Ziglar <jpz@vt.edu>
* \date: 10/28/2015
*/
#include "khan_control/KHANHWInterface.h"
#include <ros/ros.h>
#include <controller_manager/controller_manager.h>
controller_manager::ControllerManager* CM = NULL;
khan::KHANHWInterface* HWInterface = NULL;
void updateHW(const ros::TimerEvent& event)
{
CM->update(event.current_real, event.current_real - event.last_real);
HWInterface->write(event.current_real, event.current_real - event.last_real);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "KHANPythonControl");
ros::NodeHandle nhp("~");
std::string robot_ns;
double period;
nhp.param("robot_namespace", robot_ns, std::string(""));
nhp.param("period", period, 1.0 / 50.0);
//Ensure the namespace is valid
if(!robot_ns.empty() && robot_ns[robot_ns.length() - 1] != '/')
{
robot_ns = robot_ns + "/";
}
HWInterface = new khan::KHANHWInterface(robot_ns);
CM = new controller_manager::ControllerManager(HWInterface);
ros::Timer timer = nhp.createTimer(ros::Duration(period), updateHW);
ros::spin();
}<commit_msg>Adding multi-threaded spinner to the hardware interface.<commit_after>/**
* ros_control node for commanding K.H.A.N. via Python
* \author: Jason Ziglar <jpz@vt.edu>
* \date: 10/28/2015
*/
#include "khan_control/KHANHWInterface.h"
#include <ros/ros.h>
#include <controller_manager/controller_manager.h>
controller_manager::ControllerManager* CM = NULL;
khan::KHANHWInterface* HWInterface = NULL;
void updateHW(const ros::TimerEvent& event)
{
CM->update(event.current_real, event.current_real - event.last_real);
HWInterface->write(event.current_real, event.current_real - event.last_real);
}
int main(int argc, char** argv)
{
ros::init(argc, argv, "KHANPythonControl");
ros::NodeHandle nhp("~");
std::string robot_ns;
double period;
nhp.param("robot_namespace", robot_ns, std::string(""));
nhp.param("period", period, 1.0 / 50.0);
//Ensure the namespace is valid
if(!robot_ns.empty() && robot_ns[robot_ns.length() - 1] != '/')
{
robot_ns = robot_ns + "/";
}
HWInterface = new khan::KHANHWInterface(robot_ns);
CM = new controller_manager::ControllerManager(HWInterface);
ros::Timer timer = nhp.createTimer(ros::Duration(period), updateHW);
ros::MultiThreadedSpinner spinner(2);
spinner.spin();
return 0;
}<|endoftext|>
|
<commit_before>/*
* IceWM
*
* Copyright (C) 1997-2003 Marko Macek
*
* Dialogs
*/
#include "config.h"
#include "ylib.h"
#include "wmabout.h"
#include "yprefs.h"
#include "prefs.h"
#include "wmapp.h"
#include "wmframe.h"
#include "sysdep.h"
#include "WinMgr.h"
#include "intl.h"
AboutDlg::AboutDlg(): YDialog() {
char const *version("IceWM " VERSION " (" HOSTOS "/" HOSTCPU ")");
ustring copyright =
ustring("Copyright ")
.append(_("(C)"))
.append(" 1997-2008 Marko Macek, ")
.append(_("(C)"))
.append(" 2001 Mathias Hasselmann");
fProgTitle = new YLabel(version, this);
fCopyright = new YLabel(copyright, this);
fThemeNameS = new YLabel(_("Theme:"), this);
fThemeDescriptionS = new YLabel(_("Theme Description:"), this);
fThemeAuthorS = new YLabel(_("Theme Author:"), this);
fThemeName = new YLabel(themeName, this);
fThemeDescription = new YLabel(themeDescription, this);
fThemeAuthor = new YLabel(themeAuthor, this);
fCodeSetS = new YLabel(_("CodeSet:"), this);
fLanguageS = new YLabel(_("Language:"), this);
const char *codeset = "";
const char *language = "";
#ifdef CONFIG_I18N
codeset = nl_langinfo(CODESET);
language = getenv("LANG");
#endif
fCodeSet = new YLabel(codeset, this);
fLanguage = new YLabel(language, this);
autoSize();
fProgTitle->show();
fCopyright->show();
fThemeNameS->show();
fThemeName->show();
fThemeDescriptionS->show();
fThemeDescription->show();
fThemeAuthorS->show();
fThemeAuthor->show();
fCodeSetS->show();
fCodeSet->show();
fLanguageS->show();
fLanguage->show();
setWindowTitle(_("icewm - About"));
//setIconTitle("icewm - About");
setWinLayerHint(WinLayerAboveDock);
setWinWorkspaceHint(-1);
setWinHintsHint(WinHintsSkipWindowMenu);
setMwmHints(MwmHints(
MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS,
MWM_FUNC_MOVE | MWM_FUNC_CLOSE,
MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MENU,
0,
0));
}
AboutDlg::~AboutDlg() {
delete fProgTitle;
delete fCopyright;
delete fThemeName;
delete fThemeDescription;
delete fThemeAuthor;
delete fThemeNameS;
delete fThemeDescriptionS;
delete fThemeAuthorS;
delete fCodeSetS;
delete fCodeSet;
delete fLanguageS;
delete fLanguage;
}
#define RX(w) (int((w)->x() + (w)->width()))
#define XMAX(x,nx) ((nx) > (x) ? (nx) : (x))
void AboutDlg::autoSize() {
int dx = 20, dx1 = 20;
int dy = 20;
int W = 0, H;
int cy;
fProgTitle->setPosition(dx, dy); dy += fProgTitle->height();
W = XMAX(W, RX(fProgTitle));
dy += 4;
fCopyright->setPosition(dx, dy); dy += fCopyright->height();
W = XMAX(W, RX(fCopyright));
dy += 20;
fThemeNameS->setPosition(dx, dy);
fThemeDescriptionS->setPosition(dx, dy);
fThemeAuthorS->setPosition(dx, dy);
fCodeSetS->setPosition(dx, dy);
fLanguageS->setPosition(dx, dy);
dx = XMAX(dx, RX(fThemeNameS));
dx = XMAX(dx, RX(fThemeDescriptionS));
dx = XMAX(dx, RX(fThemeAuthorS));
dx = XMAX(dx, RX(fCodeSetS));
dx = XMAX(dx, RX(fLanguageS));
dx += 20;
fThemeNameS->setPosition(dx1, dy);
cy = fThemeNameS->height();
W = XMAX(W, RX(fThemeName));
fThemeName->setPosition(dx, dy);
cy = XMAX(cy, int(fThemeName->height()));
W = XMAX(W, RX(fThemeName));
dy += cy;
dy += 4;
fThemeDescriptionS->setPosition(dx1, dy);
cy = fThemeDescriptionS->height();
W = XMAX(W, RX(fThemeDescriptionS));
fThemeDescription->setPosition(dx, dy);
cy = XMAX(cy, int(fThemeDescription->height()));
W = XMAX(W, RX(fThemeDescription));
dy += cy;
dy += 4;
fThemeAuthorS->setPosition(dx1, dy);
cy = fThemeAuthorS->height();
W = XMAX(W, RX(fThemeAuthorS));
fThemeAuthor->setPosition(dx, dy);
cy = XMAX(cy, int(fThemeAuthor->height()));
W = XMAX(W, RX(fThemeAuthor));
dy += cy;
dy += 20;
fCodeSetS->setPosition(dx1, dy);
cy = fCodeSetS->height();
W = XMAX(W, RX(fCodeSetS));
fCodeSet->setPosition(dx, dy);
cy = XMAX(cy, int(fCodeSet->height()));
W = XMAX(W, RX(fCodeSet));
dy += cy;
dy += 4;
fLanguageS->setPosition(dx1, dy);
cy = fLanguageS->height();
W = XMAX(W, RX(fLanguageS));
fLanguage->setPosition(dx, dy);
cy = XMAX(cy, int(fLanguage->height()));
W = XMAX(W, RX(fLanguage));
dy += cy;
H = dy + 20;
W += 20;
setSize(W, H);
}
void AboutDlg::showFocused() {
int dx, dy;
unsigned dw, dh;
manager->getScreenGeometry(&dx, &dy, &dw, &dh);
if (getFrame() == 0)
manager->manageClient(handle(), false);
if (getFrame() != 0) {
getFrame()->setNormalPositionOuter(
dx + dw / 2 - getFrame()->width() / 2,
dy + dh / 2 - getFrame()->height() / 2);
getFrame()->activateWindow(true);
}
}
void AboutDlg::handleClose() {
if (!getFrame()->isHidden())
getFrame()->wmHide();
}
// vim: set sw=4 ts=4 et:
<commit_msg>Set About title + class.<commit_after>/*
* IceWM
*
* Copyright (C) 1997-2003 Marko Macek
*
* Dialogs
*/
#include "config.h"
#include "ylib.h"
#include "wmabout.h"
#include "yprefs.h"
#include "prefs.h"
#include "wmapp.h"
#include "wmframe.h"
#include "sysdep.h"
#include "WinMgr.h"
#include "intl.h"
AboutDlg::AboutDlg(): YDialog() {
char const *version("IceWM " VERSION " (" HOSTOS "/" HOSTCPU ")");
ustring copyright =
ustring("Copyright ")
.append(_("(C)"))
.append(" 1997-2008 Marko Macek, ")
.append(_("(C)"))
.append(" 2001 Mathias Hasselmann");
fProgTitle = new YLabel(version, this);
fCopyright = new YLabel(copyright, this);
fThemeNameS = new YLabel(_("Theme:"), this);
fThemeDescriptionS = new YLabel(_("Theme Description:"), this);
fThemeAuthorS = new YLabel(_("Theme Author:"), this);
fThemeName = new YLabel(themeName, this);
fThemeDescription = new YLabel(themeDescription, this);
fThemeAuthor = new YLabel(themeAuthor, this);
fCodeSetS = new YLabel(_("CodeSet:"), this);
fLanguageS = new YLabel(_("Language:"), this);
const char *codeset = "";
const char *language = "";
#ifdef CONFIG_I18N
codeset = nl_langinfo(CODESET);
language = getenv("LANG");
#endif
fCodeSet = new YLabel(codeset, this);
fLanguage = new YLabel(language, this);
autoSize();
fProgTitle->show();
fCopyright->show();
fThemeNameS->show();
fThemeName->show();
fThemeDescriptionS->show();
fThemeDescription->show();
fThemeAuthorS->show();
fThemeAuthor->show();
fCodeSetS->show();
fCodeSet->show();
fLanguageS->show();
fLanguage->show();
setTitle("About");
setWindowTitle(_("icewm - About"));
//setIconTitle("icewm - About");
setClassHint("about", "IceWM");
setWinLayerHint(WinLayerAboveDock);
setWinWorkspaceHint(-1);
setWinHintsHint(WinHintsSkipWindowMenu);
setMwmHints(MwmHints(
MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS,
MWM_FUNC_MOVE | MWM_FUNC_CLOSE,
MWM_DECOR_BORDER | MWM_DECOR_TITLE | MWM_DECOR_MENU,
0,
0));
}
AboutDlg::~AboutDlg() {
delete fProgTitle;
delete fCopyright;
delete fThemeName;
delete fThemeDescription;
delete fThemeAuthor;
delete fThemeNameS;
delete fThemeDescriptionS;
delete fThemeAuthorS;
delete fCodeSetS;
delete fCodeSet;
delete fLanguageS;
delete fLanguage;
}
#define RX(w) (int((w)->x() + (w)->width()))
#define XMAX(x,nx) ((nx) > (x) ? (nx) : (x))
void AboutDlg::autoSize() {
int dx = 20, dx1 = 20;
int dy = 20;
int W = 0, H;
int cy;
fProgTitle->setPosition(dx, dy); dy += fProgTitle->height();
W = XMAX(W, RX(fProgTitle));
dy += 4;
fCopyright->setPosition(dx, dy); dy += fCopyright->height();
W = XMAX(W, RX(fCopyright));
dy += 20;
fThemeNameS->setPosition(dx, dy);
fThemeDescriptionS->setPosition(dx, dy);
fThemeAuthorS->setPosition(dx, dy);
fCodeSetS->setPosition(dx, dy);
fLanguageS->setPosition(dx, dy);
dx = XMAX(dx, RX(fThemeNameS));
dx = XMAX(dx, RX(fThemeDescriptionS));
dx = XMAX(dx, RX(fThemeAuthorS));
dx = XMAX(dx, RX(fCodeSetS));
dx = XMAX(dx, RX(fLanguageS));
dx += 20;
fThemeNameS->setPosition(dx1, dy);
cy = fThemeNameS->height();
W = XMAX(W, RX(fThemeName));
fThemeName->setPosition(dx, dy);
cy = XMAX(cy, int(fThemeName->height()));
W = XMAX(W, RX(fThemeName));
dy += cy;
dy += 4;
fThemeDescriptionS->setPosition(dx1, dy);
cy = fThemeDescriptionS->height();
W = XMAX(W, RX(fThemeDescriptionS));
fThemeDescription->setPosition(dx, dy);
cy = XMAX(cy, int(fThemeDescription->height()));
W = XMAX(W, RX(fThemeDescription));
dy += cy;
dy += 4;
fThemeAuthorS->setPosition(dx1, dy);
cy = fThemeAuthorS->height();
W = XMAX(W, RX(fThemeAuthorS));
fThemeAuthor->setPosition(dx, dy);
cy = XMAX(cy, int(fThemeAuthor->height()));
W = XMAX(W, RX(fThemeAuthor));
dy += cy;
dy += 20;
fCodeSetS->setPosition(dx1, dy);
cy = fCodeSetS->height();
W = XMAX(W, RX(fCodeSetS));
fCodeSet->setPosition(dx, dy);
cy = XMAX(cy, int(fCodeSet->height()));
W = XMAX(W, RX(fCodeSet));
dy += cy;
dy += 4;
fLanguageS->setPosition(dx1, dy);
cy = fLanguageS->height();
W = XMAX(W, RX(fLanguageS));
fLanguage->setPosition(dx, dy);
cy = XMAX(cy, int(fLanguage->height()));
W = XMAX(W, RX(fLanguage));
dy += cy;
H = dy + 20;
W += 20;
setSize(W, H);
}
void AboutDlg::showFocused() {
int dx, dy;
unsigned dw, dh;
manager->getScreenGeometry(&dx, &dy, &dw, &dh);
if (getFrame() == 0)
manager->manageClient(handle(), false);
if (getFrame() != 0) {
getFrame()->setNormalPositionOuter(
dx + dw / 2 - getFrame()->width() / 2,
dy + dh / 2 - getFrame()->height() / 2);
getFrame()->activateWindow(true);
}
}
void AboutDlg::handleClose() {
if (!getFrame()->isHidden())
getFrame()->wmHide();
}
// vim: set sw=4 ts=4 et:
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include "wishes.hpp"
#include "objectives.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "fortune.hpp"
#include "accounts.hpp"
#include "args.hpp"
#include "data.hpp"
#include "guid.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "console.hpp"
#include "budget_exception.hpp"
#include "compute.hpp"
using namespace budget;
namespace {
static data_handler<wish> wishes;
void list_wishes(){
if(wishes.data.size() == 0){
std::cout << "No wishes" << std::endl;
} else {
std::vector<std::string> columns = {"ID", "Name", "Amount", "Paid"};
std::vector<std::vector<std::string>> contents;
money total;
money unpaid_total;
for(auto& wish : wishes.data){
contents.push_back({to_string(wish.id), wish.name, to_string(wish.amount), wish.paid ? to_string(wish.paid_amount) : "No"});
total += wish.amount;
if(!wish.paid){
unpaid_total += wish.amount;
}
}
contents.push_back({"", "", "", ""});
contents.push_back({"", "Total", to_string(total), ""});
contents.push_back({"", "Unpaid Total", to_string(unpaid_total), ""});
display_table(columns, contents);
}
}
void status_wishes(){
std::cout << "Wishes" << std::endl << std::endl;
size_t width = 0;
for(auto& wish : wishes.data){
if(wish.paid){
continue;
}
width = std::max(rsize(wish.name), width);
}
auto today = boost::gregorian::day_clock::local_day();
auto month_status = budget::compute_month_status(today.year(), today.month());
auto year_status = budget::compute_year_status(today.year(), today.month());
auto fortune_amount = budget::current_fortune();
for(auto& wish : wishes.data){
if(wish.paid){
continue;
}
auto amount = wish.amount;
std::cout << " ";
print_minimum(wish.name, width);
std::cout << " ";
size_t monthly_breaks = 0;
size_t yearly_breaks = 0;
bool month_objective = true;
bool year_objective = true;
for(auto& objective : all_objectives()){
if(objective.type == "monthly"){
auto success_before = budget::compute_success(month_status, objective);
auto success_after = budget::compute_success(month_status.add_expense(amount), objective);
if(success_before >= 100 && success_after < 100){
++monthly_breaks;
}
if(success_after < 100){
month_objective = false;
}
} else if(objective.type == "yearly"){
auto success_before = budget::compute_success(year_status, objective);
auto success_after = budget::compute_success(year_status.add_expense(amount), objective);
if(success_before >= 100 && success_after < 100){
++yearly_breaks;
}
if(success_after < 100){
year_objective = false;
}
}
}
if(fortune_amount < wish.amount){
std::cout << "Impossible (not enough fortune)";
} else {
if(month_status.balance > wish.amount){
if(!all_objectives().empty()){
if(month_objective && year_objective){
std::cout << "Perfect (On month balance, all objectives fullfilled)";
} else if(month_objective){
std::cout << "Good (On month balance, month objectives fullfilled)";
} else if(yearly_breaks > 0 || monthly_breaks > 0){
std::cout << "OK (On month balance, " << (yearly_breaks + monthly_breaks) << " objectives broken)";
} else if(yearly_breaks == 0 && monthly_breaks == 0){
std::cout << "Warning (On month balance, objectives not fullfilled)";
}
} else {
std::cout << "OK (on month balance)";
}
} else if(year_status.balance > wish.amount){
if(!all_objectives().empty()){
if(month_objective && year_objective){
std::cout << "Perfect (On year balance, all objectives fullfilled)";
} else if(month_objective){
std::cout << "Good (On year balance, month objectives fullfilled)";
} else if(yearly_breaks > 0 || monthly_breaks > 0){
std::cout << "OK (On year balance, " << (yearly_breaks + monthly_breaks) << " objectives broken)";
} else if(yearly_breaks == 0 && monthly_breaks == 0){
std::cout << "Warning (On year balance, objectives not fullfilled)";
}
} else {
std::cout << "OK (on year balance)";
}
} else {
std::cout << "Warning (on fortune only)";
}
}
std::cout << std::endl;
}
}
void edit(budget::wish& wish){
edit_string(wish.name, "Name", not_empty_checker());
edit_money(wish.amount, "Amount", not_negative_checker(), not_zero_checker());
}
} //end of anonymous namespace
void budget::wishes_module::load(){
load_expenses();
load_earnings();
load_accounts();
load_fortunes();
load_objectives();
load_wishes();
}
void budget::wishes_module::unload(){
save_wishes();
}
void budget::wishes_module::handle(const std::vector<std::string>& args){
if(args.size() == 1){
status_wishes();
} else {
auto& subcommand = args[1];
if(subcommand == "list"){
list_wishes();
} else if(subcommand == "status"){
status_wishes();
} else if(subcommand == "add"){
wish wish;
wish.guid = generate_guid();
wish.date = boost::gregorian::day_clock::local_day();
edit(wish);
auto id = add_data(wishes, std::move(wish));
std::cout << "Wish " << id << " has been created" << std::endl;
} else if(subcommand == "delete"){
enough_args(args, 3);
std::size_t id = to_number<std::size_t>(args[2]);
if(!exists(wishes, id)){
throw budget_exception("There are no wish with id " + args[2]);
}
remove(wishes, id);
std::cout << "wish " << id << " has been deleted" << std::endl;
} else if(subcommand == "edit"){
enough_args(args, 3);
std::size_t id = to_number<std::size_t>(args[2]);
if(!exists(wishes, id)){
throw budget_exception("There are no wish with id " + args[2]);
}
auto& wish = get(wishes, id);
edit(wish);
set_wishes_changed();
std::cout << "wish " << id << " has been modified" << std::endl;
} else if(subcommand == "paid"){
enough_args(args, 3);
std::size_t id = to_number<std::size_t>(args[2]);
if(!exists(wishes, id)){
throw budget_exception("There are no wish with id " + args[2]);
}
auto& wish = get(wishes, id);
edit_money(wish.paid_amount, "Paid Amount", not_negative_checker(), not_zero_checker());
wish.paid = true;
set_wishes_changed();
std::cout << "wish " << id << " has been marked as paid" << std::endl;
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::load_wishes(){
load_data(wishes, "wishes.data");
}
void budget::save_wishes(){
save_data(wishes, "wishes.data");
}
void budget::add_wish(budget::wish&& wish){
add_data(wishes, std::forward<budget::wish>(wish));
}
std::ostream& budget::operator<<(std::ostream& stream, const wish& wish){
return stream
<< wish.id << ':'
<< wish.guid << ':'
<< wish.name << ':'
<< wish.amount << ':'
<< to_string(wish.date) << ':'
<< static_cast<size_t>(wish.paid) << ':'
<< wish.paid_amount;
}
void budget::operator>>(const std::vector<std::string>& parts, wish& wish){
wish.id = to_number<std::size_t>(parts[0]);
wish.guid = parts[1];
wish.name = parts[2];
wish.amount = parse_money(parts[3]);
wish.date = boost::gregorian::from_string(parts[4]);
wish.paid = to_number<std::size_t>(parts[5]) == 1;
wish.paid_amount = parse_money(parts[6]);
}
std::vector<wish>& budget::all_wishes(){
return wishes.data;
}
void budget::set_wishes_changed(){
wishes.changed = true;
}
void budget::migrate_wishes_2_to_3(){
load_data(wishes, "wishes.data", [](const std::vector<std::string>& parts, wish& wish){
wish.id = to_number<std::size_t>(parts[0]);
wish.guid = parts[1];
wish.name = parts[2];
wish.amount = parse_money(parts[3]);
wish.date = boost::gregorian::from_string(parts[4]);
wish.paid = false;
wish.paid_amount = budget::money(0,0);
});
set_wishes_changed();
save_data(wishes, "wishes.data");
}
<commit_msg>Display warning if early in the month<commit_after>//=======================================================================
// Copyright (c) 2013-2014 Baptiste Wicht.
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
#include "wishes.hpp"
#include "objectives.hpp"
#include "expenses.hpp"
#include "earnings.hpp"
#include "fortune.hpp"
#include "accounts.hpp"
#include "args.hpp"
#include "data.hpp"
#include "guid.hpp"
#include "config.hpp"
#include "utils.hpp"
#include "console.hpp"
#include "budget_exception.hpp"
#include "compute.hpp"
using namespace budget;
namespace {
static data_handler<wish> wishes;
void list_wishes(){
if(wishes.data.size() == 0){
std::cout << "No wishes" << std::endl;
} else {
std::vector<std::string> columns = {"ID", "Name", "Amount", "Paid"};
std::vector<std::vector<std::string>> contents;
money total;
money unpaid_total;
for(auto& wish : wishes.data){
contents.push_back({to_string(wish.id), wish.name, to_string(wish.amount), wish.paid ? to_string(wish.paid_amount) : "No"});
total += wish.amount;
if(!wish.paid){
unpaid_total += wish.amount;
}
}
contents.push_back({"", "", "", ""});
contents.push_back({"", "Total", to_string(total), ""});
contents.push_back({"", "Unpaid Total", to_string(unpaid_total), ""});
display_table(columns, contents);
}
}
void status_wishes(){
auto today = boost::gregorian::day_clock::local_day();
if(today.day() < 12){
std::cout << "WARNING: It is early in the month, no one can know what may happen ;)" << std::endl << std::endl;
}
std::cout << "Wishes" << std::endl << std::endl;
size_t width = 0;
for(auto& wish : wishes.data){
if(wish.paid){
continue;
}
width = std::max(rsize(wish.name), width);
}
auto month_status = budget::compute_month_status(today.year(), today.month());
auto year_status = budget::compute_year_status(today.year(), today.month());
auto fortune_amount = budget::current_fortune();
for(auto& wish : wishes.data){
if(wish.paid){
continue;
}
auto amount = wish.amount;
std::cout << " ";
print_minimum(wish.name, width);
std::cout << " ";
size_t monthly_breaks = 0;
size_t yearly_breaks = 0;
bool month_objective = true;
bool year_objective = true;
for(auto& objective : all_objectives()){
if(objective.type == "monthly"){
auto success_before = budget::compute_success(month_status, objective);
auto success_after = budget::compute_success(month_status.add_expense(amount), objective);
if(success_before >= 100 && success_after < 100){
++monthly_breaks;
}
if(success_after < 100){
month_objective = false;
}
} else if(objective.type == "yearly"){
auto success_before = budget::compute_success(year_status, objective);
auto success_after = budget::compute_success(year_status.add_expense(amount), objective);
if(success_before >= 100 && success_after < 100){
++yearly_breaks;
}
if(success_after < 100){
year_objective = false;
}
}
}
if(fortune_amount < wish.amount){
std::cout << "Impossible (not enough fortune)";
} else {
if(month_status.balance > wish.amount){
if(!all_objectives().empty()){
if(month_objective && year_objective){
std::cout << "Perfect (On month balance, all objectives fullfilled)";
} else if(month_objective){
std::cout << "Good (On month balance, month objectives fullfilled)";
} else if(yearly_breaks > 0 || monthly_breaks > 0){
std::cout << "OK (On month balance, " << (yearly_breaks + monthly_breaks) << " objectives broken)";
} else if(yearly_breaks == 0 && monthly_breaks == 0){
std::cout << "Warning (On month balance, objectives not fullfilled)";
}
} else {
std::cout << "OK (on month balance)";
}
} else if(year_status.balance > wish.amount){
if(!all_objectives().empty()){
if(month_objective && year_objective){
std::cout << "Perfect (On year balance, all objectives fullfilled)";
} else if(month_objective){
std::cout << "Good (On year balance, month objectives fullfilled)";
} else if(yearly_breaks > 0 || monthly_breaks > 0){
std::cout << "OK (On year balance, " << (yearly_breaks + monthly_breaks) << " objectives broken)";
} else if(yearly_breaks == 0 && monthly_breaks == 0){
std::cout << "Warning (On year balance, objectives not fullfilled)";
}
} else {
std::cout << "OK (on year balance)";
}
} else {
std::cout << "Warning (on fortune only)";
}
}
std::cout << std::endl;
}
}
void edit(budget::wish& wish){
edit_string(wish.name, "Name", not_empty_checker());
edit_money(wish.amount, "Amount", not_negative_checker(), not_zero_checker());
}
} //end of anonymous namespace
void budget::wishes_module::load(){
load_expenses();
load_earnings();
load_accounts();
load_fortunes();
load_objectives();
load_wishes();
}
void budget::wishes_module::unload(){
save_wishes();
}
void budget::wishes_module::handle(const std::vector<std::string>& args){
if(args.size() == 1){
status_wishes();
} else {
auto& subcommand = args[1];
if(subcommand == "list"){
list_wishes();
} else if(subcommand == "status"){
status_wishes();
} else if(subcommand == "add"){
wish wish;
wish.guid = generate_guid();
wish.date = boost::gregorian::day_clock::local_day();
edit(wish);
auto id = add_data(wishes, std::move(wish));
std::cout << "Wish " << id << " has been created" << std::endl;
} else if(subcommand == "delete"){
enough_args(args, 3);
std::size_t id = to_number<std::size_t>(args[2]);
if(!exists(wishes, id)){
throw budget_exception("There are no wish with id " + args[2]);
}
remove(wishes, id);
std::cout << "wish " << id << " has been deleted" << std::endl;
} else if(subcommand == "edit"){
enough_args(args, 3);
std::size_t id = to_number<std::size_t>(args[2]);
if(!exists(wishes, id)){
throw budget_exception("There are no wish with id " + args[2]);
}
auto& wish = get(wishes, id);
edit(wish);
set_wishes_changed();
std::cout << "wish " << id << " has been modified" << std::endl;
} else if(subcommand == "paid"){
enough_args(args, 3);
std::size_t id = to_number<std::size_t>(args[2]);
if(!exists(wishes, id)){
throw budget_exception("There are no wish with id " + args[2]);
}
auto& wish = get(wishes, id);
edit_money(wish.paid_amount, "Paid Amount", not_negative_checker(), not_zero_checker());
wish.paid = true;
set_wishes_changed();
std::cout << "wish " << id << " has been marked as paid" << std::endl;
} else {
throw budget_exception("Invalid subcommand \"" + subcommand + "\"");
}
}
}
void budget::load_wishes(){
load_data(wishes, "wishes.data");
}
void budget::save_wishes(){
save_data(wishes, "wishes.data");
}
void budget::add_wish(budget::wish&& wish){
add_data(wishes, std::forward<budget::wish>(wish));
}
std::ostream& budget::operator<<(std::ostream& stream, const wish& wish){
return stream
<< wish.id << ':'
<< wish.guid << ':'
<< wish.name << ':'
<< wish.amount << ':'
<< to_string(wish.date) << ':'
<< static_cast<size_t>(wish.paid) << ':'
<< wish.paid_amount;
}
void budget::operator>>(const std::vector<std::string>& parts, wish& wish){
wish.id = to_number<std::size_t>(parts[0]);
wish.guid = parts[1];
wish.name = parts[2];
wish.amount = parse_money(parts[3]);
wish.date = boost::gregorian::from_string(parts[4]);
wish.paid = to_number<std::size_t>(parts[5]) == 1;
wish.paid_amount = parse_money(parts[6]);
}
std::vector<wish>& budget::all_wishes(){
return wishes.data;
}
void budget::set_wishes_changed(){
wishes.changed = true;
}
void budget::migrate_wishes_2_to_3(){
load_data(wishes, "wishes.data", [](const std::vector<std::string>& parts, wish& wish){
wish.id = to_number<std::size_t>(parts[0]);
wish.guid = parts[1];
wish.name = parts[2];
wish.amount = parse_money(parts[3]);
wish.date = boost::gregorian::from_string(parts[4]);
wish.paid = false;
wish.paid_amount = budget::money(0,0);
});
set_wishes_changed();
save_data(wishes, "wishes.data");
}
<|endoftext|>
|
<commit_before>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE table_index
#include "test.hpp"
#include "fixtures/events.hpp"
#include "fixtures/filesystem.hpp"
#include "vast/bitmap.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/vast/error.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/system/table_index.hpp"
using namespace vast;
using namespace vast::system;
namespace {
struct fixture : fixtures::events, fixtures::filesystem {
template <class T>
T unbox(expected<T> x) {
if (!x)
FAIL("error: " << x.error());
return std::move(*x);
}
ids query(std::string_view what) {
return unbox(tbl->lookup(unbox(to<expression>(what))));
}
void reset(table_index&& new_tbl) {
tbl = std::make_unique<table_index>(std::move(new_tbl));
}
void reset(expected<table_index>&& new_tbl) {
if (!new_tbl)
FAIL("error: " << new_tbl.error());
reset(std::move(*new_tbl));
}
void add(event x) {
tbl->add(std::move(x));
}
std::unique_ptr<table_index> tbl;
};
} // namespace <anonymous>
FIXTURE_SCOPE(table_index_tests, fixture)
TEST(flat type) {
MESSAGE("generate table layout for flat integer type");
reset(make_table_index(directory, integer_type{}));
MESSAGE("ingest test data (integers)");
std::vector<int> xs{1, 2, 3, 1, 2, 3, 1, 2, 3};
for (size_t i = 0; i < xs.size(); ++i) {
event x{xs[i]};
x.id(i);
add(std::move(x));
}
auto res = [&](auto... args) {
return make_ids({args...}, xs.size());
};
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(query(":int == +1"), res(0, 3, 6));
CHECK_EQUAL(query(":int == +2"), res(1, 4, 7));
CHECK_EQUAL(query(":int == +3"), res(2, 5, 8));
CHECK_EQUAL(query(":int == +4"), res());
CHECK_EQUAL(query(":int != +1"), res(1, 2, 4, 5, 7, 8));
CHECK_EQUAL(query("!(:int == +1)"), res(1, 2, 4, 5, 7, 8));
CHECK_EQUAL(query(":int > +1 && :int < +3"), res(1, 4, 7));
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, integer_type{}));
MESSAGE("verify table index again");
verify();
}
TEST(record type) {
MESSAGE("generate table layout for record type");
auto tbl_type = record_type{
{"x", record_type{
{"a", integer_type{}},
{"b", boolean_type{}}
}},
{"y", record_type{
{"a", string_type{}}
}}
};
reset(make_table_index(directory, tbl_type));
MESSAGE("ingest test data (records)");
auto mk_row = [&](int x, bool y, std::string z) {
return value::make(vector{vector{x, y}, vector{std::move(z)}}, tbl_type);
};
// Some test data.
std::vector<value> xs{mk_row(1, true, "abc"), mk_row(10, false, "def"),
mk_row(5, true, "hello"), mk_row(1, true, "d e f"),
mk_row(15, true, "world"), mk_row(5, true, "bar"),
mk_row(10, false, "a b c"), mk_row(10, false, "baz"),
mk_row(5, false, "foo"), mk_row(1, true, "test")};
for (size_t i = 0; i < xs.size(); ++i) {
event x{xs[i]};
x.id(i);
add(std::move(x));
}
auto res = [&](auto... args) {
return make_ids({args...}, xs.size());
};
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(query("x.a == +1"), res(0, 3, 9));
CHECK_EQUAL(query("x.a > +1"), res(1, 2, 4, 5, 6, 7, 8));
CHECK_EQUAL(query("x.a > +1 && x.b == T"), res(2, 4, 5));
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, tbl_type));
MESSAGE("verify table index again");
verify();
}
TEST(bro conn logs) {
MESSAGE("generate table layout for bro conn logs");
auto tbl_type = bro_conn_log[0].type();
reset(make_table_index(directory, tbl_type));
CHECK_EQUAL(tbl->num_meta_columns(), 2u);
MESSAGE("ingest test data (bro conn log)");
for (auto& entry : bro_conn_log) {
add(entry);
}
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(rank(query("id.resp_p == 995/?")), 53u);
CHECK_EQUAL(rank(query("id.resp_p == 5355/?")), 49u);
CHECK_EQUAL(rank(query("id.resp_p == 995/? || id.resp_p == 5355/?")), 102u);
CHECK_EQUAL(rank(query("&time > 1970-01-01")), bro_conn_log.size());
CHECK_EQUAL(rank(query("proto == \"udp\"")), 5306u);
CHECK_EQUAL(rank(query("proto == \"tcp\"")), 3135u);
CHECK_EQUAL(rank(query("uid == \"nkCxlvNN8pi\"")), 1u);
CHECK_EQUAL(rank(query("orig_bytes < 400")), 5332u);
CHECK_EQUAL(rank(query("orig_bytes < 400 && proto == \"udp\"")), 4357u);
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, tbl_type));
MESSAGE("verify table index again");
verify();
}
FIXTURE_SCOPE_END()
<commit_msg>Generate events with proper type<commit_after>/******************************************************************************
* _ _____ __________ *
* | | / / _ | / __/_ __/ Visibility *
* | |/ / __ |_\ \ / / Across *
* |___/_/ |_/___/ /_/ Space and Time *
* *
* This file is part of VAST. It is subject to the license terms in the *
* LICENSE file found in the top-level directory of this distribution and at *
* http://vast.io/license. No part of VAST, including this file, may be *
* copied, modified, propagated, or distributed except according to the terms *
* contained in the LICENSE file. *
******************************************************************************/
#define SUITE table_index
#include "test.hpp"
#include "fixtures/events.hpp"
#include "fixtures/filesystem.hpp"
#include "vast/bitmap.hpp"
#include "vast/concept/parseable/to.hpp"
#include "vast/concept/parseable/vast/expression.hpp"
#include "vast/concept/printable/stream.hpp"
#include "vast/concept/printable/vast/error.hpp"
#include "vast/concept/printable/vast/event.hpp"
#include "vast/concept/printable/vast/expression.hpp"
#include "vast/system/table_index.hpp"
using namespace vast;
using namespace vast::system;
namespace {
struct fixture : fixtures::events, fixtures::filesystem {
template <class T>
T unbox(expected<T> x) {
if (!x)
FAIL("error: " << x.error());
return std::move(*x);
}
ids query(std::string_view what) {
return unbox(tbl->lookup(unbox(to<expression>(what))));
}
void reset(table_index&& new_tbl) {
tbl = std::make_unique<table_index>(std::move(new_tbl));
}
void reset(expected<table_index>&& new_tbl) {
if (!new_tbl)
FAIL("error: " << new_tbl.error());
reset(std::move(*new_tbl));
}
void add(event x) {
auto err = tbl->add(std::move(x));
if (err)
FAIL("error: " << err);
}
std::unique_ptr<table_index> tbl;
};
} // namespace <anonymous>
FIXTURE_SCOPE(table_index_tests, fixture)
TEST(flat type) {
MESSAGE("generate table layout for flat integer type");
integer_type layout;
reset(make_table_index(directory, layout));
MESSAGE("ingest test data (integers)");
std::vector<int> xs{1, 2, 3, 1, 2, 3, 1, 2, 3};
size_t next_id = 0;
for (auto i : xs)
add(event::make(i, layout, next_id++));
auto res = [&](auto... args) {
return make_ids({args...}, xs.size());
};
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(query(":int == +1"), res(0, 3, 6));
CHECK_EQUAL(query(":int == +2"), res(1, 4, 7));
CHECK_EQUAL(query(":int == +3"), res(2, 5, 8));
CHECK_EQUAL(query(":int == +4"), res());
CHECK_EQUAL(query(":int != +1"), res(1, 2, 4, 5, 7, 8));
CHECK_EQUAL(query("!(:int == +1)"), res(1, 2, 4, 5, 7, 8));
CHECK_EQUAL(query(":int > +1 && :int < +3"), res(1, 4, 7));
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, integer_type{}));
MESSAGE("verify table index again");
verify();
}
TEST(record type) {
MESSAGE("generate table layout for record type");
auto tbl_type = record_type{
{"x", record_type{
{"a", integer_type{}},
{"b", boolean_type{}}
}},
{"y", record_type{
{"a", string_type{}}
}}
};
reset(make_table_index(directory, tbl_type));
MESSAGE("ingest test data (records)");
auto mk_row = [&](int x, bool y, std::string z) {
return value::make(vector{vector{x, y}, vector{std::move(z)}}, tbl_type);
};
// Some test data.
std::vector<value> xs{mk_row(1, true, "abc"), mk_row(10, false, "def"),
mk_row(5, true, "hello"), mk_row(1, true, "d e f"),
mk_row(15, true, "world"), mk_row(5, true, "bar"),
mk_row(10, false, "a b c"), mk_row(10, false, "baz"),
mk_row(5, false, "foo"), mk_row(1, true, "test")};
for (size_t i = 0; i < xs.size(); ++i) {
event x{xs[i]};
x.id(i);
add(std::move(x));
}
auto res = [&](auto... args) {
return make_ids({args...}, xs.size());
};
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(query("x.a == +1"), res(0, 3, 9));
CHECK_EQUAL(query("x.a > +1"), res(1, 2, 4, 5, 6, 7, 8));
CHECK_EQUAL(query("x.a > +1 && x.b == T"), res(2, 4, 5));
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, tbl_type));
MESSAGE("verify table index again");
verify();
}
TEST(bro conn logs) {
MESSAGE("generate table layout for bro conn logs");
auto tbl_type = bro_conn_log[0].type();
reset(make_table_index(directory, tbl_type));
CHECK_EQUAL(tbl->num_meta_columns(), 2u);
MESSAGE("ingest test data (bro conn log)");
for (auto& entry : bro_conn_log) {
add(entry);
}
MESSAGE("verify table index");
auto verify = [&] {
CHECK_EQUAL(rank(query("id.resp_p == 995/?")), 53u);
CHECK_EQUAL(rank(query("id.resp_p == 5355/?")), 49u);
CHECK_EQUAL(rank(query("id.resp_p == 995/? || id.resp_p == 5355/?")), 102u);
CHECK_EQUAL(rank(query("&time > 1970-01-01")), bro_conn_log.size());
CHECK_EQUAL(rank(query("proto == \"udp\"")), 5306u);
CHECK_EQUAL(rank(query("proto == \"tcp\"")), 3135u);
CHECK_EQUAL(rank(query("uid == \"nkCxlvNN8pi\"")), 1u);
CHECK_EQUAL(rank(query("orig_bytes < 400")), 5332u);
CHECK_EQUAL(rank(query("orig_bytes < 400 && proto == \"udp\"")), 4357u);
};
verify();
MESSAGE("(automatically) persist table index and restore from disk");
reset(make_table_index(directory, tbl_type));
MESSAGE("verify table index again");
verify();
}
FIXTURE_SCOPE_END()
<|endoftext|>
|
<commit_before>#include <build-bot/worker.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/process.hpp>
namespace fs = boost::filesystem;
namespace dsn {
namespace build_bot {
namespace priv {
class Worker : public dsn::log::Base<Worker> {
private:
std::string m_url;
std::string m_branch;
std::string m_revision;
std::string m_configFile;
std::string m_profileName;
std::string m_buildDir;
std::string m_repoName;
std::string m_macroFile;
std::string generateBuildId()
{
std::string res;
boost::random::random_device rng;
boost::random::uniform_int_distribution<> dist(0, BUILD_ID_CHARS.size() - 1);
for (size_t i = 0; i < BUILD_ID_LENGTH; i++)
res += BUILD_ID_CHARS[dist(rng)];
return res;
}
std::string m_buildId;
static const std::string BUILD_ID_CHARS;
static const size_t BUILD_ID_LENGTH;
std::string m_toplevelDirectory;
bool initToplevelDirectory()
{
std::stringstream ss;
ss << m_buildDir << "/" << m_profileName << "/" << m_repoName << "/" << m_buildId;
m_toplevelDirectory = ss.str();
fs::path path(m_toplevelDirectory);
BOOST_LOG_SEV(log, severity::info) << "Toplevel build directory is " << m_toplevelDirectory;
if (!fs::exists(path)) {
try {
fs::create_directories(path);
}
catch (boost::system::system_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to create toplevel directory " << m_toplevelDirectory << ": " << ex.what();
return false;
}
}
return true;
}
std::string m_gitExecutable;
bool findGitExecutable()
{
try {
m_gitExecutable = boost::process::search_path("git");
}
catch (std::runtime_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to locate git executable in PATH: " << ex.what();
return false;
}
if (m_gitExecutable.size() == 0) {
BOOST_LOG_SEV(log, severity::error) << "No git executable found in PATH!";
return false;
}
BOOST_LOG_SEV(log, severity::debug) << "Using git executable from " << m_gitExecutable;
return true;
}
std::string m_sourceDirectory;
bool checkoutSources()
{
m_sourceDirectory = m_toplevelDirectory + "/repo";
BOOST_LOG_SEV(log, severity::info) << "Checking out sources from " << m_url << " to " << m_sourceDirectory;
try {
std::stringstream ssArgs;
ssArgs << m_gitExecutable << " clone --recursive -b " << m_branch << " " << m_url << " " << m_sourceDirectory;
std::string args = ssArgs.str();
BOOST_LOG_SEV(log, severity::debug) << "Git command line is " << args;
boost::process::child child = boost::process::execute(boost::process::initializers::run_exe(m_gitExecutable),
boost::process::initializers::set_cmd_line(args));
auto exit_code = boost::process::wait_for_exit(child);
if (exit_code != 0) {
BOOST_LOG_SEV(log, severity::error) << "Got non-zero exit status from '" << args << "': " << exit_code;
return false;
}
}
catch (boost::system::system_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to run git to check out sources: " << ex.what();
return false;
}
BOOST_LOG_SEV(log, severity::info) << "Repository cloned successfully. Checking out revision " << m_revision;
try {
std::stringstream ssArgs;
ssArgs << m_gitExecutable << " checkout " << m_revision << " .";
std::string args = ssArgs.str();
BOOST_LOG_SEV(log, severity::debug) << "Git command line is " << args;
boost::process::child child = boost::process::execute(boost::process::initializers::run_exe(m_gitExecutable),
boost::process::initializers::set_cmd_line(args),
boost::process::initializers::start_in_dir(m_sourceDirectory));
auto exit_code = boost::process::wait_for_exit(child);
if (exit_code != 0) {
BOOST_LOG_SEV(log, severity::error) << "Got non-zero exit status from '" << args << "': " << exit_code;
return false;
}
}
catch (boost::system::system_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to run git to check out revision " << m_revision << ": " << ex.what();
return false;
}
BOOST_LOG_SEV(log, severity::info) << "Checked out revision " << m_revision;
return true;
}
boost::property_tree::ptree m_macros;
bool loadMacroFile()
{
fs::path path(m_macroFile);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::warning) << "Macro file " << m_macroFile << " doesn't exist!";
return true;
}
if (!fs::is_regular_file(path)) {
BOOST_LOG_SEV(log, severity::error) << "Macro configuration " << m_macroFile << " exists but isn't a regular file!";
return false;
}
try {
boost::property_tree::read_ini(m_macroFile, m_macros);
}
catch (boost::property_tree::ptree_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to parse macros from " << m_macroFile << ": " << ex.what();
return false;
}
return true;
}
boost::property_tree::ptree m_buildSettings;
bool loadBuildConfig()
{
std::string configFile = m_sourceDirectory + "/" + m_configFile;
fs::path path(configFile);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::error) << "Build config file " << m_configFile << " doesn't exist in " << m_sourceDirectory;
return false;
}
if (!fs::is_regular_file(path)) {
BOOST_LOG_SEV(log, severity::error) << "Build config file " << configFile << " exists but isn't a regular file!";
return false;
}
try {
boost::property_tree::read_ini(configFile, m_buildSettings);
}
catch (boost::property_tree::ini_parser_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to parse build configuration in " << m_configFile << ": " << ex.what();
return false;
}
return true;
}
std::string m_binaryDir;
bool createBinaryDir()
{
m_binaryDir = m_toplevelDirectory + "/build";
fs::path path(m_binaryDir);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::info) << "Creating binary dir: " << m_binaryDir;
try {
fs::create_directories(path);
}
catch (boost::system::system_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to create binary dir " << m_binaryDir << ": " << ex.what();
return false;
}
}
return true;
}
bool replaceMacros(std::string& str)
{
for (auto& kv : m_macros) {
try {
std::string key = kv.first;
std::string val = m_macros.get<std::string>(key);
std::string token = "@" + key + "@";
boost::algorithm::replace_all(str, token, val);
}
catch (boost::property_tree::ptree_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to replace macro: " << ex.what();
return false;
}
}
return true;
}
bool configureSources()
{
BOOST_LOG_SEV(log, severity::info) << "Trying to configure sources";
std::string configureCommand;
try {
configureCommand = m_buildSettings.get<std::string>(m_profileName + ".cmd_configure");
}
catch (boost::property_tree::ptree_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to get configure command from build settings: " << ex.what();
return false;
}
if (configureCommand.size() == 0) {
BOOST_LOG_SEV(log, severity::warning) << "Configure command is empty; continuing build!";
return true;
}
BOOST_LOG_SEV(log, severity::debug) << "Configure command is: " << configureCommand;
if (!replaceMacros(configureCommand)) {
BOOST_LOG_SEV(log, severity::error) << "Macro expansion failed for configure command!";
return false;
}
BOOST_LOG_SEV(log, severity::debug) << "Configure command after macro expansion is: " << configureCommand;
return true;
}
public:
Worker(const std::string& macro_file, const std::string& build_directory,
const std::string& repo_name,
const std::string& url, const std::string& branch, const std::string& revision,
const std::string& config_file, const std::string& profile_name)
: m_buildDir(build_directory)
, m_macroFile(macro_file)
, m_url(url)
, m_branch(branch)
, m_revision(revision)
, m_configFile(config_file)
, m_profileName(profile_name)
, m_repoName(repo_name)
{
}
void run()
{
if (!findGitExecutable()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to find git; build FAILED!";
return;
}
m_buildId = generateBuildId();
BOOST_LOG_SEV(log, severity::info) << "Worker started for repo " << m_repoName
<< " (profile: " << m_profileName << ", config: " << m_configFile << ") - Build ID: " << m_buildId;
if (!initToplevelDirectory()) {
BOOST_LOG_SEV(log, severity::error) << "Unable to create build directory; build FAILED!";
return;
}
if (!loadMacroFile()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to load macro file; build FAILED!";
return;
}
if (!checkoutSources()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to checkout sources from " << m_url << "; build FAILED!";
return;
}
if (!createBinaryDir()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to create build directory; build FAILED!";
return;
}
if (!loadBuildConfig()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to load build configuration; build FAILED!";
return;
}
if (!configureSources()) {
BOOST_LOG_SEV(log, severity::error) << "Configure step aborted; build FAILED!";
return;
}
}
};
const std::string Worker::BUILD_ID_CHARS{ "0123456789abcdef" };
const size_t Worker::BUILD_ID_LENGTH{ 8 };
}
}
}
using namespace dsn::build_bot;
Worker::Worker(const std::string& macro_file, const std::string& build_directory,
const std::string& repo_name,
const std::string& url, const std::string& branch, const std::string& revision,
const std::string& config_file, const std::string& profile_name)
: m_impl(new priv::Worker(macro_file, build_directory, repo_name, url, branch, revision, config_file, profile_name))
{
}
Worker::~Worker()
{
}
void Worker::run()
{
return m_impl->run();
}
<commit_msg>Add source directory to macro expansion list<commit_after>#include <build-bot/worker.h>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/random/random_device.hpp>
#include <boost/random/uniform_int_distribution.hpp>
#include <boost/process.hpp>
namespace fs = boost::filesystem;
namespace dsn {
namespace build_bot {
namespace priv {
class Worker : public dsn::log::Base<Worker> {
private:
std::string m_url;
std::string m_branch;
std::string m_revision;
std::string m_configFile;
std::string m_profileName;
std::string m_buildDir;
std::string m_repoName;
std::string m_macroFile;
std::string generateBuildId()
{
std::string res;
boost::random::random_device rng;
boost::random::uniform_int_distribution<> dist(0, BUILD_ID_CHARS.size() - 1);
for (size_t i = 0; i < BUILD_ID_LENGTH; i++)
res += BUILD_ID_CHARS[dist(rng)];
return res;
}
std::string m_buildId;
static const std::string BUILD_ID_CHARS;
static const size_t BUILD_ID_LENGTH;
std::string m_toplevelDirectory;
bool initToplevelDirectory()
{
std::stringstream ss;
ss << m_buildDir << "/" << m_profileName << "/" << m_repoName << "/" << m_buildId;
m_toplevelDirectory = ss.str();
fs::path path(m_toplevelDirectory);
BOOST_LOG_SEV(log, severity::info) << "Toplevel build directory is " << m_toplevelDirectory;
if (!fs::exists(path)) {
try {
fs::create_directories(path);
}
catch (boost::system::system_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to create toplevel directory " << m_toplevelDirectory << ": " << ex.what();
return false;
}
}
return true;
}
std::string m_gitExecutable;
bool findGitExecutable()
{
try {
m_gitExecutable = boost::process::search_path("git");
}
catch (std::runtime_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to locate git executable in PATH: " << ex.what();
return false;
}
if (m_gitExecutable.size() == 0) {
BOOST_LOG_SEV(log, severity::error) << "No git executable found in PATH!";
return false;
}
BOOST_LOG_SEV(log, severity::debug) << "Using git executable from " << m_gitExecutable;
return true;
}
std::string m_sourceDirectory;
bool checkoutSources()
{
m_sourceDirectory = m_toplevelDirectory + "/repo";
BOOST_LOG_SEV(log, severity::info) << "Checking out sources from " << m_url << " to " << m_sourceDirectory;
try {
std::stringstream ssArgs;
ssArgs << m_gitExecutable << " clone --recursive -b " << m_branch << " " << m_url << " " << m_sourceDirectory;
std::string args = ssArgs.str();
BOOST_LOG_SEV(log, severity::debug) << "Git command line is " << args;
boost::process::child child = boost::process::execute(boost::process::initializers::run_exe(m_gitExecutable),
boost::process::initializers::set_cmd_line(args));
auto exit_code = boost::process::wait_for_exit(child);
if (exit_code != 0) {
BOOST_LOG_SEV(log, severity::error) << "Got non-zero exit status from '" << args << "': " << exit_code;
return false;
}
}
catch (boost::system::system_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to run git to check out sources: " << ex.what();
return false;
}
BOOST_LOG_SEV(log, severity::info) << "Repository cloned successfully. Checking out revision " << m_revision;
try {
std::stringstream ssArgs;
ssArgs << m_gitExecutable << " checkout " << m_revision << " .";
std::string args = ssArgs.str();
BOOST_LOG_SEV(log, severity::debug) << "Git command line is " << args;
boost::process::child child = boost::process::execute(boost::process::initializers::run_exe(m_gitExecutable),
boost::process::initializers::set_cmd_line(args),
boost::process::initializers::start_in_dir(m_sourceDirectory));
auto exit_code = boost::process::wait_for_exit(child);
if (exit_code != 0) {
BOOST_LOG_SEV(log, severity::error) << "Got non-zero exit status from '" << args << "': " << exit_code;
return false;
}
}
catch (boost::system::system_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to run git to check out revision " << m_revision << ": " << ex.what();
return false;
}
BOOST_LOG_SEV(log, severity::info) << "Checked out revision " << m_revision;
m_macros.put<std::string>("CMAKE_SOURCE_DIRECTORY", m_sourceDirectory);
return true;
}
boost::property_tree::ptree m_macros;
bool loadMacroFile()
{
fs::path path(m_macroFile);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::warning) << "Macro file " << m_macroFile << " doesn't exist!";
return true;
}
if (!fs::is_regular_file(path)) {
BOOST_LOG_SEV(log, severity::error) << "Macro configuration " << m_macroFile << " exists but isn't a regular file!";
return false;
}
try {
boost::property_tree::read_ini(m_macroFile, m_macros);
}
catch (boost::property_tree::ptree_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to parse macros from " << m_macroFile << ": " << ex.what();
return false;
}
return true;
}
boost::property_tree::ptree m_buildSettings;
bool loadBuildConfig()
{
std::string configFile = m_sourceDirectory + "/" + m_configFile;
fs::path path(configFile);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::error) << "Build config file " << m_configFile << " doesn't exist in " << m_sourceDirectory;
return false;
}
if (!fs::is_regular_file(path)) {
BOOST_LOG_SEV(log, severity::error) << "Build config file " << configFile << " exists but isn't a regular file!";
return false;
}
try {
boost::property_tree::read_ini(configFile, m_buildSettings);
}
catch (boost::property_tree::ini_parser_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to parse build configuration in " << m_configFile << ": " << ex.what();
return false;
}
return true;
}
std::string m_binaryDir;
bool createBinaryDir()
{
m_binaryDir = m_toplevelDirectory + "/build";
fs::path path(m_binaryDir);
if (!fs::exists(path)) {
BOOST_LOG_SEV(log, severity::info) << "Creating binary dir: " << m_binaryDir;
try {
fs::create_directories(path);
}
catch (boost::system::system_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to create binary dir " << m_binaryDir << ": " << ex.what();
return false;
}
}
return true;
}
bool replaceMacros(std::string& str)
{
for (auto& kv : m_macros) {
try {
std::string key = kv.first;
std::string val = m_macros.get<std::string>(key);
std::string token = "@" + key + "@";
boost::algorithm::replace_all(str, token, val);
}
catch (boost::property_tree::ptree_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to replace macro: " << ex.what();
return false;
}
}
return true;
}
bool configureSources()
{
BOOST_LOG_SEV(log, severity::info) << "Trying to configure sources";
std::string configureCommand;
try {
configureCommand = m_buildSettings.get<std::string>(m_profileName + ".cmd_configure");
}
catch (boost::property_tree::ptree_error& ex) {
BOOST_LOG_SEV(log, severity::error) << "Failed to get configure command from build settings: " << ex.what();
return false;
}
if (configureCommand.size() == 0) {
BOOST_LOG_SEV(log, severity::warning) << "Configure command is empty; continuing build!";
return true;
}
BOOST_LOG_SEV(log, severity::debug) << "Configure command is: " << configureCommand;
if (!replaceMacros(configureCommand)) {
BOOST_LOG_SEV(log, severity::error) << "Macro expansion failed for configure command!";
return false;
}
BOOST_LOG_SEV(log, severity::debug) << "Configure command after macro expansion is: " << configureCommand;
return true;
}
public:
Worker(const std::string& macro_file, const std::string& build_directory,
const std::string& repo_name,
const std::string& url, const std::string& branch, const std::string& revision,
const std::string& config_file, const std::string& profile_name)
: m_buildDir(build_directory)
, m_macroFile(macro_file)
, m_url(url)
, m_branch(branch)
, m_revision(revision)
, m_configFile(config_file)
, m_profileName(profile_name)
, m_repoName(repo_name)
{
}
void run()
{
if (!findGitExecutable()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to find git; build FAILED!";
return;
}
m_buildId = generateBuildId();
BOOST_LOG_SEV(log, severity::info) << "Worker started for repo " << m_repoName
<< " (profile: " << m_profileName << ", config: " << m_configFile << ") - Build ID: " << m_buildId;
if (!initToplevelDirectory()) {
BOOST_LOG_SEV(log, severity::error) << "Unable to create build directory; build FAILED!";
return;
}
if (!loadMacroFile()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to load macro file; build FAILED!";
return;
}
if (!checkoutSources()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to checkout sources from " << m_url << "; build FAILED!";
return;
}
if (!createBinaryDir()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to create build directory; build FAILED!";
return;
}
if (!loadBuildConfig()) {
BOOST_LOG_SEV(log, severity::error) << "Failed to load build configuration; build FAILED!";
return;
}
if (!configureSources()) {
BOOST_LOG_SEV(log, severity::error) << "Configure step aborted; build FAILED!";
return;
}
}
};
const std::string Worker::BUILD_ID_CHARS{ "0123456789abcdef" };
const size_t Worker::BUILD_ID_LENGTH{ 8 };
}
}
}
using namespace dsn::build_bot;
Worker::Worker(const std::string& macro_file, const std::string& build_directory,
const std::string& repo_name,
const std::string& url, const std::string& branch, const std::string& revision,
const std::string& config_file, const std::string& profile_name)
: m_impl(new priv::Worker(macro_file, build_directory, repo_name, url, branch, revision, config_file, profile_name))
{
}
Worker::~Worker()
{
}
void Worker::run()
{
return m_impl->run();
}
<|endoftext|>
|
<commit_before>#include "Scene.h"
#include"ObjectBehaviour.h"
namespace AEngine::Game
{
void Scene::OnInit()
{
for (var i : m_objects)
{
i->OnInit();
}
}
void Scene::OnUpdate()
{
}
void Scene::OnRelease()
{
for (var i : m_objects)
{
RemoveObject(dynamic_cast<GameObject*>(dynamic_cast<ObjectBehaviour*>(i)));
}
}
void Scene::AddObject(GameObject * obj)
{
for (var i : obj->GetChildren())
{
AddObject(i);
}
var behaviour = dynamic_cast<ObjectBehaviour*>(obj);
for (var i : behaviour->GetComponents())
{
if (i)
{
m_objects.emplace_back(dynamic_cast<BaseBehaviour*>(i));
}
}
m_objects.emplace_back(dynamic_cast<BaseBehaviour*>(behaviour));
}
void Scene::RemoveObject(GameObject * obj)
{
lock_guard<std::mutex> lock(m_mutex);
for (var i : obj->GetChildren())
{
RemoveObject(i);
}
var behaviour = dynamic_cast<BaseBehaviour*>(dynamic_cast<ObjectBehaviour*>(obj));
behaviour->OnRelease();
}
}<commit_msg>Try my best to avoid deadlock<commit_after>#include "Scene.h"
#include"ObjectBehaviour.h"
namespace AEngine::Game
{
void Scene::OnInit()
{
for (var i : m_objects)
{
i->OnInit();
}
}
void Scene::OnUpdate()
{
}
void Scene::OnRelease()
{
for (var i : m_objects)
{
RemoveObject(dynamic_cast<GameObject*>(dynamic_cast<ObjectBehaviour*>(i)));
}
}
void Scene::AddObject(GameObject * obj)
{
for (var i : obj->GetChildren())
{
AddObject(i);
}
var behaviour = dynamic_cast<ObjectBehaviour*>(obj);
for (var i : behaviour->GetComponents())
{
if (i)
{
m_objects.emplace_back(dynamic_cast<BaseBehaviour*>(i));
}
}
m_objects.emplace_back(dynamic_cast<BaseBehaviour*>(behaviour));
}
void Scene::RemoveObject(GameObject * obj)
{
for (var i : obj->GetChildren())
{
RemoveObject(i);
}
lock_guard<std::mutex> lock(m_mutex);
var behaviour = dynamic_cast<BaseBehaviour*>(dynamic_cast<ObjectBehaviour*>(obj));
behaviour->OnRelease();
}
}<|endoftext|>
|
<commit_before>#include <sstream>
#include <pcl/features/fpfh.h>
#include <pcl/io/pcd_io.h>
#include <pcl/keypoints/uniform_sampling.h>
#include <pcl/registration/icp.h>
#include <pcl/registration/ia_ransac.h>
#include <pcl/common/time.h>
#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/ia_ransac_sub.h"
namespace pcl {
namespace proctor {
/** create the viewports to be used by top candidates */
class create_viewports {
public:
create_viewports(PointCloud<PointNormal>::ConstPtr sentinel) : sentinel(sentinel) {}
void operator()(visualization::PCLVisualizer &v) {
for (int ci = 0; ci < Detector::num_registration; ci++) {
int vp;
v.createViewPort(double(ci) / Detector::num_registration, 0, double(ci + 1) / Detector::num_registration, 1, vp);
{
stringstream ss;
ss << "candidate_" << ci;
v.addPointCloud(sentinel, visualization::PointCloudColorHandlerCustom<PointNormal>(sentinel, 0xc0, 0x00, 0x40), ss.str(), vp);
}
{
stringstream ss;
ss << "aligned_" << ci;
v.addPointCloud(sentinel, visualization::PointCloudColorHandlerCustom<PointNormal>(sentinel, 0xc0, 0x00, 0x40), ss.str(), vp);
}
}
}
private:
PointCloud<PointNormal>::ConstPtr sentinel;
};
/** show a candidate model as the specified candidate */
class show_candidate {
public:
show_candidate(int ci, PointCloud<PointNormal>::ConstPtr candidate) : ci(ci), candidate(candidate) {}
void operator()(visualization::PCLVisualizer &v) {
{
stringstream ss;
ss << "candidate_" << ci;
v.updatePointCloud(candidate, visualization::PointCloudColorHandlerCustom<PointNormal>(candidate, 0xc0, 0x00, 0x40), ss.str());
}
{
stringstream ss;
ss << "aligned_" << ci;
v.updatePointCloud(candidate, visualization::PointCloudColorHandlerCustom<PointNormal>(candidate, 0xc0, 0x00, 0x40), ss.str());
}
}
private:
int ci;
PointCloud<PointNormal>::ConstPtr candidate;
};
/** show an aligned point cloud in the specified viewport */
class show_aligned {
public:
show_aligned(int ci, PointCloud<PointNormal>::ConstPtr aligned) : ci(ci), aligned(aligned) {}
void operator()(visualization::PCLVisualizer &v) {
stringstream ss;
ss << "aligned_" << ci;
v.updatePointCloud(aligned, visualization::PointCloudColorHandlerCustom<PointNormal>(aligned, 0xff, 0xff, 0xff), ss.str());
}
private:
int ci;
PointCloud<PointNormal>::ConstPtr aligned;
};
class visualization_callback {
public:
visualization_callback(int ci, visualization::CloudViewer *vis) : ci(ci), vis(vis) {}
void operator()(const PointCloud<PointNormal> &cloud_src,
const vector<int> &indices_src,
const PointCloud<PointNormal> &cloud_tgt,
const vector<int> &indices_tgt) {
// make a copy of the cloud. expensive.
PointCloud<PointNormal>::ConstPtr aligned (new PointCloud<PointNormal>(cloud_src));
vis->runOnVisualizationThreadOnce(show_aligned(ci, aligned));
}
private:
int ci;
visualization::CloudViewer *vis;
};
/** Detector */
const double Detector::keypoint_separation = 0.1;
const int Detector::max_votes = 100;
const int Detector::num_registration = 4;
/* Trains a single model */
void Detector::train(Scene &scene) {
srand(0);
IndicesPtr keypoints = computeKeypoints(scene.cloud);
PointCloud<Detector::Signature>::Ptr features = obtainFeatures(scene, keypoints, false);
Entry e;
e.cloud = scene.cloud;
e.indices = keypoints;
e.features = features;
e.tree = KdTree<Signature>::Ptr(new KdTreeFLANN<Signature>());
e.tree->setInputCloud(e.features);
database[scene.id] = e;
}
typedef struct {
std::string id;
float votes;
} Candidate;
bool operator<(const Candidate &a, const Candidate &b) {
return a.votes > b.votes; // sort descending
}
double Detector::get_votes(Entry &query, Entry &match) {
double votes = 0;
for (unsigned int pi = 0; pi < query.indices->size(); pi++) {
vector<int> indices;
vector<float> distances;
clock_t start = clock();
StopWatch s;
match.tree->nearestKSearch(*query.features, pi, max_votes, indices, distances);
for (int ri = 0; ri < max_votes; ri++) {
//votes += 1. / (distances[ri] + numeric_limits<float>::epsilon());
votes -= distances[ri];
}
}
return votes;
}
// TODO scene as a reference
std::string Detector::query(Scene scene, float *classifier, double *registration) {
cout << "Running a test on model " << scene.id << endl;
Entry e;
e.cloud = scene.cloud;
timer.start();
e.indices = computeKeypoints(e.cloud);
timer.stop(KEYPOINTS_TESTING);
timer.start();
e.features = obtainFeatures(scene, e.indices, true);
timer.stop(COMPUTE_FEATURES_TESTING);
// let each point cast votes
timer.start();
memset(classifier, 0, Config::num_models * sizeof(*classifier));
clock_t totalTime = 0;
float time = 0;
StopWatch s;
std::map<std::string, Entry>::iterator it;
// get top candidates
vector<Candidate> ballot;
for ( it = database.begin() ; it != database.end(); it++ ) {
std::string target_id = (*it).first;
Entry target = (*it).second;
Candidate* candidate = new Candidate;
candidate->id = target_id;
candidate->votes = get_votes(e, target);
ballot.push_back(*candidate);
}
sort(ballot.begin(), ballot.end());
time += s.getTimeSeconds();
//cout << "Total K-Nearest Search Time for Query: " << time << endl;
//timer.stop(VOTING_CLASSIFIER);
//if (vis.get()) {
//for (int ci = 0; ci < num_registration; ci++) {
//vis->runOnVisualizationThreadOnce(show_candidate(ci, database[ballot[ci].mi].cloud));
//}
//}
//run registration on top candidates
//memset(registration, 0, Config::num_models * sizeof(*registration));
std::map<std::string, double> reg_scores;
double best = numeric_limits<double>::infinity();
std::string guessed_id = "";
for (int ci = 0; ci < num_registration; ci++) {
std::string id = ballot[ci].id;
flush(cout << id << ": " << ballot[ci].votes);
reg_scores[id] = computeRegistration(e, id, ci);
cout << " / " << reg_scores[id] << endl;
if (reg_scores[id] < best) {
guessed_id = id;
best = reg_scores[id];
}
}
return guessed_id;
}
void Detector::enableVisualization() {
vis.reset(new visualization::CloudViewer("Detector Visualization"));
PointCloud<PointNormal>::Ptr sentinel (new PointCloud<PointNormal>());
sentinel->points.push_back(PointNormal());
vis->runOnVisualizationThreadOnce(create_viewports(sentinel));
}
void Detector::printTimer() {
printf(
"select training keypoints: %10.3f sec\n"
"obtain training features: %10.3f sec\n"
"build feature tree: %10.3f sec\n"
"select testing keypoints: %10.3f sec\n"
"compute testing features: %10.3f sec\n"
"voting classifier: %10.3f sec\n"
"initial alignment: %10.3f sec\n"
"ICP: %10.3f sec\n",
timer[KEYPOINTS_TRAINING],
timer[OBTAIN_FEATURES_TRAINING],
timer[BUILD_TREE],
timer[KEYPOINTS_TESTING],
timer[COMPUTE_FEATURES_TESTING],
timer[VOTING_CLASSIFIER],
timer[IA_RANSAC],
timer[ICP]
);
}
IndicesPtr Detector::computeKeypoints(PointCloud<PointNormal>::Ptr cloud) {
IndicesPtr indices (new vector<int>());
PointCloud<int> leaves;
UniformSampling<PointNormal> us;
us.setRadiusSearch(keypoint_separation);
us.setInputCloud(cloud);
us.compute(leaves);
indices->assign(leaves.points.begin(), leaves.points.end()); // can't use operator=, probably because of different allocators
return indices;
srand(0);
int r = 200;
IndicesPtr subset (new vector<int>());
for (int i = 0; i < r; i++) {
if (indices->size() == 0) {
break;
}
int pick = rand() % indices->size();
subset->push_back(indices->at(pick));
indices->erase(indices->begin() + pick);
}
cout << "Subset Size: " << subset->size() << endl;
return subset;
}
PointCloud<Detector::Signature>::Ptr Detector::computeFeatures(PointCloud<PointNormal>::Ptr cloud, IndicesPtr indices) {
cout << "computing features on " << indices->size() << " points" << endl;
PointCloud<Signature>::Ptr features (new PointCloud<Signature>());
FPFHEstimation<PointNormal, PointNormal, Signature> fpfh;
fpfh.setRadiusSearch(0.1);
fpfh.setInputCloud(cloud);
fpfh.setIndices(indices);
search::KdTree<PointNormal>::Ptr kdt (new search::KdTree<PointNormal>());
fpfh.setSearchMethod(kdt);
fpfh.setInputNormals(cloud);
fpfh.compute(*features);
if (features->points.size() != indices->size())
cout << "got " << features->points.size() << " features from " << indices->size() << " points" << endl;
return features;
}
// TODO Enum for is_test_phase
PointCloud<Detector::Signature>::Ptr Detector::obtainFeatures(Scene &scene, IndicesPtr indices, bool is_test_phase) {
std::string name_str = std::string("feature_") + scene.id;
if (is_test_phase) {
name_str += "_test";
}
else {
name_str += "_train";
}
name_str += ".pcd";
const char *name = name_str.c_str();
if (ifstream(name)) {
PointCloud<Signature>::Ptr features (new PointCloud<Signature>());
io::loadPCDFile(name, *features);
//if (features->points.size() != indices->size())
//cout << "got " << features->points.size() << " features from " << indices->size() << " points" << endl;
return features;
} else {
PointCloud<Signature>::Ptr features = computeFeatures(scene.cloud, indices);
io::savePCDFileBinary(name, *features);
return features;
}
}
double Detector::computeRegistration(Entry &source, std::string id, int ci) {
Entry& target = database[id];
typedef boost::function<void(const PointCloud<PointNormal> &cloud_src,
const vector<int> &indices_src,
const PointCloud<PointNormal> &cloud_tgt,
const vector<int> &indices_tgt)> f;
//cout << "Source: " << id << "\tSize: " << source.cloud->size() << "\tIndices Size: " << source.indices->size() << "\tFeature Size: " << source.features->size() << endl;
//cout << "Target: " << id << "\tSize: " << target.cloud->size() << "\tIndices Size: " << target.indices->size() << "\tFeature Size: " << target.features->size() << endl;
// Copy the source/target clouds with only the subset of points that
// also features calculated for them.
PointCloud<PointNormal>::Ptr source_subset(
new PointCloud<PointNormal>(*(source.cloud), *(source.indices)));
PointCloud<PointNormal>::Ptr target_subset(
new PointCloud<PointNormal>(*(target.cloud), *(target.indices)));
timer.start();
// TODO Filtering the source cloud makes it much faster when computing the
// error metric, but may not be as good
SampleConsensusInitialAlignment<PointNormal, PointNormal, Signature> ia_ransac;
ia_ransac.setMinSampleDistance(0.05);
ia_ransac.setMaxCorrespondenceDistance(0.5);
ia_ransac.setMaximumIterations(256);
ia_ransac.setInputCloud(source_subset);
ia_ransac.setSourceFeatures(source.features);
//ia_ransac.setSourceIndices(source.indices);
ia_ransac.setInputTarget(target_subset);
ia_ransac.setTargetFeatures(target.features);
//ia_ransac.setTargetIndices(target.indices);
if (vis.get()) {
f updater (visualization_callback(ci, vis.get()));
ia_ransac.registerVisualizationCallback(updater);
}
PointCloud<PointNormal>::Ptr aligned (new PointCloud<PointNormal>());
ia_ransac.align(*aligned);
timer.stop(IA_RANSAC);
timer.start();
IterativeClosestPoint<PointNormal, PointNormal> icp;
PointCloud<PointNormal>::Ptr aligned2 (new PointCloud<PointNormal>());
icp.setInputCloud(aligned);
icp.setInputTarget(target.cloud);
icp.setMaxCorrespondenceDistance(0.1);
icp.setMaximumIterations(64);
if (vis.get()) {
f updater (visualization_callback(ci, vis.get()));
icp.registerVisualizationCallback(updater);
}
icp.align(*aligned2);
timer.stop(ICP);
return icp.getFitnessScore();
}
}
}
<commit_msg>Fixed voting bug, where the number of votes is not kept track of.<commit_after>#include <sstream>
#include <pcl/features/fpfh.h>
#include <pcl/io/pcd_io.h>
#include <pcl/keypoints/uniform_sampling.h>
#include <pcl/registration/icp.h>
#include <pcl/registration/ia_ransac.h>
#include <pcl/common/time.h>
#include "proctor/detector.h"
#include "proctor/proctor.h"
#include "proctor/ia_ransac_sub.h"
namespace pcl {
namespace proctor {
/** create the viewports to be used by top candidates */
class create_viewports {
public:
create_viewports(PointCloud<PointNormal>::ConstPtr sentinel) : sentinel(sentinel) {}
void operator()(visualization::PCLVisualizer &v) {
for (int ci = 0; ci < Detector::num_registration; ci++) {
int vp;
v.createViewPort(double(ci) / Detector::num_registration, 0, double(ci + 1) / Detector::num_registration, 1, vp);
{
stringstream ss;
ss << "candidate_" << ci;
v.addPointCloud(sentinel, visualization::PointCloudColorHandlerCustom<PointNormal>(sentinel, 0xc0, 0x00, 0x40), ss.str(), vp);
}
{
stringstream ss;
ss << "aligned_" << ci;
v.addPointCloud(sentinel, visualization::PointCloudColorHandlerCustom<PointNormal>(sentinel, 0xc0, 0x00, 0x40), ss.str(), vp);
}
}
}
private:
PointCloud<PointNormal>::ConstPtr sentinel;
};
/** show a candidate model as the specified candidate */
class show_candidate {
public:
show_candidate(int ci, PointCloud<PointNormal>::ConstPtr candidate) : ci(ci), candidate(candidate) {}
void operator()(visualization::PCLVisualizer &v) {
{
stringstream ss;
ss << "candidate_" << ci;
v.updatePointCloud(candidate, visualization::PointCloudColorHandlerCustom<PointNormal>(candidate, 0xc0, 0x00, 0x40), ss.str());
}
{
stringstream ss;
ss << "aligned_" << ci;
v.updatePointCloud(candidate, visualization::PointCloudColorHandlerCustom<PointNormal>(candidate, 0xc0, 0x00, 0x40), ss.str());
}
}
private:
int ci;
PointCloud<PointNormal>::ConstPtr candidate;
};
/** show an aligned point cloud in the specified viewport */
class show_aligned {
public:
show_aligned(int ci, PointCloud<PointNormal>::ConstPtr aligned) : ci(ci), aligned(aligned) {}
void operator()(visualization::PCLVisualizer &v) {
stringstream ss;
ss << "aligned_" << ci;
v.updatePointCloud(aligned, visualization::PointCloudColorHandlerCustom<PointNormal>(aligned, 0xff, 0xff, 0xff), ss.str());
}
private:
int ci;
PointCloud<PointNormal>::ConstPtr aligned;
};
class visualization_callback {
public:
visualization_callback(int ci, visualization::CloudViewer *vis) : ci(ci), vis(vis) {}
void operator()(const PointCloud<PointNormal> &cloud_src,
const vector<int> &indices_src,
const PointCloud<PointNormal> &cloud_tgt,
const vector<int> &indices_tgt) {
// make a copy of the cloud. expensive.
PointCloud<PointNormal>::ConstPtr aligned (new PointCloud<PointNormal>(cloud_src));
vis->runOnVisualizationThreadOnce(show_aligned(ci, aligned));
}
private:
int ci;
visualization::CloudViewer *vis;
};
/** Detector */
const double Detector::keypoint_separation = 0.1;
const int Detector::max_votes = 100;
const int Detector::num_registration = 4;
/* Trains a single model */
void Detector::train(Scene &scene) {
srand(0);
IndicesPtr keypoints = computeKeypoints(scene.cloud);
PointCloud<Detector::Signature>::Ptr features = obtainFeatures(scene, keypoints, false);
Entry e;
e.cloud = scene.cloud;
e.indices = keypoints;
e.features = features;
e.tree = KdTree<Signature>::Ptr(new KdTreeFLANN<Signature>());
e.tree->setInputCloud(e.features);
database[scene.id] = e;
}
typedef struct {
std::string id;
float votes;
} Candidate;
bool operator<(const Candidate &a, const Candidate &b) {
return a.votes > b.votes; // sort descending
}
double Detector::get_votes(Entry &query, Entry &match) {
double votes = 0;
for (unsigned int pi = 0; pi < query.indices->size(); pi++) {
vector<int> indices;
vector<float> distances;
clock_t start = clock();
StopWatch s;
int num_found = match.tree->nearestKSearch(*query.features, pi, max_votes, indices, distances);
for (int ri = 0; ri < num_found; ri++) {
votes += 1. / (distances[ri] + numeric_limits<float>::epsilon());
//votes -= distances[ri];
}
}
return votes;
}
// TODO scene as a reference
std::string Detector::query(Scene scene, float *classifier, double *registration) {
cout << "Running a test on model " << scene.id << endl;
Entry e;
e.cloud = scene.cloud;
timer.start();
e.indices = computeKeypoints(e.cloud);
timer.stop(KEYPOINTS_TESTING);
timer.start();
e.features = obtainFeatures(scene, e.indices, true);
timer.stop(COMPUTE_FEATURES_TESTING);
// let each point cast votes
timer.start();
memset(classifier, 0, Config::num_models * sizeof(*classifier));
clock_t totalTime = 0;
float time = 0;
StopWatch s;
std::map<std::string, Entry>::iterator it;
// get top candidates
vector<Candidate> ballot;
for ( it = database.begin() ; it != database.end(); it++ ) {
std::string target_id = (*it).first;
Entry target = (*it).second;
Candidate* candidate = new Candidate;
candidate->id = target_id;
candidate->votes = get_votes(e, target);
ballot.push_back(*candidate);
}
sort(ballot.begin(), ballot.end());
time += s.getTimeSeconds();
//cout << "Total K-Nearest Search Time for Query: " << time << endl;
//timer.stop(VOTING_CLASSIFIER);
//if (vis.get()) {
//for (int ci = 0; ci < num_registration; ci++) {
//vis->runOnVisualizationThreadOnce(show_candidate(ci, database[ballot[ci].mi].cloud));
//}
//}
//run registration on top candidates
//memset(registration, 0, Config::num_models * sizeof(*registration));
std::map<std::string, double> reg_scores;
double best = numeric_limits<double>::infinity();
std::string guessed_id = "";
for (int ci = 0; ci < num_registration; ci++) {
std::string id = ballot[ci].id;
flush(cout << id << ": " << ballot[ci].votes);
reg_scores[id] = computeRegistration(e, id, ci);
cout << " / " << reg_scores[id] << endl;
if (reg_scores[id] < best) {
guessed_id = id;
best = reg_scores[id];
}
}
return guessed_id;
}
void Detector::enableVisualization() {
vis.reset(new visualization::CloudViewer("Detector Visualization"));
PointCloud<PointNormal>::Ptr sentinel (new PointCloud<PointNormal>());
sentinel->points.push_back(PointNormal());
vis->runOnVisualizationThreadOnce(create_viewports(sentinel));
}
void Detector::printTimer() {
printf(
"select training keypoints: %10.3f sec\n"
"obtain training features: %10.3f sec\n"
"build feature tree: %10.3f sec\n"
"select testing keypoints: %10.3f sec\n"
"compute testing features: %10.3f sec\n"
"voting classifier: %10.3f sec\n"
"initial alignment: %10.3f sec\n"
"ICP: %10.3f sec\n",
timer[KEYPOINTS_TRAINING],
timer[OBTAIN_FEATURES_TRAINING],
timer[BUILD_TREE],
timer[KEYPOINTS_TESTING],
timer[COMPUTE_FEATURES_TESTING],
timer[VOTING_CLASSIFIER],
timer[IA_RANSAC],
timer[ICP]
);
}
IndicesPtr Detector::computeKeypoints(PointCloud<PointNormal>::Ptr cloud) {
IndicesPtr indices (new vector<int>());
PointCloud<int> leaves;
UniformSampling<PointNormal> us;
us.setRadiusSearch(keypoint_separation);
us.setInputCloud(cloud);
us.compute(leaves);
indices->assign(leaves.points.begin(), leaves.points.end()); // can't use operator=, probably because of different allocators
return indices;
srand(0);
int r = 200;
IndicesPtr subset (new vector<int>());
for (int i = 0; i < r; i++) {
if (indices->size() == 0) {
break;
}
int pick = rand() % indices->size();
subset->push_back(indices->at(pick));
indices->erase(indices->begin() + pick);
}
cout << "Subset Size: " << subset->size() << endl;
return subset;
}
PointCloud<Detector::Signature>::Ptr Detector::computeFeatures(PointCloud<PointNormal>::Ptr cloud, IndicesPtr indices) {
cout << "computing features on " << indices->size() << " points" << endl;
PointCloud<Signature>::Ptr features (new PointCloud<Signature>());
FPFHEstimation<PointNormal, PointNormal, Signature> fpfh;
fpfh.setRadiusSearch(0.1);
fpfh.setInputCloud(cloud);
fpfh.setIndices(indices);
search::KdTree<PointNormal>::Ptr kdt (new search::KdTree<PointNormal>());
fpfh.setSearchMethod(kdt);
fpfh.setInputNormals(cloud);
fpfh.compute(*features);
if (features->points.size() != indices->size())
cout << "got " << features->points.size() << " features from " << indices->size() << " points" << endl;
return features;
}
// TODO Enum for is_test_phase
PointCloud<Detector::Signature>::Ptr Detector::obtainFeatures(Scene &scene, IndicesPtr indices, bool is_test_phase) {
std::string name_str = std::string("feature_") + scene.id;
if (is_test_phase) {
name_str += "_test";
}
else {
name_str += "_train";
}
name_str += ".pcd";
const char *name = name_str.c_str();
if (ifstream(name)) {
PointCloud<Signature>::Ptr features (new PointCloud<Signature>());
io::loadPCDFile(name, *features);
//if (features->points.size() != indices->size())
//cout << "got " << features->points.size() << " features from " << indices->size() << " points" << endl;
return features;
} else {
PointCloud<Signature>::Ptr features = computeFeatures(scene.cloud, indices);
io::savePCDFileBinary(name, *features);
return features;
}
}
double Detector::computeRegistration(Entry &source, std::string id, int ci) {
Entry& target = database[id];
typedef boost::function<void(const PointCloud<PointNormal> &cloud_src,
const vector<int> &indices_src,
const PointCloud<PointNormal> &cloud_tgt,
const vector<int> &indices_tgt)> f;
//cout << "Source: " << id << "\tSize: " << source.cloud->size() << "\tIndices Size: " << source.indices->size() << "\tFeature Size: " << source.features->size() << endl;
//cout << "Target: " << id << "\tSize: " << target.cloud->size() << "\tIndices Size: " << target.indices->size() << "\tFeature Size: " << target.features->size() << endl;
// Copy the source/target clouds with only the subset of points that
// also features calculated for them.
PointCloud<PointNormal>::Ptr source_subset(
new PointCloud<PointNormal>(*(source.cloud), *(source.indices)));
PointCloud<PointNormal>::Ptr target_subset(
new PointCloud<PointNormal>(*(target.cloud), *(target.indices)));
timer.start();
// TODO Filtering the source cloud makes it much faster when computing the
// error metric, but may not be as good
SampleConsensusInitialAlignment<PointNormal, PointNormal, Signature> ia_ransac;
ia_ransac.setMinSampleDistance(0.05);
ia_ransac.setMaxCorrespondenceDistance(0.5);
ia_ransac.setMaximumIterations(256);
ia_ransac.setInputCloud(source_subset);
ia_ransac.setSourceFeatures(source.features);
//ia_ransac.setSourceIndices(source.indices);
ia_ransac.setInputTarget(target_subset);
ia_ransac.setTargetFeatures(target.features);
//ia_ransac.setTargetIndices(target.indices);
if (vis.get()) {
f updater (visualization_callback(ci, vis.get()));
ia_ransac.registerVisualizationCallback(updater);
}
PointCloud<PointNormal>::Ptr aligned (new PointCloud<PointNormal>());
ia_ransac.align(*aligned);
timer.stop(IA_RANSAC);
timer.start();
IterativeClosestPoint<PointNormal, PointNormal> icp;
PointCloud<PointNormal>::Ptr aligned2 (new PointCloud<PointNormal>());
icp.setInputCloud(aligned);
icp.setInputTarget(target.cloud);
icp.setMaxCorrespondenceDistance(0.1);
icp.setMaximumIterations(64);
if (vis.get()) {
f updater (visualization_callback(ci, vis.get()));
icp.registerVisualizationCallback(updater);
}
icp.align(*aligned2);
timer.stop(ICP);
return icp.getFitnessScore();
}
}
}
<|endoftext|>
|
<commit_before>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角
m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
//velocity
if (m_pStates[STATE_RUN])
impulse *= m_fMaxVelocity;
else
impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
//clear collision flags
if (GetCollision())
{
m_nGround = 0;
m_nCeiling = 0;
}
// movement
do
{
// adaptive time step
float ifps = Min(time, ACTOR_BASE_IFPS);
time -= ifps;
// save old velocity
float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
// integrate velocity
m_vVelocity += impulse * (m_fAcceleration * ifps);
m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;
// damping
float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (target_velocity < EPSILON || current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
}
// clamp maximum velocity
current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (current_velocity > old_velocity)
{
if (current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
}
}
// frozen velocity
int is_frozen = 0;
if (current_velocity < frozen_velocity)
{
m_vVelocity = z * Dot(z, m_vVelocity);
is_frozen = 1;
}
}
}<commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "Engine.h"
#include "Game.h"
#include "ObjectDummy.h"
#include "BodyRigid.h"
#include "BodyDummy.h"
#include "Physics.h"
#include "ShapeCapsule.h"
#include "ActorBase.h"
#include "Visualizer.h"
#include "sys/SysControl.h"
using namespace MathLib;
#ifdef MEMORY_INFO
#define new new(__FILE__, __LINE__)
#endif // MEMORY_INFO
/*
*/
#define ACTOR_BASE_IFPS (1.0f / 60.0f)
#define ACTOR_BASE_CLAMP 89.9f
#define ACTOR_BASE_COLLISIONS 4
/*
*/
CActorBase::CActorBase()
{
m_vUp = vec3(0.0f, 0.0f, 1.0f);
m_pObject = new CObjectDummy();
m_pDummy = new CBodyDummy();
m_pShape = new CShapeCapsule(1.0f, 1.0f);
m_nFlush = 0;
m_vPosition = Vec3_zero;
m_vVelocity = Vec3_zero;
m_fPhiAngle = 0.0f; //倾斜角 二维平面坐标系中,直线向Y周延伸的方向与X轴正向之间的夹角
m_fThetaAngle = 0.0f; //方位角,正北方那条线与当前线条按照顺时针走过的角度
for (int i = 0; i < NUM_STATES; i++)
{
m_pStates[i] = 0;
m_pTimes[i] = 0.0f;
}
m_pDummy->SetEnabled(1);
m_pObject->SetBody(NULL);
m_pObject->SetBody(m_pDummy);
m_pShape->SetBody(NULL);
m_pShape->SetBody(m_pDummy);
m_pObject->SetWorldTransform(Get_Body_Transform());
m_pShape->SetRestitution(0.0f);
m_pShape->SetCollisionMask(2);
SetEnabled(1);
SetViewDirection(vec3(0.0f, 1.0f, 0.0f));
SetCollision(1);
SetCollisionRadius(0.3f);
SetCollisionHeight(1.0f);
SetFriction(2.0f);
SetMinVelocity(2.0f);
SetMaxVelocity(4.0f);
SetAcceleration(8.0f);
SetDamping(8.0f);
SetJumping(1.5f);
SetGround(0);
SetCeiling(0);
}
CActorBase::~CActorBase()
{
m_pDummy->SetObject(NULL);
delete m_pObject;
delete m_pDummy;
}
void CActorBase::SetEnabled(int enable)
{
m_nEnable = enable;
m_pDummy->SetEnabled(m_nEnable);
}
int CActorBase::IsEnabled() const
{
return m_nEnable;
}
void CActorBase::Update(float ifps)
{
if (!m_nEnable)
{
return;
}
// impulse
vec3 impulse = vec3_zero;
// ortho basis
vec3 tangent, binormal;
OrthoBasis(m_vUp, tangent, binormal);
// current basis
vec3 x = quat(m_vUp, -m_fPhiAngle) * binormal;
vec3 y = Normalize(Cross(m_vUp, x));
vec3 z = Normalize(Cross(x, y));
handle states
Update_States(1, ifps);
// old velocity
float x_velocity = Dot(x, m_vVelocity);
float y_velocity = Dot(y, m_vVelocity);
float z_velocity = Dot(z, m_vVelocity);
// movement
if (m_pStates[STATE_FORWARD]) impulse += x;
if (m_pStates[STATE_BACKWARD]) impulse -= x;
if (m_pStates[STATE_MOVE_LEFT]) impulse += y;
if (m_pStates[STATE_MOVE_RIGHT]) impulse -= y;
impulse.normalize();
//velocity
if (m_pStates[STATE_RUN])
impulse *= m_fMaxVelocity;
else
impulse *= m_fMinVelocity;
// jump
if (m_pStates[STATE_JUMP] == STATE_BEGIN)
{
impulse += z * CMathCore::Sqrt(2.0f * 9.8f * m_fJumping) / (m_fAcceleration * ifps);
}
// rotate velocity
if (GetGround())
{
m_vVelocity = x * x_velocity + y * y_velocity + z * z_velocity;
}
// time
float time = ifps * g_Engine.pPhysics->GetScale();
// target velocity
float target_velocity = Length(vec2(Dot(x, impulse), Dot(y, impulse)));
// penetration tolerance
float penetration = g_Engine.pPhysics->GetPenetrationTolerance();
float penetration_2 = penetration * 2.0f;
// frozen linear velocity
float frozen_velocity = g_Engine.pPhysics->GetFrozenLinearVelocity();
// friction
float friction = 0.0f;
if (target_velocity < EPSILON)
{
friction = m_fFriction;
}
//clear collision flags
if (GetCollision())
{
m_nGround = 0;
m_nCeiling = 0;
}
// movement
do
{
// adaptive time step
float ifps = Min(time, ACTOR_BASE_IFPS);
time -= ifps;
// save old velocity
float old_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
// integrate velocity
m_vVelocity += impulse * (m_fAcceleration * ifps);
m_vVelocity += g_Engine.pPhysics->GetGravity() * ifps;
// damping
float current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (target_velocity < EPSILON || current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * CMathCore::Exp(-m_fDamping * ifps) + z * Dot(z, m_vVelocity);
}
// clamp maximum velocity
current_velocity = Length(vec2(Dot(x, m_vVelocity), Dot(y, m_vVelocity)));
if (current_velocity > old_velocity)
{
if (current_velocity > target_velocity)
{
m_vVelocity = (x * Dot(x, m_vVelocity) + y * Dot(y, m_vVelocity)) * target_velocity / current_velocity + z * Dot(z, m_vVelocity);
}
}
// frozen velocity
int is_frozen = 0;
if (current_velocity < frozen_velocity)
{
m_vVelocity = z * Dot(z, m_vVelocity);
is_frozen = 1;
}
// integrate position
//m_vPosition += Vec3(m_vVelocity * ifps);
// world collision
}
}<|endoftext|>
|
<commit_before>#include "Advertisement.h"
Advertisement::Advertisement(void) {
path = "advertisement.txt";
}
Advertisement::~Advertisement(void) {};
string Advertisement::getAd(void) {
int numLines = 0;
string line;
ifstream file(path.c_str());
//count number of lines
while (getline(file, line))
++numLines;
//go back to begining of file
file.clear();
file.seekg(0, ios::beg);
string temp;
for (int i = 0; i < (rand() % (numLines + 1)); i++) {
getline(file, line);
}
file.close();
return line;
}
<commit_msg>fixed random line retrieval<commit_after>#include "Advertisement.h"
Advertisement::Advertisement(void) {
path = "advertisement.txt";
srand(time(NULL));
}
Advertisement::~Advertisement(void) {};
string Advertisement::getAd(void) {
int numLines = 0;
string randLine;
ifstream file(path.c_str());
if(file.is_open()) {
//count number of lines
while (getline(file, randLine))
numLines++;
//go back to begining of file
file.clear();
file.seekg(0, ios::beg);
//select a random line from file
string temp;
int randNum = rand();
for (int i = 0; i < randNum % numLines + 1; i++) {
getline(file, randLine);
}
file.close();
} else
return "Error in retrieving advertisement";
return randLine;
}
<|endoftext|>
|
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2010 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include "macros.h"
namespace Vc
{
namespace SSE
{
template<typename T> inline Vector<T>::Vector(VectorSpecialInitializerZero::ZEnum)
: Base(VectorHelper<VectorType>::zero())
{
}
template<typename T> inline Vector<T>::Vector(VectorSpecialInitializerOne::OEnum)
: Base(VectorHelper<T>::one())
{
}
template<typename T> inline Vector<T>::Vector(VectorSpecialInitializerIndexesFromZero::IEnum)
: Base(VectorHelper<VectorType>::load(Base::_IndexesFromZero(), Aligned))
{
}
template<typename T> inline Vector<T> Vector<T>::Zero()
{
return VectorHelper<VectorType>::zero();
}
template<typename T> inline Vector<T> Vector<T>::IndexesFromZero()
{
return VectorHelper<VectorType>::load(Base::_IndexesFromZero(), Aligned);
}
template<typename T> template<typename OtherT> inline Vector<T>::Vector(const Vector<OtherT> &x)
: Base(StaticCastHelper<OtherT, T>::cast(x.data()))
{
}
template<typename T> inline Vector<T>::Vector(EntryType a)
: Base(VectorHelper<T>::set(a))
{
}
template<typename T> inline Vector<T>::Vector(const EntryType *x)
: Base(VectorHelper<VectorType>::load(x, Aligned))
{
}
template<typename T> template<typename A> inline Vector<T>::Vector(const EntryType *x, A align)
: Base(VectorHelper<VectorType>::load(x, align))
{
}
template<typename T> inline Vector<T>::Vector(const Vector<typename CtorTypeHelper<T>::Type> *a)
: Base(VectorHelper<T>::concat(a[0].data(), a[1].data()))
{
}
template<typename T> inline void Vector<T>::expand(Vector<typename ExpandTypeHelper<T>::Type> *x) const
{
if (Size == 8u) {
x[0].data() = VectorHelper<T>::expand0(data());
x[1].data() = VectorHelper<T>::expand1(data());
}
}
template<typename T> inline void Vector<T>::load(const EntryType *mem)
{
data() = VectorHelper<VectorType>::load(mem, Aligned);
}
template<typename T> template<typename A> inline void Vector<T>::load(const EntryType *mem, A align)
{
data() = VectorHelper<VectorType>::load(mem, align);
}
template<typename T> inline void Vector<T>::makeZero()
{
data() = VectorHelper<VectorType>::zero();
}
template<typename T> inline void Vector<T>::makeZero(const Mask &k)
{
data() = VectorHelper<VectorType>::andnot_(mm128_reinterpret_cast<VectorType>(k.data()), data());
}
template<typename T> inline void Vector<T>::store(EntryType *mem) const
{
VectorHelper<VectorType>::store(mem, data(), Aligned);
}
template<typename T> inline void Vector<T>::store(EntryType *mem, const Mask &mask) const
{
VectorHelper<VectorType>::store(mem, data(), mm128_reinterpret_cast<VectorType>(mask.data()));
}
template<typename T> template<typename A> inline void Vector<T>::store(EntryType *mem, A align) const
{
VectorHelper<VectorType>::store(mem, data(), align);
}
template<typename T> template<typename A> inline void Vector<T>::store(EntryType *mem, const Mask &mask, A align) const
{
store(mem, mask);
}
template<typename T> inline Vector<T> &Vector<T>::operator/=(EntryType x)
{
if (Base::HasVectorDivision) {
return operator/=(Vector<T>(x));
}
for_all_vector_entries(i,
d.m(i) /= x;
);
return *this;
}
template<typename T> inline Vector<T> Vector<T>::operator/(EntryType x) const
{
if (Base::HasVectorDivision) {
return operator/(Vector<T>(x));
}
Vector<T> r;
for_all_vector_entries(i,
r.d.m(i) = d.m(i) / x;
);
return r;
}
template<typename T> inline Vector<T> &Vector<T>::operator/=(const Vector<T> &x)
{
for_all_vector_entries(i,
d.m(i) /= x.d.m(i);
);
return *this;
}
template<typename T> inline Vector<T> Vector<T>::operator/(const Vector<T> &x) const
{
Vector<T> r;
for_all_vector_entries(i,
r.d.m(i) = d.m(i) / x.d.m(i);
);
return r;
}
template<> inline Vector<float> &Vector<float>::operator/=(const Vector<float> &x)
{
d.v() = _mm_div_ps(d.v(), x.d.v());
return *this;
}
template<> inline Vector<float> Vector<float>::operator/(const Vector<float> &x) const
{
return _mm_div_ps(d.v(), x.d.v());
}
template<> inline Vector<float8> &Vector<float8>::operator/=(const Vector<float8> &x)
{
d.v()[0] = _mm_div_ps(d.v()[0], x.d.v()[0]);
d.v()[1] = _mm_div_ps(d.v()[1], x.d.v()[1]);
return *this;
}
template<> inline Vector<float8> Vector<float8>::operator/(const Vector<float8> &x) const
{
Vector<float8> r;
r.d.v()[0] = _mm_div_ps(d.v()[0], x.d.v()[0]);
r.d.v()[1] = _mm_div_ps(d.v()[1], x.d.v()[1]);
return r;
}
template<> inline Vector<double> &Vector<double>::operator/=(const Vector<double> &x)
{
d.v() = _mm_div_pd(d.v(), x.d.v());
return *this;
}
template<> inline Vector<double> Vector<double>::operator/(const Vector<double> &x) const
{
return _mm_div_pd(d.v(), x.d.v());
}
#define OP_IMPL(T, symbol, fun) \
template<> inline Vector<T> &VectorBase<T>::operator symbol##=(const VectorBase<T> &x) \
{ \
d.v() = VectorHelper<T>::fun(d.v(), x.d.v()); \
return *static_cast<Vector<T> *>(this); \
} \
template<> inline Vector<T> VectorBase<T>::operator symbol(const VectorBase<T> &x) const \
{ \
return Vector<T>(VectorHelper<T>::fun(d.v(), x.d.v())); \
}
OP_IMPL(int, &, and_)
OP_IMPL(int, |, or_)
OP_IMPL(int, ^, xor_)
OP_IMPL(int, <<, sll)
OP_IMPL(int, >>, srl)
OP_IMPL(unsigned int, &, and_)
OP_IMPL(unsigned int, |, or_)
OP_IMPL(unsigned int, ^, xor_)
OP_IMPL(unsigned int, <<, sll)
OP_IMPL(unsigned int, >>, srl)
OP_IMPL(short, &, and_)
OP_IMPL(short, |, or_)
OP_IMPL(short, ^, xor_)
OP_IMPL(short, <<, sll)
OP_IMPL(short, >>, srl)
OP_IMPL(unsigned short, &, and_)
OP_IMPL(unsigned short, |, or_)
OP_IMPL(unsigned short, ^, xor_)
OP_IMPL(unsigned short, <<, sll)
OP_IMPL(unsigned short, >>, srl)
#undef OP_IMPL
#define OP_IMPL(T, SUFFIX) \
template<> inline Vector<T> &VectorBase<T>::operator<<=(int x) \
{ \
d.v() = CAT(_mm_slli_epi, SUFFIX)(d.v(), x); \
return *static_cast<Vector<T> *>(this); \
} \
template<> inline Vector<T> &VectorBase<T>::operator>>=(int x) \
{ \
d.v() = CAT(_mm_srli_epi, SUFFIX)(d.v(), x); \
return *static_cast<Vector<T> *>(this); \
} \
template<> inline Vector<T> VectorBase<T>::operator<<(int x) const \
{ \
return CAT(_mm_slli_epi, SUFFIX)(d.v(), x); \
} \
template<> inline Vector<T> VectorBase<T>::operator>>(int x) const \
{ \
return CAT(_mm_srli_epi, SUFFIX)(d.v(), x); \
}
OP_IMPL(int, 32)
OP_IMPL(unsigned int, 32)
OP_IMPL(short, 16)
OP_IMPL(unsigned short, 16)
#undef OP_IMPL
} // namespace SSE
} // namespace Vc
#include "undomacros.h"
<commit_msg>unused parameter; add comment that store(T*, Mask) is unaligned<commit_after>/* This file is part of the Vc library.
Copyright (C) 2010 Matthias Kretz <kretz@kde.org>
Vc is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
Vc is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include "macros.h"
namespace Vc
{
namespace SSE
{
template<typename T> inline Vector<T>::Vector(VectorSpecialInitializerZero::ZEnum)
: Base(VectorHelper<VectorType>::zero())
{
}
template<typename T> inline Vector<T>::Vector(VectorSpecialInitializerOne::OEnum)
: Base(VectorHelper<T>::one())
{
}
template<typename T> inline Vector<T>::Vector(VectorSpecialInitializerIndexesFromZero::IEnum)
: Base(VectorHelper<VectorType>::load(Base::_IndexesFromZero(), Aligned))
{
}
template<typename T> inline Vector<T> Vector<T>::Zero()
{
return VectorHelper<VectorType>::zero();
}
template<typename T> inline Vector<T> Vector<T>::IndexesFromZero()
{
return VectorHelper<VectorType>::load(Base::_IndexesFromZero(), Aligned);
}
template<typename T> template<typename OtherT> inline Vector<T>::Vector(const Vector<OtherT> &x)
: Base(StaticCastHelper<OtherT, T>::cast(x.data()))
{
}
template<typename T> inline Vector<T>::Vector(EntryType a)
: Base(VectorHelper<T>::set(a))
{
}
template<typename T> inline Vector<T>::Vector(const EntryType *x)
: Base(VectorHelper<VectorType>::load(x, Aligned))
{
}
template<typename T> template<typename A> inline Vector<T>::Vector(const EntryType *x, A align)
: Base(VectorHelper<VectorType>::load(x, align))
{
}
template<typename T> inline Vector<T>::Vector(const Vector<typename CtorTypeHelper<T>::Type> *a)
: Base(VectorHelper<T>::concat(a[0].data(), a[1].data()))
{
}
template<typename T> inline void Vector<T>::expand(Vector<typename ExpandTypeHelper<T>::Type> *x) const
{
if (Size == 8u) {
x[0].data() = VectorHelper<T>::expand0(data());
x[1].data() = VectorHelper<T>::expand1(data());
}
}
template<typename T> inline void Vector<T>::load(const EntryType *mem)
{
data() = VectorHelper<VectorType>::load(mem, Aligned);
}
template<typename T> template<typename A> inline void Vector<T>::load(const EntryType *mem, A align)
{
data() = VectorHelper<VectorType>::load(mem, align);
}
template<typename T> inline void Vector<T>::makeZero()
{
data() = VectorHelper<VectorType>::zero();
}
template<typename T> inline void Vector<T>::makeZero(const Mask &k)
{
data() = VectorHelper<VectorType>::andnot_(mm128_reinterpret_cast<VectorType>(k.data()), data());
}
template<typename T> inline void Vector<T>::store(EntryType *mem) const
{
VectorHelper<VectorType>::store(mem, data(), Aligned);
}
template<typename T> inline void Vector<T>::store(EntryType *mem, const Mask &mask) const
{
// this executes an unaligned store because SSE does not implement aligned masked stores
VectorHelper<VectorType>::store(mem, data(), mm128_reinterpret_cast<VectorType>(mask.data()));
}
template<typename T> template<typename A> inline void Vector<T>::store(EntryType *mem, A align) const
{
VectorHelper<VectorType>::store(mem, data(), align);
}
template<typename T> template<typename A> inline void Vector<T>::store(EntryType *mem, const Mask &mask, A) const
{
store(mem, mask);
}
template<typename T> inline Vector<T> &Vector<T>::operator/=(EntryType x)
{
if (Base::HasVectorDivision) {
return operator/=(Vector<T>(x));
}
for_all_vector_entries(i,
d.m(i) /= x;
);
return *this;
}
template<typename T> inline Vector<T> Vector<T>::operator/(EntryType x) const
{
if (Base::HasVectorDivision) {
return operator/(Vector<T>(x));
}
Vector<T> r;
for_all_vector_entries(i,
r.d.m(i) = d.m(i) / x;
);
return r;
}
template<typename T> inline Vector<T> &Vector<T>::operator/=(const Vector<T> &x)
{
for_all_vector_entries(i,
d.m(i) /= x.d.m(i);
);
return *this;
}
template<typename T> inline Vector<T> Vector<T>::operator/(const Vector<T> &x) const
{
Vector<T> r;
for_all_vector_entries(i,
r.d.m(i) = d.m(i) / x.d.m(i);
);
return r;
}
template<> inline Vector<float> &Vector<float>::operator/=(const Vector<float> &x)
{
d.v() = _mm_div_ps(d.v(), x.d.v());
return *this;
}
template<> inline Vector<float> Vector<float>::operator/(const Vector<float> &x) const
{
return _mm_div_ps(d.v(), x.d.v());
}
template<> inline Vector<float8> &Vector<float8>::operator/=(const Vector<float8> &x)
{
d.v()[0] = _mm_div_ps(d.v()[0], x.d.v()[0]);
d.v()[1] = _mm_div_ps(d.v()[1], x.d.v()[1]);
return *this;
}
template<> inline Vector<float8> Vector<float8>::operator/(const Vector<float8> &x) const
{
Vector<float8> r;
r.d.v()[0] = _mm_div_ps(d.v()[0], x.d.v()[0]);
r.d.v()[1] = _mm_div_ps(d.v()[1], x.d.v()[1]);
return r;
}
template<> inline Vector<double> &Vector<double>::operator/=(const Vector<double> &x)
{
d.v() = _mm_div_pd(d.v(), x.d.v());
return *this;
}
template<> inline Vector<double> Vector<double>::operator/(const Vector<double> &x) const
{
return _mm_div_pd(d.v(), x.d.v());
}
#define OP_IMPL(T, symbol, fun) \
template<> inline Vector<T> &VectorBase<T>::operator symbol##=(const VectorBase<T> &x) \
{ \
d.v() = VectorHelper<T>::fun(d.v(), x.d.v()); \
return *static_cast<Vector<T> *>(this); \
} \
template<> inline Vector<T> VectorBase<T>::operator symbol(const VectorBase<T> &x) const \
{ \
return Vector<T>(VectorHelper<T>::fun(d.v(), x.d.v())); \
}
OP_IMPL(int, &, and_)
OP_IMPL(int, |, or_)
OP_IMPL(int, ^, xor_)
OP_IMPL(int, <<, sll)
OP_IMPL(int, >>, srl)
OP_IMPL(unsigned int, &, and_)
OP_IMPL(unsigned int, |, or_)
OP_IMPL(unsigned int, ^, xor_)
OP_IMPL(unsigned int, <<, sll)
OP_IMPL(unsigned int, >>, srl)
OP_IMPL(short, &, and_)
OP_IMPL(short, |, or_)
OP_IMPL(short, ^, xor_)
OP_IMPL(short, <<, sll)
OP_IMPL(short, >>, srl)
OP_IMPL(unsigned short, &, and_)
OP_IMPL(unsigned short, |, or_)
OP_IMPL(unsigned short, ^, xor_)
OP_IMPL(unsigned short, <<, sll)
OP_IMPL(unsigned short, >>, srl)
#undef OP_IMPL
#define OP_IMPL(T, SUFFIX) \
template<> inline Vector<T> &VectorBase<T>::operator<<=(int x) \
{ \
d.v() = CAT(_mm_slli_epi, SUFFIX)(d.v(), x); \
return *static_cast<Vector<T> *>(this); \
} \
template<> inline Vector<T> &VectorBase<T>::operator>>=(int x) \
{ \
d.v() = CAT(_mm_srli_epi, SUFFIX)(d.v(), x); \
return *static_cast<Vector<T> *>(this); \
} \
template<> inline Vector<T> VectorBase<T>::operator<<(int x) const \
{ \
return CAT(_mm_slli_epi, SUFFIX)(d.v(), x); \
} \
template<> inline Vector<T> VectorBase<T>::operator>>(int x) const \
{ \
return CAT(_mm_srli_epi, SUFFIX)(d.v(), x); \
}
OP_IMPL(int, 32)
OP_IMPL(unsigned int, 32)
OP_IMPL(short, 16)
OP_IMPL(unsigned short, 16)
#undef OP_IMPL
} // namespace SSE
} // namespace Vc
#include "undomacros.h"
<|endoftext|>
|
<commit_before>#include <common/buffer.h>
#include <ssh/ssh_algorithm_negotiation.h>
#include <ssh/ssh_mac.h>
#include <ssh/ssh_session.h>
namespace {
struct ssh_mac_algorithm {
const char *rfc4250_name_;
CryptoMAC::Algorithm crypto_algorithm_;
unsigned size_;
};
static const struct ssh_mac_algorithm ssh_mac_algorithms[] = {
{ "hmac-sha1", CryptoMAC::SHA1, 0 },
{ "hmac-sha256", CryptoMAC::SHA256, 0 },
{ "hmac-md5", CryptoMAC::MD5, 0 },
{ "hmac-ripemd160", CryptoMAC::RIPEMD160, 0 },
{ "hmac-sha1-96", CryptoMAC::SHA1, 12 },
{ "hmac-md5-96", CryptoMAC::MD5, 12 },
{ NULL, CryptoMAC::MD5, 0 }
};
class CryptoSSHMAC : public SSH::MAC {
LogHandle log_;
CryptoMAC::Instance *instance_;
public:
CryptoSSHMAC(const std::string& xname, CryptoMAC::Instance *instance, unsigned xsize)
: SSH::MAC(xname, xsize == 0 ? instance->size() : xsize, instance->size()),
log_("/ssh/mac/crypto/" + xname),
instance_(instance)
{ }
~CryptoSSHMAC()
{ }
MAC *clone(void) const
{
return (new CryptoSSHMAC(name_, instance_->clone(), key_size_));
}
bool initialize(const Buffer *key)
{
return (instance_->initialize(key));
}
bool mac(Buffer *out, const Buffer *in)
{
return (instance_->mac(out, in));
}
};
}
void
SSH::MAC::add_algorithms(Session *session)
{
const struct ssh_mac_algorithm *alg;
for (alg = ssh_mac_algorithms; alg->rfc4250_name_ != NULL; alg++) {
const CryptoMAC::Method *method = CryptoMAC::Method::method(alg->crypto_algorithm_);
if (method == NULL) {
DEBUG("/ssh/mac") << "Could not get method for algorithm: " << alg->crypto_algorithm_;
continue;
}
CryptoMAC::Instance *instance = method->instance(alg->crypto_algorithm_);
if (instance == NULL) {
DEBUG("/ssh/mac") << "Could not get instance for algorithm: " << alg->crypto_algorithm_;
continue;
}
session->algorithm_negotiation_->add_algorithm(new CryptoSSHMAC(alg->rfc4250_name_, instance, alg->size_));
}
}
SSH::MAC *
SSH::MAC::algorithm(CryptoMAC::Algorithm xalgorithm)
{
const struct ssh_mac_algorithm *alg;
for (alg = ssh_mac_algorithms; alg->rfc4250_name_ != NULL; alg++) {
if (xalgorithm != alg->crypto_algorithm_)
continue;
const CryptoMAC::Method *method = CryptoMAC::Method::method(xalgorithm);
if (method == NULL) {
ERROR("/ssh/mac") << "Could not get method for algorithm: " << xalgorithm;
return (NULL);
}
CryptoMAC::Instance *instance = method->instance(xalgorithm);
if (instance == NULL) {
ERROR("/ssh/mac") << "Could not get instance for algorithm: " << xalgorithm;
return (NULL);
}
return (new CryptoSSHMAC(alg->rfc4250_name_, instance, alg->size_));
}
ERROR("/ssh/mac") << "No SSH MAC support is available for algorithm: " << xalgorithm;
return (NULL);
}
<commit_msg>Adjust algorithms.<commit_after>#include <common/buffer.h>
#include <ssh/ssh_algorithm_negotiation.h>
#include <ssh/ssh_mac.h>
#include <ssh/ssh_session.h>
namespace {
struct ssh_mac_algorithm {
const char *rfc4250_name_;
CryptoMAC::Algorithm crypto_algorithm_;
unsigned size_;
};
static const struct ssh_mac_algorithm ssh_mac_algorithms[] = {
{ "hmac-sha1", CryptoMAC::SHA1, 0 },
{ "hmac-sha2-256", CryptoMAC::SHA256, 0 },
{ "hmac-sha2-512", CryptoMAC::SHA512, 0 },
{ "hmac-ripemd160", CryptoMAC::RIPEMD160, 0 },
{ "hmac-md5", CryptoMAC::MD5, 0 },
{ "hmac-sha1-96", CryptoMAC::SHA1, 12 },
{ "hmac-md5-96", CryptoMAC::MD5, 12 },
{ NULL, CryptoMAC::MD5, 0 }
};
class CryptoSSHMAC : public SSH::MAC {
LogHandle log_;
CryptoMAC::Instance *instance_;
public:
CryptoSSHMAC(const std::string& xname, CryptoMAC::Instance *instance, unsigned xsize)
: SSH::MAC(xname, xsize == 0 ? instance->size() : xsize, instance->size()),
log_("/ssh/mac/crypto/" + xname),
instance_(instance)
{ }
~CryptoSSHMAC()
{ }
MAC *clone(void) const
{
return (new CryptoSSHMAC(name_, instance_->clone(), key_size_));
}
bool initialize(const Buffer *key)
{
return (instance_->initialize(key));
}
bool mac(Buffer *out, const Buffer *in)
{
return (instance_->mac(out, in));
}
};
}
void
SSH::MAC::add_algorithms(Session *session)
{
const struct ssh_mac_algorithm *alg;
for (alg = ssh_mac_algorithms; alg->rfc4250_name_ != NULL; alg++) {
const CryptoMAC::Method *method = CryptoMAC::Method::method(alg->crypto_algorithm_);
if (method == NULL) {
DEBUG("/ssh/mac") << "Could not get method for algorithm: " << alg->crypto_algorithm_;
continue;
}
CryptoMAC::Instance *instance = method->instance(alg->crypto_algorithm_);
if (instance == NULL) {
DEBUG("/ssh/mac") << "Could not get instance for algorithm: " << alg->crypto_algorithm_;
continue;
}
session->algorithm_negotiation_->add_algorithm(new CryptoSSHMAC(alg->rfc4250_name_, instance, alg->size_));
}
}
SSH::MAC *
SSH::MAC::algorithm(CryptoMAC::Algorithm xalgorithm)
{
const struct ssh_mac_algorithm *alg;
for (alg = ssh_mac_algorithms; alg->rfc4250_name_ != NULL; alg++) {
if (xalgorithm != alg->crypto_algorithm_)
continue;
const CryptoMAC::Method *method = CryptoMAC::Method::method(xalgorithm);
if (method == NULL) {
ERROR("/ssh/mac") << "Could not get method for algorithm: " << xalgorithm;
return (NULL);
}
CryptoMAC::Instance *instance = method->instance(xalgorithm);
if (instance == NULL) {
ERROR("/ssh/mac") << "Could not get instance for algorithm: " << xalgorithm;
return (NULL);
}
return (new CryptoSSHMAC(alg->rfc4250_name_, instance, alg->size_));
}
ERROR("/ssh/mac") << "No SSH MAC support is available for algorithm: " << xalgorithm;
return (NULL);
}
<|endoftext|>
|
<commit_before>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
typedef ssize_t (*ReadSignature)(int, void*, size_t);
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::string printBuffer;
thread_local std::string::iterator printBufferPos;
thread_local std::vector<std::string> history;
thread_local std::vector<std::string>::iterator historyPos;
static void readHistory() {
if (history.size()) return;
std::string historyFileName(getenv("HOME"));
historyFileName += "/.bash_history";
std::ifstream historyFile(historyFileName);
std::string line;
while (std::getline(historyFile, line))
history.push_back(line); // TODO: maybe reverse order?
}
static void newlineHandler() {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
}
static void backspaceHandler() {
if (lineBufferPos != lineBuffer.begin())
*(--lineBufferPos) = 0;
}
std::string findCompletion(std::vector<std::string>::iterator start, const std::string &pattern) {
for (auto it = start - 1; it > history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyPos = it;
return *it;
}
}
historyPos = history.end();
return pattern;
}
void printCompletion(std::vector<std::string>::iterator startIterator) {
std::string pattern(lineBuffer.data());
auto completion = findCompletion(startIterator, pattern);
cursor_forward(1);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + 1);
fflush(stdout);
}
void regularCharHandler(char c) {
*lineBufferPos = c;
lineBufferPos++;
printCompletion(history.end());
}
void tabHandler() {
printCompletion(historyPos);
}
static unsigned char yebash(unsigned char c) {
static char arrowIndicator = 0;
// TODO: uncomment later
//if (!getenv("YEBASH"))
// return;
readHistory();
switch (c) {
case 0x06: // ctrl+f
// FIXME: SEGFAULT
tabHandler();
c = 0;
break;
case 0x0d: // newline
newlineHandler();
break;
case 0x1b: // first arrow char
arrowIndicator = 1;
break;
case 0x5b: // second ...
if (arrowIndicator == 1)
arrowIndicator = 2;
else regularCharHandler(c);
break;
case 0x43: // third ...
if (arrowIndicator == 2) {
arrowIndicator = 0;
} else regularCharHandler(c);
try {
printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());
printBufferPos = printBuffer.begin();
} catch (...) {
// FIXME:
}
break;
case 0x17: // ctrl+w
newlineHandler(); // TODO: this has to clear lineBuffer
break;
case 0x7f: // backspace
backspaceHandler();
break;
default: // regular char or other special chars
if (c < 0x20)
newlineHandler();
else
regularCharHandler(c);
break;
}
return c;
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
static thread_local ReadSignature realRead = nullptr;
if (fd == 0) {
if (printBuffer.length()) {
*reinterpret_cast<char *>(buf) = *printBufferPos;
*lineBufferPos = *printBufferPos++; // TODO: reapeted code
lineBufferPos++;
if (printBufferPos == printBuffer.end()) {
printBuffer.erase(printBuffer.begin(), printBuffer.end());
}
return 1;
}
}
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (fd == 0 && isatty(fileno(stdin)))
*reinterpret_cast<unsigned char *>(buf) = yebash(*reinterpret_cast<unsigned char *>(buf));
return returnValue;
}
<commit_msg>Add dummy cleaning after every history suggestion<commit_after>#include <dlfcn.h>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>
#include <array>
#include <string>
#define cursor_forward(x) printf("\033[%dC", static_cast<int>(x))
#define cursor_backward(x) printf("\033[%dD", static_cast<int>(x))
typedef ssize_t (*ReadSignature)(int, void*, size_t);
thread_local std::array<char, 1024> lineBuffer;
thread_local auto lineBufferPos = lineBuffer.begin();
thread_local std::string printBuffer;
thread_local std::string::iterator printBufferPos;
thread_local std::vector<std::string> history;
thread_local std::vector<std::string>::iterator historyPos;
static void readHistory() {
if (history.size()) return;
std::string historyFileName(getenv("HOME"));
historyFileName += "/.bash_history";
std::ifstream historyFile(historyFileName);
std::string line;
while (std::getline(historyFile, line))
history.push_back(line); // TODO: maybe reverse order?
}
static void newlineHandler() {
lineBuffer.fill(0);
lineBufferPos = lineBuffer.begin();
}
static void backspaceHandler() {
if (lineBufferPos != lineBuffer.begin())
*(--lineBufferPos) = 0;
}
std::string findCompletion(std::vector<std::string>::iterator start, const std::string &pattern) {
for (auto it = start - 1; it > history.begin(); it--) {
if (it->compare(0, pattern.length(), pattern) == 0) {
historyPos = it;
return *it;
}
}
historyPos = history.end();
return pattern;
}
void clearTerminalLine() {
// TODO: get info about terminal width and current cursor position
// and fix below loops
for (int i = 0; i < 30; i++)
printf(" ");
for (int i = 0; i < 30; i++)
cursor_backward(1);
}
void printCompletion(std::vector<std::string>::iterator startIterator) {
std::string pattern(lineBuffer.data());
auto completion = findCompletion(startIterator, pattern);
clearTerminalLine();
cursor_forward(1);
printf("\e[1;30m%s\e[0m", completion.c_str() + pattern.length());
cursor_backward(completion.length() - pattern.length() + 1);
fflush(stdout);
}
void regularCharHandler(char c) {
*lineBufferPos = c;
lineBufferPos++;
printCompletion(history.end());
}
void tabHandler() {
printCompletion(historyPos);
}
static unsigned char yebash(unsigned char c) {
static char arrowIndicator = 0;
// TODO: uncomment later
//if (!getenv("YEBASH"))
// return;
readHistory();
switch (c) {
case 0x06: // ctrl+f
// FIXME: SEGFAULT
tabHandler();
c = 0;
break;
case 0x0d: // newline
newlineHandler();
break;
case 0x1b: // first arrow char
arrowIndicator = 1;
break;
case 0x5b: // second ...
if (arrowIndicator == 1)
arrowIndicator = 2;
else regularCharHandler(c);
break;
case 0x43: // third ...
if (arrowIndicator == 2) {
arrowIndicator = 0;
} else regularCharHandler(c);
try {
printBuffer = historyPos->substr(lineBufferPos - lineBuffer.begin());
printBufferPos = printBuffer.begin();
} catch (...) {
// FIXME:
}
break;
case 0x17: // ctrl+w
newlineHandler(); // TODO: this has to clear lineBuffer only
break;
case 0x7f: // backspace
backspaceHandler();
break;
default: // regular char or other special chars
if (c < 0x20)
newlineHandler();
else
regularCharHandler(c);
break;
}
return c;
}
ssize_t read(int fd, void *buf, size_t count) {
ssize_t returnValue;
static thread_local ReadSignature realRead = nullptr;
if (fd == 0) { // TODO: make it look good
if (printBuffer.length()) {
// Return printBuffer to bash one char at time
*reinterpret_cast<char *>(buf) = *printBufferPos;
*lineBufferPos = *printBufferPos++; // TODO: reapeted code
lineBufferPos++;
if (printBufferPos == printBuffer.end()) {
printBuffer.erase(printBuffer.begin(), printBuffer.end());
}
return 1;
}
}
if (!realRead)
realRead = reinterpret_cast<ReadSignature>(dlsym(RTLD_NEXT, "read"));
returnValue = realRead(fd, buf, count);
if (fd == 0 && isatty(fileno(stdin)))
*reinterpret_cast<unsigned char *>(buf) = yebash(*reinterpret_cast<unsigned char *>(buf));
return returnValue;
}
<|endoftext|>
|
<commit_before>//===- ReaderWrappers.cpp - Parse bytecode from file or buffer -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements loading and parsing a bytecode file and parsing a
// bytecode module from a given buffer.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Reader.h"
#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "Support/StringExtras.h"
#include "Config/fcntl.h"
#include <sys/stat.h>
#include "Config/unistd.h"
#include "Config/sys/mman.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// BytecodeFileReader - Read from an mmap'able file descriptor.
//
namespace {
/// FDHandle - Simple handle class to make sure a file descriptor gets closed
/// when the object is destroyed.
///
class FDHandle {
int FD;
public:
FDHandle(int fd) : FD(fd) {}
operator int() const { return FD; }
~FDHandle() {
if (FD != -1) close(FD);
}
};
/// BytecodeFileReader - parses a bytecode file from a file
///
class BytecodeFileReader : public BytecodeParser {
private:
unsigned char *Buffer;
int Length;
BytecodeFileReader(const BytecodeFileReader&); // Do not implement
void operator=(const BytecodeFileReader &BFR); // Do not implement
public:
BytecodeFileReader(const std::string &Filename);
~BytecodeFileReader();
};
}
BytecodeFileReader::BytecodeFileReader(const std::string &Filename) {
FDHandle FD = open(Filename.c_str(), O_RDONLY);
if (FD == -1)
throw std::string("Error opening file!");
// Stat the file to get its length...
struct stat StatBuf;
if (fstat(FD, &StatBuf) == -1 || StatBuf.st_size == 0)
throw std::string("Error stat'ing file!");
// mmap in the file all at once...
Length = StatBuf.st_size;
Buffer = (unsigned char*)mmap(0, Length, PROT_READ, MAP_PRIVATE, FD, 0);
if (Buffer == (unsigned char*)MAP_FAILED)
throw std::string("Error mmapping file!");
try {
// Parse the bytecode we mmapped in
ParseBytecode(Buffer, Length, Filename);
} catch (...) {
munmap((char*)Buffer, Length);
throw;
}
}
BytecodeFileReader::~BytecodeFileReader() {
// Unmmap the bytecode...
munmap((char*)Buffer, Length);
}
//===----------------------------------------------------------------------===//
// BytecodeBufferReader - Read from a memory buffer
//
namespace {
/// BytecodeBufferReader - parses a bytecode file from a buffer
///
class BytecodeBufferReader : public BytecodeParser {
private:
const unsigned char *Buffer;
bool MustDelete;
BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
void operator=(const BytecodeBufferReader &BFR); // Do not implement
public:
BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
const std::string &ModuleID);
~BytecodeBufferReader();
};
}
BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
unsigned Length,
const std::string &ModuleID)
{
// If not aligned, allocate a new buffer to hold the bytecode...
const unsigned char *ParseBegin = 0;
if ((intptr_t)Buf & 3) {
Buffer = new unsigned char[Length+4];
unsigned Offset = 4 - ((intptr_t)Buffer & 3); // Make sure it's aligned
ParseBegin = Buffer + Offset;
memcpy((unsigned char*)ParseBegin, Buf, Length); // Copy it over
MustDelete = true;
} else {
// If we don't need to copy it over, just use the caller's copy
ParseBegin = Buffer = Buf;
MustDelete = false;
}
try {
ParseBytecode(ParseBegin, Length, ModuleID);
} catch (...) {
if (MustDelete) delete [] Buffer;
throw;
}
}
BytecodeBufferReader::~BytecodeBufferReader() {
if (MustDelete) delete [] Buffer;
}
//===----------------------------------------------------------------------===//
// BytecodeStdinReader - Read bytecode from Standard Input
//
namespace {
/// BytecodeStdinReader - parses a bytecode file from stdin
///
class BytecodeStdinReader : public BytecodeParser {
private:
std::vector<unsigned char> FileData;
unsigned char *FileBuf;
BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
void operator=(const BytecodeStdinReader &BFR); // Do not implement
public:
BytecodeStdinReader();
};
}
BytecodeStdinReader::BytecodeStdinReader() {
int BlockSize;
unsigned char Buffer[4096*4];
// Read in all of the data from stdin, we cannot mmap stdin...
while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
if (BlockSize == -1)
throw std::string("Error reading from stdin!");
FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
}
if (FileData.empty())
throw std::string("Standard Input empty!");
FileBuf = &FileData[0];
ParseBytecode(FileBuf, FileData.size(), "<stdin>");
}
//===----------------------------------------------------------------------===//
// Varargs transmogrification code...
//
// CheckVarargs - This is used to automatically translate old-style varargs to
// new style varargs for backwards compatibility.
static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
Module *M = MP->getModule();
// Check to see if va_start takes arguments...
Function *F = M->getNamedFunction("llvm.va_start");
if (F == 0) return MP; // No varargs use, just return.
if (F->getFunctionType()->getNumParams() == 0)
return MP; // Modern varargs processing, just return.
// If we get to this point, we know that we have an old-style module.
// Materialize the whole thing to perform the rewriting.
MP->materializeModule();
// If the user is making use of obsolete varargs intrinsics, adjust them for
// the user.
if (Function *F = M->getNamedFunction("llvm.va_start")) {
assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
const Type *RetTy = F->getFunctionType()->getParamType(0);
RetTy = cast<PointerType>(RetTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_end")) {
assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new LoadInst(CI->getOperand(1), "", CI);
new CallInst(NF, V, "", CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_copy")) {
assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
return MP;
}
//===----------------------------------------------------------------------===//
// Wrapper functions
//===----------------------------------------------------------------------===//
/// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
/// buffer
ModuleProvider*
llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
unsigned Length,
const std::string &ModuleID) {
return CheckVarargs(new BytecodeBufferReader(Buffer, Length, ModuleID));
}
/// ParseBytecodeBuffer - Parse a given bytecode buffer
///
Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
const std::string &ModuleID,
std::string *ErrorStr){
try {
std::auto_ptr<ModuleProvider>
AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
/// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
///
ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename) {
if (Filename != std::string("-")) // Read from a file...
return CheckVarargs(new BytecodeFileReader(Filename));
else // Read from stdin
return CheckVarargs(new BytecodeStdinReader());
}
/// ParseBytecodeFile - Parse the given bytecode file
///
Module *llvm::ParseBytecodeFile(const std::string &Filename,
std::string *ErrorStr) {
try {
std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
<commit_msg>Throw better error messages, by calling strerror(errno) when we get an error inside the bytecode reader.<commit_after>//===- ReaderWrappers.cpp - Parse bytecode from file or buffer -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements loading and parsing a bytecode file and parsing a
// bytecode module from a given buffer.
//
//===----------------------------------------------------------------------===//
#include "llvm/Bytecode/Reader.h"
#include "ReaderInternals.h"
#include "llvm/Module.h"
#include "llvm/Instructions.h"
#include "Support/StringExtras.h"
#include "Config/fcntl.h"
#include <sys/stat.h>
#include <cerrno>
#include "Config/unistd.h"
#include "Config/sys/mman.h"
using namespace llvm;
//===----------------------------------------------------------------------===//
// BytecodeFileReader - Read from an mmap'able file descriptor.
//
namespace {
/// FDHandle - Simple handle class to make sure a file descriptor gets closed
/// when the object is destroyed.
///
class FDHandle {
int FD;
public:
FDHandle(int fd) : FD(fd) {}
operator int() const { return FD; }
~FDHandle() {
if (FD != -1) close(FD);
}
};
/// BytecodeFileReader - parses a bytecode file from a file
///
class BytecodeFileReader : public BytecodeParser {
private:
unsigned char *Buffer;
int Length;
BytecodeFileReader(const BytecodeFileReader&); // Do not implement
void operator=(const BytecodeFileReader &BFR); // Do not implement
public:
BytecodeFileReader(const std::string &Filename);
~BytecodeFileReader();
};
}
static std::string ErrnoMessage (int savedErrNum, std::string descr) {
return ::strerror(savedErrNum) + std::string(", while trying to ") + descr;
}
BytecodeFileReader::BytecodeFileReader(const std::string &Filename) {
FDHandle FD = open(Filename.c_str(), O_RDONLY);
if (FD == -1)
throw ErrnoMessage(errno, "open '" + Filename + "'");
// Stat the file to get its length...
struct stat StatBuf;
if (fstat(FD, &StatBuf) == -1 || StatBuf.st_size == 0)
throw ErrnoMessage(errno, "stat '" + Filename + "'");
// mmap in the file all at once...
Length = StatBuf.st_size;
Buffer = (unsigned char*)mmap(0, Length, PROT_READ, MAP_PRIVATE, FD, 0);
if (Buffer == (unsigned char*)MAP_FAILED)
throw ErrnoMessage(errno, "map '" + Filename + "' into memory");
try {
// Parse the bytecode we mmapped in
ParseBytecode(Buffer, Length, Filename);
} catch (...) {
munmap((char*)Buffer, Length);
throw;
}
}
BytecodeFileReader::~BytecodeFileReader() {
// Unmmap the bytecode...
munmap((char*)Buffer, Length);
}
//===----------------------------------------------------------------------===//
// BytecodeBufferReader - Read from a memory buffer
//
namespace {
/// BytecodeBufferReader - parses a bytecode file from a buffer
///
class BytecodeBufferReader : public BytecodeParser {
private:
const unsigned char *Buffer;
bool MustDelete;
BytecodeBufferReader(const BytecodeBufferReader&); // Do not implement
void operator=(const BytecodeBufferReader &BFR); // Do not implement
public:
BytecodeBufferReader(const unsigned char *Buf, unsigned Length,
const std::string &ModuleID);
~BytecodeBufferReader();
};
}
BytecodeBufferReader::BytecodeBufferReader(const unsigned char *Buf,
unsigned Length,
const std::string &ModuleID)
{
// If not aligned, allocate a new buffer to hold the bytecode...
const unsigned char *ParseBegin = 0;
if ((intptr_t)Buf & 3) {
Buffer = new unsigned char[Length+4];
unsigned Offset = 4 - ((intptr_t)Buffer & 3); // Make sure it's aligned
ParseBegin = Buffer + Offset;
memcpy((unsigned char*)ParseBegin, Buf, Length); // Copy it over
MustDelete = true;
} else {
// If we don't need to copy it over, just use the caller's copy
ParseBegin = Buffer = Buf;
MustDelete = false;
}
try {
ParseBytecode(ParseBegin, Length, ModuleID);
} catch (...) {
if (MustDelete) delete [] Buffer;
throw;
}
}
BytecodeBufferReader::~BytecodeBufferReader() {
if (MustDelete) delete [] Buffer;
}
//===----------------------------------------------------------------------===//
// BytecodeStdinReader - Read bytecode from Standard Input
//
namespace {
/// BytecodeStdinReader - parses a bytecode file from stdin
///
class BytecodeStdinReader : public BytecodeParser {
private:
std::vector<unsigned char> FileData;
unsigned char *FileBuf;
BytecodeStdinReader(const BytecodeStdinReader&); // Do not implement
void operator=(const BytecodeStdinReader &BFR); // Do not implement
public:
BytecodeStdinReader();
};
}
BytecodeStdinReader::BytecodeStdinReader() {
int BlockSize;
unsigned char Buffer[4096*4];
// Read in all of the data from stdin, we cannot mmap stdin...
while ((BlockSize = ::read(0 /*stdin*/, Buffer, 4096*4))) {
if (BlockSize == -1)
throw ErrnoMessage(errno, "read from standard input");
FileData.insert(FileData.end(), Buffer, Buffer+BlockSize);
}
if (FileData.empty())
throw std::string("Standard Input empty!");
FileBuf = &FileData[0];
ParseBytecode(FileBuf, FileData.size(), "<stdin>");
}
//===----------------------------------------------------------------------===//
// Varargs transmogrification code...
//
// CheckVarargs - This is used to automatically translate old-style varargs to
// new style varargs for backwards compatibility.
static ModuleProvider *CheckVarargs(ModuleProvider *MP) {
Module *M = MP->getModule();
// Check to see if va_start takes arguments...
Function *F = M->getNamedFunction("llvm.va_start");
if (F == 0) return MP; // No varargs use, just return.
if (F->getFunctionType()->getNumParams() == 0)
return MP; // Modern varargs processing, just return.
// If we get to this point, we know that we have an old-style module.
// Materialize the whole thing to perform the rewriting.
MP->materializeModule();
// If the user is making use of obsolete varargs intrinsics, adjust them for
// the user.
if (Function *F = M->getNamedFunction("llvm.va_start")) {
assert(F->asize() == 1 && "Obsolete va_start takes 1 argument!");
const Type *RetTy = F->getFunctionType()->getParamType(0);
RetTy = cast<PointerType>(RetTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_start", RetTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_end")) {
assert(F->asize() == 1 && "Obsolete va_end takes 1 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_end", Type::VoidTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new LoadInst(CI->getOperand(1), "", CI);
new CallInst(NF, V, "", CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
if (Function *F = M->getNamedFunction("llvm.va_copy")) {
assert(F->asize() == 2 && "Obsolete va_copy takes 2 argument!");
const Type *ArgTy = F->getFunctionType()->getParamType(0);
ArgTy = cast<PointerType>(ArgTy)->getElementType();
Function *NF = M->getOrInsertFunction("llvm.va_copy", ArgTy,
ArgTy, 0);
for (Value::use_iterator I = F->use_begin(), E = F->use_end(); I != E; )
if (CallInst *CI = dyn_cast<CallInst>(*I++)) {
Value *V = new CallInst(NF, CI->getOperand(2), "", CI);
new StoreInst(V, CI->getOperand(1), CI);
CI->getParent()->getInstList().erase(CI);
}
F->setName("");
}
return MP;
}
//===----------------------------------------------------------------------===//
// Wrapper functions
//===----------------------------------------------------------------------===//
/// getBytecodeBufferModuleProvider - lazy function-at-a-time loading from a
/// buffer
ModuleProvider*
llvm::getBytecodeBufferModuleProvider(const unsigned char *Buffer,
unsigned Length,
const std::string &ModuleID) {
return CheckVarargs(new BytecodeBufferReader(Buffer, Length, ModuleID));
}
/// ParseBytecodeBuffer - Parse a given bytecode buffer
///
Module *llvm::ParseBytecodeBuffer(const unsigned char *Buffer, unsigned Length,
const std::string &ModuleID,
std::string *ErrorStr){
try {
std::auto_ptr<ModuleProvider>
AMP(getBytecodeBufferModuleProvider(Buffer, Length, ModuleID));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
/// getBytecodeModuleProvider - lazy function-at-a-time loading from a file
///
ModuleProvider *llvm::getBytecodeModuleProvider(const std::string &Filename) {
if (Filename != std::string("-")) // Read from a file...
return CheckVarargs(new BytecodeFileReader(Filename));
else // Read from stdin
return CheckVarargs(new BytecodeStdinReader());
}
/// ParseBytecodeFile - Parse the given bytecode file
///
Module *llvm::ParseBytecodeFile(const std::string &Filename,
std::string *ErrorStr) {
try {
std::auto_ptr<ModuleProvider> AMP(getBytecodeModuleProvider(Filename));
return AMP->releaseModule();
} catch (std::string &err) {
if (ErrorStr) *ErrorStr = err;
return 0;
}
}
<|endoftext|>
|
<commit_before>//===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is an extremely simple MachineInstr-level copy propagation pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
#define DEBUG_TYPE "codegen-cp"
STATISTIC(NumDeletes, "Number of dead copies deleted");
namespace {
class MachineCopyPropagation : public MachineFunctionPass {
const TargetRegisterInfo *TRI;
const TargetInstrInfo *TII;
MachineRegisterInfo *MRI;
public:
static char ID; // Pass identification, replacement for typeid
MachineCopyPropagation() : MachineFunctionPass(ID) {
initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
private:
typedef SmallVector<unsigned, 4> DestList;
typedef DenseMap<unsigned, DestList> SourceMap;
void SourceNoLongerAvailable(unsigned Reg,
SourceMap &SrcMap,
DenseMap<unsigned, MachineInstr*> &AvailCopyMap);
bool CopyPropagateBlock(MachineBasicBlock &MBB);
};
}
char MachineCopyPropagation::ID = 0;
char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
INITIALIZE_PASS(MachineCopyPropagation, "machine-cp",
"Machine Copy Propagation Pass", false, false)
void
MachineCopyPropagation::SourceNoLongerAvailable(unsigned Reg,
SourceMap &SrcMap,
DenseMap<unsigned, MachineInstr*> &AvailCopyMap) {
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
SourceMap::iterator SI = SrcMap.find(*AI);
if (SI != SrcMap.end()) {
const DestList& Defs = SI->second;
for (DestList::const_iterator I = Defs.begin(), E = Defs.end();
I != E; ++I) {
unsigned MappedDef = *I;
// Source of copy is no longer available for propagation.
AvailCopyMap.erase(MappedDef);
for (MCSubRegIterator SR(MappedDef, TRI); SR.isValid(); ++SR)
AvailCopyMap.erase(*SR);
}
}
}
}
static bool NoInterveningSideEffect(const MachineInstr *CopyMI,
const MachineInstr *MI) {
const MachineBasicBlock *MBB = CopyMI->getParent();
if (MI->getParent() != MBB)
return false;
MachineBasicBlock::const_iterator I = CopyMI;
MachineBasicBlock::const_iterator E = MBB->end();
MachineBasicBlock::const_iterator E2 = MI;
++I;
while (I != E && I != E2) {
if (I->hasUnmodeledSideEffects() || I->isCall() ||
I->isTerminator())
return false;
++I;
}
return true;
}
/// isNopCopy - Return true if the specified copy is really a nop. That is
/// if the source of the copy is the same of the definition of the copy that
/// supplied the source. If the source of the copy is a sub-register than it
/// must check the sub-indices match. e.g.
/// ecx = mov eax
/// al = mov cl
/// But not
/// ecx = mov eax
/// al = mov ch
static bool isNopCopy(MachineInstr *CopyMI, unsigned Def, unsigned Src,
const TargetRegisterInfo *TRI) {
unsigned SrcSrc = CopyMI->getOperand(1).getReg();
if (Def == SrcSrc)
return true;
if (TRI->isSubRegister(SrcSrc, Def)) {
unsigned SrcDef = CopyMI->getOperand(0).getReg();
unsigned SubIdx = TRI->getSubRegIndex(SrcSrc, Def);
if (!SubIdx)
return false;
return SubIdx == TRI->getSubRegIndex(SrcDef, Src);
}
return false;
}
bool MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
SmallSetVector<MachineInstr*, 8> MaybeDeadCopies; // Candidates for deletion
DenseMap<unsigned, MachineInstr*> AvailCopyMap; // Def -> available copies map
DenseMap<unsigned, MachineInstr*> CopyMap; // Def -> copies map
SourceMap SrcMap; // Src -> Def map
DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
bool Changed = false;
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
MachineInstr *MI = &*I;
++I;
if (MI->isCopy()) {
unsigned Def = MI->getOperand(0).getReg();
unsigned Src = MI->getOperand(1).getReg();
if (TargetRegisterInfo::isVirtualRegister(Def) ||
TargetRegisterInfo::isVirtualRegister(Src))
report_fatal_error("MachineCopyPropagation should be run after"
" register allocation!");
DenseMap<unsigned, MachineInstr*>::iterator CI = AvailCopyMap.find(Src);
if (CI != AvailCopyMap.end()) {
MachineInstr *CopyMI = CI->second;
if (!MRI->isReserved(Def) &&
(!MRI->isReserved(Src) || NoInterveningSideEffect(CopyMI, MI)) &&
isNopCopy(CopyMI, Def, Src, TRI)) {
// The two copies cancel out and the source of the first copy
// hasn't been overridden, eliminate the second one. e.g.
// %ECX<def> = COPY %EAX<kill>
// ... nothing clobbered EAX.
// %EAX<def> = COPY %ECX
// =>
// %ECX<def> = COPY %EAX
//
// Also avoid eliminating a copy from reserved registers unless the
// definition is proven not clobbered. e.g.
// %RSP<def> = COPY %RAX
// CALL
// %RAX<def> = COPY %RSP
DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; MI->dump());
// Clear any kills of Def between CopyMI and MI. This extends the
// live range.
for (MachineBasicBlock::iterator I = CopyMI, E = MI; I != E; ++I)
I->clearRegisterKills(Def, TRI);
MI->eraseFromParent();
Changed = true;
++NumDeletes;
continue;
}
}
// If Src is defined by a previous copy, it cannot be eliminated.
for (MCRegAliasIterator AI(Src, TRI, true); AI.isValid(); ++AI) {
CI = CopyMap.find(*AI);
if (CI != CopyMap.end()) {
DEBUG(dbgs() << "MCP: Copy is no longer dead: "; CI->second->dump());
MaybeDeadCopies.remove(CI->second);
}
}
DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
// Copy is now a candidate for deletion.
MaybeDeadCopies.insert(MI);
// If 'Src' is previously source of another copy, then this earlier copy's
// source is no longer available. e.g.
// %xmm9<def> = copy %xmm2
// ...
// %xmm2<def> = copy %xmm0
// ...
// %xmm2<def> = copy %xmm9
SourceNoLongerAvailable(Def, SrcMap, AvailCopyMap);
// Remember Def is defined by the copy.
// ... Make sure to clear the def maps of aliases first.
for (MCRegAliasIterator AI(Def, TRI, false); AI.isValid(); ++AI) {
CopyMap.erase(*AI);
AvailCopyMap.erase(*AI);
}
for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
++SR) {
CopyMap[*SR] = MI;
AvailCopyMap[*SR] = MI;
}
// Remember source that's copied to Def. Once it's clobbered, then
// it's no longer available for copy propagation.
if (std::find(SrcMap[Src].begin(), SrcMap[Src].end(), Def) ==
SrcMap[Src].end()) {
SrcMap[Src].push_back(Def);
}
continue;
}
// Not a copy.
SmallVector<unsigned, 2> Defs;
int RegMaskOpNum = -1;
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
MachineOperand &MO = MI->getOperand(i);
if (MO.isRegMask())
RegMaskOpNum = i;
if (!MO.isReg())
continue;
unsigned Reg = MO.getReg();
if (!Reg)
continue;
if (TargetRegisterInfo::isVirtualRegister(Reg))
report_fatal_error("MachineCopyPropagation should be run after"
" register allocation!");
if (MO.isDef()) {
Defs.push_back(Reg);
continue;
}
// If 'Reg' is defined by a copy, the copy is no longer a candidate
// for elimination.
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
DenseMap<unsigned, MachineInstr*>::iterator CI = CopyMap.find(*AI);
if (CI != CopyMap.end()) {
DEBUG(dbgs() << "MCP: Copy is used - not dead: "; CI->second->dump());
MaybeDeadCopies.remove(CI->second);
}
}
// Treat undef use like defs for copy propagation but not for
// dead copy. We would need to do a liveness check to be sure the copy
// is dead for undef uses.
// The backends are allowed to do whatever they want with undef value
// and we cannot be sure this register will not be rewritten to break
// some false dependencies for the hardware for instance.
if (MO.isUndef())
Defs.push_back(Reg);
}
// The instruction has a register mask operand which means that it clobbers
// a large set of registers. It is possible to use the register mask to
// prune the available copies, but treat it like a basic block boundary for
// now.
if (RegMaskOpNum >= 0) {
// Erase any MaybeDeadCopies whose destination register is clobbered.
const MachineOperand &MaskMO = MI->getOperand(RegMaskOpNum);
for (SmallSetVector<MachineInstr*, 8>::iterator
DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
DI != DE; ++DI) {
unsigned Reg = (*DI)->getOperand(0).getReg();
if (MRI->isReserved(Reg) || !MaskMO.clobbersPhysReg(Reg))
continue;
DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
(*DI)->dump());
(*DI)->eraseFromParent();
Changed = true;
++NumDeletes;
}
// Clear all data structures as if we were beginning a new basic block.
MaybeDeadCopies.clear();
AvailCopyMap.clear();
CopyMap.clear();
SrcMap.clear();
continue;
}
for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
unsigned Reg = Defs[i];
// No longer defined by a copy.
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
CopyMap.erase(*AI);
AvailCopyMap.erase(*AI);
}
// If 'Reg' is previously source of a copy, it is no longer available for
// copy propagation.
SourceNoLongerAvailable(Reg, SrcMap, AvailCopyMap);
}
}
// If MBB doesn't have successors, delete the copies whose defs are not used.
// If MBB does have successors, then conservative assume the defs are live-out
// since we don't want to trust live-in lists.
if (MBB.succ_empty()) {
for (SmallSetVector<MachineInstr*, 8>::iterator
DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
DI != DE; ++DI) {
if (!MRI->isReserved((*DI)->getOperand(0).getReg())) {
(*DI)->eraseFromParent();
Changed = true;
++NumDeletes;
}
}
}
return Changed;
}
bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
if (skipOptnoneFunction(*MF.getFunction()))
return false;
bool Changed = false;
TRI = MF.getSubtarget().getRegisterInfo();
TII = MF.getSubtarget().getInstrInfo();
MRI = &MF.getRegInfo();
for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Changed |= CopyPropagateBlock(*I);
return Changed;
}
<commit_msg>[MachineCopyPropagation] Fix comment. NFC<commit_after>//===- MachineCopyPropagation.cpp - Machine Copy Propagation Pass ---------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This is an extremely simple MachineInstr-level copy propagation pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/Passes.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetInstrInfo.h"
#include "llvm/Target/TargetRegisterInfo.h"
#include "llvm/Target/TargetSubtargetInfo.h"
using namespace llvm;
#define DEBUG_TYPE "codegen-cp"
STATISTIC(NumDeletes, "Number of dead copies deleted");
namespace {
class MachineCopyPropagation : public MachineFunctionPass {
const TargetRegisterInfo *TRI;
const TargetInstrInfo *TII;
MachineRegisterInfo *MRI;
public:
static char ID; // Pass identification, replacement for typeid
MachineCopyPropagation() : MachineFunctionPass(ID) {
initializeMachineCopyPropagationPass(*PassRegistry::getPassRegistry());
}
bool runOnMachineFunction(MachineFunction &MF) override;
private:
typedef SmallVector<unsigned, 4> DestList;
typedef DenseMap<unsigned, DestList> SourceMap;
void SourceNoLongerAvailable(unsigned Reg,
SourceMap &SrcMap,
DenseMap<unsigned, MachineInstr*> &AvailCopyMap);
bool CopyPropagateBlock(MachineBasicBlock &MBB);
};
}
char MachineCopyPropagation::ID = 0;
char &llvm::MachineCopyPropagationID = MachineCopyPropagation::ID;
INITIALIZE_PASS(MachineCopyPropagation, "machine-cp",
"Machine Copy Propagation Pass", false, false)
void
MachineCopyPropagation::SourceNoLongerAvailable(unsigned Reg,
SourceMap &SrcMap,
DenseMap<unsigned, MachineInstr*> &AvailCopyMap) {
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
SourceMap::iterator SI = SrcMap.find(*AI);
if (SI != SrcMap.end()) {
const DestList& Defs = SI->second;
for (DestList::const_iterator I = Defs.begin(), E = Defs.end();
I != E; ++I) {
unsigned MappedDef = *I;
// Source of copy is no longer available for propagation.
AvailCopyMap.erase(MappedDef);
for (MCSubRegIterator SR(MappedDef, TRI); SR.isValid(); ++SR)
AvailCopyMap.erase(*SR);
}
}
}
}
static bool NoInterveningSideEffect(const MachineInstr *CopyMI,
const MachineInstr *MI) {
const MachineBasicBlock *MBB = CopyMI->getParent();
if (MI->getParent() != MBB)
return false;
MachineBasicBlock::const_iterator I = CopyMI;
MachineBasicBlock::const_iterator E = MBB->end();
MachineBasicBlock::const_iterator E2 = MI;
++I;
while (I != E && I != E2) {
if (I->hasUnmodeledSideEffects() || I->isCall() ||
I->isTerminator())
return false;
++I;
}
return true;
}
/// isNopCopy - Return true if the specified copy is really a nop. That is
/// if the source of the copy is the same of the definition of the copy that
/// supplied the source. If the source of the copy is a sub-register than it
/// must check the sub-indices match. e.g.
/// ecx = mov eax
/// al = mov cl
/// But not
/// ecx = mov eax
/// al = mov ch
static bool isNopCopy(MachineInstr *CopyMI, unsigned Def, unsigned Src,
const TargetRegisterInfo *TRI) {
unsigned SrcSrc = CopyMI->getOperand(1).getReg();
if (Def == SrcSrc)
return true;
if (TRI->isSubRegister(SrcSrc, Def)) {
unsigned SrcDef = CopyMI->getOperand(0).getReg();
unsigned SubIdx = TRI->getSubRegIndex(SrcSrc, Def);
if (!SubIdx)
return false;
return SubIdx == TRI->getSubRegIndex(SrcDef, Src);
}
return false;
}
bool MachineCopyPropagation::CopyPropagateBlock(MachineBasicBlock &MBB) {
SmallSetVector<MachineInstr*, 8> MaybeDeadCopies; // Candidates for deletion
DenseMap<unsigned, MachineInstr*> AvailCopyMap; // Def -> available copies map
DenseMap<unsigned, MachineInstr*> CopyMap; // Def -> copies map
SourceMap SrcMap; // Src -> Def map
DEBUG(dbgs() << "MCP: CopyPropagateBlock " << MBB.getName() << "\n");
bool Changed = false;
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end(); I != E; ) {
MachineInstr *MI = &*I;
++I;
if (MI->isCopy()) {
unsigned Def = MI->getOperand(0).getReg();
unsigned Src = MI->getOperand(1).getReg();
if (TargetRegisterInfo::isVirtualRegister(Def) ||
TargetRegisterInfo::isVirtualRegister(Src))
report_fatal_error("MachineCopyPropagation should be run after"
" register allocation!");
DenseMap<unsigned, MachineInstr*>::iterator CI = AvailCopyMap.find(Src);
if (CI != AvailCopyMap.end()) {
MachineInstr *CopyMI = CI->second;
if (!MRI->isReserved(Def) &&
(!MRI->isReserved(Src) || NoInterveningSideEffect(CopyMI, MI)) &&
isNopCopy(CopyMI, Def, Src, TRI)) {
// The two copies cancel out and the source of the first copy
// hasn't been overridden, eliminate the second one. e.g.
// %ECX<def> = COPY %EAX<kill>
// ... nothing clobbered EAX.
// %EAX<def> = COPY %ECX
// =>
// %ECX<def> = COPY %EAX
//
// Also avoid eliminating a copy from reserved registers unless the
// definition is proven not clobbered. e.g.
// %RSP<def> = COPY %RAX
// CALL
// %RAX<def> = COPY %RSP
DEBUG(dbgs() << "MCP: copy is a NOP, removing: "; MI->dump());
// Clear any kills of Def between CopyMI and MI. This extends the
// live range.
for (MachineBasicBlock::iterator I = CopyMI, E = MI; I != E; ++I)
I->clearRegisterKills(Def, TRI);
MI->eraseFromParent();
Changed = true;
++NumDeletes;
continue;
}
}
// If Src is defined by a previous copy, the previous copy cannot be
// eliminated.
for (MCRegAliasIterator AI(Src, TRI, true); AI.isValid(); ++AI) {
CI = CopyMap.find(*AI);
if (CI != CopyMap.end()) {
DEBUG(dbgs() << "MCP: Copy is no longer dead: "; CI->second->dump());
MaybeDeadCopies.remove(CI->second);
}
}
DEBUG(dbgs() << "MCP: Copy is a deletion candidate: "; MI->dump());
// Copy is now a candidate for deletion.
MaybeDeadCopies.insert(MI);
// If 'Def' is previously source of another copy, then this earlier copy's
// source is no longer available. e.g.
// %xmm9<def> = copy %xmm2
// ...
// %xmm2<def> = copy %xmm0
// ...
// %xmm2<def> = copy %xmm9
SourceNoLongerAvailable(Def, SrcMap, AvailCopyMap);
// Remember Def is defined by the copy.
// ... Make sure to clear the def maps of aliases first.
for (MCRegAliasIterator AI(Def, TRI, false); AI.isValid(); ++AI) {
CopyMap.erase(*AI);
AvailCopyMap.erase(*AI);
}
for (MCSubRegIterator SR(Def, TRI, /*IncludeSelf=*/true); SR.isValid();
++SR) {
CopyMap[*SR] = MI;
AvailCopyMap[*SR] = MI;
}
// Remember source that's copied to Def. Once it's clobbered, then
// it's no longer available for copy propagation.
if (std::find(SrcMap[Src].begin(), SrcMap[Src].end(), Def) ==
SrcMap[Src].end()) {
SrcMap[Src].push_back(Def);
}
continue;
}
// Not a copy.
SmallVector<unsigned, 2> Defs;
int RegMaskOpNum = -1;
for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i) {
MachineOperand &MO = MI->getOperand(i);
if (MO.isRegMask())
RegMaskOpNum = i;
if (!MO.isReg())
continue;
unsigned Reg = MO.getReg();
if (!Reg)
continue;
if (TargetRegisterInfo::isVirtualRegister(Reg))
report_fatal_error("MachineCopyPropagation should be run after"
" register allocation!");
if (MO.isDef()) {
Defs.push_back(Reg);
continue;
}
// If 'Reg' is defined by a copy, the copy is no longer a candidate
// for elimination.
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
DenseMap<unsigned, MachineInstr*>::iterator CI = CopyMap.find(*AI);
if (CI != CopyMap.end()) {
DEBUG(dbgs() << "MCP: Copy is used - not dead: "; CI->second->dump());
MaybeDeadCopies.remove(CI->second);
}
}
// Treat undef use like defs for copy propagation but not for
// dead copy. We would need to do a liveness check to be sure the copy
// is dead for undef uses.
// The backends are allowed to do whatever they want with undef value
// and we cannot be sure this register will not be rewritten to break
// some false dependencies for the hardware for instance.
if (MO.isUndef())
Defs.push_back(Reg);
}
// The instruction has a register mask operand which means that it clobbers
// a large set of registers. It is possible to use the register mask to
// prune the available copies, but treat it like a basic block boundary for
// now.
if (RegMaskOpNum >= 0) {
// Erase any MaybeDeadCopies whose destination register is clobbered.
const MachineOperand &MaskMO = MI->getOperand(RegMaskOpNum);
for (SmallSetVector<MachineInstr*, 8>::iterator
DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
DI != DE; ++DI) {
unsigned Reg = (*DI)->getOperand(0).getReg();
if (MRI->isReserved(Reg) || !MaskMO.clobbersPhysReg(Reg))
continue;
DEBUG(dbgs() << "MCP: Removing copy due to regmask clobbering: ";
(*DI)->dump());
(*DI)->eraseFromParent();
Changed = true;
++NumDeletes;
}
// Clear all data structures as if we were beginning a new basic block.
MaybeDeadCopies.clear();
AvailCopyMap.clear();
CopyMap.clear();
SrcMap.clear();
continue;
}
for (unsigned i = 0, e = Defs.size(); i != e; ++i) {
unsigned Reg = Defs[i];
// No longer defined by a copy.
for (MCRegAliasIterator AI(Reg, TRI, true); AI.isValid(); ++AI) {
CopyMap.erase(*AI);
AvailCopyMap.erase(*AI);
}
// If 'Reg' is previously source of a copy, it is no longer available for
// copy propagation.
SourceNoLongerAvailable(Reg, SrcMap, AvailCopyMap);
}
}
// If MBB doesn't have successors, delete the copies whose defs are not used.
// If MBB does have successors, then conservative assume the defs are live-out
// since we don't want to trust live-in lists.
if (MBB.succ_empty()) {
for (SmallSetVector<MachineInstr*, 8>::iterator
DI = MaybeDeadCopies.begin(), DE = MaybeDeadCopies.end();
DI != DE; ++DI) {
if (!MRI->isReserved((*DI)->getOperand(0).getReg())) {
(*DI)->eraseFromParent();
Changed = true;
++NumDeletes;
}
}
}
return Changed;
}
bool MachineCopyPropagation::runOnMachineFunction(MachineFunction &MF) {
if (skipOptnoneFunction(*MF.getFunction()))
return false;
bool Changed = false;
TRI = MF.getSubtarget().getRegisterInfo();
TII = MF.getSubtarget().getInstrInfo();
MRI = &MF.getRegInfo();
for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I)
Changed |= CopyPropagateBlock(*I);
return Changed;
}
<|endoftext|>
|
<commit_before>// (C) 2014 Arek Olek
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include "options.hpp"
#include "test_suite.hpp"
#include "timing.hpp"
#include "bfs.hpp"
#include "lost.hpp"
using namespace std;
typedef boost::adjacency_list<
boost::hash_setS, boost::vecS, boost::undirectedS
> graph;
//~ boost::adjacency_matrix<boost::undirectedS> typedef graph;
int main(int argc, char** argv) {
options opt(argc, argv);
int z = opt.get<int>("-z", 1);
int N = opt.get<int>("-n", 500);
float p = opt.get<float>("-p", 1);
timing timer;
lost_light improve;
for(int n = 100; n <= N; n += 100) {
test_suite<graph> suite(z, n, p);
for(auto G : suite) {
auto T = bfs_tree(G);
timer.start();
improve(G, T);
auto sec = timer.stop();
cout << "{" << n << "," << sec << "}";
if(n < N) cout << ",";
cout << endl;
}
}
return 0;
}
<commit_msg>measure mean time<commit_after>// (C) 2014 Arek Olek
#include <iostream>
#include <boost/graph/adjacency_list.hpp>
#include "options.hpp"
#include "test_suite.hpp"
#include "timing.hpp"
#include "bfs.hpp"
#include "lost.hpp"
using namespace std;
typedef boost::adjacency_list<
boost::hash_setS, boost::vecS, boost::undirectedS
> graph;
//~ boost::adjacency_matrix<boost::undirectedS> typedef graph;
int main(int argc, char** argv) {
options opt(argc, argv);
int z = opt.get<int>("-z", 1);
int N = opt.get<int>("-n", 500);
float p = opt.get<float>("-p", 1);
timing timer;
lost_light improve;
for(int n = 100; n <= N; n += 100) {
test_suite<graph> suite(z, n, p);
double total = 0;
for(auto G : suite) {
auto T = bfs_tree(G);
timer.start();
improve(G, T);
total += timer.stop();
}
cout << "{" << n << "," << total/suite.size() << "}";
if(n < N) cout << ",";
cout << endl;
}
return 0;
}
<|endoftext|>
|
<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Javier López-Gómez <jalopezg@inf.uc3m.es>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "DefinitionShadower.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Utils/AST.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclContextInternals.h"
#include "clang/AST/Stmt.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include <algorithm>
using namespace clang;
namespace cling {
/// \brief Returns whether the given source location is a Cling input line. If
/// it came from the prompt, the file is a virtual file with overriden contents.
static bool typedInClingPrompt(FullSourceLoc L) {
if (L.isInvalid())
return false;
const SourceManager &SM = L.getManager();
const FileID FID = SM.getFileID(L);
return SM.isFileOverridden(SM.getFileEntryForID(FID))
&& (SM.getFileID(SM.getIncludeLoc(FID)) == SM.getMainFileID());
}
/// \brief Returns whether the given {Function,Tag,Var}Decl/TemplateDecl is a definition.
static bool isDefinition(const Decl *D) {
if (auto FD = dyn_cast<FunctionDecl>(D))
return FD->isThisDeclarationADefinition();
if (auto TD = dyn_cast<TagDecl>(D))
return TD->isThisDeclarationADefinition();
if (auto VD = dyn_cast<VarDecl>(D))
return VD->isThisDeclarationADefinition();
if (auto TD = dyn_cast<TemplateDecl>(D))
return isDefinition(TD->getTemplatedDecl());
return true;
}
/// \brief Returns whether the given declaration is a template instantiation
/// or specialization.
static bool isInstantiationOrSpecialization(const Decl *D) {
if (auto FD = dyn_cast<FunctionDecl>(D))
return FD->isTemplateInstantiation() || FD->isFunctionTemplateSpecialization();
if (auto CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
return CTSD->getSpecializationKind() != TSK_Undeclared;
if (auto VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
return VTSD->getSpecializationKind() != TSK_Undeclared;
return false;
}
DefinitionShadower::DefinitionShadower(Sema& S, Interpreter& I)
: ASTTransformer(&S), m_Context(S.getASTContext()), m_Interp(I),
m_TU(S.getASTContext().getTranslationUnitDecl()),
m_ShadowsDeclInStdDiagID(S.getDiagnostics().getCustomDiagID(
DiagnosticsEngine::Warning,
"'%0' shadows a declaration with the same name in the 'std' "
"namespace; consider using '::%0' to reference this declaration"))
{}
bool DefinitionShadower::isClingShadowNamespace(const DeclContext *DC) {
auto NS = dyn_cast<NamespaceDecl>(DC);
return NS && NS->getName().startswith("__cling_N5");
}
void DefinitionShadower::hideDecl(clang::NamedDecl *D) const {
// FIXME: this hides a decl from SemaLookup (there is no unloading). For
// (large) L-values, this might be a memory leak. Should this be fixed?
if (Scope* S = m_Sema->getScopeForContext(m_TU)) {
S->RemoveDecl(D);
if (utils::Analyze::isOnScopeChains(D, *m_Sema))
m_Sema->IdResolver.RemoveDecl(D);
}
clang::StoredDeclsList &SDL = (*m_TU->getLookupPtr())[D->getDeclName()];
if (SDL.getAsDecl() == D) {
SDL.setOnlyValue(nullptr);
}
if (auto Vec = SDL.getAsVector()) {
// FIXME: investigate why StoredDeclList has duplicated entries coming from PCM.
Vec->erase(std::remove_if(Vec->begin(), Vec->end(),
[D](Decl *Other) { return cast<Decl>(D) == Other; }),
Vec->end());
}
if (InterpreterCallbacks *IC = m_Interp.getCallbacks())
IC->DefinitionShadowed(D);
}
void DefinitionShadower::invalidatePreviousDefinitions(NamedDecl *D) const {
// NotForRedeclaration: lookup anything visible; follows using directives
LookupResult Previous(*m_Sema, D->getDeclName(), D->getLocation(),
Sema::LookupOrdinaryName, Sema::NotForRedeclaration);
Previous.suppressDiagnostics();
m_Sema->LookupQualifiedName(Previous, m_TU);
bool shadowsDeclInStd{};
for (auto Prev : Previous) {
if (Prev == D)
continue;
if (isDefinition(Prev) && !isDefinition(D))
continue;
// If the found declaration is a function overload, do not invalidate it.
// For templated functions, Sema::IsOverload() does the right thing as per
// C++ [temp.over.link]p4.
if (isa<FunctionDecl>(Prev) && isa<FunctionDecl>(D)
&& m_Sema->IsOverload(cast<FunctionDecl>(D),
cast<FunctionDecl>(Prev), /*IsForUsingDecl=*/false))
continue;
if (isa<FunctionTemplateDecl>(Prev) && isa<FunctionTemplateDecl>(D)
&& m_Sema->IsOverload(cast<FunctionTemplateDecl>(D)->getTemplatedDecl(),
cast<FunctionTemplateDecl>(Prev)->getTemplatedDecl(),
/*IsForUsingDecl=*/false))
continue;
shadowsDeclInStd |= Prev->isInStdNamespace();
hideDecl(Prev);
// For unscoped enumerations, also invalidate all enumerators.
if (EnumDecl *ED = dyn_cast<EnumDecl>(Prev)) {
if (!ED->isTransparentContext())
continue;
for (auto &J : ED->decls())
if (NamedDecl *ND = dyn_cast<NamedDecl>(J))
hideDecl(ND);
}
}
// Ignore any forward declaration issued after a definition. Fixes "error
// : reference to 'xxx' is ambiguous" in `class C {}; class C; C foo;`.
if (!Previous.empty() && !isDefinition(D))
D->setInvalidDecl();
// Diagnose shadowing of decls in the `std` namespace (see ROOT-5971).
// For unnamed macros, the input is ingested in a single `Interpreter::process()`
// call. Do not emit the warning in that case, as all references are local
// to the wrapper function and this diagnostic might be misleading.
if (shadowsDeclInStd
&& ((m_Interp.getInputFlags() & (Interpreter::kInputFromFile
| Interpreter::kIFFLineByLine))
!= Interpreter::kInputFromFile)) {
m_Sema->Diag(D->getBeginLoc(), m_ShadowsDeclInStdDiagID)
<< D->getQualifiedNameAsString();
}
}
void DefinitionShadower::invalidatePreviousDefinitions(FunctionDecl *D) const {
const CompilationOptions &CO = getTransaction()->getCompilationOpts();
if (utils::Analyze::IsWrapper(D)) {
if (!CO.DeclarationExtraction)
return;
// DeclExtractor shall move local declarations to the TU. Invalidate all
// previous definitions (that may clash) before it runs.
auto CS = dyn_cast<CompoundStmt>(D->getBody());
for (auto &I : CS->body()) {
auto DS = dyn_cast<DeclStmt>(I);
if (!DS)
continue;
for (auto &J : DS->decls())
if (auto ND = dyn_cast<NamedDecl>(J))
invalidatePreviousDefinitions(ND);
}
} else
invalidatePreviousDefinitions(cast<NamedDecl>(D));
}
void DefinitionShadower::invalidatePreviousDefinitions(Decl *D) const {
if (auto FD = dyn_cast<FunctionDecl>(D))
invalidatePreviousDefinitions(FD);
else if (auto ND = dyn_cast<NamedDecl>(D))
invalidatePreviousDefinitions(ND);
}
ASTTransformer::Result DefinitionShadower::Transform(Decl* D) {
Transaction *T = getTransaction();
if (!T->getCompilationOpts().EnableShadowing)
return Result(D, true);
// For variable templates, Transform() is invoked with a VarDecl; get the
// corresponding VarTemplateDecl.
if (auto VD = dyn_cast<VarDecl>(D))
if (auto VTD = VD->getDescribedVarTemplate())
D = VTD;
// Disable definition shadowing for some specific cases.
if (D->getLexicalDeclContext() != m_TU || D->isInvalidDecl()
|| isa<UsingDirectiveDecl>(D) || isa<UsingDecl>(D) || isa<NamespaceDecl>(D)
|| isInstantiationOrSpecialization(D)
|| !typedInClingPrompt(FullSourceLoc{D->getLocation(),
m_Context.getSourceManager()}))
return Result(D, true);
// Each transaction gets at most a `__cling_N5xxx' namespace. If `T' already
// has one, reuse it.
auto NS = T->getDefinitionShadowNS();
if (!NS) {
NS = NamespaceDecl::Create(m_Context, m_TU, /*inline=*/true,
SourceLocation(), SourceLocation(),
&m_Context.Idents.get("__cling_N5"
+ std::to_string(m_UniqueNameCounter++)),
nullptr);
//NS->setImplicit();
m_TU->addDecl(NS);
T->setDefinitionShadowNS(NS);
}
m_TU->removeDecl(D);
if (isa<CXXRecordDecl>(D->getDeclContext()))
D->setLexicalDeclContext(NS);
else
D->setDeclContext(NS);
// An instantiated function template inherits the declaration context of the
// templated decl. This is used for name mangling; fix it to avoid clashing.
if (auto FTD = dyn_cast<FunctionTemplateDecl>(D))
FTD->getTemplatedDecl()->setDeclContext(NS);
NS->addDecl(D);
// Invalidate previous definitions so that LookupResult::resolveKind() does not
// mark resolution as ambiguous.
invalidatePreviousDefinitions(D);
return Result(D, true);
}
} // end namespace cling
<commit_msg>Minor readability/aesthetic changes<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// author: Javier López-Gómez <jalopezg@inf.uc3m.es>
//
// This file is dual-licensed: you can choose to license it under the University
// of Illinois Open Source License or the GNU Lesser General Public License. See
// LICENSE.TXT for details.
//------------------------------------------------------------------------------
#include "DefinitionShadower.h"
#include "cling/Interpreter/Interpreter.h"
#include "cling/Interpreter/InterpreterCallbacks.h"
#include "cling/Utils/AST.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclContextInternals.h"
#include "clang/AST/Stmt.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include <algorithm>
using namespace clang;
namespace cling {
/// \brief Returns whether the given source location is a Cling input line. If
/// it came from the prompt, the file is a virtual file with overriden contents.
static bool typedInClingPrompt(FullSourceLoc L) {
if (L.isInvalid())
return false;
const SourceManager &SM = L.getManager();
const FileID FID = SM.getFileID(L);
return SM.isFileOverridden(SM.getFileEntryForID(FID))
&& (SM.getFileID(SM.getIncludeLoc(FID)) == SM.getMainFileID());
}
/// \brief Returns whether the given {Function,Tag,Var}Decl/TemplateDecl is a definition.
static bool isDefinition(const Decl *D) {
if (auto FD = dyn_cast<FunctionDecl>(D))
return FD->isThisDeclarationADefinition();
if (auto TD = dyn_cast<TagDecl>(D))
return TD->isThisDeclarationADefinition();
if (auto VD = dyn_cast<VarDecl>(D))
return VD->isThisDeclarationADefinition();
if (auto TD = dyn_cast<TemplateDecl>(D))
return isDefinition(TD->getTemplatedDecl());
return true;
}
/// \brief Returns whether the given declaration is a template instantiation
/// or specialization.
static bool isInstantiationOrSpecialization(const Decl *D) {
if (auto FD = dyn_cast<FunctionDecl>(D))
return FD->isTemplateInstantiation() || FD->isFunctionTemplateSpecialization();
if (auto CTSD = dyn_cast<ClassTemplateSpecializationDecl>(D))
return CTSD->getSpecializationKind() != TSK_Undeclared;
if (auto VTSD = dyn_cast<VarTemplateSpecializationDecl>(D))
return VTSD->getSpecializationKind() != TSK_Undeclared;
return false;
}
DefinitionShadower::DefinitionShadower(Sema& S, Interpreter& I)
: ASTTransformer(&S), m_Context(S.getASTContext()), m_Interp(I),
m_TU(S.getASTContext().getTranslationUnitDecl()),
m_ShadowsDeclInStdDiagID(S.getDiagnostics().getCustomDiagID(
DiagnosticsEngine::Warning,
"'%0' shadows a declaration with the same name in the 'std' "
"namespace; use '::%0' to reference this declaration"))
{}
bool DefinitionShadower::isClingShadowNamespace(const DeclContext *DC) {
auto NS = dyn_cast<NamespaceDecl>(DC);
return NS && NS->getName().startswith("__cling_N5");
}
void DefinitionShadower::hideDecl(clang::NamedDecl *D) const {
// FIXME: this hides a decl from SemaLookup (there is no unloading). For
// (large) L-values, this might be a memory leak. Should this be fixed?
if (Scope* S = m_Sema->getScopeForContext(m_TU)) {
S->RemoveDecl(D);
if (utils::Analyze::isOnScopeChains(D, *m_Sema))
m_Sema->IdResolver.RemoveDecl(D);
}
clang::StoredDeclsList &SDL = (*m_TU->getLookupPtr())[D->getDeclName()];
if (SDL.getAsDecl() == D) {
SDL.setOnlyValue(nullptr);
}
if (auto Vec = SDL.getAsVector()) {
// FIXME: investigate why StoredDeclList has duplicated entries coming from PCM.
Vec->erase(std::remove_if(Vec->begin(), Vec->end(),
[D](Decl *Other) { return cast<Decl>(D) == Other; }),
Vec->end());
}
if (InterpreterCallbacks *IC = m_Interp.getCallbacks())
IC->DefinitionShadowed(D);
}
void DefinitionShadower::invalidatePreviousDefinitions(NamedDecl *D) const {
// NotForRedeclaration: lookup anything visible; follows using directives
LookupResult Previous(*m_Sema, D->getDeclName(), D->getLocation(),
Sema::LookupOrdinaryName, Sema::NotForRedeclaration);
Previous.suppressDiagnostics();
m_Sema->LookupQualifiedName(Previous, m_TU);
bool shadowsDeclInStd = false;
for (auto Prev : Previous) {
if (Prev == D)
continue;
if (isDefinition(Prev) && !isDefinition(D))
continue;
// If the found declaration is a function overload, do not invalidate it.
// For templated functions, Sema::IsOverload() does the right thing as per
// C++ [temp.over.link]p4.
if (isa<FunctionDecl>(Prev) && isa<FunctionDecl>(D)
&& m_Sema->IsOverload(cast<FunctionDecl>(D),
cast<FunctionDecl>(Prev), /*IsForUsingDecl=*/false))
continue;
if (isa<FunctionTemplateDecl>(Prev) && isa<FunctionTemplateDecl>(D)
&& m_Sema->IsOverload(cast<FunctionTemplateDecl>(D)->getTemplatedDecl(),
cast<FunctionTemplateDecl>(Prev)->getTemplatedDecl(),
/*IsForUsingDecl=*/false))
continue;
shadowsDeclInStd |= Prev->isInStdNamespace();
hideDecl(Prev);
// For unscoped enumerations, also invalidate all enumerators.
if (EnumDecl *ED = dyn_cast<EnumDecl>(Prev)) {
if (!ED->isTransparentContext())
continue;
for (auto &J : ED->decls())
if (NamedDecl *ND = dyn_cast<NamedDecl>(J))
hideDecl(ND);
}
}
// Ignore any forward declaration issued after a definition. Fixes "error
// : reference to 'xxx' is ambiguous" in `class C {}; class C; C foo;`.
if (!Previous.empty() && !isDefinition(D))
D->setInvalidDecl();
// Diagnose shadowing of decls in the `std` namespace (see ROOT-5971).
// For unnamed macros, the input is ingested in a single `Interpreter::process()`
// call. Do not emit the warning in that case, as all references are local
// to the wrapper function and this diagnostic might be misleading.
if (shadowsDeclInStd
&& ((m_Interp.getInputFlags() & (Interpreter::kInputFromFile
| Interpreter::kIFFLineByLine))
!= Interpreter::kInputFromFile)) {
m_Sema->Diag(D->getBeginLoc(), m_ShadowsDeclInStdDiagID)
<< D->getQualifiedNameAsString();
}
}
void DefinitionShadower::invalidatePreviousDefinitions(FunctionDecl *D) const {
const CompilationOptions &CO = getTransaction()->getCompilationOpts();
if (utils::Analyze::IsWrapper(D)) {
if (!CO.DeclarationExtraction)
return;
// DeclExtractor shall move local declarations to the TU. Invalidate all
// previous definitions (that may clash) before it runs.
auto CS = dyn_cast<CompoundStmt>(D->getBody());
for (auto &I : CS->body()) {
auto DS = dyn_cast<DeclStmt>(I);
if (!DS)
continue;
for (auto &J : DS->decls())
if (auto ND = dyn_cast<NamedDecl>(J))
invalidatePreviousDefinitions(ND);
}
} else
invalidatePreviousDefinitions(cast<NamedDecl>(D));
}
void DefinitionShadower::invalidatePreviousDefinitions(Decl *D) const {
if (auto FD = dyn_cast<FunctionDecl>(D))
invalidatePreviousDefinitions(FD);
else if (auto ND = dyn_cast<NamedDecl>(D))
invalidatePreviousDefinitions(ND);
}
ASTTransformer::Result DefinitionShadower::Transform(Decl* D) {
Transaction *T = getTransaction();
if (!T->getCompilationOpts().EnableShadowing)
return Result(D, true);
// For variable templates, Transform() is invoked with a VarDecl; get the
// corresponding VarTemplateDecl.
if (auto VD = dyn_cast<VarDecl>(D))
if (auto VTD = VD->getDescribedVarTemplate())
D = VTD;
// Disable definition shadowing for some specific cases.
if (D->getLexicalDeclContext() != m_TU || D->isInvalidDecl()
|| isa<UsingDirectiveDecl>(D) || isa<UsingDecl>(D) || isa<NamespaceDecl>(D)
|| isInstantiationOrSpecialization(D)
|| !typedInClingPrompt(FullSourceLoc{D->getLocation(),
m_Context.getSourceManager()}))
return Result(D, true);
// Each transaction gets at most a `__cling_N5xxx' namespace. If `T' already
// has one, reuse it.
auto NS = T->getDefinitionShadowNS();
if (!NS) {
NS = NamespaceDecl::Create(m_Context, m_TU, /*inline=*/true,
SourceLocation(), SourceLocation(),
&m_Context.Idents.get("__cling_N5"
+ std::to_string(m_UniqueNameCounter++)),
nullptr);
//NS->setImplicit();
m_TU->addDecl(NS);
T->setDefinitionShadowNS(NS);
}
m_TU->removeDecl(D);
if (isa<CXXRecordDecl>(D->getDeclContext()))
D->setLexicalDeclContext(NS);
else
D->setDeclContext(NS);
// An instantiated function template inherits the declaration context of the
// templated decl. This is used for name mangling; fix it to avoid clashing.
if (auto FTD = dyn_cast<FunctionTemplateDecl>(D))
FTD->getTemplatedDecl()->setDeclContext(NS);
NS->addDecl(D);
// Invalidate previous definitions so that LookupResult::resolveKind() does not
// mark resolution as ambiguous.
invalidatePreviousDefinitions(D);
return Result(D, true);
}
} // end namespace cling
<|endoftext|>
|
<commit_before>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/***************************************************************************
LogHost.cc
***************************************************************************/
#include "ts/ink_platform.h"
#include "LogUtils.h"
#include "LogSock.h"
#include "LogField.h"
#include "LogFile.h"
#include "LogFormat.h"
#include "LogBuffer.h"
#include "LogHost.h"
#include "LogObject.h"
#include "LogConfig.h"
#include "Log.h"
#include "LogCollationClientSM.h"
#define PING true
#define NOPING false
static Ptr<LogFile>
make_orphan_logfile(LogHost *lh, const char *filename)
{
const char *ext = "orphan";
unsigned name_len = (unsigned)(strlen(filename) + strlen(lh->name()) + strlen(ext) + 16);
char *name_buf = (char *)ats_malloc(name_len);
// NT: replace ':'s with '-'s. This change is necessary because
// NT doesn't like filenames with ':'s in them. ^_^
snprintf(name_buf, name_len, "%s%s%s-%u.%s", filename, LOGFILE_SEPARATOR_STRING, lh->name(), lh->port(), ext);
// XXX should check for conflicts with orphan filename
Ptr<LogFile> orphan(new LogFile(name_buf, nullptr, LOG_FILE_ASCII, lh->signature()));
ats_free(name_buf);
return orphan;
}
/*-------------------------------------------------------------------------
LogHost
-------------------------------------------------------------------------*/
LogHost::LogHost(const char *object_filename, uint64_t object_signature)
: m_object_filename(ats_strdup(object_filename)),
m_object_signature(object_signature),
m_port(0),
m_name(nullptr),
m_sock(nullptr),
m_sock_fd(-1),
m_connected(false),
m_orphan_file(nullptr),
m_log_collation_client_sm(nullptr)
{
ink_zero(m_ip);
ink_zero(m_ipstr);
}
LogHost::LogHost(const LogHost &rhs)
: m_object_filename(ats_strdup(rhs.m_object_filename)),
m_object_signature(rhs.m_object_signature),
m_ip(rhs.m_ip),
m_port(0),
m_name(ats_strdup(rhs.m_name)),
m_sock(nullptr),
m_sock_fd(-1),
m_connected(false),
m_orphan_file(nullptr),
m_log_collation_client_sm(nullptr)
{
memcpy(m_ipstr, rhs.m_ipstr, sizeof(m_ipstr));
m_orphan_file = make_orphan_logfile(this, m_object_filename);
}
LogHost::~LogHost()
{
clear();
ats_free(m_object_filename);
}
//
// There are 3 ways to establish a LogHost:
// - by "hostname:port" or IP:port", where IP is a string of the
// form "xxx.xxx.xxx.xxx".
// - by specifying a hostname and a port (as separate arguments).
// - by specifying an ip and a port (as separate arguments).
//
bool
LogHost::set_name_port(const char *hostname, unsigned int pt)
{
if (!hostname || hostname[0] == 0) {
Note("Cannot establish LogHost with NULL hostname");
return false;
}
clear(); // remove all previous state for this LogHost
m_name = ats_strdup(hostname);
m_port = pt;
Debug("log-host", "LogHost established as %s:%u", this->name(), this->port());
m_orphan_file = make_orphan_logfile(this, m_object_filename);
return true;
}
bool
LogHost::set_ipstr_port(const char *ipstr, unsigned int pt)
{
if (!ipstr || ipstr[0] == 0) {
Note("Cannot establish LogHost with NULL ipstr");
return false;
}
clear(); // remove all previous state for this LogHost
if (0 != m_ip.load(ipstr)) {
Note("Log host failed to parse IP address %s", ipstr);
}
m_port = pt;
ink_strlcpy(m_ipstr, ipstr, sizeof(m_ipstr));
m_name = ats_strdup(ipstr);
Debug("log-host", "LogHost established as %s:%u", name(), pt);
m_orphan_file = make_orphan_logfile(this, m_object_filename);
return true;
}
bool
LogHost::set_name_or_ipstr(const char *name_or_ip)
{
if (name_or_ip && name_or_ip[0] != '\0') {
std::string_view addr, port;
if (ats_ip_parse(std::string_view(name_or_ip), &addr, &port) == 0) {
uint16_t p = port.empty() ? Log::config->collation_port : atoi(port.data());
char *n = const_cast<char *>(addr.data());
// Force termination. We know we can do this because the address
// string is followed by either a nul or a colon.
n[addr.size()] = 0;
if (AF_UNSPEC == ats_ip_check_characters(addr)) {
return set_name_port(n, p);
} else {
return set_ipstr_port(n, p);
}
}
}
return false;
}
bool
LogHost::connected(bool ping)
{
if (m_connected && m_sock && m_sock_fd >= 0) {
if (m_sock->is_connected(m_sock_fd, ping)) {
return true;
}
}
return false;
}
bool
LogHost::connect()
{
if (!m_ip.isValid()) {
Note("Cannot connect to LogHost; host IP has not been established");
return false;
}
if (connected(PING)) {
return true;
}
IpEndpoint target;
ip_port_text_buffer ipb;
target.assign(m_ip, htons(m_port));
if (is_debug_tag_set("log-host")) {
Debug("log-host", "Connecting to LogHost %s", ats_ip_nptop(&target, ipb, sizeof ipb));
}
disconnect(); // make sure connection members are initialized
if (m_sock == nullptr) {
m_sock = new LogSock();
ink_assert(m_sock != nullptr);
}
m_sock_fd = m_sock->connect(&target.sa);
if (m_sock_fd < 0) {
Note("Connection to LogHost %s failed", ats_ip_nptop(&target, ipb, sizeof ipb));
return false;
}
m_connected = true;
if (!authenticated()) {
Note("Authentication to LogHost %s failed", ats_ip_nptop(&target, ipb, sizeof ipb));
disconnect();
return false;
}
return true;
}
void
LogHost::disconnect()
{
if (m_sock && m_sock_fd >= 0) {
m_sock->close(m_sock_fd);
m_sock_fd = -1;
}
if (m_log_collation_client_sm) {
delete m_log_collation_client_sm;
m_log_collation_client_sm = nullptr;
}
m_connected = false;
}
//
// preprocess the given buffer data before sent to target host
// and try to delete it when its reference become zero.
//
bool
LogHost::preproc_and_try_delete(LogBuffer *&lb)
{
if (lb == nullptr) {
Note("Cannot write LogBuffer to LogHost %s; LogBuffer is NULL", name());
return false;
}
LogBufferHeader *buffer_header = lb->header();
if (buffer_header == nullptr) {
Note("Cannot write LogBuffer to LogHost %s; LogBufferHeader is NULL", name());
goto done;
}
if (buffer_header->entry_count == 0) {
// no bytes to write
goto done;
}
// create a new collation client if necessary
if (m_log_collation_client_sm == nullptr) {
m_log_collation_client_sm = new LogCollationClientSM(this);
ink_assert(m_log_collation_client_sm != nullptr);
}
// send log_buffer
if (m_log_collation_client_sm->send(lb) <= 0) {
goto done;
}
return true;
done:
LogBuffer::destroy(lb);
return false;
}
//
// write the given buffer data to orphan file and
// try to delete it when its reference become zero.
//
void
LogHost::orphan_write_and_try_delete(LogBuffer *&lb)
{
RecIncrRawStat(log_rsb, this_thread()->mutex->thread_holding, log_stat_num_lost_before_sent_to_network_stat,
lb->header()->entry_count);
RecIncrRawStat(log_rsb, this_thread()->mutex->thread_holding, log_stat_bytes_lost_before_sent_to_network_stat,
lb->header()->byte_count);
if (!Log::config->logging_space_exhausted) {
Debug("log-host", "Sending LogBuffer to orphan file %s", m_orphan_file->get_name());
m_orphan_file->preproc_and_try_delete(lb);
} else {
Debug("log-host", "logging space exhausted, failed to write orphan file, drop(%" PRIu32 ") bytes", lb->header()->byte_count);
LogBuffer::destroy(lb);
}
}
void
LogHost::display(FILE *fd)
{
fprintf(fd, "LogHost: %s:%u, %s\n", name(), port(), (connected(NOPING)) ? "connected" : "not connected");
LogHost *host = this;
while (host->failover_link.next != nullptr) {
fprintf(fd, "Failover: %s:%u, %s\n", host->name(), host->port(), (host->connected(NOPING)) ? "connected" : "not connected");
host = host->failover_link.next;
}
}
void
LogHost::clear()
{
// close an established connection and clear the state of this host
disconnect();
ats_free(m_name);
delete m_sock;
m_orphan_file.clear();
ink_zero(m_ip);
m_port = 0;
ink_zero(m_ipstr);
m_name = nullptr;
m_sock = nullptr;
m_sock_fd = -1;
m_connected = false;
}
bool
LogHost::authenticated()
{
if (!connected(NOPING)) {
Note("Cannot authenticate LogHost %s; not connected", name());
return false;
}
Debug("log-host", "Authenticating LogHost %s ...", name());
char *auth_key = Log::config->collation_secret;
unsigned auth_key_len = (unsigned)::strlen(auth_key) + 1; // incl null
int bytes = m_sock->write(m_sock_fd, auth_key, auth_key_len);
if ((unsigned)bytes != auth_key_len) {
Debug("log-host", "... bad write on authenticate");
return false;
}
Debug("log-host", "... authenticated");
return true;
}
/*-------------------------------------------------------------------------
LogHostList
-------------------------------------------------------------------------*/
LogHostList::LogHostList() {}
LogHostList::~LogHostList()
{
clear();
}
void
LogHostList::add(LogHost *object, bool copy)
{
ink_assert(object != nullptr);
if (copy) {
m_host_list.enqueue(new LogHost(*object));
} else {
m_host_list.enqueue(object);
}
}
unsigned
LogHostList::count()
{
unsigned cnt = 0;
for (LogHost *host = first(); host; host = next(host)) {
cnt++;
}
return cnt;
}
void
LogHostList::clear()
{
LogHost *host;
while ((host = m_host_list.dequeue())) {
delete host;
}
}
int
LogHostList::preproc_and_try_delete(LogBuffer *lb)
{
int success = false;
unsigned nr_host, nr;
bool need_orphan = true;
LogHost *available_host = nullptr;
ink_release_assert(lb->m_references == 0);
nr_host = nr = count();
ink_atomic_increment(&lb->m_references, nr_host);
for (LogHost *host = first(); host && nr; host = next(host)) {
LogHost *lh = host;
available_host = lh;
do {
ink_atomic_increment(&lb->m_references, 1);
success = lh->preproc_and_try_delete(lb);
need_orphan = need_orphan && (success == false);
} while (lb && (success == false) && (lh = lh->failover_link.next));
nr--;
}
if (lb != nullptr && need_orphan && available_host) {
ink_atomic_increment(&lb->m_references, 1);
available_host->orphan_write_and_try_delete(lb);
}
if (lb != nullptr) {
LogBuffer::destroy(lb);
}
return 0;
}
void
LogHostList::display(FILE *fd)
{
for (LogHost *host = first(); host; host = next(host)) {
host->display(fd);
}
}
bool
LogHostList::operator==(LogHostList &rhs)
{
LogHost *host;
for (host = first(); host; host = next(host)) {
LogHost *rhs_host;
for (rhs_host = rhs.first(); rhs_host; rhs_host = next(host)) {
if ((host->port() == rhs_host->port() && host->ip_addr().isValid() && host->ip_addr() == rhs_host->ip_addr()) ||
(host->name() && rhs_host->name() && (strcmp(host->name(), rhs_host->name()) == 0)) ||
(*(host->ipstr()) && *(rhs_host->ipstr()) && (strcmp(host->ipstr(), rhs_host->ipstr()) == 0))) {
break;
}
}
if (rhs_host == nullptr) {
return false;
}
}
return true;
}
<commit_msg>Log Collation - Memory leak when all hosts are down.<commit_after>/** @file
A brief file description
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
/***************************************************************************
LogHost.cc
***************************************************************************/
#include "ts/ink_platform.h"
#include "LogUtils.h"
#include "LogSock.h"
#include "LogField.h"
#include "LogFile.h"
#include "LogFormat.h"
#include "LogBuffer.h"
#include "LogHost.h"
#include "LogObject.h"
#include "LogConfig.h"
#include "Log.h"
#include "LogCollationClientSM.h"
#define PING true
#define NOPING false
static Ptr<LogFile>
make_orphan_logfile(LogHost *lh, const char *filename)
{
const char *ext = "orphan";
unsigned name_len = (unsigned)(strlen(filename) + strlen(lh->name()) + strlen(ext) + 16);
char *name_buf = (char *)ats_malloc(name_len);
// NT: replace ':'s with '-'s. This change is necessary because
// NT doesn't like filenames with ':'s in them. ^_^
snprintf(name_buf, name_len, "%s%s%s-%u.%s", filename, LOGFILE_SEPARATOR_STRING, lh->name(), lh->port(), ext);
// XXX should check for conflicts with orphan filename
Ptr<LogFile> orphan(new LogFile(name_buf, nullptr, LOG_FILE_ASCII, lh->signature()));
ats_free(name_buf);
return orphan;
}
/*-------------------------------------------------------------------------
LogHost
-------------------------------------------------------------------------*/
LogHost::LogHost(const char *object_filename, uint64_t object_signature)
: m_object_filename(ats_strdup(object_filename)),
m_object_signature(object_signature),
m_port(0),
m_name(nullptr),
m_sock(nullptr),
m_sock_fd(-1),
m_connected(false),
m_orphan_file(nullptr),
m_log_collation_client_sm(nullptr)
{
ink_zero(m_ip);
ink_zero(m_ipstr);
}
LogHost::LogHost(const LogHost &rhs)
: m_object_filename(ats_strdup(rhs.m_object_filename)),
m_object_signature(rhs.m_object_signature),
m_ip(rhs.m_ip),
m_port(0),
m_name(ats_strdup(rhs.m_name)),
m_sock(nullptr),
m_sock_fd(-1),
m_connected(false),
m_orphan_file(nullptr),
m_log_collation_client_sm(nullptr)
{
memcpy(m_ipstr, rhs.m_ipstr, sizeof(m_ipstr));
m_orphan_file = make_orphan_logfile(this, m_object_filename);
}
LogHost::~LogHost()
{
clear();
ats_free(m_object_filename);
}
//
// There are 3 ways to establish a LogHost:
// - by "hostname:port" or IP:port", where IP is a string of the
// form "xxx.xxx.xxx.xxx".
// - by specifying a hostname and a port (as separate arguments).
// - by specifying an ip and a port (as separate arguments).
//
bool
LogHost::set_name_port(const char *hostname, unsigned int pt)
{
if (!hostname || hostname[0] == 0) {
Note("Cannot establish LogHost with NULL hostname");
return false;
}
clear(); // remove all previous state for this LogHost
m_name = ats_strdup(hostname);
m_port = pt;
Debug("log-host", "LogHost established as %s:%u", this->name(), this->port());
m_orphan_file = make_orphan_logfile(this, m_object_filename);
return true;
}
bool
LogHost::set_ipstr_port(const char *ipstr, unsigned int pt)
{
if (!ipstr || ipstr[0] == 0) {
Note("Cannot establish LogHost with NULL ipstr");
return false;
}
clear(); // remove all previous state for this LogHost
if (0 != m_ip.load(ipstr)) {
Note("Log host failed to parse IP address %s", ipstr);
}
m_port = pt;
ink_strlcpy(m_ipstr, ipstr, sizeof(m_ipstr));
m_name = ats_strdup(ipstr);
Debug("log-host", "LogHost established as %s:%u", name(), pt);
m_orphan_file = make_orphan_logfile(this, m_object_filename);
return true;
}
bool
LogHost::set_name_or_ipstr(const char *name_or_ip)
{
if (name_or_ip && name_or_ip[0] != '\0') {
std::string_view addr, port;
if (ats_ip_parse(std::string_view(name_or_ip), &addr, &port) == 0) {
uint16_t p = port.empty() ? Log::config->collation_port : atoi(port.data());
char *n = const_cast<char *>(addr.data());
// Force termination. We know we can do this because the address
// string is followed by either a nul or a colon.
n[addr.size()] = 0;
if (AF_UNSPEC == ats_ip_check_characters(addr)) {
return set_name_port(n, p);
} else {
return set_ipstr_port(n, p);
}
}
}
return false;
}
bool
LogHost::connected(bool ping)
{
if (m_connected && m_sock && m_sock_fd >= 0) {
if (m_sock->is_connected(m_sock_fd, ping)) {
return true;
}
}
return false;
}
bool
LogHost::connect()
{
if (!m_ip.isValid()) {
Note("Cannot connect to LogHost; host IP has not been established");
return false;
}
if (connected(PING)) {
return true;
}
IpEndpoint target;
ip_port_text_buffer ipb;
target.assign(m_ip, htons(m_port));
if (is_debug_tag_set("log-host")) {
Debug("log-host", "Connecting to LogHost %s", ats_ip_nptop(&target, ipb, sizeof ipb));
}
disconnect(); // make sure connection members are initialized
if (m_sock == nullptr) {
m_sock = new LogSock();
ink_assert(m_sock != nullptr);
}
m_sock_fd = m_sock->connect(&target.sa);
if (m_sock_fd < 0) {
Note("Connection to LogHost %s failed", ats_ip_nptop(&target, ipb, sizeof ipb));
return false;
}
m_connected = true;
if (!authenticated()) {
Note("Authentication to LogHost %s failed", ats_ip_nptop(&target, ipb, sizeof ipb));
disconnect();
return false;
}
return true;
}
void
LogHost::disconnect()
{
if (m_sock && m_sock_fd >= 0) {
m_sock->close(m_sock_fd);
m_sock_fd = -1;
}
if (m_log_collation_client_sm) {
delete m_log_collation_client_sm;
m_log_collation_client_sm = nullptr;
}
m_connected = false;
}
//
// preprocess the given buffer data before sent to target host
// and try to delete it when its reference become zero.
//
bool
LogHost::preproc_and_try_delete(LogBuffer *&lb)
{
if (lb == nullptr) {
Note("Cannot write LogBuffer to LogHost %s; LogBuffer is NULL", name());
return false;
}
LogBufferHeader *buffer_header = lb->header();
if (buffer_header == nullptr) {
Note("Cannot write LogBuffer to LogHost %s; LogBufferHeader is NULL", name());
goto done;
}
if (buffer_header->entry_count == 0) {
// no bytes to write
goto done;
}
// create a new collation client if necessary
if (m_log_collation_client_sm == nullptr) {
m_log_collation_client_sm = new LogCollationClientSM(this);
ink_assert(m_log_collation_client_sm != nullptr);
}
// send log_buffer
if (m_log_collation_client_sm->send(lb) <= 0) {
goto done;
}
return true;
done:
LogBuffer::destroy(lb);
return false;
}
//
// write the given buffer data to orphan file and
// try to delete it when its reference become zero.
//
void
LogHost::orphan_write_and_try_delete(LogBuffer *&lb)
{
RecIncrRawStat(log_rsb, this_thread()->mutex->thread_holding, log_stat_num_lost_before_sent_to_network_stat,
lb->header()->entry_count);
RecIncrRawStat(log_rsb, this_thread()->mutex->thread_holding, log_stat_bytes_lost_before_sent_to_network_stat,
lb->header()->byte_count);
if (!Log::config->logging_space_exhausted) {
Debug("log-host", "Sending LogBuffer to orphan file %s", m_orphan_file->get_name());
m_orphan_file->preproc_and_try_delete(lb);
} else {
Debug("log-host", "logging space exhausted, failed to write orphan file, drop(%" PRIu32 ") bytes", lb->header()->byte_count);
}
LogBuffer::destroy(lb);
}
void
LogHost::display(FILE *fd)
{
fprintf(fd, "LogHost: %s:%u, %s\n", name(), port(), (connected(NOPING)) ? "connected" : "not connected");
LogHost *host = this;
while (host->failover_link.next != nullptr) {
fprintf(fd, "Failover: %s:%u, %s\n", host->name(), host->port(), (host->connected(NOPING)) ? "connected" : "not connected");
host = host->failover_link.next;
}
}
void
LogHost::clear()
{
// close an established connection and clear the state of this host
disconnect();
ats_free(m_name);
delete m_sock;
m_orphan_file.clear();
ink_zero(m_ip);
m_port = 0;
ink_zero(m_ipstr);
m_name = nullptr;
m_sock = nullptr;
m_sock_fd = -1;
m_connected = false;
}
bool
LogHost::authenticated()
{
if (!connected(NOPING)) {
Note("Cannot authenticate LogHost %s; not connected", name());
return false;
}
Debug("log-host", "Authenticating LogHost %s ...", name());
char *auth_key = Log::config->collation_secret;
unsigned auth_key_len = (unsigned)::strlen(auth_key) + 1; // incl null
int bytes = m_sock->write(m_sock_fd, auth_key, auth_key_len);
if ((unsigned)bytes != auth_key_len) {
Debug("log-host", "... bad write on authenticate");
return false;
}
Debug("log-host", "... authenticated");
return true;
}
/*-------------------------------------------------------------------------
LogHostList
-------------------------------------------------------------------------*/
LogHostList::LogHostList() {}
LogHostList::~LogHostList()
{
clear();
}
void
LogHostList::add(LogHost *object, bool copy)
{
ink_assert(object != nullptr);
if (copy) {
m_host_list.enqueue(new LogHost(*object));
} else {
m_host_list.enqueue(object);
}
}
unsigned
LogHostList::count()
{
unsigned cnt = 0;
for (LogHost *host = first(); host; host = next(host)) {
cnt++;
}
return cnt;
}
void
LogHostList::clear()
{
LogHost *host;
while ((host = m_host_list.dequeue())) {
delete host;
}
}
int
LogHostList::preproc_and_try_delete(LogBuffer *lb)
{
int success = false;
unsigned nr_host, nr;
bool need_orphan = true;
LogHost *available_host = nullptr;
ink_release_assert(lb->m_references == 0);
nr_host = nr = count();
ink_atomic_increment(&lb->m_references, nr_host);
for (LogHost *host = first(); host && nr; host = next(host)) {
LogHost *lh = host;
available_host = lh;
do {
ink_atomic_increment(&lb->m_references, 1);
success = lh->preproc_and_try_delete(lb);
need_orphan = need_orphan && (success == false);
} while (lb && (success == false) && (lh = lh->failover_link.next));
nr--;
}
if (lb != nullptr && need_orphan && available_host) {
ink_atomic_increment(&lb->m_references, 1);
available_host->orphan_write_and_try_delete(lb);
}
if (lb != nullptr) {
LogBuffer::destroy(lb);
}
return 0;
}
void
LogHostList::display(FILE *fd)
{
for (LogHost *host = first(); host; host = next(host)) {
host->display(fd);
}
}
bool
LogHostList::operator==(LogHostList &rhs)
{
LogHost *host;
for (host = first(); host; host = next(host)) {
LogHost *rhs_host;
for (rhs_host = rhs.first(); rhs_host; rhs_host = next(host)) {
if ((host->port() == rhs_host->port() && host->ip_addr().isValid() && host->ip_addr() == rhs_host->ip_addr()) ||
(host->name() && rhs_host->name() && (strcmp(host->name(), rhs_host->name()) == 0)) ||
(*(host->ipstr()) && *(rhs_host->ipstr()) && (strcmp(host->ipstr(), rhs_host->ipstr()) == 0))) {
break;
}
}
if (rhs_host == nullptr) {
return false;
}
}
return true;
}
<|endoftext|>
|
<commit_before>/**
* 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 <errno.h>
#include <signal.h>
#include <stdio.h> // For perror.
#include <string.h>
#include <map>
#include <set>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <stout/check.hpp>
#include <stout/exit.hpp>
#include <stout/foreach.hpp>
#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/uuid.hpp>
#include "common/type_utils.hpp"
#include "slave/flags.hpp"
#include "slave/process_isolator.hpp"
#include "slave/state.hpp"
using namespace process;
using std::map;
using std::set;
using std::string;
using process::defer;
using process::wait; // Necessary on some OS's to disambiguate.
namespace mesos {
namespace internal {
namespace slave {
using launcher::ExecutorLauncher;
using state::SlaveState;
using state::FrameworkState;
using state::ExecutorState;
using state::RunState;
ProcessIsolator::ProcessIsolator()
: ProcessBase(ID::generate("process-isolator")),
initialized(false) {}
void ProcessIsolator::initialize(
const Flags& _flags,
const Resources& _,
bool _local,
const PID<Slave>& _slave)
{
flags = _flags;
local = _local;
slave = _slave;
initialized = true;
}
void ProcessIsolator::launchExecutor(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const FrameworkInfo& frameworkInfo,
const ExecutorInfo& executorInfo,
const UUID& uuid,
const string& directory,
const Resources& resources)
{
CHECK(initialized) << "Cannot launch executors before initialization!";
const ExecutorID& executorId = executorInfo.executor_id();
LOG(INFO) << "Launching " << executorId
<< " (" << executorInfo.command().value() << ")"
<< " in " << directory
<< " with resources " << resources
<< "' for framework " << frameworkId;
ProcessInfo* info = new ProcessInfo(frameworkId, executorId);
infos[frameworkId][executorId] = info;
// Use pipes to determine which child has successfully changed session.
int pipes[2];
if (pipe(pipes) < 0) {
PLOG(FATAL) << "Failed to create a pipe";
}
// Set the FD_CLOEXEC flags on these pipes
Try<Nothing> cloexec = os::cloexec(pipes[0]);
CHECK_SOME(cloexec) << "Error setting FD_CLOEXEC on pipe[0]";
cloexec = os::cloexec(pipes[1]);
CHECK_SOME(cloexec) << "Error setting FD_CLOEXEC on pipe[1]";
// Create the ExecutorLauncher instance before the fork for the
// child process to use.
ExecutorLauncher launcher(
slaveId,
frameworkId,
executorInfo.executor_id(),
uuid,
executorInfo.command(),
frameworkInfo.user(),
directory,
flags.work_dir,
slave,
flags.frameworks_home,
flags.hadoop_home,
!local,
flags.switch_user,
frameworkInfo.checkpoint());
// We get the environment map for launching mesos-launcher before
// the fork, because we have seen deadlock issues with ostringstream
// in the forked process before it calls exec.
map<string, string> env = launcher.getLauncherEnvironment();
pid_t pid;
if ((pid = fork()) == -1) {
PLOG(FATAL) << "Failed to fork to launch new executor";
}
if (pid > 0) {
os::close(pipes[1]);
// Get the child's pid via the pipe.
if (read(pipes[0], &pid, sizeof(pid)) == -1) {
PLOG(FATAL) << "Failed to get child PID from pipe";
}
os::close(pipes[0]);
// In parent process.
LOG(INFO) << "Forked executor at " << pid;
// Record the pid (should also be the pgid since we setsid below).
infos[frameworkId][executorId]->pid = pid;
reaper.monitor(pid)
.onAny(defer(PID<ProcessIsolator>(this),
&ProcessIsolator::reaped,
pid,
lambda::_1));
// Tell the slave this executor has started.
dispatch(slave, &Slave::executorStarted, frameworkId, executorId, pid);
} else {
// In child process, we make cleanup easier by putting process
// into it's own session. DO NOT USE GLOG!
os::close(pipes[0]);
// NOTE: We setsid() in a loop because setsid() might fail if another
// process has the same process group id as the calling process.
while ((pid = setsid()) == -1) {
perror("Could not put executor in its own session");
std::cout << "Forking another process and retrying ..." << std::endl;
if ((pid = fork()) == -1) {
perror("Failed to fork to launch executor");
abort();
}
if (pid > 0) {
// In parent process.
// It is ok to suicide here, though process reaper signals the exit,
// because the process isolator ignores unknown processes.
exit(0);
}
}
if (write(pipes[1], &pid, sizeof(pid)) != sizeof(pid)) {
perror("Failed to write PID on pipe");
abort();
}
os::close(pipes[1]);
// Setup the environment for launcher.
foreachpair (const string& key, const string& value, env) {
os::setenv(key, value);
}
const char** args = (const char**) new char*[2];
// Determine path for mesos-launcher.
Try<string> realpath = os::realpath(
path::join(flags.launcher_dir, "mesos-launcher"));
if (realpath.isError()) {
EXIT(1) << "Failed to determine the canonical path "
<< "for the mesos-launcher: " << realpath.error();
}
// Grab a copy of the path so that we can reliably use 'c_str()'.
const string& path = realpath.get();
args[0] = path.c_str();
args[1] = NULL;
// Execute the mesos-launcher!
execvp(args[0], (char* const*) args);
// If we get here, the execvp call failed.
perror("Failed to execvp the mesos-launcher");
abort();
}
}
// NOTE: This function can be called by the isolator itself or by the
// slave if it doesn't hear about an executor exit after it sends a
// shutdown message.
void ProcessIsolator::killExecutor(
const FrameworkID& frameworkId,
const ExecutorID& executorId)
{
CHECK(initialized) << "Cannot kill executors before initialization!";
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
LOG(ERROR) << "Asked to kill an unknown/killed executor! " << executorId;
return;
}
const Option<pid_t>& pid = infos[frameworkId][executorId]->pid;
if (pid.isSome()) {
// TODO(vinod): Call killtree on the pid of the actual executor process
// that is running the tasks (stored in the local storage by the
// executor module).
os::killtree(pid.get(), SIGKILL, true, true, &LOG(INFO));
// Also kill all processes that belong to the process group of the executor.
// This is valuable in situations where the top level executor process
// exited and hence killtree is unable to kill any spawned orphans.
// NOTE: This assumes that the process group id of the executor process is
// same as its pid (which is expected to be the case with setsid()).
// TODO(vinod): Also (recursively) kill processes belonging to the
// same session, but have a different process group id.
if (killpg(pid.get(), SIGKILL) == -1 && errno != ESRCH) {
PLOG(WARNING) << "Failed to kill process group " << pid.get();
}
infos[frameworkId][executorId]->killed = true;
}
}
void ProcessIsolator::resourcesChanged(
const FrameworkID& frameworkId,
const ExecutorID& executorId,
const Resources& resources)
{
CHECK(initialized) << "Cannot do resourcesChanged before initialization!";
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
LOG(INFO) << "Asked to update resources for an unknown/killed executor '"
<< executorId << "' of framework " << frameworkId;
return;
}
ProcessInfo* info = CHECK_NOTNULL(infos[frameworkId][executorId]);
info->resources = resources;
// Do nothing; subclasses may override this.
}
Future<Nothing> ProcessIsolator::recover(
const Option<SlaveState>& state)
{
LOG(INFO) << "Recovering isolator";
if (state.isNone()) {
return Nothing();
}
foreachvalue (const FrameworkState& framework, state.get().frameworks) {
foreachvalue (const ExecutorState& executor, framework.executors) {
LOG(INFO) << "Recovering executor '" << executor.id
<< "' of framework " << framework.id;
if (executor.info.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its info cannot be recovered";
continue;
}
if (executor.latest.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its latest run cannot be recovered";
continue;
}
// We are only interested in the latest run of the executor!
const UUID& uuid = executor.latest.get();
CHECK(executor.runs.contains(uuid));
const RunState& run = executor.runs.get(uuid).get();
ProcessInfo* info =
new ProcessInfo(framework.id, executor.id, run.forkedPid);
infos[framework.id][executor.id] = info;
// Add the pid to the reaper to monitor exit status.
if (run.forkedPid.isSome()) {
reaper.monitor(run.forkedPid.get())
.onAny(defer(PID<ProcessIsolator>(this),
&ProcessIsolator::reaped,
run.forkedPid.get(),
lambda::_1));
}
}
}
return Nothing();
}
Future<ResourceStatistics> ProcessIsolator::usage(
const FrameworkID& frameworkId,
const ExecutorID& executorId)
{
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
return Future<ResourceStatistics>::failed("Unknown/killed executor");
}
ProcessInfo* info = infos[frameworkId][executorId];
CHECK_NOTNULL(info);
ResourceStatistics result;
result.set_timestamp(Clock::now().secs());
// Set the resource allocations.
const Option<Bytes>& mem = info->resources.mem();
if (mem.isSome()) {
result.set_mem_limit_bytes(mem.get().bytes());
}
const Option<double>& cpus = info->resources.cpus();
if (cpus.isSome()) {
result.set_cpus_limit(cpus.get());
}
CHECK_SOME(info->pid);
Result<os::Process> process = os::process(info->pid.get());
if (!process.isSome()) {
return Future<ResourceStatistics>::failed(
process.isError() ? process.error() : "Process does not exist");
}
result.set_timestamp(Clock::now().secs());
if (process.get().rss.isSome()) {
result.set_mem_rss_bytes(process.get().rss.get().bytes());
}
// We only show utime and stime when both are available, otherwise
// we're exposing a partial view of the CPU times.
if (process.get().utime.isSome() && process.get().stime.isSome()) {
result.set_cpus_user_time_secs(process.get().utime.get().secs());
result.set_cpus_system_time_secs(process.get().stime.get().secs());
}
// Now aggregate all descendant process usage statistics.
const Try<set<pid_t> >& children = os::children(info->pid.get(), true);
if (children.isError()) {
return Future<ResourceStatistics>::failed(
"Failed to get children of " + stringify(info->pid.get()) + ": " +
children.error());
}
// Aggregate the usage of all child processes.
foreach (pid_t child, children.get()) {
process = os::process(child);
// Skip processes that disappear.
if (process.isNone()) {
continue;
}
if (process.isError()) {
LOG(WARNING) << "Failed to get status of descendant process " << child
<< " of parent " << info->pid.get() << ": "
<< process.error();
continue;
}
if (process.get().rss.isSome()) {
result.set_mem_rss_bytes(
result.mem_rss_bytes() + process.get().rss.get().bytes());
}
// We only show utime and stime when both are available, otherwise
// we're exposing a partial view of the CPU times.
if (process.get().utime.isSome() && process.get().stime.isSome()) {
result.set_cpus_user_time_secs(
result.cpus_user_time_secs() + process.get().utime.get().secs());
result.set_cpus_system_time_secs(
result.cpus_system_time_secs() + process.get().stime.get().secs());
}
}
return result;
}
void ProcessIsolator::reaped(pid_t pid, const Future<Option<int> >& status)
{
foreachkey (const FrameworkID& frameworkId, infos) {
foreachkey (const ExecutorID& executorId, infos[frameworkId]) {
ProcessInfo* info = infos[frameworkId][executorId];
if (info->pid.isSome() && info->pid.get() == pid) {
if (!status.isReady()) {
LOG(ERROR) << "Failed to get the status for executor '" << executorId
<< "' of framework " << frameworkId << ": "
<< (status.isFailed() ? status.failure() : "discarded");
return;
}
LOG(INFO) << "Telling slave of terminated executor '" << executorId
<< "' of framework " << frameworkId;
dispatch(slave,
&Slave::executorTerminated,
frameworkId,
executorId,
status.get(),
false,
"Executor terminated");
if (!info->killed) {
// Try and cleanup after the executor.
killExecutor(frameworkId, executorId);
}
if (infos[frameworkId].size() == 1) {
infos.erase(frameworkId);
} else {
infos[frameworkId].erase(executorId);
}
delete info;
return;
}
}
}
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<commit_msg>Fixed a log line to show the path of launcher in process isolator.<commit_after>/**
* 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 <errno.h>
#include <signal.h>
#include <stdio.h> // For perror.
#include <string.h>
#include <map>
#include <set>
#include <process/clock.hpp>
#include <process/defer.hpp>
#include <process/dispatch.hpp>
#include <process/id.hpp>
#include <stout/check.hpp>
#include <stout/exit.hpp>
#include <stout/foreach.hpp>
#include <stout/lambda.hpp>
#include <stout/nothing.hpp>
#include <stout/option.hpp>
#include <stout/os.hpp>
#include <stout/uuid.hpp>
#include "common/type_utils.hpp"
#include "slave/flags.hpp"
#include "slave/process_isolator.hpp"
#include "slave/state.hpp"
using namespace process;
using std::map;
using std::set;
using std::string;
using process::defer;
using process::wait; // Necessary on some OS's to disambiguate.
namespace mesos {
namespace internal {
namespace slave {
using launcher::ExecutorLauncher;
using state::SlaveState;
using state::FrameworkState;
using state::ExecutorState;
using state::RunState;
ProcessIsolator::ProcessIsolator()
: ProcessBase(ID::generate("process-isolator")),
initialized(false) {}
void ProcessIsolator::initialize(
const Flags& _flags,
const Resources& _,
bool _local,
const PID<Slave>& _slave)
{
flags = _flags;
local = _local;
slave = _slave;
initialized = true;
}
void ProcessIsolator::launchExecutor(
const SlaveID& slaveId,
const FrameworkID& frameworkId,
const FrameworkInfo& frameworkInfo,
const ExecutorInfo& executorInfo,
const UUID& uuid,
const string& directory,
const Resources& resources)
{
CHECK(initialized) << "Cannot launch executors before initialization!";
const ExecutorID& executorId = executorInfo.executor_id();
LOG(INFO) << "Launching " << executorId
<< " (" << executorInfo.command().value() << ")"
<< " in " << directory
<< " with resources " << resources
<< "' for framework " << frameworkId;
ProcessInfo* info = new ProcessInfo(frameworkId, executorId);
infos[frameworkId][executorId] = info;
// Use pipes to determine which child has successfully changed session.
int pipes[2];
if (pipe(pipes) < 0) {
PLOG(FATAL) << "Failed to create a pipe";
}
// Set the FD_CLOEXEC flags on these pipes
Try<Nothing> cloexec = os::cloexec(pipes[0]);
CHECK_SOME(cloexec) << "Error setting FD_CLOEXEC on pipe[0]";
cloexec = os::cloexec(pipes[1]);
CHECK_SOME(cloexec) << "Error setting FD_CLOEXEC on pipe[1]";
// Create the ExecutorLauncher instance before the fork for the
// child process to use.
ExecutorLauncher launcher(
slaveId,
frameworkId,
executorInfo.executor_id(),
uuid,
executorInfo.command(),
frameworkInfo.user(),
directory,
flags.work_dir,
slave,
flags.frameworks_home,
flags.hadoop_home,
!local,
flags.switch_user,
frameworkInfo.checkpoint());
// We get the environment map for launching mesos-launcher before
// the fork, because we have seen deadlock issues with ostringstream
// in the forked process before it calls exec.
map<string, string> env = launcher.getLauncherEnvironment();
pid_t pid;
if ((pid = fork()) == -1) {
PLOG(FATAL) << "Failed to fork to launch new executor";
}
if (pid > 0) {
os::close(pipes[1]);
// Get the child's pid via the pipe.
if (read(pipes[0], &pid, sizeof(pid)) == -1) {
PLOG(FATAL) << "Failed to get child PID from pipe";
}
os::close(pipes[0]);
// In parent process.
LOG(INFO) << "Forked executor at " << pid;
// Record the pid (should also be the pgid since we setsid below).
infos[frameworkId][executorId]->pid = pid;
reaper.monitor(pid)
.onAny(defer(PID<ProcessIsolator>(this),
&ProcessIsolator::reaped,
pid,
lambda::_1));
// Tell the slave this executor has started.
dispatch(slave, &Slave::executorStarted, frameworkId, executorId, pid);
} else {
// In child process, we make cleanup easier by putting process
// into it's own session. DO NOT USE GLOG!
os::close(pipes[0]);
// NOTE: We setsid() in a loop because setsid() might fail if another
// process has the same process group id as the calling process.
while ((pid = setsid()) == -1) {
perror("Could not put executor in its own session");
std::cout << "Forking another process and retrying ..." << std::endl;
if ((pid = fork()) == -1) {
perror("Failed to fork to launch executor");
abort();
}
if (pid > 0) {
// In parent process.
// It is ok to suicide here, though process reaper signals the exit,
// because the process isolator ignores unknown processes.
exit(0);
}
}
if (write(pipes[1], &pid, sizeof(pid)) != sizeof(pid)) {
perror("Failed to write PID on pipe");
abort();
}
os::close(pipes[1]);
// Setup the environment for launcher.
foreachpair (const string& key, const string& value, env) {
os::setenv(key, value);
}
const char** args = (const char**) new char*[2];
// Determine path for mesos-launcher.
Try<string> realpath = os::realpath(
path::join(flags.launcher_dir, "mesos-launcher"));
if (realpath.isError()) {
EXIT(1) << "Failed to determine the canonical path "
<< "for the mesos-launcher '"
<< path::join(flags.launcher_dir, "mesos-launcher")
<< "': " << realpath.error();
}
// Grab a copy of the path so that we can reliably use 'c_str()'.
const string& path = realpath.get();
args[0] = path.c_str();
args[1] = NULL;
// Execute the mesos-launcher!
execvp(args[0], (char* const*) args);
// If we get here, the execvp call failed.
perror("Failed to execvp the mesos-launcher");
abort();
}
}
// NOTE: This function can be called by the isolator itself or by the
// slave if it doesn't hear about an executor exit after it sends a
// shutdown message.
void ProcessIsolator::killExecutor(
const FrameworkID& frameworkId,
const ExecutorID& executorId)
{
CHECK(initialized) << "Cannot kill executors before initialization!";
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
LOG(ERROR) << "Asked to kill an unknown/killed executor! " << executorId;
return;
}
const Option<pid_t>& pid = infos[frameworkId][executorId]->pid;
if (pid.isSome()) {
// TODO(vinod): Call killtree on the pid of the actual executor process
// that is running the tasks (stored in the local storage by the
// executor module).
os::killtree(pid.get(), SIGKILL, true, true, &LOG(INFO));
// Also kill all processes that belong to the process group of the executor.
// This is valuable in situations where the top level executor process
// exited and hence killtree is unable to kill any spawned orphans.
// NOTE: This assumes that the process group id of the executor process is
// same as its pid (which is expected to be the case with setsid()).
// TODO(vinod): Also (recursively) kill processes belonging to the
// same session, but have a different process group id.
if (killpg(pid.get(), SIGKILL) == -1 && errno != ESRCH) {
PLOG(WARNING) << "Failed to kill process group " << pid.get();
}
infos[frameworkId][executorId]->killed = true;
}
}
void ProcessIsolator::resourcesChanged(
const FrameworkID& frameworkId,
const ExecutorID& executorId,
const Resources& resources)
{
CHECK(initialized) << "Cannot do resourcesChanged before initialization!";
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
LOG(INFO) << "Asked to update resources for an unknown/killed executor '"
<< executorId << "' of framework " << frameworkId;
return;
}
ProcessInfo* info = CHECK_NOTNULL(infos[frameworkId][executorId]);
info->resources = resources;
// Do nothing; subclasses may override this.
}
Future<Nothing> ProcessIsolator::recover(
const Option<SlaveState>& state)
{
LOG(INFO) << "Recovering isolator";
if (state.isNone()) {
return Nothing();
}
foreachvalue (const FrameworkState& framework, state.get().frameworks) {
foreachvalue (const ExecutorState& executor, framework.executors) {
LOG(INFO) << "Recovering executor '" << executor.id
<< "' of framework " << framework.id;
if (executor.info.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its info cannot be recovered";
continue;
}
if (executor.latest.isNone()) {
LOG(WARNING) << "Skipping recovery of executor '" << executor.id
<< "' of framework " << framework.id
<< " because its latest run cannot be recovered";
continue;
}
// We are only interested in the latest run of the executor!
const UUID& uuid = executor.latest.get();
CHECK(executor.runs.contains(uuid));
const RunState& run = executor.runs.get(uuid).get();
ProcessInfo* info =
new ProcessInfo(framework.id, executor.id, run.forkedPid);
infos[framework.id][executor.id] = info;
// Add the pid to the reaper to monitor exit status.
if (run.forkedPid.isSome()) {
reaper.monitor(run.forkedPid.get())
.onAny(defer(PID<ProcessIsolator>(this),
&ProcessIsolator::reaped,
run.forkedPid.get(),
lambda::_1));
}
}
}
return Nothing();
}
Future<ResourceStatistics> ProcessIsolator::usage(
const FrameworkID& frameworkId,
const ExecutorID& executorId)
{
if (!infos.contains(frameworkId) ||
!infos[frameworkId].contains(executorId) ||
infos[frameworkId][executorId]->killed) {
return Future<ResourceStatistics>::failed("Unknown/killed executor");
}
ProcessInfo* info = infos[frameworkId][executorId];
CHECK_NOTNULL(info);
ResourceStatistics result;
result.set_timestamp(Clock::now().secs());
// Set the resource allocations.
const Option<Bytes>& mem = info->resources.mem();
if (mem.isSome()) {
result.set_mem_limit_bytes(mem.get().bytes());
}
const Option<double>& cpus = info->resources.cpus();
if (cpus.isSome()) {
result.set_cpus_limit(cpus.get());
}
CHECK_SOME(info->pid);
Result<os::Process> process = os::process(info->pid.get());
if (!process.isSome()) {
return Future<ResourceStatistics>::failed(
process.isError() ? process.error() : "Process does not exist");
}
result.set_timestamp(Clock::now().secs());
if (process.get().rss.isSome()) {
result.set_mem_rss_bytes(process.get().rss.get().bytes());
}
// We only show utime and stime when both are available, otherwise
// we're exposing a partial view of the CPU times.
if (process.get().utime.isSome() && process.get().stime.isSome()) {
result.set_cpus_user_time_secs(process.get().utime.get().secs());
result.set_cpus_system_time_secs(process.get().stime.get().secs());
}
// Now aggregate all descendant process usage statistics.
const Try<set<pid_t> >& children = os::children(info->pid.get(), true);
if (children.isError()) {
return Future<ResourceStatistics>::failed(
"Failed to get children of " + stringify(info->pid.get()) + ": " +
children.error());
}
// Aggregate the usage of all child processes.
foreach (pid_t child, children.get()) {
process = os::process(child);
// Skip processes that disappear.
if (process.isNone()) {
continue;
}
if (process.isError()) {
LOG(WARNING) << "Failed to get status of descendant process " << child
<< " of parent " << info->pid.get() << ": "
<< process.error();
continue;
}
if (process.get().rss.isSome()) {
result.set_mem_rss_bytes(
result.mem_rss_bytes() + process.get().rss.get().bytes());
}
// We only show utime and stime when both are available, otherwise
// we're exposing a partial view of the CPU times.
if (process.get().utime.isSome() && process.get().stime.isSome()) {
result.set_cpus_user_time_secs(
result.cpus_user_time_secs() + process.get().utime.get().secs());
result.set_cpus_system_time_secs(
result.cpus_system_time_secs() + process.get().stime.get().secs());
}
}
return result;
}
void ProcessIsolator::reaped(pid_t pid, const Future<Option<int> >& status)
{
foreachkey (const FrameworkID& frameworkId, infos) {
foreachkey (const ExecutorID& executorId, infos[frameworkId]) {
ProcessInfo* info = infos[frameworkId][executorId];
if (info->pid.isSome() && info->pid.get() == pid) {
if (!status.isReady()) {
LOG(ERROR) << "Failed to get the status for executor '" << executorId
<< "' of framework " << frameworkId << ": "
<< (status.isFailed() ? status.failure() : "discarded");
return;
}
LOG(INFO) << "Telling slave of terminated executor '" << executorId
<< "' of framework " << frameworkId;
dispatch(slave,
&Slave::executorTerminated,
frameworkId,
executorId,
status.get(),
false,
"Executor terminated");
if (!info->killed) {
// Try and cleanup after the executor.
killExecutor(frameworkId, executorId);
}
if (infos[frameworkId].size() == 1) {
infos.erase(frameworkId);
} else {
infos[frameworkId].erase(executorId);
}
delete info;
return;
}
}
}
}
} // namespace slave {
} // namespace internal {
} // namespace mesos {
<|endoftext|>
|
<commit_before>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
namespace etl {
namespace impl {
namespace reduc {
/*!
* \brief Pad the input matrix in the output matrix for convolution as multiplication
* \param in The input matrix
* \param out The output matrix
*/
template <typename F1, typename F2>
void complex_pad_3d(const F1& in, F2& out) {
for (std::size_t outer = 0; outer < etl::dim<0>(in); ++outer) {
auto* direct = out(outer).memory_start();
for (std::size_t i = 0; i < etl::dim<1>(in); ++i) {
for (std::size_t j = 0; j < etl::dim<2>(in); ++j) {
direct[i * out.template dim<2>() + j] = in(outer, i, j);
}
}
}
}
/*!
* \brief Pad the input matrix in the output matrix for convolution as multiplication
* \param in The input matrix
* \param out The output matrix
*/
template <typename F1, typename F2>
void complex_pad_2d(const F1& in, F2& out) {
auto* direct = out.memory_start();
for (std::size_t i = 0; i < etl::dim<0>(in); ++i) {
for (std::size_t j = 0; j < etl::dim<1>(in); ++j) {
direct[i * out.template dim<1>() + j] = in(i, j);
}
}
}
/*!
* \brief Standard implementation of a 2D 'valid' convolution C = I * K, with multiple kernels
* \param input The input matrix
* \param kernel The kernel matrix
* \param conv The output matrix
*/
template <typename I, typename K_T, typename C>
void fft_conv2_valid_multi(const I& input, const K_T& kernels, C&& conv) {
const std::size_t K = etl::dim<0>(kernels);
const std::size_t i1 = etl::dim<0>(input);
const std::size_t i2 = etl::dim<1>(input);
const std::size_t k1 = etl::dim<1>(kernels);
const std::size_t k2 = etl::dim<2>(kernels);
const std::size_t v1 = i1 - k1 + 1;
const std::size_t v2 = i2 - k2 + 1;
const std::size_t t1 = i1 + k1 - 1;
const std::size_t t2 = i2 + k2 - 1;
const std::size_t b1 = (t1 - v1) / 2;
const std::size_t b2 = (t2 - v2) / 2;
etl::dyn_matrix<std::complex<value_t<I>>> input_padded(t1, t2);
etl::dyn_matrix<std::complex<value_t<I>>, 3> kernels_padded(K, t1, t2);
etl::dyn_matrix<std::complex<value_t<I>>, 3> tmp_result(K, t1, t2);
complex_pad_2d(input, input_padded);
complex_pad_3d(kernels, kernels_padded);
input_padded.fft2_inplace();
kernels_padded.fft2_many_inplace();
for (std::size_t k = 0; k < K; ++k) {
tmp_result(k) = input_padded >> kernels_padded(k);
}
tmp_result.ifft2_many_inplace();
for (std::size_t k = 0; k < K; ++k) {
for (std::size_t i = 0; i < v1; ++i) {
for (std::size_t j = 0; j < v2; ++j) {
conv(k, i, j) = tmp_result(k, i + b1, j + b2).real();
}
}
}
}
/*!
* \brief BLAS implementation of a 2D 'valid' convolution C = I * K, with multiple kernels
* \param input The input matrix
* \param kernel The kernel matrix
* \param conv The output matrix
*/
template <typename I, typename K_T, typename C>
void blas_conv2_valid_multi(const I& input, const K_T& kernels, C&& conv) {
const std::size_t K = etl::dim<0>(kernels);
const std::size_t v1 = etl::dim<0>(input);
const std::size_t v2 = etl::dim<1>(input);
const std::size_t k1 = etl::dim<1>(kernels);
const std::size_t k2 = etl::dim<2>(kernels);
const std::size_t f1 = etl::dim<1>(conv);
const std::size_t f2 = etl::dim<2>(conv);
auto prepared_k = force_temporary(kernels);
for (std::size_t i = 0; i < K; ++i) {
prepared_k(i).fflip_inplace();
}
etl::dyn_matrix<value_t<I>, 2> input_col(k1 * k2, (v1 - k1 + 1) * (v2 - k2 + 1));
im2col_direct_tr(input_col, input, k1, k2);
*mul(
etl::reshape(prepared_k, K, k1 * k2),
input_col,
etl::reshape(conv, K, f1 * f2));
}
/*!
* \brief Standard implementation of a 2D 'valid' convolution C = I * K, with multiple flipped kernels
* \param input The input matrix
* \param kernel The kernel matrix
* \param conv The output matrix
*/
template <typename I, typename K_T, typename C>
void fft_conv2_valid_multi_flipped(const I& input, const K_T& kernels, C&& conv) {
auto kernels_f = etl::force_temporary(kernels);
for (std::size_t i = 0; i < etl::dim<0>(kernels_f); ++i) {
kernels_f(i).fflip_inplace();
}
fft_conv2_valid_multi(input, kernels_f, conv);
}
/*!
* \brief BLAS implementation of a 2D 'valid' convolution C = I * K, with multiple flipped kernels
* \param input The input matrix
* \param kernel The kernel matrix
* \param conv The output matrix
*/
template <typename I, typename K_T, typename C>
void blas_conv2_valid_multi_flipped(const I& input, const K_T& kernels, C&& conv) {
const std::size_t K = etl::dim<0>(kernels);
const std::size_t v1 = etl::dim<0>(input);
const std::size_t v2 = etl::dim<1>(input);
const std::size_t f1 = etl::dim<1>(conv);
const std::size_t f2 = etl::dim<2>(conv);
const std::size_t k1 = etl::dim<1>(kernels);
const std::size_t k2 = etl::dim<2>(kernels);
etl::dyn_matrix<value_t<I>, 2> input_col(k1 * k2, (v1 - k1 + 1) * (v2 - k2 + 1));
im2col_direct_tr(input_col, input, k1, k2);
*mul(
etl::reshape(kernels, K, k1 * k2),
input_col,
etl::reshape(conv, K, f1 * f2));
}
} //end of namespace reduc
} //end of namespace impl
} //end of namespace etl
<commit_msg>Direct multiplication<commit_after>//=======================================================================
// Copyright (c) 2014-2016 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
// http://opensource.org/licenses/MIT)
//=======================================================================
#pragma once
namespace etl {
namespace impl {
namespace reduc {
/*!
* \brief Pad the input matrix in the output matrix for convolution as multiplication
* \param in The input matrix
* \param out The output matrix
*/
template <typename F1, typename F2>
void complex_pad_3d(const F1& in, F2& out) {
for (std::size_t outer = 0; outer < etl::dim<0>(in); ++outer) {
auto* direct = out(outer).memory_start();
for (std::size_t i = 0; i < etl::dim<1>(in); ++i) {
for (std::size_t j = 0; j < etl::dim<2>(in); ++j) {
direct[i * out.template dim<2>() + j] = in(outer, i, j);
}
}
}
}
/*!
* \brief Pad the input matrix in the output matrix for convolution as multiplication
* \param in The input matrix
* \param out The output matrix
*/
template <typename F1, typename F2>
void complex_pad_2d(const F1& in, F2& out) {
auto* direct = out.memory_start();
for (std::size_t i = 0; i < etl::dim<0>(in); ++i) {
for (std::size_t j = 0; j < etl::dim<1>(in); ++j) {
direct[i * out.template dim<1>() + j] = in(i, j);
}
}
}
/*!
* \brief Standard implementation of a 2D 'valid' convolution C = I * K, with multiple kernels
* \param input The input matrix
* \param kernel The kernel matrix
* \param conv The output matrix
*/
template <typename I, typename K_T, typename C>
void fft_conv2_valid_multi(const I& input, const K_T& kernels, C&& conv) {
const std::size_t K = etl::dim<0>(kernels);
const std::size_t i1 = etl::dim<0>(input);
const std::size_t i2 = etl::dim<1>(input);
const std::size_t k1 = etl::dim<1>(kernels);
const std::size_t k2 = etl::dim<2>(kernels);
const std::size_t v1 = i1 - k1 + 1;
const std::size_t v2 = i2 - k2 + 1;
const std::size_t t1 = i1 + k1 - 1;
const std::size_t t2 = i2 + k2 - 1;
const std::size_t b1 = (t1 - v1) / 2;
const std::size_t b2 = (t2 - v2) / 2;
etl::dyn_matrix<std::complex<value_t<I>>> input_padded(t1, t2);
etl::dyn_matrix<std::complex<value_t<I>>, 3> kernels_padded(K, t1, t2);
etl::dyn_matrix<std::complex<value_t<I>>, 3> tmp_result(K, t1, t2);
complex_pad_2d(input, input_padded);
complex_pad_3d(kernels, kernels_padded);
input_padded.fft2_inplace();
kernels_padded.fft2_many_inplace();
for (std::size_t k = 0; k < K; ++k) {
tmp_result(k) = input_padded >> kernels_padded(k);
}
tmp_result.ifft2_many_inplace();
for (std::size_t k = 0; k < K; ++k) {
for (std::size_t i = 0; i < v1; ++i) {
for (std::size_t j = 0; j < v2; ++j) {
conv(k, i, j) = tmp_result(k, i + b1, j + b2).real();
}
}
}
}
/*!
* \brief BLAS implementation of a 2D 'valid' convolution C = I * K, with multiple kernels
* \param input The input matrix
* \param kernel The kernel matrix
* \param conv The output matrix
*/
template <typename I, typename K_T, typename C>
void blas_conv2_valid_multi(const I& input, const K_T& kernels, C&& conv) {
const std::size_t K = etl::dim<0>(kernels);
const std::size_t v1 = etl::dim<0>(input);
const std::size_t v2 = etl::dim<1>(input);
const std::size_t k1 = etl::dim<1>(kernels);
const std::size_t k2 = etl::dim<2>(kernels);
const std::size_t f1 = etl::dim<1>(conv);
const std::size_t f2 = etl::dim<2>(conv);
auto prepared_k = force_temporary(kernels);
for (std::size_t i = 0; i < K; ++i) {
prepared_k(i).fflip_inplace();
}
etl::dyn_matrix<value_t<I>, 2> input_col(k1 * k2, (v1 - k1 + 1) * (v2 - k2 + 1));
im2col_direct_tr(input_col, input, k1, k2);
etl::reshape(conv, K, f1 * f2) = mul(etl::reshape(prepared_k, K, k1 * k2), input_col);
}
/*!
* \brief Standard implementation of a 2D 'valid' convolution C = I * K, with multiple flipped kernels
* \param input The input matrix
* \param kernel The kernel matrix
* \param conv The output matrix
*/
template <typename I, typename K_T, typename C>
void fft_conv2_valid_multi_flipped(const I& input, const K_T& kernels, C&& conv) {
auto kernels_f = etl::force_temporary(kernels);
for (std::size_t i = 0; i < etl::dim<0>(kernels_f); ++i) {
kernels_f(i).fflip_inplace();
}
fft_conv2_valid_multi(input, kernels_f, conv);
}
/*!
* \brief BLAS implementation of a 2D 'valid' convolution C = I * K, with multiple flipped kernels
* \param input The input matrix
* \param kernel The kernel matrix
* \param conv The output matrix
*/
template <typename I, typename K_T, typename C>
void blas_conv2_valid_multi_flipped(const I& input, const K_T& kernels, C&& conv) {
const std::size_t K = etl::dim<0>(kernels);
const std::size_t v1 = etl::dim<0>(input);
const std::size_t v2 = etl::dim<1>(input);
const std::size_t f1 = etl::dim<1>(conv);
const std::size_t f2 = etl::dim<2>(conv);
const std::size_t k1 = etl::dim<1>(kernels);
const std::size_t k2 = etl::dim<2>(kernels);
etl::dyn_matrix<value_t<I>, 2> input_col(k1 * k2, (v1 - k1 + 1) * (v2 - k2 + 1));
im2col_direct_tr(input_col, input, k1, k2);
etl::reshape(conv, K, f1 * f2) = mul(etl::reshape(kernels, K, k1 * k2), input_col);
}
} //end of namespace reduc
} //end of namespace impl
} //end of namespace etl
<|endoftext|>
|
<commit_before>//
// Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ParallelPrimeSieve.h"
#include "PrimeSieve.h"
#include "imath.h"
#include "config.h"
#ifdef _OPENMP
#include <omp.h>
#include "openmp_RAII.h"
#endif
#include <stdint.h>
#include <cstdlib>
#include <cassert>
#include <algorithm>
using namespace soe;
ParallelPrimeSieve::ParallelPrimeSieve() :
shm_(NULL),
numThreads_(IDEAL_NUM_THREADS)
{ }
/// API for the primesieve GUI application
void ParallelPrimeSieve::init(SharedMemory& shm) {
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
/// Get the number of logical CPU cores
int ParallelPrimeSieve::getMaxThreads() {
#ifdef _OPENMP
return omp_get_max_threads();
#else
return 1;
#endif
}
/// Get the current set number of threads for sieving
int ParallelPrimeSieve::getNumThreads() const {
return (numThreads_ == IDEAL_NUM_THREADS) ? idealNumThreads() : numThreads_;
}
/// Set the number of threads for sieving
void ParallelPrimeSieve::setNumThreads(int threads) {
numThreads_ = getInBetween(1, threads, getMaxThreads());
}
int ParallelPrimeSieve::idealNumThreads() const {
// use 1 thread to generate primes in arithmetic order
if (isGenerate()) return 1;
// each thread sieves at least an interval of size sqrt(x) / 5
// but not smaller than MIN_THREAD_INTERVAL
uint64_t threshold = std::max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = getInBetween<uint64_t>(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load balance
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const {
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = std::min(balanced, unbalanced);
uint64_t threadInterval = getInBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = std::max(config::MIN_THREAD_INTERVAL, unbalanced);
// align to modulo 30 to prevent prime k-tuplet gaps
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
#ifdef _OPENMP
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock() {
omp_set_lock(&lock_);
}
void ParallelPrimeSieve::unsetLock() {
omp_unset_lock(&lock_);
}
/// Calculate the sieving status (in percent).
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock) {
OmpGuard lock(lock_, waitForLock);
if (lock.isSet()) {
PrimeSieve::updateStatus(processed, false);
if (shm_ != NULL)
shm_->status = getStatus();
}
return lock.isSet();
}
bool ParallelPrimeSieve::tooMany(int threads) const {
return (threads > 1 && getInterval() / threads < config::MIN_THREAD_INTERVAL);
}
/// Sieve the primes and prime k-tuplets within [start, stop]
/// in parallel using OpenMP (version 3.0 or later).
///
void ParallelPrimeSieve::sieve() {
if (start_ > stop_)
throw primesieve_error("start must be <= stop");
int threads = getNumThreads();
if (tooMany(threads)) threads = idealNumThreads();
OmpInitGuard init(lock_);
if (threads == 1)
PrimeSieve::sieve();
else {
double t1 = omp_get_wtime();
reset();
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
uint64_t align = start_ + 32 - start_ % 30;
uint64_t threadInterval = getThreadInterval(threads);
// The sieve interval [start_, stop_] is subdivided into chunks of
// size 'threadInterval' that are sieved in parallel using
// multiple threads. This scales well as each thread sieves using
// its own private memory without need of synchronization.
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (uint64_t n = align; n < stop_; n += threadInterval) {
uint64_t threadStart = (n == align) ? start_ : n;
uint64_t threadStop = std::min(n + threadInterval, stop_);
PrimeSieve ps(*this, omp_get_thread_num());
ps.sieve(threadStart, threadStop);
count0 += ps.getCounts(0);
count1 += ps.getCounts(1);
count2 += ps.getCounts(2);
count3 += ps.getCounts(3);
count4 += ps.getCounts(4);
count5 += ps.getCounts(5);
count6 += ps.getCounts(6);
}
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
counts_[6] = count6;
seconds_ = omp_get_wtime() - t1;
}
// communicate the sieving results to the
// primesieve GUI application
if (shm_ != NULL) {
std::copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
#endif
<commit_msg>updated<commit_after>//
// Copyright (c) 2012 Kim Walisch, <kim.walisch@gmail.com>.
// All rights reserved.
//
// This file is part of primesieve.
// Homepage: http://primesieve.googlecode.com
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of the author nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.
#include "ParallelPrimeSieve.h"
#include "PrimeSieve.h"
#include "imath.h"
#include "config.h"
#ifdef _OPENMP
#include <omp.h>
#include "openmp_RAII.h"
#endif
#include <stdint.h>
#include <cstdlib>
#include <cassert>
#include <algorithm>
using namespace soe;
ParallelPrimeSieve::ParallelPrimeSieve() :
shm_(NULL),
numThreads_(IDEAL_NUM_THREADS)
{ }
/// API for the primesieve GUI application
void ParallelPrimeSieve::init(SharedMemory& shm) {
setStart(shm.start);
setStop(shm.stop);
setSieveSize(shm.sieveSize);
setFlags(shm.flags);
setNumThreads(shm.threads);
shm_ = &shm;
}
/// Get the number of CPU cores
int ParallelPrimeSieve::getMaxThreads() {
#ifdef _OPENMP
return omp_get_max_threads();
#else
return 1;
#endif
}
/// Get the current set number of threads for sieving
int ParallelPrimeSieve::getNumThreads() const {
return (numThreads_ == IDEAL_NUM_THREADS) ? idealNumThreads() : numThreads_;
}
/// Set the number of threads for sieving
void ParallelPrimeSieve::setNumThreads(int threads) {
numThreads_ = getInBetween(1, threads, getMaxThreads());
}
int ParallelPrimeSieve::idealNumThreads() const {
// use 1 thread to generate primes in arithmetic order
if (isGenerate()) return 1;
// each thread sieves at least an interval of size sqrt(x) / 5
// but not smaller than MIN_THREAD_INTERVAL
uint64_t threshold = std::max(config::MIN_THREAD_INTERVAL, isqrt(stop_) / 5);
uint64_t threads = getInterval() / threshold;
threads = getInBetween<uint64_t>(1, threads, getMaxThreads());
return static_cast<int>(threads);
}
/// Get an interval size that ensures a good load balance
uint64_t ParallelPrimeSieve::getThreadInterval(int threads) const {
assert(threads > 0);
uint64_t unbalanced = getInterval() / threads;
uint64_t balanced = isqrt(stop_) * 1000;
uint64_t fastest = std::min(balanced, unbalanced);
uint64_t threadInterval = getInBetween(config::MIN_THREAD_INTERVAL, fastest, config::MAX_THREAD_INTERVAL);
uint64_t chunks = getInterval() / threadInterval;
if (chunks < threads * 5u)
threadInterval = std::max(config::MIN_THREAD_INTERVAL, unbalanced);
// align to modulo 30 to prevent prime k-tuplet gaps
threadInterval += 30 - threadInterval % 30;
return threadInterval;
}
#ifdef _OPENMP
/// Used to synchronize threads for prime number generation
void ParallelPrimeSieve::setLock() {
omp_set_lock(&lock_);
}
void ParallelPrimeSieve::unsetLock() {
omp_unset_lock(&lock_);
}
/// Calculate the sieving status (in percent).
/// @param processed Sum of recently processed segments.
///
bool ParallelPrimeSieve::updateStatus(uint64_t processed, bool waitForLock) {
OmpGuard lock(lock_, waitForLock);
if (lock.isSet()) {
PrimeSieve::updateStatus(processed, false);
if (shm_ != NULL)
shm_->status = getStatus();
}
return lock.isSet();
}
bool ParallelPrimeSieve::tooMany(int threads) const {
return (threads > 1 && getInterval() / threads < config::MIN_THREAD_INTERVAL);
}
/// Sieve the primes and prime k-tuplets within [start, stop]
/// in parallel using OpenMP (version 3.0 or later).
///
void ParallelPrimeSieve::sieve() {
if (start_ > stop_)
throw primesieve_error("start must be <= stop");
int threads = getNumThreads();
if (tooMany(threads)) threads = idealNumThreads();
OmpInitGuard init(lock_);
if (threads == 1)
PrimeSieve::sieve();
else {
double t1 = omp_get_wtime();
reset();
uint64_t count0 = 0, count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0, count6 = 0;
uint64_t align = start_ + 32 - start_ % 30;
uint64_t threadInterval = getThreadInterval(threads);
// The sieve interval [start_, stop_] is subdivided into chunks of
// size 'threadInterval' that are sieved in parallel using
// multiple threads. This scales well as each thread sieves using
// its own private memory without need of synchronization.
#pragma omp parallel for schedule(dynamic) num_threads(threads) \
reduction(+: count0, count1, count2, count3, count4, count5, count6)
for (uint64_t n = align; n < stop_; n += threadInterval) {
uint64_t threadStart = (n == align) ? start_ : n;
uint64_t threadStop = std::min(n + threadInterval, stop_);
PrimeSieve ps(*this, omp_get_thread_num());
ps.sieve(threadStart, threadStop);
count0 += ps.getCounts(0);
count1 += ps.getCounts(1);
count2 += ps.getCounts(2);
count3 += ps.getCounts(3);
count4 += ps.getCounts(4);
count5 += ps.getCounts(5);
count6 += ps.getCounts(6);
}
counts_[0] = count0;
counts_[1] = count1;
counts_[2] = count2;
counts_[3] = count3;
counts_[4] = count4;
counts_[5] = count5;
counts_[6] = count6;
seconds_ = omp_get_wtime() - t1;
}
// communicate the sieving results to the
// primesieve GUI application
if (shm_ != NULL) {
std::copy(counts_.begin(), counts_.end(), shm_->counts);
shm_->seconds = seconds_;
}
}
#endif
<|endoftext|>
|
<commit_before>/*
* Copyright (c) 2015 Intel Corporation. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "BleCharacteristic.h"
#include "internal/ble_client.h"
#define BLE_CCCD_DESCRIPTOR_UUID 0x2092
#define BLE_CCCD_NOTIFY_EN_MASK 0x1
#define BLE_CCCD_INDICATE_EN_MASK 0x2
/* Each characteristic has a Client Characteristic Configuration Descriptor (CCCD)
* This callback is invoked whenever the CCCD for a given characteristic is updated
* by a remote client to enable/disable receipt of notifications/indications
*/
void
_cccdEventHandler(BleDescriptor &cccd, BleDescriptorEvent event, void *arg)
{
if (BLE_DESC_EVENT_WRITE == event) {
BleStatus status;
uint16_t cccdVal;
BleCharacteristic *ch = (BleCharacteristic *)arg;
status = cccd.getValue(cccdVal);
if (BLE_STATUS_SUCCESS != status)
return;
ch->_notifyEnabled = (cccdVal & BLE_CCCD_NOTIFY_EN_MASK) ? true : false;
ch->_indicateEnabled = (cccdVal & BLE_CCCD_INDICATE_EN_MASK) ? true : false;
}
}
BleCharacteristic::BleCharacteristic(const uint16_t maxLength,
const BleClientAccessMode clientAccess,
const BleClientNotifyMode clientNotify)
: _cccd(BLE_CCCD_DESCRIPTOR_UUID, sizeof(uint16_t), BLE_CLIENT_ACCESS_READ_WRITE)
{
_initialised = false;
_connected = false;
_notifyEnabled = false;
_indicateEnabled = false;
_data_len = 0;
_data[0] = 0;
_clientAccess = clientAccess;
_clientNotify = clientNotify;
memset(&_char_data, 0, sizeof(_char_data));
_char_data.p_uuid = &_uuid;
if ((_clientAccess == BLE_CLIENT_ACCESS_READ_ONLY) ||
(_clientAccess == BLE_CLIENT_ACCESS_READ_WRITE)) {
_char_data.perms.rd = GAP_SEC_MODE_1 | GAP_SEC_LEVEL_1;
_char_data.props.props |= BLE_GATT_CHAR_PROP_BIT_READ;
/* Enable notifications only if characteristic is also readable by client */
if (_clientNotify == BLE_CLIENT_NOTIFY_ENABLED)
_char_data.props.props |= BLE_GATT_CHAR_PROP_BIT_NOTIFY;
else if (_clientNotify == BLE_CLIENT_NOTIFY_WITH_ACK)
_char_data.props.props |= BLE_GATT_CHAR_PROP_BIT_INDICATE;
}
else {
_char_data.perms.rd = GAP_SEC_NO_PERMISSION;
}
if ((_clientAccess == BLE_CLIENT_ACCESS_WRITE_ONLY) ||
(_clientAccess == BLE_CLIENT_ACCESS_READ_WRITE)) {
_char_data.perms.wr = GAP_SEC_MODE_1 | GAP_SEC_LEVEL_1;
_char_data.props.props |= (BLE_GATT_CHAR_PROP_BIT_WRITE | BLE_GATT_CHAR_PROP_BIT_WRITE_NR);
}
else {
_char_data.perms.wr = GAP_SEC_NO_PERMISSION;
}
_char_data.init_len = _data_len;
_char_data.max_len = maxLength > BLE_MAX_ATTR_DATA_LEN ? BLE_MAX_ATTR_DATA_LEN : maxLength;
_char_data.p_value = _data;
}
BleCharacteristic::BleCharacteristic(const uint16_t uuid16,
const uint16_t maxLength,
const BleClientAccessMode clientAccess,
const BleClientNotifyMode clientNotify)
: BleCharacteristic(maxLength, clientAccess, clientNotify)
{
_uuid.type = BT_UUID16;
_uuid.uuid16 = uuid16;
}
BleCharacteristic::BleCharacteristic(const uint8_t uuid128[],
const uint16_t maxLength,
const BleClientAccessMode clientAccess,
const BleClientNotifyMode clientNotify)
: BleCharacteristic(maxLength, clientAccess, clientNotify)
{
_uuid.type = BT_UUID128;
memcpy(&_uuid.uuid128, uuid128, MAX_UUID_SIZE);
}
BleStatus
BleCharacteristic::addUserDescription(const char *description)
{
if (_initialised)
return BLE_STATUS_WRONG_STATE;
if (description && description[0]) {
_user_desc.len = strlen(description);
if (_user_desc.len > sizeof(_user_desc_data))
_user_desc.len = sizeof(_user_desc_data);
memset(_user_desc_data, 0, sizeof(_user_desc_data));
memcpy(_user_desc_data, description, _user_desc.len);
_user_desc.buffer = _user_desc_data;
_char_data.p_user_desc = &_user_desc;
}
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::addPresentationFormat(const uint8_t format,
const int8_t exponent,
const uint16_t unit,
const uint8_t nameSpace,
const uint16_t description)
{
if (_initialised)
return BLE_STATUS_WRONG_STATE;
_pf_desc.format = format;
_pf_desc.exp = exponent;
_pf_desc.unit = unit;
_pf_desc.name_spc = nameSpace;
_pf_desc.descr = description;
_char_data.p_char_pf_desc = &_pf_desc;
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::_setValue(void)
{
BleStatus status;
if (!_initialised)
return BLE_STATUS_WRONG_STATE;
if ((_data_len > BLE_MAX_ATTR_DATA_LEN) && (_data_len > _char_data.max_len))
return BLE_STATUS_NOT_ALLOWED;
status = ble_client_gatts_set_attribute_value(_handles.value_handle,
_data_len, _data, 0);
if (BLE_STATUS_SUCCESS != status)
return status;
if (_notifyEnabled || _indicateEnabled) {
status = ble_client_gatts_send_notif_ind(_handles.value_handle, _data_len, _data, 0, _indicateEnabled);
if (BLE_STATUS_SUCCESS != status)
return status;
if (_indicateEnabled && _event_cb)
_event_cb(*this, BLE_CHAR_EVENT_INDICATION_ACK, _event_cb_arg);
}
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::setValue(const uint8_t value[], const uint16_t length)
{
if (!value)
return BLE_STATUS_NOT_ALLOWED;
if (length > _char_data.max_len)
return BLE_STATUS_NOT_ALLOWED;
/* Cache the value locally */
memcpy(_data, value, length);
_data_len = length;
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const String &str)
{
str.getBytes((unsigned char *)&_data, (unsigned int)_char_data.max_len, 0U);
_data_len = str.length() + 1;
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const char *cstr)
{
return setValue((uint8_t *)cstr, (uint16_t) (strlen(cstr) + 1));
}
BleStatus
BleCharacteristic::setValue(const char &value)
{
uint8_t *p = _data;
INT8_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const unsigned char &value)
{
uint8_t *p = _data;
UINT8_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const short &value)
{
uint8_t *p = _data;
INT16_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const unsigned short &value)
{
uint8_t *p = _data;
UINT16_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const int &value)
{
uint8_t *p = _data;
INT32_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const unsigned int &value)
{
uint8_t *p = _data;
UINT32_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const long &value)
{
uint8_t *p = _data;
INT32_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const unsigned long &value)
{
uint8_t *p = _data;
UINT32_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::getValue(uint8_t value[], uint16_t &length) const
{
if (!_initialised)
return BLE_STATUS_WRONG_STATE;
memcpy(value, _data, _data_len);
length = _data_len;
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(String &str) const
{
str = (char *)_data;
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(char *cstr) const
{
memcpy(cstr, _data, _data_len);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(char &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_INT8(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(unsigned char &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_UINT8(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(short &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_INT16(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(unsigned short &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_UINT16(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(int &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_INT32(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(unsigned int &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_UINT32(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(long &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_INT32(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(unsigned long &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_UINT32(p, value);
return BLE_STATUS_SUCCESS;
}
void
BleCharacteristic::setEventCallback(BleCharacteristicEventCb callback,
void *arg)
{
noInterrupts();
_event_cb = callback; /* callback disabled if NULL */
_event_cb_arg = arg;
interrupts();
}
BleStatus
BleCharacteristic::addDescriptor(BleDescriptor &descriptor)
{
BleStatus status;
if (!_initialised)
return BLE_STATUS_WRONG_STATE;
if (_num_descriptors >= BLE_MAX_DESCRIPTORS)
return BLE_STATUS_ERROR;
/* If this service has a 128-bit UUID, it shall be inherited
* by included services, characteristics, and descriptors
*/
if ((BT_UUID128 == _uuid.type) && (BT_UUID16 == descriptor._uuid.type))
BLE_UUID16_TO_UUID128(descriptor._uuid, _uuid);
status = ble_client_gatts_add_descriptor(_svc_handle,
&descriptor._desc,
&descriptor._handle);
if (BLE_STATUS_SUCCESS == status) {
descriptor._initialised = true;
_descriptors[_num_descriptors++] = &descriptor;
}
return status;
}
BleDescriptor *
BleCharacteristic::_matchDescriptor(uint16_t handle) const
{
for (unsigned i = 0; i < _num_descriptors; i++) {
BleDescriptor *desc = _descriptors[i];
if (handle == desc->_handle)
return desc;
}
return NULL;
}
void
BleCharacteristic::_addCCCDescriptor(void)
{
/* Activate our CCCD descriptor object */
_cccd._handle = _handles.cccd_handle;
_cccd._initialised = true;
_cccd.setEventCallback(_cccdEventHandler, (void *)this);
_descriptors[_num_descriptors++] = &_cccd;
}
void
BleCharacteristic::_setConnectedState(boolean_t connected)
{
_connected = connected;
/* Reset the state of these internal variables when connection is dropped */
if (!connected) {
_notifyEnabled = false;
_indicateEnabled = false;
}
/* Cascade the connected-state update to descriptors */
for (unsigned i = 0; i < _num_descriptors; i++)
_descriptors[i]->_setConnectedState(connected);
}
<commit_msg>Fix Klocwork#2051,2060: Array may be outside index<commit_after>/*
* Copyright (c) 2015 Intel Corporation. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
*/
#include "BleCharacteristic.h"
#include "internal/ble_client.h"
#define BLE_CCCD_DESCRIPTOR_UUID 0x2092
#define BLE_CCCD_NOTIFY_EN_MASK 0x1
#define BLE_CCCD_INDICATE_EN_MASK 0x2
/* Each characteristic has a Client Characteristic Configuration Descriptor (CCCD)
* This callback is invoked whenever the CCCD for a given characteristic is updated
* by a remote client to enable/disable receipt of notifications/indications
*/
void
_cccdEventHandler(BleDescriptor &cccd, BleDescriptorEvent event, void *arg)
{
if (BLE_DESC_EVENT_WRITE == event) {
BleStatus status;
uint16_t cccdVal;
BleCharacteristic *ch = (BleCharacteristic *)arg;
status = cccd.getValue(cccdVal);
if (BLE_STATUS_SUCCESS != status)
return;
ch->_notifyEnabled = (cccdVal & BLE_CCCD_NOTIFY_EN_MASK) ? true : false;
ch->_indicateEnabled = (cccdVal & BLE_CCCD_INDICATE_EN_MASK) ? true : false;
}
}
BleCharacteristic::BleCharacteristic(const uint16_t maxLength,
const BleClientAccessMode clientAccess,
const BleClientNotifyMode clientNotify)
: _cccd(BLE_CCCD_DESCRIPTOR_UUID, sizeof(uint16_t), BLE_CLIENT_ACCESS_READ_WRITE)
{
_initialised = false;
_connected = false;
_notifyEnabled = false;
_indicateEnabled = false;
_data_len = 0;
_data[0] = 0;
_clientAccess = clientAccess;
_clientNotify = clientNotify;
memset(&_char_data, 0, sizeof(_char_data));
_char_data.p_uuid = &_uuid;
if ((_clientAccess == BLE_CLIENT_ACCESS_READ_ONLY) ||
(_clientAccess == BLE_CLIENT_ACCESS_READ_WRITE)) {
_char_data.perms.rd = GAP_SEC_MODE_1 | GAP_SEC_LEVEL_1;
_char_data.props.props |= BLE_GATT_CHAR_PROP_BIT_READ;
/* Enable notifications only if characteristic is also readable by client */
if (_clientNotify == BLE_CLIENT_NOTIFY_ENABLED)
_char_data.props.props |= BLE_GATT_CHAR_PROP_BIT_NOTIFY;
else if (_clientNotify == BLE_CLIENT_NOTIFY_WITH_ACK)
_char_data.props.props |= BLE_GATT_CHAR_PROP_BIT_INDICATE;
}
else {
_char_data.perms.rd = GAP_SEC_NO_PERMISSION;
}
if ((_clientAccess == BLE_CLIENT_ACCESS_WRITE_ONLY) ||
(_clientAccess == BLE_CLIENT_ACCESS_READ_WRITE)) {
_char_data.perms.wr = GAP_SEC_MODE_1 | GAP_SEC_LEVEL_1;
_char_data.props.props |= (BLE_GATT_CHAR_PROP_BIT_WRITE | BLE_GATT_CHAR_PROP_BIT_WRITE_NR);
}
else {
_char_data.perms.wr = GAP_SEC_NO_PERMISSION;
}
_char_data.init_len = _data_len;
_char_data.max_len = maxLength > BLE_MAX_ATTR_DATA_LEN ? BLE_MAX_ATTR_DATA_LEN : maxLength;
_char_data.p_value = _data;
}
BleCharacteristic::BleCharacteristic(const uint16_t uuid16,
const uint16_t maxLength,
const BleClientAccessMode clientAccess,
const BleClientNotifyMode clientNotify)
: BleCharacteristic(maxLength, clientAccess, clientNotify)
{
_uuid.type = BT_UUID16;
_uuid.uuid16 = uuid16;
}
BleCharacteristic::BleCharacteristic(const uint8_t uuid128[],
const uint16_t maxLength,
const BleClientAccessMode clientAccess,
const BleClientNotifyMode clientNotify)
: BleCharacteristic(maxLength, clientAccess, clientNotify)
{
_uuid.type = BT_UUID128;
memcpy(&_uuid.uuid128, uuid128, MAX_UUID_SIZE);
}
BleStatus
BleCharacteristic::addUserDescription(const char *description)
{
if (_initialised)
return BLE_STATUS_WRONG_STATE;
if (description && description[0]) {
_user_desc.len = strlen(description);
if (_user_desc.len > sizeof(_user_desc_data))
_user_desc.len = sizeof(_user_desc_data);
memset(_user_desc_data, 0, sizeof(_user_desc_data));
memcpy(_user_desc_data, description, _user_desc.len);
_user_desc.buffer = _user_desc_data;
_char_data.p_user_desc = &_user_desc;
}
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::addPresentationFormat(const uint8_t format,
const int8_t exponent,
const uint16_t unit,
const uint8_t nameSpace,
const uint16_t description)
{
if (_initialised)
return BLE_STATUS_WRONG_STATE;
_pf_desc.format = format;
_pf_desc.exp = exponent;
_pf_desc.unit = unit;
_pf_desc.name_spc = nameSpace;
_pf_desc.descr = description;
_char_data.p_char_pf_desc = &_pf_desc;
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::_setValue(void)
{
BleStatus status;
if (!_initialised)
return BLE_STATUS_WRONG_STATE;
if ((_data_len > BLE_MAX_ATTR_DATA_LEN) || (_data_len > _char_data.max_len))
return BLE_STATUS_NOT_ALLOWED;
status = ble_client_gatts_set_attribute_value(_handles.value_handle,
_data_len, _data, 0);
if (BLE_STATUS_SUCCESS != status)
return status;
if (_notifyEnabled || _indicateEnabled) {
status = ble_client_gatts_send_notif_ind(_handles.value_handle, _data_len, _data, 0, _indicateEnabled);
if (BLE_STATUS_SUCCESS != status)
return status;
if (_indicateEnabled && _event_cb)
_event_cb(*this, BLE_CHAR_EVENT_INDICATION_ACK, _event_cb_arg);
}
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::setValue(const uint8_t value[], const uint16_t length)
{
if (!value)
return BLE_STATUS_NOT_ALLOWED;
if (length > _char_data.max_len)
return BLE_STATUS_NOT_ALLOWED;
/* Cache the value locally */
memcpy(_data, value, length);
_data_len = length;
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const String &str)
{
str.getBytes((unsigned char *)&_data, (unsigned int)_char_data.max_len, 0U);
_data_len = str.length() + 1;
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const char *cstr)
{
return setValue((uint8_t *)cstr, (uint16_t) (strlen(cstr) + 1));
}
BleStatus
BleCharacteristic::setValue(const char &value)
{
uint8_t *p = _data;
INT8_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const unsigned char &value)
{
uint8_t *p = _data;
UINT8_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const short &value)
{
uint8_t *p = _data;
INT16_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const unsigned short &value)
{
uint8_t *p = _data;
UINT16_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const int &value)
{
uint8_t *p = _data;
INT32_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const unsigned int &value)
{
uint8_t *p = _data;
UINT32_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const long &value)
{
uint8_t *p = _data;
INT32_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::setValue(const unsigned long &value)
{
uint8_t *p = _data;
UINT32_TO_LESTREAM(p, value);
_data_len = sizeof(value);
return _setValue();
}
BleStatus
BleCharacteristic::getValue(uint8_t value[], uint16_t &length) const
{
if (!_initialised)
return BLE_STATUS_WRONG_STATE;
memcpy(value, _data, _data_len);
length = _data_len;
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(String &str) const
{
str = (char *)_data;
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(char *cstr) const
{
memcpy(cstr, _data, _data_len);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(char &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_INT8(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(unsigned char &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_UINT8(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(short &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_INT16(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(unsigned short &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_UINT16(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(int &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_INT32(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(unsigned int &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_UINT32(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(long &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_INT32(p, value);
return BLE_STATUS_SUCCESS;
}
BleStatus
BleCharacteristic::getValue(unsigned long &value) const
{
const uint8_t *p = _data;
LESTREAM_TO_UINT32(p, value);
return BLE_STATUS_SUCCESS;
}
void
BleCharacteristic::setEventCallback(BleCharacteristicEventCb callback,
void *arg)
{
noInterrupts();
_event_cb = callback; /* callback disabled if NULL */
_event_cb_arg = arg;
interrupts();
}
BleStatus
BleCharacteristic::addDescriptor(BleDescriptor &descriptor)
{
BleStatus status;
if (!_initialised)
return BLE_STATUS_WRONG_STATE;
if (_num_descriptors >= BLE_MAX_DESCRIPTORS)
return BLE_STATUS_ERROR;
/* If this service has a 128-bit UUID, it shall be inherited
* by included services, characteristics, and descriptors
*/
if ((BT_UUID128 == _uuid.type) && (BT_UUID16 == descriptor._uuid.type))
BLE_UUID16_TO_UUID128(descriptor._uuid, _uuid);
status = ble_client_gatts_add_descriptor(_svc_handle,
&descriptor._desc,
&descriptor._handle);
if (BLE_STATUS_SUCCESS == status) {
descriptor._initialised = true;
_descriptors[_num_descriptors++] = &descriptor;
}
return status;
}
BleDescriptor *
BleCharacteristic::_matchDescriptor(uint16_t handle) const
{
for (unsigned i = 0; i < _num_descriptors; i++) {
BleDescriptor *desc = _descriptors[i];
if (handle == desc->_handle)
return desc;
}
return NULL;
}
void
BleCharacteristic::_addCCCDescriptor(void)
{
/* Activate our CCCD descriptor object */
_cccd._handle = _handles.cccd_handle;
_cccd._initialised = true;
_cccd.setEventCallback(_cccdEventHandler, (void *)this);
_descriptors[_num_descriptors++] = &_cccd;
}
void
BleCharacteristic::_setConnectedState(boolean_t connected)
{
_connected = connected;
/* Reset the state of these internal variables when connection is dropped */
if (!connected) {
_notifyEnabled = false;
_indicateEnabled = false;
}
/* Cascade the connected-state update to descriptors */
for (unsigned i = 0; i < _num_descriptors; i++)
_descriptors[i]->_setConnectedState(connected);
}
<|endoftext|>
|
<commit_before>#pragma once
#include <stdexcept>
#include <string>
#include <cassert>
#define NEVER_INLINE __attribute__((noinline))
#define ALWAYS_INLINE __attribute__((always_inline))
#define UNUSED __attribute__((unused))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#define MICROSCOPES_DCHECK(expr, msg) \
do { \
if (unlikely(!(expr))) \
throw ::std::runtime_error(msg); \
} while (0)
// from https://code.google.com/p/protobuf/source/browse/trunk/src/google/protobuf/stubs/common.h
#define MICROSCOPES_ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / \
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
#define _STRINGIFY(x) #x
/**
* __LINE__ comes from the preprocessor as an int.
* Stringify hack comes from:
* http://www.decompile.com/cpp/faq/file_and_line_error_string.htm
*/
#define _LINEHACK(x) _STRINGIFY(x)
#define _SOURCE_INFO \
(::std::string(__PRETTY_FUNCTION__) + \
::std::string(" (" __FILE__ ":" _LINEHACK(__LINE__) ")"))
#define MICROSCOPES_NOT_REACHABLE() \
do { \
throw ::std::runtime_error( \
::std::string("Should not be reached: ") + \
::std::string(_SOURCE_INFO)); \
} while (0)
#ifdef NDEBUG
#define ALWAYS_ASSERT(expr) (likely((expr)) ? (void)0 : abort())
#else
#define ALWAYS_ASSERT(expr) assert((expr))
#endif
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)
#define GCC_AT_LEAST_47 1
#else
#define GCC_AT_LEAST_47 0
#endif
// g++-4.6 does not support override, so we define it to be a no-op
#if !GCC_AT_LEAST_47
#define override
#endif
<commit_msg>don't redefine override on __clang__<commit_after>#pragma once
#include <stdexcept>
#include <string>
#include <cassert>
#define NEVER_INLINE __attribute__((noinline))
#define ALWAYS_INLINE __attribute__((always_inline))
#define UNUSED __attribute__((unused))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#define MICROSCOPES_DCHECK(expr, msg) \
do { \
if (unlikely(!(expr))) \
throw ::std::runtime_error(msg); \
} while (0)
// from https://code.google.com/p/protobuf/source/browse/trunk/src/google/protobuf/stubs/common.h
#define MICROSCOPES_ARRAYSIZE(a) \
((sizeof(a) / sizeof(*(a))) / \
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
#define _STRINGIFY(x) #x
/**
* __LINE__ comes from the preprocessor as an int.
* Stringify hack comes from:
* http://www.decompile.com/cpp/faq/file_and_line_error_string.htm
*/
#define _LINEHACK(x) _STRINGIFY(x)
#define _SOURCE_INFO \
(::std::string(__PRETTY_FUNCTION__) + \
::std::string(" (" __FILE__ ":" _LINEHACK(__LINE__) ")"))
#define MICROSCOPES_NOT_REACHABLE() \
do { \
throw ::std::runtime_error( \
::std::string("Should not be reached: ") + \
::std::string(_SOURCE_INFO)); \
} while (0)
#ifdef NDEBUG
#define ALWAYS_ASSERT(expr) (likely((expr)) ? (void)0 : abort())
#else
#define ALWAYS_ASSERT(expr) assert((expr))
#endif
#if __GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 7)
#define GCC_AT_LEAST_47 1
#else
#define GCC_AT_LEAST_47 0
#endif
// g++-4.6 does not support override, so we define it to be a no-op
#if !defined(__clang__) && !GCC_AT_LEAST_47
#define override
#endif
<|endoftext|>
|
<commit_before>/*
Copyright (C) 2004 by Jorrit Tyberghein
(C) 2004 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/databuf.h"
#include "csutil/scanstr.h"
#include "csutil/util.h"
#include "csutil/xmltiny.h"
#include "csgfx/shaderexp.h"
#include "imap/services.h"
#include "iutil/verbositymanager.h"
#include "iutil/vfs.h"
#include "ivaria/reporter.h"
#include "csplugincommon/shader/shaderprogram.h"
void csShaderProgram::ProgramParam::SetValue (float val)
{
var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID));
var->SetValue (val);
valid = true;
}
void csShaderProgram::ProgramParam::SetValue (const csVector4& val)
{
var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID));
var->SetValue (val);
valid = true;
}
//---------------------------------------------------------------------------
CS_LEAKGUARD_IMPLEMENT (csShaderProgram);
csShaderProgram::csShaderProgram (iObjectRegistry* objectReg)
: scfImplementationType (this)
{
InitCommonTokens (commonTokens);
csShaderProgram::objectReg = objectReg;
synsrv = csQueryRegistry<iSyntaxService> (objectReg);
stringsSvName = csQueryRegistryTagInterface<iShaderVarStringSet>
(objectReg, "crystalspace.shader.variablenameset");
csRef<iVerbosityManager> verbosemgr (
csQueryRegistry<iVerbosityManager> (objectReg));
if (verbosemgr)
doVerbose = verbosemgr->Enabled("renderer.shader");
else
doVerbose = false;
}
csShaderProgram::~csShaderProgram ()
{
}
bool csShaderProgram::ProgramParamParser::ParseProgramParam (
iDocumentNode* node, ProgramParam& param, uint types)
{
const char* type = node->GetAttributeValue ("type");
if (type == 0)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"No 'type' attribute");
return false;
}
// Var for static data
csRef<csShaderVariable> var;
var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID));
ProgramParamType paramType = ParamInvalid;
if (strcmp (type, "shadervar") == 0)
{
const char* value = node->GetContentsValue();
if (!value)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Node has no contents");
return false;
}
CS::Graphics::ShaderVarNameParser nameParse (value);
param.name = stringsSvName->Request (nameParse.GetShaderVarName());
for (size_t n = 0; n < nameParse.GetIndexNum(); n++)
{
param.indices.Push (nameParse.GetIndexValue (n));
}
param.valid = true;
return true;
}
else if (strcmp (type, "int") == 0)
{
paramType = ParamInt;
}
else if (strcmp (type, "float") == 0)
{
paramType = ParamFloat;
}
else if (strcmp (type, "vector2") == 0)
{
paramType = ParamVector2;
}
else if (strcmp (type, "vector3") == 0)
{
paramType = ParamVector3;
}
else if (strcmp (type, "vector4") == 0)
{
paramType = ParamVector4;
}
else if (strcmp (type, "matrix") == 0)
{
paramType = ParamMatrix;
}
else if (strcmp (type, "transform") == 0)
{
paramType = ParamTransform;
}
else if ((strcmp (type, "expression") == 0) || (strcmp (type, "expr") == 0))
{
// Parse exp and save it
csRef<iShaderVariableAccessor> acc = synsrv->ParseShaderVarExpr (node);
var->SetAccessor (acc);
param.var = var;
param.valid = true;
return true;
}
else if (strcmp (type, "array") == 0)
{
csArray<ProgramParam> allParams;
ProgramParam tmpParam;
csRef<iDocumentNodeIterator> it = node->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child = it->Next ();
ParseProgramParam (child, tmpParam, types & 0x3F);
allParams.Push (tmpParam);
}
//Save the params
var->SetType (csShaderVariable::ARRAY);
var->SetArraySize (allParams.GetSize ());
for (uint i = 0; i < allParams.GetSize (); i++)
{
var->SetArrayElement (i, allParams[i].var);
}
paramType = ParamArray;
}
else
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Unknown type '%s'", type);
return false;
}
if (!(types & paramType))
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Type '%s' not supported by this parameter", type);
return false;
}
const uint directValueTypes = ParamInt | ParamFloat | ParamVector2
| ParamVector3 | ParamVector4 | ParamMatrix | ParamTransform;
switch (paramType & directValueTypes)
{
case ParamInvalid:
return false;
break;
case ParamInt:
{
int x = node->GetContentsValueAsInt ();
var->SetValue (x);
}
break;
case ParamFloat:
{
float x = node->GetContentsValueAsFloat ();
var->SetValue (x);
}
break;
case ParamVector2:
{
float x, y;
const char* value = node->GetContentsValue();
if (!value)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Node has no contents");
return false;
}
if (csScanStr (value, "%f,%f", &x, &y) != 2)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Couldn't parse vector2 '%s'", value);
return false;
}
var->SetValue (csVector2 (x,y));
}
break;
case ParamVector3:
{
float x, y, z;
const char* value = node->GetContentsValue();
if (!value)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Node has no contents");
return false;
}
if (csScanStr (value, "%f,%f,%f", &x, &y, &z) != 3)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Couldn't parse vector3 '%s'", value);
return false;
}
var->SetValue (csVector3 (x,y,z));
}
break;
case ParamVector4:
{
float x, y, z, w;
const char* value = node->GetContentsValue();
if (!value)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Node has no contents");
return false;
}
if (csScanStr (value, "%f,%f,%f,%f", &x, &y, &z, &w) != 4)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Couldn't parse vector4 '%s'", value);
return false;
}
var->SetValue (csVector4 (x,y,z,w));
}
break;
case ParamMatrix:
{
csMatrix3 matrix;
if (!synsrv->ParseMatrix (node, matrix))
return false;
var->SetValue (matrix);
}
break;
case ParamTransform:
{
csReversibleTransform t;
csRef<iDocumentNode> matrix_node = node->GetNode ("matrix");
if (matrix_node)
{
csMatrix3 m;
if (!synsrv->ParseMatrix (matrix_node, m))
return false;
t.SetT2O (m);
}
csRef<iDocumentNode> vector_node = node->GetNode ("v");
if (vector_node)
{
csVector3 v;
if (!synsrv->ParseVector (vector_node, v))
return false;
t.SetOrigin (v);
}
var->SetValue (t);
}
break;
}
param.var = var;
param.valid = true;
return true;
}
bool csShaderProgram::ParseCommon (iDocumentNode* child)
{
const char* value = child->GetValue ();
csStringID id = commonTokens.Request (value);
switch (id)
{
case XMLTOKEN_VARIABLEMAP:
{
//@@ REWRITE
const char* destname = child->GetAttributeValue ("destination");
if (!destname)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING, child,
"<variablemap> has no 'destination' attribute");
return false;
}
const char* varname = child->GetAttributeValue ("variable");
if (!varname)
{
// "New style" variable mapping
VariableMapEntry vme (CS::InvalidShaderVarStringID, destname);
if (!ParseProgramParam (child, vme.mappingParam,
ParamFloat | ParamVector2 | ParamVector3 | ParamVector4))
return false;
variablemap.Push (vme);
}
else
{
// "Classic" variable mapping
CS::Graphics::ShaderVarNameParser nameParse (varname);
VariableMapEntry vme (
stringsSvName->Request (nameParse.GetShaderVarName()),
destname);
for (size_t n = 0; n < nameParse.GetIndexNum(); n++)
{
vme.mappingParam.indices.Push (nameParse.GetIndexValue (n));
}
variablemap.Push (vme);
}
}
break;
case XMLTOKEN_PROGRAM:
{
const char* filename = child->GetAttributeValue ("file");
if (filename != 0)
{
programFileName = filename;
csRef<iVFS> vfs = csQueryRegistry<iVFS> (objectReg);
csRef<iFile> file = vfs->Open (filename, VFS_FILE_READ);
if (!file.IsValid())
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING, child,
"Could not open '%s'", filename);
return false;
}
programFile = file;
}
else
programNode = child;
}
break;
case XMLTOKEN_DESCRIPTION:
description = child->GetContentsValue();
break;
default:
synsrv->ReportBadToken (child);
return false;
}
return true;
}
#include "csutil/custom_new_disable.h"
iDocumentNode* csShaderProgram::GetProgramNode ()
{
if (programNode.IsValid ())
return programNode;
if (programFile.IsValid ())
{
csRef<iDocumentSystem> docsys =
csQueryRegistry<iDocumentSystem> (objectReg);
if (!docsys)
docsys.AttachNew (new csTinyDocumentSystem ());
csRef<iDocument> doc (docsys->CreateDocument ());
const char* err = doc->Parse (programFile, true);
if (err != 0)
{
csReport (objectReg,
CS_REPORTER_SEVERITY_WARNING,
"crystalspace.graphics3d.shader.common",
"Error parsing %s: %s", programFileName.GetData(), err);
return 0;
}
programNode = doc->GetRoot ();
programFile = 0;
return programNode;
}
return 0;
}
csPtr<iDataBuffer> csShaderProgram::GetProgramData ()
{
if (programFile.IsValid())
{
return programFile->GetAllData ();
}
if (programNode.IsValid())
{
char* data = CS::StrDup (programNode->GetContentsValue ());
csRef<iDataBuffer> newbuff;
newbuff.AttachNew (new CS::DataBuffer<> (data, data ? strlen (data) : 0));
return csPtr<iDataBuffer> (newbuff);
}
return 0;
}
#include "csutil/custom_new_enable.h"
void csShaderProgram::DumpProgramInfo (csString& output)
{
output << "Program description: " <<
(description.Length () ? description.GetData () : "<none>") << "\n";
output << "Program file name: " << programFileName << "\n";
}
void csShaderProgram::DumpVariableMappings (csString& output)
{
for (size_t v = 0; v < variablemap.GetSize (); v++)
{
const VariableMapEntry& vme = variablemap[v];
output << stringsSvName->Request (vme.name);
output << '(' << vme.name << ") -> ";
output << vme.destination << ' ';
output << vme.userVal << ' ';
output << '\n';
}
}
void csShaderProgram::GetUsedShaderVarsFromVariableMappings (
csBitArray& bits) const
{
for (size_t i = 0; i < variablemap.GetSize(); i++)
{
TryAddUsedShaderVarName (variablemap[i].name, bits);
}
}
void csShaderProgram::GetUsedShaderVars (csBitArray& bits) const
{
GetUsedShaderVarsFromVariableMappings (bits);
}
iShaderProgram::CacheLoadResult csShaderProgram::LoadFromCache (
iHierarchicalCache* cache, iBase* previous, iDocumentNode* programNode,
csRef<iString>* failReason, csRef<iString>*)
{
csRef<iShaderDestinationResolver> resolver =
scfQueryInterfaceSafe<iShaderDestinationResolver> (previous);
if (Load (resolver, programNode))
return loadSuccessShaderValid;
else
return loadSuccessShaderInvalid;
}
<commit_msg>Default LoadFromCache() must not only call Load(), but also Compile()<commit_after>/*
Copyright (C) 2004 by Jorrit Tyberghein
(C) 2004 by Frank Richter
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csutil/databuf.h"
#include "csutil/scanstr.h"
#include "csutil/util.h"
#include "csutil/xmltiny.h"
#include "csgfx/shaderexp.h"
#include "imap/services.h"
#include "iutil/verbositymanager.h"
#include "iutil/vfs.h"
#include "ivaria/reporter.h"
#include "csplugincommon/shader/shaderprogram.h"
void csShaderProgram::ProgramParam::SetValue (float val)
{
var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID));
var->SetValue (val);
valid = true;
}
void csShaderProgram::ProgramParam::SetValue (const csVector4& val)
{
var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID));
var->SetValue (val);
valid = true;
}
//---------------------------------------------------------------------------
CS_LEAKGUARD_IMPLEMENT (csShaderProgram);
csShaderProgram::csShaderProgram (iObjectRegistry* objectReg)
: scfImplementationType (this)
{
InitCommonTokens (commonTokens);
csShaderProgram::objectReg = objectReg;
synsrv = csQueryRegistry<iSyntaxService> (objectReg);
stringsSvName = csQueryRegistryTagInterface<iShaderVarStringSet>
(objectReg, "crystalspace.shader.variablenameset");
csRef<iVerbosityManager> verbosemgr (
csQueryRegistry<iVerbosityManager> (objectReg));
if (verbosemgr)
doVerbose = verbosemgr->Enabled("renderer.shader");
else
doVerbose = false;
}
csShaderProgram::~csShaderProgram ()
{
}
bool csShaderProgram::ProgramParamParser::ParseProgramParam (
iDocumentNode* node, ProgramParam& param, uint types)
{
const char* type = node->GetAttributeValue ("type");
if (type == 0)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"No 'type' attribute");
return false;
}
// Var for static data
csRef<csShaderVariable> var;
var.AttachNew (new csShaderVariable (CS::InvalidShaderVarStringID));
ProgramParamType paramType = ParamInvalid;
if (strcmp (type, "shadervar") == 0)
{
const char* value = node->GetContentsValue();
if (!value)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Node has no contents");
return false;
}
CS::Graphics::ShaderVarNameParser nameParse (value);
param.name = stringsSvName->Request (nameParse.GetShaderVarName());
for (size_t n = 0; n < nameParse.GetIndexNum(); n++)
{
param.indices.Push (nameParse.GetIndexValue (n));
}
param.valid = true;
return true;
}
else if (strcmp (type, "int") == 0)
{
paramType = ParamInt;
}
else if (strcmp (type, "float") == 0)
{
paramType = ParamFloat;
}
else if (strcmp (type, "vector2") == 0)
{
paramType = ParamVector2;
}
else if (strcmp (type, "vector3") == 0)
{
paramType = ParamVector3;
}
else if (strcmp (type, "vector4") == 0)
{
paramType = ParamVector4;
}
else if (strcmp (type, "matrix") == 0)
{
paramType = ParamMatrix;
}
else if (strcmp (type, "transform") == 0)
{
paramType = ParamTransform;
}
else if ((strcmp (type, "expression") == 0) || (strcmp (type, "expr") == 0))
{
// Parse exp and save it
csRef<iShaderVariableAccessor> acc = synsrv->ParseShaderVarExpr (node);
var->SetAccessor (acc);
param.var = var;
param.valid = true;
return true;
}
else if (strcmp (type, "array") == 0)
{
csArray<ProgramParam> allParams;
ProgramParam tmpParam;
csRef<iDocumentNodeIterator> it = node->GetNodes ();
while (it->HasNext ())
{
csRef<iDocumentNode> child = it->Next ();
ParseProgramParam (child, tmpParam, types & 0x3F);
allParams.Push (tmpParam);
}
//Save the params
var->SetType (csShaderVariable::ARRAY);
var->SetArraySize (allParams.GetSize ());
for (uint i = 0; i < allParams.GetSize (); i++)
{
var->SetArrayElement (i, allParams[i].var);
}
paramType = ParamArray;
}
else
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Unknown type '%s'", type);
return false;
}
if (!(types & paramType))
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Type '%s' not supported by this parameter", type);
return false;
}
const uint directValueTypes = ParamInt | ParamFloat | ParamVector2
| ParamVector3 | ParamVector4 | ParamMatrix | ParamTransform;
switch (paramType & directValueTypes)
{
case ParamInvalid:
return false;
break;
case ParamInt:
{
int x = node->GetContentsValueAsInt ();
var->SetValue (x);
}
break;
case ParamFloat:
{
float x = node->GetContentsValueAsFloat ();
var->SetValue (x);
}
break;
case ParamVector2:
{
float x, y;
const char* value = node->GetContentsValue();
if (!value)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Node has no contents");
return false;
}
if (csScanStr (value, "%f,%f", &x, &y) != 2)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Couldn't parse vector2 '%s'", value);
return false;
}
var->SetValue (csVector2 (x,y));
}
break;
case ParamVector3:
{
float x, y, z;
const char* value = node->GetContentsValue();
if (!value)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Node has no contents");
return false;
}
if (csScanStr (value, "%f,%f,%f", &x, &y, &z) != 3)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Couldn't parse vector3 '%s'", value);
return false;
}
var->SetValue (csVector3 (x,y,z));
}
break;
case ParamVector4:
{
float x, y, z, w;
const char* value = node->GetContentsValue();
if (!value)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Node has no contents");
return false;
}
if (csScanStr (value, "%f,%f,%f,%f", &x, &y, &z, &w) != 4)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING,
node,
"Couldn't parse vector4 '%s'", value);
return false;
}
var->SetValue (csVector4 (x,y,z,w));
}
break;
case ParamMatrix:
{
csMatrix3 matrix;
if (!synsrv->ParseMatrix (node, matrix))
return false;
var->SetValue (matrix);
}
break;
case ParamTransform:
{
csReversibleTransform t;
csRef<iDocumentNode> matrix_node = node->GetNode ("matrix");
if (matrix_node)
{
csMatrix3 m;
if (!synsrv->ParseMatrix (matrix_node, m))
return false;
t.SetT2O (m);
}
csRef<iDocumentNode> vector_node = node->GetNode ("v");
if (vector_node)
{
csVector3 v;
if (!synsrv->ParseVector (vector_node, v))
return false;
t.SetOrigin (v);
}
var->SetValue (t);
}
break;
}
param.var = var;
param.valid = true;
return true;
}
bool csShaderProgram::ParseCommon (iDocumentNode* child)
{
const char* value = child->GetValue ();
csStringID id = commonTokens.Request (value);
switch (id)
{
case XMLTOKEN_VARIABLEMAP:
{
//@@ REWRITE
const char* destname = child->GetAttributeValue ("destination");
if (!destname)
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING, child,
"<variablemap> has no 'destination' attribute");
return false;
}
const char* varname = child->GetAttributeValue ("variable");
if (!varname)
{
// "New style" variable mapping
VariableMapEntry vme (CS::InvalidShaderVarStringID, destname);
if (!ParseProgramParam (child, vme.mappingParam,
ParamFloat | ParamVector2 | ParamVector3 | ParamVector4))
return false;
variablemap.Push (vme);
}
else
{
// "Classic" variable mapping
CS::Graphics::ShaderVarNameParser nameParse (varname);
VariableMapEntry vme (
stringsSvName->Request (nameParse.GetShaderVarName()),
destname);
for (size_t n = 0; n < nameParse.GetIndexNum(); n++)
{
vme.mappingParam.indices.Push (nameParse.GetIndexValue (n));
}
variablemap.Push (vme);
}
}
break;
case XMLTOKEN_PROGRAM:
{
const char* filename = child->GetAttributeValue ("file");
if (filename != 0)
{
programFileName = filename;
csRef<iVFS> vfs = csQueryRegistry<iVFS> (objectReg);
csRef<iFile> file = vfs->Open (filename, VFS_FILE_READ);
if (!file.IsValid())
{
synsrv->Report ("crystalspace.graphics3d.shader.common",
CS_REPORTER_SEVERITY_WARNING, child,
"Could not open '%s'", filename);
return false;
}
programFile = file;
}
else
programNode = child;
}
break;
case XMLTOKEN_DESCRIPTION:
description = child->GetContentsValue();
break;
default:
synsrv->ReportBadToken (child);
return false;
}
return true;
}
#include "csutil/custom_new_disable.h"
iDocumentNode* csShaderProgram::GetProgramNode ()
{
if (programNode.IsValid ())
return programNode;
if (programFile.IsValid ())
{
csRef<iDocumentSystem> docsys =
csQueryRegistry<iDocumentSystem> (objectReg);
if (!docsys)
docsys.AttachNew (new csTinyDocumentSystem ());
csRef<iDocument> doc (docsys->CreateDocument ());
const char* err = doc->Parse (programFile, true);
if (err != 0)
{
csReport (objectReg,
CS_REPORTER_SEVERITY_WARNING,
"crystalspace.graphics3d.shader.common",
"Error parsing %s: %s", programFileName.GetData(), err);
return 0;
}
programNode = doc->GetRoot ();
programFile = 0;
return programNode;
}
return 0;
}
csPtr<iDataBuffer> csShaderProgram::GetProgramData ()
{
if (programFile.IsValid())
{
return programFile->GetAllData ();
}
if (programNode.IsValid())
{
char* data = CS::StrDup (programNode->GetContentsValue ());
csRef<iDataBuffer> newbuff;
newbuff.AttachNew (new CS::DataBuffer<> (data, data ? strlen (data) : 0));
return csPtr<iDataBuffer> (newbuff);
}
return 0;
}
#include "csutil/custom_new_enable.h"
void csShaderProgram::DumpProgramInfo (csString& output)
{
output << "Program description: " <<
(description.Length () ? description.GetData () : "<none>") << "\n";
output << "Program file name: " << programFileName << "\n";
}
void csShaderProgram::DumpVariableMappings (csString& output)
{
for (size_t v = 0; v < variablemap.GetSize (); v++)
{
const VariableMapEntry& vme = variablemap[v];
output << stringsSvName->Request (vme.name);
output << '(' << vme.name << ") -> ";
output << vme.destination << ' ';
output << vme.userVal << ' ';
output << '\n';
}
}
void csShaderProgram::GetUsedShaderVarsFromVariableMappings (
csBitArray& bits) const
{
for (size_t i = 0; i < variablemap.GetSize(); i++)
{
TryAddUsedShaderVarName (variablemap[i].name, bits);
}
}
void csShaderProgram::GetUsedShaderVars (csBitArray& bits) const
{
GetUsedShaderVarsFromVariableMappings (bits);
}
iShaderProgram::CacheLoadResult csShaderProgram::LoadFromCache (
iHierarchicalCache* cache, iBase* previous, iDocumentNode* programNode,
csRef<iString>* failReason, csRef<iString>* tag)
{
csRef<iShaderDestinationResolver> resolver =
scfQueryInterfaceSafe<iShaderDestinationResolver> (previous);
if (Load (resolver, programNode) && Compile (0, tag))
return loadSuccessShaderValid;
else
return loadSuccessShaderInvalid;
}
<|endoftext|>
|
<commit_before>/*
* Salsa20 / XSalsa20
* (C) 1999-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/salsa20.h>
#include <botan/loadstor.h>
#include <botan/rotate.h>
#include <botan/internal/xor_buf.h>
namespace Botan {
namespace {
/*
* Generate HSalsa20 cipher stream (for XSalsa20 IV setup)
*/
void hsalsa20(u32bit output[8], const u32bit input[16])
{
u32bit x00 = input[0];
u32bit x01 = input[1];
u32bit x02 = input[2];
u32bit x03 = input[3];
u32bit x04 = input[4];
u32bit x05 = input[5];
u32bit x06 = input[6];
u32bit x07 = input[7];
u32bit x08 = input[8];
u32bit x09 = input[9];
u32bit x10 = input[10];
u32bit x11 = input[11];
u32bit x12 = input[12];
u32bit x13 = input[13];
u32bit x14 = input[14];
u32bit x15 = input[15];
for(u32bit i = 0; i != 10; ++i)
{
x04 ^= rotate_left(x00 + x12, 7);
x08 ^= rotate_left(x04 + x00, 9);
x12 ^= rotate_left(x08 + x04, 13);
x00 ^= rotate_left(x12 + x08, 18);
x09 ^= rotate_left(x05 + x01, 7);
x13 ^= rotate_left(x09 + x05, 9);
x01 ^= rotate_left(x13 + x09, 13);
x05 ^= rotate_left(x01 + x13, 18);
x14 ^= rotate_left(x10 + x06, 7);
x02 ^= rotate_left(x14 + x10, 9);
x06 ^= rotate_left(x02 + x14, 13);
x10 ^= rotate_left(x06 + x02, 18);
x03 ^= rotate_left(x15 + x11, 7);
x07 ^= rotate_left(x03 + x15, 9);
x11 ^= rotate_left(x07 + x03, 13);
x15 ^= rotate_left(x11 + x07, 18);
x01 ^= rotate_left(x00 + x03, 7);
x02 ^= rotate_left(x01 + x00, 9);
x03 ^= rotate_left(x02 + x01, 13);
x00 ^= rotate_left(x03 + x02, 18);
x06 ^= rotate_left(x05 + x04, 7);
x07 ^= rotate_left(x06 + x05, 9);
x04 ^= rotate_left(x07 + x06, 13);
x05 ^= rotate_left(x04 + x07, 18);
x11 ^= rotate_left(x10 + x09, 7);
x08 ^= rotate_left(x11 + x10, 9);
x09 ^= rotate_left(x08 + x11, 13);
x10 ^= rotate_left(x09 + x08, 18);
x12 ^= rotate_left(x15 + x14, 7);
x13 ^= rotate_left(x12 + x15, 9);
x14 ^= rotate_left(x13 + x12, 13);
x15 ^= rotate_left(x14 + x13, 18);
}
output[0] = x00;
output[1] = x05;
output[2] = x10;
output[3] = x15;
output[4] = x06;
output[5] = x07;
output[6] = x08;
output[7] = x09;
}
/*
* Generate Salsa20 cipher stream
*/
void salsa20(byte output[64], const u32bit input[16])
{
u32bit x00 = input[0];
u32bit x01 = input[1];
u32bit x02 = input[2];
u32bit x03 = input[3];
u32bit x04 = input[4];
u32bit x05 = input[5];
u32bit x06 = input[6];
u32bit x07 = input[7];
u32bit x08 = input[8];
u32bit x09 = input[9];
u32bit x10 = input[10];
u32bit x11 = input[11];
u32bit x12 = input[12];
u32bit x13 = input[13];
u32bit x14 = input[14];
u32bit x15 = input[15];
for(u32bit i = 0; i != 10; ++i)
{
x04 ^= rotate_left(x00 + x12, 7);
x08 ^= rotate_left(x04 + x00, 9);
x12 ^= rotate_left(x08 + x04, 13);
x00 ^= rotate_left(x12 + x08, 18);
x09 ^= rotate_left(x05 + x01, 7);
x13 ^= rotate_left(x09 + x05, 9);
x01 ^= rotate_left(x13 + x09, 13);
x05 ^= rotate_left(x01 + x13, 18);
x14 ^= rotate_left(x10 + x06, 7);
x02 ^= rotate_left(x14 + x10, 9);
x06 ^= rotate_left(x02 + x14, 13);
x10 ^= rotate_left(x06 + x02, 18);
x03 ^= rotate_left(x15 + x11, 7);
x07 ^= rotate_left(x03 + x15, 9);
x11 ^= rotate_left(x07 + x03, 13);
x15 ^= rotate_left(x11 + x07, 18);
x01 ^= rotate_left(x00 + x03, 7);
x02 ^= rotate_left(x01 + x00, 9);
x03 ^= rotate_left(x02 + x01, 13);
x00 ^= rotate_left(x03 + x02, 18);
x06 ^= rotate_left(x05 + x04, 7);
x07 ^= rotate_left(x06 + x05, 9);
x04 ^= rotate_left(x07 + x06, 13);
x05 ^= rotate_left(x04 + x07, 18);
x11 ^= rotate_left(x10 + x09, 7);
x08 ^= rotate_left(x11 + x10, 9);
x09 ^= rotate_left(x08 + x11, 13);
x10 ^= rotate_left(x09 + x08, 18);
x12 ^= rotate_left(x15 + x14, 7);
x13 ^= rotate_left(x12 + x15, 9);
x14 ^= rotate_left(x13 + x12, 13);
x15 ^= rotate_left(x14 + x13, 18);
}
store_le(x00 + input[ 0], output + 4 * 0);
store_le(x01 + input[ 1], output + 4 * 1);
store_le(x02 + input[ 2], output + 4 * 2);
store_le(x03 + input[ 3], output + 4 * 3);
store_le(x04 + input[ 4], output + 4 * 4);
store_le(x05 + input[ 5], output + 4 * 5);
store_le(x06 + input[ 6], output + 4 * 6);
store_le(x07 + input[ 7], output + 4 * 7);
store_le(x08 + input[ 8], output + 4 * 8);
store_le(x09 + input[ 9], output + 4 * 9);
store_le(x10 + input[10], output + 4 * 10);
store_le(x11 + input[11], output + 4 * 11);
store_le(x12 + input[12], output + 4 * 12);
store_le(x13 + input[13], output + 4 * 13);
store_le(x14 + input[14], output + 4 * 14);
store_le(x15 + input[15], output + 4 * 15);
}
}
/*
* Combine cipher stream with message
*/
void Salsa20::cipher(const byte in[], byte out[], u32bit length)
{
while(length >= buffer.size() - position)
{
xor_buf(out, in, &buffer[position], buffer.size() - position);
length -= (buffer.size() - position);
in += (buffer.size() - position);
out += (buffer.size() - position);
salsa20(&buffer[0], state);
++state[8];
if(!state[8]) // if overflow in state[8]
++state[9]; // carry to state[9]
position = 0;
}
xor_buf(out, in, &buffer[position], length);
position += length;
}
/*
* Salsa20 Key Schedule
*/
void Salsa20::key_schedule(const byte key[], u32bit length)
{
static const u32bit TAU[] =
{ 0x61707865, 0x3120646e, 0x79622d36, 0x6b206574 };
static const u32bit SIGMA[] =
{ 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 };
clear();
if(length == 16)
{
state[0] = TAU[0];
state[1] = load_le<u32bit>(key, 0);
state[2] = load_le<u32bit>(key, 1);
state[3] = load_le<u32bit>(key, 2);
state[4] = load_le<u32bit>(key, 3);
state[5] = TAU[1];
state[10] = TAU[2];
state[11] = load_le<u32bit>(key, 0);
state[12] = load_le<u32bit>(key, 1);
state[13] = load_le<u32bit>(key, 2);
state[14] = load_le<u32bit>(key, 3);
state[15] = TAU[3];
}
else if(length == 32)
{
state[0] = SIGMA[0];
state[1] = load_le<u32bit>(key, 0);
state[2] = load_le<u32bit>(key, 1);
state[3] = load_le<u32bit>(key, 2);
state[4] = load_le<u32bit>(key, 3);
state[5] = SIGMA[1];
state[10] = SIGMA[2];
state[11] = load_le<u32bit>(key, 4);
state[12] = load_le<u32bit>(key, 5);
state[13] = load_le<u32bit>(key, 6);
state[14] = load_le<u32bit>(key, 7);
state[15] = SIGMA[3];
}
const byte ZERO[8] = { 0 };
set_iv(ZERO, sizeof(ZERO));
}
/*
* Return the name of this type
*/
void Salsa20::set_iv(const byte iv[], u32bit length)
{
if(!valid_iv_length(length))
throw Invalid_IV_Length(name(), length);
if(length == 8)
{
// Salsa20
state[6] = load_le<u32bit>(iv, 0);
state[7] = load_le<u32bit>(iv, 1);
}
else
{
// XSalsa20
state[6] = load_le<u32bit>(iv, 0);
state[7] = load_le<u32bit>(iv, 1);
state[8] = load_le<u32bit>(iv, 2);
state[9] = load_le<u32bit>(iv, 3);
SecureVector<u32bit> hsalsa(8);
hsalsa20(hsalsa, state);
state[ 1] = hsalsa[0];
state[ 2] = hsalsa[1];
state[ 3] = hsalsa[2];
state[ 4] = hsalsa[3];
state[ 6] = load_le<u32bit>(iv, 4);
state[ 7] = load_le<u32bit>(iv, 5);
state[11] = hsalsa[4];
state[12] = hsalsa[5];
state[13] = hsalsa[6];
state[14] = hsalsa[7];
}
state[8] = 0;
state[9] = 0;
salsa20(&buffer[0], state);
++state[8];
if(!state[8]) // if overflow in state[8]
++state[9]; // carry to state[9]
position = 0;
}
/*
* Return the name of this type
*/
std::string Salsa20::name() const
{
return "Salsa20";
}
/*
* Clear memory of sensitive data
*/
void Salsa20::clear()
{
state.clear();
buffer.clear();
position = 0;
}
/*
* Salsa20 Constructor
*/
Salsa20::Salsa20() : StreamCipher(16, 32, 16)
{
clear();
}
}
<commit_msg>Use a macro to make Salsa20 code a bit more compact<commit_after>/*
* Salsa20 / XSalsa20
* (C) 1999-2010 Jack Lloyd
*
* Distributed under the terms of the Botan license
*/
#include <botan/salsa20.h>
#include <botan/loadstor.h>
#include <botan/rotate.h>
#include <botan/internal/xor_buf.h>
namespace Botan {
namespace {
#define SALSA20_QUARTER_ROUND(x1, x2, x3, x4) \
do { \
x2 ^= rotate_left(x1 + x4, 7); \
x3 ^= rotate_left(x2 + x1, 9); \
x4 ^= rotate_left(x3 + x2, 13); \
x1 ^= rotate_left(x4 + x3, 18); \
} while(0)
/*
* Generate HSalsa20 cipher stream (for XSalsa20 IV setup)
*/
void hsalsa20(u32bit output[8], const u32bit input[16])
{
u32bit x00 = input[0];
u32bit x01 = input[1];
u32bit x02 = input[2];
u32bit x03 = input[3];
u32bit x04 = input[4];
u32bit x05 = input[5];
u32bit x06 = input[6];
u32bit x07 = input[7];
u32bit x08 = input[8];
u32bit x09 = input[9];
u32bit x10 = input[10];
u32bit x11 = input[11];
u32bit x12 = input[12];
u32bit x13 = input[13];
u32bit x14 = input[14];
u32bit x15 = input[15];
for(u32bit i = 0; i != 10; ++i)
{
SALSA20_QUARTER_ROUND(x00, x04, x08, x12);
SALSA20_QUARTER_ROUND(x05, x09, x13, x01);
SALSA20_QUARTER_ROUND(x10, x14, x02, x06);
SALSA20_QUARTER_ROUND(x15, x03, x07, x11);
SALSA20_QUARTER_ROUND(x00, x01, x02, x03);
SALSA20_QUARTER_ROUND(x05, x06, x07, x04);
SALSA20_QUARTER_ROUND(x10, x11, x08, x09);
SALSA20_QUARTER_ROUND(x15, x12, x13, x14);
}
output[0] = x00;
output[1] = x05;
output[2] = x10;
output[3] = x15;
output[4] = x06;
output[5] = x07;
output[6] = x08;
output[7] = x09;
}
/*
* Generate Salsa20 cipher stream
*/
void salsa20(byte output[64], const u32bit input[16])
{
u32bit x00 = input[0];
u32bit x01 = input[1];
u32bit x02 = input[2];
u32bit x03 = input[3];
u32bit x04 = input[4];
u32bit x05 = input[5];
u32bit x06 = input[6];
u32bit x07 = input[7];
u32bit x08 = input[8];
u32bit x09 = input[9];
u32bit x10 = input[10];
u32bit x11 = input[11];
u32bit x12 = input[12];
u32bit x13 = input[13];
u32bit x14 = input[14];
u32bit x15 = input[15];
for(u32bit i = 0; i != 10; ++i)
{
SALSA20_QUARTER_ROUND(x00, x04, x08, x12);
SALSA20_QUARTER_ROUND(x05, x09, x13, x01);
SALSA20_QUARTER_ROUND(x10, x14, x02, x06);
SALSA20_QUARTER_ROUND(x15, x03, x07, x11);
SALSA20_QUARTER_ROUND(x00, x01, x02, x03);
SALSA20_QUARTER_ROUND(x05, x06, x07, x04);
SALSA20_QUARTER_ROUND(x10, x11, x08, x09);
SALSA20_QUARTER_ROUND(x15, x12, x13, x14);
}
store_le(x00 + input[ 0], output + 4 * 0);
store_le(x01 + input[ 1], output + 4 * 1);
store_le(x02 + input[ 2], output + 4 * 2);
store_le(x03 + input[ 3], output + 4 * 3);
store_le(x04 + input[ 4], output + 4 * 4);
store_le(x05 + input[ 5], output + 4 * 5);
store_le(x06 + input[ 6], output + 4 * 6);
store_le(x07 + input[ 7], output + 4 * 7);
store_le(x08 + input[ 8], output + 4 * 8);
store_le(x09 + input[ 9], output + 4 * 9);
store_le(x10 + input[10], output + 4 * 10);
store_le(x11 + input[11], output + 4 * 11);
store_le(x12 + input[12], output + 4 * 12);
store_le(x13 + input[13], output + 4 * 13);
store_le(x14 + input[14], output + 4 * 14);
store_le(x15 + input[15], output + 4 * 15);
}
}
/*
* Combine cipher stream with message
*/
void Salsa20::cipher(const byte in[], byte out[], u32bit length)
{
while(length >= buffer.size() - position)
{
xor_buf(out, in, &buffer[position], buffer.size() - position);
length -= (buffer.size() - position);
in += (buffer.size() - position);
out += (buffer.size() - position);
salsa20(&buffer[0], state);
++state[8];
if(!state[8]) // if overflow in state[8]
++state[9]; // carry to state[9]
position = 0;
}
xor_buf(out, in, &buffer[position], length);
position += length;
}
/*
* Salsa20 Key Schedule
*/
void Salsa20::key_schedule(const byte key[], u32bit length)
{
static const u32bit TAU[] =
{ 0x61707865, 0x3120646e, 0x79622d36, 0x6b206574 };
static const u32bit SIGMA[] =
{ 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 };
clear();
if(length == 16)
{
state[0] = TAU[0];
state[1] = load_le<u32bit>(key, 0);
state[2] = load_le<u32bit>(key, 1);
state[3] = load_le<u32bit>(key, 2);
state[4] = load_le<u32bit>(key, 3);
state[5] = TAU[1];
state[10] = TAU[2];
state[11] = load_le<u32bit>(key, 0);
state[12] = load_le<u32bit>(key, 1);
state[13] = load_le<u32bit>(key, 2);
state[14] = load_le<u32bit>(key, 3);
state[15] = TAU[3];
}
else if(length == 32)
{
state[0] = SIGMA[0];
state[1] = load_le<u32bit>(key, 0);
state[2] = load_le<u32bit>(key, 1);
state[3] = load_le<u32bit>(key, 2);
state[4] = load_le<u32bit>(key, 3);
state[5] = SIGMA[1];
state[10] = SIGMA[2];
state[11] = load_le<u32bit>(key, 4);
state[12] = load_le<u32bit>(key, 5);
state[13] = load_le<u32bit>(key, 6);
state[14] = load_le<u32bit>(key, 7);
state[15] = SIGMA[3];
}
const byte ZERO[8] = { 0 };
set_iv(ZERO, sizeof(ZERO));
}
/*
* Return the name of this type
*/
void Salsa20::set_iv(const byte iv[], u32bit length)
{
if(!valid_iv_length(length))
throw Invalid_IV_Length(name(), length);
if(length == 8)
{
// Salsa20
state[6] = load_le<u32bit>(iv, 0);
state[7] = load_le<u32bit>(iv, 1);
}
else
{
// XSalsa20
state[6] = load_le<u32bit>(iv, 0);
state[7] = load_le<u32bit>(iv, 1);
state[8] = load_le<u32bit>(iv, 2);
state[9] = load_le<u32bit>(iv, 3);
SecureVector<u32bit> hsalsa(8);
hsalsa20(hsalsa, state);
state[ 1] = hsalsa[0];
state[ 2] = hsalsa[1];
state[ 3] = hsalsa[2];
state[ 4] = hsalsa[3];
state[ 6] = load_le<u32bit>(iv, 4);
state[ 7] = load_le<u32bit>(iv, 5);
state[11] = hsalsa[4];
state[12] = hsalsa[5];
state[13] = hsalsa[6];
state[14] = hsalsa[7];
}
state[8] = 0;
state[9] = 0;
salsa20(&buffer[0], state);
++state[8];
if(!state[8]) // if overflow in state[8]
++state[9]; // carry to state[9]
position = 0;
}
/*
* Return the name of this type
*/
std::string Salsa20::name() const
{
return "Salsa20";
}
/*
* Clear memory of sensitive data
*/
void Salsa20::clear()
{
state.clear();
buffer.clear();
position = 0;
}
/*
* Salsa20 Constructor
*/
Salsa20::Salsa20() : StreamCipher(16, 32, 16)
{
clear();
}
}
<|endoftext|>
|
<commit_before>//----------------------------------------------------------------------------
/// \file mean_variance.hpp
//----------------------------------------------------------------------------
/// This file contains classes used for calculating mean and
/// variance. They are used mainly in unit tests.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Omnibius, LLC
// Author: Serge Aleynikov <saleyn@mail.com>
// Created: 2010-05-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_MEAN_VARIANCE_HPP_
#define _UTXX_MEAN_VARIANCE_HPP_
namespace utxx {
namespace detail {
template <class T>
double mean(const T* begin, const T* end) {
size_t count = 0;
double sum = 0;
for (const T* p=begin; p != end; ++p, ++count)
sum += *p;
return (double)sum / count;
}
template <class T>
double variance(const T* begin, const T* end) {
double avg = mean(begin, end);
size_t count = 0;
double sum = 0;
for (const T* p=begin; p != end; ++p, ++count)
sum += (*p - avg) * (*p - avg);
return sum / count;
}
// A numerically stable algorithm for the computation
// of the variance (and the mean as well).
template <class T>
double online_variance(const T* begin, const T* end) {
double count = 0;
double mean = 0;
double sum = 0;
for (const T* p=begin; p != end; ++p) {
count = count + 1;
double delta = *p - mean;
mean = mean + delta/count;
sum = sum + delta*(*p - mean);
}
return sum/count;
}
} // namespace detail
} // namespace utxx
#endif // _UTXX_MEAN_VARIANCE_HPP_
<commit_msg>Format the code with 4-space tabulation<commit_after>//----------------------------------------------------------------------------
/// \file mean_variance.hpp
//----------------------------------------------------------------------------
/// This file contains classes used for calculating mean and
/// variance. They are used mainly in unit tests.
//----------------------------------------------------------------------------
// Copyright (c) 2010 Omnibius, LLC
// Author: Serge Aleynikov <saleyn@mail.com>
// Created: 2010-05-20
//----------------------------------------------------------------------------
/*
***** BEGIN LICENSE BLOCK *****
This file is part of the utxx open-source project
Copyright (C) 2010 Serge Aleynikov <saleyn@gmail.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
***** END LICENSE BLOCK *****
*/
#ifndef _UTXX_MEAN_VARIANCE_HPP_
#define _UTXX_MEAN_VARIANCE_HPP_
namespace utxx {
namespace detail {
template <class T>
double mean(const T* begin, const T* end) {
size_t count = 0;
double sum = 0;
for (const T* p=begin; p != end; ++p, ++count)
sum += *p;
return (double)sum / count;
}
template <class T>
double variance(const T* begin, const T* end) {
double avg = mean(begin, end);
size_t count = 0;
double sum = 0;
for (const T* p=begin; p != end; ++p, ++count)
sum += (*p - avg) * (*p - avg);
return sum / count;
}
// A numerically stable algorithm for the computation
// of the variance (and the mean as well).
template <class T>
double online_variance(const T* begin, const T* end) {
double count = 0;
double mean = 0;
double sum = 0;
for (const T* p=begin; p != end; ++p) {
count = count + 1;
double delta = *p - mean;
mean = mean + delta/count;
sum = sum + delta*(*p - mean);
}
return sum/count;
}
} // namespace detail
} // namespace utxx
#endif // _UTXX_MEAN_VARIANCE_HPP_
<|endoftext|>
|
<commit_before>//==============================================================================
// Single cell simulation view simulation worker
//==============================================================================
#include "cellmlfileruntime.h"
#include "coredaesolver.h"
#include "corenlasolver.h"
#include "coreodesolver.h"
#include "singlecellsimulationviewsimulation.h"
#include "singlecellsimulationviewsimulationworker.h"
#include "thread.h"
//==============================================================================
#include <QTime>
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulationView {
//==============================================================================
SingleCellSimulationViewSimulationWorker::SingleCellSimulationViewSimulationWorker(const SolverInterfaces &pSolverInterfaces,
CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime,
SingleCellSimulationViewSimulationData *pData) :
mStatus(Idling),
mSolverInterfaces(pSolverInterfaces),
mCellmlFileRuntime(pCellmlFileRuntime),
mData(pData),
mError(false)
{
// Initialise our progress and let people know about it
updateAndEmitProgress(0.0);
}
//==============================================================================
SingleCellSimulationViewSimulationWorker::Status SingleCellSimulationViewSimulationWorker::status() const
{
// Return our status
return mStatus;
}
//==============================================================================
double SingleCellSimulationViewSimulationWorker::progress() const
{
// Return our progress
return mProgress;
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::updateAndEmitProgress(const double &pProgress)
{
// Set our progress
mProgress = pProgress;
// Let people know about our progress
emit progress(pProgress);
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::run()
{
// Run ourselves, but only if we are currently idling
if (mStatus == Idling) {
// We are running
mStatus = Running;
// Let people know that we are running
emit running();
// Set up our ODE/DAE solver
CoreSolver::CoreVoiSolver *voiSolver = 0;
CoreSolver::CoreOdeSolver *odeSolver = 0;
CoreSolver::CoreDaeSolver *daeSolver = 0;
if (mCellmlFileRuntime->needOdeSolver()) {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mData->odeSolverName())) {
// The requested ODE solver was found, so retrieve an
// instance of it
voiSolver = odeSolver = reinterpret_cast<CoreSolver::CoreOdeSolver *>(solverInterface->instance());
break;
}
} else {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare("IDA")) {
// The requested DAE solver was found, so retrieve an
// instance of it
voiSolver = daeSolver = reinterpret_cast<CoreSolver::CoreDaeSolver *>(solverInterface->instance());
break;
}
}
// Set up our NLA solver, if needed
if (mCellmlFileRuntime->needNlaSolver())
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mData->nlaSolverName())) {
// The requested NLA solver was found, so retrieve an
// instance of it
CoreSolver::setGlobalNlaSolver(reinterpret_cast<CoreSolver::CoreNlaSolver *>(solverInterface->instance()));
break;
}
// Keep track of any error that might be reported by any of our solvers
mError = false;
if (mCellmlFileRuntime->needOdeSolver())
connect(odeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
else
connect(daeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
if (mCellmlFileRuntime->needNlaSolver())
connect(CoreSolver::globalNlaSolver(), SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
// Retrieve our simulation properties
double startingPoint = mData->startingPoint();
double endingPoint = mData->endingPoint();
double pointInterval = mData->pointInterval();
bool increasingPoints = endingPoint > startingPoint;
const double oneOverPointRange = 1.0/(endingPoint-startingPoint);
int voiCounter = 0;
double currentPoint = startingPoint;
// Initialise our ODE/DAE solver
if (mCellmlFileRuntime->needOdeSolver()) {
odeSolver->setProperties(mData->odeSolverProperties());
odeSolver->initialize(currentPoint,
mCellmlFileRuntime->statesCount(),
mData->constants(), mData->rates(),
mData->states(), mData->algebraic(),
mCellmlFileRuntime->computeRates());
} else {
daeSolver->setProperties(mData->daeSolverProperties());
daeSolver->initialize(currentPoint, endingPoint,
mCellmlFileRuntime->statesCount(),
mCellmlFileRuntime->condVarCount(),
mData->constants(), mData->states(),
mData->rates(), mData->algebraic(),
mData->condVar(),
mCellmlFileRuntime->computeEssentialVariables(),
mCellmlFileRuntime->computeResiduals(),
mCellmlFileRuntime->computeRootInformation(),
mCellmlFileRuntime->computeStateInformation());
}
// Initialise our NLA solver
//---GRY--- CHECK do_nonlinearsolve() IN compilermath.cpp SINCE IT ISN'T
// CURRENTLY NEEDED. HOWEVER, OUR CURRENT APPROACH IS NOT NICE AND WE
// REALLY SHOULD INITIALISE THINGS HERE...
if (mCellmlFileRuntime->needNlaSolver()) {
CoreSolver::globalNlaSolver()->setProperties(mData->nlaSolverProperties());
// CoreSolver::globalNlaSolver()->initialize(...);
}
// Now, we are ready to compute our model, but only if no error has
// occurred so far
if (!mError) {
// Start our timer
QTime timer;
int totalElapsedTime = 0;
timer.start();
// Our main work loop
QString states;
for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
if (i)
states += ",STATES["+QString::number(i)+"]";
else
states = "STATES["+QString::number(i)+"]";
qDebug("time,%s", qPrintable(states));
while ( (currentPoint != endingPoint) && !mError
&& (mStatus != Stopped)) {
// Handle our current point after making sure that all the
// variables have been computed
mCellmlFileRuntime->computeVariables()(currentPoint,
mData->constants(),
mData->rates(),
mData->states(),
mData->algebraic());
//---GRY--- TO BE DONE...
for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
if (i)
states += ","+QString::number(mData->states()[i]);
else
states = QString::number(mData->states()[i]);
qDebug("%f,%s", currentPoint, qPrintable(states));
// Let people know about our progress
updateAndEmitProgress((currentPoint-startingPoint)*oneOverPointRange);
// Check whether we should be pausing
if(mStatus == Pausing) {
// We have been asked to pause, so do just that after stopping
// our timer
totalElapsedTime += timer.elapsed();
mStatusMutex.lock();
mStatusCondition.wait(&mStatusMutex);
mStatusMutex.unlock();
// We are running again
mStatus = Running;
// Let people know that we are running again
emit running();
// Restart our timer
timer.restart();
}
// Determine our next point and compute our model up to it
++voiCounter;
voiSolver->solve(currentPoint,
increasingPoints?
qMin(endingPoint, startingPoint+voiCounter*pointInterval):
qMax(endingPoint, startingPoint+voiCounter*pointInterval));
// Delay things a bit, if (really) needed
if (mData->delay() && (mStatus != Stopped)) {
totalElapsedTime += timer.elapsed();
static_cast<Core::Thread *>(thread())->msleep(mData->delay());
timer.restart();
}
}
if (!mError && (mStatus != Stopped)) {
// Handle our last point
//---GRY--- TO BE DONE...
for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
if (i)
states += ","+QString::number(mData->states()[i]);
else
states = QString::number(mData->states()[i]);
qDebug("%f,%s", currentPoint, qPrintable(states));
// Let people know about our final progress, but only if we didn't stop
// the simulation
updateAndEmitProgress(1.0);
}
// Reset our progress
// Note: we would normally use updateAndEmitProgress(), but we don't
// want to emit the progress, so...
mProgress = 0.0;
// Retrieve the total elapsed time
if (!mError)
totalElapsedTime += timer.elapsed();
// We are done, so...
mStatus = Finished;
// Let people know that we are done and give them the total elapsed time too
emit finished(mError?-1:totalElapsedTime);
// Note: we use -1 as a way to indicate that something went wrong...
} else {
// An error occurred, so...
mStatus = Finished;
// Let people know that we are done
// Note: we use -1 as a way to indicate that something went wrong...
emit finished(-1);
}
// Delete our solver(s)
delete odeSolver;
delete daeSolver;
CoreSolver::resetGlobalNlaSolver();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::pause()
{
// Pause ourselves, but only if we are currently running
if (mStatus == Running) {
// We are pausing
mStatus = Pausing;
// Let people know that we are pausing
emit pausing();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::resume()
{
// Resume ourselves, but only if are currently pausing
if (mStatus == Pausing) {
// Actually resume ourselves
mStatusCondition.wakeAll();
// We are running again
mStatus = Running;
// Let people know that we are running again
emit running();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::stop()
{
// Check that we are either running or pausing
if ((mStatus == Running) || (mStatus == Pausing)) {
// Resume ourselves, if needed
if (mStatus == Pausing)
mStatusCondition.wakeAll();
// Stop ourselves
mStatus = Stopped;
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::emitError(const QString &pMessage)
{
// A solver error occurred, so keep track of it and let people know about it
mError = true;
emit error(pMessage);
}
//==============================================================================
} // namespace SingleCellSimulationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<commit_msg>Some work on our SingleCellSimulationView plugin (#112).<commit_after>//==============================================================================
// Single cell simulation view simulation worker
//==============================================================================
#include "cellmlfileruntime.h"
#include "coredaesolver.h"
#include "corenlasolver.h"
#include "coreodesolver.h"
#include "singlecellsimulationviewsimulation.h"
#include "singlecellsimulationviewsimulationworker.h"
#include "thread.h"
//==============================================================================
#include <QTime>
//==============================================================================
namespace OpenCOR {
namespace SingleCellSimulationView {
//==============================================================================
SingleCellSimulationViewSimulationWorker::SingleCellSimulationViewSimulationWorker(const SolverInterfaces &pSolverInterfaces,
CellMLSupport::CellmlFileRuntime *pCellmlFileRuntime,
SingleCellSimulationViewSimulationData *pData) :
mStatus(Idling),
mSolverInterfaces(pSolverInterfaces),
mCellmlFileRuntime(pCellmlFileRuntime),
mData(pData),
mError(false)
{
// Initialise our progress and let people know about it
updateAndEmitProgress(0.0);
}
//==============================================================================
SingleCellSimulationViewSimulationWorker::Status SingleCellSimulationViewSimulationWorker::status() const
{
// Return our status
return mStatus;
}
//==============================================================================
double SingleCellSimulationViewSimulationWorker::progress() const
{
// Return our progress
return mProgress;
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::updateAndEmitProgress(const double &pProgress)
{
// Set our progress
mProgress = pProgress;
// Let people know about our progress
emit progress(pProgress);
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::run()
{
// Run ourselves, but only if we are currently idling
if (mStatus == Idling) {
// We are running
mStatus = Running;
// Let people know that we are running
emit running();
// Set up our ODE/DAE solver
CoreSolver::CoreVoiSolver *voiSolver = 0;
CoreSolver::CoreOdeSolver *odeSolver = 0;
CoreSolver::CoreDaeSolver *daeSolver = 0;
if (mCellmlFileRuntime->needOdeSolver()) {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mData->odeSolverName())) {
// The requested ODE solver was found, so retrieve an
// instance of it
voiSolver = odeSolver = reinterpret_cast<CoreSolver::CoreOdeSolver *>(solverInterface->instance());
break;
}
} else {
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare("IDA")) {
// The requested DAE solver was found, so retrieve an
// instance of it
voiSolver = daeSolver = reinterpret_cast<CoreSolver::CoreDaeSolver *>(solverInterface->instance());
break;
}
}
// Set up our NLA solver, if needed
if (mCellmlFileRuntime->needNlaSolver())
foreach (SolverInterface *solverInterface, mSolverInterfaces)
if (!solverInterface->name().compare(mData->nlaSolverName())) {
// The requested NLA solver was found, so retrieve an
// instance of it
CoreSolver::setGlobalNlaSolver(reinterpret_cast<CoreSolver::CoreNlaSolver *>(solverInterface->instance()));
break;
}
// Keep track of any error that might be reported by any of our solvers
mError = false;
if (mCellmlFileRuntime->needOdeSolver())
connect(odeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
else
connect(daeSolver, SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
if (mCellmlFileRuntime->needNlaSolver())
connect(CoreSolver::globalNlaSolver(), SIGNAL(error(const QString &)),
this, SLOT(emitError(const QString &)));
// Retrieve our simulation properties
double startingPoint = mData->startingPoint();
double endingPoint = mData->endingPoint();
double pointInterval = mData->pointInterval();
bool increasingPoints = endingPoint > startingPoint;
const double oneOverPointRange = 1.0/(endingPoint-startingPoint);
int voiCounter = 0;
double currentPoint = startingPoint;
// Initialise our ODE/DAE solver
if (mCellmlFileRuntime->needOdeSolver()) {
odeSolver->setProperties(mData->odeSolverProperties());
odeSolver->initialize(currentPoint,
mCellmlFileRuntime->statesCount(),
mData->constants(), mData->states(),
mData->rates(), mData->algebraic(),
mCellmlFileRuntime->computeRates());
} else {
daeSolver->setProperties(mData->daeSolverProperties());
daeSolver->initialize(currentPoint, endingPoint,
mCellmlFileRuntime->statesCount(),
mCellmlFileRuntime->condVarCount(),
mData->constants(), mData->states(),
mData->rates(), mData->algebraic(),
mData->condVar(),
mCellmlFileRuntime->computeEssentialVariables(),
mCellmlFileRuntime->computeResiduals(),
mCellmlFileRuntime->computeRootInformation(),
mCellmlFileRuntime->computeStateInformation());
}
// Initialise our NLA solver
//---GRY--- CHECK do_nonlinearsolve() IN compilermath.cpp SINCE IT ISN'T
// CURRENTLY NEEDED. HOWEVER, OUR CURRENT APPROACH IS NOT NICE AND WE
// REALLY SHOULD INITIALISE THINGS HERE...
if (mCellmlFileRuntime->needNlaSolver()) {
CoreSolver::globalNlaSolver()->setProperties(mData->nlaSolverProperties());
// CoreSolver::globalNlaSolver()->initialize(...);
}
// Now, we are ready to compute our model, but only if no error has
// occurred so far
if (!mError) {
// Start our timer
QTime timer;
int totalElapsedTime = 0;
timer.start();
// Our main work loop
QString states;
for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
if (i)
states += ",STATES["+QString::number(i)+"]";
else
states = "STATES["+QString::number(i)+"]";
qDebug("time,%s", qPrintable(states));
while ( (currentPoint != endingPoint) && !mError
&& (mStatus != Stopped)) {
// Handle our current point after making sure that all the
// variables have been computed
mCellmlFileRuntime->computeVariables()(currentPoint,
mData->constants(),
mData->rates(),
mData->states(),
mData->algebraic());
//---GRY--- TO BE DONE...
for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
if (i)
states += ","+QString::number(mData->states()[i]);
else
states = QString::number(mData->states()[i]);
qDebug("%f,%s", currentPoint, qPrintable(states));
// Let people know about our progress
updateAndEmitProgress((currentPoint-startingPoint)*oneOverPointRange);
// Check whether we should be pausing
if(mStatus == Pausing) {
// We have been asked to pause, so do just that after stopping
// our timer
totalElapsedTime += timer.elapsed();
mStatusMutex.lock();
mStatusCondition.wait(&mStatusMutex);
mStatusMutex.unlock();
// We are running again
mStatus = Running;
// Let people know that we are running again
emit running();
// Restart our timer
timer.restart();
}
// Determine our next point and compute our model up to it
++voiCounter;
voiSolver->solve(currentPoint,
increasingPoints?
qMin(endingPoint, startingPoint+voiCounter*pointInterval):
qMax(endingPoint, startingPoint+voiCounter*pointInterval));
// Delay things a bit, if (really) needed
if (mData->delay() && (mStatus != Stopped)) {
totalElapsedTime += timer.elapsed();
static_cast<Core::Thread *>(thread())->msleep(mData->delay());
timer.restart();
}
}
if (!mError && (mStatus != Stopped)) {
// Handle our last point
//---GRY--- TO BE DONE...
for (int i = 0, iMax = mCellmlFileRuntime->statesCount(); i < iMax; ++i)
if (i)
states += ","+QString::number(mData->states()[i]);
else
states = QString::number(mData->states()[i]);
qDebug("%f,%s", currentPoint, qPrintable(states));
// Let people know about our final progress, but only if we didn't stop
// the simulation
updateAndEmitProgress(1.0);
}
// Reset our progress
// Note: we would normally use updateAndEmitProgress(), but we don't
// want to emit the progress, so...
mProgress = 0.0;
// Retrieve the total elapsed time
if (!mError)
totalElapsedTime += timer.elapsed();
// We are done, so...
mStatus = Finished;
// Let people know that we are done and give them the total elapsed time too
emit finished(mError?-1:totalElapsedTime);
// Note: we use -1 as a way to indicate that something went wrong...
} else {
// An error occurred, so...
mStatus = Finished;
// Let people know that we are done
// Note: we use -1 as a way to indicate that something went wrong...
emit finished(-1);
}
// Delete our solver(s)
delete odeSolver;
delete daeSolver;
CoreSolver::resetGlobalNlaSolver();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::pause()
{
// Pause ourselves, but only if we are currently running
if (mStatus == Running) {
// We are pausing
mStatus = Pausing;
// Let people know that we are pausing
emit pausing();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::resume()
{
// Resume ourselves, but only if are currently pausing
if (mStatus == Pausing) {
// Actually resume ourselves
mStatusCondition.wakeAll();
// We are running again
mStatus = Running;
// Let people know that we are running again
emit running();
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::stop()
{
// Check that we are either running or pausing
if ((mStatus == Running) || (mStatus == Pausing)) {
// Resume ourselves, if needed
if (mStatus == Pausing)
mStatusCondition.wakeAll();
// Stop ourselves
mStatus = Stopped;
}
}
//==============================================================================
void SingleCellSimulationViewSimulationWorker::emitError(const QString &pMessage)
{
// A solver error occurred, so keep track of it and let people know about it
mError = true;
emit error(pMessage);
}
//==============================================================================
} // namespace SingleCellSimulationView
} // namespace OpenCOR
//==============================================================================
// End of file
//==============================================================================
<|endoftext|>
|
<commit_before>/**
* @file llsecapi_test.cpp
* @author Roxie
* @date 2009-02-10
* @brief Test the sec api functionality
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden LregisterSecAPIab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "../llviewerprecompiledheaders.h"
#include "../llviewernetwork.h"
#include "../test/lltut.h"
#include "../llsecapi.h"
#include "../../llxml/llcontrol.h"
//----------------------------------------------------------------------------
// Mock objects for the dependencies of the code we're testing
LLControlGroup::LLControlGroup(const std::string& name)
: LLInstanceTracker<LLControlGroup, std::string>(name) {}
LLControlGroup::~LLControlGroup() {}
BOOL LLControlGroup::declareString(const std::string& name,
const std::string& initial_val,
const std::string& comment,
BOOL persist) {return TRUE;}
void LLControlGroup::setString(const std::string& name, const std::string& val){}
std::string LLControlGroup::getString(const std::string& name)
{
return "";
}
LLControlGroup gSavedSettings("test");
class LLSecAPIBasicHandler : public LLSecAPIHandler
{
protected:
LLPointer<LLCertificateChain> mCertChain;
LLPointer<LLCertificate> mCert;
LLPointer<LLCertificateStore> mCertStore;
LLSD mLLSD;
public:
LLSecAPIBasicHandler() {}
virtual ~LLSecAPIBasicHandler() {}
// instantiate a certificate from a pem string
virtual LLPointer<LLCertificate> getCertificate(const std::string& pem_cert)
{
return mCert;
}
// instiate a certificate from an openssl X509 structure
virtual LLPointer<LLCertificate> getCertificate(X509* openssl_cert)
{
return mCert;
}
// instantiate a chain from an X509_STORE_CTX
virtual LLPointer<LLCertificateChain> getCertificateChain(const X509_STORE_CTX* chain)
{
return mCertChain;
}
// instantiate a cert store given it's id. if a persisted version
// exists, it'll be loaded. If not, one will be created (but not
// persisted)
virtual LLPointer<LLCertificateStore> getCertificateStore(const std::string& store_id)
{
return mCertStore;
}
// persist data in a protected store
virtual void setProtectedData(const std::string& data_type,
const std::string& data_id,
const LLSD& data) {}
// retrieve protected data
virtual LLSD getProtectedData(const std::string& data_type,
const std::string& data_id)
{
return mLLSD;
}
virtual void deleteProtectedData(const std::string& data_type,
const std::string& data_id)
{
}
virtual LLPointer<LLCredential> createCredential(const std::string& grid,
const LLSD& identifier,
const LLSD& authenticator)
{
LLPointer<LLCredential> cred = NULL;
return cred;
}
virtual LLPointer<LLCredential> loadCredential(const std::string& grid)
{
LLPointer<LLCredential> cred = NULL;
return cred;
}
virtual void saveCredential(LLPointer<LLCredential> cred, bool save_authenticator) {}
virtual void deleteCredential(LLPointer<LLCredential> cred) {}
};
// -------------------------------------------------------------------------------------------
// TUT
// -------------------------------------------------------------------------------------------
namespace tut
{
// Test wrapper declaration : wrapping nothing for the moment
struct secapiTest
{
secapiTest()
{
}
~secapiTest()
{
}
};
// Tut templating thingamagic: test group, object and test instance
typedef test_group<secapiTest> secapiTestFactory;
typedef secapiTestFactory::object secapiTestObject;
tut::secapiTestFactory tut_test("llsecapi");
// ---------------------------------------------------------------------------------------
// Test functions
// ---------------------------------------------------------------------------------------
// registration
template<> template<>
void secapiTestObject::test<1>()
{
// retrieve an unknown handler
ensure("'Unknown' handler should be NULL", !(BOOL)getSecHandler("unknown"));
LLPointer<LLSecAPIHandler> test1_handler = new LLSecAPIBasicHandler();
registerSecHandler("sectest1", test1_handler);
ensure("'Unknown' handler should be NULL", !(BOOL)getSecHandler("unknown"));
LLPointer<LLSecAPIHandler> retrieved_test1_handler = getSecHandler("sectest1");
ensure("Retrieved sectest1 handler should be the same",
retrieved_test1_handler == test1_handler);
// insert a second handler
LLPointer<LLSecAPIHandler> test2_handler = new LLSecAPIBasicHandler();
registerSecHandler("sectest2", test2_handler);
ensure("'Unknown' handler should be NULL", !(BOOL)getSecHandler("unknown"));
retrieved_test1_handler = getSecHandler("sectest1");
ensure("Retrieved sectest1 handler should be the same",
retrieved_test1_handler == test1_handler);
LLPointer<LLSecAPIHandler> retrieved_test2_handler = getSecHandler("sectest2");
ensure("Retrieved sectest1 handler should be the same",
retrieved_test2_handler == test2_handler);
}
}
<commit_msg>Fix for SNOW-742 compile & link errors under certain gcc versions due to violation of One Definition Rule. reviewed by Moss.<commit_after>/**
* @file llsecapi_test.cpp
* @author Roxie
* @date 2009-02-10
* @brief Test the sec api functionality
*
* $LicenseInfo:firstyear=2009&license=viewergpl$
*
* Copyright (c) 2009, Linden Research, Inc.
*
* Second Life Viewer Source Code
* The source code in this file ("Source Code") is provided by Linden LregisterSecAPIab
* to you under the terms of the GNU General Public License, version 2.0
* ("GPL"), unless you have obtained a separate licensing agreement
* ("Other License"), formally executed by you and Linden Lab. Terms of
* the GPL can be found in doc/GPL-license.txt in this distribution, or
* online at http://secondlifegrid.net/programs/open_source/licensing/gplv2
*
* There are special exceptions to the terms and conditions of the GPL as
* it is applied to this Source Code. View the full text of the exception
* in the file doc/FLOSS-exception.txt in this software distribution, or
* online at
* http://secondlifegrid.net/programs/open_source/licensing/flossexception
*
* By copying, modifying or distributing this software, you acknowledge
* that you have read and understood your obligations described above,
* and agree to abide by those obligations.
*
* ALL LINDEN LAB SOURCE CODE IS PROVIDED "AS IS." LINDEN LAB MAKES NO
* WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,
* COMPLETENESS OR PERFORMANCE.
* $/LicenseInfo$
*/
#include "../llviewerprecompiledheaders.h"
#include "../llviewernetwork.h"
#include "../test/lltut.h"
#include "../llsecapi.h"
#include "../llsechandler_basic.h"
#include "../../llxml/llcontrol.h"
//----------------------------------------------------------------------------
// Mock objects for the dependencies of the code we're testing
LLControlGroup::LLControlGroup(const std::string& name)
: LLInstanceTracker<LLControlGroup, std::string>(name) {}
LLControlGroup::~LLControlGroup() {}
BOOL LLControlGroup::declareString(const std::string& name,
const std::string& initial_val,
const std::string& comment,
BOOL persist) {return TRUE;}
void LLControlGroup::setString(const std::string& name, const std::string& val){}
std::string LLControlGroup::getString(const std::string& name)
{
return "";
}
LLControlGroup gSavedSettings("test");
LLSecAPIBasicHandler::LLSecAPIBasicHandler() {}
void LLSecAPIBasicHandler::init() {}
LLSecAPIBasicHandler::~LLSecAPIBasicHandler() {}
LLPointer<LLCertificate> LLSecAPIBasicHandler::getCertificate(const std::string& pem_cert) { return NULL; }
LLPointer<LLCertificate> LLSecAPIBasicHandler::getCertificate(X509* openssl_cert) { return NULL; }
LLPointer<LLCertificateChain> LLSecAPIBasicHandler::getCertificateChain(const X509_STORE_CTX* chain) { return NULL; }
LLPointer<LLCertificateStore> LLSecAPIBasicHandler::getCertificateStore(const std::string& store_id) { return NULL; }
void LLSecAPIBasicHandler::setProtectedData(const std::string& data_type, const std::string& data_id, const LLSD& data) {}
LLSD LLSecAPIBasicHandler::getProtectedData(const std::string& data_type, const std::string& data_id) { return LLSD(); }
void LLSecAPIBasicHandler::deleteProtectedData(const std::string& data_type, const std::string& data_id) {}
LLPointer<LLCredential> LLSecAPIBasicHandler::createCredential(const std::string& grid, const LLSD& identifier, const LLSD& authenticator) { return NULL; }
LLPointer<LLCredential> LLSecAPIBasicHandler::loadCredential(const std::string& grid) { return NULL; }
void LLSecAPIBasicHandler::saveCredential(LLPointer<LLCredential> cred, bool save_authenticator) {}
void LLSecAPIBasicHandler::deleteCredential(LLPointer<LLCredential> cred) {}
// -------------------------------------------------------------------------------------------
// TUT
// -------------------------------------------------------------------------------------------
namespace tut
{
// Test wrapper declaration : wrapping nothing for the moment
struct secapiTest
{
secapiTest()
{
}
~secapiTest()
{
}
};
// Tut templating thingamagic: test group, object and test instance
typedef test_group<secapiTest> secapiTestFactory;
typedef secapiTestFactory::object secapiTestObject;
tut::secapiTestFactory tut_test("llsecapi");
// ---------------------------------------------------------------------------------------
// Test functions
// ---------------------------------------------------------------------------------------
// registration
template<> template<>
void secapiTestObject::test<1>()
{
// retrieve an unknown handler
ensure("'Unknown' handler should be NULL", !(BOOL)getSecHandler("unknown"));
LLPointer<LLSecAPIHandler> test1_handler = new LLSecAPIBasicHandler();
registerSecHandler("sectest1", test1_handler);
ensure("'Unknown' handler should be NULL", !(BOOL)getSecHandler("unknown"));
LLPointer<LLSecAPIHandler> retrieved_test1_handler = getSecHandler("sectest1");
ensure("Retrieved sectest1 handler should be the same",
retrieved_test1_handler == test1_handler);
// insert a second handler
LLPointer<LLSecAPIHandler> test2_handler = new LLSecAPIBasicHandler();
registerSecHandler("sectest2", test2_handler);
ensure("'Unknown' handler should be NULL", !(BOOL)getSecHandler("unknown"));
retrieved_test1_handler = getSecHandler("sectest1");
ensure("Retrieved sectest1 handler should be the same",
retrieved_test1_handler == test1_handler);
LLPointer<LLSecAPIHandler> retrieved_test2_handler = getSecHandler("sectest2");
ensure("Retrieved sectest1 handler should be the same",
retrieved_test2_handler == test2_handler);
}
}
<|endoftext|>
|
<commit_before>//===-- XCoreISelDAGToDAG.cpp - A dag to dag inst selector for XCore ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the XCore target.
//
//===----------------------------------------------------------------------===//
#include "XCore.h"
#include "XCoreTargetMachine.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLowering.h"
using namespace llvm;
/// XCoreDAGToDAGISel - XCore specific code to select XCore machine
/// instructions for SelectionDAG operations.
///
namespace {
class XCoreDAGToDAGISel : public SelectionDAGISel {
public:
XCoreDAGToDAGISel(XCoreTargetMachine &TM, CodeGenOpt::Level OptLevel)
: SelectionDAGISel(TM, OptLevel) {}
SDNode *SelectImpl(SDNode *N) override;
SDNode *SelectBRIND(SDNode *N);
/// getI32Imm - Return a target constant with the specified value, of type
/// i32.
inline SDValue getI32Imm(unsigned Imm, SDLoc dl) {
return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
}
inline bool immMskBitp(SDNode *inN) const {
ConstantSDNode *N = cast<ConstantSDNode>(inN);
uint32_t value = (uint32_t)N->getZExtValue();
if (!isMask_32(value)) {
return false;
}
int msksize = 32 - countLeadingZeros(value);
return (msksize >= 1 && msksize <= 8) ||
msksize == 16 || msksize == 24 || msksize == 32;
}
// Complex Pattern Selectors.
bool SelectADDRspii(SDValue Addr, SDValue &Base, SDValue &Offset);
bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
std::vector<SDValue> &OutOps) override;
const char *getPassName() const override {
return "XCore DAG->DAG Pattern Instruction Selection";
}
// Include the pieces autogenerated from the target description.
#include "XCoreGenDAGISel.inc"
};
} // end anonymous namespace
/// createXCoreISelDag - This pass converts a legalized DAG into a
/// XCore-specific DAG, ready for instruction scheduling.
///
FunctionPass *llvm::createXCoreISelDag(XCoreTargetMachine &TM,
CodeGenOpt::Level OptLevel) {
return new XCoreDAGToDAGISel(TM, OptLevel);
}
bool XCoreDAGToDAGISel::SelectADDRspii(SDValue Addr, SDValue &Base,
SDValue &Offset) {
FrameIndexSDNode *FIN = nullptr;
if ((FIN = dyn_cast<FrameIndexSDNode>(Addr))) {
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
return true;
}
if (Addr.getOpcode() == ISD::ADD) {
ConstantSDNode *CN = nullptr;
if ((FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0)))
&& (CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
&& (CN->getSExtValue() % 4 == 0 && CN->getSExtValue() >= 0)) {
// Constant positive word offset from frame index
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
Offset = CurDAG->getTargetConstant(CN->getSExtValue(), SDLoc(Addr),
MVT::i32);
return true;
}
}
return false;
}
bool XCoreDAGToDAGISel::
SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
std::vector<SDValue> &OutOps) {
SDValue Reg;
switch (ConstraintID) {
default: return true;
case InlineAsm::Constraint_m: // Memory.
switch (Op.getOpcode()) {
default: return true;
case XCoreISD::CPRelativeWrapper:
Reg = CurDAG->getRegister(XCore::CP, MVT::i32);
break;
case XCoreISD::DPRelativeWrapper:
Reg = CurDAG->getRegister(XCore::DP, MVT::i32);
break;
}
}
OutOps.push_back(Reg);
OutOps.push_back(Op.getOperand(0));
return false;
}
SDNode *XCoreDAGToDAGISel::SelectImpl(SDNode *N) {
SDLoc dl(N);
switch (N->getOpcode()) {
default: break;
case ISD::Constant: {
uint64_t Val = cast<ConstantSDNode>(N)->getZExtValue();
if (immMskBitp(N)) {
// Transformation function: get the size of a mask
// Look for the first non-zero bit
SDValue MskSize = getI32Imm(32 - countLeadingZeros((uint32_t)Val), dl);
return CurDAG->getMachineNode(XCore::MKMSK_rus, dl,
MVT::i32, MskSize);
}
else if (!isUInt<16>(Val)) {
SDValue CPIdx = CurDAG->getTargetConstantPool(
ConstantInt::get(Type::getInt32Ty(*CurDAG->getContext()), Val),
getTargetLowering()->getPointerTy(CurDAG->getDataLayout()));
SDNode *node = CurDAG->getMachineNode(XCore::LDWCP_lru6, dl, MVT::i32,
MVT::Other, CPIdx,
CurDAG->getEntryNode());
MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
MemOp[0] =
MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
MachineMemOperand::MOLoad, 4, 4);
cast<MachineSDNode>(node)->setMemRefs(MemOp, MemOp + 1);
return node;
}
break;
}
case XCoreISD::LADD: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2) };
return CurDAG->getMachineNode(XCore::LADD_l5r, dl, MVT::i32, MVT::i32,
Ops);
}
case XCoreISD::LSUB: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2) };
return CurDAG->getMachineNode(XCore::LSUB_l5r, dl, MVT::i32, MVT::i32,
Ops);
}
case XCoreISD::MACCU: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2), N->getOperand(3) };
return CurDAG->getMachineNode(XCore::MACCU_l4r, dl, MVT::i32, MVT::i32,
Ops);
}
case XCoreISD::MACCS: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2), N->getOperand(3) };
return CurDAG->getMachineNode(XCore::MACCS_l4r, dl, MVT::i32, MVT::i32,
Ops);
}
case XCoreISD::LMUL: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2), N->getOperand(3) };
return CurDAG->getMachineNode(XCore::LMUL_l6r, dl, MVT::i32, MVT::i32,
Ops);
}
case XCoreISD::CRC8: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) };
return CurDAG->getMachineNode(XCore::CRC8_l4r, dl, MVT::i32, MVT::i32,
Ops);
}
case ISD::BRIND:
if (SDNode *ResNode = SelectBRIND(N))
return ResNode;
break;
// Other cases are autogenerated.
}
return SelectCode(N);
}
/// Given a chain return a new chain where any appearance of Old is replaced
/// by New. There must be at most one instruction between Old and Chain and
/// this instruction must be a TokenFactor. Returns an empty SDValue if
/// these conditions don't hold.
static SDValue
replaceInChain(SelectionDAG *CurDAG, SDValue Chain, SDValue Old, SDValue New)
{
if (Chain == Old)
return New;
if (Chain->getOpcode() != ISD::TokenFactor)
return SDValue();
SmallVector<SDValue, 8> Ops;
bool found = false;
for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) {
if (Chain->getOperand(i) == Old) {
Ops.push_back(New);
found = true;
} else {
Ops.push_back(Chain->getOperand(i));
}
}
if (!found)
return SDValue();
return CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, Ops);
}
SDNode *XCoreDAGToDAGISel::SelectBRIND(SDNode *N) {
SDLoc dl(N);
// (brind (int_xcore_checkevent (addr)))
SDValue Chain = N->getOperand(0);
SDValue Addr = N->getOperand(1);
if (Addr->getOpcode() != ISD::INTRINSIC_W_CHAIN)
return nullptr;
unsigned IntNo = cast<ConstantSDNode>(Addr->getOperand(1))->getZExtValue();
if (IntNo != Intrinsic::xcore_checkevent)
return nullptr;
SDValue nextAddr = Addr->getOperand(2);
SDValue CheckEventChainOut(Addr.getNode(), 1);
if (!CheckEventChainOut.use_empty()) {
// If the chain out of the checkevent intrinsic is an operand of the
// indirect branch or used in a TokenFactor which is the operand of the
// indirect branch then build a new chain which uses the chain coming into
// the checkevent intrinsic instead.
SDValue CheckEventChainIn = Addr->getOperand(0);
SDValue NewChain = replaceInChain(CurDAG, Chain, CheckEventChainOut,
CheckEventChainIn);
if (!NewChain.getNode())
return nullptr;
Chain = NewChain;
}
// Enable events on the thread using setsr 1 and then disable them immediately
// after with clrsr 1. If any resources owned by the thread are ready an event
// will be taken. If no resource is ready we branch to the address which was
// the operand to the checkevent intrinsic.
SDValue constOne = getI32Imm(1, dl);
SDValue Glue =
SDValue(CurDAG->getMachineNode(XCore::SETSR_branch_u6, dl, MVT::Glue,
constOne, Chain), 0);
Glue =
SDValue(CurDAG->getMachineNode(XCore::CLRSR_branch_u6, dl, MVT::Glue,
constOne, Glue), 0);
if (nextAddr->getOpcode() == XCoreISD::PCRelativeWrapper &&
nextAddr->getOperand(0)->getOpcode() == ISD::TargetBlockAddress) {
return CurDAG->SelectNodeTo(N, XCore::BRFU_lu6, MVT::Other,
nextAddr->getOperand(0), Glue);
}
return CurDAG->SelectNodeTo(N, XCore::BAU_1r, MVT::Other, nextAddr, Glue);
}
<commit_msg>SDAG: Implement Select instead of SelectImpl in XCoreDAGToDAGISel<commit_after>//===-- XCoreISelDAGToDAG.cpp - A dag to dag inst selector for XCore ------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines an instruction selector for the XCore target.
//
//===----------------------------------------------------------------------===//
#include "XCore.h"
#include "XCoreTargetMachine.h"
#include "llvm/CodeGen/MachineFrameInfo.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/SelectionDAG.h"
#include "llvm/CodeGen/SelectionDAGISel.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetLowering.h"
using namespace llvm;
/// XCoreDAGToDAGISel - XCore specific code to select XCore machine
/// instructions for SelectionDAG operations.
///
namespace {
class XCoreDAGToDAGISel : public SelectionDAGISel {
public:
XCoreDAGToDAGISel(XCoreTargetMachine &TM, CodeGenOpt::Level OptLevel)
: SelectionDAGISel(TM, OptLevel) {}
void Select(SDNode *N) override;
bool tryBRIND(SDNode *N);
/// getI32Imm - Return a target constant with the specified value, of type
/// i32.
inline SDValue getI32Imm(unsigned Imm, SDLoc dl) {
return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
}
inline bool immMskBitp(SDNode *inN) const {
ConstantSDNode *N = cast<ConstantSDNode>(inN);
uint32_t value = (uint32_t)N->getZExtValue();
if (!isMask_32(value)) {
return false;
}
int msksize = 32 - countLeadingZeros(value);
return (msksize >= 1 && msksize <= 8) ||
msksize == 16 || msksize == 24 || msksize == 32;
}
// Complex Pattern Selectors.
bool SelectADDRspii(SDValue Addr, SDValue &Base, SDValue &Offset);
bool SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
std::vector<SDValue> &OutOps) override;
const char *getPassName() const override {
return "XCore DAG->DAG Pattern Instruction Selection";
}
// Include the pieces autogenerated from the target description.
#include "XCoreGenDAGISel.inc"
};
} // end anonymous namespace
/// createXCoreISelDag - This pass converts a legalized DAG into a
/// XCore-specific DAG, ready for instruction scheduling.
///
FunctionPass *llvm::createXCoreISelDag(XCoreTargetMachine &TM,
CodeGenOpt::Level OptLevel) {
return new XCoreDAGToDAGISel(TM, OptLevel);
}
bool XCoreDAGToDAGISel::SelectADDRspii(SDValue Addr, SDValue &Base,
SDValue &Offset) {
FrameIndexSDNode *FIN = nullptr;
if ((FIN = dyn_cast<FrameIndexSDNode>(Addr))) {
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
Offset = CurDAG->getTargetConstant(0, SDLoc(Addr), MVT::i32);
return true;
}
if (Addr.getOpcode() == ISD::ADD) {
ConstantSDNode *CN = nullptr;
if ((FIN = dyn_cast<FrameIndexSDNode>(Addr.getOperand(0)))
&& (CN = dyn_cast<ConstantSDNode>(Addr.getOperand(1)))
&& (CN->getSExtValue() % 4 == 0 && CN->getSExtValue() >= 0)) {
// Constant positive word offset from frame index
Base = CurDAG->getTargetFrameIndex(FIN->getIndex(), MVT::i32);
Offset = CurDAG->getTargetConstant(CN->getSExtValue(), SDLoc(Addr),
MVT::i32);
return true;
}
}
return false;
}
bool XCoreDAGToDAGISel::
SelectInlineAsmMemoryOperand(const SDValue &Op, unsigned ConstraintID,
std::vector<SDValue> &OutOps) {
SDValue Reg;
switch (ConstraintID) {
default: return true;
case InlineAsm::Constraint_m: // Memory.
switch (Op.getOpcode()) {
default: return true;
case XCoreISD::CPRelativeWrapper:
Reg = CurDAG->getRegister(XCore::CP, MVT::i32);
break;
case XCoreISD::DPRelativeWrapper:
Reg = CurDAG->getRegister(XCore::DP, MVT::i32);
break;
}
}
OutOps.push_back(Reg);
OutOps.push_back(Op.getOperand(0));
return false;
}
void XCoreDAGToDAGISel::Select(SDNode *N) {
SDLoc dl(N);
switch (N->getOpcode()) {
default: break;
case ISD::Constant: {
uint64_t Val = cast<ConstantSDNode>(N)->getZExtValue();
if (immMskBitp(N)) {
// Transformation function: get the size of a mask
// Look for the first non-zero bit
SDValue MskSize = getI32Imm(32 - countLeadingZeros((uint32_t)Val), dl);
ReplaceNode(N, CurDAG->getMachineNode(XCore::MKMSK_rus, dl,
MVT::i32, MskSize));
return;
}
else if (!isUInt<16>(Val)) {
SDValue CPIdx = CurDAG->getTargetConstantPool(
ConstantInt::get(Type::getInt32Ty(*CurDAG->getContext()), Val),
getTargetLowering()->getPointerTy(CurDAG->getDataLayout()));
SDNode *node = CurDAG->getMachineNode(XCore::LDWCP_lru6, dl, MVT::i32,
MVT::Other, CPIdx,
CurDAG->getEntryNode());
MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
MemOp[0] =
MF->getMachineMemOperand(MachinePointerInfo::getConstantPool(*MF),
MachineMemOperand::MOLoad, 4, 4);
cast<MachineSDNode>(node)->setMemRefs(MemOp, MemOp + 1);
ReplaceNode(N, node);
return;
}
break;
}
case XCoreISD::LADD: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2) };
ReplaceNode(N, CurDAG->getMachineNode(XCore::LADD_l5r, dl, MVT::i32,
MVT::i32, Ops));
return;
}
case XCoreISD::LSUB: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2) };
ReplaceNode(N, CurDAG->getMachineNode(XCore::LSUB_l5r, dl, MVT::i32,
MVT::i32, Ops));
return;
}
case XCoreISD::MACCU: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2), N->getOperand(3) };
ReplaceNode(N, CurDAG->getMachineNode(XCore::MACCU_l4r, dl, MVT::i32,
MVT::i32, Ops));
return;
}
case XCoreISD::MACCS: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2), N->getOperand(3) };
ReplaceNode(N, CurDAG->getMachineNode(XCore::MACCS_l4r, dl, MVT::i32,
MVT::i32, Ops));
return;
}
case XCoreISD::LMUL: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1),
N->getOperand(2), N->getOperand(3) };
ReplaceNode(N, CurDAG->getMachineNode(XCore::LMUL_l6r, dl, MVT::i32,
MVT::i32, Ops));
return;
}
case XCoreISD::CRC8: {
SDValue Ops[] = { N->getOperand(0), N->getOperand(1), N->getOperand(2) };
ReplaceNode(N, CurDAG->getMachineNode(XCore::CRC8_l4r, dl, MVT::i32,
MVT::i32, Ops));
return;
}
case ISD::BRIND:
if (tryBRIND(N))
return;
break;
// Other cases are autogenerated.
}
SelectCode(N);
}
/// Given a chain return a new chain where any appearance of Old is replaced
/// by New. There must be at most one instruction between Old and Chain and
/// this instruction must be a TokenFactor. Returns an empty SDValue if
/// these conditions don't hold.
static SDValue
replaceInChain(SelectionDAG *CurDAG, SDValue Chain, SDValue Old, SDValue New)
{
if (Chain == Old)
return New;
if (Chain->getOpcode() != ISD::TokenFactor)
return SDValue();
SmallVector<SDValue, 8> Ops;
bool found = false;
for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i) {
if (Chain->getOperand(i) == Old) {
Ops.push_back(New);
found = true;
} else {
Ops.push_back(Chain->getOperand(i));
}
}
if (!found)
return SDValue();
return CurDAG->getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, Ops);
}
bool XCoreDAGToDAGISel::tryBRIND(SDNode *N) {
SDLoc dl(N);
// (brind (int_xcore_checkevent (addr)))
SDValue Chain = N->getOperand(0);
SDValue Addr = N->getOperand(1);
if (Addr->getOpcode() != ISD::INTRINSIC_W_CHAIN)
return false;
unsigned IntNo = cast<ConstantSDNode>(Addr->getOperand(1))->getZExtValue();
if (IntNo != Intrinsic::xcore_checkevent)
return false;
SDValue nextAddr = Addr->getOperand(2);
SDValue CheckEventChainOut(Addr.getNode(), 1);
if (!CheckEventChainOut.use_empty()) {
// If the chain out of the checkevent intrinsic is an operand of the
// indirect branch or used in a TokenFactor which is the operand of the
// indirect branch then build a new chain which uses the chain coming into
// the checkevent intrinsic instead.
SDValue CheckEventChainIn = Addr->getOperand(0);
SDValue NewChain = replaceInChain(CurDAG, Chain, CheckEventChainOut,
CheckEventChainIn);
if (!NewChain.getNode())
return false;
Chain = NewChain;
}
// Enable events on the thread using setsr 1 and then disable them immediately
// after with clrsr 1. If any resources owned by the thread are ready an event
// will be taken. If no resource is ready we branch to the address which was
// the operand to the checkevent intrinsic.
SDValue constOne = getI32Imm(1, dl);
SDValue Glue =
SDValue(CurDAG->getMachineNode(XCore::SETSR_branch_u6, dl, MVT::Glue,
constOne, Chain), 0);
Glue =
SDValue(CurDAG->getMachineNode(XCore::CLRSR_branch_u6, dl, MVT::Glue,
constOne, Glue), 0);
if (nextAddr->getOpcode() == XCoreISD::PCRelativeWrapper &&
nextAddr->getOperand(0)->getOpcode() == ISD::TargetBlockAddress) {
CurDAG->SelectNodeTo(N, XCore::BRFU_lu6, MVT::Other,
nextAddr->getOperand(0), Glue);
return true;
}
CurDAG->SelectNodeTo(N, XCore::BAU_1r, MVT::Other, nextAddr, Glue);
return true;
}
<|endoftext|>
|
<commit_before>//===- ConstantProp.cpp - Code to perform Simple Constant Propagation -----===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements constant propagation and merging:
//
// Specifically, this:
// * Converts instructions like "add int 1, 2" into 3
//
// Notice that:
// * This pass has a habit of making definitions be dead. It is a good idea
// to to run a DIE pass sometime after running this pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constant.h"
#include "llvm/Instruction.h"
#include "llvm/Pass.h"
#include "llvm/Support/InstIterator.h"
#include "Support/Statistic.h"
#include <set>
using namespace llvm;
namespace {
Statistic<> NumInstKilled("constprop", "Number of instructions killed");
struct ConstantPropagation : public FunctionPass {
bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
};
RegisterOpt<ConstantPropagation> X("constprop","Simple constant propagation");
}
Pass *llvm::createConstantPropagationPass() {
return new ConstantPropagation();
}
bool ConstantPropagation::runOnFunction(Function &F) {
// Initialize the worklist to all of the instructions ready to process...
std::set<Instruction*> WorkList(inst_begin(F), inst_end(F));
bool Changed = false;
while (!WorkList.empty()) {
Instruction *I = *WorkList.begin();
WorkList.erase(WorkList.begin()); // Get an element from the worklist...
if (!I->use_empty()) // Don't muck with dead instructions...
if (Constant *C = ConstantFoldInstruction(I)) {
// Add all of the users of this instruction to the worklist, they might
// be constant propagatable now...
for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
UI != UE; ++UI)
WorkList.insert(cast<Instruction>(*UI));
// Replace all of the uses of a variable with uses of the constant.
I->replaceAllUsesWith(C);
// We made a change to the function...
Changed = true;
++NumInstKilled;
}
}
return Changed;
}
<commit_msg>Constant propagation should remove the dead instructions<commit_after>//===- ConstantProp.cpp - Code to perform Simple Constant Propagation -----===//
//
// The LLVM Compiler Infrastructure
//
// This file was developed by the LLVM research group and is distributed under
// the University of Illinois Open Source License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file implements constant propagation and merging:
//
// Specifically, this:
// * Converts instructions like "add int 1, 2" into 3
//
// Notice that:
// * This pass has a habit of making definitions be dead. It is a good idea
// to to run a DIE pass sometime after running this pass.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/Local.h"
#include "llvm/Constant.h"
#include "llvm/Instruction.h"
#include "llvm/Pass.h"
#include "llvm/Support/InstIterator.h"
#include "Support/Statistic.h"
#include <set>
using namespace llvm;
namespace {
Statistic<> NumInstKilled("constprop", "Number of instructions killed");
struct ConstantPropagation : public FunctionPass {
bool runOnFunction(Function &F);
virtual void getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesCFG();
}
};
RegisterOpt<ConstantPropagation> X("constprop","Simple constant propagation");
}
Pass *llvm::createConstantPropagationPass() {
return new ConstantPropagation();
}
bool ConstantPropagation::runOnFunction(Function &F) {
// Initialize the worklist to all of the instructions ready to process...
std::set<Instruction*> WorkList(inst_begin(F), inst_end(F));
bool Changed = false;
while (!WorkList.empty()) {
Instruction *I = *WorkList.begin();
WorkList.erase(WorkList.begin()); // Get an element from the worklist...
if (!I->use_empty()) // Don't muck with dead instructions...
if (Constant *C = ConstantFoldInstruction(I)) {
// Add all of the users of this instruction to the worklist, they might
// be constant propagatable now...
for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
UI != UE; ++UI)
WorkList.insert(cast<Instruction>(*UI));
// Replace all of the uses of a variable with uses of the constant.
I->replaceAllUsesWith(C);
// Remove the dead instruction.
WorkList.erase(I);
I->getParent()->getInstList().erase(I);
// We made a change to the function...
Changed = true;
++NumInstKilled;
}
}
return Changed;
}
<|endoftext|>
|
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <util/TranscodingException.hpp>
#include <util/XMLString.hpp>
#include <util/XMLUTF8Transcoder.hpp>
#include <util/UTFDataFormatException.hpp>
// ---------------------------------------------------------------------------
// Local static data
//
// gUTFBytes
// A list of counts of trailing bytes for each initial byte in the input.
//
// gUTFOffsets
// A list of values to offset each result char type, according to how
// many source bytes when into making it.
//
// gFirstByteMark
// A list of values to mask onto the first byte of an encoded sequence,
// indexed by the number of bytes used to create the sequence.
// ---------------------------------------------------------------------------
static const XMLByte gUTFBytes[256] =
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2
, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5
};
static const XMLUInt32 gUTFOffsets[6] =
{
0, 0x3080, 0xE2080, 0x3C82080, 0xFA082080, 0x82082080
};
static const XMLByte gFirstByteMark[7] =
{
0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC
};
// ---------------------------------------------------------------------------
// XMLUTF8Transcoder: Constructors and Destructor
// ---------------------------------------------------------------------------
XMLUTF8Transcoder::XMLUTF8Transcoder(const XMLCh* const encodingName
, const unsigned int blockSize) :
XMLTranscoder(encodingName, blockSize)
{
}
XMLUTF8Transcoder::~XMLUTF8Transcoder()
{
}
// ---------------------------------------------------------------------------
// XMLUTF8Transcoder: Implementation of the transcoder API
// ---------------------------------------------------------------------------
unsigned int
XMLUTF8Transcoder::transcodeFrom(const XMLByte* const srcData
, const unsigned int srcCount
, XMLCh* const toFill
, const unsigned int maxChars
, unsigned int& bytesEaten
, unsigned char* const charSizes)
{
// Watch for pathological scenario. Shouldn't happen, but...
if (!srcCount || !maxChars)
return 0;
// If debugging, make sure that the block size is legal
#if defined(XERCES_DEBUG)
checkBlockSize(maxChars);
#endif
//
// Get pointers to our start and end points of the input and output
// buffers.
//
const XMLByte* srcPtr = srcData;
const XMLByte* srcEnd = srcPtr + srcCount;
XMLCh* outPtr = toFill;
XMLCh* outEnd = outPtr + maxChars;
unsigned char* sizePtr = charSizes;
//
// We now loop until we either run out of input data, or room to store
// output chars.
//
while ((srcPtr < srcEnd) && (outPtr < outEnd))
{
// Get the next leading byte out
const XMLByte firstByte = *srcPtr;
// Special-case ASCII, which is a leading byte value of <= 127
if (firstByte <= 127)
{
*outPtr++ = XMLCh(firstByte);
srcPtr++;
*sizePtr++ = 1;
continue;
}
// See how many trailing src bytes this sequence is going to require
const unsigned int trailingBytes = gUTFBytes[firstByte];
//
// If there are not enough source bytes to do this one, then we
// are done. Note that we done >= here because we are implicitly
// counting the 1 byte we get no matter what.
//
// If we break out here, then there is nothing to undo since we
// haven't updated any pointers yet.
//
if (srcPtr + trailingBytes >= srcEnd)
break;
// Looks ok, so lets build up the value
XMLUInt32 tmpVal = 0;
switch(trailingBytes)
{
case 5 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 4 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 3 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 2 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 1 : tmpVal += *srcPtr++; tmpVal <<= 6;
case 0 : tmpVal += *srcPtr++;
break;
default :
ThrowXML(TranscodingException, XMLExcepts::Trans_BadSrcSeq);
}
tmpVal -= gUTFOffsets[trailingBytes];
//
// If it will fit into a single char, then put it in. Otherwise
// encode it as a surrogate pair. If its not valid, use the
// replacement char.
//
if (!(tmpVal & 0xFFFF0000))
{
*sizePtr++ = trailingBytes + 1;
*outPtr++ = XMLCh(tmpVal);
}
else if (tmpVal > 0x10FFFF)
{
//
// If we've gotten more than 32 chars so far, then just break
// out for now and lets process those. When we come back in
// here again, we'll get no chars and throw an exception. This
// way, the error will have a line and col number closer to
// the real problem area.
//
if ((outPtr - toFill) > 32)
break;
ThrowXML(TranscodingException, XMLExcepts::Trans_BadSrcSeq);
}
else
{
//
// If we have enough room to store the leading and trailing
// chars, then lets do it. Else, pretend this one never
// happened, and leave it for the next time. Since we don't
// update the bytes read until the bottom of the loop, by
// breaking out here its like it never happened.
//
if (outPtr + 1 >= outEnd)
break;
// Store the leading surrogate char
tmpVal -= 0x10000;
*sizePtr++ = trailingBytes + 1;
*outPtr++ = XMLCh((tmpVal >> 10) + 0xD800);
//
// And then the treailing char. This one accounts for no
// bytes eaten from the source, so set the char size for this
// one to be zero.
//
*sizePtr++ = 0;
*outPtr++ = XMLCh(tmpVal & 0x3FF) + 0xDC00;
}
}
// Update the bytes eaten
bytesEaten = srcPtr - srcData;
// Return the characters read
return outPtr - toFill;
}
unsigned int
XMLUTF8Transcoder::transcodeTo( const XMLCh* const srcData
, const unsigned int srcCount
, XMLByte* const toFill
, const unsigned int maxBytes
, unsigned int& charsEaten
, const UnRepOpts options)
{
// Watch for pathological scenario. Shouldn't happen, but...
if (!srcCount || !maxBytes)
return 0;
//
// Get pointers to our start and end points of the input and output
// buffers.
//
const XMLCh* srcPtr = srcData;
const XMLCh* srcEnd = srcPtr + srcCount;
XMLByte* outPtr = toFill;
XMLByte* outEnd = toFill + maxBytes;
while (srcPtr < srcEnd)
{
//
// Tentatively get the next char out. We have to get it into a
// 32 bit value, because it could be a surrogate pair.
//
XMLUInt32 curVal = *srcPtr;
//
// If its a leading surrogate, then lets see if we have the trailing
// available. If not, then give up now and leave it for next time.
//
unsigned int srcUsed = 1;
if ((curVal >= 0xD800) && (curVal <= 0xDBFF))
{
if (srcPtr + 1 >= srcEnd)
break;
// Create the composite surrogate pair
curVal = ((curVal - 0xD800) << 10)
+ ((*(srcPtr + 1) - 0xDC00) + 0x10000);
// And indicate that we ate another one
srcUsed++;
}
// Figure out how many bytes we need
unsigned int encodedBytes;
if (curVal < 0x80)
encodedBytes = 1;
else if (curVal < 0x800)
encodedBytes = 2;
else if (curVal < 0x10000)
encodedBytes = 3;
else if (curVal < 0x200000)
encodedBytes = 4;
else if (curVal < 0x4000000)
encodedBytes = 5;
else if (curVal <= 0x7FFFFFFF)
encodedBytes = 6;
else
{
// If the options say to throw, then throw
if (options == UnRep_Throw)
{
XMLCh tmpBuf[16];
XMLString::binToText(curVal, tmpBuf, 16, 16);
ThrowXML2
(
TranscodingException
, XMLExcepts::Trans_Unrepresentable
, tmpBuf
, getEncodingName()
);
}
// Else, use the replacement character
*outPtr++ = chSpace;
srcPtr += srcUsed;
continue;
}
//
// If we cannot fully get this char into the output buffer,
// then leave it for the next time.
//
if (outPtr + encodedBytes > outEnd)
break;
// We can do it, so update the source index
srcPtr += srcUsed;
//
// And spit out the bytes. We spit them out in reverse order
// here, so bump up the output pointer and work down as we go.
//
outPtr += encodedBytes;
switch(encodedBytes)
{
case 6 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
curVal >>= 6;
case 5 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
curVal >>= 6;
case 4 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
curVal >>= 6;
case 3 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
curVal >>= 6;
case 2 : *--outPtr = XMLByte((curVal | 0x80UL) & 0xBFUL);
curVal >>= 6;
case 1 : *--outPtr = XMLByte
(
curVal | gFirstByteMark[encodedBytes]
);
}
// Add the encoded bytes back in again to indicate we've eaten them
outPtr += encodedBytes;
}
// Fill in the chars we ate
charsEaten = (srcPtr - srcData);
// And return the bytes we filled in
return (outPtr - toFill);
}
bool XMLUTF8Transcoder::canTranscodeTo(const unsigned int toCheck) const
{
// We can represent anything in the Unicode (with surrogates) range
return (toCheck <= 0x10FFFF);
}
<commit_msg>Undo inadvertant remove<commit_after><|endoftext|>
|
<commit_before>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <functional>
// class function<R(ArgTypes...)>
// explicit function();
#include <functional>
#include <cassert>
int main(int, char**)
{
std::function<int(int)> f;
assert(!f);
return 0;
}
<commit_msg>[NFC] Fix incorrect comment in std::function test<commit_after>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// <functional>
// class function<R(ArgTypes...)>
// function();
#include <functional>
#include <cassert>
int main(int, char**)
{
std::function<int(int)> f;
assert(!f);
return 0;
}
<|endoftext|>
|
<commit_before>/////////////////////////////////////
// This C code is a companion to the paper
//
/////////////////////////////////////
//
// this code will hash strings of 64-bit characters. To use on
// strings of 8-bit characters, you may need some adequate padding.
//
#include <cassert>
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
#include <iostream>
using namespace std;
#ifdef __AVX__
#define __PCLMUL__ 1
#endif
extern "C" {
#include "timers.h"
#include "hashfunctions32bits.h"
#include "hashfunctions64bits.h"
#include "clmulhashfunctions32bits.h"
#include "clmulhashfunctions64bits.h"
#include "clmulpoly64bits.h"
#include "clmulhierarchical64bits.h"
#include "ghash.h"
#include "bigendianuniversal.h"
}
#include "treehash/simple-treehash.hh"
#include "treehash/recursive-treehash.hh"
#include "treehash/binary-treehash.hh"
#include "treehash/boosted-treehash.hh"
struct NamedFunc {
const hashFunction64 f;
const string name;
NamedFunc(const hashFunction64& f, const string& name) : f(f), name(name) {}
};
#define NAMED(f) NamedFunc(f, #f)
NamedFunc hashFunctions[] = {
// From the 2015 paper:
NAMED(&hashVHASH64), NAMED(&CLHASH), NAMED(&hashCity), NAMED(&hashSipHash),
NAMED(&GHASH64bit),
// Horner methods:
NAMED(&hornerHash), NAMED(&unrolledHorner4), NAMED(&twiceHorner32),
NAMED(&iterateCL11),
// Tree hashing:
NAMED(&treeCL9), NAMED(&simple_treehash), NAMED(&recursive_treehash),
NAMED(&binary_treehash), NAMED(&boosted_treehash<1>),
NAMED(&boosted_treehash<2>), NAMED(&boosted_treehash<3>),
NAMED(&boosted_treehash<4>), NAMED(&boosted_treehash<5>),
NAMED(&boosted_treehash<6>), NAMED(&boosted_treehash<7>),
NAMED(&simple_cl_treehash), NAMED(&generic_simple_treehash<MultiplyShift>),
NAMED(&generic_simple_treehash<NH>), NAMED(&generic_simple_treehash<CLNH>),
NAMED((&generic_simple_treehash<Wide<MultiplyShift, 15> >)),
NAMED((&generic_simple_treehash<Wide<NH, 4> >)),
NAMED((&generic_simple_treehash<Wide<CLNH, 4> >)),
NAMED((&generic_simple_treehash<Wide<CLNHx2, 4> >)),
};
const int HowManyFunctions64 =
sizeof(hashFunctions) / sizeof(hashFunctions[0]);
int main(int c, char ** arg) {
(void) (c);
(void) (arg);
uint64_t which_algos = ~0;
assert(HowManyFunctions64 <= 64);
if (c > 1) {
if (1 != sscanf(arg[1], "%" SCNu64, &which_algos)) {
return 1;
}
}
int lengthStart = 1, lengthEnd = 2048; // inclusive
if (c > 2)
lengthStart = atoi(arg[2]);
if (c > 3)
lengthEnd = atoi(arg[3]);
int i, j;
int length;
int SHORTTRIALS;
struct timeval start, finish;
uint64_t randbuffer[150] __attribute__ ((aligned (16)));// 150 should be plenty
uint32_t sumToFoolCompiler = 0;
uint64_t * intstring;
// We need 32 bytes of alignment for working with __m256i's
if (posix_memalign((void **)(&intstring), 32, sizeof(uint64_t)*lengthEnd)) {
cerr << "Failed to allocate " << lengthEnd << " words." << endl;
return 1;
}
for (i = 0; i < 150; ++i) {
randbuffer[i] = rand() | ((uint64_t)(rand()) << 32);
}
for (i = 0; i < lengthEnd; ++i) {
intstring[i] = rand() | ((uint64_t)(rand()) << 32);
}
printf("#Reporting the number of cycles per byte.\n");
printf("#First number is input length in 8-byte words.\n");
printf("0 ");
for (i = 0; i < HowManyFunctions64; ++i) {
if (which_algos & (0x1ull << i))
cout << '"' << hashFunctions[i].name << "\" ";
}
printf("\n");
fflush(stdout);
for (length = lengthStart; length <= lengthEnd; length += 1) {
SHORTTRIALS = 8000000 / length;
printf("%8d \t\t", length);
for (i = 0; i < HowManyFunctions64; ++i) {
if (!(which_algos & (0x1ull << i)))
continue; // skip unselected algos
const hashFunction64 thisfunc64 = hashFunctions[i].f;
sumToFoolCompiler += thisfunc64(randbuffer, intstring, length); // we do not count the first one
gettimeofday(&start, 0);
ticks lowest = ~(ticks)0;
for (j = 0; j < SHORTTRIALS; ++j) {
const ticks bef = startRDTSC();
sumToFoolCompiler += thisfunc64(randbuffer, intstring, length);
const ticks aft = stopRDTSCP();
const ticks diff = aft-bef;
lowest = (lowest < diff) ? lowest : diff;
}
gettimeofday(&finish, 0);
printf(" %.2f ", lowest * 1.0 / (8.0 * length));
fflush(stdout);
}
printf("\n");
}
free(intstring);
printf("# ignore this #%d\n", sumToFoolCompiler);
}
<commit_msg>Add one more to the precision for fine-tuning<commit_after>/////////////////////////////////////
// This C code is a companion to the paper
//
/////////////////////////////////////
//
// this code will hash strings of 64-bit characters. To use on
// strings of 8-bit characters, you may need some adequate padding.
//
#include <cassert>
#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <sys/time.h>
#include <iostream>
using namespace std;
#ifdef __AVX__
#define __PCLMUL__ 1
#endif
extern "C" {
#include "timers.h"
#include "hashfunctions32bits.h"
#include "hashfunctions64bits.h"
#include "clmulhashfunctions32bits.h"
#include "clmulhashfunctions64bits.h"
#include "clmulpoly64bits.h"
#include "clmulhierarchical64bits.h"
#include "ghash.h"
#include "bigendianuniversal.h"
}
#include "treehash/simple-treehash.hh"
#include "treehash/recursive-treehash.hh"
#include "treehash/binary-treehash.hh"
#include "treehash/boosted-treehash.hh"
struct NamedFunc {
const hashFunction64 f;
const string name;
NamedFunc(const hashFunction64& f, const string& name) : f(f), name(name) {}
};
#define NAMED(f) NamedFunc(f, #f)
NamedFunc hashFunctions[] = {
// From the 2015 paper:
NAMED(&hashVHASH64), NAMED(&CLHASH), NAMED(&hashCity), NAMED(&hashSipHash),
NAMED(&GHASH64bit),
// Horner methods:
NAMED(&hornerHash), NAMED(&unrolledHorner4), NAMED(&twiceHorner32),
NAMED(&iterateCL11),
// Tree hashing:
NAMED(&treeCL9), NAMED(&simple_treehash), NAMED(&recursive_treehash),
NAMED(&binary_treehash), NAMED(&boosted_treehash<1>),
NAMED(&boosted_treehash<2>), NAMED(&boosted_treehash<3>),
NAMED(&boosted_treehash<4>), NAMED(&boosted_treehash<5>),
NAMED(&boosted_treehash<6>), NAMED(&boosted_treehash<7>),
NAMED(&simple_cl_treehash), NAMED(&generic_simple_treehash<MultiplyShift>),
NAMED(&generic_simple_treehash<NH>), NAMED(&generic_simple_treehash<CLNH>),
NAMED((&generic_simple_treehash<Wide<MultiplyShift, 15> >)),
NAMED((&generic_simple_treehash<Wide<NH, 4> >)),
NAMED((&generic_simple_treehash<Wide<CLNH, 4> >)),
NAMED((&generic_simple_treehash<Wide<CLNHx2, 4> >)),
};
const int HowManyFunctions64 =
sizeof(hashFunctions) / sizeof(hashFunctions[0]);
int main(int c, char ** arg) {
(void) (c);
(void) (arg);
uint64_t which_algos = ~0;
assert(HowManyFunctions64 <= 64);
if (c > 1) {
if (1 != sscanf(arg[1], "%" SCNu64, &which_algos)) {
return 1;
}
}
int lengthStart = 1, lengthEnd = 2048; // inclusive
if (c > 2)
lengthStart = atoi(arg[2]);
if (c > 3)
lengthEnd = atoi(arg[3]);
int i, j;
int length;
int SHORTTRIALS;
struct timeval start, finish;
uint64_t randbuffer[150] __attribute__ ((aligned (16)));// 150 should be plenty
uint32_t sumToFoolCompiler = 0;
uint64_t * intstring;
// We need 32 bytes of alignment for working with __m256i's
if (posix_memalign((void **)(&intstring), 32, sizeof(uint64_t)*lengthEnd)) {
cerr << "Failed to allocate " << lengthEnd << " words." << endl;
return 1;
}
for (i = 0; i < 150; ++i) {
randbuffer[i] = rand() | ((uint64_t)(rand()) << 32);
}
for (i = 0; i < lengthEnd; ++i) {
intstring[i] = rand() | ((uint64_t)(rand()) << 32);
}
printf("#Reporting the number of cycles per byte.\n");
printf("#First number is input length in 8-byte words.\n");
printf("0 ");
for (i = 0; i < HowManyFunctions64; ++i) {
if (which_algos & (0x1ull << i))
cout << '"' << hashFunctions[i].name << "\" ";
}
printf("\n");
fflush(stdout);
for (length = lengthStart; length <= lengthEnd; length += 1) {
SHORTTRIALS = 8000000 / length;
printf("%8d \t\t", length);
for (i = 0; i < HowManyFunctions64; ++i) {
if (!(which_algos & (0x1ull << i)))
continue; // skip unselected algos
const hashFunction64 thisfunc64 = hashFunctions[i].f;
sumToFoolCompiler += thisfunc64(randbuffer, intstring, length); // we do not count the first one
gettimeofday(&start, 0);
ticks lowest = ~(ticks)0;
for (j = 0; j < SHORTTRIALS; ++j) {
const ticks bef = startRDTSC();
sumToFoolCompiler += thisfunc64(randbuffer, intstring, length);
const ticks aft = stopRDTSCP();
const ticks diff = aft-bef;
lowest = (lowest < diff) ? lowest : diff;
}
gettimeofday(&finish, 0);
printf(" %.3f ", lowest * 1.0 / (8.0 * length));
fflush(stdout);
}
printf("\n");
}
free(intstring);
printf("# ignore this #%d\n", sumToFoolCompiler);
}
<|endoftext|>
|
<commit_before>#include <boost/pointer_cast.hpp>
#include "messageStream.h"
using namespace watcher;
using namespace watcher::event;
using namespace std;
INIT_LOGGER(MessageStream, "MessageStream");
MessageStream::MessageStream(const string &serverName_, const Timestamp &startTime_, const float streamRate_) :
messageStreamFilters(),
streamRate(streamRate_),
streamStartTime(startTime_),
connection(new Client(serverName_, shared_from_this())) // GTL - there has got to be a better way to do this.
{
TRACE_ENTER();
TRACE_EXIT();
}
// virtual
MessageStream::~MessageStream()
{
TRACE_ENTER();
TRACE_EXIT();
}
bool MessageStream::setStreamTimeStart(const Timestamp &startTime)
{
TRACE_ENTER()
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::setStreamRate(const float &messageStreamRate)
{
TRACE_ENTER();
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::getNextMessage(MessagePtr newMessage)
{
TRACE_ENTER();
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::isStreamReadable() const
{
TRACE_ENTER();
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::addMessageFilter(const MessageStreamFilter &filter)
{
TRACE_ENTER();
assert(0); // filters are not supported yet.
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::getMessageTimeRange(Timestamp &startTime, Timestamp endTime)
{
TRACE_ENTER();
TRACE_EXIT_RET("true");
return true;
}
//virtual
std::ostream &MessageStream::toStream(std::ostream &out) const
{
TRACE_ENTER();
out << "MessageStream output operator not yet implemented - this space intensionally left blank";
TRACE_EXIT();
return out;
}
bool MessageStream::startStream()
{
TRACE_ENTER();
// startWatcherMessagePtr mess(new startWatcherMessage);
// bool retVal=connection.sendMessage(mess);
// TRACE_EXIT_RET((retVal==true?"true":"false"));
// return retVal;
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::stopStream()
{
TRACE_ENTER();
// stopWatcherMessagePtr mess(new stopWatcherMessage);
// bool retVal=connection.sendMessage(mess);
// TRACE_EXIT_RET((retVal==true?"true":"false"));
// return retVal;
TRACE_EXIT_RET("true");
return true;
}
//virtual
bool MessageStream::messageArrived(MessagePtr message)
{
TRACE_ENTER();
TRACE_EXIT();
}
std::ostream &operator<<(std::ostream &out, const MessageStream &messStream)
{
TRACE_ENTER();
TRACE_EXIT();
return out;
}
<commit_msg>return value from skel function to stop warning.<commit_after>#include <boost/pointer_cast.hpp>
#include "messageStream.h"
using namespace watcher;
using namespace watcher::event;
using namespace std;
INIT_LOGGER(MessageStream, "MessageStream");
MessageStream::MessageStream(const string &serverName_, const Timestamp &startTime_, const float streamRate_) :
messageStreamFilters(),
streamRate(streamRate_),
streamStartTime(startTime_),
connection(new Client(serverName_, shared_from_this())) // GTL - there has got to be a better way to do this.
{
TRACE_ENTER();
TRACE_EXIT();
}
// virtual
MessageStream::~MessageStream()
{
TRACE_ENTER();
TRACE_EXIT();
}
bool MessageStream::setStreamTimeStart(const Timestamp &startTime)
{
TRACE_ENTER()
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::setStreamRate(const float &messageStreamRate)
{
TRACE_ENTER();
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::getNextMessage(MessagePtr newMessage)
{
TRACE_ENTER();
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::isStreamReadable() const
{
TRACE_ENTER();
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::addMessageFilter(const MessageStreamFilter &filter)
{
TRACE_ENTER();
assert(0); // filters are not supported yet.
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::getMessageTimeRange(Timestamp &startTime, Timestamp endTime)
{
TRACE_ENTER();
TRACE_EXIT_RET("true");
return true;
}
//virtual
std::ostream &MessageStream::toStream(std::ostream &out) const
{
TRACE_ENTER();
out << "MessageStream output operator not yet implemented - this space intensionally left blank";
TRACE_EXIT();
return out;
}
bool MessageStream::startStream()
{
TRACE_ENTER();
// startWatcherMessagePtr mess(new startWatcherMessage);
// bool retVal=connection.sendMessage(mess);
// TRACE_EXIT_RET((retVal==true?"true":"false"));
// return retVal;
TRACE_EXIT_RET("true");
return true;
}
bool MessageStream::stopStream()
{
TRACE_ENTER();
// stopWatcherMessagePtr mess(new stopWatcherMessage);
// bool retVal=connection.sendMessage(mess);
// TRACE_EXIT_RET((retVal==true?"true":"false"));
// return retVal;
TRACE_EXIT_RET("true");
return true;
}
//virtual
bool MessageStream::messageArrived(MessagePtr message)
{
TRACE_ENTER();
TRACE_EXIT_RET("false");
return false;
}
std::ostream &operator<<(std::ostream &out, const MessageStream &messStream)
{
TRACE_ENTER();
TRACE_EXIT();
return out;
}
<|endoftext|>
|
<commit_before>// Composes two transform sets.
// Output transform is the result of applying the first input transform, followed by the second.
#include <assert.h>
#include "itkTransformFileReader.h"
#include "itkTransformFileWriter.h"
#include "itkTransformFactory.h"
#include "itkMatrixOffsetTransformBase.h"
#include "IOHelpers.hpp"
#include "Dirs.hpp"
void checkUsage(int argc, char const *argv[]) {
if( argc < 3 )
{
cerr << "\nUsage: " << endl;
cerr << argv[0] << " firstInputDir secondInputDir outputDir\n\n";
exit(EXIT_FAILURE);
}
}
int main(int argc, char const *argv[]) {
// Verify the number of parameters in the command line
checkUsage(argc, argv);
// Generate file lists
vector< string > firstInputFileNames = constructPaths(argv[1], Dirs::ImageList(), ".meta");
vector< string > secondInputFileNames = constructPaths(argv[2], Dirs::ImageList(), ".meta");
vector< string > outputFileNames = constructPaths(argv[3], Dirs::ImageList(), ".meta");
// Some transforms might not be registered
// with the factory so we add them manually
itk::TransformFactoryBase::RegisterDefaultTransforms();
// itk::TransformFactory< itk::TranslationTransform< double, 2 > >::RegisterTransform();
// Generate new transforms
typedef itk::TransformFileReader ReaderType;
typedef itk::TransformFileWriter WriterType;
// TranslationTransform also has a Compose() interface, but only with other TranslationTransforms
typedef itk::MatrixOffsetTransformBase< double, 2, 2 > ComposableTransformType;
for(unsigned int i=0; i < firstInputFileNames.size(); ++i)
{
// Load input transforms
ReaderType::Pointer firstReader = ReaderType::New();
ReaderType::Pointer secondReader = ReaderType::New();
firstReader->SetFileName( firstInputFileNames[i].c_str() );
secondReader->SetFileName( secondInputFileNames[i].c_str() );
firstReader->Update();
secondReader->Update();
// check that transforms are of the right dynamic type
ComposableTransformType *pFirstTransform = dynamic_cast<ComposableTransformType*>( firstReader->GetTransformList()->begin()->GetPointer() );
ComposableTransformType *pSecondTransform = dynamic_cast<ComposableTransformType*>( secondReader->GetTransformList()->begin()->GetPointer() );
assert( pFirstTransform != 0 && pSecondTransform != 0 );
// compose transforms
// If the argument pre is true, then other is precomposed with self; that is, the resulting transformation consists of first applying
// other to the source, followed by self. If pre is false or omitted, then other is post-composed with self; that is the resulting
// transformation consists of first applying self to the source, followed by other. This updates the Translation based on current center.
pFirstTransform->Compose(pSecondTransform);
// save output transform
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputFileNames[i].c_str() );
writer->AddTransform( pFirstTransform );
writer->Update();
}
return EXIT_SUCCESS;
}
<commit_msg>Compose diffusion transforms from originals and adjustments<commit_after>// Composes two transform sets.
// Output transform is the result of applying the first input transform, followed by the second.
#include <assert.h>
#include "itkTransformFileReader.h"
#include "itkTransformFileWriter.h"
#include "itkTransformFactory.h"
#include "itkAffineTransform.h"
#include "IOHelpers.hpp"
#include "Dirs.hpp"
void checkUsage(int argc, char const *argv[]) {
if( argc < 3 )
{
cerr << "\nUsage: " << endl;
cerr << argv[0] << " originalDir adjustmentDir outputDir\n\n";
exit(EXIT_FAILURE);
}
}
int main(int argc, char const *argv[]) {
// Verify the number of parameters in the command line
checkUsage(argc, argv);
// Generate file lists
vector< string > basenames = directoryContents(argv[1]);
vector< string > originalPaths = constructPaths(argv[1], basenames);
vector< string > adjustmentPaths = constructPaths(argv[2], basenames);
vector< string > outputPaths = constructPaths(argv[3], basenames);
// clear results directory
remove_all(argv[3]);
create_directory(argv[3]);
// Some transforms might not be registered
// with the factory so we add them manually
itk::TransformFactoryBase::RegisterDefaultTransforms();
// itk::TransformFactory< itk::TranslationTransform< double, 2 > >::RegisterTransform();
// Generate new transforms
typedef itk::TransformFileReader ReaderType;
typedef itk::TransformFileWriter WriterType;
// TranslationTransform also has a Compose() interface, but only with other TranslationTransforms
typedef itk::MatrixOffsetTransformBase< double, 2, 2 > ComposableTransformType;
typedef itk::AffineTransform< double, 2 > AffineTransformType;
// the first and last slices should not have adjustments
// apply adjustments for every other slice
for(unsigned int i=1; i < originalPaths.size() - 1; ++i)
{
// Load input transforms
ReaderType::Pointer originalReader = ReaderType::New();
ReaderType::Pointer adjustmentReader = ReaderType::New();
originalReader->SetFileName( originalPaths[i].c_str() );
adjustmentReader->SetFileName( adjustmentPaths[i].c_str() );
originalReader->Update();
adjustmentReader->Update();
// check that transforms are of the right dynamic type
ComposableTransformType *pOriginalTransform = dynamic_cast<ComposableTransformType*>( originalReader->GetTransformList()->begin()->GetPointer() );
ComposableTransformType *pAdjustmentTransform = dynamic_cast<ComposableTransformType*>( adjustmentReader->GetTransformList()->begin()->GetPointer() );
assert( pOriginalTransform != 0 && pAdjustmentTransform != 0 );
// compose transforms
// If the argument pre is true (default false), then other is precomposed with self; that is, the resulting transformation consists of first
// applying other to the source, followed by self. If pre is false or omitted, then other is post-composed with self; that is the resulting
// transformation consists of first applying self to the source, followed by other. This updates the Translation based on current center.
AffineTransformType::Pointer outputTransform = AffineTransformType::New();
outputTransform->SetIdentity();
outputTransform->Compose(pOriginalTransform);
outputTransform->Compose(pAdjustmentTransform);
// save output transform
WriterType::Pointer writer = WriterType::New();
writer->SetFileName( outputPaths[i].c_str() );
writer->AddTransform( outputTransform );
writer->Update();
}
// write out the unaltered first and last transforms
copy_file( *(originalPaths.begin()), *(outputPaths.begin()) );
copy_file( *(--originalPaths.end()), *(--outputPaths.end()) );
return EXIT_SUCCESS;
}
<|endoftext|>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.