<commit_before>/*************************************************************************
 *
 *  $RCSfile: AccessibleComponentBase.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: af $ $Date: 2002-03-06 15:56:26 $
 *
 *  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 WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES 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): _______________________________________
 *
 *
 ************************************************************************/

#include "AccessibleComponentBase.hxx"

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_
#include <com/sun/star/drawing/XShapeDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;

namespace accessibility {

//=====  internal  ============================================================

AccessibleComponentBase::AccessibleComponentBase (void)
{
}

AccessibleComponentBase::~AccessibleComponentBase (void)
{
}

//=====  XAccessibleComponent  ================================================

sal_Bool SAL_CALL AccessibleComponentBase::contains (
        const ::com::sun::star::awt::Point& aPoint)
        throw (::com::sun::star::uno::RuntimeException)
{
    return sal_False;
}

::com::sun::star::uno::Reference<
    ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL
    AccessibleComponentBase::getAccessibleAt (
        const ::com::sun::star::awt::Point& aPoint)
    throw (::com::sun::star::uno::RuntimeException)
{
    return uno::Reference<XAccessible>();
}

::com::sun::star::awt::Rectangle SAL_CALL AccessibleComponentBase::getBounds (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    awt::Rectangle aBBox;
    return aBBox;
}

awt::Point SAL_CALL AccessibleComponentBase::getLocation (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Point aLocation;
    return aLocation;
}

awt::Point SAL_CALL AccessibleComponentBase::getLocationOnScreen (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Point aLocation;
    return aLocation;
}

::com::sun::star::awt::Size SAL_CALL AccessibleComponentBase::getSize (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Size aSize;
    return aSize;
}

sal_Bool SAL_CALL AccessibleComponentBase::isShowing (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return sal_False;
}

sal_Bool SAL_CALL AccessibleComponentBase::isVisible (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return sal_False;
}

sal_Bool SAL_CALL AccessibleComponentBase::isFocusTraversable (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return sal_False;
}

void SAL_CALL AccessibleComponentBase::addFocusListener (
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener)
    throw (::com::sun::star::uno::RuntimeException)
{
    // emtpy
}

void SAL_CALL AccessibleComponentBase::removeFocusListener (const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener )
    throw (::com::sun::star::uno::RuntimeException)
{
    // emtpy
}

void SAL_CALL AccessibleComponentBase::grabFocus (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    // emtpy
}

::com::sun::star::uno::Any SAL_CALL AccessibleComponentBase::getAccessibleKeyBinding (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    uno::Any aKeyBinding;
    return aKeyBinding;
}

//=====  XAccessibleExtendedComponent  ========================================

sal_Int32 SAL_CALL AccessibleComponentBase::getForeground (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return 0;
}

sal_Int32 SAL_CALL AccessibleComponentBase::getBackground (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return -1;
}

::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL
        AccessibleComponentBase::getFont (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return uno::Reference<awt::XFont>();
}

awt::FontDescriptor SAL_CALL
        AccessibleComponentBase::getFontMetrics (const uno::Reference<awt::XFont >& xFont)
        throw (::com::sun::star::uno::RuntimeException)
{
    awt::FontDescriptor aFontDescriptor;
    return aFontDescriptor;
}

sal_Bool SAL_CALL AccessibleComponentBase::isEnabled (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return sal_True;
}

::rtl::OUString SAL_CALL AccessibleComponentBase::getTitledBorderText (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString::createFromAscii ("Dummy Title Border Text");
}

::rtl::OUString SAL_CALL AccessibleComponentBase::getToolTipText (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString::createFromAscii ("Dummy Tool Tip Text");
}

//=====  XTypeProvider  ===================================================

uno::Sequence<uno::Type> SAL_CALL
    AccessibleComponentBase::getTypes (void)
    throw (uno::RuntimeException)
{
    // Get list of types from the context base implementation...
    uno::Sequence<uno::Type> aTypeList (2);
    // ...and add the additional type for the component.
    const uno::Type aComponentType =
         ::getCppuType((const uno::Reference<XAccessibleComponent>*)0);
    const uno::Type aExtendedComponentType =
        ::getCppuType((const uno::Reference<XAccessibleExtendedComponent>*)0);
    aTypeList[0] = aComponentType;
    aTypeList[1] = aExtendedComponentType;

    return aTypeList;
}

} // end of namespace accessibility
<commit_msg>#95585# Using getBounds to implement getLocation and getSize.<commit_after>/*************************************************************************
 *
 *  $RCSfile: AccessibleComponentBase.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: af $ $Date: 2002-03-18 10:13:19 $
 *
 *  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 WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES 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): _______________________________________
 *
 *
 ************************************************************************/

#include "AccessibleComponentBase.hxx"

#ifndef _DRAFTS_COM_SUN_STAR_ACCESSIBILITY_ACCESSIBLE_ROLE_HPP_
#include <drafts/com/sun/star/accessibility/AccessibleRole.hpp>
#endif
#ifndef _COM_SUN_STAR_CONTAINER_XCHILD_HPP_
#include <com/sun/star/container/XChild.hpp>
#endif
#ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_
#include <com/sun/star/beans/XPropertySet.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPES_HPP_
#include <com/sun/star/drawing/XShapes.hpp>
#endif
#ifndef _COM_SUN_STAR_DRAWING_XSHAPEDESCRIPTOR_HPP_
#include <com/sun/star/drawing/XShapeDescriptor.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_INDEXOUTOFBOUNDSEXCEPTION_HPP_
#include <com/sun/star/lang/IndexOutOfBoundsException.hpp>
#endif

using namespace ::rtl;
using namespace ::com::sun::star;
using namespace ::drafts::com::sun::star::accessibility;

namespace accessibility {

//=====  internal  ============================================================

AccessibleComponentBase::AccessibleComponentBase (void)
{
}

AccessibleComponentBase::~AccessibleComponentBase (void)
{
}

//=====  XAccessibleComponent  ================================================

sal_Bool SAL_CALL AccessibleComponentBase::contains (
        const ::com::sun::star::awt::Point& aPoint)
        throw (::com::sun::star::uno::RuntimeException)
{
    return sal_False;
}

::com::sun::star::uno::Reference<
    ::drafts::com::sun::star::accessibility::XAccessible > SAL_CALL
    AccessibleComponentBase::getAccessibleAt (
        const ::com::sun::star::awt::Point& aPoint)
    throw (::com::sun::star::uno::RuntimeException)
{
    return uno::Reference<XAccessible>();
}

::com::sun::star::awt::Rectangle SAL_CALL AccessibleComponentBase::getBounds (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    awt::Rectangle aBBox;
    return aBBox;
}

awt::Point SAL_CALL AccessibleComponentBase::getLocation (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Rectangle aBBox (getBounds());
    return awt::Point (aBBox.X, aBBox.Y);
}

awt::Point SAL_CALL AccessibleComponentBase::getLocationOnScreen (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Point aLocation;
    return aLocation;
}

::com::sun::star::awt::Size SAL_CALL AccessibleComponentBase::getSize (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    awt::Rectangle aBBox (getBounds());
    return awt::Size (aBBox.Width, aBBox.Height);
}

sal_Bool SAL_CALL AccessibleComponentBase::isShowing (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return sal_False;
}

sal_Bool SAL_CALL AccessibleComponentBase::isVisible (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return sal_False;
}

sal_Bool SAL_CALL AccessibleComponentBase::isFocusTraversable (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return sal_False;
}

void SAL_CALL AccessibleComponentBase::addFocusListener (
    const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener)
    throw (::com::sun::star::uno::RuntimeException)
{
    // emtpy
}

void SAL_CALL AccessibleComponentBase::removeFocusListener (const ::com::sun::star::uno::Reference<
    ::com::sun::star::awt::XFocusListener >& xListener )
    throw (::com::sun::star::uno::RuntimeException)
{
    // emtpy
}

void SAL_CALL AccessibleComponentBase::grabFocus (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    // emtpy
}

::com::sun::star::uno::Any SAL_CALL AccessibleComponentBase::getAccessibleKeyBinding (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    uno::Any aKeyBinding;
    return aKeyBinding;
}

//=====  XAccessibleExtendedComponent  ========================================

sal_Int32 SAL_CALL AccessibleComponentBase::getForeground (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return 0;
}

sal_Int32 SAL_CALL AccessibleComponentBase::getBackground (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return -1;
}

::com::sun::star::uno::Reference< ::com::sun::star::awt::XFont > SAL_CALL
        AccessibleComponentBase::getFont (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return uno::Reference<awt::XFont>();
}

awt::FontDescriptor SAL_CALL
        AccessibleComponentBase::getFontMetrics (const uno::Reference<awt::XFont >& xFont)
        throw (::com::sun::star::uno::RuntimeException)
{
    awt::FontDescriptor aFontDescriptor;
    return aFontDescriptor;
}

sal_Bool SAL_CALL AccessibleComponentBase::isEnabled (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return sal_True;
}

::rtl::OUString SAL_CALL AccessibleComponentBase::getTitledBorderText (void)
        throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString::createFromAscii ("Dummy Title Border Text");
}

