<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program EGL Module
 * ---------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief Simple Context construction test.
 *//*--------------------------------------------------------------------*/

#include "teglCreateContextTests.hpp"
#include "teglSimpleConfigCase.hpp"
#include "egluStrUtil.hpp"
#include "egluUtil.hpp"
#include "egluUnique.hpp"
#include "eglwLibrary.hpp"
#include "eglwEnums.hpp"
#include "tcuTestLog.hpp"
#include "deSTLUtil.hpp"

namespace deqp
{
namespace egl
{

using std::vector;
using tcu::TestLog;
using namespace eglw;

static const EGLint s_es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION,	1, EGL_NONE };
static const EGLint s_es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION,	2, EGL_NONE };
static const EGLint s_es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR,	3, EGL_NONE };

static const struct
{
	const char*		name;
	EGLenum			api;
	EGLint			apiBit;
	const EGLint*	ctxAttrs;
} s_apis[] =
{
	{ "OpenGL",			EGL_OPENGL_API,		EGL_OPENGL_BIT,			DE_NULL		},
	{ "OpenGL ES 1",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES_BIT,		s_es1Attrs	},
	{ "OpenGL ES 2",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES2_BIT,		s_es2Attrs	},
	{ "OpenGL ES 3",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES3_BIT_KHR,	s_es3Attrs	},
	{ "OpenVG",			EGL_OPENVG_API,		EGL_OPENVG_BIT,			DE_NULL		}
};

class CreateContextCase : public SimpleConfigCase
{
public:
						CreateContextCase			(EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters);
						~CreateContextCase			(void);

	void				executeForConfig			(EGLDisplay display, EGLConfig config);
};

CreateContextCase::CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters)
	: SimpleConfigCase(eglTestCtx, name, description, filters)
{
}

CreateContextCase::~CreateContextCase (void)
{
}

void CreateContextCase::executeForConfig (EGLDisplay display, EGLConfig config)
{
	const Library&	egl		= m_eglTestCtx.getLibrary();
	TestLog&		log		= m_testCtx.getLog();
	EGLint			id		= eglu::getConfigAttribInt(egl, display, config, EGL_CONFIG_ID);
	EGLint			apiBits	= eglu::getConfigAttribInt(egl, display, config, EGL_RENDERABLE_TYPE);

	for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
	{
		if ((apiBits & s_apis[apiNdx].apiBit) == 0)
			continue; // Not supported API

		log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context with config ID " << id << TestLog::EndMessage;
		EGLU_CHECK_MSG(egl, "init");

		EGLU_CHECK_CALL(egl, bindAPI(s_apis[apiNdx].api));

		EGLContext	context = egl.createContext(display, config, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
		EGLenum		err		= egl.getError();

		if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
		{
			log << TestLog::Message << "  Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
			m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
		}
		else
		{
			// Destroy
			EGLU_CHECK_CALL(egl, destroyContext(display, context));
			log << TestLog::Message << "  Pass" << TestLog::EndMessage;
		}
	}
}

class CreateContextNoConfigCase : public TestCase
{
public:
	CreateContextNoConfigCase (EglTestContext& eglTestCtx)
		: TestCase(eglTestCtx, "no_config", "EGL_KHR_no_config_context")
	{
	}

	IterateResult iterate (void)
	{
		const eglw::Library&		egl		= m_eglTestCtx.getLibrary();
		const eglu::UniqueDisplay	display	(egl, eglu::getAndInitDisplay(m_eglTestCtx.getNativeDisplay(), DE_NULL));
		tcu::TestLog&				log		= m_testCtx.getLog();

		if (!eglu::hasExtension(egl, *display, "EGL_KHR_no_config_context"))
			TCU_THROW(NotSupportedError, "EGL_KHR_no_config_context is not supported");

		m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "pass");

		for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
		{
			const EGLenum	api		= s_apis[apiNdx].api;

			if (egl.bindAPI(api) == EGL_FALSE)
			{
				TCU_CHECK(egl.getError() == EGL_BAD_PARAMETER);
				log << TestLog::Message << "eglBindAPI(" << eglu::getAPIStr(api) << ") failed, skipping" << TestLog::EndMessage;
				continue;
			}

			log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context" << TestLog::EndMessage;

			const EGLContext	context = egl.createContext(*display, (EGLConfig)0, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
			const EGLenum		err		= egl.getError();

			if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
			{
				log << TestLog::Message << "  Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
				m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
			}
			else
			{
				// Destroy
				EGLU_CHECK_CALL(egl, destroyContext(*display, context));
				log << TestLog::Message << "  Pass" << TestLog::EndMessage;
			}
		}

		return STOP;
	}
};

CreateContextTests::CreateContextTests (EglTestContext& eglTestCtx)
	: TestCaseGroup(eglTestCtx, "create_context", "Basic eglCreateContext() tests")
{
}

CreateContextTests::~CreateContextTests (void)
{
}

void CreateContextTests::init (void)
{
	vector<NamedFilterList>	filterLists;
	getDefaultFilterLists(filterLists, eglu::FilterList());

	for (vector<NamedFilterList>::iterator i = filterLists.begin(); i != filterLists.end(); i++)
		addChild(new CreateContextCase(m_eglTestCtx, i->getName(), i->getDescription(), *i));

	addChild(new CreateContextNoConfigCase(m_eglTestCtx));
}

} // egl
} // deqp
<commit_msg>Handle unsupported no_config contexts am: b60ae978ad am: 307c716b4e am: d217b05e1c<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program EGL Module
 * ---------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 *//*!
 * \file
 * \brief Simple Context construction test.
 *//*--------------------------------------------------------------------*/

#include "teglCreateContextTests.hpp"
#include "teglSimpleConfigCase.hpp"
#include "egluStrUtil.hpp"
#include "egluUtil.hpp"
#include "egluUnique.hpp"
#include "eglwLibrary.hpp"
#include "eglwEnums.hpp"
#include "tcuTestLog.hpp"
#include "deSTLUtil.hpp"

namespace deqp
{
namespace egl
{

using std::vector;
using tcu::TestLog;
using namespace eglw;

static const EGLint s_glAttrs[]  = { EGL_CONTEXT_MAJOR_VERSION_KHR,	3, EGL_NONE };
static const EGLint s_es1Attrs[] = { EGL_CONTEXT_CLIENT_VERSION,	1, EGL_NONE };
static const EGLint s_es2Attrs[] = { EGL_CONTEXT_CLIENT_VERSION,	2, EGL_NONE };
static const EGLint s_es3Attrs[] = { EGL_CONTEXT_MAJOR_VERSION_KHR,	3, EGL_NONE };

static const struct
{
	const char*		name;
	EGLenum			api;
	EGLint			apiBit;
	bool			noConfigOptional;
	const EGLint*	ctxAttrs;
} s_apis[] =
{
	{ "OpenGL",			EGL_OPENGL_API,		EGL_OPENGL_BIT,			false,	s_glAttrs	},
	{ "OpenGL ES 1",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES_BIT,		true,	s_es1Attrs	},
	{ "OpenGL ES 2",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES2_BIT,		true,	s_es2Attrs	},
	{ "OpenGL ES 3",	EGL_OPENGL_ES_API,	EGL_OPENGL_ES3_BIT_KHR,	false,	s_es3Attrs	},
	{ "OpenVG",			EGL_OPENVG_API,		EGL_OPENVG_BIT,			false,	DE_NULL		}
};

class CreateContextCase : public SimpleConfigCase
{
public:
						CreateContextCase			(EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters);
						~CreateContextCase			(void);

