<commit_before>/*
    Copyright 2011 Joe Hermaszewski. All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.

    The views and conclusions contained in the software and documentation are
    those of the authors and should not be interpreted as representing official
    policies, either expressed or implied, of Joe Hermaszewski.
*/

#include "state_assignment_statement.hpp"

#include <cassert>
#include <memory>
#include <string>
#include <utility>

#include <compiler/code_generator.hpp>
#include <compiler/generic_value.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expressions/expression.hpp>
#include <compiler/tokens/expressions/cast_expression.hpp>
#include <joelang/state.hpp>
#include <joelang/state_assignment.hpp>

namespace JoeLang
{
namespace Compiler
{

//------------------------------------------------------------------------------
// StateAssignmentStatement
//------------------------------------------------------------------------------
StateAssignmentStatement::StateAssignmentStatement(
                                    std::string identifier,
                                    Expression_up expression )
    :PassStatement( TokenTy::StateAssignmentStatement )
    ,m_Identifier( std::move(identifier) )
    ,m_Expression( std::move(expression) )
{
    assert( !m_Identifier.empty() &&
            "Trying to create a StateAssignmentStatement with an empty state "
            "name" );
    assert( m_Expression &&
            "Trying to create a StateAssignmentStatement with a null "
            "expression" );
}

StateAssignmentStatement::~StateAssignmentStatement()
{
}

bool StateAssignmentStatement::PerformSema( SemaAnalyzer& sema )
{
    // create a scope for the enumerants
    SemaAnalyzer::ScopeHolder scope( sema );
    scope.Enter();

    // Try and get the state to which we are assigning
    m_State = sema.GetState( m_Identifier );
    if( !m_State )
    {
        sema.Error( "Undeclared state: " + m_Identifier );
        return false;
    }
    sema.LoadStateEnumerants( *m_State );

    m_Expression = CastExpression::Create( m_State->GetType(),
                                           std::move(m_Expression),
                                           false );

    if( !m_Expression->PerformSema( sema ) )
        return false;

    // best to be explicit about these things
    scope.Leave();

    return true;
}

std::unique_ptr<StateAssignmentBase>
                    StateAssignmentStatement::GenerateStateAssignment(
                                                 CodeGenerator& code_gen,
                                                 const std::string& name ) const
{
    assert( m_State &&
            "Trying to generate a state assignment without a state" );

    Type t = m_State->GetType();

    assert( m_Expression->GetType().GetType() == t &&
            "Trying to create a state assignment with mismatched types" );

    // If this is just a constant return a ConstStateAssignment
    if( m_Expression->IsConst() )
    {
        GenericValue v = code_gen.EvaluateExpression( *m_Expression );
        switch( t )
        {
        case Type::BOOL:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_bool>(
                                 static_cast<const State<jl_bool>&>(*m_State),
                                 v.GetBool() ) );
        case Type::CHAR:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_char>(
                                 static_cast<const State<jl_char>&>(*m_State),
                                 v.GetChar() ) );
        case Type::SHORT:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_short>(
                                 static_cast<const State<jl_short>&>(*m_State),
                                 v.GetShort() ) );
        case Type::INT:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_int>(
                                 static_cast<const State<jl_int>&>(*m_State),
                                 v.GetInt() ) );
        case Type::LONG:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_long>(
                                 static_cast<const State<jl_long>&>(*m_State),
                                 v.GetLong() ) );
        case Type::UCHAR:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_uchar>(
                                 static_cast<const State<jl_uchar>&>(*m_State),
                                 v.GetUChar() ) );
        case Type::USHORT:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_ushort>(
                                 static_cast<const State<jl_ushort>&>(*m_State),
                                 v.GetUShort() ) );
        case Type::UINT:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_uint>(
                                 static_cast<const State<jl_uint>&>(*m_State),
                                 v.GetUInt() ) );
        case Type::UINT2:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_uint2>(
                                 static_cast<const State<jl_uint2>&>(*m_State),
                                 v.GetUInt2() ) );
        case Type::ULONG:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_ulong>(
                                 static_cast<const State<jl_ulong>&>(*m_State),
                                 v.GetULong() ) );
        case Type::FLOAT:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_float>(
                                 static_cast<const State<jl_float>&>(*m_State),
                                 v.GetFloat() ) );
        case Type::FLOAT2:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_float2>(
                                 static_cast<const State<jl_float2>&>(*m_State),
                                 v.GetFloat2() ) );
        case Type::FLOAT3:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_float3>(
                                 static_cast<const State<jl_float3>&>(*m_State),
                                 v.GetFloat3() ) );
        case Type::FLOAT4:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_float4>(
                                 static_cast<const State<jl_float4>&>(*m_State),
                                 v.GetFloat4() ) );
        case Type::DOUBLE:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<jl_double>(
                                 static_cast<const State<jl_double>&>(*m_State),
                                 v.GetDouble() ) );
        case Type::STRING:
            return std::unique_ptr<StateAssignmentBase>(
                          new ConstStateAssignment<std::string>(
                               static_cast<const State<std::string>&>(*m_State),
                               v.GetString() ) );
        default:
            assert( false &&
             "Trying to create a ConstStateAssignment with an unhandled type" );
            return nullptr;
        }
    }

    return code_gen.GenerateStateAssignment( *m_State,
                                             *m_Expression,
                                             name + "_" + m_Identifier );
}

bool StateAssignmentStatement::Parse(
                              Parser& parser,
                              std::unique_ptr<StateAssignmentStatement>& token )
{
    // Read the state identifier
    std::string identifier;
    if( !parser.ExpectTerminal( TerminalType::IDENTIFIER, identifier ) )
        return false;

    // The assignment operator
    if( !parser.ExpectTerminal( TerminalType::EQUALS ) )
        return false;

    // And the expression
    Expression_up expression;
    if( !parser.Expect< Expression >( expression ) )
        return false;

    // Closing semicolon
    if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
        return false;

    token.reset( new StateAssignmentStatement( std::move(identifier),
                                               std::move(expression) ) );
    return true;
}

bool StateAssignmentStatement::classof( const Token* t )
{
    return t->GetSubClassID() == TokenTy::StateAssignmentStatement;
}

bool StateAssignmentStatement::classof( const StateAssignmentStatement* t )
{
    return true;
}

} // namespace Compiler
} // namespace JoeLang
<commit_msg>[+] Types for const state assignments<commit_after>/*
    Copyright 2011 Joe Hermaszewski. All rights reserved.

    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:

    1. Redistributions of source code must retain the above copyright notice,
    this list of conditions and the following disclaimer.

    2. Redistributions in binary form must reproduce the above copyright notice,
    this list of conditions and the following disclaimer in the documentation
    and/or other materials provided with the distribution.

    THIS SOFTWARE IS PROVIDED BY JOE HERMASZEWSKI "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 JOE HERMASZEWSKI 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.

    The views and conclusions contained in the software and documentation are
    those of the authors and should not be interpreted as representing official
    policies, either expressed or implied, of Joe Hermaszewski.
*/

#include "state_assignment_statement.hpp"

#include <cassert>
#include <memory>
#include <string>
#include <utility>

#include <compiler/code_generator.hpp>
#include <compiler/generic_value.hpp>
#include <compiler/parser.hpp>
#include <compiler/sema_analyzer.hpp>
#include <compiler/terminal_types.hpp>
#include <compiler/tokens/expressions/expression.hpp>
#include <compiler/tokens/expressions/cast_expression.hpp>
#include <joelang/state.hpp>
#include <joelang/state_assignment.hpp>
#include <joelang/types.hpp>

namespace JoeLang
{
namespace Compiler
{

//------------------------------------------------------------------------------
// StateAssignmentStatement
//------------------------------------------------------------------------------
StateAssignmentStatement::StateAssignmentStatement(
                                    std::string identifier,
                                    Expression_up expression )
    :PassStatement( TokenTy::StateAssignmentStatement )
    ,m_Identifier( std::move(identifier) )
    ,m_Expression( std::move(expression) )
{
    assert( !m_Identifier.empty() &&
            "Trying to create a StateAssignmentStatement with an empty state "
            "name" );
    assert( m_Expression &&
            "Trying to create a StateAssignmentStatement with a null "
            "expression" );
}

StateAssignmentStatement::~StateAssignmentStatement()
{
}

bool StateAssignmentStatement::PerformSema( SemaAnalyzer& sema )
{
    // create a scope for the enumerants
    SemaAnalyzer::ScopeHolder scope( sema );
    scope.Enter();

    // Try and get the state to which we are assigning
    m_State = sema.GetState( m_Identifier );
    if( !m_State )
    {
        sema.Error( "Undeclared state: " + m_Identifier );
        return false;
    }
    sema.LoadStateEnumerants( *m_State );

    m_Expression = CastExpression::Create( m_State->GetType(),
                                           std::move(m_Expression),
                                           false );

    if( !m_Expression->PerformSema( sema ) )
        return false;

    // best to be explicit about these things
    scope.Leave();

    return true;
}

std::unique_ptr<StateAssignmentBase>
                    StateAssignmentStatement::GenerateStateAssignment(
                                                 CodeGenerator& code_gen,
                                                 const std::string& name ) const
{
    assert( m_State &&
            "Trying to generate a state assignment without a state" );

    Type t = m_State->GetType();

    assert( m_Expression->GetType().GetType() == t &&
            "Trying to create a state assignment with mismatched types" );

#define CREATE_CONST_STATE_ASSIGNMENT( type, Type ) \
    case JoeLangType<type>::value: \
        return std::unique_ptr<StateAssignmentBase>( \
                          new ConstStateAssignment<type>( \
                                    static_cast<const State<type>&>(*m_State), \
                                    v.Get##Type() ) );

#define CREATE_CONST_STATE_ASSIGNMENT_N( type, Type ) \
    CREATE_CONST_STATE_ASSIGNMENT( type, Type ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##2, Type##2 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##3, Type##3 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##4, Type##4 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##2x2, Type##2x2 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##2x3, Type##2x3 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##2x4, Type##2x4 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##3x2, Type##3x2 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##3x3, Type##3x3 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##3x4, Type##3x4 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##4x2, Type##4x2 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##4x3, Type##4x3 ) \
    CREATE_CONST_STATE_ASSIGNMENT( type##4x4, Type##4x4 )

    // If this is just a constant return a ConstStateAssignment
    if( m_Expression->IsConst() )
    {
        GenericValue v = code_gen.EvaluateExpression( *m_Expression );
        switch( t )
        {
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_bool, Bool )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_char, Char )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_short, Short )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_int, Int )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_long, Long )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_uchar, UChar )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_ushort, UShort )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_uint, UInt )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_ulong, ULong )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_float, Float )
        CREATE_CONST_STATE_ASSIGNMENT_N( jl_double, Double )
        CREATE_CONST_STATE_ASSIGNMENT( std::string, String )

        default:
            assert( false &&
             "Trying to create a ConstStateAssignment with an unhandled type" );
            return nullptr;
        }
    }