::rtl::OUString SAL_CALL AccessibleComponentBase::getToolTipText (void)
    throw (::com::sun::star::uno::RuntimeException)
{
    return ::rtl::OUString::createFromAscii ("Dummy Tool Tip Text");
}

//=====  XTypeProvider  ===================================================

uno::Sequence<uno::Type> SAL_CALL
    AccessibleComponentBase::getTypes (void)
    throw (uno::RuntimeException)
{
    // Get list of types from the context base implementation...
    uno::Sequence<uno::Type> aTypeList (2);
    // ...and add the additional type for the component.
    const uno::Type aComponentType =
         ::getCppuType((const uno::Reference<XAccessibleComponent>*)0);
    const uno::Type aExtendedComponentType =
        ::getCppuType((const uno::Reference<XAccessibleExtendedComponent>*)0);
    aTypeList[0] = aComponentType;
    aTypeList[1] = aExtendedComponentType;

    return aTypeList;
}

} // end of namespace accessibility
<|endoftext|>


<commit_before>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3279
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3279 to 3280<commit_after>/* Copyright (c) 2010-present Advanced Micro Devices, Inc.

 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3280
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.

 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3422
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<commit_msg>SWDEV-2 - Change OpenCL version number from  3422 to 3423<commit_after>/* Copyright (c) 2010 - 2021 Advanced Micro Devices, Inc.

 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. */

#ifndef VERSIONS_HPP_
#define VERSIONS_HPP_

#include "utils/macros.hpp"

#ifndef AMD_PLATFORM_NAME
#define AMD_PLATFORM_NAME "AMD Accelerated Parallel Processing"
#endif  // AMD_PLATFORM_NAME

#ifndef AMD_PLATFORM_BUILD_NUMBER
#define AMD_PLATFORM_BUILD_NUMBER 3423
#endif  // AMD_PLATFORM_BUILD_NUMBER

#ifndef AMD_PLATFORM_REVISION_NUMBER
#define AMD_PLATFORM_REVISION_NUMBER 0
#endif  // AMD_PLATFORM_REVISION_NUMBER

#ifndef AMD_PLATFORM_RELEASE_INFO
#define AMD_PLATFORM_RELEASE_INFO
#endif  // AMD_PLATFORM_RELEASE_INFO

#define AMD_BUILD_STRING                                                                           \
  XSTR(AMD_PLATFORM_BUILD_NUMBER)                                                                  \
  "." XSTR(AMD_PLATFORM_REVISION_NUMBER)

#ifndef AMD_PLATFORM_INFO
#define AMD_PLATFORM_INFO                                                                          \
  "AMD-APP" AMD_PLATFORM_RELEASE_INFO DEBUG_ONLY(                                                  \
      "." IF(IS_OPTIMIZED, "opt", "dbg")) " (" AMD_BUILD_STRING ")"
#endif  // ATI_PLATFORM_INFO

#endif  // VERSIONS_HPP_
<|endoftext|>


<commit_before>#include "entity_template_system.h"
#include "core/array.h"
#include "core/crc32.h"
#include "core/iserializer.h"
#include "core/map.h"
#include "core/string.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "universe/entity.h"
#include "universe/universe.h"

namespace Lumix
{

	class EntityTemplateSystemImpl : public EntityTemplateSystem
	{
		public:
			EntityTemplateSystemImpl(WorldEditor& editor)
				: m_editor(editor)
			{
				m_universe = editor.getEngine().getUniverse();
				editor.universeCreated().bind<EntityTemplateSystemImpl, &EntityTemplateSystemImpl::onUniverseCreated>(this);
				editor.universeDestroyed().bind<EntityTemplateSystemImpl, &EntityTemplateSystemImpl::onUniverseDestroyed>(this);
			}

			~EntityTemplateSystemImpl()
			{
				m_editor.universeCreated().unbind<EntityTemplateSystemImpl, &EntityTemplateSystemImpl::onUniverseCreated>(this);
				m_editor.universeDestroyed().unbind<EntityTemplateSystemImpl, &EntityTemplateSystemImpl::onUniverseDestroyed>(this);
			}

			void onUniverseCreated()
			{
				m_instances.clear();
				m_template_names.clear();
				m_universe = m_editor.getEngine().getUniverse();
			}

			void onUniverseDestroyed()
			{
				m_instances.clear();
				m_template_names.clear();
				m_universe = NULL;
			}

			virtual void createTemplateFromEntity(const char* name, const Entity& entity) override
			{
				uint32_t name_hash = crc32(name);
				if (m_instances.find(name_hash) == m_instances.end())
				{
					m_template_names.push(string(name));
					m_instances[name_hash].push(entity);
					m_updated.invoke();
				}
				else
				{
					ASSERT(false);
				}
			}

			virtual uint32_t getTemplate(const Entity& entity) override
			{
				for (auto iter = m_instances.begin(), end = m_instances.end(); iter != end; ++iter)
				{
					Array<Entity>& entities = iter.second();
					for (int i = 0, c = entities.size(); i < c; ++i)
					{
						if (entities[i] == entity)
						{
							return iter.first();
						}
					}
				}
				return 0;
			}

			virtual const Array<Entity>& getInstances(uint32_t template_name_hash) override
			{
				return m_instances[template_name_hash];
			}

			virtual Entity createInstance(const char* name) override
			{
				uint32_t name_hash = crc32(name);
				Map<uint32_t, Array<Entity> >::iterator iter = m_instances.find(name_hash);
				if (iter == m_instances.end())
				{
					ASSERT(false);
					return Entity::INVALID;
				}
				else
				{
					Entity entity = m_editor.addEntity();
					m_instances[name_hash].push(entity);
					Entity template_entity = iter.second()[0];
					const Entity::ComponentList& template_cmps = template_entity.getComponents();
					for (int i = 0; i < template_cmps.size(); ++i)
					{
						m_editor.cloneComponent(template_cmps[i], entity);
					}
					return entity;
				}
			}

			virtual void serialize(ISerializer& serializer) override
			{
				serializer.serialize("templates_count", (int32_t)m_template_names.size());
				serializer.beginArray("template_names");
				for (int i = 0, c = m_template_names.size(); i < c;  ++i)
				{
					serializer.serializeArrayItem(m_template_names[i].c_str());
				}
				serializer.endArray();
				serializer.serialize("instance_count", (int32_t)m_instances.size());
				serializer.beginArray("instances");
				for (auto i = m_instances.begin(), end = m_instances.end(); i != end; ++i)
				{
					serializer.serializeArrayItem(i.first());
					serializer.serializeArrayItem((int32_t)i.second().size());
					for (int j = 0, c = i.second().size(); j < c; ++j)
					{
						serializer.serializeArrayItem(i.second()[j].index);
					}
				}
				serializer.endArray();

			}

			virtual void deserialize(ISerializer& serializer) override
			{
				int32_t count;
				serializer.deserialize("templates_count", count);
				serializer.deserializeArrayBegin("template_names");
				for (int i = 0; i < count; ++i)
				{
					const int MAX_NAME_LENGTH = 50;
					char name[MAX_NAME_LENGTH];
					serializer.deserializeArrayItem(name, MAX_NAME_LENGTH);
					m_template_names.push(string(name));
				}
				serializer.deserializeArrayEnd();
				serializer.deserialize("instance_count", count);
				serializer.deserializeArrayBegin("instances");
				for (int i = 0; i < count; ++i)
				{
					uint32_t hash;
					serializer.deserializeArrayItem(hash);
					int32_t instances_per_template;
					serializer.deserializeArrayItem(instances_per_template);
					m_instances.insert(hash, Array<Entity>());
					Array<Entity>& entities = m_instances[hash];
					for (int j = 0; j < instances_per_template; ++j)
					{
						int32_t entity_index;
						serializer.deserializeArrayItem(entity_index);
						entities.push(Entity(m_universe, entity_index));
					}
				}
				serializer.deserializeArrayEnd();
				m_updated.invoke();
			}

			virtual Array<string>& getTemplateNames() override
			{
				return m_template_names;
			}

			virtual DelegateList<void()>& updated() override
			{
				return m_updated;
			}

		private:
			Map<uint32_t, Array<Entity> > m_instances;
			Array<string> m_template_names;
			Universe* m_universe;
			WorldEditor& m_editor;
			DelegateList<void()> m_updated;

	}; // class EntityTemplateSystemImpl