	void				executeForConfig			(EGLDisplay display, EGLConfig config);
};

CreateContextCase::CreateContextCase (EglTestContext& eglTestCtx, const char* name, const char* description, const eglu::FilterList& filters)
	: SimpleConfigCase(eglTestCtx, name, description, filters)
{
}

CreateContextCase::~CreateContextCase (void)
{
}

void CreateContextCase::executeForConfig (EGLDisplay display, EGLConfig config)
{
	const Library&	egl		= m_eglTestCtx.getLibrary();
	TestLog&		log		= m_testCtx.getLog();
	EGLint			id		= eglu::getConfigAttribInt(egl, display, config, EGL_CONFIG_ID);
	EGLint			apiBits	= eglu::getConfigAttribInt(egl, display, config, EGL_RENDERABLE_TYPE);

	for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
	{
		if ((apiBits & s_apis[apiNdx].apiBit) == 0)
			continue; // Not supported API

		log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context with config ID " << id << TestLog::EndMessage;
		EGLU_CHECK_MSG(egl, "init");

		EGLU_CHECK_CALL(egl, bindAPI(s_apis[apiNdx].api));

		EGLContext	context = egl.createContext(display, config, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
		EGLenum		err		= egl.getError();

		if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
		{
			log << TestLog::Message << "  Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
			m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
		}
		else
		{
			// Destroy
			EGLU_CHECK_CALL(egl, destroyContext(display, context));
			log << TestLog::Message << "  Pass" << TestLog::EndMessage;
		}
	}
}

class CreateContextNoConfigCase : public TestCase
{
public:
	CreateContextNoConfigCase (EglTestContext& eglTestCtx)
		: TestCase(eglTestCtx, "no_config", "EGL_KHR_no_config_context")
	{
	}

	IterateResult iterate (void)
	{
		const eglw::Library&		egl		= m_eglTestCtx.getLibrary();
		const eglu::UniqueDisplay	display	(egl, eglu::getAndInitDisplay(m_eglTestCtx.getNativeDisplay(), DE_NULL));
		tcu::TestLog&				log		= m_testCtx.getLog();

		if (!eglu::hasExtension(egl, *display, "EGL_KHR_no_config_context"))
			TCU_THROW(NotSupportedError, "EGL_KHR_no_config_context is not supported");

		m_testCtx.setTestResult(QP_TEST_RESULT_PASS, "pass");

		for (int apiNdx = 0; apiNdx < (int)DE_LENGTH_OF_ARRAY(s_apis); apiNdx++)
		{
			const EGLenum	api		= s_apis[apiNdx].api;

			if (egl.bindAPI(api) == EGL_FALSE)
			{
				TCU_CHECK(egl.getError() == EGL_BAD_PARAMETER);
				log << TestLog::Message << "eglBindAPI(" << eglu::getAPIStr(api) << ") failed, skipping" << TestLog::EndMessage;
				continue;
			}

			log << TestLog::Message << "Creating " << s_apis[apiNdx].name << " context" << TestLog::EndMessage;

			const EGLContext	context = egl.createContext(*display, (EGLConfig)0, EGL_NO_CONTEXT, s_apis[apiNdx].ctxAttrs);
			const EGLenum		err		= egl.getError();

			if (context == EGL_NO_CONTEXT && err == EGL_BAD_MATCH && s_apis[apiNdx].noConfigOptional)
			{
				log << TestLog::Message << "  Unsupported" << TestLog::EndMessage;
			}
			else if (context == EGL_NO_CONTEXT || err != EGL_SUCCESS)
			{
				log << TestLog::Message << "  Fail, context: " << tcu::toHex(context) << ", error: " << eglu::getErrorName(err) << TestLog::EndMessage;
				m_testCtx.setTestResult(QP_TEST_RESULT_FAIL, "Failed to create context");
			}
			else
			{
				// Destroy
				EGLU_CHECK_CALL(egl, destroyContext(*display, context));
				log << TestLog::Message << "  Pass" << TestLog::EndMessage;
			}
		}

		return STOP;
	}
};

CreateContextTests::CreateContextTests (EglTestContext& eglTestCtx)
	: TestCaseGroup(eglTestCtx, "create_context", "Basic eglCreateContext() tests")
{
}

CreateContextTests::~CreateContextTests (void)
{
}

void CreateContextTests::init (void)
{
	vector<NamedFilterList>	filterLists;
	getDefaultFilterLists(filterLists, eglu::FilterList());

	for (vector<NamedFilterList>::iterator i = filterLists.begin(); i != filterLists.end(); i++)
		addChild(new CreateContextCase(m_eglTestCtx, i->getName(), i->getDescription(), *i));

	addChild(new CreateContextNoConfigCase(m_eglTestCtx));
}

} // egl
} // deqp
<|endoftext|>


<commit_before>#include "Component.h"
#include "Simulation.h"
#include "MooseApp.h"

unsigned int Component::subdomain_ids = 0;
unsigned int Component::bc_ids = 0;

template<>
InputParameters validParams<Component>()
{
  InputParameters params = validParams<R7Object>();
  params.addPrivateParam<Simulation *>("_sim");

  params.addParam<std::string>("physics_input_file", "Input file with physics");
  params.addPrivateParam<std::string>("built_by_action", "add_component");

  params.registerBase("Component");

  return params;
}

/*
 * Class used by Component class to map vector variables through friendly names
 * i.e. friendly name = inlet:K_loss; variableName = K_loss, position = 1
 */
RavenMapContainer::RavenMapContainer()
{
}
/*
 * CHANGE VARIABLENAME to ControllableName
 */
RavenMapContainer::RavenMapContainer(const std::string & controllableParName, unsigned int & position):
   _controllableParName(controllableParName),
   _position(position)
{
}
RavenMapContainer::~RavenMapContainer(){
}
const std::string &
RavenMapContainer::getControllableParName(){
   return _controllableParName;
}
unsigned int &
RavenMapContainer::getControllableParPosition(){
   return _position;
}

/*
 * Component implementation
 */
static unsigned int comp_id = 0;

std::string
Component::genName(const std::string & prefix, unsigned int id, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << id << ":" << suffix;
  return ss.str();
}

std::string
Component::genName(const std::string & prefix, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << suffix;
  return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & middle, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << middle << ":" << suffix;
  return ss.str();
}

std::vector<std::string>
Component::split(const std::string & rname)
{
  std::vector<std::string> splitted;
  MooseUtils::tokenize(rname, splitted, 1, ":");

  std::string section_name("");
  for (unsigned int i = 0; i < splitted.size() - 1; i++)
  {
    if (i > 0)
      section_name.append(":");
    section_name.append(splitted[i]);
  }
  std::string prop_name = splitted[splitted.size() - 1];

  // construct the 2 element array with section and property name
  std::vector<std::string> result(2);
  result[0] = section_name;
  result[1] = prop_name;

  return result;
}

Component::Component(const std::string & name, InputParameters parameters) :
    R7Object(name, parameters),
    _id(comp_id++),
    _parent(parameters.have_parameter<Component *>("_parent") ? getParam<Component *>("_parent") : NULL),
    _sim(*getParam<Simulation *>("_sim")),
    _factory(_app.getFactory()),
    _mesh(_sim.mesh()),
    _phys_mesh(_sim.physicalMesh()),

    _input_file_name(getParam<std::string>("physics_input_file")),

    _zero(_sim._zero)
{
}

Component::~Component()
{
}

void
Component::init()
{
}

unsigned int
Component::getNextSubdomainId()
{
  unsigned int sd_id = subdomain_ids++;
  _subdomains.push_back(sd_id);
  if (_parent)
    _parent->_subdomains.push_back(sd_id);
  return sd_id;
}

unsigned int
Component::getNextBCId()
{
  unsigned int id = bc_ids++;
  return id;
}

void
Component::aliasParam(const std::string & rname, const std::string & name, Component * comp/* = NULL*/)
{
  if (comp == NULL)
    _param_alias_map[rname] = std::pair<Component *, std::string>(this, name);
  else
    _param_alias_map[rname] = std::pair<Component *, std::string>(comp, name);
}

void
Component::aliasVectorParam(const std::string & rname, const std::string & name, unsigned int pos, Component * /*comp = NULL*/)
{
  createVectorControllableParMapping(rname, name, pos);
}

void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name)
{
  RavenNameEntry rne(mooseName, name);
  if (_parent != NULL)
    _parent->_rname_map[rname][name].push_back(rne);
  else
    _rname_map[rname][name].push_back(rne);
}

void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name, const std::string & par_name)
{
  RavenNameEntry rne(mooseName, par_name);
  if (_parent != NULL)
    _parent->_rname_map[rname][name].push_back(rne);
  else
    _rname_map[rname][name].push_back(rne);
}

void
Component::createVectorControllableParMapping(const std::string & rname, const std::string & mooseName, unsigned int pos)
{
  _rvect_map[rname] = RavenMapContainer(mooseName, pos);
}
<commit_msg>Whitespace cleanup - refs idaholab/relap-7#19688<commit_after>#include "Component.h"
#include "Simulation.h"
#include "MooseApp.h"

unsigned int Component::subdomain_ids = 0;
unsigned int Component::bc_ids = 0;

template<>
InputParameters validParams<Component>()
{
  InputParameters params = validParams<R7Object>();
  params.addPrivateParam<Simulation *>("_sim");

  params.addParam<std::string>("physics_input_file", "Input file with physics");
  params.addPrivateParam<std::string>("built_by_action", "add_component");

  params.registerBase("Component");

  return params;
}

/*
 * Class used by Component class to map vector variables through friendly names
 * i.e. friendly name = inlet:K_loss; variableName = K_loss, position = 1
 */
RavenMapContainer::RavenMapContainer()
{
}
/*
 * CHANGE VARIABLENAME to ControllableName
 */
RavenMapContainer::RavenMapContainer(const std::string & controllableParName, unsigned int & position):
   _controllableParName(controllableParName),
   _position(position)
{
}
RavenMapContainer::~RavenMapContainer(){
}
const std::string &
RavenMapContainer::getControllableParName(){
   return _controllableParName;
}
unsigned int &
RavenMapContainer::getControllableParPosition(){
   return _position;
}

/*
 * Component implementation
 */
static unsigned int comp_id = 0;

std::string
Component::genName(const std::string & prefix, unsigned int id, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << id << ":" << suffix;
  return ss.str();
}

std::string
Component::genName(const std::string & prefix, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << suffix;
  return ss.str();
}
std::string
Component::genName(const std::string & prefix, const std::string & middle, const std::string & suffix)
{
  std::stringstream ss;
  ss << prefix << ":" << middle << ":" << suffix;
  return ss.str();
}

std::vector<std::string>
Component::split(const std::string & rname)
{
  std::vector<std::string> splitted;
  MooseUtils::tokenize(rname, splitted, 1, ":");

  std::string section_name("");
  for (unsigned int i = 0; i < splitted.size() - 1; i++)
  {
    if (i > 0)
      section_name.append(":");
    section_name.append(splitted[i]);
  }
  std::string prop_name = splitted[splitted.size() - 1];

  // construct the 2 element array with section and property name
  std::vector<std::string> result(2);
  result[0] = section_name;
  result[1] = prop_name;

  return result;
}

Component::Component(const std::string & name, InputParameters parameters) :
    R7Object(name, parameters),
    _id(comp_id++),
    _parent(parameters.have_parameter<Component *>("_parent") ? getParam<Component *>("_parent") : NULL),
    _sim(*getParam<Simulation *>("_sim")),
    _factory(_app.getFactory()),
    _mesh(_sim.mesh()),
    _phys_mesh(_sim.physicalMesh()),

    _input_file_name(getParam<std::string>("physics_input_file")),

    _zero(_sim._zero)
{
}

Component::~Component()
{
}

void
Component::init()
{
}