#undef CREATE_CONST_STATE_ASSIGNMENT_N
#undef CREATE_CONST_STATE_ASSIGNMENT

    return code_gen.GenerateStateAssignment( *m_State,
                                             *m_Expression,
                                             name + "_" + m_Identifier );
}

bool StateAssignmentStatement::Parse(
                              Parser& parser,
                              std::unique_ptr<StateAssignmentStatement>& token )
{
    // Read the state identifier
    std::string identifier;
    if( !parser.ExpectTerminal( TerminalType::IDENTIFIER, identifier ) )
        return false;

    // The assignment operator
    if( !parser.ExpectTerminal( TerminalType::EQUALS ) )
        return false;

    // And the expression
    Expression_up expression;
    if( !parser.Expect< Expression >( expression ) )
        return false;

    // Closing semicolon
    if( !parser.ExpectTerminal( TerminalType::SEMICOLON ) )
        return false;

    token.reset( new StateAssignmentStatement( std::move(identifier),
                                               std::move(expression) ) );
    return true;
}

bool StateAssignmentStatement::classof( const Token* t )
{
    return t->GetSubClassID() == TokenTy::StateAssignmentStatement;
}

bool StateAssignmentStatement::classof( const StateAssignmentStatement* t )
{
    return true;
}

} // namespace Compiler
} // namespace JoeLang
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qqmlplatform_p.h"

QT_BEGIN_NAMESPACE

/*
    This object and its properties are documented as part of the Qt object,
    in qqmlengine.cpp
*/

QQmlPlatform::QQmlPlatform(QObject *parent)
    : QObject(parent)
{
}

QQmlPlatform::~QQmlPlatform()
{
}

QString QQmlPlatform::os()
{
#if defined(Q_OS_ANDROID)
    return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
    return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
    return QLatin1String("ios");
#elif defined(Q_OS_MAC)
    return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
    return QLatin1String("wince");
#elif defined(Q_OS_WIN)
    return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
    return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
    return QLatin1String("unix");
#else
    return QLatin1String("unknown");
#endif
}

QT_END_NAMESPACE
<commit_msg>Return "winphone" and "winrt" for Qt.platform.os when appropriate<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qqmlplatform_p.h"

QT_BEGIN_NAMESPACE

/*
    This object and its properties are documented as part of the Qt object,
    in qqmlengine.cpp
*/

QQmlPlatform::QQmlPlatform(QObject *parent)
    : QObject(parent)
{
}

QQmlPlatform::~QQmlPlatform()
{
}

QString QQmlPlatform::os()
{
#if defined(Q_OS_ANDROID)
    return QLatin1String("android");
#elif defined(Q_OS_BLACKBERRY)
    return QLatin1String("blackberry");
#elif defined(Q_OS_IOS)
    return QLatin1String("ios");
#elif defined(Q_OS_MAC)
    return QLatin1String("osx");
#elif defined(Q_OS_WINCE)
    return QLatin1String("wince");
#elif defined(Q_OS_WINPHONE)
    return QStringLiteral("winphone");
#elif defined(Q_OS_WINRT)
    return QStringLiteral("winrt");
#elif defined(Q_OS_WIN)
    return QLatin1String("windows");
#elif defined(Q_OS_LINUX)
    return QLatin1String("linux");
#elif defined(Q_OS_UNIX)
    return QLatin1String("unix");
#else
    return QLatin1String("unknown");
#endif
}

QT_END_NAMESPACE
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/mcbist/gen_mss_mcbist_traits.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file gen_mss_mcbist_traits.H
/// @brief Run and manage the MCBIST engine
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#ifndef _GEN_MSS_MCBIST_TRAITS_H_
#define _GEN_MSS_MCBIST_TRAITS_H_

#include <fapi2.H>

#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/mcbist/gen_address.H>

namespace mss
{

///
/// @class mcbistMCTraits
/// @tparam MC the mc type
/// @brief A MC to MC_TARGET_TYPE mapping
///
template< mss::mc_type MC = DEFAULT_MC_TYPE >
class mcbistMCTraits;

///
/// @class mcbistTraits
/// @tparam MC the mc type of the T
/// @tparam T the fapi2::TargetType - derived
/// @brief a collection of traits associated with the MCBIST engine or hardware
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T = mss::mcbistMCTraits<MC>::MC_TARGET_TYPE>
class mcbistTraits;

}// mss
#endif
<commit_msg>Add snapshot of ocmb/explorer for master-p10 branch<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/generic/memory/lib/utils/mcbist/gen_mss_mcbist_traits.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2019                             */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* 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.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file gen_mss_mcbist_traits.H
/// @brief Run and manage the MCBIST engine
///
// *HWP HWP Owner: Andre Marin <aamarin@us.ibm.com>
// *HWP HWP Backup: Stephen Glancy <sglancy@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 3
// *HWP Consumed by: HB:FSP

#ifndef _GEN_MSS_MCBIST_TRAITS_H_
#define _GEN_MSS_MCBIST_TRAITS_H_

#include <fapi2.H>

#include <generic/memory/lib/utils/shared/mss_generic_consts.H>
#include <generic/memory/lib/utils/mcbist/gen_mss_mcbist_address.H>

namespace mss
{

///
/// @class mcbistMCTraits
/// @tparam MC the mc type
/// @brief A MC to MC_TARGET_TYPE mapping
///
template< mss::mc_type MC = DEFAULT_MC_TYPE >
class mcbistMCTraits;

///
/// @class mcbistTraits
/// @tparam MC the mc type of the T
/// @tparam T the fapi2::TargetType - derived
/// @brief a collection of traits associated with the MCBIST engine or hardware
///
template< mss::mc_type MC = DEFAULT_MC_TYPE, fapi2::TargetType T = mss::mcbistMCTraits<MC>::MC_TARGET_TYPE>
class mcbistTraits;

}// mss
#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <openssl/rand.h>
#include "Crypto.h"
#include "Identity.h"
#include "common/key.hpp"
#include <thread>
#include <unistd.h>
#include <vector>
#include <mutex>
static std::mutex thread_mutex;
static i2p::data::SigningKeyType type;
static i2p::data::PrivateKeys keys;
static bool finded=false;
static size_t padding_size;
static uint8_t * KeyBuf;
static uint8_t * PaddingBuf;
static unsigned long long hash;

#define CPU_ONLY

#ifdef CPU_ONLY
// XXX: make this faster
static inline bool NotThat(const char * a, const char *b){
while(*b)
 if(*a++!=*b++) return true;
return false;
}

inline void twist_cpu(uint8_t * buf,size_t * l0){
//TODO: NORMAL IMPLEMENTATION
	RAND_bytes(buf,padding_size);
}

// XXX: make this faster
static inline void mutate_keys_cpu(
	uint8_t * buf,
	uint8_t * padding,
	size_t * l0)
{
  twist_cpu(padding,l0);
  thread_mutex.lock();
  keys.RecalculateIdentHash(buf);
  thread_mutex.unlock();
}