	EntityTemplateSystem* EntityTemplateSystem::create(WorldEditor& editor)
	{
		return LUMIX_NEW(EntityTemplateSystemImpl)(editor);
	}

	void EntityTemplateSystem::destroy(EntityTemplateSystem* system)
	{
		LUMIX_DELETE(system);
	}

} // namespace Lumix<commit_msg>entity template serialization is reentrant<commit_after>#include "entity_template_system.h"
#include "core/array.h"
#include "core/crc32.h"
#include "core/iserializer.h"
#include "core/map.h"
#include "core/string.h"
#include "editor/world_editor.h"
#include "engine/engine.h"
#include "universe/entity.h"
#include "universe/universe.h"

namespace Lumix
{

	class EntityTemplateSystemImpl : public EntityTemplateSystem
	{
		public:
			EntityTemplateSystemImpl(WorldEditor& editor)
				: m_editor(editor)
			{
				m_universe = editor.getEngine().getUniverse();
				editor.universeCreated().bind<EntityTemplateSystemImpl, &EntityTemplateSystemImpl::onUniverseCreated>(this);
				editor.universeDestroyed().bind<EntityTemplateSystemImpl, &EntityTemplateSystemImpl::onUniverseDestroyed>(this);
			}

			~EntityTemplateSystemImpl()
			{
				m_editor.universeCreated().unbind<EntityTemplateSystemImpl, &EntityTemplateSystemImpl::onUniverseCreated>(this);
				m_editor.universeDestroyed().unbind<EntityTemplateSystemImpl, &EntityTemplateSystemImpl::onUniverseDestroyed>(this);
			}

			void onUniverseCreated()
			{
				m_instances.clear();
				m_template_names.clear();
				m_universe = m_editor.getEngine().getUniverse();
			}

			void onUniverseDestroyed()
			{
				m_instances.clear();
				m_template_names.clear();
				m_universe = NULL;
			}

			virtual void createTemplateFromEntity(const char* name, const Entity& entity) override
			{
				uint32_t name_hash = crc32(name);
				if (m_instances.find(name_hash) == m_instances.end())
				{
					m_template_names.push(string(name));
					m_instances[name_hash].push(entity);
					m_updated.invoke();
				}
				else
				{
					ASSERT(false);
				}
			}

			virtual uint32_t getTemplate(const Entity& entity) override
			{
				for (auto iter = m_instances.begin(), end = m_instances.end(); iter != end; ++iter)
				{
					Array<Entity>& entities = iter.second();
					for (int i = 0, c = entities.size(); i < c; ++i)
					{
						if (entities[i] == entity)
						{
							return iter.first();
						}
					}
				}
				return 0;
			}

			virtual const Array<Entity>& getInstances(uint32_t template_name_hash) override
			{
				return m_instances[template_name_hash];
			}

			virtual Entity createInstance(const char* name) override
			{
				uint32_t name_hash = crc32(name);
				Map<uint32_t, Array<Entity> >::iterator iter = m_instances.find(name_hash);
				if (iter == m_instances.end())
				{
					ASSERT(false);
					return Entity::INVALID;
				}
				else
				{
					Entity entity = m_editor.addEntity();
					m_instances[name_hash].push(entity);
					Entity template_entity = iter.second()[0];
					const Entity::ComponentList& template_cmps = template_entity.getComponents();
					for (int i = 0; i < template_cmps.size(); ++i)
					{
						m_editor.cloneComponent(template_cmps[i], entity);
					}
					return entity;
				}
			}

			virtual void serialize(ISerializer& serializer) override
			{
				serializer.serialize("templates_count", (int32_t)m_template_names.size());
				serializer.beginArray("template_names");
				for (int i = 0, c = m_template_names.size(); i < c;  ++i)
				{
					serializer.serializeArrayItem(m_template_names[i].c_str());
				}
				serializer.endArray();
				serializer.serialize("instance_count", (int32_t)m_instances.size());
				serializer.beginArray("instances");
				for (auto i = m_instances.begin(), end = m_instances.end(); i != end; ++i)
				{
					serializer.serializeArrayItem(i.first());
					serializer.serializeArrayItem((int32_t)i.second().size());
					for (int j = 0, c = i.second().size(); j < c; ++j)
					{
						serializer.serializeArrayItem(i.second()[j].index);
					}
				}
				serializer.endArray();

			}

			virtual void deserialize(ISerializer& serializer) override
			{
				m_template_names.clear();
				m_instances.clear();
				int32_t count;
				serializer.deserialize("templates_count", count);
				serializer.deserializeArrayBegin("template_names");
				for (int i = 0; i < count; ++i)
				{
					const int MAX_NAME_LENGTH = 50;
					char name[MAX_NAME_LENGTH];
					serializer.deserializeArrayItem(name, MAX_NAME_LENGTH);
					m_template_names.push(string(name));
				}
				serializer.deserializeArrayEnd();
				serializer.deserialize("instance_count", count);
				serializer.deserializeArrayBegin("instances");
				for (int i = 0; i < count; ++i)
				{
					uint32_t hash;
					serializer.deserializeArrayItem(hash);
					int32_t instances_per_template;
					serializer.deserializeArrayItem(instances_per_template);
					m_instances.insert(hash, Array<Entity>());
					Array<Entity>& entities = m_instances[hash];
					for (int j = 0; j < instances_per_template; ++j)
					{
						int32_t entity_index;
						serializer.deserializeArrayItem(entity_index);
						entities.push(Entity(m_universe, entity_index));
					}
				}
				serializer.deserializeArrayEnd();
				m_updated.invoke();
			}

			virtual Array<string>& getTemplateNames() override
			{
				return m_template_names;
			}

			virtual DelegateList<void()>& updated() override
			{
				return m_updated;
			}

		private:
			Map<uint32_t, Array<Entity> > m_instances;
			Array<string> m_template_names;
			Universe* m_universe;
			WorldEditor& m_editor;
			DelegateList<void()> m_updated;

	}; // class EntityTemplateSystemImpl

	EntityTemplateSystem* EntityTemplateSystem::create(WorldEditor& editor)
	{
		return LUMIX_NEW(EntityTemplateSystemImpl)(editor);
	}

	void EntityTemplateSystem::destroy(EntityTemplateSystem* system)
	{
		LUMIX_DELETE(system);
	}

} // namespace Lumix<|endoftext|>


<commit_before>#include "precompiled.h"
#include "engine/render/term/TermRender.h"

//Only compile if its in use
#ifdef TERMRENDER

#include "engine/console/Cvar.h"

namespace cvar {
	CVAR(int,fastexit,0,CVAR_NORMAL);
}

namespace engine {
namespace render {
namespace term {

	void TermRender::update(){
		tb_cell cell; //temp cell used in rendering

		//Check that the camera is not out of bounds...
		if(cameraPos.x < 0 || cameraPos.x >= WORLD_WIDTH){
			LOG_ERROR("Camera out of bounds! (x)");
			return;
		}

		if(cameraPos.y < 0 || cameraPos.y >= WORLD_HEIGHT){
			LOG_ERROR("Camera out of bounds! (y)");
			return;
		}

		if(cameraPos.z < 0 || cameraPos.z >= WORLD_DEPTH){
			LOG_ERROR("Camera out of bounds! (z)");
			return;
		}

		/* RENDER MAP */
		world::Room *currentRoom = sceneSystem->getWorld()->getRoom(cameraPos);

		vec2 pos;
		for(int x = 0;x < ROOM_WIDTH;++x){
			for(int y = 0;y < ROOM_HEIGHT;++y){
				pos.x = (x + 2);
				pos.y = (y + 2);
				//Changing the color
				world::Tile *tile = currentRoom->getTile(x,y);

				cell.ch = tile->visual;
				cell.fg = convertColor(tile->fgColor);
				cell.bg = convertColor(tile->bgColor);

				tb_put_cell(x,y,&cell);
			}
		}

		/* RENDER ACTORS */

		std::vector<actor::ActorBase *> actors = sceneSystem->getActorManager()->getActorsInRoom(cameraPos);

		cell.fg = TB_WHITE;
		cell.bg = TB_BLACK;
		for(unsigned int i = 0; i < actors.size();++i){
			cell.ch = actors.at(i)->getSymbol();
			cell.bg = currentRoom->getTile(actors.at(i)->getPos()->x,actors.at(i)->getPos()->y)->bgColor;
			tb_put_cell(actors.at(i)->getPos()->x, actors.at(i)->getPos()->y, &cell);
		}

		/* "RENDER" UI */

		uiSystem->windows.size();

		/* RENDER THE ACTUAL STUFF */

		tb_present();

		tb_event event;

		tb_poll_event(&event);

		if(*cvar::fastexit == 1){
			if(event.type == TB_EVENT_KEY){
				if(event.key == TB_KEY_ESC){
					LOG_INFO("User wants to quit the game");

					//Dont fuck up the console while closing the game.
					tb_shutdown();
					exit(0);
				}
			}
		}

		return;
	}