unsigned int
Component::getNextSubdomainId()
{
  unsigned int sd_id = subdomain_ids++;
  _subdomains.push_back(sd_id);
  if (_parent)
    _parent->_subdomains.push_back(sd_id);
  return sd_id;
}

unsigned int
Component::getNextBCId()
{
  unsigned int id = bc_ids++;
  return id;
}

void
Component::aliasParam(const std::string & rname, const std::string & name, Component * comp/* = NULL*/)
{
  if (comp == NULL)
    _param_alias_map[rname] = std::pair<Component *, std::string>(this, name);
  else
    _param_alias_map[rname] = std::pair<Component *, std::string>(comp, name);
}

void
Component::aliasVectorParam(const std::string & rname, const std::string & name, unsigned int pos, Component * /*comp = NULL*/)
{
  createVectorControllableParMapping(rname, name, pos);
}

void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name)
{
  RavenNameEntry rne(mooseName, name);
  if (_parent != NULL)
    _parent->_rname_map[rname][name].push_back(rne);
  else
    _rname_map[rname][name].push_back(rne);
}

void
Component::connectObject(const std::string & rname, const std::string & mooseName, const std::string & name, const std::string & par_name)
{
  RavenNameEntry rne(mooseName, par_name);
  if (_parent != NULL)
    _parent->_rname_map[rname][name].push_back(rne);
  else
    _rname_map[rname][name].push_back(rne);
}

void
Component::createVectorControllableParMapping(const std::string & rname, const std::string & mooseName, unsigned int pos)
{
  _rvect_map[rname] = RavenMapContainer(mooseName, pos);
}
<|endoftext|>


<commit_before>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
#include "Factory.h"
#include "FlowModelSinglePhase.h"
#include "FlowModelTwoPhase.h"

template <>
InputParameters
validParams<SolidWall>()
{
  InputParameters params = validParams<FlowBoundary>();
  return params;
}

SolidWall::SolidWall(const InputParameters & params) : FlowBoundary(params) {}

void
SolidWall::check()
{
  if ((_spatial_discretization == FlowModel::rDG) && (_flow_model_id == RELAP7::FM_TWO_PHASE))
    logSpatialDiscretizationNotImplementedError(_spatial_discretization);
}

void
SolidWall::addMooseObjects1Phase()
{
  if (_spatial_discretization == FlowModel::CG)
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "rhou"), params);
  }
  else if (_spatial_discretization == FlowModel::rDG)
  {
    ExecFlagEnum userobject_execute_on(MooseUtils::getDefaultExecFlagEnum());
    userobject_execute_on = {EXEC_LINEAR, EXEC_NONLINEAR};

    // boundary flux user object
    const std::string boundary_flux_name = genName(name(), "boundary_flux");
    {
      const std::string class_name = "Euler1DVarAreaWallBoundaryFlux";
      InputParameters params = _factory.getValidParams(class_name);
      params.set<UserObjectName>("rdg_flux") = _rdg_flux_name;
      params.set<bool>("implicit") = _implicit_rdg;
      params.set<ExecFlagEnum>("execute_on") = userobject_execute_on;
      _sim.addUserObject(class_name, boundary_flux_name, params);
    }

    // BCs
    createRDGBoundaryConditions1Phase(boundary_flux_name);
  }
}

void
SolidWall::addMooseObjects2Phase()
{
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_LIQUID;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_liquid"), params);
  }
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_VAPOR;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_vapor"), params);
  }
}

void
SolidWall::addMooseObjects()
{
  if (_flow_model_id == RELAP7::FM_SINGLE_PHASE)
    addMooseObjects1Phase();
  else if (_flow_model_id == RELAP7::FM_TWO_PHASE)
    addMooseObjects2Phase();
}
<commit_msg>Register objects in individual source files instead of RELAP7App.C<commit_after>#include "SolidWall.h"
#include "Simulation.h"
#include "FEProblem.h"
#include "Pipe.h"
#include "Factory.h"
#include "FlowModelSinglePhase.h"
#include "FlowModelTwoPhase.h"

registerMooseObject("RELAP7App", SolidWall);

template <>
InputParameters
validParams<SolidWall>()
{
  InputParameters params = validParams<FlowBoundary>();
  return params;
}

SolidWall::SolidWall(const InputParameters & params) : FlowBoundary(params) {}

void
SolidWall::check()
{
  if ((_spatial_discretization == FlowModel::rDG) && (_flow_model_id == RELAP7::FM_TWO_PHASE))
    logSpatialDiscretizationNotImplementedError(_spatial_discretization);
}

void
SolidWall::addMooseObjects1Phase()
{
  if (_spatial_discretization == FlowModel::CG)
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelSinglePhase::RHOUA;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "rhou"), params);
  }
  else if (_spatial_discretization == FlowModel::rDG)
  {
    ExecFlagEnum userobject_execute_on(MooseUtils::getDefaultExecFlagEnum());
    userobject_execute_on = {EXEC_LINEAR, EXEC_NONLINEAR};

    // boundary flux user object
    const std::string boundary_flux_name = genName(name(), "boundary_flux");
    {
      const std::string class_name = "Euler1DVarAreaWallBoundaryFlux";
      InputParameters params = _factory.getValidParams(class_name);
      params.set<UserObjectName>("rdg_flux") = _rdg_flux_name;
      params.set<bool>("implicit") = _implicit_rdg;
      params.set<ExecFlagEnum>("execute_on") = userobject_execute_on;
      _sim.addUserObject(class_name, boundary_flux_name, params);
    }

    // BCs
    createRDGBoundaryConditions1Phase(boundary_flux_name);
  }
}

void
SolidWall::addMooseObjects2Phase()
{
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_LIQUID;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_liquid"), params);
  }
  {
    InputParameters params = _factory.getValidParams("DirichletBC");
    params.set<NonlinearVariableName>("variable") = FlowModelTwoPhase::ALPHA_RHOU_A_VAPOR;
    params.set<std::vector<BoundaryName>>("boundary") = getBoundaryNames();
    params.set<Real>("value") = 0.;
    _sim.addBoundaryCondition("DirichletBC", genName(name(), "arhouA_vapor"), params);
  }
}

void
SolidWall::addMooseObjects()
{
  if (_flow_model_id == RELAP7::FM_SINGLE_PHASE)
    addMooseObjects1Phase();
  else if (_flow_model_id == RELAP7::FM_TWO_PHASE)
    addMooseObjects2Phase();
}
<|endoftext|>


<commit_before>#include "Tilemap.h"

#include "io/FileLoader.h"
#include "graphics/Window.h"
#include "graphics/Drawer.h"
#include "util/Logger.h"
#define DIR "Contents/MainGame/"

//std::string Tilemap::getLocationDir(std::string filename)
//{
//    std::string aux;
//    int i = filename.find_last_of('/');
//    aux.append(filename.substr(0,i) + '/');
//    return aux;

//}
std::vector<Uint32> Tilemap::getLayers(int i) const
{
    return layers.at(i).data;
}

Tilemap::Tilemap(std::string jsonFile)
{
    Json::Value json = FileLoader::LoadJson(jsonFile);
//    std::string Dir = getLocationDir(jsonFile);

    m_size.x = json["height"].asInt();
    m_size.y = json["width"].asInt();

    m_tileSize.x = json["tileheight"].asInt();
    m_tileSize.y = json["tilewidth"].asInt();

    int ArraySize = json["tilesets"].size();
    for(int i = 0; i < ArraySize ; ++i)
    {
        m_tileImages.push_back(new TileImage(FileLoader::LoadTexture(DIR + json["tilesets"][i]["image"].asString()),
                                        json["tilesets"][i]["name"].asString(),
                                        Vector2D<int>(json["tilesets"][i]["imagewidth"].asInt(),
                                                      json["tilesets"][i]["imageheight"].asInt()) ));
    }

    Json::Value jsonLayers = json["layers"];
    ArraySize = jsonLayers.size();

    for(int i = 0; i < ArraySize; ++i)
    {
        Layer l1;
        l1.size = Vector2D<int>(jsonLayers[i]["width"].asInt(),jsonLayers[i]["height"].asInt());
        l1.visible = jsonLayers[i]["visible"].asBool();

        if(l1.visible)
        {
            for(auto iit = jsonLayers[i]["data"].begin();
                iit != jsonLayers[i]["data"].end();
                ++iit)
            {
                    l1.data.push_back((*iit).asInt());
            }

            layers.push_back(l1);
        }

    }

    tileTexture = std::shared_ptr<Texture>(new Texture(
            m_size.x * m_tileSize.x,
            m_size.y * m_tileSize.y));

//    std::cout << m_size << std::endl;
    generateTileMap();
}

Tilemap::~Tilemap()
{
    for (auto i : m_tileImages)
        delete i;

}

void Tilemap::Render(Vector2D<int> pos)
{
    Drawer::Render(tileTexture,pos);
}

void Tilemap::Render(int x, int y)
{
    Drawer::Render(tileTexture,x,y);

}

std::vector<Uint32> Tilemap::operator[](int i)
{
    return  layers.at(i).data;
}

Vector2D<int> Tilemap::getLayerSize()
{
    return layers.at(0).size;
}

