<commit_before>/****************************************************************************
 *
 * Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
 * Copyright (c) 2019 PX4 Development Team. 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. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "microRTPS_transport.h"
#include "microRTPS_client.h"

#include <inttypes.h>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <termios.h>

#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/getopt.h>
#include <px4_platform_common/cli.h>
#include <px4_platform_common/module.h>
#include <px4_platform_common/posix.h>
#include <px4_platform_common/tasks.h>
#include <px4_platform_common/time.h>

extern "C" __EXPORT int micrortps_client_main(int argc, char *argv[]);

static int _rtps_task = -1;
bool _should_exit_task = false;
Transport_node *transport_node = nullptr;
struct options _options;

static void usage(const char *name)
{
	PRINT_MODULE_USAGE_NAME("micrortps_client", "communication");
	PRINT_MODULE_USAGE_COMMAND("start");

	PRINT_MODULE_USAGE_PARAM_STRING('t', "UART", "UART|UDP", "Transport protocol", true);
	PRINT_MODULE_USAGE_PARAM_STRING('d', "/dev/ttyACM0", "<file:dev>", "Select Serial Device", true);
	PRINT_MODULE_USAGE_PARAM_INT('b', 460800, 9600, 3000000, "Baudrate (can also be p:<param_name>)", true);
	PRINT_MODULE_USAGE_PARAM_INT('p', -1, 1, 1000, "Poll timeout for UART in ms", true);
	PRINT_MODULE_USAGE_PARAM_INT('l', 10000, -1, 100000, "Limit number of iterations until the program exits (-1=infinite)",
				     true);
	PRINT_MODULE_USAGE_PARAM_INT('w', 1, 1, 1000, "Time in ms for which each iteration sleeps", true);
	PRINT_MODULE_USAGE_PARAM_INT('r', 2019, 0, 65536, "Select UDP Network Port for receiving (local)", true);
	PRINT_MODULE_USAGE_PARAM_INT('s', 2020, 0, 65536, "Select UDP Network Port for sending (remote)", true);
	PRINT_MODULE_USAGE_PARAM_STRING('i', "127.0.0.1", "<x.x.x.x>", "Select IP address (remote)", true);
	PRINT_MODULE_USAGE_PARAM_FLAG('f', "Activate UART link SW flow control", true);
	PRINT_MODULE_USAGE_PARAM_FLAG('h', "Activate UART link HW flow control", true);
	PRINT_MODULE_USAGE_PARAM_FLAG('v', "Add more verbosity", true);

	PRINT_MODULE_USAGE_COMMAND("stop");
	PRINT_MODULE_USAGE_COMMAND("status");
}

static int parse_options(int argc, char *argv[])
{
	int ch;
	int myoptind = 1;
	const char *myoptarg = nullptr;

	while ((ch = px4_getopt(argc, argv, "t:d:l:w:b:p:r:s:i:fhv", &myoptind, &myoptarg)) != EOF) {
		switch (ch) {
		case 't': _options.transport      = strcmp(myoptarg, "UDP") == 0 ?
							    options::eTransports::UDP
							    : options::eTransports::UART;   break;

		case 'd': if (nullptr != myoptarg) strcpy(_options.device, myoptarg);   break;

		case 'l': _options.loops           =  strtol(myoptarg, nullptr, 10);    break;

		case 'w': _options.sleep_ms        = strtoul(myoptarg, nullptr, 10);    break;

		case 'b': {
				int baudrate = 0;

				if (px4_get_parameter_value(myoptarg, baudrate) != 0) {
					PX4_ERR("baudrate parsing failed");
				}

				if (baudrate < 9600 || baudrate > 3000000) {
					PX4_ERR("invalid baud rate '%s'", myoptarg);
				}

				_options.baudrate = baudrate;

				break;
			}

		case 'r': _options.recv_port       = strtoul(myoptarg, nullptr, 10);    break;

		case 's': _options.send_port       = strtoul(myoptarg, nullptr, 10);    break;

		case 'i': if (nullptr != myoptarg) strcpy(_options.ip, myoptarg);       break;

		case 'f': _options.sw_flow_control = true;     				break;

		case 'h': _options.hw_flow_control = true;     				break;

		case 'v': _options.verbose_debug   = true;     				break;

		default:
			usage(argv[1]);
			return -1;
		}
	}

	if (_options.poll_ms < 1) {
		_options.poll_ms = 1;
		PX4_ERR("poll timeout too low, using 1 ms");
	}

	if (_options.hw_flow_control && _options.sw_flow_control) {
		PX4_ERR("HW and SW flow control set. Please set only one or another");
		return -1;
	}

	return 0;
}

static int micrortps_start(int argc, char *argv[])
{
	if (0 > parse_options(argc, argv)) {
		PX4_INFO("EXITING...");
		_rtps_task = -1;
		return -1;
	}

	switch (_options.transport) {
	case options::eTransports::UART: {
			transport_node = new UART_node(_options.device, _options.baudrate, _options.poll_ms,
						       _options.sw_flow_control, _options.hw_flow_control, _options.verbose_debug);
			PX4_INFO("UART transport: device: %s; baudrate: %d; sleep: %dms; poll: %dms; flow_control: %s",
				 _options.device, _options.baudrate, _options.sleep_ms, _options.poll_ms,
				 _options.sw_flow_control ? "SW enabled" : (_options.hw_flow_control ? "HW enabled" : "No"));
		}
		break;

	case options::eTransports::UDP: {
			transport_node = new UDP_node(_options.ip, _options.recv_port, _options.send_port,
						      _options.verbose_debug);
			PX4_INFO("UDP transport: ip address: %s; recv port: %u; send port: %u; sleep: %dms",
				 _options.ip, _options.recv_port, _options.send_port, _options.sleep_ms);

		}
		break;

	default:
		_rtps_task = -1;
		PX4_INFO("EXITING...");
		return -1;
	}

	if (0 > transport_node->init()) {
		PX4_INFO("EXITING...");
		_rtps_task = -1;
		return -1;
	}

	struct timespec begin;

	struct timespec end;

	uint64_t total_read = 0, received = 0;

	int loop = 0;

	micrortps_start_topics(begin, total_read, received, loop);

	px4_clock_gettime(CLOCK_REALTIME, &end);

	double elapsed_secs = static_cast<double>(end.tv_sec - begin.tv_sec + (end.tv_nsec - begin.tv_nsec) / 1e9);

	PX4_INFO("RECEIVED: %" PRIu64 " messages in %d LOOPS, %" PRIu64 " bytes in %.03f seconds - %.02fKB/s",
		 received, loop, total_read, elapsed_secs, static_cast<double>(total_read / (1e3 * elapsed_secs)));

	delete transport_node;

	transport_node = nullptr;

	PX4_INFO("Stopped!");

	fflush(stdout);

	_rtps_task = -1;

	return 0;
}

int micrortps_client_main(int argc, char *argv[])
{
	if (argc < 2) {
		usage(argv[0]);
		return -1;
	}

	if (!strcmp(argv[1], "start")) {
		if (_rtps_task != -1) {
			PX4_INFO("Already running");
			return -1;
		}

		_rtps_task = px4_task_spawn_cmd("micrortps_client",
						SCHED_DEFAULT,
						SCHED_PRIORITY_DEFAULT,
						2650,
						(px4_main_t) micrortps_start,
						(char *const *)argv);

		if (_rtps_task < 0) {
			PX4_WARN("Could not start task");
			_rtps_task = -1;
			return -1;
		}

		return 0;
	}

	if (!strcmp(argv[1], "status")) {
		if (_rtps_task == -1) {
			PX4_INFO("Not running");

		} else {
			PX4_INFO("Running");
		}

		return 0;
	}

	if (!strcmp(argv[1], "stop")) {
		if (_rtps_task == -1) {
			PX4_INFO("Not running");
			return -1;
		}

		_should_exit_task = true;

		if (nullptr != transport_node) { transport_node->close(); }

		_rtps_task = -1;
		return 0;
	}

	usage(argv[0]);
	return -1;
}
<commit_msg>RTPS client remove redundant baudrate check<commit_after>/****************************************************************************
 *
 * Copyright 2017 Proyectos y Sistemas de Mantenimiento SL (eProsima).
 * Copyright (c) 2019 PX4 Development Team. 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. Neither the name of the copyright holder nor the names of its contributors
 * may be used to endorse or promote products derived from this software without
 * specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

#include "microRTPS_transport.h"
#include "microRTPS_client.h"

#include <inttypes.h>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <termios.h>

#include <px4_platform_common/px4_config.h>
#include <px4_platform_common/getopt.h>
#include <px4_platform_common/cli.h>
#include <px4_platform_common/module.h>
#include <px4_platform_common/posix.h>
#include <px4_platform_common/tasks.h>
#include <px4_platform_common/time.h>

extern "C" __EXPORT int micrortps_client_main(int argc, char *argv[]);

static int _rtps_task = -1;
bool _should_exit_task = false;
Transport_node *transport_node = nullptr;
struct options _options;

static void usage(const char *name)
{
	PRINT_MODULE_USAGE_NAME("micrortps_client", "communication");
	PRINT_MODULE_USAGE_COMMAND("start");

	PRINT_MODULE_USAGE_PARAM_STRING('t', "UART", "UART|UDP", "Transport protocol", true);
	PRINT_MODULE_USAGE_PARAM_STRING('d', "/dev/ttyACM0", "<file:dev>", "Select Serial Device", true);
	PRINT_MODULE_USAGE_PARAM_INT('b', 460800, 9600, 3000000, "Baudrate (can also be p:<param_name>)", true);
	PRINT_MODULE_USAGE_PARAM_INT('p', -1, 1, 1000, "Poll timeout for UART in ms", true);
	PRINT_MODULE_USAGE_PARAM_INT('l', 10000, -1, 100000, "Limit number of iterations until the program exits (-1=infinite)",
				     true);
	PRINT_MODULE_USAGE_PARAM_INT('w', 1, 1, 1000, "Time in ms for which each iteration sleeps", true);
	PRINT_MODULE_USAGE_PARAM_INT('r', 2019, 0, 65536, "Select UDP Network Port for receiving (local)", true);
	PRINT_MODULE_USAGE_PARAM_INT('s', 2020, 0, 65536, "Select UDP Network Port for sending (remote)", true);
	PRINT_MODULE_USAGE_PARAM_STRING('i', "127.0.0.1", "<x.x.x.x>", "Select IP address (remote)", true);
	PRINT_MODULE_USAGE_PARAM_FLAG('f', "Activate UART link SW flow control", true);
	PRINT_MODULE_USAGE_PARAM_FLAG('h', "Activate UART link HW flow control", true);
	PRINT_MODULE_USAGE_PARAM_FLAG('v', "Add more verbosity", true);

	PRINT_MODULE_USAGE_COMMAND("stop");
	PRINT_MODULE_USAGE_COMMAND("status");
}

static int parse_options(int argc, char *argv[])
{
	int ch;
	int myoptind = 1;
	const char *myoptarg = nullptr;

	while ((ch = px4_getopt(argc, argv, "t:d:l:w:b:p:r:s:i:fhv", &myoptind, &myoptarg)) != EOF) {
		switch (ch) {
		case 't': _options.transport      = strcmp(myoptarg, "UDP") == 0 ?
							    options::eTransports::UDP
							    : options::eTransports::UART;   break;

		case 'd': if (nullptr != myoptarg) strcpy(_options.device, myoptarg);   break;

		case 'l': _options.loops           =  strtol(myoptarg, nullptr, 10);    break;

		case 'w': _options.sleep_ms        = strtoul(myoptarg, nullptr, 10);    break;

		case 'b': {
				int baudrate = 0;

				if (px4_get_parameter_value(myoptarg, baudrate) != 0) {
					PX4_ERR("baudrate parsing failed");
				}

				_options.baudrate = baudrate;

				break;
			}

		case 'r': _options.recv_port       = strtoul(myoptarg, nullptr, 10);    break;

		case 's': _options.send_port       = strtoul(myoptarg, nullptr, 10);    break;

		case 'i': if (nullptr != myoptarg) strcpy(_options.ip, myoptarg);       break;

		case 'f': _options.sw_flow_control = true;     				break;

		case 'h': _options.hw_flow_control = true;     				break;

		case 'v': _options.verbose_debug   = true;     				break;

		default:
			usage(argv[1]);
			return -1;
		}
	}

	if (_options.poll_ms < 1) {
		_options.poll_ms = 1;
		PX4_ERR("poll timeout too low, using 1 ms");
	}

	if (_options.hw_flow_control && _options.sw_flow_control) {
		PX4_ERR("HW and SW flow control set. Please set only one or another");
		return -1;
	}

	return 0;
}

static int micrortps_start(int argc, char *argv[])
{
	if (0 > parse_options(argc, argv)) {
		PX4_INFO("EXITING...");
		_rtps_task = -1;
		return -1;
	}

	switch (_options.transport) {
	case options::eTransports::UART: {
			transport_node = new UART_node(_options.device, _options.baudrate, _options.poll_ms,
						       _options.sw_flow_control, _options.hw_flow_control, _options.verbose_debug);
			PX4_INFO("UART transport: device: %s; baudrate: %d; sleep: %dms; poll: %dms; flow_control: %s",
				 _options.device, _options.baudrate, _options.sleep_ms, _options.poll_ms,
				 _options.sw_flow_control ? "SW enabled" : (_options.hw_flow_control ? "HW enabled" : "No"));
		}
		break;

	case options::eTransports::UDP: {
			transport_node = new UDP_node(_options.ip, _options.recv_port, _options.send_port,
						      _options.verbose_debug);
			PX4_INFO("UDP transport: ip address: %s; recv port: %u; send port: %u; sleep: %dms",
				 _options.ip, _options.recv_port, _options.send_port, _options.sleep_ms);

		}
		break;

	default:
		_rtps_task = -1;
		PX4_INFO("EXITING...");
		return -1;
	}

	if (0 > transport_node->init()) {
		PX4_INFO("EXITING...");
		_rtps_task = -1;
		return -1;
	}

	struct timespec begin;

	struct timespec end;

	uint64_t total_read = 0, received = 0;

	int loop = 0;

	micrortps_start_topics(begin, total_read, received, loop);

	px4_clock_gettime(CLOCK_REALTIME, &end);

	double elapsed_secs = static_cast<double>(end.tv_sec - begin.tv_sec + (end.tv_nsec - begin.tv_nsec) / 1e9);

	PX4_INFO("RECEIVED: %" PRIu64 " messages in %d LOOPS, %" PRIu64 " bytes in %.03f seconds - %.02fKB/s",
		 received, loop, total_read, elapsed_secs, static_cast<double>(total_read / (1e3 * elapsed_secs)));

	delete transport_node;

	transport_node = nullptr;

	PX4_INFO("Stopped!");

	fflush(stdout);

	_rtps_task = -1;

	return 0;
}

int micrortps_client_main(int argc, char *argv[])
{
	if (argc < 2) {
		usage(argv[0]);
		return -1;
	}

	if (!strcmp(argv[1], "start")) {
		if (_rtps_task != -1) {
			PX4_INFO("Already running");
			return -1;
		}

		_rtps_task = px4_task_spawn_cmd("micrortps_client",
						SCHED_DEFAULT,
						SCHED_PRIORITY_DEFAULT,
						2650,
						(px4_main_t) micrortps_start,
						(char *const *)argv);

		if (_rtps_task < 0) {
			PX4_WARN("Could not start task");
			_rtps_task = -1;
			return -1;
		}

		return 0;
	}

	if (!strcmp(argv[1], "status")) {
		if (_rtps_task == -1) {
			PX4_INFO("Not running");

		} else {
			PX4_INFO("Running");
		}

		return 0;
	}

	if (!strcmp(argv[1], "stop")) {
		if (_rtps_task == -1) {
			PX4_INFO("Not running");
			return -1;
		}

		_should_exit_task = true;

		if (nullptr != transport_node) { transport_node->close(); }

		_rtps_task = -1;
		return 0;
	}

	usage(argv[0]);
	return -1;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep08/call_proc_check_secondary_sbe_seeprom_complete.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2020,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file call_proc_check_secondary_sbe_seeprom_complete.C
 *
 *  Support file for IStep: proc_check_secondary_sbe_seeprom_complete
 *   Secondary SBE
 *
 */