void thread_find(const char * prefix){
  while(NotThat(keys.GetPublic()->GetIdentHash().ToBase32().c_str(),prefix) and !finded)
  {
    size_t l0 = 0;

    mutate_keys_cpu(KeyBuf,PaddingBuf, (size_t*)&l0);
    hash++;
  }
}
#endif
int main (int argc, char * argv[])
{
	if ( argc < 3 )
	{
		std::cout << "Usage: " << argv[0] << " filename generatestring <signature type>" << std::endl;
		return 0;
	}
	i2p::crypto::InitCrypto (false);
	type = i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519;
	if ( argc > 3 )
		type = NameToSigType(std::string(argv[3]));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			keys = i2p::data::PrivateKeys::CreateRandomKeys (type);
			switch(type){
			case i2p::data::SIGNING_KEY_TYPE_DSA_SHA1:
			case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048:
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072:
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096:
			case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512:
			case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512_TEST:
			std::cout << "Sorry, i don't can generate adress for this signature type" << std::endl;
			return 0;
			break;
			}
			switch(type){
			case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
			padding_size=64;
			break;
			case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
			padding_size=32;
			break;
			case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
			padding_size=4;
			break;
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048:
			padding_size=128;
			break;
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072:
			padding_size=256;
			break;
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096:
			padding_size=384;
			break;
			case i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
			padding_size=96;
			break;
			case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256:
			case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256_TEST:
			padding_size=64;
			break;
			}

  // TODO: multi threading
  KeyBuf = new uint8_t[keys.GetFullLen()];
  PaddingBuf = keys.GetPadding();
  unsigned int count_cpu = sysconf(_SC_NPROCESSORS_ONLN);
  std::vector<std::thread> threads(count_cpu);
  std::cout << "Start vanity generator in " << count_cpu << " threads" << std::endl;
  for ( unsigned int j = count_cpu;j--;){
   threads[j] = std::thread(thread_find,argv[2]);
    sched_param sch;
    int policy;
    pthread_getschedparam(threads[j].native_handle(), &policy, &sch);
    sch.sched_priority = 10;
    if (pthread_setschedparam(threads[j].native_handle(), SCHED_FIFO, &sch)) {
        std::cout << "Failed to setschedparam" << std::endl;
        return 1;
    }
  }
  for(unsigned int j = 0; j < count_cpu;j++)
   threads[j].join();

  std::cout << "Hashes: " << hash << std::endl;

	std::ofstream f (argv[1], std::ofstream::binary | std::ofstream::out);
	if (f)
	{
		size_t len = keys.GetFullLen ();
		len = keys.ToBuffer (KeyBuf, len);
		f.write ((char *)KeyBuf, len);
   		delete [] KeyBuf;
		std::cout << "Destination " << keys.GetPublic ()->GetIdentHash ().ToBase32 () << " created" << std::endl;
	}
	else
		std::cout << "Can't create file " << argv[1] << std::endl;

	i2p::crypto::TerminateCrypto ();

	return 0;
}
<commit_msg>notes<commit_after>#include <iostream>
#include <fstream>
#include <stdlib.h>
#include <openssl/rand.h>
#include "Crypto.h"
#include "Identity.h"
#include "common/key.hpp"
#include <thread>
#include <unistd.h>
#include <vector>
#include <mutex>
static std::mutex thread_mutex;
static i2p::data::SigningKeyType type;
static i2p::data::PrivateKeys keys;
static bool finded=false;
static size_t padding_size;
static uint8_t * KeyBuf;
static uint8_t * PaddingBuf;
static unsigned long long hash;

#define CPU_ONLY

#ifdef CPU_ONLY
static inline bool NotThat(const char * a, const char *b){
while(*b)
 if(*a++!=*b++) return true;
return false;
}

inline void twist_cpu(uint8_t * buf,size_t * l0){
//TODO: NORMAL IMPLEMENTATION,\
As in miner...

	RAND_bytes(buf,padding_size);
}

// XXX: make this faster
static inline void mutate_keys_cpu(
	uint8_t * buf,
	uint8_t * padding,
	size_t * l0)
{
  twist_cpu(padding,l0);
  thread_mutex.lock();
  keys.RecalculateIdentHash(buf);
  thread_mutex.unlock();
}

void thread_find(const char * prefix){
  while(NotThat(keys.GetPublic()->GetIdentHash().ToBase32().c_str(),prefix) and !finded)
  {
    size_t l0 = 0;

    mutate_keys_cpu(KeyBuf,PaddingBuf, (size_t*)&l0);
    hash++;
  }
}
#endif
int main (int argc, char * argv[])
{
	if ( argc < 3 )
	{
		std::cout << "Usage: " << argv[0] << " filename generatestring <signature type>" << std::endl;
		return 0;
	}
	i2p::crypto::InitCrypto (false);
	type = i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519;
	if ( argc > 3 )
		type = NameToSigType(std::string(argv[3]));
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			keys = i2p::data::PrivateKeys::CreateRandomKeys (type);
			switch(type){
			case i2p::data::SIGNING_KEY_TYPE_DSA_SHA1:
			case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048:
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072:
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096:
			case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512:
			case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_TC26_A_512_GOSTR3411_512_TEST:
			std::cout << "Sorry, i don't can generate adress for this signature type" << std::endl;
			return 0;
			break;
			}
			switch(type){
			case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA256_P256:
			padding_size=64;
			break;
			case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA384_P384:
			padding_size=32;
			break;
			case i2p::data::SIGNING_KEY_TYPE_ECDSA_SHA512_P521:
			padding_size=4;
			break;
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA256_2048:
			padding_size=128;
			break;
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA384_3072:
			padding_size=256;
			break;
			case i2p::data::SIGNING_KEY_TYPE_RSA_SHA512_4096:
			padding_size=384;
			break;
			case i2p::data::SIGNING_KEY_TYPE_EDDSA_SHA512_ED25519:
			padding_size=96;
			break;
			case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256:
			case i2p::data::SIGNING_KEY_TYPE_GOSTR3410_CRYPTO_PRO_A_GOSTR3411_256_TEST:
			padding_size=64;
			break;
			}

  // TODO: multi threading
/*
TODO:
 <orignal> Francezgy переделай пожалуйста треды
 <orignal> без всех это pthread
 * orignal has quit (Quit: Leaving)
*/
  KeyBuf = new uint8_t[keys.GetFullLen()];
  PaddingBuf = keys.GetPadding();
  unsigned int count_cpu = sysconf(_SC_NPROCESSORS_ONLN);
  std::vector<std::thread> threads(count_cpu);
  std::cout << "Start vanity generator in " << count_cpu << " threads" << std::endl;
  for ( unsigned int j = count_cpu;j--;){
   threads[j] = std::thread(thread_find,argv[2]);
    sched_param sch;
    int policy;
    pthread_getschedparam(threads[j].native_handle(), &policy, &sch);
    sch.sched_priority = 10;
    if (pthread_setschedparam(threads[j].native_handle(), SCHED_FIFO, &sch)) {
        std::cout << "Failed to setschedparam" << std::endl;
        return 1;
    }
  }
  for(unsigned int j = 0; j < count_cpu;j++)
   threads[j].join();

  std::cout << "Hashes: " << hash << std::endl;

	std::ofstream f (argv[1], std::ofstream::binary | std::ofstream::out);
	if (f)
	{
		size_t len = keys.GetFullLen ();
		len = keys.ToBuffer (KeyBuf, len);
		f.write ((char *)KeyBuf, len);
   		delete [] KeyBuf;
		std::cout << "Destination " << keys.GetPublic ()->GetIdentHash ().ToBase32 () << " created" << std::endl;
	}
	else
		std::cout << "Can't create file " << argv[1] << std::endl;

	i2p::crypto::TerminateCrypto ();

	return 0;
}
<|endoftext|>


<commit_before><commit_msg>Delay deletion of view in View::DoRemoveChildView<commit_after><|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2009 Sacha Schutz <istdasklar@free.fr>
 * Copyright (C) 2009-2011 Guillaume Martres <smarter@ubuntu.com>
 * Copyright (C) 2011 Laszlo Papp <lpapp@kde.org>
 *
 * 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 "sound.h"

#include "engine.h"

#include <core/debughelper.h>

#include <alure.h>

using namespace GluonAudio;

class Sound::SoundPrivate
{
    public:
        SoundPrivate()
            : isValid(false)
            , isStreamed(false)
            , isLooping(false)
            , status(STOPPED)
            , stream(0)
            , source(0)
            , position(QVector3D( 0, 0, 0 ))
            , volume(1.0f)
            , pitch(1.0f)
            , radius(10000.0f)
            , duration(0)
        {
        }

        ~SoundPrivate()
        {
        }

        bool newError( const QString& str )
        {
            QLatin1String error = QLatin1String( alureGetErrorString() );
            if( error != QLatin1String( "No error" ) )
            {
                DEBUG_BLOCK
                DEBUG_TEXT2( "Alure error: %1", error )
                DEBUG_TEXT2( "%1", str )
                isValid = false;
                return true;
            }
            return false;
        }

        bool setupSource()
        {
            if( path.isEmpty() )
            {
                return false;
            }

            alGenSources( 1, &source );
            if( source == 0 )
            {
                DEBUG_BLOCK
                DEBUG_TEXT2( "Empty source, OpenAL error: %1", alGetError() )
                return false;
            }

            ALfloat sourcePosition[] = { position.x(), position.y() , position.z() };
            alSourcefv( source, AL_POSITION, sourcePosition );
            alSourcef( source, AL_GAIN, volume );
            alSourcef( source, AL_PITCH, pitch );
            alSourcef( source, AL_REFERENCE_DISTANCE, radius );

            return true;
        }

        void _k_deleteSource()
        {
            if( source != 0 )
            {
                alureStopSource( source, false );
                alDeleteSources( 1, &source );
                source = 0;
            }
            isValid = false;
            status = STOPPED;
            if( isStreamed )
            {
                alureDestroyStream( stream, 0, 0 );
            }
            stream = 0;
        }

        QString path;