	/**
	 * Convert engine color to termbox color
	 */
	uint16_t TermRender::convertColor(render::Color color){
		switch(color){
			case C_WHITE:
				return TB_WHITE;
			case C_BLACK:
				return TB_BLACK;
			case C_RED:
				return TB_RED;
			case C_GREEN:
				return TB_GREEN;
			case C_BLUE:
				return TB_BLUE;
		}

		return TB_WHITE;
	}

}
}
}

#endif
<commit_msg>Fixed termbox builds<commit_after>#include "precompiled.h"
#include "engine/render/term/TermRender.h"

//Only compile if its in use
#ifdef TERMRENDER

#include "engine/console/Cvar.h"

namespace cvar {
	CVAR(int,fastexit,0,CVAR_NORMAL);
}

namespace engine {
namespace render {
namespace term {

	void TermRender::update(){
		tb_cell cell; //temp cell used in rendering

		//Check that the camera is not out of bounds...
		if(cameraPos.x < 0 || cameraPos.x >= WORLD_WIDTH){
			LOG_ERROR("Camera out of bounds! (x)");
			return;
		}

		if(cameraPos.y < 0 || cameraPos.y >= WORLD_HEIGHT){
			LOG_ERROR("Camera out of bounds! (y)");
			return;
		}

		if(cameraPos.z < 0 || cameraPos.z >= WORLD_DEPTH){
			LOG_ERROR("Camera out of bounds! (z)");
			return;
		}

		/* RENDER MAP */
		world::Room *currentRoom = sceneSystem->getWorld()->getRoom(cameraPos);

		vec2 pos;
		for(int x = 0;x < ROOM_WIDTH;++x){
			for(int y = 0;y < ROOM_HEIGHT;++y){
				pos.x = (x + 2);
				pos.y = (y + 2);
				//Changing the color
				world::Tile *tile = currentRoom->getTile(x,y);

				cell.ch = tile->visual;
				cell.fg = convertColor(tile->fgColor);
				cell.bg = convertColor(tile->bgColor);

				tb_put_cell(x,y,&cell);
			}
		}

		/* RENDER ACTORS */

		std::vector<actor::ActorBase *> actors = sceneSystem->getActorManager()->getActorSystem()->getActorsInRoom(cameraPos);

		cell.fg = TB_WHITE;
		cell.bg = TB_BLACK;
		for(unsigned int i = 0; i < actors.size();++i){
			cell.ch = actors.at(i)->getSymbol();
			cell.bg = currentRoom->getTile(actors.at(i)->getPos()->x,actors.at(i)->getPos()->y)->bgColor;
			tb_put_cell(actors.at(i)->getPos()->x, actors.at(i)->getPos()->y, &cell);
		}

		/* "RENDER" UI */

		uiSystem->windows.size();

		/* RENDER THE ACTUAL STUFF */

		tb_present();

		tb_event event;

		tb_poll_event(&event);

		if(*cvar::fastexit == 1){
			if(event.type == TB_EVENT_KEY){
				if(event.key == TB_KEY_ESC){
					LOG_INFO("User wants to quit the game");

					//Dont fuck up the console while closing the game.
					tb_shutdown();
					exit(0);
				}
			}
		}

		return;
	}

	/**
	 * Convert engine color to termbox color
	 */
	uint16_t TermRender::convertColor(render::Color color){
		switch(color){
			case C_WHITE:
				return TB_WHITE;
			case C_BLACK:
				return TB_BLACK;
			case C_RED:
				return TB_RED;
			case C_GREEN:
				return TB_GREEN;
			case C_BLUE:
				return TB_BLUE;
		}

		return TB_WHITE;
	}

}
}
}

#endif
<|endoftext|>


<commit_before>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iterator>
#include <vector>

#include "tensorflow/core/kernels/data/generator_dataset_op.h"

#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/captured_function.h"
#include "tensorflow/core/lib/random/random.h"

namespace tensorflow {
namespace data {

// See documentation in ../ops/dataset_ops.cc for a high-level
// description of the following op.

class GeneratorDatasetOp::Dataset : public DatasetBase {
 public:
  Dataset(OpKernelContext* ctx, std::unique_ptr<CapturedFunction> init_func,
          std::unique_ptr<CapturedFunction> next_func,
          std::unique_ptr<CapturedFunction> finalize_func,
          const DataTypeVector& output_types,
          const std::vector<PartialTensorShape>& output_shapes)
      : DatasetBase(DatasetContext(ctx)),
        init_func_(std::move(init_func)),
        next_func_(std::move(next_func)),
        finalize_func_(std::move(finalize_func)),
        output_types_(output_types),
        output_shapes_(output_shapes) {}

  std::unique_ptr<IteratorBase> MakeIteratorInternal(
      const string& prefix) const override {
    return std::unique_ptr<IteratorBase>(
        new Iterator({this, strings::StrCat(prefix, "::Generator")}));
  }

  const DataTypeVector& output_dtypes() const override { return output_types_; }

  const std::vector<PartialTensorShape>& output_shapes() const override {
    return output_shapes_;
  }

  string DebugString() const override { return "GeneratorDatasetOp::Dataset"; }

 protected:
  Status AsGraphDefInternal(SerializationContext* ctx,
                            DatasetGraphDefBuilder* b,
                            Node** output) const override {
    return errors::Unimplemented("%s does not support serialization",
                                 DebugString());
  }

 private:
  class Iterator : public DatasetIterator<Dataset> {
   public:
    explicit Iterator(const Params& params)
        : DatasetIterator<Dataset>(params) {}

    ~Iterator() override {
      if (!finalized_) {
        std::vector<Tensor> ignored;
        Status s = dataset()->finalize_func_->RunInstantiated(state_, &ignored);
        if (!s.ok()) {
          LOG(WARNING)
              << "Error occurred when finalizing GeneratorDataset iterator: "
              << s;
        }
      }
    }

    Status Initialize(IteratorContext* ctx) override {
      TF_RETURN_IF_ERROR(dataset()->init_func_->Instantiate(ctx));
      TF_RETURN_IF_ERROR(dataset()->next_func_->Instantiate(ctx));
      TF_RETURN_IF_ERROR(dataset()->finalize_func_->Instantiate(ctx));
      TF_RETURN_IF_ERROR(
          dataset()->init_func_->RunWithBorrowedArgs(ctx, {}, &state_));
      return Status::OK();
    }

    Status GetNextInternal(IteratorContext* ctx,
                           std::vector<Tensor>* out_tensors,
                           bool* end_of_sequence) override {
      mutex_lock l(mu_);

      if (finalized_) {
        *end_of_sequence = true;
        return Status::OK();
      }

      Status s =
          dataset()->next_func_->RunWithBorrowedArgs(ctx, state_, out_tensors);
      if (s.ok()) {
        *end_of_sequence = false;
      } else if (errors::IsOutOfRange(s)) {
        // `next_func` may deliberately raise `errors::OutOfRange`
        // to indicate that we should terminate the iteration.
        s = Status::OK();
        *end_of_sequence = true;

        // NOTE(mrry): We ignore any tensors returned by the
        // finalize function.
        std::vector<Tensor> ignored;
        TF_RETURN_IF_ERROR(
            dataset()->finalize_func_->RunInstantiated(state_, &ignored));
        finalized_ = true;
      }
      return s;
    }

   private:
    mutex mu_;
    bool finalized_ GUARDED_BY(mu_) = false;
    std::vector<Tensor> state_ GUARDED_BY(mu_);
  };