void Tilemap::generateTileMap()
{
    Drawer::RenderTo(tileTexture);

    Rect srcrect;
    Rect destrect;
    Drawer::clearScreen(0,0,0,255);

    for(Layer layer : layers)
    {
        //Pegar o tamanho da imagem em tiles
        Vector2D<int> imageSizeIT(m_tileImages[0]->size.x / m_tileSize.x,
                                  m_tileImages[0]->size.y / m_tileSize.y);
        //Para cada valor na camada de tiles
        for(Uint32 i = 0; i < layer.data.size(); ++i)
        {
            int value = layer.data[i];
            //Gerar um novo retangulo src
            srcrect = Rect( ((value-1)%imageSizeIT.x) * m_tileSize.x,
                               ((value-1)/imageSizeIT.x) * m_tileSize.y,
                               m_tileSize.x,m_tileSize.y);
            //Gerar um novo retangulo dest
            destrect = Rect( (i%m_size.x) * m_tileSize.x,
                                (i/m_size.y) * m_tileSize.y,
                                m_tileSize.x,m_tileSize.y);
            m_tileRects.push_back(destrect);
            //Renderizar na tela
            TileImage *tileimage = m_tileImages[0];
            Drawer::Render(tileimage->tex,&srcrect,&destrect);

        }

    }
    Drawer::RenderTo(NULL);

}
<commit_msg>Bug fix: havia um bug na hora de ler os dados do mapa, onde o código pulava uma linha horizontal antes do momento correto<commit_after>#include "Tilemap.h"

#include "io/FileLoader.h"
#include "graphics/Window.h"
#include "graphics/Drawer.h"
#include "util/Logger.h"
#define DIR "Contents/MainGame/"

//std::string Tilemap::getLocationDir(std::string filename)
//{
//    std::string aux;
//    int i = filename.find_last_of('/');
//    aux.append(filename.substr(0,i) + '/');
//    return aux;

//}
std::vector<Uint32> Tilemap::getLayers(int i) const
{
    return layers.at(i).data;
}

Tilemap::Tilemap(std::string jsonFile)
{
    Json::Value json = FileLoader::LoadJson(jsonFile);
//    std::string Dir = getLocationDir(jsonFile);

    m_size.x = json["width"].asInt();
    m_size.y = json["height"].asInt();

    m_tileSize.x = json["tilewidth"].asInt();
    m_tileSize.y = json["tileheight"].asInt();

    int ArraySize = json["tilesets"].size();
    for(int i = 0; i < ArraySize ; ++i)
    {
        m_tileImages.push_back(new TileImage(FileLoader::LoadTexture(DIR + json["tilesets"][i]["image"].asString()),
                                        json["tilesets"][i]["name"].asString(),
                                        Vector2D<int>(json["tilesets"][i]["imagewidth"].asInt(),
                                                      json["tilesets"][i]["imageheight"].asInt()) ));
    }

    Json::Value jsonLayers = json["layers"];
    ArraySize = jsonLayers.size();

    for(int i = 0; i < ArraySize; ++i)
    {
        Layer l1;
        l1.size = Vector2D<int>(jsonLayers[i]["width"].asInt(),jsonLayers[i]["height"].asInt());
        l1.visible = jsonLayers[i]["visible"].asBool();

        if(l1.visible)
        {
            for(auto iit = jsonLayers[i]["data"].begin();
                iit != jsonLayers[i]["data"].end();
                ++iit)
            {
                    l1.data.push_back((*iit).asInt());
            }

            layers.push_back(l1);
        }

    }

    tileTexture = std::shared_ptr<Texture>(new Texture(
            m_size.x * m_tileSize.x,
            m_size.y * m_tileSize.y));

//    std::cout << m_size << std::endl;
    generateTileMap();
}

Tilemap::~Tilemap()
{
    for (auto i : m_tileImages)
        delete i;

}

void Tilemap::Render(Vector2D<int> pos)
{
    Drawer::Render(tileTexture,pos);
}

void Tilemap::Render(int x, int y)
{
    Drawer::Render(tileTexture,x,y);

}

std::vector<Uint32> Tilemap::operator[](int i)
{
    return  layers.at(i).data;
}

Vector2D<int> Tilemap::getLayerSize()
{
    return layers.at(0).size;
}

void Tilemap::generateTileMap()
{
    Drawer::RenderTo(tileTexture);

    Rect srcrect;
    Rect destrect;
    Drawer::clearScreen(0,0,0,255);

    for(Layer layer : layers)
    {
        //Pegar o tamanho da imagem em tiles
        Vector2D<int> imageSizeIT(m_tileImages[0]->size.x / m_tileSize.x,
                                  m_tileImages[0]->size.y / m_tileSize.y);
        //Para cada valor na camada de tiles
        for(Uint32 i = 0; i < layer.data.size(); ++i)
        {
            int value = layer.data[i];
            //Gerar um novo retangulo src
            srcrect = Rect( ((value-1)%imageSizeIT.x) * m_tileSize.x,
                               ((value-1)/imageSizeIT.x) * m_tileSize.y,
                               m_tileSize.x,m_tileSize.y);
            //Gerar um novo retangulo dest
            destrect = Rect( (i%m_size.x) * m_tileSize.x,
                                (i/m_size.x) * m_tileSize.y,
                                m_tileSize.x,m_tileSize.y);
            m_tileRects.push_back(destrect);
            //Renderizar na tela
            TileImage *tileimage = m_tileImages[0];
            Drawer::Render(tileimage->tex,&srcrect,&destrect);

        }

    }
    Drawer::RenderTo(NULL);

}
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
/* Patch from Trevor Smigiel                                   */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_NO_TYPEINFO
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_POSIX2_AVAILABLE
#define XALAN_BIG_ENDIAN

#define XALAN_UNALIGNED

#endif  // HPUXDEFINITIONS_HEADER_GUARD_1357924680

<commit_msg>Removed #define.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
/* Patch from Trevor Smigiel                                   */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH
#define XALAN_NO_STD_ALLOCATORS
#define XALAN_POSIX2_AVAILABLE
#define XALAN_BIG_ENDIAN

#define XALAN_UNALIGNED

#endif  // HPUXDEFINITIONS_HEADER_GUARD_1357924680

<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
/* Patch from Trevor Smigiel                                   */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_NO_MEMBER_TEMPLATES
#define XALAN_NO_COVARIANT_RETURN_TYPE
#define XALAN_RTTI_AVAILABLE
#define XALAN_NO_TYPEINFO
#define XALAN_SGI_BASED_STL
#define XALAN_OLD_STYLE_CASTS
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH

#define XALAN_BIG_ENDIAN

#endif  // HPUXDEFINITIONS_HEADER_GUARD_1357924680

<commit_msg>HP port based on work from Trevor Smigiel and Troy Heber.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
/* Patch from Trevor Smigiel                                   */
#if !defined(HPUXDEFINITIONS_HEADER_GUARD_1357924680)
#define HPUXDEFINITIONS_HEADER_GUARD_1357924680

// ---------------------------------------------------------------------------
//  A define in the build for each project is also used to control whether
//  the export keyword is from the project's viewpoint or the client's.
//  These defines provide the platform specific keywords that they need
//  to do this.
// ---------------------------------------------------------------------------

#define XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT
#define XALAN_PLATFORM_EXPORT_FUNCTION(T) T XALAN_PLATFORM_EXPORT
#define XALAN_PLATFORM_IMPORT_FUNCTION(T) T XALAN_PLATFORM_IMPORT

#define XALAN_OLD_STREAM_HEADERS
#define XALAN_NO_IOSFWD
#define XALAN_RTTI_AVAILABLE
#define XALAN_SGI_BASED_STL
#define XALAN_NO_NAMESPACES
#define XALAN_XALANDOMCHAR_USHORT_MISMATCH

#define XALAN_BIG_ENDIAN

#endif  // HPUXDEFINITIONS_HEADER_GUARD_1357924680

<|endoftext|>


<commit_before>//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

#include <cassert>
#include <vector>
#include <unordered_map>

#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeBuilder.h"
#if (LLVM_VERSION_MINOR >= 5)
  #include "llvm/IR/InstIterator.h"
#else
  #include "llvm/Support/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"

using namespace llvm;

class InitializeUninitialized : public FunctionPass {
    Function *_kms = nullptr; // klee_make_symbolic function
    Type *_size_t_Ty = nullptr; // type of size_t

    std::unordered_map<llvm::Type *, llvm::GlobalVariable *> added_globals;

    // add global of given type and initialize it in may as nondeterministic
    GlobalVariable *getGlobalNondet(llvm::Type *, llvm::Module *);
    Function *get_klee_make_symbolic(llvm::Module *);
    Type *get_size_t(llvm::Module *);
  public:
    static char ID;

    InitializeUninitialized() : FunctionPass(ID) {}
    virtual bool runOnFunction(Function &F);
};

static RegisterPass<InitializeUninitialized> INIUNINI("initialize-uninitialized",
                                                      "initialize all uninitialized variables to non-deterministic value");
char InitializeUninitialized::ID;

Function *InitializeUninitialized::get_klee_make_symbolic(llvm::Module *M)
{
  if (_kms)
    return _kms;

  LLVMContext& Ctx = M->getContext();
  //void klee_make_symbolic(void *addr, size_t nbytes, const char *name);
  Constant *C = M->getOrInsertFunction("klee_make_symbolic",
                                       Type::getVoidTy(Ctx),
                                       Type::getInt8PtrTy(Ctx), // addr
                                       get_size_t(M),   // nbytes
                                       Type::getInt8PtrTy(Ctx), // name
                                       nullptr);
  _kms = cast<Function>(C);
  return _kms;
}

Type *InitializeUninitialized::get_size_t(llvm::Module *M)
{
  if (_size_t_Ty)
    return _size_t_Ty;

  std::unique_ptr<DataLayout> DL
    = std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));
  LLVMContext& Ctx = M->getContext();

  if (DL->getPointerSizeInBits() > 32)
    _size_t_Ty = Type::getInt64Ty(Ctx);
  else
    _size_t_Ty = Type::getInt32Ty(Ctx);

  return _size_t_Ty;
}