        bool isValid;
        bool isStreamed;
        bool isLooping;
        Status status;
        alureStream* stream;
        ALuint source;
        QVector3D position;
        ALfloat volume;
        ALfloat pitch;
        ALfloat radius;
        double duration;
};

Sound::Sound(QObject *parent)
    : QObject( parent )
    , d( new SoundPrivate )
{
    d->isValid = false;
}

Sound::Sound( const QString& fileName )
    : QObject( Engine::instance() )
    , d( new SoundPrivate )
{
    load( fileName );
}

Sound::~Sound()
{
    d->_k_deleteSource();
    delete d;
}

bool Sound::isValid() const
{
    return d->isValid;
}

bool Sound::load( const QString& fileName )
{
    if( fileName.isEmpty() )
    {
        d->isValid = false;
        return false;
    }

    if( !d->path.isEmpty() )
    {
        d->_k_deleteSource();
    }
    d->path = fileName;

    if( !d->setupSource() )
        return false;

    alureStreamSizeIsMicroSec(true);
    alureStream *stream = alureCreateStreamFromFile(fileName.toLocal8Bit().data(), Engine::instance()->bufferLength(), 0, NULL);
    if( stream )
        d->duration = (double)alureGetStreamLength(stream) / alureGetStreamFrequency(stream);

    d->isStreamed = (d->duration >= Engine::instance()->bufferLength()*Engine::instance()->buffersPerStream() / 1e6);
    if( d->isStreamed )
        d->stream = stream;
    else
    {
        alureDestroyStream(stream, 0, NULL);
        stream = NULL;

        ALuint buffer = Engine::instance()->genBuffer( d->path );
        if( d->newError( "Loading " + d->path + " failed" ) )
        {
            d->isValid = false;
            return false;
        }
        alSourcei( d->source, AL_BUFFER, buffer );
    }

    d->isValid = !d->newError( "Loading " + d->path + " failed" );

    return d->isValid;
}

ALfloat Sound::elapsedTime() const
{
    ALfloat seconds = 0.f;
    alGetSourcef( d->source, AL_SEC_OFFSET, &seconds );
    return seconds;
}

ALint Sound::status() const
{
    ALint status;
    alGetSourcei( d->source, AL_SOURCE_STATE, &status );
    return status;
}

bool Sound::isLooping() const
{
    return d->isLooping;
}

bool Sound::isPlaying() const
{
    return d->status == PLAYING;
}

bool Sound::isPaused() const
{
    return d->status == PAUSED;
}

bool Sound::isStopped() const
{
    return d->status == STOPPED;
}

void Sound::setLoop( bool enabled )
{
    d->isLooping = enabled;
    if( !d->isStreamed )
    {
        alSourcei( d->source, AL_LOOPING, enabled );
    }
}

void Sound::clear()
{
    d->_k_deleteSource();
}

QVector3D Sound::position() const
{
    return d->position;
}

ALfloat Sound::x() const
{
    return d->position.x();
}

ALfloat Sound::y() const
{
    return d->position.y();
}

ALfloat Sound::z() const
{
    return d->position.z();
}

ALfloat Sound::volume() const
{
    return d->volume;
}

ALfloat Sound::pitch() const
{
    return d->pitch;
}

ALfloat Sound::radius() const
{
    return d->radius;
}

double Sound::duration() const
{
    if( !d->isValid )
    {
        return 0;
    }
    return d->duration;
}

void Sound::setPosition( ALfloat x, ALfloat y, ALfloat z )
{
    setPosition( QVector3D( x, y, z ) );
}

void Sound::setPosition( QVector3D position )
{
    d->position = position;
    ALfloat sourcePosition[] = { position.x(), position.y() , position.z() };
    alSourcefv( d->source, AL_POSITION, sourcePosition );
}

void Sound::setVolume( ALfloat volume )
{
    d->volume = volume;
    alSourcef( d->source, AL_GAIN, volume );
}

void Sound::setPitch( ALfloat pitch )
{
    d->pitch = pitch;
    alSourcef( d->source, AL_PITCH, pitch );
}

void Sound::setRadius( ALfloat radius )
{
    d->radius = radius;
    alSourcef( d->source, AL_REFERENCE_DISTANCE, radius );
}

void Sound::callbackStopped( void* object, ALuint source )
{
    static_cast<GluonAudio::Sound*>( object )->cbStop();
}

void Sound::cbStop()
{
    d->status = STOPPED;
    if( d->isLooping )
    {
        play();
    }
    else
    {
        emit stopped();
    }
}

void Sound::play()
{
    if( isPaused() )
    {
        alureResumeSource( d->source );
    }
    else if( isPlaying() )
    {
        stop();
    }

    if( d->isStreamed )
    {
        int loopCount = ( d->isLooping ? -1 : 0 );
        alurePlaySourceStream( d->source, d->stream, Engine::instance()->buffersPerStream(), loopCount, Sound::callbackStopped, this );
    }
    else
    {
        alurePlaySource( d->source, callbackStopped, this );
    }
    d->status = PLAYING;
    d->newError( "Playing " + d->path + " failed" );
    emit played();
}

void Sound::pause()
{
    alurePauseSource( d->source );
    d->status = PAUSED;
    d->newError( "Pausing " + d->path + " failed" );
    emit paused();
}

void Sound::stop()
{
    alureStopSource( d->source, false );
    d->status = STOPPED;
    d->newError( "Stopping " + d->path + " failed" );
}

void Sound::rewind()
{
    if( d->isStreamed )
    {
        alureRewindStream( d->stream );
    }
    else
    {
        alSourceRewind( d->source );
    }
    d->newError( "Rewinding " + d->path + " failed" );
}

void Sound::setMinVolume( ALfloat min )
{
    alSourcef( d->source, AL_MIN_GAIN, min );
}

void Sound::setMaxVolume( ALfloat max )
{
    alSourcef( d->source, AL_MAX_GAIN, max );
}

void Sound::setVelocity( ALfloat vx, ALfloat vy, ALfloat vz )
{
    ALfloat velocity[] = { vx, vy, vz };
    alSourcefv( d->source, AL_VELOCITY, velocity );
}

void Sound::setDirection( ALfloat dx, ALfloat dy, ALfloat dz )
{
    ALfloat direction[] = { dx, dy, dz };
    alSourcefv( d->source, AL_POSITION, direction );
}

void Sound::setTimePosition( ALfloat time )
{
    alSourcef( d->source, AL_SEC_OFFSET, time );

}

#include "sound.moc"
<commit_msg>Do not stop playing when Sound::play is called while already playing.<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (C) 2009 Sacha Schutz <istdasklar@free.fr>
 * Copyright (C) 2009-2011 Guillaume Martres <smarter@ubuntu.com>
 * Copyright (C) 2011 Laszlo Papp <lpapp@kde.org>
 *
 * 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 "sound.h"

#include "engine.h"

#include <core/debughelper.h>

#include <alure.h>

using namespace GluonAudio;

class Sound::SoundPrivate
{
    public:
        SoundPrivate()
            : isValid(false)
            , isStreamed(false)
            , isLooping(false)
            , status(STOPPED)
            , stream(0)
            , source(0)
            , position(QVector3D( 0, 0, 0 ))
            , volume(1.0f)
            , pitch(1.0f)
            , radius(10000.0f)
            , duration(0)
        {
        }

        ~SoundPrivate()
        {
        }

        bool newError( const QString& str )
        {
            QLatin1String error = QLatin1String( alureGetErrorString() );
            if( error != QLatin1String( "No error" ) )
            {
                DEBUG_BLOCK
                DEBUG_TEXT2( "Alure error: %1", error )
                DEBUG_TEXT2( "%1", str )
                isValid = false;
                return true;
            }
            return false;
        }

        bool setupSource()
        {
            if( path.isEmpty() )
            {
                return false;
            }

            alGenSources( 1, &source );
            if( source == 0 )
            {
                DEBUG_BLOCK
                DEBUG_TEXT2( "Empty source, OpenAL error: %1", alGetError() )
                return false;
            }

            ALfloat sourcePosition[] = { position.x(), position.y() , position.z() };
            alSourcefv( source, AL_POSITION, sourcePosition );
            alSourcef( source, AL_GAIN, volume );
            alSourcef( source, AL_PITCH, pitch );
            alSourcef( source, AL_REFERENCE_DISTANCE, radius );

            return true;
        }

        void _k_deleteSource()
        {
            if( source != 0 )
            {
                alureStopSource( source, false );
                alDeleteSources( 1, &source );
                source = 0;
            }
            isValid = false;
            status = STOPPED;
            if( isStreamed )
            {
                alureDestroyStream( stream, 0, 0 );
            }
            stream = 0;
        }

        QString path;

        bool isValid;
        bool isStreamed;
        bool isLooping;
        Status status;
        alureStream* stream;
        ALuint source;
        QVector3D position;
        ALfloat volume;
        ALfloat pitch;
        ALfloat radius;
        double duration;
};

Sound::Sound(QObject *parent)
    : QObject( parent )
    , d( new SoundPrivate )
{
    d->isValid = false;
}

Sound::Sound( const QString& fileName )
    : QObject( Engine::instance() )
    , d( new SoundPrivate )
{
    load( fileName );
}

Sound::~Sound()
{
    d->_k_deleteSource();
    delete d;
}

bool Sound::isValid() const
{
    return d->isValid;
}