  const std::unique_ptr<CapturedFunction> init_func_;
  const std::unique_ptr<CapturedFunction> next_func_;
  const std::unique_ptr<CapturedFunction> finalize_func_;
  const DataTypeVector output_types_;
  const std::vector<PartialTensorShape> output_shapes_;
};

GeneratorDatasetOp::GeneratorDatasetOp(OpKernelConstruction* ctx)
    : DatasetOpKernel(ctx) {
  OP_REQUIRES_OK(ctx, ctx->GetAttr("init_func", &init_func_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr("next_func", &next_func_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr("finalize_func", &finalize_func_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
}

void GeneratorDatasetOp::MakeDataset(OpKernelContext* ctx,
                                     DatasetBase** output) {
  std::unique_ptr<CapturedFunction> init_func;
  OP_REQUIRES_OK(ctx, CapturedFunction::Create(
                          init_func_, ctx, "init_func_other_args", &init_func));

  std::unique_ptr<CapturedFunction> next_func;
  OP_REQUIRES_OK(ctx, CapturedFunction::Create(
                          next_func_, ctx, "next_func_other_args", &next_func));

  std::unique_ptr<CapturedFunction> finalize_func;
  OP_REQUIRES_OK(ctx, CapturedFunction::Create(finalize_func_, ctx,
                                               "finalize_func_other_args",
                                               &finalize_func));

  *output =
      new Dataset(ctx, std::move(init_func), std::move(next_func),
                  std::move(finalize_func), output_types_, output_shapes_);
}

namespace {
REGISTER_KERNEL_BUILDER(Name("GeneratorDataset").Device(DEVICE_CPU),
                        GeneratorDatasetOp);
REGISTER_KERNEL_BUILDER(
    Name("GeneratorDataset").Device(DEVICE_GPU).HostMemory("handle"),
    GeneratorDatasetOp);
}  // namespace

}  // namespace data
}  // namespace tensorflow
<commit_msg>The GeneratorDataset init function was being run during Initialization which is a blocking Op. Moving it to the GetNext call which is a non blocking async op.<commit_after>/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include <iterator>
#include <vector>

#include "tensorflow/core/kernels/data/generator_dataset_op.h"

#include "tensorflow/core/framework/partial_tensor_shape.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/kernels/data/captured_function.h"
#include "tensorflow/core/lib/random/random.h"

namespace tensorflow {
namespace data {

// See documentation in ../ops/dataset_ops.cc for a high-level
// description of the following op.

class GeneratorDatasetOp::Dataset : public DatasetBase {
 public:
  Dataset(OpKernelContext* ctx, std::unique_ptr<CapturedFunction> init_func,
          std::unique_ptr<CapturedFunction> next_func,
          std::unique_ptr<CapturedFunction> finalize_func,
          const DataTypeVector& output_types,
          const std::vector<PartialTensorShape>& output_shapes)
      : DatasetBase(DatasetContext(ctx)),
        init_func_(std::move(init_func)),
        next_func_(std::move(next_func)),
        finalize_func_(std::move(finalize_func)),
        output_types_(output_types),
        output_shapes_(output_shapes) {}

  std::unique_ptr<IteratorBase> MakeIteratorInternal(
      const string& prefix) const override {
    return std::unique_ptr<IteratorBase>(
        new Iterator({this, strings::StrCat(prefix, "::Generator")}));
  }

  const DataTypeVector& output_dtypes() const override { return output_types_; }

  const std::vector<PartialTensorShape>& output_shapes() const override {
    return output_shapes_;
  }

  string DebugString() const override { return "GeneratorDatasetOp::Dataset"; }

 protected:
  Status AsGraphDefInternal(SerializationContext* ctx,
                            DatasetGraphDefBuilder* b,
                            Node** output) const override {
    return errors::Unimplemented("%s does not support serialization",
                                 DebugString());
  }

 private:
  class Iterator : public DatasetIterator<Dataset> {
   public:
    explicit Iterator(const Params& params)
        : DatasetIterator<Dataset>(params) {}

    ~Iterator() override {
      if (!finalized_) {
        std::vector<Tensor> ignored;
        Status s = dataset()->finalize_func_->RunInstantiated(state_, &ignored);
        if (!s.ok()) {
          LOG(WARNING)
              << "Error occurred when finalizing GeneratorDataset iterator: "
              << s;
        }
      }
    }

    Status Initialize(IteratorContext* ctx) override {
      TF_RETURN_IF_ERROR(dataset()->init_func_->Instantiate(ctx));
      TF_RETURN_IF_ERROR(dataset()->next_func_->Instantiate(ctx));
      TF_RETURN_IF_ERROR(dataset()->finalize_func_->Instantiate(ctx));
      return Status::OK();
    }

    Status GetNextInternal(IteratorContext* ctx,
                           std::vector<Tensor>* out_tensors,
                           bool* end_of_sequence) override {
      mutex_lock l(mu_);

      if (!initialized_) {
        TF_RETURN_IF_ERROR(
            dataset()->init_func_->RunWithBorrowedArgs(ctx, {}, &state_));
        initialized_ = true;
      }

      if (finalized_) {
        *end_of_sequence = true;
        return Status::OK();
      }

      Status s =
          dataset()->next_func_->RunWithBorrowedArgs(ctx, state_, out_tensors);
      if (s.ok()) {
        *end_of_sequence = false;
      } else if (errors::IsOutOfRange(s)) {
        // `next_func` may deliberately raise `errors::OutOfRange`
        // to indicate that we should terminate the iteration.
        s = Status::OK();
        *end_of_sequence = true;

        // NOTE(mrry): We ignore any tensors returned by the
        // finalize function.
        std::vector<Tensor> ignored;
        TF_RETURN_IF_ERROR(
            dataset()->finalize_func_->RunInstantiated(state_, &ignored));
        finalized_ = true;
      }
      return s;
    }

   private:
    mutex mu_;
    bool initialized_ GUARDED_BY(mu_) = false;
    bool finalized_ GUARDED_BY(mu_) = false;
    std::vector<Tensor> state_ GUARDED_BY(mu_);
  };

  const std::unique_ptr<CapturedFunction> init_func_;
  const std::unique_ptr<CapturedFunction> next_func_;
  const std::unique_ptr<CapturedFunction> finalize_func_;
  const DataTypeVector output_types_;
  const std::vector<PartialTensorShape> output_shapes_;
};

GeneratorDatasetOp::GeneratorDatasetOp(OpKernelConstruction* ctx)
    : DatasetOpKernel(ctx) {
  OP_REQUIRES_OK(ctx, ctx->GetAttr("init_func", &init_func_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr("next_func", &next_func_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr("finalize_func", &finalize_func_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr("output_types", &output_types_));
  OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_));
}

void GeneratorDatasetOp::MakeDataset(OpKernelContext* ctx,
                                     DatasetBase** output) {
  std::unique_ptr<CapturedFunction> init_func;
  OP_REQUIRES_OK(ctx, CapturedFunction::Create(
                          init_func_, ctx, "init_func_other_args", &init_func));

  std::unique_ptr<CapturedFunction> next_func;
  OP_REQUIRES_OK(ctx, CapturedFunction::Create(
                          next_func_, ctx, "next_func_other_args", &next_func));

  std::unique_ptr<CapturedFunction> finalize_func;
  OP_REQUIRES_OK(ctx, CapturedFunction::Create(finalize_func_, ctx,
                                               "finalize_func_other_args",
                                               &finalize_func));

  *output =
      new Dataset(ctx, std::move(init_func), std::move(next_func),
                  std::move(finalize_func), output_types_, output_shapes_);
}

namespace {
REGISTER_KERNEL_BUILDER(Name("GeneratorDataset").Device(DEVICE_CPU),
                        GeneratorDatasetOp);
REGISTER_KERNEL_BUILDER(
    Name("GeneratorDataset").Device(DEVICE_GPU).HostMemory("handle"),
    GeneratorDatasetOp);
}  // namespace

}  // namespace data
}  // namespace tensorflow
<|endoftext|>


<commit_before>#include "Arduino.h"
#include "pins.h"
#include "BrolightManager.h"

namespace BrolightState
{
    enum Enum
    {
        Waiting = 0,
        Rising,
        Blink1,
        Clear1,
        Blink2,
        Clear2,
        Blink3,
        Clear3,
        Max
    };
};

BrolightState::Enum s_currentState = BrolightState::Waiting;

void BrolightManager::ShowLights(int strength)
{
    if ((strength < 1) || (strength > 5))
    {
        return;
    }
}

void BrolightManager::ClearLights()
{
    SetLights(cMaxLights, LOW, 0);
}

void BrolightManager::ShowSomeLights(int strength)
{
    SetLights(strength, HIGH, 200);

    delay(500);

    BlinkLights(strength);
    BlinkLights(strength);
    BlinkLights(strength);

    delay(1000);

    SetLights(cMaxLights, LOW, 0);
}

void BrolightManager::SetLights(int cLights, int value, int msDelay)
{
    for (int i = 0; i < cLights; i++)
    {
        digitalWrite(rgLights[i], value);
        delay(msDelay);
    }
}

void BrolightManager::BlinkLights(int cLights)
{
    const int msDelay = 400;

    SetLights(cLights, LOW, 0);
    delay(400);

    SetLights(cLights, HIGH, 0);
    delay(400);
}

<commit_msg>Initialing BrolightManager's async state<commit_after>#include "Arduino.h"
#include "pins.h"
#include "BrolightManager.h"

namespace BrolightState
{
    enum Enum
    {
        Waiting = 0,
        Rising,
        Blink1,
        Clear1,
        Blink2,
        Clear2,
        Blink3,
        Clear3,
        Max
    };
};

BrolightState::Enum s_currentState = BrolightState::Waiting;
int s_iMaxStrength = 0;
int s_iCurrentStength = 0;

void BrolightManager::ShowLights(int strength)
{
    if ((strength < 1) || (strength > 5))
    {
        return;
    }

    s_currentState = BrolightState::Rising;
    s_iMaxStength = strength;
    s_iCurrentStrength = 0;
}

void BrolightManager::ClearLights()
{
    SetLights(cMaxLights, LOW, 0);
}

void BrolightManager::ShowSomeLights(int strength)
{
    SetLights(strength, HIGH, 200);

    delay(500);

    BlinkLights(strength);
    BlinkLights(strength);
    BlinkLights(strength);

    delay(1000);

    SetLights(cMaxLights, LOW, 0);
}

void BrolightManager::SetLights(int cLights, int value, int msDelay)
{
    for (int i = 0; i < cLights; i++)
    {
        digitalWrite(rgLights[i], value);
        delay(msDelay);
    }
}

void BrolightManager::BlinkLights(int cLights)
{
    const int msDelay = 400;

    SetLights(cLights, LOW, 0);
    delay(400);

    SetLights(cLights, HIGH, 0);
    delay(400);
}

<|endoftext|>


<commit_before>//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This checker flags misuses of KeyChainAPI. In particular, the password data
// allocated/returned by SecKeychainItemCopyContent,
// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
// to be freed using a call to SecKeychainItemFreeContent.
//===----------------------------------------------------------------------===//

#include "ClangSACheckers.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"

using namespace clang;
using namespace ento;

namespace {
class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
                                               check::PreStmt<ReturnStmt>,
                                               check::PostStmt<CallExpr>,
                                               check::EndPath > {
  mutable llvm::OwningPtr<BugType> BT;

public:
  void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
  void checkPostStmt(const CallExpr *S, CheckerContext &C) const;

  void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;

private:
  /// Stores the information about the allocator and deallocator functions -
  /// these are the functions the checker is tracking.
  struct ADFunctionInfo {
    const char* Name;
    unsigned int Param;
    unsigned int DeallocatorIdx;
  };
  static const unsigned InvalidIdx = 100000;
  static const unsigned FunctionsToTrackSize = 6;
  static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
  /// The value, which represents no error return value for allocator functions.
  static const unsigned NoErr = 0;

  /// Given the function name, returns the index of the allocator/deallocator
  /// function.
  unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const;

  inline void initBugType() const {
    if (!BT)
      BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
  }
};
}

/// AllocationState is a part of the checker specific state together with the
/// MemRegion corresponding to the allocated data.
struct AllocationState {
  const Expr *Address;
  /// The index of the allocator function.
  unsigned int AllocatorIdx;
  SymbolRef RetValue;

  AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
    Address(E),
    AllocatorIdx(Idx),
    RetValue(R) {}

  bool operator==(const AllocationState &X) const {
    return Address == X.Address;
  }
  void Profile(llvm::FoldingSetNodeID &ID) const {
    ID.AddPointer(Address);
    ID.AddInteger(AllocatorIdx);
  }
};

/// GRState traits to store the currently allocated (and not yet freed) symbols.
typedef llvm::ImmutableMap<const SymbolMetadata *,
                           AllocationState> AllocatedSetTy;

namespace { struct AllocatedData {}; }
namespace clang { namespace ento {
template<> struct GRStateTrait<AllocatedData>
    :  public GRStatePartialTrait<AllocatedSetTy > {
  static void *GDMIndex() { static int index = 0; return &index; }
};
}}

static bool isEnclosingFunctionParam(const Expr *E) {
  E = E->IgnoreParenCasts();
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
    const ValueDecl *VD = DRE->getDecl();
    if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
      return true;
  }
  return false;
}

const MacOSKeychainAPIChecker::ADFunctionInfo
  MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
    {"SecKeychainItemCopyContent", 4, 3},                       // 0
    {"SecKeychainFindGenericPassword", 6, 3},                   // 1
    {"SecKeychainFindInternetPassword", 13, 3},                 // 2
    {"SecKeychainItemFreeContent", 1, InvalidIdx},              // 3
    {"SecKeychainItemCopyAttributesAndData", 5, 5},             // 4
    {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx},    // 5
};

unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
                                                       bool IsAllocator) const {
  for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
    ADFunctionInfo FI = FunctionsToTrack[I];
    if (FI.Name != Name)
      continue;
    // Make sure the function is of the right type (allocator vs deallocator).
    if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
      return InvalidIdx;
    if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
      return InvalidIdx;

    return I;
  }
  // The function is not tracked.
  return InvalidIdx;
}

static const SymbolMetadata *getSymbolMetadata(CheckerContext &C,
                                               const MemRegion *R) {
  QualType sizeTy = C.getSValBuilder().getContext().getSizeType();
  return C.getSymbolManager().getMetadataSymbol(R, 0, sizeTy, 0);
}

/// Given the address expression, retrieve the value it's pointing to. Assume
/// that value is itself an address, and return the corresponding MemRegion.
static const SymbolMetadata *getAsPointeeMemoryRegion(const Expr *Expr,
                                                      CheckerContext &C) {
  const GRState *State = C.getState();
  SVal ArgV = State->getSVal(Expr);

  if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
    StoreManager& SM = C.getStoreManager();
    const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
    if (V)
      return getSymbolMetadata(C, V);
  }
  return 0;
}