/******************************************************************************/
// Includes
/******************************************************************************/

#include <hbotcompid.H>           // HWPF_COMP_ID
#include <attributeenums.H>       // TYPE_PROC
#include <isteps/hwpisteperror.H> //ISTEP_ERROR:IStepError
#include <istepHelperFuncs.H>     // captureError
#include <fapi2/plat_hwp_invoker.H>
#include <nest/nestHwpHelperFuncs.H>
#include <sbeio/sbe_retry_handler.H>
#include <sbeio/sbeioif.H>
#include <errl/errludtarget.H>
#include <spi/spi.H> // for SPI lock support
#include <p10_getecid.H>
#include <util/utilmbox_scratch.H>
#include <hwas/hwasPlat.H>

using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ISTEPS_TRACE;
using namespace TARGETING;
using namespace ERRORLOG;
using namespace SBEIO;

namespace ISTEP_08
{

//******************************************************************************
// call_proc_check_secondary_sbe_seeprom_complete function
//******************************************************************************
void* call_proc_check_secondary_sbe_seeprom_complete( void *io_pArgs )
{
    IStepError  l_stepError;
    errlHndl_t  l_errl = nullptr;

    TRACFCOMP(g_trac_isteps_trace, ENTER_MRK"call_proc_check_secondary_sbe_seeprom_complete");

    //
    //  get the master Proc target, we want to IGNORE this one.
    //
    Target* l_pMasterProcTarget = nullptr;
    targetService().masterProcChipTargetHandle(l_pMasterProcTarget);

    //
    //  get a list of all the procs in the system
    //
    TargetHandleList l_cpuTargetList;
    getAllChips(l_cpuTargetList, TYPE_PROC);

    TRACFCOMP(g_trac_isteps_trace,
        "proc_check_secondary_sbe_seeprom_complete: %d procs in the system.",
        l_cpuTargetList.size());

    // loop thru all the cpus
    for (const auto & l_cpu_target: l_cpuTargetList)
    {
        if ( l_cpu_target  ==  l_pMasterProcTarget )
        {
            TRACFCOMP(g_trac_isteps_trace,
                      "Master SBE found, HUID %.8X, "
                      "skipping to look for Slave SBEs.",
                      get_huid(l_cpu_target));
            // we are just checking the Slave SBEs, skip the master
            continue;
        }

        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2ProcTarget(
                            const_cast<Target*> (l_cpu_target));

        TRACFCOMP(g_trac_isteps_trace,
                  "Running p10_get_sbe_msg_register HWP"
                  " on processor target %.8X",
                  get_huid(l_cpu_target));

        //Note no PLID passed in
        SbeRetryHandler l_SBEobj = SbeRetryHandler(
                SbeRetryHandler::SBE_MODE_OF_OPERATION::ATTEMPT_REBOOT);

        l_SBEobj.setSbeRestartMethod(SbeRetryHandler::
                                     SBE_RESTART_METHOD::START_CBS);

        // We want to tell the retry handler that we have just powered
        // on the sbe, to distinguish this case from other cases where
        // we have determined there is something wrong w/ the sbe and
        // want to diagnose the problem
        l_SBEobj.setInitialPowerOn(true);

        l_SBEobj.main_sbe_handler(l_cpu_target);

        // We will judge whether or not the SBE had a successful
        // boot if it made it to runtime
        if(l_SBEobj.isSbeAtRuntime())
        {
            // Set attribute indicating that SBE is started
            l_cpu_target->setAttr<ATTR_SBE_IS_STARTED>(1);

            // Make the FIFO call to get and apply the SBE Capabilities
            // for secondary SBEs
            l_errl = getFifoSbeCapabilities(l_cpu_target);
            if (l_errl)
            {
                TRACFCOMP(g_trac_isteps_trace, ERR_MRK
                      "proc_check_secondary_sbe_seeprom_complete: "
                      " getFifoSbeCapabilities(proc 0x%.8X) failed",
                      get_huid(l_cpu_target));

                // allow istep to continue to SBE update
                // prevent reconfig loop by removing deconfig
                l_errl->removeGardAndDeconfigure();
                // Ensure the error log is visible.
                if ( l_errl->sev() < ERRORLOG::ERRL_SEV_PREDICTIVE )
                {
                    l_errl->setSev( ERRORLOG::ERRL_SEV_PREDICTIVE );
                }
                l_errl->collectTrace("ISTEPS_TRACE", 256);
                errlCommit(l_errl, ISTEP_COMP_ID); // commit error and move on
            }

            // Switch to using SBE SCOM
            ScomSwitches l_switches =
                l_cpu_target->getAttr<ATTR_SCOM_SWITCHES>();
            ScomSwitches l_switches_before = l_switches;

            // Turn on SBE SCOM and turn off FSI SCOM.
            l_switches.useFsiScom = 0;
            l_switches.useSbeScom = 1;

            TRACFCOMP(g_trac_isteps_trace,
                      "proc_check_secondary_sbe_seeprom_complete: changing SCOM"
                      " switches from 0x%.2X to 0x%.2X for proc 0x%.8X",
                      l_switches_before,
                      l_switches,
                      get_huid(l_cpu_target));
            l_cpu_target->setAttr<ATTR_SCOM_SWITCHES>(l_switches);

            TRACFCOMP(g_trac_isteps_trace,
                      "SUCCESS : proc_check_secondary_sbe_seeprom_complete"
                      " completed ok for proc 0x%.8X",
                      get_huid(l_cpu_target));

            // Ensure that the mailbox scratch registers 1 and 2 match what we
            // calculated for functional state

            const auto l_scratch = Util::readScratchRegs(l_cpu_target);

            TRACFCOMP(g_trac_isteps_trace,
                      "proc_check_secondary_sbe_seeprom_complete: "
                      "Checking SBE functional state scratch registers on processor 0x%08x",
                      get_huid(l_cpu_target));

            l_errl = HWAS::HWASPlatVerification().verifyDeconfiguration(l_cpu_target, l_scratch);

            // This shouldn't ever fail because Hostboot pushes the values to
            // the secondary SBEs, so if it does then make the error
            // UNRECOVERABLE.
            if (l_errl)
            {
                l_errl->setSev(ERRORLOG::ERRL_SEV_UNRECOVERABLE);
                l_errl->collectTrace("ISTEPS_TRACE", 256);
                captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);
            }
        }
        else
        {
            TRACFCOMP(g_trac_isteps_trace,
                      "FAILURE : proc_check_secondary_sbe_seeprom_complete"
                      "SBE for proc 0x%.8X did not reach runtime",
                      get_huid(l_cpu_target));
           /*@
            * @reasoncode RC_FAILED_TO_BOOT_SBE
            * @severity   ERRORLOG::ERRL_SEV_UNRECOVERABLE
            * @moduleid   MOD_CHECK_SECONDARY_SBE_SEEPROM_COMPLETE
            * @userdata1  HUID of proc that failed to boot its SBE
            * @userdata2  Unused
            * @devdesc    Failed to boot a slave SBE
            * @custdesc   Processor Error
            */
            l_errl = new ErrlEntry(ERRL_SEV_UNRECOVERABLE,
                                            MOD_CHECK_SECONDARY_SBE_SEEPROM_COMPLETE,
                                            RC_FAILED_TO_BOOT_SBE,
                                            get_huid(l_cpu_target),
                                            0);
            l_errl->collectTrace("ISTEPS_TRACE", 256);
            captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);

        }

/* @TODO-RTC:100963 This should only be called when the SBE has completely
              crashed. There is a path in OpenPower where HB may get an
              attention and need to call it. For now, though, just associate
              with this story for tracking.

        // Not a way to pass in -soft_err, assuming that is default behavior
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "Running p9_extract_sbe_rc HWP"
                " on processor target %.8X",
                  TARGETING::get_huid(l_cpu_target) );

**/
        // Enable HB SPI operations to this slave processor after SBE boot
        l_errl = SPI::spiLockProcessor(l_cpu_target, false);
        if (l_errl)
        {
            // This would be a firmware bug that would be hard to
            // find later so terminate with this failure
            TRACFCOMP(g_trac_isteps_trace,
                      "ERROR : SPI unlock failed to target %.8X"
                      TRACE_ERR_FMT,
                      get_huid(l_cpu_target),
                      TRACE_ERR_ARGS(l_errl));
            captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);
            break;
        }
        // Need to switch SPI control register back to FSI_ACCESS mode
        // since SBE will flip the access mode into PIB_ACCESS
        l_errl = SPI::spiSetAccessMode(l_cpu_target, SPI::FSI_ACCESS);
        if (l_errl)
        {
            // This would be another hard to find firmware bug so terminate
            // with this failure
            TRACFCOMP(g_trac_isteps_trace,
                      "ERROR: SPI access mode switch to FSI_ACCESS failed for target %.8X"
                      TRACE_ERR_FMT,
                      get_huid(l_cpu_target),
                      TRACE_ERR_ARGS(l_errl));
            captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);
            break;
        }

    }   // end of going through all slave processors

    //  Once the sbes are up correctly, fetch all the proc ECIDs and
    //  store them in an attribute.
    for (const auto & l_cpu_target: l_cpuTargetList)
    {
      const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2ProcTarget(
                          const_cast<Target*> (l_cpu_target));

      TRACFCOMP(g_trac_isteps_trace,
                "Running p10_getecid HWP"
                " on processor target %.8X",
                get_huid(l_cpu_target));

      //  p10_getecid should set the fuse string to proper length
      fapi2::variable_buffer  l_fuseString(p10_getecid_fuseString_len);

      // Invoke the HWP
      FAPI_INVOKE_HWP(l_errl,
                      p10_getecid,
                      l_fapi2ProcTarget,
                      l_fuseString);

      if (l_errl)
      {
        if (l_cpu_target->getAttr<ATTR_HWAS_STATE>().functional)
        {
            TRACFCOMP(g_trac_isteps_trace,
                    "ERROR : p10_getecid failed, returning errorlog target %.8X"
                    TRACE_ERR_FMT,
                    get_huid(l_cpu_target),
                    TRACE_ERR_ARGS(l_errl));

            captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);
        }
        else // Not functional, proc deconfigured, don't report error
        {
            TRACFCOMP(g_trac_isteps_trace,
                      "ERROR : p10_getecid failed, proc target %.8X deconfigured",
                      get_huid(l_cpu_target));
            delete l_errl;
            l_errl = nullptr;
        }
      }
      else
      {
          TRACFCOMP(g_trac_isteps_trace,
                    "SUCCESS : proc_getecid completed ok target %.8X",
                    get_huid(l_cpu_target));

          // Update HDAT_EC to account for anything lower than the minor EC
          auto l_miniEC = l_cpu_target->getAttr<ATTR_MINI_EC>();
          if( l_miniEC != 0 )
          {
              auto l_hdatEC = l_cpu_target->getAttr<ATTR_HDAT_EC>();
              auto l_EC = l_cpu_target->getAttr<ATTR_EC>();
              auto l_newHdatEC = l_EC + l_miniEC;
              TRACFCOMP(g_trac_isteps_trace,
                        "MINI_EC=%d, HDAT_EC changing from %d->%d",
                        l_miniEC, l_hdatEC, l_newHdatEC);
              l_cpu_target->setAttr<ATTR_HDAT_EC>(l_newHdatEC);
          }
      }

    }  // end of going through all processors

    TRACFCOMP(g_trac_isteps_trace, EXIT_MRK"call_proc_check_secondary_sbe_seeprom_complete");
    return l_stepError.getErrorHandle();
}

};
<commit_msg>Unlock SPI mutex before checking for SBE boot completion<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/isteps/istep08/call_proc_check_secondary_sbe_seeprom_complete.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2020,2021                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file call_proc_check_secondary_sbe_seeprom_complete.C
 *
 *  Support file for IStep: proc_check_secondary_sbe_seeprom_complete
 *   Secondary SBE
 *
 */