// add global of given type and initialize it in may as nondeterministic
GlobalVariable *InitializeUninitialized::getGlobalNondet(llvm::Type *Ty, llvm::Module *M)
{
  auto it = added_globals.find(Ty);
  if (it != added_globals.end())
    return it->second;

  LLVMContext& Ctx = M->getContext();
  GlobalVariable *G = new GlobalVariable(*M, Ty, false /* constant */,
                                         GlobalValue::PrivateLinkage,
                                         /* initializer */
                                         Constant::getNullValue(Ty),
                                         "nondet_gl");

  added_globals.emplace(Ty, G);

  // insert initialization of the new global variable
  // at the beginning of main
  Function *kms = get_klee_make_symbolic(M);
  CastInst *CastI = CastInst::CreatePointerCast(G, Type::getInt8PtrTy(Ctx));

  std::vector<Value *> args;
  //XXX: we should not build the new DL every time
  std::unique_ptr<DataLayout> DL
    = std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));

  args.push_back(CastI);
  args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));
  Constant *name = ConstantDataArray::getString(Ctx, "nondet");
  GlobalVariable *nameG = new GlobalVariable(*M, name->getType(), true /*constant */,
                                             GlobalVariable::PrivateLinkage, name);
  args.push_back(ConstantExpr::getPointerCast(nameG, Type::getInt8PtrTy(Ctx)));
  //args.push_back(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx)));
  CallInst *CI = CallInst::Create(kms, args);

  Function *main = M->getFunction("main");
  assert(main && "Do not have main");
  BasicBlock& block = main->getBasicBlockList().front();
  // there must be some instruction, otherwise we would not be calling
  // this function
  Instruction& I = *(block.begin());
  CastI->insertBefore(&I);
  CI->insertBefore(&I);

  return G;
}

// no hard analysis, just check wether the alloca is initialized
// in the same block. (we could do an O(n) analysis that would
// do DFS and if the alloca would be initialized on every path
// before reaching some backedge, then it must be initialized),
// for all allocas the running time would be O(n^2) and it could
// probably be decreased (without pointers)
static bool mayBeUnititialized(const llvm::AllocaInst *AI)
{
	Type *AITy = AI->getAllocatedType();
	if(!AITy->isSized())
		return true;

    const BasicBlock *block = AI->getParent();
    auto I = block->begin();
    auto E = block->end();
    // shift to AI
    while (I != E && (&*I) != AI)
        ++I;

    if (I == E)
        return true;

    // iterate over instructions after AI in this block
    for (++I /* shift after AI */; I != E; ++I) {
        if (const StoreInst *SI = dyn_cast<StoreInst>(&*I)) {
            // we store into AI and we store the same type
            // (that is, we overwrite the whole memory?)
            if (SI->getPointerOperand() == AI &&
                SI->getValueOperand()->getType() == AITy)
                return false;
        }
    }

    return true;
}

bool InitializeUninitialized::runOnFunction(Function &F)
{
  // do not run the initializer on __VERIFIER and __INSTR functions
  const auto& fname = F.getName();
  if (fname.startswith("__VERIFIER_") || fname.startswith("__INSTR_"))
    return false;

  bool modified = false;
  Module *M = F.getParent();
  LLVMContext& Ctx = M->getContext();
  DataLayout *DL = new DataLayout(M->getDataLayout());
  Constant *name_init = ConstantDataArray::getString(Ctx, "nondet");
  GlobalVariable *name = new GlobalVariable(*M, name_init->getType(), true,
                                            GlobalValue::PrivateLinkage,
                                            name_init);

  Function *C = get_klee_make_symbolic(M);

  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {
    Instruction *ins = &*I;
    ++I;

    if (AllocaInst *AI = dyn_cast<AllocaInst>(ins)) {
      if (!mayBeUnititialized(AI))
        continue;

      Type *Ty = AI->getAllocatedType();
      AllocaInst *newAlloca = nullptr;
      CallInst *CI = nullptr;
      CastInst *CastI = nullptr;
      StoreInst *SI = nullptr;
      LoadInst *LI = nullptr;
      BinaryOperator *MulI = nullptr;

      std::vector<Value *> args;

      // create new allocainst, declare it symbolic and store it
      // to the original alloca. This way slicer will slice this
      // initialization away if program initialize it manually later
      if (Ty->isSized()) {
        // if this is an array allocation, just call klee_make_symbolic on it,
        // since storing whole symbolic array into it would have soo huge overhead
        if (Ty->isArrayTy()) {
            CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));
            args.push_back(CastI);
            args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));
            args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));

            CI = CallInst::Create(C, args);
            CastI->insertAfter(AI);
            CI->insertAfter(CastI);
        } else if (AI->isArrayAllocation()) {
            CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));
            MulI = BinaryOperator::CreateMul(AI->getArraySize(),
                                             ConstantInt::get(get_size_t(M),
                                                              DL->getTypeAllocSize(Ty)),
                                             "val_size");
            args.push_back(CastI);
            args.push_back(MulI);
            args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));

            CI = CallInst::Create(C, args);
            CastI->insertAfter(AI);
            MulI->insertAfter(CastI);
            CI->insertAfter(MulI);
        } else {
            // when this is not an array allocation,
            // store the symbolic value into the allocated memory using normal StoreInst.
            // That will allow slice away more unneeded allocations
            LI = new LoadInst(getGlobalNondet(Ty, M));
            SI = new StoreInst(LI, AI);

            LI->insertAfter(AI);
            SI->insertAfter(LI);
        }

        modified = true;
      }
    }
  }

  delete DL;
  return modified;
}

<commit_msg>InitializeUninitialized: make mayBeUninitialized aware of pointers<commit_after>//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.

#include <cassert>
#include <vector>
#include <unordered_map>

#include "llvm/IR/DataLayout.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/Pass.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/TypeBuilder.h"
#if (LLVM_VERSION_MINOR >= 5)
  #include "llvm/IR/InstIterator.h"
#else
  #include "llvm/Support/InstIterator.h"
#endif
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"

using namespace llvm;

class InitializeUninitialized : public FunctionPass {
    Function *_kms = nullptr; // klee_make_symbolic function
    Type *_size_t_Ty = nullptr; // type of size_t

    std::unordered_map<llvm::Type *, llvm::GlobalVariable *> added_globals;

    // add global of given type and initialize it in may as nondeterministic
    GlobalVariable *getGlobalNondet(llvm::Type *, llvm::Module *);
    Function *get_klee_make_symbolic(llvm::Module *);
    Type *get_size_t(llvm::Module *);
  public:
    static char ID;

    InitializeUninitialized() : FunctionPass(ID) {}
    virtual bool runOnFunction(Function &F);
};

static RegisterPass<InitializeUninitialized> INIUNINI("initialize-uninitialized",
                                                      "initialize all uninitialized variables to non-deterministic value");
char InitializeUninitialized::ID;

Function *InitializeUninitialized::get_klee_make_symbolic(llvm::Module *M)
{
  if (_kms)
    return _kms;

  LLVMContext& Ctx = M->getContext();
  //void klee_make_symbolic(void *addr, size_t nbytes, const char *name);
  Constant *C = M->getOrInsertFunction("klee_make_symbolic",
                                       Type::getVoidTy(Ctx),
                                       Type::getInt8PtrTy(Ctx), // addr
                                       get_size_t(M),   // nbytes
                                       Type::getInt8PtrTy(Ctx), // name
                                       nullptr);
  _kms = cast<Function>(C);
  return _kms;
}

Type *InitializeUninitialized::get_size_t(llvm::Module *M)
{
  if (_size_t_Ty)
    return _size_t_Ty;

  std::unique_ptr<DataLayout> DL
    = std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));
  LLVMContext& Ctx = M->getContext();

  if (DL->getPointerSizeInBits() > 32)
    _size_t_Ty = Type::getInt64Ty(Ctx);
  else
    _size_t_Ty = Type::getInt32Ty(Ctx);

  return _size_t_Ty;
}

// add global of given type and initialize it in may as nondeterministic
GlobalVariable *InitializeUninitialized::getGlobalNondet(llvm::Type *Ty, llvm::Module *M)
{
  auto it = added_globals.find(Ty);
  if (it != added_globals.end())
    return it->second;

  LLVMContext& Ctx = M->getContext();
  GlobalVariable *G = new GlobalVariable(*M, Ty, false /* constant */,
                                         GlobalValue::PrivateLinkage,
                                         /* initializer */
                                         Constant::getNullValue(Ty),
                                         "nondet_gl");

  added_globals.emplace(Ty, G);

  // insert initialization of the new global variable
  // at the beginning of main
  Function *kms = get_klee_make_symbolic(M);
  CastInst *CastI = CastInst::CreatePointerCast(G, Type::getInt8PtrTy(Ctx));

  std::vector<Value *> args;
  //XXX: we should not build the new DL every time
  std::unique_ptr<DataLayout> DL
    = std::unique_ptr<DataLayout>(new DataLayout(M->getDataLayout()));

  args.push_back(CastI);
  args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));
  Constant *name = ConstantDataArray::getString(Ctx, "nondet");
  GlobalVariable *nameG = new GlobalVariable(*M, name->getType(), true /*constant */,
                                             GlobalVariable::PrivateLinkage, name);
  args.push_back(ConstantExpr::getPointerCast(nameG, Type::getInt8PtrTy(Ctx)));
  //args.push_back(ConstantPointerNull::get(Type::getInt8PtrTy(Ctx)));
  CallInst *CI = CallInst::Create(kms, args);

  Function *main = M->getFunction("main");
  assert(main && "Do not have main");
  BasicBlock& block = main->getBasicBlockList().front();
  // there must be some instruction, otherwise we would not be calling
  // this function
  Instruction& I = *(block.begin());
  CastI->insertBefore(&I);
  CI->insertBefore(&I);

  return G;
}