bool Sound::load( const QString& fileName )
{
    if( fileName.isEmpty() )
    {
        d->isValid = false;
        return false;
    }

    if( !d->path.isEmpty() )
    {
        d->_k_deleteSource();
    }
    d->path = fileName;

    if( !d->setupSource() )
        return false;

    alureStreamSizeIsMicroSec(true);
    alureStream *stream = alureCreateStreamFromFile(fileName.toLocal8Bit().data(), Engine::instance()->bufferLength(), 0, NULL);
    if( stream )
        d->duration = (double)alureGetStreamLength(stream) / alureGetStreamFrequency(stream);

    d->isStreamed = (d->duration >= Engine::instance()->bufferLength()*Engine::instance()->buffersPerStream() / 1e6);
    if( d->isStreamed )
        d->stream = stream;
    else
    {
        alureDestroyStream(stream, 0, NULL);
        stream = NULL;

        ALuint buffer = Engine::instance()->genBuffer( d->path );
        if( d->newError( "Loading " + d->path + " failed" ) )
        {
            d->isValid = false;
            return false;
        }
        alSourcei( d->source, AL_BUFFER, buffer );
    }

    d->isValid = !d->newError( "Loading " + d->path + " failed" );

    return d->isValid;
}

ALfloat Sound::elapsedTime() const
{
    ALfloat seconds = 0.f;
    alGetSourcef( d->source, AL_SEC_OFFSET, &seconds );
    return seconds;
}

ALint Sound::status() const
{
    ALint status;
    alGetSourcei( d->source, AL_SOURCE_STATE, &status );
    return status;
}

bool Sound::isLooping() const
{
    return d->isLooping;
}

bool Sound::isPlaying() const
{
    return d->status == PLAYING;
}

bool Sound::isPaused() const
{
    return d->status == PAUSED;
}

bool Sound::isStopped() const
{
    return d->status == STOPPED;
}

void Sound::setLoop( bool enabled )
{
    d->isLooping = enabled;
    if( !d->isStreamed )
    {
        alSourcei( d->source, AL_LOOPING, enabled );
    }
}

void Sound::clear()
{
    d->_k_deleteSource();
}

QVector3D Sound::position() const
{
    return d->position;
}

ALfloat Sound::x() const
{
    return d->position.x();
}

ALfloat Sound::y() const
{
    return d->position.y();
}

ALfloat Sound::z() const
{
    return d->position.z();
}

ALfloat Sound::volume() const
{
    return d->volume;
}

ALfloat Sound::pitch() const
{
    return d->pitch;
}

ALfloat Sound::radius() const
{
    return d->radius;
}

double Sound::duration() const
{
    if( !d->isValid )
    {
        return 0;
    }
    return d->duration;
}

void Sound::setPosition( ALfloat x, ALfloat y, ALfloat z )
{
    setPosition( QVector3D( x, y, z ) );
}

void Sound::setPosition( QVector3D position )
{
    d->position = position;
    ALfloat sourcePosition[] = { position.x(), position.y() , position.z() };
    alSourcefv( d->source, AL_POSITION, sourcePosition );
}

void Sound::setVolume( ALfloat volume )
{
    d->volume = volume;
    alSourcef( d->source, AL_GAIN, volume );
}

void Sound::setPitch( ALfloat pitch )
{
    d->pitch = pitch;
    alSourcef( d->source, AL_PITCH, pitch );
}

void Sound::setRadius( ALfloat radius )
{
    d->radius = radius;
    alSourcef( d->source, AL_REFERENCE_DISTANCE, radius );
}

void Sound::callbackStopped( void* object, ALuint source )
{
    static_cast<GluonAudio::Sound*>( object )->cbStop();
}

void Sound::cbStop()
{
    d->status = STOPPED;
    if( d->isLooping )
    {
        play();
    }
    else
    {
        emit stopped();
    }
}

void Sound::play()
{
    if( isPaused() )
    {
        alureResumeSource( d->source );
    }
    else if( isPlaying() )
    {
        return;
    }

    if( d->isStreamed )
    {
        int loopCount = ( d->isLooping ? -1 : 0 );
        alurePlaySourceStream( d->source, d->stream, Engine::instance()->buffersPerStream(), loopCount, Sound::callbackStopped, this );
    }
    else
    {
        alurePlaySource( d->source, callbackStopped, this );
    }
    d->status = PLAYING;
    d->newError( "Playing " + d->path + " failed" );
    emit played();
}

void Sound::pause()
{
    alurePauseSource( d->source );
    d->status = PAUSED;
    d->newError( "Pausing " + d->path + " failed" );
    emit paused();
}

void Sound::stop()
{
    alureStopSource( d->source, false );
    d->status = STOPPED;
    d->newError( "Stopping " + d->path + " failed" );
}

void Sound::rewind()
{
    if( d->isStreamed )
    {
        alureRewindStream( d->stream );
    }
    else
    {
        alSourceRewind( d->source );
    }
    d->newError( "Rewinding " + d->path + " failed" );
}

void Sound::setMinVolume( ALfloat min )
{
    alSourcef( d->source, AL_MIN_GAIN, min );
}

void Sound::setMaxVolume( ALfloat max )
{
    alSourcef( d->source, AL_MAX_GAIN, max );
}

void Sound::setVelocity( ALfloat vx, ALfloat vy, ALfloat vz )
{
    ALfloat velocity[] = { vx, vy, vz };
    alSourcefv( d->source, AL_VELOCITY, velocity );
}

void Sound::setDirection( ALfloat dx, ALfloat dy, ALfloat dz )
{
    ALfloat direction[] = { dx, dy, dz };
    alSourcefv( d->source, AL_POSITION, direction );
}

void Sound::setTimePosition( ALfloat time )
{
    alSourcef( d->source, AL_SEC_OFFSET, time );

}

#include "sound.moc"
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "common/errdbg/exceptions.h"
#include "ugnames.h"

/* {% globals */

static UGlobalNamesRegistryItem *registry = NULL;
static UGlobalNamesRegistrySearchProc searchProc = NULL;

/* }% */

#ifdef _WIN32
#define IPC_PRIVATE 0
#ifndef snprintf
#define snprintf _snprintf
#endif
#else
#include <sys/types.h>
#include <sys/ipc.h>
#endif

void
UReleaseGlobalNamesRegistry()
{
	registry = NULL;
	searchProc = NULL;
}

static
const UGlobalNamesRegistryItem *
SearchGlobalNamesRegistry(const UGlobalNamesRegistryItem *registry,
						  const char *basename)
{
	assert(registry);
	while (registry->basename && 0!=strcmp(registry->basename,basename)) ++registry;
	return registry->basename ? registry : NULL;
}

static void ThrowSystemException(const char *msg)
{
	throw SYSTEM_EXCEPTION(msg);
}

static int ValidateBaseName(const char *baseName)
{
	/* TODO: implement validation */
	return 1;
}

static int ValidateGlobalName(const char *globalName)
{
	/* TODO: implement validation */
	return 1;
}

static int ValidateCompoundName(const char *compoundName)
{
	/* TODO: implement validation */
	return 1;
}

void
UInitGlobalNamesRegistry(UGlobalNamesRegistryItem *registryParam,
						 UGlobalNamesRegistrySearchProc searchProcParam,
						 int rangeBegin,
						 int rangeEnd)
{
	int rangeSizeMin = 0;
	UGlobalNamesRegistryItem *i = NULL;
	char errorBuf[128];

	assert(registryParam);
	/* first let's estimate the required range size */
	for (i = registryParam; i->basename; ++i)
	{
		if (!ValidateBaseName(i->basename) || i->nObjectsMax<1 || (i->prefix==NULL && i->nObjectsMax > 1))
		{
			snprintf(errorBuf, sizeof errorBuf,
				"UInitGlobalNamesRegistry: bad item '%s'", i->basename);
			errorBuf[(sizeof errorBuf)-1]=0;
			ThrowSystemException(errorBuf);
		}
		rangeSizeMin+=i->nObjectsMax;
	}
	registry = registryParam;
	/* check if the passed range is ok */
	if (rangeEnd - rangeBegin < rangeSizeMin)
		ThrowSystemException("InitGlobalNamesRegistry: range too small");
	/* now initialize per-entry ranges */
	for (i = registry; i->basename; ++i)
	{
		i->rangeBegin = rangeBegin;
		rangeBegin = i->rangeEnd = rangeBegin + i->nObjectsMax;
	}
	/* complete initialization */
	searchProc = (searchProcParam ? searchProcParam : SearchGlobalNamesRegistry);
}

const char *
UCreateGlobalName(const char *basename,
				  int objectId,
				  char *buf,
				  size_t bufSize)
{
	char prefix[32] = "", errorBuf[128];
	int ordinal = 0;
	const UGlobalNamesRegistryItem *item = NULL;
	int stored = 0;

	assert (basename);
	item = searchProc(registry, basename);
	if (!item)
	{
		snprintf(errorBuf, sizeof errorBuf, "CreateGlobalName: '%s' not found", basename);
		errorBuf[(sizeof errorBuf)-1]=0;
		ThrowSystemException(errorBuf);
	}
	ordinal = item->rangeBegin + objectId;
	if (item->prefix)
	{
		stored = snprintf(prefix, sizeof prefix, "%s%d.", item->prefix, objectId);
		if (stored<0 || (size_t)stored>=(sizeof prefix))
			ThrowSystemException("UCreateGlobalName: prefix too long");
	}
	if (ordinal >= item->rangeEnd || ordinal < item->rangeBegin)
		ThrowSystemException("CreateGlobalName: generated ordinal out of range");

	stored = snprintf(buf, bufSize, "Global\\SEDNA%d.%s%s@%d", registry->rangeBegin, prefix, basename, ordinal);
	if (stored<0 || (size_t)stored>=bufSize)
		ThrowSystemException("CreateGlobalName: buffer too small");

	return buf;
}