/******************************************************************************/
// Includes
/******************************************************************************/

#include <hbotcompid.H>           // HWPF_COMP_ID
#include <attributeenums.H>       // TYPE_PROC
#include <isteps/hwpisteperror.H> //ISTEP_ERROR:IStepError
#include <istepHelperFuncs.H>     // captureError
#include <fapi2/plat_hwp_invoker.H>
#include <nest/nestHwpHelperFuncs.H>
#include <sbeio/sbe_retry_handler.H>
#include <sbeio/sbeioif.H>
#include <errl/errludtarget.H>
#include <spi/spi.H> // for SPI lock support
#include <p10_getecid.H>
#include <util/utilmbox_scratch.H>
#include <hwas/hwasPlat.H>

using namespace ISTEP;
using namespace ISTEP_ERROR;
using namespace ISTEPS_TRACE;
using namespace TARGETING;
using namespace ERRORLOG;
using namespace SBEIO;

namespace ISTEP_08
{

//******************************************************************************
// call_proc_check_secondary_sbe_seeprom_complete function
//******************************************************************************
void* call_proc_check_secondary_sbe_seeprom_complete( void *io_pArgs )
{
    IStepError  l_stepError;
    errlHndl_t  l_errl = nullptr;

    TRACFCOMP(g_trac_isteps_trace, ENTER_MRK"call_proc_check_secondary_sbe_seeprom_complete");

    //
    //  get the master Proc target, we want to IGNORE this one.
    //
    Target* l_pMasterProcTarget = nullptr;
    targetService().masterProcChipTargetHandle(l_pMasterProcTarget);

    //
    //  get a list of all the procs in the system
    //
    TargetHandleList l_cpuTargetList;
    getAllChips(l_cpuTargetList, TYPE_PROC);

    TRACFCOMP(g_trac_isteps_trace,
        "proc_check_secondary_sbe_seeprom_complete: %d procs in the system.",
        l_cpuTargetList.size());

    // loop thru all the cpus
    for (const auto & l_cpu_target: l_cpuTargetList)
    {
        if ( l_cpu_target  ==  l_pMasterProcTarget )
        {
            TRACFCOMP(g_trac_isteps_trace,
                      "Master SBE found, HUID %.8X, "
                      "skipping to look for Slave SBEs.",
                      get_huid(l_cpu_target));
            // we are just checking the Slave SBEs, skip the master
            continue;
        }

        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2ProcTarget(
                            const_cast<Target*> (l_cpu_target));

        TRACFCOMP(g_trac_isteps_trace,
                  "Running p10_get_sbe_msg_register HWP"
                  " on processor target %.8X",
                  get_huid(l_cpu_target));

        //Note no PLID passed in
        SbeRetryHandler l_SBEobj = SbeRetryHandler(
                SbeRetryHandler::SBE_MODE_OF_OPERATION::ATTEMPT_REBOOT);

        l_SBEobj.setSbeRestartMethod(SbeRetryHandler::
                                     SBE_RESTART_METHOD::START_CBS);

        // We want to tell the retry handler that we have just powered
        // on the sbe, to distinguish this case from other cases where
        // we have determined there is something wrong w/ the sbe and
        // want to diagnose the problem
        l_SBEobj.setInitialPowerOn(true);

        // Enable HB SPI operations to this slave processor before
        // checking for success because we may end up doing SPI
        // operations (writing MVPD) as part of the recovery.
        l_errl = SPI::spiLockProcessor(l_cpu_target, false);
        if (l_errl)
        {
            // This would be a firmware bug that would be hard to
            // find later so terminate with this failure
            TRACFCOMP(g_trac_isteps_trace,
                      "ERROR : SPI unlock failed to target %.8X"
                      TRACE_ERR_FMT,
                      get_huid(l_cpu_target),
                      TRACE_ERR_ARGS(l_errl));
            captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);
            break;
        }

        // Poll for SBE boot complete
        l_SBEobj.main_sbe_handler(l_cpu_target);

        // We will judge whether or not the SBE had a successful
        // boot if it made it to runtime
        if(l_SBEobj.isSbeAtRuntime())
        {
            // Set attribute indicating that SBE is started
            l_cpu_target->setAttr<ATTR_SBE_IS_STARTED>(1);

            // Make the FIFO call to get and apply the SBE Capabilities
            // for secondary SBEs
            l_errl = getFifoSbeCapabilities(l_cpu_target);
            if (l_errl)
            {
                TRACFCOMP(g_trac_isteps_trace, ERR_MRK
                      "proc_check_secondary_sbe_seeprom_complete: "
                      " getFifoSbeCapabilities(proc 0x%.8X) failed",
                      get_huid(l_cpu_target));

                // allow istep to continue to SBE update
                // prevent reconfig loop by removing deconfig
                l_errl->removeGardAndDeconfigure();
                // Ensure the error log is visible.
                if ( l_errl->sev() < ERRORLOG::ERRL_SEV_PREDICTIVE )
                {
                    l_errl->setSev( ERRORLOG::ERRL_SEV_PREDICTIVE );
                }
                l_errl->collectTrace("ISTEPS_TRACE", 256);
                errlCommit(l_errl, ISTEP_COMP_ID); // commit error and move on
            }

            // Switch to using SBE SCOM
            ScomSwitches l_switches =
                l_cpu_target->getAttr<ATTR_SCOM_SWITCHES>();
            ScomSwitches l_switches_before = l_switches;

            // Turn on SBE SCOM and turn off FSI SCOM.
            l_switches.useFsiScom = 0;
            l_switches.useSbeScom = 1;

            TRACFCOMP(g_trac_isteps_trace,
                      "proc_check_secondary_sbe_seeprom_complete: changing SCOM"
                      " switches from 0x%.2X to 0x%.2X for proc 0x%.8X",
                      l_switches_before,
                      l_switches,
                      get_huid(l_cpu_target));
            l_cpu_target->setAttr<ATTR_SCOM_SWITCHES>(l_switches);

            TRACFCOMP(g_trac_isteps_trace,
                      "SUCCESS : proc_check_secondary_sbe_seeprom_complete"
                      " completed ok for proc 0x%.8X",
                      get_huid(l_cpu_target));

            // Ensure that the mailbox scratch registers 1 and 2 match what we
            // calculated for functional state

            const auto l_scratch = Util::readScratchRegs(l_cpu_target);

            TRACFCOMP(g_trac_isteps_trace,
                      "proc_check_secondary_sbe_seeprom_complete: "
                      "Checking SBE functional state scratch registers on processor 0x%08x",
                      get_huid(l_cpu_target));

            l_errl = HWAS::HWASPlatVerification().verifyDeconfiguration(l_cpu_target, l_scratch);

            // This shouldn't ever fail because Hostboot pushes the values to
            // the secondary SBEs, so if it does then make the error
            // UNRECOVERABLE.
            if (l_errl)
            {
                l_errl->setSev(ERRORLOG::ERRL_SEV_UNRECOVERABLE);
                l_errl->collectTrace("ISTEPS_TRACE", 256);
                captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);
            }
        }
        else
        {
            TRACFCOMP(g_trac_isteps_trace,
                      "FAILURE : proc_check_secondary_sbe_seeprom_complete"
                      "SBE for proc 0x%.8X did not reach runtime",
                      get_huid(l_cpu_target));
           /*@
            * @reasoncode RC_FAILED_TO_BOOT_SBE
            * @severity   ERRORLOG::ERRL_SEV_UNRECOVERABLE
            * @moduleid   MOD_CHECK_SECONDARY_SBE_SEEPROM_COMPLETE
            * @userdata1  HUID of proc that failed to boot its SBE
            * @userdata2  Unused
            * @devdesc    Failed to boot a slave SBE
            * @custdesc   Processor Error
            */
            l_errl = new ErrlEntry(ERRL_SEV_UNRECOVERABLE,
                                            MOD_CHECK_SECONDARY_SBE_SEEPROM_COMPLETE,
                                            RC_FAILED_TO_BOOT_SBE,
                                            get_huid(l_cpu_target),
                                            0);
            l_errl->collectTrace("ISTEPS_TRACE", 256);
            captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);

        }