// no hard analysis, just check wether the alloca is initialized
// in the same block. (we could do an O(n) analysis that would
// do DFS and if the alloca would be initialized on every path
// before reaching some backedge, then it must be initialized),
// for all allocas the running time would be O(n^2) and it could
// probably be decreased (without pointers)
static bool mayBeUnititialized(const llvm::AllocaInst *AI)
{
	Type *AITy = AI->getAllocatedType();
	if(!AITy->isSized())
		return true;

    const BasicBlock *block = AI->getParent();
    auto I = block->begin();
    auto E = block->end();
    // shift to AI
    while (I != E && (&*I) != AI)
        ++I;

    if (I == E)
        return true;

    // iterate over instructions after AI in this block
    for (++I /* shift after AI */; I != E; ++I) {
        if (const LoadInst *LI = dyn_cast<LoadInst>(&*I)) {
            if (LI->getPointerOperand() == AI)
                return true;
        } else if (const StoreInst *SI = dyn_cast<StoreInst>(&*I)) {
            // we store into AI and we store the same type
            // (that is, we overwrite the whole memory?)
            if (SI->getPointerOperand() == AI &&
                SI->getValueOperand()->getType() == AITy)
                return false;
            else if (SI->getValueOperand() == AI)
                // if we store this address to some pointer,
                // we just bail out, since we do not perform
                // any points-to analysis
                return true;
        }
    }

    return true;
}

bool InitializeUninitialized::runOnFunction(Function &F)
{
  // do not run the initializer on __VERIFIER and __INSTR functions
  const auto& fname = F.getName();
  if (fname.startswith("__VERIFIER_") || fname.startswith("__INSTR_"))
    return false;

  bool modified = false;
  Module *M = F.getParent();
  LLVMContext& Ctx = M->getContext();
  DataLayout *DL = new DataLayout(M->getDataLayout());
  Constant *name_init = ConstantDataArray::getString(Ctx, "nondet");
  GlobalVariable *name = new GlobalVariable(*M, name_init->getType(), true,
                                            GlobalValue::PrivateLinkage,
                                            name_init);

  Function *C = get_klee_make_symbolic(M);

  for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E;) {
    Instruction *ins = &*I;
    ++I;

    if (AllocaInst *AI = dyn_cast<AllocaInst>(ins)) {
      if (!mayBeUnititialized(AI))
        continue;

      Type *Ty = AI->getAllocatedType();
      AllocaInst *newAlloca = nullptr;
      CallInst *CI = nullptr;
      CastInst *CastI = nullptr;
      StoreInst *SI = nullptr;
      LoadInst *LI = nullptr;
      BinaryOperator *MulI = nullptr;

      std::vector<Value *> args;

      // create new allocainst, declare it symbolic and store it
      // to the original alloca. This way slicer will slice this
      // initialization away if program initialize it manually later
      if (Ty->isSized()) {
        // if this is an array allocation, just call klee_make_symbolic on it,
        // since storing whole symbolic array into it would have soo huge overhead
        if (Ty->isArrayTy()) {
            CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));
            args.push_back(CastI);
            args.push_back(ConstantInt::get(get_size_t(M), DL->getTypeAllocSize(Ty)));
            args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));

            CI = CallInst::Create(C, args);
            CastI->insertAfter(AI);
            CI->insertAfter(CastI);
        } else if (AI->isArrayAllocation()) {
            CastI = CastInst::CreatePointerCast(AI, Type::getInt8PtrTy(Ctx));
            MulI = BinaryOperator::CreateMul(AI->getArraySize(),
                                             ConstantInt::get(get_size_t(M),
                                                              DL->getTypeAllocSize(Ty)),
                                             "val_size");
            args.push_back(CastI);
            args.push_back(MulI);
            args.push_back(ConstantExpr::getPointerCast(name, Type::getInt8PtrTy(Ctx)));

            CI = CallInst::Create(C, args);
            CastI->insertAfter(AI);
            MulI->insertAfter(CastI);
            CI->insertAfter(MulI);
        } else {
            // when this is not an array allocation,
            // store the symbolic value into the allocated memory using normal StoreInst.
            // That will allow slice away more unneeded allocations
            LI = new LoadInst(getGlobalNondet(Ty, M));
            SI = new StoreInst(LI, AI);

            LI->insertAfter(AI);
            SI->insertAfter(LI);
        }

        modified = true;
      }
    }
  }

  delete DL;
  return modified;
}

<|endoftext|>