void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
                                           CheckerContext &C) const {
  const GRState *State = C.getState();
  const Expr *Callee = CE->getCallee();
  SVal L = State->getSVal(Callee);
  unsigned idx = InvalidIdx;

  const FunctionDecl *funDecl = L.getAsFunctionDecl();
  if (!funDecl)
    return;
  IdentifierInfo *funI = funDecl->getIdentifier();
  if (!funI)
    return;
  StringRef funName = funI->getName();

  // If it is a call to an allocator function, it could be a double allocation.
  idx = getTrackedFunctionIndex(funName, true);
  if (idx != InvalidIdx) {
    const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
    if (const SymbolMetadata *V = getAsPointeeMemoryRegion(ArgExpr, C))
      if (const AllocationState *AS = State->get<AllocatedData>(V)) {
        ExplodedNode *N = C.generateSink(State);
        if (!N)
          return;
        initBugType();
        std::string sbuf;
        llvm::raw_string_ostream os(sbuf);
        unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
        os << "Allocated data should be released before another call to "
           << "the allocator: missing a call to '"
           << FunctionsToTrack[DIdx].Name
           << "'.";
        RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N);
        Report->addRange(ArgExpr->getSourceRange());
        C.EmitReport(Report);
      }
    return;
  }

  // Is it a call to one of deallocator functions?
  idx = getTrackedFunctionIndex(funName, false);
  if (idx == InvalidIdx)
    return;

  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
  const MemRegion *Arg = State->getSVal(ArgExpr).getAsRegion();
  if (!Arg)
    return;
  const SymbolMetadata *ArgSM = getSymbolMetadata(C, Arg);

  // If trying to free data which has not been allocated yet, report as bug.
  const AllocationState *AS = State->get<AllocatedData>(ArgSM);
  if (!AS) {
    // It is possible that this is a false positive - the argument might
    // have entered as an enclosing function parameter.
    if (isEnclosingFunctionParam(ArgExpr))
      return;

    ExplodedNode *N = C.generateNode(State);
    if (!N)
      return;
    initBugType();
    RangedBugReport *Report = new RangedBugReport(*BT,
        "Trying to free data which has not been allocated.", N);
    Report->addRange(ArgExpr->getSourceRange());
    C.EmitReport(Report);
    return;
  }

  // Check if the proper deallocator is used.
  unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
  if (PDeallocIdx != idx) {
    ExplodedNode *N = C.generateSink(State);
    if (!N)
      return;
    initBugType();

    std::string sbuf;
    llvm::raw_string_ostream os(sbuf);
    os << "Allocator doesn't match the deallocator: '"
       << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
    RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N);
    Report->addRange(ArgExpr->getSourceRange());
    C.EmitReport(Report);
    return;
  }

  // If a value has been freed, remove it from the list and continue exploring
  // from the new state.
  State = State->remove<AllocatedData>(ArgSM);
  C.addTransition(State);
}