/* @TODO-RTC:100963 This should only be called when the SBE has completely
              crashed. There is a path in OpenPower where HB may get an
              attention and need to call it. For now, though, just associate
              with this story for tracking.

        // Not a way to pass in -soft_err, assuming that is default behavior
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                "Running p9_extract_sbe_rc HWP"
                " on processor target %.8X",
                  TARGETING::get_huid(l_cpu_target) );

**/
        // Need to switch SPI control register back to FSI_ACCESS mode
        // since SBE will flip the access mode into PIB_ACCESS
        l_errl = SPI::spiSetAccessMode(l_cpu_target, SPI::FSI_ACCESS);
        if (l_errl)
        {
            // This would be another hard to find firmware bug so terminate
            // with this failure
            TRACFCOMP(g_trac_isteps_trace,
                      "ERROR: SPI access mode switch to FSI_ACCESS failed for target %.8X"
                      TRACE_ERR_FMT,
                      get_huid(l_cpu_target),
                      TRACE_ERR_ARGS(l_errl));
            captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);
            break;
        }

    }   // end of going through all slave processors

    //  Once the sbes are up correctly, fetch all the proc ECIDs and
    //  store them in an attribute.
    for (const auto & l_cpu_target: l_cpuTargetList)
    {
      const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP> l_fapi2ProcTarget(
                          const_cast<Target*> (l_cpu_target));

      TRACFCOMP(g_trac_isteps_trace,
                "Running p10_getecid HWP"
                " on processor target %.8X",
                get_huid(l_cpu_target));

      //  p10_getecid should set the fuse string to proper length
      fapi2::variable_buffer  l_fuseString(p10_getecid_fuseString_len);

      // Invoke the HWP
      FAPI_INVOKE_HWP(l_errl,
                      p10_getecid,
                      l_fapi2ProcTarget,
                      l_fuseString);

      if (l_errl)
      {
        if (l_cpu_target->getAttr<ATTR_HWAS_STATE>().functional)
        {
            TRACFCOMP(g_trac_isteps_trace,
                    "ERROR : p10_getecid failed, returning errorlog target %.8X"
                    TRACE_ERR_FMT,
                    get_huid(l_cpu_target),
                    TRACE_ERR_ARGS(l_errl));

            captureError(l_errl, l_stepError, HWPF_COMP_ID, l_cpu_target);
        }
        else // Not functional, proc deconfigured, don't report error
        {
            TRACFCOMP(g_trac_isteps_trace,
                      "ERROR : p10_getecid failed, proc target %.8X deconfigured",
                      get_huid(l_cpu_target));
            delete l_errl;
            l_errl = nullptr;
        }
      }
      else
      {
          TRACFCOMP(g_trac_isteps_trace,
                    "SUCCESS : proc_getecid completed ok target %.8X",
                    get_huid(l_cpu_target));

          // Update HDAT_EC to account for anything lower than the minor EC
          auto l_miniEC = l_cpu_target->getAttr<ATTR_MINI_EC>();
          if( l_miniEC != 0 )
          {
              auto l_hdatEC = l_cpu_target->getAttr<ATTR_HDAT_EC>();
              auto l_EC = l_cpu_target->getAttr<ATTR_EC>();
              auto l_newHdatEC = l_EC + l_miniEC;
              TRACFCOMP(g_trac_isteps_trace,
                        "MINI_EC=%d, HDAT_EC changing from %d->%d",
                        l_miniEC, l_hdatEC, l_newHdatEC);
              l_cpu_target->setAttr<ATTR_HDAT_EC>(l_newHdatEC);
          }
      }

    }  // end of going through all processors

    TRACFCOMP(g_trac_isteps_trace, EXIT_MRK"call_proc_check_secondary_sbe_seeprom_complete");
    return l_stepError.getErrorHandle();
}

};
<|endoftext|>