struct GlobalNameComponents
{
	const char *strNameBegin, *strNameEnd;
	int base, ordinal;
};

static
void ParseGlobalName(GlobalNameComponents *components,
					 const char *globalName)
{
	assert(components);
	if (globalName==NULL)
	{
		components->strNameBegin = NULL;
		components->strNameEnd = NULL;
		components->base = 0;
		components->ordinal = 0;
	}
	else
	{
		const char *sep = NULL;
		char *tail = NULL;
		int ordinal = 0, base = 0;

		sep = strchr(globalName,'@');
		if (sep==NULL || (ordinal=strtol(sep+1,&tail,10), *tail!='\0'))
		{
			ThrowSystemException("ParseGlobalName: bad global name syntax");
		}
		components->strNameBegin = globalName;
		components->strNameEnd = sep;
		components->base = base;
		components->ordinal = ordinal;
	}
}

static
const char *StrNameFromGlobalName(const char *globalName,
								  size_t limit,
								  const char *prefix,
								  char *buf,
								  size_t bufSize)
{
	char bufjr[16];
	int partSz = 0, stored = 0;
	GlobalNameComponents components = {NULL};

	assert(prefix);
	ParseGlobalName(&components,globalName);
	if (globalName == NULL)
	{
		buf = NULL;
	}
	else
	{
		partSz = (int)(components.strNameEnd - components.strNameBegin);
		stored = snprintf(buf, bufSize, "%s%.*s", prefix, partSz, components.strNameBegin);
		if (stored<0 || (size_t)stored>=bufSize)
			ThrowSystemException("StrNameFromGlobalName: buffer too small");
		if (limit>0 && (size_t)stored>limit)
		{
			stored = snprintf(bufjr, sizeof bufjr, "~%d", components.ordinal);
			if (stored<0 || (size_t)stored>=sizeof bufjr) ThrowSystemException("StrNameFromGlobalName: internal error");
			if ((size_t)stored>limit) ThrowSystemException("StrNameFromGlobalName: impossible limit");
			strcpy(buf+limit-stored, bufjr);
		}
	}
	return buf;
}

const char *UWinIPCNameFromGlobalName(const char *globalName,
									  char *buf,
									  size_t bufSize)
{
	return StrNameFromGlobalName(globalName, 0, "", buf, bufSize);
}

const char *UPosixIPCNameFromGlobalName(const char *globalName,
										char *buf,
										size_t bufSize)
{
	const char *prefix = "/";
	size_t limit = 0;

#if (defined(FreeBSD) || defined(DARWIN))
	prefix = "/tmp/";
#endif

#if defined(DARWIN)
    limit = 30;
#endif

	return StrNameFromGlobalName(globalName, limit, prefix, buf, bufSize);
}

int USys5IPCKeyFromGlobalName(const char *globalName)
{
	int key = 0;
	GlobalNameComponents components = {NULL};

	ParseGlobalName(&components,globalName);
	if (globalName == NULL)
	{
		key = IPC_PRIVATE;
	}
	else
	{
		key = components.ordinal;
		if (key==IPC_PRIVATE)
			ThrowSystemException("USys5IPCKeyFromGlobalName: bad key");
	}
	return key;
}

const char *
UCreateCompoundName(const char **namesVec,
					size_t namesCount,
					char *buf,
					size_t bufSize)
{
	size_t nameLen = 0;
	const char **nameCur = namesVec, **namesEnd = namesVec+namesCount;
	char *bufpos = buf;
	assert(buf && bufSize>0);
	strcpy(bufpos,"");
	while(nameCur != namesEnd)
	{
		if (nameCur!=namesVec)
		{
			/* checked there is enough room in buf on previous iteration */
			strcpy(bufpos,",");
			++bufpos; bufSize-=1;
		}
		if (!ValidateGlobalName(*nameCur))
			ThrowSystemException("UCreateCompoundName: bad global name syntax");
		nameLen = (*nameCur?strlen(*nameCur):0);
		if (bufSize < nameLen + 2)
			ThrowSystemException("UCreateCompoundName: buffer too small");
		if (*nameCur)
		{
			strcpy(bufpos, *nameCur);
			bufpos+=nameLen;
			bufSize-=nameLen;
		}
		++nameCur;
	}
	return buf;
}

const char *
UGlobalNameFromCompoundName(const char *compoundName,
							int index,
							char *buf,
							size_t bufSize)
{
	const char *pos = NULL, *epos=NULL;
	assert(buf && compoundName);
	if (!ValidateCompoundName(compoundName))
	{
		ThrowSystemException("UGlobalNameFromCompoundName: bad compound name syntax");
	}
	else
	{
		pos = compoundName;
		while(index > 0 && pos)
		{
			pos = strchr(pos,',');
			if (pos) pos+=1;
			--index;
		}
		if (!pos || index<0)
		{
			ThrowSystemException("UGlobalNameFromCompoundName: index out of range");
		}
		epos = strchr(pos,',');
		if (!epos) epos=pos+strlen(pos);
		if (bufSize < (unsigned int) (epos-pos+1))
		{
			ThrowSystemException("UGlobalNameFromCompoundName: buffer too small");
		}
		if (pos == epos)
		{
			buf = NULL;
		}
		else
		{
			memcpy(buf,pos,epos-pos);
			buf[epos-pos]=0;
		}
	}
	return buf;
}
<commit_msg>revert unintended patch from the previous commit<commit_after>#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <assert.h>
#include "common/errdbg/exceptions.h"
#include "ugnames.h"

/* {% globals */

static UGlobalNamesRegistryItem *registry = NULL;
static UGlobalNamesRegistrySearchProc searchProc = NULL;

/* }% */

#ifdef _WIN32
#define IPC_PRIVATE 0
#ifndef snprintf
#define snprintf _snprintf
#endif
#else
#include <sys/types.h>
#include <sys/ipc.h>
#endif

void
UReleaseGlobalNamesRegistry()
{
	registry = NULL;
	searchProc = NULL;
}

static
const UGlobalNamesRegistryItem *
SearchGlobalNamesRegistry(const UGlobalNamesRegistryItem *registry,
						  const char *basename)
{
	assert(registry);
	while (registry->basename && 0!=strcmp(registry->basename,basename)) ++registry;
	return registry->basename ? registry : NULL;
}

static void ThrowSystemException(const char *msg)
{
	throw SYSTEM_EXCEPTION(msg);
}

static int ValidateBaseName(const char *baseName)
{
	/* TODO: implement validation */
	return 1;
}

static int ValidateGlobalName(const char *globalName)
{
	/* TODO: implement validation */
	return 1;
}

static int ValidateCompoundName(const char *compoundName)
{
	/* TODO: implement validation */
	return 1;
}

void
UInitGlobalNamesRegistry(UGlobalNamesRegistryItem *registryParam,
						 UGlobalNamesRegistrySearchProc searchProcParam,
						 int rangeBegin,
						 int rangeEnd)
{
	int rangeSizeMin = 0;
	UGlobalNamesRegistryItem *i = NULL;
	char errorBuf[128];

	assert(registryParam);
	/* first let's estimate the required range size */
	for (i = registryParam; i->basename; ++i)
	{
		if (!ValidateBaseName(i->basename) || i->nObjectsMax<1 || (i->prefix==NULL && i->nObjectsMax > 1))
		{
			snprintf(errorBuf, sizeof errorBuf,
				"UInitGlobalNamesRegistry: bad item '%s'", i->basename);
			errorBuf[(sizeof errorBuf)-1]=0;
			ThrowSystemException(errorBuf);
		}
		rangeSizeMin+=i->nObjectsMax;
	}
	registry = registryParam;
	/* check if the passed range is ok */
	if (rangeEnd - rangeBegin < rangeSizeMin)
		ThrowSystemException("InitGlobalNamesRegistry: range too small");
	/* now initialize per-entry ranges */
	for (i = registry; i->basename; ++i)
	{
		i->rangeBegin = rangeBegin;
		rangeBegin = i->rangeEnd = rangeBegin + i->nObjectsMax;
	}
	/* complete initialization */
	searchProc = (searchProcParam ? searchProcParam : SearchGlobalNamesRegistry);
}