void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
                                            CheckerContext &C) const {
  const GRState *State = C.getState();
  const Expr *Callee = CE->getCallee();
  SVal L = State->getSVal(Callee);

  const FunctionDecl *funDecl = L.getAsFunctionDecl();
  if (!funDecl)
    return;
  IdentifierInfo *funI = funDecl->getIdentifier();
  if (!funI)
    return;
  StringRef funName = funI->getName();

  // If a value has been allocated, add it to the set for tracking.
  unsigned idx = getTrackedFunctionIndex(funName, true);
  if (idx == InvalidIdx)
    return;

  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
  if (const SymbolMetadata *V = getAsPointeeMemoryRegion(ArgExpr, C)) {
    // If the argument points to something that's not a region, it can be:
    //  - unknown (cannot reason about it)
    //  - undefined (already reported by other checker)
    //  - constant (null - should not be tracked,
    //              other constant will generate a compiler warning)
    //  - goto (should be reported by other checker)

    // We only need to track the value if the function returned noErr(0), so
    // bind the return value of the function to 0 and proceed from the no error
    // state.
    SValBuilder &Builder = C.getSValBuilder();
    SVal NoErrVal = Builder.makeIntVal(NoErr, CE->getCallReturnType());
    const GRState *NoErr = State->BindExpr(CE, NoErrVal);
    // Add the symbolic value V, which represents the location of the allocated
    // data, to the set.
    NoErr = NoErr->set<AllocatedData>(V,
      AllocationState(ArgExpr, idx, State->getSVal(CE).getAsSymbol()));

    assert(NoErr);
    C.addTransition(NoErr);

    // Generate a transition to explore the state space when there is an error.
    // In this case, we do not track the allocated data.
    SVal ReturnedError = Builder.evalBinOpNN(State, BO_NE,
                                             cast<NonLoc>(NoErrVal),
                                             cast<NonLoc>(State->getSVal(CE)),
                                             CE->getCallReturnType());
    const GRState *Err = State->assume(cast<NonLoc>(ReturnedError), true);
    assert(Err);
    C.addTransition(Err);
  }
}

void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
                                           CheckerContext &C) const {
  const Expr *retExpr = S->getRetValue();
  if (!retExpr)
    return;

  // Check  if the value is escaping through the return.
  const GRState *state = C.getState();
  const MemRegion *V = state->getSVal(retExpr).getAsRegion();
  if (!V)
    return;
  state = state->remove<AllocatedData>(getSymbolMetadata(C, V));

  // Proceed from the new state.
  C.addTransition(state);
}

void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
                                           ExprEngine &Eng) const {
  const GRState *state = B.getState();
  AllocatedSetTy AS = state->get<AllocatedData>();
  ExplodedNode *N = B.generateNode(state);
  if (!N)
    return;
  initBugType();

  // Anything which has been allocated but not freed (nor escaped) will be
  // found here, so report it.
  for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
    const ADFunctionInfo &FI = FunctionsToTrack[I->second.AllocatorIdx];

    std::string sbuf;
    llvm::raw_string_ostream os(sbuf);
    os << "Allocated data is not released: missing a call to '"
       << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
    RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N);
    // TODO: The report has to mention the expression which contains the
    // allocated content as well as the point at which it has been allocated.
    // Currently, the next line is useless.
    Report->addRange(I->second.Address->getSourceRange());
    Eng.getBugReporter().EmitReport(Report);
  }
}

void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
  mgr.registerChecker<MacOSKeychainAPIChecker>();
}
<commit_msg>MacOSKeychainAPIChecker: There is no need to use SymbolMetadata to represent the allocated data symbol, we can just use the symbol corresponding to the SymbolicRegion. This simplifies tracking of the symbol, for example, SymbolMetadata needs to go through extra hoops to stay alive.<commit_after>//==--- MacOSKeychainAPIChecker.cpp ------------------------------*- C++ -*-==//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// This checker flags misuses of KeyChainAPI. In particular, the password data
// allocated/returned by SecKeychainItemCopyContent,
// SecKeychainFindGenericPassword, SecKeychainFindInternetPassword functions has
// to be freed using a call to SecKeychainItemFreeContent.
//===----------------------------------------------------------------------===//

#include "ClangSACheckers.h"
#include "clang/StaticAnalyzer/Core/Checker.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Core/BugReporter/BugType.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/CheckerContext.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/GRState.h"
#include "clang/StaticAnalyzer/Core/PathSensitive/GRStateTrait.h"

using namespace clang;
using namespace ento;

namespace {
class MacOSKeychainAPIChecker : public Checker<check::PreStmt<CallExpr>,
                                               check::PreStmt<ReturnStmt>,
                                               check::PostStmt<CallExpr>,
                                               check::EndPath > {
  mutable llvm::OwningPtr<BugType> BT;

public:
  /// AllocationState is a part of the checker specific state together with the
  /// MemRegion corresponding to the allocated data.
  struct AllocationState {
    const Expr *Address;
    /// The index of the allocator function.
    unsigned int AllocatorIdx;
    SymbolRef RetValue;

    AllocationState(const Expr *E, unsigned int Idx, SymbolRef R) :
      Address(E),
      AllocatorIdx(Idx),
      RetValue(R) {}

    bool operator==(const AllocationState &X) const {
      return Address == X.Address;
    }
    void Profile(llvm::FoldingSetNodeID &ID) const {
      ID.AddPointer(Address);
      ID.AddInteger(AllocatorIdx);
    }
  };

  void checkPreStmt(const CallExpr *S, CheckerContext &C) const;
  void checkPreStmt(const ReturnStmt *S, CheckerContext &C) const;
  void checkPostStmt(const CallExpr *S, CheckerContext &C) const;

  void checkEndPath(EndOfFunctionNodeBuilder &B, ExprEngine &Eng) const;

private:
  /// Stores the information about the allocator and deallocator functions -
  /// these are the functions the checker is tracking.
  struct ADFunctionInfo {
    const char* Name;
    unsigned int Param;
    unsigned int DeallocatorIdx;
  };
  static const unsigned InvalidIdx = 100000;
  static const unsigned FunctionsToTrackSize = 6;
  static const ADFunctionInfo FunctionsToTrack[FunctionsToTrackSize];
  /// The value, which represents no error return value for allocator functions.
  static const unsigned NoErr = 0;

  /// Given the function name, returns the index of the allocator/deallocator
  /// function.
  unsigned getTrackedFunctionIndex(StringRef Name, bool IsAllocator) const;

  inline void initBugType() const {
    if (!BT)
      BT.reset(new BugType("Improper use of SecKeychain API", "Mac OS API"));
  }
};
}

/// GRState traits to store the currently allocated (and not yet freed) symbols.
/// This is a map from the allocated content symbol to the corresponding
/// AllocationState.
typedef llvm::ImmutableMap<SymbolRef,
                       MacOSKeychainAPIChecker::AllocationState> AllocatedSetTy;

namespace { struct AllocatedData {}; }
namespace clang { namespace ento {
template<> struct GRStateTrait<AllocatedData>
    :  public GRStatePartialTrait<AllocatedSetTy > {
  static void *GDMIndex() { static int index = 0; return &index; }
};
}}

static bool isEnclosingFunctionParam(const Expr *E) {
  E = E->IgnoreParenCasts();
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
    const ValueDecl *VD = DRE->getDecl();
    if (isa<ImplicitParamDecl>(VD) || isa<ParmVarDecl>(VD))
      return true;
  }
  return false;
}

const MacOSKeychainAPIChecker::ADFunctionInfo
  MacOSKeychainAPIChecker::FunctionsToTrack[FunctionsToTrackSize] = {
    {"SecKeychainItemCopyContent", 4, 3},                       // 0
    {"SecKeychainFindGenericPassword", 6, 3},                   // 1
    {"SecKeychainFindInternetPassword", 13, 3},                 // 2
    {"SecKeychainItemFreeContent", 1, InvalidIdx},              // 3
    {"SecKeychainItemCopyAttributesAndData", 5, 5},             // 4
    {"SecKeychainItemFreeAttributesAndData", 1, InvalidIdx},    // 5
};

unsigned MacOSKeychainAPIChecker::getTrackedFunctionIndex(StringRef Name,
                                                       bool IsAllocator) const {
  for (unsigned I = 0; I < FunctionsToTrackSize; ++I) {
    ADFunctionInfo FI = FunctionsToTrack[I];
    if (FI.Name != Name)
      continue;
    // Make sure the function is of the right type (allocator vs deallocator).
    if (IsAllocator && (FI.DeallocatorIdx == InvalidIdx))
      return InvalidIdx;
    if (!IsAllocator && (FI.DeallocatorIdx != InvalidIdx))
      return InvalidIdx;

    return I;
  }
  // The function is not tracked.
  return InvalidIdx;
}

static SymbolRef getSymbolForRegion(CheckerContext &C,
                                   const MemRegion *R) {
  if (!isa<SymbolicRegion>(R))
    return 0;
  return cast<SymbolicRegion>(R)->getSymbol();
}