<commit_before>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/browser/application_tizen.h"

#include <set>
#include <string>
#include <vector>

#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"

#include "xwalk/runtime/browser/ui/native_app_window.h"
#include "xwalk/runtime/common/xwalk_common_messages.h"

#if defined(USE_OZONE)
#include "base/message_loop/message_pump_ozone.h"
#include "content/public/browser/render_view_host.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/keycodes/keyboard_codes_posix.h"
#include "xwalk/application/common/manifest_handlers/tizen_setting_handler.h"
#endif

#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/manifest_handlers/navigation_handler.h"

namespace xwalk {

namespace widget_keys = application_widget_keys;

namespace application {

namespace {
const char kAsterisk[] = "*";
}  // namespace

ApplicationTizen::ApplicationTizen(
    scoped_refptr<ApplicationData> data,
    RuntimeContext* runtime_context,
    Application::Observer* observer)
    : Application(data, runtime_context, observer) {
#if defined(USE_OZONE)
  base::MessagePumpOzone::Current()->AddObserver(this);
#endif
}

ApplicationTizen::~ApplicationTizen() {
#if defined(USE_OZONE)
  base::MessagePumpOzone::Current()->RemoveObserver(this);
#endif
}

void ApplicationTizen::Hide() {
  DCHECK(runtimes_.size());
  std::set<Runtime*>::iterator it = runtimes_.begin();
  for (; it != runtimes_.end(); ++it) {
    if ((*it)->window())
      (*it)->window()->Hide();
  }
}

void ApplicationTizen::InitSecurityPolicy() {
  // On Tizen, CSP mode has higher priority, and WARP will be disabled
  // if the application is under CSP mode.
  if (!data_->HasCSPDefined()) {
    Application::InitSecurityPolicy();
    return;
  }

  if (data_->GetPackageType() != Package::WGT)
    return;

  // Always enable security mode when under CSP mode.
  security_mode_enabled_ = true;
  NavigationInfo* info = static_cast<NavigationInfo*>(
      data_->GetManifestData(widget_keys::kAllowNavigationKey));
  if (info) {
    const std::vector<std::string>& allowed_list = info->GetAllowedDomains();
    for (std::vector<std::string>::const_iterator it = allowed_list.begin();
         it != allowed_list.end(); ++it) {
      // If the policy is "*", it represents that any external link is allowed
      // to navigate to.
      if ((*it) == kAsterisk) {
        security_mode_enabled_ = false;
        return;
      }

      // If the policy start with "*.", like this: *.domain,
      // means that can access to all subdomains for 'domain',
      // otherwise, the host of request url should exactly the same
      // as policy.
      bool subdomains = ((*it).find("*.") == 0);
      std::string host = subdomains ? (*it).substr(2) : (*it);
      AddSecurityPolicy(GURL("http://" + host), subdomains);
      AddSecurityPolicy(GURL("https://" + host), subdomains);
    }
  }
  DCHECK(render_process_host_);
  render_process_host_->Send(
      new ViewMsg_EnableSecurityMode(
          ApplicationData::GetBaseURLFromApplicationId(id()),
          SecurityPolicy::CSP));
}

#if defined(USE_OZONE)
base::EventStatus ApplicationTizen::WillProcessEvent(
    const base::NativeEvent& event) {
  return base::EVENT_CONTINUE;
}

void ApplicationTizen::DidProcessEvent(
    const base::NativeEvent& event) {
  ui::Event* ui_event = static_cast<ui::Event*>(event);
  if (!ui_event->IsKeyEvent() || ui_event->type() != ui::ET_KEY_PRESSED)
    return;

  ui::KeyEvent* key_event = static_cast<ui::KeyEvent*>(ui_event);

  // FIXME: Most Wayland devices don't have similar hardware button for 'back'
  // and 'memu' as Tizen Mobile, even that hardare buttons could be different
  // across different kinds of Wayland platforms.
  // Here use external keyboard button 'Backspace' & 'HOME' to emulate 'back'
  // and 'menu' key. Should change this if there is customized key binding.
  if (key_event->key_code() != ui::VKEY_BACK &&
      key_event->key_code() != ui::VKEY_HOME)
    return;

  TizenSettingInfo* info = static_cast<TizenSettingInfo*>(
      data()->GetManifestData(widget_keys::kTizenSettingKey));
  if (info && !info->hwkey_enabled())
    return;

  for (std::set<xwalk::Runtime*>::iterator it = runtimes_.begin();
      it != runtimes_.end(); ++it) {
    (*it)->web_contents()->GetRenderViewHost()->Send(new ViewMsg_HWKeyPressed(
        (*it)->web_contents()->GetRoutingID(), key_event->key_code()));
  }
}
#endif

}  // namespace application
}  // namespace xwalk
<commit_msg>[Tizen][Runtime] Add default csp support for tizen.<commit_after>// Copyright (c) 2013 Intel Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "xwalk/application/browser/application_tizen.h"