const char *
UCreateGlobalName(const char *basename,
				  int objectId,
				  char *buf,
				  size_t bufSize)
{
	char prefix[32] = "", errorBuf[128];
	int ordinal = 0;
	const UGlobalNamesRegistryItem *item = NULL;
	int stored = 0;

	assert (basename);
	item = searchProc(registry, basename);
	if (!item)
	{
		snprintf(errorBuf, sizeof errorBuf, "CreateGlobalName: '%s' not found", basename);
		errorBuf[(sizeof errorBuf)-1]=0;
		ThrowSystemException(errorBuf);
	}
	ordinal = item->rangeBegin + objectId;
	if (item->prefix)
	{
		stored = snprintf(prefix, sizeof prefix, "%s%d.", item->prefix, objectId);
		if (stored<0 || (size_t)stored>=(sizeof prefix))
			ThrowSystemException("UCreateGlobalName: prefix too long");
	}
	if (ordinal >= item->rangeEnd || ordinal < item->rangeBegin)
		ThrowSystemException("CreateGlobalName: generated ordinal out of range");

	stored = snprintf(buf, bufSize, "SEDNA%d.%s%s@%d", registry->rangeBegin, prefix, basename, ordinal);
	if (stored<0 || (size_t)stored>=bufSize)
		ThrowSystemException("CreateGlobalName: buffer too small");

	return buf;
}

struct GlobalNameComponents
{
	const char *strNameBegin, *strNameEnd;
	int base, ordinal;
};

static
void ParseGlobalName(GlobalNameComponents *components,
					 const char *globalName)
{
	assert(components);
	if (globalName==NULL)
	{
		components->strNameBegin = NULL;
		components->strNameEnd = NULL;
		components->base = 0;
		components->ordinal = 0;
	}
	else
	{
		const char *sep = NULL;
		char *tail = NULL;
		int ordinal = 0, base = 0;

		sep = strchr(globalName,'@');
		if (sep==NULL || (ordinal=strtol(sep+1,&tail,10), *tail!='\0'))
		{
			ThrowSystemException("ParseGlobalName: bad global name syntax");
		}
		components->strNameBegin = globalName;
		components->strNameEnd = sep;
		components->base = base;
		components->ordinal = ordinal;
	}
}

static
const char *StrNameFromGlobalName(const char *globalName,
								  size_t limit,
								  const char *prefix,
								  char *buf,
								  size_t bufSize)
{
	char bufjr[16];
	int partSz = 0, stored = 0;
	GlobalNameComponents components = {NULL};

	assert(prefix);
	ParseGlobalName(&components,globalName);
	if (globalName == NULL)
	{
		buf = NULL;
	}
	else
	{
		partSz = (int)(components.strNameEnd - components.strNameBegin);
		stored = snprintf(buf, bufSize, "%s%.*s", prefix, partSz, components.strNameBegin);
		if (stored<0 || (size_t)stored>=bufSize)
			ThrowSystemException("StrNameFromGlobalName: buffer too small");
		if (limit>0 && (size_t)stored>limit)
		{
			stored = snprintf(bufjr, sizeof bufjr, "~%d", components.ordinal);
			if (stored<0 || (size_t)stored>=sizeof bufjr) ThrowSystemException("StrNameFromGlobalName: internal error");
			if ((size_t)stored>limit) ThrowSystemException("StrNameFromGlobalName: impossible limit");
			strcpy(buf+limit-stored, bufjr);
		}
	}
	return buf;
}

const char *UWinIPCNameFromGlobalName(const char *globalName,
									  char *buf,
									  size_t bufSize)
{
	return StrNameFromGlobalName(globalName, 0, "", buf, bufSize);
}

const char *UPosixIPCNameFromGlobalName(const char *globalName,
										char *buf,
										size_t bufSize)
{
	const char *prefix = "/";
	size_t limit = 0;

#if (defined(FreeBSD) || defined(DARWIN))
	prefix = "/tmp/";
#endif

#if defined(DARWIN)
    limit = 30;
#endif

	return StrNameFromGlobalName(globalName, limit, prefix, buf, bufSize);
}

int USys5IPCKeyFromGlobalName(const char *globalName)
{
	int key = 0;
	GlobalNameComponents components = {NULL};

	ParseGlobalName(&components,globalName);
	if (globalName == NULL)
	{
		key = IPC_PRIVATE;
	}
	else
	{
		key = components.ordinal;
		if (key==IPC_PRIVATE)
			ThrowSystemException("USys5IPCKeyFromGlobalName: bad key");
	}
	return key;
}

const char *
UCreateCompoundName(const char **namesVec,
					size_t namesCount,
					char *buf,
					size_t bufSize)
{
	size_t nameLen = 0;
	const char **nameCur = namesVec, **namesEnd = namesVec+namesCount;
	char *bufpos = buf;
	assert(buf && bufSize>0);
	strcpy(bufpos,"");
	while(nameCur != namesEnd)
	{
		if (nameCur!=namesVec)
		{
			/* checked there is enough room in buf on previous iteration */
			strcpy(bufpos,",");
			++bufpos; bufSize-=1;
		}
		if (!ValidateGlobalName(*nameCur))
			ThrowSystemException("UCreateCompoundName: bad global name syntax");
		nameLen = (*nameCur?strlen(*nameCur):0);
		if (bufSize < nameLen + 2)
			ThrowSystemException("UCreateCompoundName: buffer too small");
		if (*nameCur)
		{
			strcpy(bufpos, *nameCur);
			bufpos+=nameLen;
			bufSize-=nameLen;
		}
		++nameCur;
	}
	return buf;
}

const char *
UGlobalNameFromCompoundName(const char *compoundName,
							int index,
							char *buf,
							size_t bufSize)
{
	const char *pos = NULL, *epos=NULL;
	assert(buf && compoundName);
	if (!ValidateCompoundName(compoundName))
	{
		ThrowSystemException("UGlobalNameFromCompoundName: bad compound name syntax");
	}
	else
	{
		pos = compoundName;
		while(index > 0 && pos)
		{
			pos = strchr(pos,',');
			if (pos) pos+=1;
			--index;
		}
		if (!pos || index<0)
		{
			ThrowSystemException("UGlobalNameFromCompoundName: index out of range");
		}
		epos = strchr(pos,',');
		if (!epos) epos=pos+strlen(pos);
		if (bufSize < (unsigned int) (epos-pos+1))
		{
			ThrowSystemException("UGlobalNameFromCompoundName: buffer too small");
		}
		if (pos == epos)
		{
			buf = NULL;
		}
		else
		{
			memcpy(buf,pos,epos-pos);
			buf[epos-pos]=0;
		}
	}
	return buf;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#include <iostream>
#include <sstream>

#ifdef __APPLE__
#include <dlfcn.h>
#include <execinfo.h>
#include <CoreFoundation/CoreFoundation.h>
#endif

#ifdef __ANDROID__
#include <android/log.h>
#endif

#include <realm/util/terminate.hpp>

namespace {

// extern "C" and noinline so that a readable message shows up in the stack trace
// of the crash
// prototype here to silence warning
extern "C" REALM_NORETURN REALM_NOINLINE
void please_report_this_error_to_help_at_realm_dot_io();

extern "C" REALM_NORETURN REALM_NOINLINE
void please_report_this_error_to_help_at_realm_dot_io() {
    std::abort();
}

#ifdef __APPLE__
void nslog(const char *message) {
    CFStringRef str = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, message, kCFStringEncodingUTF8, kCFAllocatorNull);
    CFShow(str);

    // Log the message to Crashlytics if it's loaded into the process
    void* addr = dlsym(RTLD_DEFAULT, "CLSLog");
    if (addr) {
        auto fn = reinterpret_cast<void (*)(CFStringRef, ...)>(reinterpret_cast<size_t>(addr));
        fn(CFSTR("%@"), str);
    }

    CFRelease(str);
}
#endif

} // unnamed namespace

namespace realm {
namespace util {

REALM_NORETURN void terminate_internal(std::stringstream& ss) noexcept
{

#if defined(__APPLE__)
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char** strs = backtrace_symbols(callstack, frames);
    for (int i = 0; i < frames; ++i) {
        ss << strs[i] << '\n';
    }
    free(strs);
#endif

    ss << "IMPORTANT: if you see this error, please send this log to help@realm.io.";
#ifdef REALM_DEBUG
    std::cerr << ss.rdbuf() << '\n';
#endif

#if defined(__APPLE__)
    nslog(ss.str().c_str());
#elif defined(__ANDROID__)
    __android_log_print(ANDROID_LOG_ERROR, "REALM", ss.str().c_str());
#endif

    please_report_this_error_to_help_at_realm_dot_io();
}

REALM_NORETURN void terminate(const char* message, const char* file, long line) noexcept
{
    std::stringstream ss;
    ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << '\n';
    terminate_internal(ss);
}

} // namespace util
} // namespace realm
<commit_msg>Erroneously placed `please_report_this_error_to_help_at_realm_dot_io` in an unnamed namespace.<commit_after>/*************************************************************************
 *
 * REALM CONFIDENTIAL
 * __________________
 *
 *  [2011] - [2012] Realm Inc
 *  All Rights Reserved.
 *
 * NOTICE:  All information contained herein is, and remains
 * the property of Realm Incorporated and its suppliers,
 * if any.  The intellectual and technical concepts contained
 * herein are proprietary to Realm Incorporated
 * and its suppliers and may be covered by U.S. and Foreign Patents,
 * patents in process, and are protected by trade secret or copyright law.
 * Dissemination of this information or reproduction of this material
 * is strictly forbidden unless prior written permission is obtained
 * from Realm Incorporated.
 *
 **************************************************************************/
#include <iostream>
#include <sstream>

#ifdef __APPLE__
#include <dlfcn.h>
#include <execinfo.h>
#include <CoreFoundation/CoreFoundation.h>
#endif

#ifdef __ANDROID__
#include <android/log.h>
#endif