<commit_before>/*
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation,
 modification or redistribution of this Apple software constitutes acceptance of these
 terms.  If you do not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.

 In consideration of your agreement to abide by the following terms, and subject to these
 terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in
 this original Apple software (the "Apple Software"), to use, reproduce, modify and
 redistribute the Apple Software, with or without modifications, in source and/or binary
 forms; provided that if you redistribute the Apple Software in its entirety and without
 modifications, you must retain this notice and the following text and disclaimers in all
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your
 derivative works or by other works in which the Apple Software may be incorporated.

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES,
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
          OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <stdio.h>
#include <wtf/Platform.h>
#if PLATFORM(UNIX)
#include <X11/Xlib.h>
#endif
#include "PluginObject.h"

#ifdef WIN32
#define strcasecmp _stricmp
#define NPAPI WINAPI
#else
#define NPAPI
#endif

// Mach-o entry points
extern "C" {
    NPError NPAPI NP_Initialize(NPNetscapeFuncs *browserFuncs);
    NPError NPAPI NP_GetEntryPoints(NPPluginFuncs *pluginFuncs);
    void NPAPI NP_Shutdown(void);
}

// Mach-o entry points
NPError NPAPI NP_Initialize(NPNetscapeFuncs *browserFuncs)
{
    browser = browserFuncs;
    return NPERR_NO_ERROR;
}

NPError NPAPI NP_GetEntryPoints(NPPluginFuncs *pluginFuncs)
{
    pluginFuncs->version = 11;
    pluginFuncs->size = sizeof(pluginFuncs);
    pluginFuncs->newp = NPP_New;
    pluginFuncs->destroy = NPP_Destroy;
    pluginFuncs->setwindow = NPP_SetWindow;
    pluginFuncs->newstream = NPP_NewStream;
    pluginFuncs->destroystream = NPP_DestroyStream;
    pluginFuncs->asfile = NPP_StreamAsFile;
    pluginFuncs->writeready = NPP_WriteReady;
    pluginFuncs->write = (NPP_WriteProcPtr)NPP_Write;
    pluginFuncs->print = NPP_Print;
    pluginFuncs->event = NPP_HandleEvent;
    pluginFuncs->urlnotify = NPP_URLNotify;
    pluginFuncs->getvalue = NPP_GetValue;
    pluginFuncs->setvalue = NPP_SetValue;

    return NPERR_NO_ERROR;
}

void NPAPI NP_Shutdown(void)
{
}

NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved)
{
    if (browser->version >= 14) {
        PluginObject* obj = (PluginObject*)browser->createobject(instance, getPluginClass());

        obj->onStreamLoad = NULL;

        for (int i = 0; i < argc; i++) {
            if (strcasecmp(argn[i], "onstreamload") == 0 && !obj->onStreamLoad)
                obj->onStreamLoad = strdup(argv[i]);
            else if (strcasecmp(argn[i], "src") == 0 &&
                     strcasecmp(argv[i], "data:application/x-webkit-test-netscape,returnerrorfromnewstream") == 0)
                obj->returnErrorFromNewStream = TRUE;
            else if (strcasecmp(argn[i], "logfirstsetwindow") == 0)
                obj->logSetWindow = TRUE;
        }

        instance->pdata = obj;
    }

    // On Windows and Unix, plugins only get events if they are windowless.
    return browser->setvalue(instance, NPPVpluginWindowBool, NULL);
}

NPError NPP_Destroy(NPP instance, NPSavedData **save)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
    if (obj) {
        if (obj->onStreamLoad)
            free(obj->onStreamLoad);

        if (obj->logDestroy)
            printf("PLUGIN: NPP_Destroy\n");

        browser->releaseobject(&obj->header);
    }

    fflush(stdout);

    return NPERR_NO_ERROR;
}

NPError NPP_SetWindow(NPP instance, NPWindow *window)
{
    if (window->window == NULL) {
        return NPERR_NO_ERROR;
    }

    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);

    if (obj) {
        if (obj->logSetWindow) {
            printf("PLUGIN: NPP_SetWindow: %d %d\n", (int)window->width, (int)window->height);
            obj->logSetWindow = false;
        }
    }

    return NPERR_NO_ERROR;
}

NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16 *stype)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
    obj->stream = stream;
    *stype = NP_ASFILEONLY;

    if (obj->returnErrorFromNewStream)
        return NPERR_GENERIC_ERROR;

    if (browser->version >= NPVERS_HAS_RESPONSE_HEADERS)
        notifyStream(obj, stream->url, stream->headers);

    if (obj->onStreamLoad) {
        NPObject *windowScriptObject;
        browser->getvalue(obj->npp, NPNVWindowNPObject, &windowScriptObject);

        NPString script;
        script.UTF8Characters = obj->onStreamLoad;
        script.UTF8Length = strlen(obj->onStreamLoad);

        NPVariant browserResult;
        browser->evaluate(obj->npp, windowScriptObject, &script, &browserResult);
        browser->releasevariantvalue(&browserResult);
    }

    return NPERR_NO_ERROR;
}

NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
    obj->stream = 0;

    return NPERR_NO_ERROR;
}

int32 NPP_WriteReady(NPP instance, NPStream *stream)
{
    return 0;
}

int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer)
{
    return 0;
}

void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname)
{
}

void NPP_Print(NPP instance, NPPrint *platformPrint)
{
}

int16 NPP_HandleEvent(NPP instance, void *event)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
    if (!obj->eventLogging)
        return 0;

#ifdef WIN32
    // Below is the event handling code.  Per the NPAPI spec, the events don't
    // map directly between operating systems:
    // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
    NPEvent* evt = static_cast<NPEvent*>(event);
    short x = static_cast<short>(evt->lParam & 0xffff);
    short y = static_cast<short>(evt->lParam >> 16);
    switch (evt->event) {
        case WM_PAINT:
            printf("PLUGIN: updateEvt\n");
            break;
        case WM_LBUTTONDOWN:
        case WM_MBUTTONDOWN:
        case WM_RBUTTONDOWN:
            printf("PLUGIN: mouseDown at (%d, %d)\n", x, y);
            break;
        case WM_LBUTTONUP:
        case WM_MBUTTONUP:
        case WM_RBUTTONUP:
            printf("PLUGIN: mouseUp at (%d, %d)\n", x, y);
            break;
        case WM_LBUTTONDBLCLK:
        case WM_MBUTTONDBLCLK:
        case WM_RBUTTONDBLCLK:
            break;
        case WM_MOUSEMOVE:
            printf("PLUGIN: adjustCursorEvent\n");
            break;
        case WM_KEYUP:
            // TODO(tc): We need to convert evt->wParam from virtual-key code
            // to key code.
            printf("NOTIMPLEMENTED PLUGIN: keyUp '%c'\n", ' ');
            break;
        case WM_KEYDOWN:
            // TODO(tc): We need to convert evt->wParam from virtual-key code
            // to key code.
            printf("NOTIMPLEMENTED PLUGIN: keyDown '%c'\n", ' ');
            break;
        case WM_SETCURSOR:
            break;
        case WM_SETFOCUS:
            printf("PLUGIN: getFocusEvent\n");
            break;
        case WM_KILLFOCUS:
            printf("PLUGIN: loseFocusEvent\n");
            break;
        default:
            printf("PLUGIN: event %d\n", evt->event);
    }

    fflush(stdout);

#elif PLATFORM(UNIX)
    XEvent* evt = static_cast<XEvent*>(event);
    XButtonPressedEvent* bpress_evt = reinterpret_cast<XButtonPressedEvent*>(evt);
    XButtonReleasedEvent* brelease_evt = reinterpret_cast<XButtonReleasedEvent*>(evt);
    switch (evt->type) {
        case ButtonPress:
            printf("PLUGIN: mouseDown at (%d, %d)\n", bpress_evt->x, bpress_evt->y);
            break;
        case ButtonRelease:
            printf("PLUGIN: mouseUp at (%d, %d)\n", brelease_evt->x, brelease_evt->y);
            break;
        case KeyPress:
            // TODO: extract key code
            printf("NOTIMPLEMENTED PLUGIN: keyDown '%c'\n", ' ');
            break;
        case KeyRelease:
            // TODO: extract key code
            printf("NOTIMPLEMENTED PLUGIN: keyUp '%c'\n", ' ');
            break;
        case GraphicsExpose:
            printf("PLUGIN: updateEvt\n");
            break;
        // NPAPI events
        case FocusIn:
            printf("PLUGIN: getFocusEvent\n");
            break;
        case FocusOut:
            printf("PLUGIN: loseFocusEvent\n");
            break;
        case EnterNotify:
        case LeaveNotify:
        case MotionNotify:
            printf("PLUGIN: adjustCursorEvent\n");
            break;
        default:
            printf("PLUGIN: event %d\n", evt->type);
    }

    fflush(stdout);

#else
    EventRecord* evt = static_cast<EventRecord*>(event);
    Point pt = { evt->where.v, evt->where.h };
    switch (evt->what) {
        case nullEvent:
            // these are delivered non-deterministically, don't log.
            break;
        case mouseDown:
            GlobalToLocal(&pt);
            printf("PLUGIN: mouseDown at (%d, %d)\n", pt.h, pt.v);
            break;
        case mouseUp:
            GlobalToLocal(&pt);
            printf("PLUGIN: mouseUp at (%d, %d)\n", pt.h, pt.v);
            break;
        case keyDown:
            printf("PLUGIN: keyDown '%c'\n", (char)(evt->message & 0xFF));
            break;
        case keyUp:
            printf("PLUGIN: keyUp '%c'\n", (char)(evt->message & 0xFF));
            break;
        case autoKey:
            printf("PLUGIN: autoKey '%c'\n", (char)(evt->message & 0xFF));
            break;
        case updateEvt:
            printf("PLUGIN: updateEvt\n");
            break;
        case diskEvt:
            printf("PLUGIN: diskEvt\n");
            break;
        case activateEvt:
            printf("PLUGIN: activateEvt\n");
            break;
        case osEvt:
            printf("PLUGIN: osEvt - ");
            switch ((evt->message & 0xFF000000) >> 24) {
                case suspendResumeMessage:
                    printf("%s\n", (evt->message & 0x1) ? "resume" : "suspend");
                    break;
                case mouseMovedMessage:
                    printf("mouseMoved\n");
                    break;
                default:
                    printf("%08lX\n", evt->message);
            }
            break;
        case kHighLevelEvent:
            printf("PLUGIN: kHighLevelEvent\n");
            break;
        // NPAPI events
        case getFocusEvent:
            printf("PLUGIN: getFocusEvent\n");
            break;
        case loseFocusEvent:
            printf("PLUGIN: loseFocusEvent\n");
            break;
        case adjustCursorEvent:
            printf("PLUGIN: adjustCursorEvent\n");
            break;
        default:
            printf("PLUGIN: event %d\n", evt->what);
    }
#endif

    return 0;
}

void NPP_URLNotify(NPP instance, const char *url, NPReason reason, void *notifyData)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);

    handleCallback(obj, url, reason, notifyData);
}

NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
    if (variable == NPPVpluginScriptableNPObject) {
        void **v = (void **)value;
        PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
        // Return value is expected to be retained
        browser->retainobject((NPObject *)obj);
        *v = obj;
        return NPERR_NO_ERROR;
    }
    return NPERR_GENERIC_ERROR;
}

NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
{
    return NPERR_GENERIC_ERROR;
}
<commit_msg>Temporarily disable any use of Xlib in our code until we get the X development libs on the buildbots.<commit_after>/*
 IMPORTANT:  This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in
 consideration of your agreement to the following terms, and your use, installation,
 modification or redistribution of this Apple software constitutes acceptance of these
 terms.  If you do not agree with these terms, please do not use, install, modify or
 redistribute this Apple software.

 In consideration of your agreement to abide by the following terms, and subject to these
 terms, Apple grants you a personal, non-exclusive license, under Apple’s copyrights in
 this original Apple software (the "Apple Software"), to use, reproduce, modify and
 redistribute the Apple Software, with or without modifications, in source and/or binary
 forms; provided that if you redistribute the Apple Software in its entirety and without
 modifications, you must retain this notice and the following text and disclaimers in all
 such redistributions of the Apple Software.  Neither the name, trademarks, service marks
 or logos of Apple Computer, Inc. may be used to endorse or promote products derived from
 the Apple Software without specific prior written permission from Apple. Except as expressly
 stated in this notice, no other rights or licenses, express or implied, are granted by Apple
 herein, including but not limited to any patent rights that may be infringed by your
 derivative works or by other works in which the Apple Software may be incorporated.

 The Apple Software is provided by Apple on an "AS IS" basis.  APPLE MAKES NO WARRANTIES,
 EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
 MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS
 USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.

 IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL
 DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
          OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE,
 REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND
 WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR
 OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#include <stdlib.h>
#include <stdio.h>
#include <wtf/Platform.h>
// The buildbot doesn't have Xlib.  Rather than revert this, I've just
// temporarily ifdef'd it out.
#ifdef XLIB_TEMPORARILY_DISABLED
#if PLATFORM(UNIX)
#include <X11/Xlib.h>
#endif
#endif
#include "PluginObject.h"

#ifdef WIN32
#define strcasecmp _stricmp
#define NPAPI WINAPI
#else
#define NPAPI
#endif

// Mach-o entry points
extern "C" {
    NPError NPAPI NP_Initialize(NPNetscapeFuncs *browserFuncs);
    NPError NPAPI NP_GetEntryPoints(NPPluginFuncs *pluginFuncs);
    void NPAPI NP_Shutdown(void);
}

// Mach-o entry points
NPError NPAPI NP_Initialize(NPNetscapeFuncs *browserFuncs)
{
    browser = browserFuncs;
    return NPERR_NO_ERROR;
}

NPError NPAPI NP_GetEntryPoints(NPPluginFuncs *pluginFuncs)
{
    pluginFuncs->version = 11;
    pluginFuncs->size = sizeof(pluginFuncs);
    pluginFuncs->newp = NPP_New;
    pluginFuncs->destroy = NPP_Destroy;
    pluginFuncs->setwindow = NPP_SetWindow;
    pluginFuncs->newstream = NPP_NewStream;
    pluginFuncs->destroystream = NPP_DestroyStream;
    pluginFuncs->asfile = NPP_StreamAsFile;
    pluginFuncs->writeready = NPP_WriteReady;
    pluginFuncs->write = (NPP_WriteProcPtr)NPP_Write;
    pluginFuncs->print = NPP_Print;
    pluginFuncs->event = NPP_HandleEvent;
    pluginFuncs->urlnotify = NPP_URLNotify;
    pluginFuncs->getvalue = NPP_GetValue;
    pluginFuncs->setvalue = NPP_SetValue;

    return NPERR_NO_ERROR;
}

void NPAPI NP_Shutdown(void)
{
}

NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16 mode, int16 argc, char *argn[], char *argv[], NPSavedData *saved)
{
    if (browser->version >= 14) {
        PluginObject* obj = (PluginObject*)browser->createobject(instance, getPluginClass());

        obj->onStreamLoad = NULL;

        for (int i = 0; i < argc; i++) {
            if (strcasecmp(argn[i], "onstreamload") == 0 && !obj->onStreamLoad)
                obj->onStreamLoad = strdup(argv[i]);
            else if (strcasecmp(argn[i], "src") == 0 &&
                     strcasecmp(argv[i], "data:application/x-webkit-test-netscape,returnerrorfromnewstream") == 0)
                obj->returnErrorFromNewStream = TRUE;
            else if (strcasecmp(argn[i], "logfirstsetwindow") == 0)
                obj->logSetWindow = TRUE;
        }

        instance->pdata = obj;
    }

    // On Windows and Unix, plugins only get events if they are windowless.
    return browser->setvalue(instance, NPPVpluginWindowBool, NULL);
}

NPError NPP_Destroy(NPP instance, NPSavedData **save)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
    if (obj) {
        if (obj->onStreamLoad)
            free(obj->onStreamLoad);

        if (obj->logDestroy)
            printf("PLUGIN: NPP_Destroy\n");

        browser->releaseobject(&obj->header);
    }

    fflush(stdout);

    return NPERR_NO_ERROR;
}

NPError NPP_SetWindow(NPP instance, NPWindow *window)
{
    if (window->window == NULL) {
        return NPERR_NO_ERROR;
    }

    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);

    if (obj) {
        if (obj->logSetWindow) {
            printf("PLUGIN: NPP_SetWindow: %d %d\n", (int)window->width, (int)window->height);
            obj->logSetWindow = false;
        }
    }

    return NPERR_NO_ERROR;
}

NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream *stream, NPBool seekable, uint16 *stype)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
    obj->stream = stream;
    *stype = NP_ASFILEONLY;

    if (obj->returnErrorFromNewStream)
        return NPERR_GENERIC_ERROR;

    if (browser->version >= NPVERS_HAS_RESPONSE_HEADERS)
        notifyStream(obj, stream->url, stream->headers);

    if (obj->onStreamLoad) {
        NPObject *windowScriptObject;
        browser->getvalue(obj->npp, NPNVWindowNPObject, &windowScriptObject);

        NPString script;
        script.UTF8Characters = obj->onStreamLoad;
        script.UTF8Length = strlen(obj->onStreamLoad);

        NPVariant browserResult;
        browser->evaluate(obj->npp, windowScriptObject, &script, &browserResult);
        browser->releasevariantvalue(&browserResult);
    }

    return NPERR_NO_ERROR;
}

NPError NPP_DestroyStream(NPP instance, NPStream *stream, NPReason reason)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
    obj->stream = 0;

    return NPERR_NO_ERROR;
}

int32 NPP_WriteReady(NPP instance, NPStream *stream)
{
    return 0;
}

int32 NPP_Write(NPP instance, NPStream *stream, int32 offset, int32 len, void *buffer)
{
    return 0;
}

void NPP_StreamAsFile(NPP instance, NPStream *stream, const char *fname)
{
}

void NPP_Print(NPP instance, NPPrint *platformPrint)
{
}

int16 NPP_HandleEvent(NPP instance, void *event)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
    if (!obj->eventLogging)
        return 0;

#ifdef WIN32
    // Below is the event handling code.  Per the NPAPI spec, the events don't
    // map directly between operating systems:
    // http://devedge-temp.mozilla.org/library/manuals/2002/plugin/1.0/structures5.html#1000000
    NPEvent* evt = static_cast<NPEvent*>(event);
    short x = static_cast<short>(evt->lParam & 0xffff);
    short y = static_cast<short>(evt->lParam >> 16);
    switch (evt->event) {
        case WM_PAINT:
            printf("PLUGIN: updateEvt\n");
            break;
        case WM_LBUTTONDOWN:
        case WM_MBUTTONDOWN:
        case WM_RBUTTONDOWN:
            printf("PLUGIN: mouseDown at (%d, %d)\n", x, y);
            break;
        case WM_LBUTTONUP:
        case WM_MBUTTONUP:
        case WM_RBUTTONUP:
            printf("PLUGIN: mouseUp at (%d, %d)\n", x, y);
            break;
        case WM_LBUTTONDBLCLK:
        case WM_MBUTTONDBLCLK:
        case WM_RBUTTONDBLCLK:
            break;
        case WM_MOUSEMOVE:
            printf("PLUGIN: adjustCursorEvent\n");
            break;
        case WM_KEYUP:
            // TODO(tc): We need to convert evt->wParam from virtual-key code
            // to key code.
            printf("NOTIMPLEMENTED PLUGIN: keyUp '%c'\n", ' ');
            break;
        case WM_KEYDOWN:
            // TODO(tc): We need to convert evt->wParam from virtual-key code
            // to key code.
            printf("NOTIMPLEMENTED PLUGIN: keyDown '%c'\n", ' ');
            break;
        case WM_SETCURSOR:
            break;
        case WM_SETFOCUS:
            printf("PLUGIN: getFocusEvent\n");
            break;
        case WM_KILLFOCUS:
            printf("PLUGIN: loseFocusEvent\n");
            break;
        default:
            printf("PLUGIN: event %d\n", evt->event);
    }

    fflush(stdout);

#elif PLATFORM(UNIX)
#ifdef XLIB_TEMPORARILY_DISABLED
    XEvent* evt = static_cast<XEvent*>(event);
    XButtonPressedEvent* bpress_evt = reinterpret_cast<XButtonPressedEvent*>(evt);
    XButtonReleasedEvent* brelease_evt = reinterpret_cast<XButtonReleasedEvent*>(evt);
    switch (evt->type) {
        case ButtonPress:
            printf("PLUGIN: mouseDown at (%d, %d)\n", bpress_evt->x, bpress_evt->y);
            break;
        case ButtonRelease:
            printf("PLUGIN: mouseUp at (%d, %d)\n", brelease_evt->x, brelease_evt->y);
            break;
        case KeyPress:
            // TODO: extract key code
            printf("NOTIMPLEMENTED PLUGIN: keyDown '%c'\n", ' ');
            break;
        case KeyRelease:
            // TODO: extract key code
            printf("NOTIMPLEMENTED PLUGIN: keyUp '%c'\n", ' ');
            break;
        case GraphicsExpose:
            printf("PLUGIN: updateEvt\n");
            break;
        // NPAPI events
        case FocusIn:
            printf("PLUGIN: getFocusEvent\n");
            break;
        case FocusOut:
            printf("PLUGIN: loseFocusEvent\n");
            break;
        case EnterNotify:
        case LeaveNotify:
        case MotionNotify:
            printf("PLUGIN: adjustCursorEvent\n");
            break;
        default:
            printf("PLUGIN: event %d\n", evt->type);
    }

    fflush(stdout);
#endif  // XLIB_TEMPORARILY_DISABLED

#else
    EventRecord* evt = static_cast<EventRecord*>(event);
    Point pt = { evt->where.v, evt->where.h };
    switch (evt->what) {
        case nullEvent:
            // these are delivered non-deterministically, don't log.
            break;
        case mouseDown:
            GlobalToLocal(&pt);
            printf("PLUGIN: mouseDown at (%d, %d)\n", pt.h, pt.v);
            break;
        case mouseUp:
            GlobalToLocal(&pt);
            printf("PLUGIN: mouseUp at (%d, %d)\n", pt.h, pt.v);
            break;
        case keyDown:
            printf("PLUGIN: keyDown '%c'\n", (char)(evt->message & 0xFF));
            break;
        case keyUp:
            printf("PLUGIN: keyUp '%c'\n", (char)(evt->message & 0xFF));
            break;
        case autoKey:
            printf("PLUGIN: autoKey '%c'\n", (char)(evt->message & 0xFF));
            break;
        case updateEvt:
            printf("PLUGIN: updateEvt\n");
            break;
        case diskEvt:
            printf("PLUGIN: diskEvt\n");
            break;
        case activateEvt:
            printf("PLUGIN: activateEvt\n");
            break;
        case osEvt:
            printf("PLUGIN: osEvt - ");
            switch ((evt->message & 0xFF000000) >> 24) {
                case suspendResumeMessage:
                    printf("%s\n", (evt->message & 0x1) ? "resume" : "suspend");
                    break;
                case mouseMovedMessage:
                    printf("mouseMoved\n");
                    break;
                default:
                    printf("%08lX\n", evt->message);
            }
            break;
        case kHighLevelEvent:
            printf("PLUGIN: kHighLevelEvent\n");
            break;
        // NPAPI events
        case getFocusEvent:
            printf("PLUGIN: getFocusEvent\n");
            break;
        case loseFocusEvent:
            printf("PLUGIN: loseFocusEvent\n");
            break;
        case adjustCursorEvent:
            printf("PLUGIN: adjustCursorEvent\n");
            break;
        default:
            printf("PLUGIN: event %d\n", evt->what);
    }
#endif

    return 0;
}

void NPP_URLNotify(NPP instance, const char *url, NPReason reason, void *notifyData)
{
    PluginObject* obj = static_cast<PluginObject*>(instance->pdata);

    handleCallback(obj, url, reason, notifyData);
}

NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
    if (variable == NPPVpluginScriptableNPObject) {
        void **v = (void **)value;
        PluginObject* obj = static_cast<PluginObject*>(instance->pdata);
        // Return value is expected to be retained
        browser->retainobject((NPObject *)obj);
        *v = obj;
        return NPERR_NO_ERROR;
    }
    return NPERR_GENERIC_ERROR;
}

NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
{
    return NPERR_GENERIC_ERROR;
}
<|endoftext|>