#include <set>
#include <string>
#include <vector>

#include "content/public/browser/web_contents.h"
#include "content/public/browser/render_process_host.h"

#include "xwalk/runtime/browser/ui/native_app_window.h"
#include "xwalk/runtime/common/xwalk_common_messages.h"

#if defined(USE_OZONE)
#include "base/message_loop/message_pump_ozone.h"
#include "content/public/browser/render_view_host.h"
#include "ui/events/event.h"
#include "ui/events/event_constants.h"
#include "ui/events/keycodes/keyboard_codes_posix.h"
#include "xwalk/application/common/manifest_handlers/tizen_setting_handler.h"
#endif

#include "xwalk/application/common/application_manifest_constants.h"
#include "xwalk/application/common/manifest_handlers/csp_handler.h"
#include "xwalk/application/common/manifest_handlers/navigation_handler.h"

namespace xwalk {

namespace widget_keys = application_widget_keys;

namespace application {

namespace {
const char kAsterisk[] = "*";

const char kDirectiveValueSelf[] = "'self'";
const char kDirectiveValueNone[] = "'none'";

const char kDirectiveNameDefault[] = "default-src";
const char kDirectiveNameScript[] = "script-src";
const char kDirectiveNameStyle[] = "style-src";
const char kDirectiveNameObject[] = "object-src";

CSPInfo* GetDefaultCSPInfo() {
  static CSPInfo default_csp_info;
  if (default_csp_info.GetDirectives().empty()) {
    std::vector<std::string> directive_all;
    std::vector<std::string> directive_self;
    std::vector<std::string> directive_none;
    directive_all.push_back(kAsterisk);
    directive_self.push_back(kDirectiveValueSelf);
    directive_none.push_back(kDirectiveValueNone);

    default_csp_info.SetDirective(kDirectiveNameDefault, directive_all);
    default_csp_info.SetDirective(kDirectiveNameScript, directive_self);
    default_csp_info.SetDirective(kDirectiveNameStyle, directive_self);
    default_csp_info.SetDirective(kDirectiveNameObject, directive_none);
  }

  return (new CSPInfo(default_csp_info));
}

}  // namespace

ApplicationTizen::ApplicationTizen(
    scoped_refptr<ApplicationData> data,
    RuntimeContext* runtime_context,
    Application::Observer* observer)
    : Application(data, runtime_context, observer) {
#if defined(USE_OZONE)
  base::MessagePumpOzone::Current()->AddObserver(this);
#endif
}

ApplicationTizen::~ApplicationTizen() {
#if defined(USE_OZONE)
  base::MessagePumpOzone::Current()->RemoveObserver(this);
#endif
}

void ApplicationTizen::Hide() {
  DCHECK(runtimes_.size());
  std::set<Runtime*>::iterator it = runtimes_.begin();
  for (; it != runtimes_.end(); ++it) {
    if ((*it)->window())
      (*it)->window()->Hide();
  }
}

void ApplicationTizen::InitSecurityPolicy() {
  // On Tizen, CSP mode has higher priority, and WARP will be disabled
  // if the application is under CSP mode.
  if (!data_->HasCSPDefined()) {
    Application::InitSecurityPolicy();
    return;
  }

  if (data_->GetPackageType() != Package::WGT)
    return;

  CSPInfo* csp_info =
      static_cast<CSPInfo*>(data_->GetManifestData(widget_keys::kCSPKey));
  if (!csp_info || csp_info->GetDirectives().empty())
    data_->SetManifestData(widget_keys::kCSPKey, GetDefaultCSPInfo());

  // Always enable security mode when under CSP mode.
  security_mode_enabled_ = true;
  NavigationInfo* info = static_cast<NavigationInfo*>(
      data_->GetManifestData(widget_keys::kAllowNavigationKey));
  if (info) {
    const std::vector<std::string>& allowed_list = info->GetAllowedDomains();
    for (std::vector<std::string>::const_iterator it = allowed_list.begin();
         it != allowed_list.end(); ++it) {
      // If the policy is "*", it represents that any external link is allowed
      // to navigate to.
      if ((*it) == kAsterisk) {
        security_mode_enabled_ = false;
        return;
      }

      // If the policy start with "*.", like this: *.domain,
      // means that can access to all subdomains for 'domain',
      // otherwise, the host of request url should exactly the same
      // as policy.
      bool subdomains = ((*it).find("*.") == 0);
      std::string host = subdomains ? (*it).substr(2) : (*it);
      AddSecurityPolicy(GURL("http://" + host), subdomains);
      AddSecurityPolicy(GURL("https://" + host), subdomains);
    }
  }
  DCHECK(render_process_host_);
  render_process_host_->Send(
      new ViewMsg_EnableSecurityMode(
          ApplicationData::GetBaseURLFromApplicationId(id()),
          SecurityPolicy::CSP));
}

#if defined(USE_OZONE)
base::EventStatus ApplicationTizen::WillProcessEvent(
    const base::NativeEvent& event) {
  return base::EVENT_CONTINUE;
}

void ApplicationTizen::DidProcessEvent(
    const base::NativeEvent& event) {
  ui::Event* ui_event = static_cast<ui::Event*>(event);
  if (!ui_event->IsKeyEvent() || ui_event->type() != ui::ET_KEY_PRESSED)
    return;

  ui::KeyEvent* key_event = static_cast<ui::KeyEvent*>(ui_event);

  // FIXME: Most Wayland devices don't have similar hardware button for 'back'
  // and 'memu' as Tizen Mobile, even that hardare buttons could be different
  // across different kinds of Wayland platforms.
  // Here use external keyboard button 'Backspace' & 'HOME' to emulate 'back'
  // and 'menu' key. Should change this if there is customized key binding.
  if (key_event->key_code() != ui::VKEY_BACK &&
      key_event->key_code() != ui::VKEY_HOME)
    return;

  TizenSettingInfo* info = static_cast<TizenSettingInfo*>(
      data()->GetManifestData(widget_keys::kTizenSettingKey));
  if (info && !info->hwkey_enabled())
    return;

  for (std::set<xwalk::Runtime*>::iterator it = runtimes_.begin();
      it != runtimes_.end(); ++it) {
    (*it)->web_contents()->GetRenderViewHost()->Send(new ViewMsg_HWKeyPressed(
        (*it)->web_contents()->GetRoutingID(), key_event->key_code()));
  }
}
#endif

}  // namespace application
}  // namespace xwalk
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "projectbuilder.h"