#include <realm/util/terminate.hpp>

// extern "C" and noinline so that a readable message shows up in the stack trace
// of the crash
// prototype here to silence warning
extern "C" REALM_NORETURN REALM_NOINLINE
void please_report_this_error_to_help_at_realm_dot_io();

extern "C" REALM_NORETURN REALM_NOINLINE
void please_report_this_error_to_help_at_realm_dot_io() {
    std::abort();
}

namespace {

#ifdef __APPLE__
void nslog(const char *message) {
    CFStringRef str = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, message, kCFStringEncodingUTF8, kCFAllocatorNull);
    CFShow(str);

    // Log the message to Crashlytics if it's loaded into the process
    void* addr = dlsym(RTLD_DEFAULT, "CLSLog");
    if (addr) {
        auto fn = reinterpret_cast<void (*)(CFStringRef, ...)>(reinterpret_cast<size_t>(addr));
        fn(CFSTR("%@"), str);
    }

    CFRelease(str);
}
#endif

} // unnamed namespace

namespace realm {
namespace util {

REALM_NORETURN void terminate_internal(std::stringstream& ss) noexcept
{

#if defined(__APPLE__)
    void* callstack[128];
    int frames = backtrace(callstack, 128);
    char** strs = backtrace_symbols(callstack, frames);
    for (int i = 0; i < frames; ++i) {
        ss << strs[i] << '\n';
    }
    free(strs);
#endif

    ss << "IMPORTANT: if you see this error, please send this log to help@realm.io.";
#ifdef REALM_DEBUG
    std::cerr << ss.rdbuf() << '\n';
#endif

#if defined(__APPLE__)
    nslog(ss.str().c_str());
#elif defined(__ANDROID__)
    __android_log_print(ANDROID_LOG_ERROR, "REALM", ss.str().c_str());
#endif

    please_report_this_error_to_help_at_realm_dot_io();
}

REALM_NORETURN void terminate(const char* message, const char* file, long line) noexcept
{
    std::stringstream ss;
    ss << file << ":" << line << ": " REALM_VER_CHUNK " " << message << '\n';
    terminate_internal(ss);
}

} // namespace util
} // namespace realm
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2003-2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY, TITLE, NONINFRINGEMENT or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307  USA
 */

#include "winsock.h"

#include <objbase.h>
#include <initguid.h>
#include <connmgr.h>
#include <wininet.h>

#include "http/GPRSConnection.h"
#include "base/Log.h"

/*
* Method to test if connection is alive. If no one is found, it tries to establish
* default connection.
*/

BOOL EstablishConnection() {

    HANDLE  phWebConnection = NULL;

    // First we check if we might have a connection
    DWORD  pdwStatus = 0;
    LOG.info("Establish connection: test internet connection status...");
    ConnMgrConnectionStatus(phWebConnection, &pdwStatus);

    if (pdwStatus == CONNMGR_STATUS_CONNECTED) {
        LOG.info("Arleady connected");
        //We are already connected!
        return TRUE;
    }
#if _WIN32_WCE > 0x500
    else if (pdwStatus == CONNMGR_STATUS_PHONEOFF) {
        LOG.info("phone off");
        //We are already connected!
        return FALSE;
    }
#endif
    else {
        LOG.debug("Not connected: try to connect...");
        //We are not connected, so lets try:
        //The CONNECTIONINFO is the structure that
        //tells Connection Manager how we want
        //to connect

        CONNMGR_CONNECTIONINFO sConInfo;
        memset(&sConInfo,0, sizeof(CONNMGR_CONNECTIONINFO));
        sConInfo.cbSize = sizeof(CONNMGR_CONNECTIONINFO);
        // We want to use the "guidDestNet" parameter
        sConInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
        // This is the highest data priority.
        sConInfo.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
        // sConInfo.dwFlags = 0;
        sConInfo.dwFlags=CONNMGR_FLAG_PROXY_HTTP;
        // Lets be nice and share the connection with
        // other applications
        sConInfo.bExclusive = FALSE;
        sConInfo.bDisabled = FALSE;
        sConInfo.guidDestNet = IID_DestNetInternet;
        LOG.debug("Try to establish connection...");
        if (ConnMgrEstablishConnection(&sConInfo,&phWebConnection) == S_OK) {
            LOG.debug("Start internet connection process...");
            //We start successfully process!
            for (unsigned int k = 0; k < 6; k++) {
                ConnMgrConnectionStatus(phWebConnection,&pdwStatus);

                if (pdwStatus == CONNMGR_STATUS_CONNECTED) {
                    LOG.info("Internet connection succesfully completed.");
                    return TRUE;

                }
                else {
                    if (pdwStatus == CONNMGR_STATUS_CONNECTIONCANCELED || pdwStatus == CONNMGR_STATUS_WAITINGCONNECTIONABORT) {
                        LOG.debug("Internet connection not succeded.");
                        return FALSE;

                    }
                    Sleep(2000);

                    ConnMgrConnectionStatus(phWebConnection,&pdwStatus);
                    if (pdwStatus == CONNMGR_STATUS_WAITINGCONNECTION) {
                        // it is possible to do something...
                    }

                    if (pdwStatus == CONNMGR_STATUS_CONNECTIONCANCELED || pdwStatus == CONNMGR_STATUS_WAITINGCONNECTIONABORT) {
                        LOG.debug("Internet connection not succeded");
                        return FALSE;
                    }
                }
            }
            LOG.debug("Internet connection not succeded after connection process");
            return FALSE;
        }
        else {
            //Connection failed!
            LOG.info("Internet connection failed.");
            return FALSE;

        }

    }

}
<commit_msg>use winsock2 lib<commit_after>/*
 * Copyright (C) 2003-2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY, TITLE, NONINFRINGEMENT or FITNESS FOR A PARTICULAR
 * PURPOSE.  See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
 * 02111-1307  USA
 */

#include "winsock2.h"

#include <objbase.h>
#include <initguid.h>
#include <connmgr.h>
#include <wininet.h>

#include "http/GPRSConnection.h"
#include "base/Log.h"

/*
* Method to test if connection is alive. If no one is found, it tries to establish
* default connection.
*/

BOOL EstablishConnection() {

    HANDLE  phWebConnection = NULL;

    // First we check if we might have a connection
    DWORD  pdwStatus = 0;
    LOG.info("Establish connection: test internet connection status...");
    ConnMgrConnectionStatus(phWebConnection, &pdwStatus);

    if (pdwStatus == CONNMGR_STATUS_CONNECTED) {
        LOG.info("Arleady connected");
        //We are already connected!
        return TRUE;
    }
#if _WIN32_WCE > 0x500
    else if (pdwStatus == CONNMGR_STATUS_PHONEOFF) {
        LOG.info("phone off");
        //We are already connected!
        return FALSE;
    }
#endif
    else {
        LOG.debug("Not connected: try to connect...");
        //We are not connected, so lets try:
        //The CONNECTIONINFO is the structure that
        //tells Connection Manager how we want
        //to connect

        CONNMGR_CONNECTIONINFO sConInfo;
        memset(&sConInfo,0, sizeof(CONNMGR_CONNECTIONINFO));
        sConInfo.cbSize = sizeof(CONNMGR_CONNECTIONINFO);
        // We want to use the "guidDestNet" parameter
        sConInfo.dwParams = CONNMGR_PARAM_GUIDDESTNET;
        // This is the highest data priority.
        sConInfo.dwPriority = CONNMGR_PRIORITY_USERINTERACTIVE;
        // sConInfo.dwFlags = 0;
        sConInfo.dwFlags=CONNMGR_FLAG_PROXY_HTTP;
        // Lets be nice and share the connection with
        // other applications
        sConInfo.bExclusive = FALSE;
        sConInfo.bDisabled = FALSE;
        sConInfo.guidDestNet = IID_DestNetInternet;
        LOG.debug("Try to establish connection...");
        if (ConnMgrEstablishConnection(&sConInfo,&phWebConnection) == S_OK) {
            LOG.debug("Start internet connection process...");
            //We start successfully process!
            for (unsigned int k = 0; k < 6; k++) {
                ConnMgrConnectionStatus(phWebConnection,&pdwStatus);

                if (pdwStatus == CONNMGR_STATUS_CONNECTED) {
                    LOG.info("Internet connection succesfully completed.");
                    return TRUE;

                }
                else {
                    if (pdwStatus == CONNMGR_STATUS_CONNECTIONCANCELED || pdwStatus == CONNMGR_STATUS_WAITINGCONNECTIONABORT) {
                        LOG.debug("Internet connection not succeded.");
                        return FALSE;

                    }
                    Sleep(2000);

                    ConnMgrConnectionStatus(phWebConnection,&pdwStatus);
                    if (pdwStatus == CONNMGR_STATUS_WAITINGCONNECTION) {
                        // it is possible to do something...
                    }

                    if (pdwStatus == CONNMGR_STATUS_CONNECTIONCANCELED || pdwStatus == CONNMGR_STATUS_WAITINGCONNECTIONABORT) {
                        LOG.debug("Internet connection not succeded");
                        return FALSE;
                    }
                }
            }
            LOG.debug("Internet connection not succeded after connection process");
            return FALSE;
        }
        else {
            //Connection failed!
            LOG.info("Internet connection failed.");
            return FALSE;

        }

    }

}
<|endoftext|>