static bool isBadDeallocationArgument(const MemRegion *Arg) {
  if (isa<AllocaRegion>(Arg) ||
      isa<BlockDataRegion>(Arg) ||
      isa<TypedRegion>(Arg)) {
    return true;
  }
  return false;
}
/// Given the address expression, retrieve the value it's pointing to. Assume
/// that value is itself an address, and return the corresponding symbol.
static SymbolRef getAsPointeeSymbol(const Expr *Expr,
                                    CheckerContext &C) {
  const GRState *State = C.getState();
  SVal ArgV = State->getSVal(Expr);

  if (const loc::MemRegionVal *X = dyn_cast<loc::MemRegionVal>(&ArgV)) {
    StoreManager& SM = C.getStoreManager();
    const MemRegion *V = SM.Retrieve(State->getStore(), *X).getAsRegion();
    if (V)
      return getSymbolForRegion(C, V);
  }
  return 0;
}

void MacOSKeychainAPIChecker::checkPreStmt(const CallExpr *CE,
                                           CheckerContext &C) const {
  const GRState *State = C.getState();
  const Expr *Callee = CE->getCallee();
  SVal L = State->getSVal(Callee);
  unsigned idx = InvalidIdx;

  const FunctionDecl *funDecl = L.getAsFunctionDecl();
  if (!funDecl)
    return;
  IdentifierInfo *funI = funDecl->getIdentifier();
  if (!funI)
    return;
  StringRef funName = funI->getName();

  // If it is a call to an allocator function, it could be a double allocation.
  idx = getTrackedFunctionIndex(funName, true);
  if (idx != InvalidIdx) {
    const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
    if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C))
      if (const AllocationState *AS = State->get<AllocatedData>(V)) {
        ExplodedNode *N = C.generateSink(State);
        if (!N)
          return;
        initBugType();
        std::string sbuf;
        llvm::raw_string_ostream os(sbuf);
        unsigned int DIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
        os << "Allocated data should be released before another call to "
           << "the allocator: missing a call to '"
           << FunctionsToTrack[DIdx].Name
           << "'.";
        RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N);
        Report->addRange(ArgExpr->getSourceRange());
        C.EmitReport(Report);
      }
    return;
  }

  // Is it a call to one of deallocator functions?
  idx = getTrackedFunctionIndex(funName, false);
  if (idx == InvalidIdx)
    return;

  // Check the argument to the deallocator.
  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
  SVal ArgSVal = State->getSVal(ArgExpr);

  // Undef is reported by another checker.
  if (ArgSVal.isUndef())
    return;

  const MemRegion *Arg = ArgSVal.getAsRegion();
  if (!Arg)
    return;

  SymbolRef ArgSM = getSymbolForRegion(C, Arg);
  bool RegionArgIsBad = ArgSM ? false : isBadDeallocationArgument(Arg);
  // If the argument is coming from the heap, globals, or unknown, do not
  // report it.
  if (!ArgSM && !RegionArgIsBad)
    return;

  // If trying to free data which has not been allocated yet, report as bug.
  const AllocationState *AS = State->get<AllocatedData>(ArgSM);
  if (!AS || RegionArgIsBad) {
    // It is possible that this is a false positive - the argument might
    // have entered as an enclosing function parameter.
    if (isEnclosingFunctionParam(ArgExpr))
      return;

    ExplodedNode *N = C.generateNode(State);
    if (!N)
      return;
    initBugType();
    RangedBugReport *Report = new RangedBugReport(*BT,
        "Trying to free data which has not been allocated.", N);
    Report->addRange(ArgExpr->getSourceRange());
    C.EmitReport(Report);
    return;
  }

  // Check if the proper deallocator is used.
  unsigned int PDeallocIdx = FunctionsToTrack[AS->AllocatorIdx].DeallocatorIdx;
  if (PDeallocIdx != idx) {
    ExplodedNode *N = C.generateSink(State);
    if (!N)
      return;
    initBugType();

    std::string sbuf;
    llvm::raw_string_ostream os(sbuf);
    os << "Allocator doesn't match the deallocator: '"
       << FunctionsToTrack[PDeallocIdx].Name << "' should be used.";
    RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N);
    Report->addRange(ArgExpr->getSourceRange());
    C.EmitReport(Report);
    return;
  }

  // The call is deallocating a value we previously allocated, so remove it
  // from the next state.
  State = State->remove<AllocatedData>(ArgSM);
  C.addTransition(State);
}

void MacOSKeychainAPIChecker::checkPostStmt(const CallExpr *CE,
                                            CheckerContext &C) const {
  const GRState *State = C.getState();
  const Expr *Callee = CE->getCallee();
  SVal L = State->getSVal(Callee);

  const FunctionDecl *funDecl = L.getAsFunctionDecl();
  if (!funDecl)
    return;
  IdentifierInfo *funI = funDecl->getIdentifier();
  if (!funI)
    return;
  StringRef funName = funI->getName();

  // If a value has been allocated, add it to the set for tracking.
  unsigned idx = getTrackedFunctionIndex(funName, true);
  if (idx == InvalidIdx)
    return;

  const Expr *ArgExpr = CE->getArg(FunctionsToTrack[idx].Param);
  if (SymbolRef V = getAsPointeeSymbol(ArgExpr, C)) {
    // If the argument points to something that's not a symbolic region, it
    // can be:
    //  - unknown (cannot reason about it)
    //  - undefined (already reported by other checker)
    //  - constant (null - should not be tracked,
    //              other constant will generate a compiler warning)
    //  - goto (should be reported by other checker)

    // We only need to track the value if the function returned noErr(0), so
    // bind the return value of the function to 0 and proceed from the no error
    // state.
    SValBuilder &Builder = C.getSValBuilder();
    SVal NoErrVal = Builder.makeIntVal(NoErr, CE->getCallReturnType());
    const GRState *NoErr = State->BindExpr(CE, NoErrVal);
    // Add the symbolic value V, which represents the location of the allocated
    // data, to the set.
    SymbolRef RetStatusSymbol = State->getSVal(CE).getAsSymbol();
    NoErr = NoErr->set<AllocatedData>(V, AllocationState(ArgExpr, idx,
                                                         RetStatusSymbol));

    assert(NoErr);
    C.addTransition(NoErr);

    // Generate a transition to explore the state space when there is an error.
    // In this case, we do not track the allocated data.
    SVal ReturnedError = Builder.evalBinOpNN(State, BO_NE,
                                             cast<NonLoc>(NoErrVal),
                                             cast<NonLoc>(State->getSVal(CE)),
                                             CE->getCallReturnType());
    const GRState *Err = State->assume(cast<NonLoc>(ReturnedError), true);
    assert(Err);
    C.addTransition(Err);
  }
}

void MacOSKeychainAPIChecker::checkPreStmt(const ReturnStmt *S,
                                           CheckerContext &C) const {
  const Expr *retExpr = S->getRetValue();
  if (!retExpr)
    return;

  // Check  if the value is escaping through the return.
  const GRState *state = C.getState();
  const MemRegion *V = state->getSVal(retExpr).getAsRegion();
  if (!V)
    return;
  state = state->remove<AllocatedData>(getSymbolForRegion(C, V));

  // Proceed from the new state.
  C.addTransition(state);
}

void MacOSKeychainAPIChecker::checkEndPath(EndOfFunctionNodeBuilder &B,
                                           ExprEngine &Eng) const {
  const GRState *state = B.getState();
  AllocatedSetTy AS = state->get<AllocatedData>();
  ExplodedNode *N = B.generateNode(state);
  if (!N)
    return;
  initBugType();

  // Anything which has been allocated but not freed (nor escaped) will be
  // found here, so report it.
  for (AllocatedSetTy::iterator I = AS.begin(), E = AS.end(); I != E; ++I ) {
    const ADFunctionInfo &FI = FunctionsToTrack[I->second.AllocatorIdx];

    std::string sbuf;
    llvm::raw_string_ostream os(sbuf);
    os << "Allocated data is not released: missing a call to '"
       << FunctionsToTrack[FI.DeallocatorIdx].Name << "'.";
    RangedBugReport *Report = new RangedBugReport(*BT, os.str(), N);
    // TODO: The report has to mention the expression which contains the
    // allocated content as well as the point at which it has been allocated.
    // Currently, the next line is useless.
    Report->addRange(I->second.Address->getSourceRange());
    Eng.getBugReporter().EmitReport(Report);
  }
}

void ento::registerMacOSKeychainAPIChecker(CheckerManager &mgr) {
  mgr.registerChecker<MacOSKeychainAPIChecker>();
}
<|endoftext|>