// appleseed.studio headers.
#include "mainwindow/project/assemblyinstancecollectionitem.h"
#include "mainwindow/project/exceptioninvalidentityname.h"
#include "mainwindow/project/texturecollectionitem.h"
#include "mainwindow/project/textureinstancecollectionitem.h"

// appleseed.renderer headers.
#include "renderer/api/object.h"
#include "renderer/api/project.h"
#include "renderer/api/scene.h"
#include "renderer/api/texture.h"

// appleseed.foundation headers.
#include "foundation/math/matrix.h"
#include "foundation/math/transform.h"
#include "foundation/utility/containers/specializedarrays.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/string.h"

// boost headers.
#include "boost/filesystem/path.hpp"

// Standard headers.
#include <memory>

using namespace boost;
using namespace foundation;
using namespace renderer;
using namespace std;

namespace appleseed {
namespace studio {

ProjectBuilder::ProjectBuilder(
    Project&            project,
    ProjectTree&        project_tree)
  : m_project(project)
  , m_project_tree(project_tree)
{
}

void ProjectBuilder::notify_project_modification() const
{
    emit signal_project_modified();
}

void ProjectBuilder::insert_assembly(
    const string&       name) const
{
    auto_release_ptr<Assembly> assembly(
        AssemblyFactory::create(name.c_str(), ParamArray()));

    m_project_tree.get_assembly_collection_item().add_item(assembly.get());

    m_project.get_scene()->assemblies().insert(assembly);

    notify_project_modification();
}

void ProjectBuilder::insert_assembly_instance(
    const string&       name,
    Assembly&           assembly) const
{
    auto_release_ptr<AssemblyInstance> assembly_instance(
        AssemblyInstanceFactory::create(
            name.c_str(),
            assembly,
            Transformd(Matrix4d::identity())));

    m_project_tree.add_item(assembly_instance.get());

    Scene* scene = m_project.get_scene();
    scene->assembly_instances().insert(assembly_instance);
    scene->bump_geometry_version_id();

    notify_project_modification();
}

void ProjectBuilder::remove_assembly_instance(
    const UniqueID      assembly_instance_id) const
{
    m_project_tree
        .get_assembly_instance_collection_item()
            .remove_item(assembly_instance_id);

    Scene* scene = m_project.get_scene();
    scene->assembly_instances().remove(assembly_instance_id);
    scene->bump_geometry_version_id();

    notify_project_modification();
}

void ProjectBuilder::insert_objects(
    Assembly&           assembly,
    const string&       path) const
{
    const string base_object_name = filesystem::path(path).replace_extension().filename();

    const MeshObjectArray mesh_objects =
        MeshObjectReader().read(
            path.c_str(),
            base_object_name.c_str(),
            ParamArray());

    for (size_t i = 0; i < mesh_objects.size(); ++i)
    {
        MeshObject* object = mesh_objects[i];

        object->get_parameters().insert("filename", filesystem::path(path).filename());
        object->get_parameters().insert("__common_base_name", base_object_name);

        m_project_tree.get_assembly_collection_item().get_item(assembly).add_item(object);

        const size_t object_index =
            assembly.objects().insert(auto_release_ptr<Object>(object));

        const string object_instance_name = string(object->get_name()) + "_inst";

        auto_release_ptr<ObjectInstance> object_instance(
            ObjectInstanceFactory::create(
                object_instance_name.c_str(),
                *object,
                object_index,
                Transformd(Matrix4d::identity()),
                StringArray()));

        m_project_tree.get_assembly_collection_item().get_item(assembly).add_item(object_instance.get());

        assembly.object_instances().insert(object_instance);
    }

    assembly.bump_version_id();

    if (!mesh_objects.empty())
        notify_project_modification();
}

namespace
{
    auto_release_ptr<Texture> create_texture(
        const string&   path)
    {
        const string texture_name = filesystem::path(path).replace_extension().filename();

        ParamArray texture_params;
        texture_params.insert("filename", path);
        texture_params.insert("color_space", "srgb");

        SearchPaths search_paths;
        return auto_release_ptr<Texture>(
            DiskTexture2dFactory().create(
                texture_name.c_str(),
                texture_params,
                search_paths));
    }

    auto_release_ptr<TextureInstance> create_texture_instance(
        const string&   texture_name,
        const size_t    texture_index)
    {
        const string texture_instance_name = texture_name + "_inst";

        ParamArray texture_instance_params;
        texture_instance_params.insert("addressing_mode", "clamp");
        texture_instance_params.insert("filtering_mode", "bilinear");

        return auto_release_ptr<TextureInstance>(
            TextureInstanceFactory::create(
                texture_instance_name.c_str(),
                texture_instance_params,
                texture_index));
    }
}

void ProjectBuilder::insert_textures(
    Assembly&           assembly,
    const string&       path) const
{
    auto_release_ptr<Texture> texture = create_texture(path);
    const string texture_name = texture->get_name();

    m_project_tree.get_assembly_collection_item().get_item(assembly).add_item(texture.get());

    const size_t texture_index = assembly.textures().insert(texture);

    auto_release_ptr<TextureInstance> texture_instance =
        create_texture_instance(texture_name, texture_index);

    m_project_tree.get_assembly_collection_item().get_item(assembly).add_item(texture_instance.get());

    assembly.texture_instances().insert(texture_instance);

    notify_project_modification();
}

void ProjectBuilder::insert_textures(
    const string&       path) const
{
    const Scene& scene = *m_project.get_scene();

    auto_release_ptr<Texture> texture = create_texture(path);
    const string texture_name = texture->get_name();

    m_project_tree.add_item(texture.get());

    const size_t texture_index = scene.textures().insert(texture);

    auto_release_ptr<TextureInstance> texture_instance =
        create_texture_instance(texture_name, texture_index);

    m_project_tree.add_item(texture_instance.get());

    scene.texture_instances().insert(texture_instance);

    notify_project_modification();
}

string ProjectBuilder::get_entity_name(const Dictionary& values)
{
    if (!values.strings().exist(EntityEditorFormFactoryBase::NameParameter))
        throw ExceptionInvalidEntityName();

    const string name = trim_both(
        values.get<string>(EntityEditorFormFactoryBase::NameParameter));

    if (!is_valid_entity_name(name))
        throw ExceptionInvalidEntityName();

    return name;
}

bool ProjectBuilder::is_valid_entity_name(const string& name)
{
    return !name.empty();
}

}   // namespace studio
}   // namespace appleseed
<commit_msg>minor code simplification.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2011 Francois Beaune
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "projectbuilder.h"

// appleseed.studio headers.
#include "mainwindow/project/assemblyinstancecollectionitem.h"
#include "mainwindow/project/exceptioninvalidentityname.h"
#include "mainwindow/project/texturecollectionitem.h"
#include "mainwindow/project/textureinstancecollectionitem.h"

// appleseed.renderer headers.
#include "renderer/api/object.h"
#include "renderer/api/project.h"
#include "renderer/api/scene.h"
#include "renderer/api/texture.h"

// appleseed.foundation headers.
#include "foundation/math/matrix.h"
#include "foundation/math/transform.h"
#include "foundation/utility/containers/specializedarrays.h"
#include "foundation/utility/searchpaths.h"
#include "foundation/utility/foreach.h"
#include "foundation/utility/string.h"

// boost headers.
#include "boost/filesystem/path.hpp"

// Standard headers.
#include <memory>

using namespace boost;
using namespace foundation;
using namespace renderer;
using namespace std;

namespace appleseed {
namespace studio {

ProjectBuilder::ProjectBuilder(
    Project&            project,
    ProjectTree&        project_tree)
  : m_project(project)
  , m_project_tree(project_tree)
{
}

void ProjectBuilder::notify_project_modification() const
{
    emit signal_project_modified();
}

void ProjectBuilder::insert_assembly(
    const string&       name) const
{
    auto_release_ptr<Assembly> assembly(
        AssemblyFactory::create(name.c_str(), ParamArray()));

    m_project_tree.add_item(assembly.get());

    m_project.get_scene()->assemblies().insert(assembly);

    notify_project_modification();
}

void ProjectBuilder::insert_assembly_instance(
    const string&       name,
    Assembly&           assembly) const
{
    auto_release_ptr<AssemblyInstance> assembly_instance(
        AssemblyInstanceFactory::create(
            name.c_str(),
            assembly,
            Transformd(Matrix4d::identity())));

    m_project_tree.add_item(assembly_instance.get());

    Scene* scene = m_project.get_scene();
    scene->assembly_instances().insert(assembly_instance);
    scene->bump_geometry_version_id();

    notify_project_modification();
}

void ProjectBuilder::remove_assembly_instance(
    const UniqueID      assembly_instance_id) const
{
    m_project_tree
        .get_assembly_instance_collection_item()
            .remove_item(assembly_instance_id);

    Scene* scene = m_project.get_scene();
    scene->assembly_instances().remove(assembly_instance_id);
    scene->bump_geometry_version_id();

    notify_project_modification();
}

void ProjectBuilder::insert_objects(
    Assembly&           assembly,
    const string&       path) const
{
    const string base_object_name = filesystem::path(path).replace_extension().filename();

    const MeshObjectArray mesh_objects =
        MeshObjectReader().read(
            path.c_str(),
            base_object_name.c_str(),
            ParamArray());

    for (size_t i = 0; i < mesh_objects.size(); ++i)
    {
        MeshObject* object = mesh_objects[i];

        object->get_parameters().insert("filename", filesystem::path(path).filename());
        object->get_parameters().insert("__common_base_name", base_object_name);

        m_project_tree.get_assembly_collection_item().get_item(assembly).add_item(object);

        const size_t object_index =
            assembly.objects().insert(auto_release_ptr<Object>(object));

        const string object_instance_name = string(object->get_name()) + "_inst";

        auto_release_ptr<ObjectInstance> object_instance(
            ObjectInstanceFactory::create(
                object_instance_name.c_str(),
                *object,
                object_index,
                Transformd(Matrix4d::identity()),
                StringArray()));

        m_project_tree.get_assembly_collection_item().get_item(assembly).add_item(object_instance.get());

        assembly.object_instances().insert(object_instance);
    }

    assembly.bump_version_id();

    if (!mesh_objects.empty())
        notify_project_modification();
}

namespace
{
    auto_release_ptr<Texture> create_texture(
        const string&   path)
    {
        const string texture_name = filesystem::path(path).replace_extension().filename();

        ParamArray texture_params;
        texture_params.insert("filename", path);
        texture_params.insert("color_space", "srgb");

        SearchPaths search_paths;
        return auto_release_ptr<Texture>(
            DiskTexture2dFactory().create(
                texture_name.c_str(),
                texture_params,
                search_paths));
    }

    auto_release_ptr<TextureInstance> create_texture_instance(
        const string&   texture_name,
        const size_t    texture_index)
    {
        const string texture_instance_name = texture_name + "_inst";

        ParamArray texture_instance_params;
        texture_instance_params.insert("addressing_mode", "clamp");
        texture_instance_params.insert("filtering_mode", "bilinear");

        return auto_release_ptr<TextureInstance>(
            TextureInstanceFactory::create(
                texture_instance_name.c_str(),
                texture_instance_params,
                texture_index));
    }
}

void ProjectBuilder::insert_textures(
    Assembly&           assembly,
    const string&       path) const
{
    auto_release_ptr<Texture> texture = create_texture(path);
    const string texture_name = texture->get_name();

    m_project_tree.get_assembly_collection_item().get_item(assembly).add_item(texture.get());

    const size_t texture_index = assembly.textures().insert(texture);

    auto_release_ptr<TextureInstance> texture_instance =
        create_texture_instance(texture_name, texture_index);

    m_project_tree.get_assembly_collection_item().get_item(assembly).add_item(texture_instance.get());

    assembly.texture_instances().insert(texture_instance);

    notify_project_modification();
}

void ProjectBuilder::insert_textures(
    const string&       path) const
{
    const Scene& scene = *m_project.get_scene();

    auto_release_ptr<Texture> texture = create_texture(path);
    const string texture_name = texture->get_name();

    m_project_tree.add_item(texture.get());

    const size_t texture_index = scene.textures().insert(texture);

    auto_release_ptr<TextureInstance> texture_instance =
        create_texture_instance(texture_name, texture_index);

    m_project_tree.add_item(texture_instance.get());

    scene.texture_instances().insert(texture_instance);

    notify_project_modification();
}

string ProjectBuilder::get_entity_name(const Dictionary& values)
{
    if (!values.strings().exist(EntityEditorFormFactoryBase::NameParameter))
        throw ExceptionInvalidEntityName();

    const string name = trim_both(
        values.get<string>(EntityEditorFormFactoryBase::NameParameter));

    if (!is_valid_entity_name(name))
        throw ExceptionInvalidEntityName();

    return name;
}

bool ProjectBuilder::is_valid_entity_name(const string& name)
{
    return !name.empty();
}

}   // namespace studio
}   // namespace appleseed
<|endoftext|>