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

#include <string.h>

#include "chrome/browser/chromeos/bluetooth/bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/test/mock_bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/test/mock_bluetooth_device.h"
#include "chrome/browser/chromeos/extensions/bluetooth_event_router.h"
#include "chrome/browser/extensions/api/bluetooth/bluetooth_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/ui/browser.h"
#include "chromeos/dbus/bluetooth_out_of_band_client.h"
#include "testing/gmock/include/gmock/gmock.h"

using extensions::Extension;

namespace utils = extension_function_test_utils;
namespace api = extensions::api;

namespace chromeos {

class BluetoothAdapater;

}  // namespace chromeos

namespace {

class BluetoothApiTest : public PlatformAppApiTest {
 public:
  BluetoothApiTest() : empty_extension_(utils::CreateEmptyExtension()) {}

  virtual void SetUpOnMainThread() OVERRIDE {
    // The browser will clean this up when it is torn down
    mock_adapter_ = new testing::StrictMock<chromeos::MockBluetoothAdapter>;
    event_router()->SetAdapterForTest(mock_adapter_);
  }

  void expectBooleanResult(bool expected,
                           UIThreadExtensionFunction* function,
                           const std::string& args) {
    scoped_ptr<base::Value> result(
        utils::RunFunctionAndReturnResult(function, args, browser()));
    ASSERT_TRUE(result.get() != NULL);
    ASSERT_EQ(base::Value::TYPE_BOOLEAN, result->GetType());
    bool boolean_value;
    result->GetAsBoolean(&boolean_value);
    EXPECT_EQ(expected, boolean_value);
  }

  template <class T>
  T* setupFunction(T* function) {
    function->set_extension(empty_extension_.get());
    function->set_has_callback(true);
    return function;
  }

 protected:
  testing::StrictMock<chromeos::MockBluetoothAdapter>* mock_adapter_;

 private:
  chromeos::ExtensionBluetoothEventRouter* event_router() {
    return browser()->profile()->GetExtensionService()->
        bluetooth_event_router();
  }

  chromeos::BluetoothAdapter* original_adapter_;
  scoped_refptr<Extension> empty_extension_;
};

static const char kOutOfBandPairingDataHash[] = "0123456789ABCDEh";
static const char kOutOfBandPairingDataRandomizer[] = "0123456789ABCDEr";

static chromeos::BluetoothOutOfBandPairingData GetOutOfBandPairingData() {
  chromeos::BluetoothOutOfBandPairingData data;
  memcpy(&(data.hash), kOutOfBandPairingDataHash,
      chromeos::kBluetoothOutOfBandPairingDataSize);
  memcpy(&(data.randomizer), kOutOfBandPairingDataRandomizer,
      chromeos::kBluetoothOutOfBandPairingDataSize);
  return data;
}

static bool CallClosure(const base::Closure& callback) {
  callback.Run();
  return true;
}

static bool CallOutOfBandPairingDataCallback(
      const chromeos::BluetoothAdapter::BluetoothOutOfBandPairingDataCallback&
          callback) {
  callback.Run(GetOutOfBandPairingData());
  return true;
}

}  // namespace

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsAvailable) {
  EXPECT_CALL(*mock_adapter_, IsPresent())
      .WillOnce(testing::Return(false));

  scoped_refptr<api::BluetoothIsAvailableFunction> is_available;

  is_available = setupFunction(new api::BluetoothIsAvailableFunction);
  expectBooleanResult(false, is_available, "[]");

  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  EXPECT_CALL(*mock_adapter_, IsPresent())
      .WillOnce(testing::Return(true));

  is_available = setupFunction(new api::BluetoothIsAvailableFunction);
  expectBooleanResult(true, is_available, "[]");
}

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsPowered) {
  EXPECT_CALL(*mock_adapter_, IsPowered())
      .WillOnce(testing::Return(false));

  scoped_refptr<api::BluetoothIsPoweredFunction> is_powered;

  is_powered = setupFunction(new api::BluetoothIsPoweredFunction);
  expectBooleanResult(false, is_powered, "[]");

  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  EXPECT_CALL(*mock_adapter_, IsPowered())
      .WillOnce(testing::Return(true));

  is_powered = setupFunction(new api::BluetoothIsPoweredFunction);
  expectBooleanResult(true, is_powered, "[]");
}

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevices) {
  testing::NiceMock<chromeos::MockBluetoothDevice> device1(
      mock_adapter_, "d1", "11:12:13:14:15:16",
      true /* paired */, false /* bonded */, true /* connected */);
  testing::NiceMock<chromeos::MockBluetoothDevice> device2(
      mock_adapter_, "d2", "21:22:23:24:25:26",
      false /* paired */, true /* bonded */, false /* connected */);
  chromeos::BluetoothAdapter::ConstDeviceList devices;
  devices.push_back(&device1);
  devices.push_back(&device2);

  EXPECT_CALL(device1, ProvidesServiceWithUUID("foo"))
      .WillOnce(testing::Return(false));
  EXPECT_CALL(device2, ProvidesServiceWithUUID("foo"))
      .WillOnce(testing::Return(true));

  EXPECT_CALL(*mock_adapter_, GetDevices())
      .WillOnce(testing::Return(devices));

  scoped_refptr<api::BluetoothGetDevicesFunction> get_devices;

  get_devices = setupFunction(new api::BluetoothGetDevicesFunction);
  scoped_ptr<base::Value> result(utils::RunFunctionAndReturnResult(
        get_devices,
        "[{\"uuid\":\"foo\"}]",
        browser()));

  ASSERT_EQ(base::Value::TYPE_LIST, result->GetType());
  base::ListValue* list;
  ASSERT_TRUE(result->GetAsList(&list));

  EXPECT_EQ(1u, list->GetSize());
  base::Value* device_value;
  EXPECT_TRUE(list->Get(0, &device_value));
  EXPECT_EQ(base::Value::TYPE_DICTIONARY, device_value->GetType());
  base::DictionaryValue* device;
  ASSERT_TRUE(device_value->GetAsDictionary(&device));

  std::string name;
  ASSERT_TRUE(device->GetString("name", &name));
  EXPECT_EQ("d2", name);
  std::string address;
  ASSERT_TRUE(device->GetString("address", &address));
  EXPECT_EQ("21:22:23:24:25:26", address);
  bool paired;
  ASSERT_TRUE(device->GetBoolean("paired", &paired));
  EXPECT_FALSE(paired);
  bool bonded;
  ASSERT_TRUE(device->GetBoolean("bonded", &bonded));
  EXPECT_TRUE(bonded);
  bool connected;
  ASSERT_TRUE(device->GetBoolean("connected", &connected));
  EXPECT_FALSE(connected);

  // Try again with no options
  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  EXPECT_CALL(*mock_adapter_, GetDevices())
      .WillOnce(testing::Return(devices));

  get_devices = setupFunction(new api::BluetoothGetDevicesFunction);
  result.reset(
      utils::RunFunctionAndReturnResult(get_devices, "[{}]", browser()));

  ASSERT_EQ(base::Value::TYPE_LIST, result->GetType());
  ASSERT_TRUE(result->GetAsList(&list));

  EXPECT_EQ(2u, list->GetSize());
}

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetLocalOutOfBandPairingData) {
  EXPECT_CALL(*mock_adapter_,
              ReadLocalOutOfBandPairingData(
                  testing::Truly(CallOutOfBandPairingDataCallback),
                  testing::_));

  scoped_refptr<api::BluetoothGetLocalOutOfBandPairingDataFunction>
      get_oob_function(setupFunction(
            new api::BluetoothGetLocalOutOfBandPairingDataFunction));

  scoped_ptr<base::Value> result(
      utils::RunFunctionAndReturnResult(get_oob_function, "[]", browser()));

  base::DictionaryValue* dict;
  EXPECT_TRUE(result->GetAsDictionary(&dict));

  base::BinaryValue* binary_value;
  EXPECT_TRUE(dict->GetBinary("hash", &binary_value));
  EXPECT_STREQ(kOutOfBandPairingDataHash,
      std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str());
  EXPECT_TRUE(dict->GetBinary("randomizer", &binary_value));
  EXPECT_STREQ(kOutOfBandPairingDataRandomizer,
      std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str());

  // Try again with an error
  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  EXPECT_CALL(*mock_adapter_,
              ReadLocalOutOfBandPairingData(
                  testing::_,
                  testing::Truly(CallClosure)));

  get_oob_function =
      setupFunction(new api::BluetoothGetLocalOutOfBandPairingDataFunction);

  std::string error(
      utils::RunFunctionAndReturnError(get_oob_function, "[]", browser()));
  EXPECT_FALSE(error.empty());
}

// Fails under ASan, see http://crbug.com/133199.
#if defined(ADDRESS_SANITIZER)
#define MAYBE_SetOutOfBandPairingData DISABLED_SetOutOfBandPairingData
#else
#define MAYBE_SetOutOfBandPairingData SetOutOfBandPairingData
#endif
IN_PROC_BROWSER_TEST_F(BluetoothApiTest, MAYBE_SetOutOfBandPairingData) {
  std::string device_address("11:12:13:14:15:16");
  testing::NiceMock<chromeos::MockBluetoothDevice> device(
      mock_adapter_, "d1", device_address,
      true /* paired */, false /* bonded */, true /* connected */);
  EXPECT_CALL(*mock_adapter_, GetDevice(device_address))
      .WillOnce(testing::Return(&device));
  EXPECT_CALL(device,
              ClearOutOfBandPairingData(testing::Truly(CallClosure),
                                        testing::_));

  char buf[64];
  snprintf(buf, sizeof(buf),
           "[{\"device_address\":\"%s\"}]", device_address.c_str());
  std::string params(buf);

  scoped_refptr<api::BluetoothSetOutOfBandPairingDataFunction> set_oob_function;
  set_oob_function = setupFunction(
      new api::BluetoothSetOutOfBandPairingDataFunction);
  // There isn't actually a result.
  (void)utils::RunFunctionAndReturnResult(set_oob_function, params, browser());

  // Try again with an error
  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  testing::Mock::VerifyAndClearExpectations(&device);
  EXPECT_CALL(*mock_adapter_, GetDevice(device_address))
      .WillOnce(testing::Return(&device));
  EXPECT_CALL(device,
              ClearOutOfBandPairingData(testing::_,
                                        testing::Truly(CallClosure)));

  set_oob_function = setupFunction(
      new api::BluetoothSetOutOfBandPairingDataFunction);
  std::string error(
      utils::RunFunctionAndReturnError(set_oob_function, params, browser()));
  EXPECT_FALSE(error.empty());

  // TODO(bryeung): Also test setting the data when there is support for
  // ArrayBuffers in the arguments to the RunFunctionAnd* methods.
  // crbug.com/132796
}
<commit_msg>Revert 142630 - Disable BluetoothApiTest.SetOutOfBandPairingData under ASan.<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string.h>

#include "chrome/browser/chromeos/bluetooth/bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/test/mock_bluetooth_adapter.h"
#include "chrome/browser/chromeos/bluetooth/test/mock_bluetooth_device.h"
#include "chrome/browser/chromeos/extensions/bluetooth_event_router.h"
#include "chrome/browser/extensions/api/bluetooth/bluetooth_api.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "chrome/browser/extensions/extension_function_test_utils.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_test_message_listener.h"
#include "chrome/browser/ui/browser.h"
#include "chromeos/dbus/bluetooth_out_of_band_client.h"
#include "testing/gmock/include/gmock/gmock.h"

using extensions::Extension;

namespace utils = extension_function_test_utils;
namespace api = extensions::api;

namespace chromeos {

class BluetoothAdapater;

}  // namespace chromeos

namespace {

class BluetoothApiTest : public PlatformAppApiTest {
 public:
  BluetoothApiTest() : empty_extension_(utils::CreateEmptyExtension()) {}

  virtual void SetUpOnMainThread() OVERRIDE {
    // The browser will clean this up when it is torn down
    mock_adapter_ = new testing::StrictMock<chromeos::MockBluetoothAdapter>;
    event_router()->SetAdapterForTest(mock_adapter_);
  }

  void expectBooleanResult(bool expected,
                           UIThreadExtensionFunction* function,
                           const std::string& args) {
    scoped_ptr<base::Value> result(
        utils::RunFunctionAndReturnResult(function, args, browser()));
    ASSERT_TRUE(result.get() != NULL);
    ASSERT_EQ(base::Value::TYPE_BOOLEAN, result->GetType());
    bool boolean_value;
    result->GetAsBoolean(&boolean_value);
    EXPECT_EQ(expected, boolean_value);
  }

  template <class T>
  T* setupFunction(T* function) {
    function->set_extension(empty_extension_.get());
    function->set_has_callback(true);
    return function;
  }

 protected:
  testing::StrictMock<chromeos::MockBluetoothAdapter>* mock_adapter_;

 private:
  chromeos::ExtensionBluetoothEventRouter* event_router() {
    return browser()->profile()->GetExtensionService()->
        bluetooth_event_router();
  }

  chromeos::BluetoothAdapter* original_adapter_;
  scoped_refptr<Extension> empty_extension_;
};

static const char kOutOfBandPairingDataHash[] = "0123456789ABCDEh";
static const char kOutOfBandPairingDataRandomizer[] = "0123456789ABCDEr";

static chromeos::BluetoothOutOfBandPairingData GetOutOfBandPairingData() {
  chromeos::BluetoothOutOfBandPairingData data;
  memcpy(&(data.hash), kOutOfBandPairingDataHash,
      chromeos::kBluetoothOutOfBandPairingDataSize);
  memcpy(&(data.randomizer), kOutOfBandPairingDataRandomizer,
      chromeos::kBluetoothOutOfBandPairingDataSize);
  return data;
}

static bool CallClosure(const base::Closure& callback) {
  callback.Run();
  return true;
}

static bool CallOutOfBandPairingDataCallback(
      const chromeos::BluetoothAdapter::BluetoothOutOfBandPairingDataCallback&
          callback) {
  callback.Run(GetOutOfBandPairingData());
  return true;
}

}  // namespace

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsAvailable) {
  EXPECT_CALL(*mock_adapter_, IsPresent())
      .WillOnce(testing::Return(false));

  scoped_refptr<api::BluetoothIsAvailableFunction> is_available;

  is_available = setupFunction(new api::BluetoothIsAvailableFunction);
  expectBooleanResult(false, is_available, "[]");

  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  EXPECT_CALL(*mock_adapter_, IsPresent())
      .WillOnce(testing::Return(true));

  is_available = setupFunction(new api::BluetoothIsAvailableFunction);
  expectBooleanResult(true, is_available, "[]");
}

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, IsPowered) {
  EXPECT_CALL(*mock_adapter_, IsPowered())
      .WillOnce(testing::Return(false));

  scoped_refptr<api::BluetoothIsPoweredFunction> is_powered;

  is_powered = setupFunction(new api::BluetoothIsPoweredFunction);
  expectBooleanResult(false, is_powered, "[]");

  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  EXPECT_CALL(*mock_adapter_, IsPowered())
      .WillOnce(testing::Return(true));

  is_powered = setupFunction(new api::BluetoothIsPoweredFunction);
  expectBooleanResult(true, is_powered, "[]");
}

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetDevices) {
  testing::NiceMock<chromeos::MockBluetoothDevice> device1(
      mock_adapter_, "d1", "11:12:13:14:15:16",
      true /* paired */, false /* bonded */, true /* connected */);
  testing::NiceMock<chromeos::MockBluetoothDevice> device2(
      mock_adapter_, "d2", "21:22:23:24:25:26",
      false /* paired */, true /* bonded */, false /* connected */);
  chromeos::BluetoothAdapter::ConstDeviceList devices;
  devices.push_back(&device1);
  devices.push_back(&device2);

  EXPECT_CALL(device1, ProvidesServiceWithUUID("foo"))
      .WillOnce(testing::Return(false));
  EXPECT_CALL(device2, ProvidesServiceWithUUID("foo"))
      .WillOnce(testing::Return(true));

  EXPECT_CALL(*mock_adapter_, GetDevices())
      .WillOnce(testing::Return(devices));

  scoped_refptr<api::BluetoothGetDevicesFunction> get_devices;

  get_devices = setupFunction(new api::BluetoothGetDevicesFunction);
  scoped_ptr<base::Value> result(utils::RunFunctionAndReturnResult(
        get_devices,
        "[{\"uuid\":\"foo\"}]",
        browser()));

  ASSERT_EQ(base::Value::TYPE_LIST, result->GetType());
  base::ListValue* list;
  ASSERT_TRUE(result->GetAsList(&list));

  EXPECT_EQ(1u, list->GetSize());
  base::Value* device_value;
  EXPECT_TRUE(list->Get(0, &device_value));
  EXPECT_EQ(base::Value::TYPE_DICTIONARY, device_value->GetType());
  base::DictionaryValue* device;
  ASSERT_TRUE(device_value->GetAsDictionary(&device));

  std::string name;
  ASSERT_TRUE(device->GetString("name", &name));
  EXPECT_EQ("d2", name);
  std::string address;
  ASSERT_TRUE(device->GetString("address", &address));
  EXPECT_EQ("21:22:23:24:25:26", address);
  bool paired;
  ASSERT_TRUE(device->GetBoolean("paired", &paired));
  EXPECT_FALSE(paired);
  bool bonded;
  ASSERT_TRUE(device->GetBoolean("bonded", &bonded));
  EXPECT_TRUE(bonded);
  bool connected;
  ASSERT_TRUE(device->GetBoolean("connected", &connected));
  EXPECT_FALSE(connected);

  // Try again with no options
  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  EXPECT_CALL(*mock_adapter_, GetDevices())
      .WillOnce(testing::Return(devices));

  get_devices = setupFunction(new api::BluetoothGetDevicesFunction);
  result.reset(
      utils::RunFunctionAndReturnResult(get_devices, "[{}]", browser()));

  ASSERT_EQ(base::Value::TYPE_LIST, result->GetType());
  ASSERT_TRUE(result->GetAsList(&list));

  EXPECT_EQ(2u, list->GetSize());
}

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, GetLocalOutOfBandPairingData) {
  EXPECT_CALL(*mock_adapter_,
              ReadLocalOutOfBandPairingData(
                  testing::Truly(CallOutOfBandPairingDataCallback),
                  testing::_));

  scoped_refptr<api::BluetoothGetLocalOutOfBandPairingDataFunction>
      get_oob_function(setupFunction(
            new api::BluetoothGetLocalOutOfBandPairingDataFunction));

  scoped_ptr<base::Value> result(
      utils::RunFunctionAndReturnResult(get_oob_function, "[]", browser()));

  base::DictionaryValue* dict;
  EXPECT_TRUE(result->GetAsDictionary(&dict));

  base::BinaryValue* binary_value;
  EXPECT_TRUE(dict->GetBinary("hash", &binary_value));
  EXPECT_STREQ(kOutOfBandPairingDataHash,
      std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str());
  EXPECT_TRUE(dict->GetBinary("randomizer", &binary_value));
  EXPECT_STREQ(kOutOfBandPairingDataRandomizer,
      std::string(binary_value->GetBuffer(), binary_value->GetSize()).c_str());

  // Try again with an error
  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  EXPECT_CALL(*mock_adapter_,
              ReadLocalOutOfBandPairingData(
                  testing::_,
                  testing::Truly(CallClosure)));

  get_oob_function =
      setupFunction(new api::BluetoothGetLocalOutOfBandPairingDataFunction);

  std::string error(
      utils::RunFunctionAndReturnError(get_oob_function, "[]", browser()));
  EXPECT_FALSE(error.empty());
}

IN_PROC_BROWSER_TEST_F(BluetoothApiTest, SetOutOfBandPairingData) {
  std::string device_address("11:12:13:14:15:16");
  testing::NiceMock<chromeos::MockBluetoothDevice> device(
      mock_adapter_, "d1", device_address,
      true /* paired */, false /* bonded */, true /* connected */);
  EXPECT_CALL(*mock_adapter_, GetDevice(device_address))
      .WillOnce(testing::Return(&device));
  EXPECT_CALL(device,
              ClearOutOfBandPairingData(testing::Truly(CallClosure),
                                        testing::_));

  char buf[64];
  snprintf(buf, sizeof(buf),
           "[{\"device_address\":\"%s\"}]", device_address.c_str());
  std::string params(buf);

  scoped_refptr<api::BluetoothSetOutOfBandPairingDataFunction> set_oob_function;
  set_oob_function = setupFunction(
      new api::BluetoothSetOutOfBandPairingDataFunction);
  // There isn't actually a result.
  (void)utils::RunFunctionAndReturnResult(set_oob_function, params, browser());

  // Try again with an error
  testing::Mock::VerifyAndClearExpectations(mock_adapter_);
  testing::Mock::VerifyAndClearExpectations(&device);
  EXPECT_CALL(*mock_adapter_, GetDevice(device_address))
      .WillOnce(testing::Return(&device));
  EXPECT_CALL(device,
              ClearOutOfBandPairingData(testing::_,
                                        testing::Truly(CallClosure)));

  set_oob_function = setupFunction(
      new api::BluetoothSetOutOfBandPairingDataFunction);
  std::string error(
      utils::RunFunctionAndReturnError(set_oob_function, params, browser()));
  EXPECT_FALSE(error.empty());

  // TODO(bryeung): Also test setting the data when there is support for
  // ArrayBuffers in the arguments to the RunFunctionAnd* methods.
  // crbug.com/132796
}
<|endoftext|>


<commit_before>#include <cstdlib>

#include "cpu.hpp"
#include "../opcodes.hpp"

CPU::CPU() :
	pc(0), mem_size(0), memory(NULL),
	flags({false,false,false,false}), extension({NULL})
{}

CPU::~CPU()
{
	free(this->memory);
}

bool
CPU::Initialize(u32 mem_size)
{
	if ((this->memory = (u32 *)calloc(mem_size, sizeof(u32))))
		this->mem_size = mem_size;
	return (bool)this->memory;
}

bool
CPU::Load(FILE *input)
{
	int byte = '\0';
	for (u32 word_index = 0; byte != EOF && word_index < this->mem_size; ++word_index)
		for (int shift = 8 * (sizeof(u32) - 1); shift >= 0 && (byte = getc(input)) != EOF; shift -= 8)
			memory[word_index] |= byte << shift;
	return byte == EOF;
}

CPU::ProgramState
CPU::Tick()
{
	if (pc >= mem_size)
		return ERR_PC_BOUNDARY;
	u32 instruction = this->memory[this->pc++];
	u32 data = instruction & ~(0xff << 24);
	switch (instruction & (0xff << 24))
	{
		case OP_NOP:
			break;
		// TODO: add remaining opcodes
		case _OP_SIZE:
			if (this->mem_size < data) {
				this->extension.required_memory = data;
				return _ERR_SIZE;
			}
			break;
		case _OP_DEBUG:
			this->extension.debug_info =  this->memory + data;
			break;
		default:
			this->set_errored_line();
			return ERR_INVALID_OPCODE;
	}
	return OK;
}

void
CPU::set_errored_line()
{
	if (!this->extension.debug_info)
		return;
	for (
		u32 *key = this->extension.debug_info;
		key < this->memory + this->mem_size;
		key += *key & 0xffff
	)
		if (this->pc == (*key >> 16))
		{
			this->extension.errored_line = (char *)(key + 1);
			return;
		}
		else if (pc < (*key >> 16))  // instruction not present in source file
			break;
		else if (!(*key & 0xffff))  // no more lines follows
			break;
	this->extension.errored_line = NULL;
}
<commit_msg>Code formatting<commit_after>#include <cstdlib>

#include "cpu.hpp"
#include "../opcodes.hpp"

CPU::CPU() :
	pc(0), mem_size(0), memory(NULL),
	flags({false, false, false, false}), extension({NULL})
{}

CPU::~CPU()
{
	free(this->memory);
}

bool
CPU::Initialize(u32 mem_size)
{
	if ((this->memory = (u32 *)calloc(mem_size, sizeof(u32))))
		this->mem_size = mem_size;
	return (bool)this->memory;
}

bool
CPU::Load(FILE *input)
{
	int byte = '\0';
	for (
		u32 word_index = 0;
		byte != EOF && word_index < this->mem_size;
		++word_index
	)
		for (
			int shift = 8 * (sizeof(u32) - 1);
			shift >= 0 && (byte = getc(input)) != EOF;
			shift -= 8
		)
			memory[word_index] |= byte << shift;
	return byte == EOF;
}

CPU::ProgramState
CPU::Tick()
{
	if (pc >= mem_size)
		return ERR_PC_BOUNDARY;
	u32 instruction = this->memory[this->pc++];
	u32 data = instruction & ~(0xff << 24);
	switch (instruction & (0xff << 24))
	{
		case OP_NOP:
			break;
		// TODO: add remaining opcodes
		case _OP_SIZE:
			if (this->mem_size < data) {
				this->extension.required_memory = data;
				return _ERR_SIZE;
			}
			break;
		case _OP_DEBUG:
			this->extension.debug_info = this->memory + data;
			break;
		default:
			this->set_errored_line();
			return ERR_INVALID_OPCODE;
	}
	return OK;
}

void
CPU::set_errored_line()
{
	if (!this->extension.debug_info)
		return;
	for (
		u32 *key = this->extension.debug_info;
		key < this->memory + this->mem_size;
		key += *key & 0xffff
	)
		if (this->pc == (*key >> 16))
		{
			this->extension.errored_line = (char *)(key + 1);
			return;
		}
		else if (pc < (*key >> 16))  // instruction not present in source file
			break;
		else if (!(*key & 0xffff))  // no more lines follows
			break;
	this->extension.errored_line = NULL;
}
<|endoftext|>


<commit_before>#include <cstdlib>
#include <cstring>

#include "cpu.hpp"
#include "../conversion.hpp"
#include "../opcodes.hpp"

#define VALIDATE_ARGS(val1, val2)\
VALIDATE_ARG(val1)\
VALIDATE_ARG(val2)

#define VALIDATE_ARG(value)\
{\
	if (((value) & ~0x80) > 0x12)\
		return ERR_INVALID_ARG;\
}

#define VALIDATE_PC()\
{\
	if (bytes2word(this->pc) >= mem_size)\
		return ERR_PC_BOUNDARY;\
}

static inline u32 opcode(u32 instruction)
{
	return instruction >> 24;
}

static inline u32 data(u32 instruction)
{
	return instruction & 0xffffff;
}

static inline u32 byte(u32 instruction, u8 number)
{
	return (instruction >> (8 * (3 - number))) & 0xff;
}

CPU::CPU() :
	lc(&this->registers[0x10 * sizeof(u32)]),
	sp(&this->registers[0x11 * sizeof(u32)]),
	pc(&this->registers[0x12 * sizeof(u32)]),
	mem_size(0), memory(NULL),
	registers({0}), stack({0}), flags({false, false, false, false}),
	extension({0})
{}

CPU::~CPU()
{
	free(this->memory);
}

u32
CPU::CurrentInstruction()
{
	return bytes2word(this->memory + bytes2word(this->pc) * sizeof(u32));
}

u32
CPU::LastInstruction()
{
	return bytes2word(this->memory + (bytes2word(this->pc) - 1) * sizeof(u32));
}

bool
CPU::Initialize(u32 mem_size)
{
	if ((this->memory = (u8 *)malloc(mem_size * sizeof(u32))))
		this->mem_size = mem_size;
	return (bool)this->memory;
}

bool
CPU::Load(FILE *input)
{
	int byte;
	u32 byte_num = 0;
	while ((byte = getc(input)) != EOF && byte_num < this->mem_size * sizeof(u32))
		this->memory[byte_num++] = byte;
	return byte == EOF;
}

u8*
CPU::WhichRegister(u8 value)
{
	u8 *reg_ptr;
	reg_ptr = &this->registers[(value & ~0x80) * sizeof(u32)];
	if (value & 0x80)
	{
		if (*reg_ptr < this->mem_size)
			return &this->memory[*reg_ptr * sizeof(u32)];
		else
			return NULL;
	}
	return reg_ptr;
}

CPU::ProgramState
CPU::Tick()
{
	VALIDATE_PC()
	u8 *ptr1;
	u64 result;
	u32 instruction = this->CurrentInstruction();
	bytes_add(this->pc, 1);
	switch (opcode(instruction))
	{
		case OP_NOP:
			break;
		case OP_HCF:
			return HALTED;
		case OP_MOV:
			if (byte(instruction, 3))
			{
				VALIDATE_ARG(byte(instruction, 1))
				VALIDATE_PC()
				memcpy(
					this->WhichRegister(byte(instruction, 1)),
					this->memory + bytes2word(this->pc) * sizeof(u32),
					sizeof(u32)
				);
				bytes_add(this->pc, 1);
			}
			else
			{
				VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
				word2bytes(
					bytes2word(this->WhichRegister(byte(instruction, 2))),
					this->WhichRegister(byte(instruction, 1))
				);
			}
			break;
		case OP_ADD:
			VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
			ptr1 = this->WhichRegister(byte(instruction, 1));
			result =
				(u64)bytes2word(ptr1) +
				bytes2word(this->WhichRegister(byte(instruction, 2)));
			word2bytes(result, ptr1);
			this->flags.carry = (bool)(result != (u32)result);
			break;
		// TODO: add remaining opcodes
		case _OP_SIZE:
			if (this->mem_size < data(instruction)) {
				this->extension.required_memory = data(instruction);
				return _ERR_SIZE;
			}
			break;
		case _OP_DEBUG:
			this->extension.debug_info = data(instruction);
			break;
		default:
			this->_SetErroredLine();
			return ERR_INVALID_OPCODE;
	}
	return OK;
}

void
CPU::_SetErroredLine()
{
	if (!this->extension.debug_info)
		return;
	DebugSymbol key;
	for (
		u32 word_index = this->extension.debug_info;
		word_index < this->mem_size;
		word_index += key.next()
	) {
		key.value = bytes2word(this->memory + word_index * sizeof(u32));
		if (word_index == bytes2word(this->pc))
		{
			this->extension.errored_line =
				(char *)(this->memory + word_index * sizeof(u32));
			return;
		}
		else if (key.word() > bytes2word(this->pc)) // instruction not present
		                                            // in the source file
			break;
		else if (!key.next())  // no more lines follows
			break;
	}
	this->extension.errored_line = NULL;
}
<commit_msg>Added address boundary checking to MOV and ADD<commit_after>#include <cstdlib>
#include <cstring>

#include "cpu.hpp"
#include "../conversion.hpp"
#include "../opcodes.hpp"

#define VALIDATE_ARGS(val1, val2)\
VALIDATE_ARG(val1)\
VALIDATE_ARG(val2)

#define VALIDATE_ARG(value)\
{\
	if (((value) & ~0x80) > 0x12)\
		return ERR_INVALID_ARG;\
}

#define VALIDATE_PC()\
{\
	if (bytes2word(this->pc) >= mem_size)\
		return ERR_PC_BOUNDARY;\
}

static inline u32 opcode(u32 instruction)
{
	return instruction >> 24;
}

static inline u32 data(u32 instruction)
{
	return instruction & 0xffffff;
}

static inline u32 byte(u32 instruction, u8 number)
{
	return (instruction >> (8 * (3 - number))) & 0xff;
}

CPU::CPU() :
	lc(&this->registers[0x10 * sizeof(u32)]),
	sp(&this->registers[0x11 * sizeof(u32)]),
	pc(&this->registers[0x12 * sizeof(u32)]),
	mem_size(0), memory(NULL),
	registers({0}), stack({0}), flags({false, false, false, false}),
	extension({0})
{}

CPU::~CPU()
{
	free(this->memory);
}

u32
CPU::CurrentInstruction()
{
	return bytes2word(this->memory + bytes2word(this->pc) * sizeof(u32));
}

u32
CPU::LastInstruction()
{
	return bytes2word(this->memory + (bytes2word(this->pc) - 1) * sizeof(u32));
}

bool
CPU::Initialize(u32 mem_size)
{
	if ((this->memory = (u8 *)malloc(mem_size * sizeof(u32))))
		this->mem_size = mem_size;
	return (bool)this->memory;
}

bool
CPU::Load(FILE *input)
{
	int byte;
	u32 byte_num = 0;
	while ((byte = getc(input)) != EOF && byte_num < this->mem_size * sizeof(u32))
		this->memory[byte_num++] = byte;
	return byte == EOF;
}

u8*
CPU::WhichRegister(u8 value)
{
	u8 *reg_ptr;
	reg_ptr = &this->registers[(value & ~0x80) * sizeof(u32)];
	if (value & 0x80)
	{
		if (*reg_ptr < this->mem_size)
			return &this->memory[*reg_ptr * sizeof(u32)];
		else
			return NULL;
	}
	return reg_ptr;
}

CPU::ProgramState
CPU::Tick()
{
	VALIDATE_PC()
	u8 *ptr1, *ptr2;
	u64 result;
	u32 instruction = this->CurrentInstruction();
	bytes_add(this->pc, 1);
	switch (opcode(instruction))
	{
		case OP_NOP:
			break;
		case OP_HCF:
			return HALTED;
		case OP_MOV:
			if (byte(instruction, 3))
			{
				VALIDATE_ARG(byte(instruction, 1))
				VALIDATE_PC()
				ptr1 = this->WhichRegister(byte(instruction, 1));
				if (!ptr1)
					return ERR_ADDRESS_BOUNDARY;
				memcpy(
					ptr1,
					this->memory + bytes2word(this->pc) * sizeof(u32),
					sizeof(u32)
				);
				bytes_add(this->pc, 1);
			}
			else
			{
				VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
				ptr1 = this->WhichRegister(byte(instruction, 1));
				ptr2 = this->WhichRegister(byte(instruction, 2));
				if (!ptr1 || !ptr2)
					return ERR_ADDRESS_BOUNDARY;
				word2bytes(bytes2word(ptr2), ptr1);
			}
			break;
		case OP_ADD:
			VALIDATE_ARGS(byte(instruction, 1), byte(instruction, 2))
			ptr1 = this->WhichRegister(byte(instruction, 1));
			ptr2 = this->WhichRegister(byte(instruction, 2));
			if (!ptr1 || !ptr2)
				return ERR_ADDRESS_BOUNDARY;
			result = (u64)bytes2word(ptr1) + bytes2word(ptr2);
			word2bytes(result, ptr1);
			this->flags.carry = (bool)(result != (u32)result);
			break;
		// TODO: add remaining opcodes
		case _OP_SIZE:
			if (this->mem_size < data(instruction)) {
				this->extension.required_memory = data(instruction);
				return _ERR_SIZE;
			}
			break;
		case _OP_DEBUG:
			this->extension.debug_info = data(instruction);
			break;
		default:
			this->_SetErroredLine();
			return ERR_INVALID_OPCODE;
	}
	return OK;
}

void
CPU::_SetErroredLine()
{
	if (!this->extension.debug_info)
		return;
	DebugSymbol key;
	for (
		u32 word_index = this->extension.debug_info;
		word_index < this->mem_size;
		word_index += key.next()
	) {
		key.value = bytes2word(this->memory + word_index * sizeof(u32));
		if (word_index == bytes2word(this->pc))
		{
			this->extension.errored_line =
				(char *)(this->memory + word_index * sizeof(u32));
			return;
		}
		else if (key.word() > bytes2word(this->pc)) // instruction not present
		                                            // in the source file
			break;
		else if (!key.next())  // no more lines follows
			break;
	}
	this->extension.errored_line = NULL;
}
<|endoftext|>


<commit_before><commit_msg>added range operator (start, end) for contour<commit_after><|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
#include "EventLog.h"

#include <stdarg.h>
#include <stdlib.h>

using namespace apache::thrift::concurrency;

namespace {

// Define environment variable DEBUG_EVENTLOG to enable debug logging
// ex: $ DEBUG_EVENTLOG=1 processor_test
static const char * DEBUG_EVENTLOG = getenv("DEBUG_EVENTLOG");

void debug(const char* fmt, ...) {
  if (DEBUG_EVENTLOG) {
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);

    fprintf(stderr, "\n");
  }
}
}

namespace apache {
namespace thrift {
namespace test {

uint32_t EventLog::nextId_ = 0;

#define EVENT_TYPE(value) EventType EventLog::value = #value
EVENT_TYPE(ET_LOG_END);
EVENT_TYPE(ET_CONN_CREATED);
EVENT_TYPE(ET_CONN_DESTROYED);
EVENT_TYPE(ET_CALL_STARTED);
EVENT_TYPE(ET_CALL_FINISHED);
EVENT_TYPE(ET_PROCESS);
EVENT_TYPE(ET_PRE_READ);
EVENT_TYPE(ET_POST_READ);
EVENT_TYPE(ET_PRE_WRITE);
EVENT_TYPE(ET_POST_WRITE);
EVENT_TYPE(ET_ASYNC_COMPLETE);
EVENT_TYPE(ET_HANDLER_ERROR);

EVENT_TYPE(ET_CALL_INCREMENT_GENERATION);
EVENT_TYPE(ET_CALL_GET_GENERATION);
EVENT_TYPE(ET_CALL_ADD_STRING);
EVENT_TYPE(ET_CALL_GET_STRINGS);
EVENT_TYPE(ET_CALL_GET_DATA_WAIT);
EVENT_TYPE(ET_CALL_ONEWAY_WAIT);
EVENT_TYPE(ET_CALL_EXCEPTION_WAIT);
EVENT_TYPE(ET_CALL_UNEXPECTED_EXCEPTION_WAIT);
EVENT_TYPE(ET_CALL_SET_VALUE);
EVENT_TYPE(ET_CALL_GET_VALUE);
EVENT_TYPE(ET_WAIT_RETURN);

EventLog::EventLog() {
  id_ = nextId_++;
  debug("New log: %d", id_);
}

void EventLog::append(EventType type,
                      uint32_t connectionId,
                      uint32_t callId,
                      const std::string& message) {
  Synchronized s(monitor_);
  debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type, message.c_str());

  Event e(type, connectionId, callId, message);
  events_.push_back(e);

  monitor_.notify();
}

Event EventLog::waitForEvent(int64_t timeout) {
  Synchronized s(monitor_);

  try {
    while (events_.empty()) {
      monitor_.wait(timeout);
    }
  } catch (TimedOutException ex) {
    return Event(ET_LOG_END, 0, 0, "");
  }

  Event event = events_.front();
  events_.pop_front();
  return event;
}

Event EventLog::waitForConnEvent(uint32_t connId, int64_t timeout) {
  Synchronized s(monitor_);

  auto it = events_.begin();
  while (true) {
    try {
      // TODO: it would be nicer to honor timeout for the duration of this
      // call, rather than restarting it for each call to wait().  It shouldn't
      // be a big problem in practice, though.
      while (it == events_.end()) {
        monitor_.wait(timeout);
      }
    } catch (TimedOutException ex) {
      return Event(ET_LOG_END, 0, 0, "");
    }

    if (it->connectionId == connId) {
      Event event = *it;
      events_.erase(it);
      return event;
    }
  }
}
}
}
} // apache::thrift::test
<commit_msg>CPP generator test, catching exceptions by ref instead.<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
#include "EventLog.h"

#include <stdarg.h>
#include <stdlib.h>

using namespace apache::thrift::concurrency;

namespace {

// Define environment variable DEBUG_EVENTLOG to enable debug logging
// ex: $ DEBUG_EVENTLOG=1 processor_test
static const char * DEBUG_EVENTLOG = getenv("DEBUG_EVENTLOG");

void debug(const char* fmt, ...) {
  if (DEBUG_EVENTLOG) {
    va_list ap;
    va_start(ap, fmt);
    vfprintf(stderr, fmt, ap);
    va_end(ap);

    fprintf(stderr, "\n");
  }
}
}

namespace apache {
namespace thrift {
namespace test {

uint32_t EventLog::nextId_ = 0;

#define EVENT_TYPE(value) EventType EventLog::value = #value
EVENT_TYPE(ET_LOG_END);
EVENT_TYPE(ET_CONN_CREATED);
EVENT_TYPE(ET_CONN_DESTROYED);
EVENT_TYPE(ET_CALL_STARTED);
EVENT_TYPE(ET_CALL_FINISHED);
EVENT_TYPE(ET_PROCESS);
EVENT_TYPE(ET_PRE_READ);
EVENT_TYPE(ET_POST_READ);
EVENT_TYPE(ET_PRE_WRITE);
EVENT_TYPE(ET_POST_WRITE);
EVENT_TYPE(ET_ASYNC_COMPLETE);
EVENT_TYPE(ET_HANDLER_ERROR);

EVENT_TYPE(ET_CALL_INCREMENT_GENERATION);
EVENT_TYPE(ET_CALL_GET_GENERATION);
EVENT_TYPE(ET_CALL_ADD_STRING);
EVENT_TYPE(ET_CALL_GET_STRINGS);
EVENT_TYPE(ET_CALL_GET_DATA_WAIT);
EVENT_TYPE(ET_CALL_ONEWAY_WAIT);
EVENT_TYPE(ET_CALL_EXCEPTION_WAIT);
EVENT_TYPE(ET_CALL_UNEXPECTED_EXCEPTION_WAIT);
EVENT_TYPE(ET_CALL_SET_VALUE);
EVENT_TYPE(ET_CALL_GET_VALUE);
EVENT_TYPE(ET_WAIT_RETURN);

EventLog::EventLog() {
  id_ = nextId_++;
  debug("New log: %d", id_);
}

void EventLog::append(EventType type,
                      uint32_t connectionId,
                      uint32_t callId,
                      const std::string& message) {
  Synchronized s(monitor_);
  debug("%d <-- %u, %u, %s \"%s\"", id_, connectionId, callId, type, message.c_str());

  Event e(type, connectionId, callId, message);
  events_.push_back(e);

  monitor_.notify();
}

Event EventLog::waitForEvent(int64_t timeout) {
  Synchronized s(monitor_);

  try {
    while (events_.empty()) {
      monitor_.wait(timeout);
    }
  } catch (const TimedOutException &) {
    return Event(ET_LOG_END, 0, 0, "");
  }

  Event event = events_.front();
  events_.pop_front();
  return event;
}

Event EventLog::waitForConnEvent(uint32_t connId, int64_t timeout) {
  Synchronized s(monitor_);

  auto it = events_.begin();
  while (true) {
    try {
      // TODO: it would be nicer to honor timeout for the duration of this
      // call, rather than restarting it for each call to wait().  It shouldn't
      // be a big problem in practice, though.
      while (it == events_.end()) {
        monitor_.wait(timeout);
      }
    } catch (const TimedOutException &) {
      return Event(ET_LOG_END, 0, 0, "");
    }

    if (it->connectionId == connId) {
      Event event = *it;
      events_.erase(it);
      return event;
    }
  }
}
}
}
} // apache::thrift::test
<|endoftext|>


<commit_before>//
//  LayerBuilder.cpp
//  G3MiOSSDK
//
//  Created by Mari Luz Mateo on 21/12/12.
//
//

#include "LayerBuilder.hpp"
#include "LevelTileCondition.hpp"
#include "LayerSet.hpp"

LayerSet* LayerBuilder::createDefaultSatelliteImagery() {
  LayerSet* layerSet = new LayerSet();

  WMSLayer* blueMarble = new WMSLayer("bmng200405",
                                      URL("http://www.nasa.network.com/wms?", false),
                                      WMS_1_1_0,
                                      Sector::fullSphere(),
                                      "image/jpeg",
                                      "EPSG:4326",
                                      "",
                                      false,
                                      new LevelTileCondition(0, 6),
                                      TimeInterval::fromDays(30),
                                      true);
  layerSet->addLayer(blueMarble);

  WMSLayer* i3Landsat = new WMSLayer("esat",
                                     URL("http://data.worldwind.arc.nasa.gov/wms?", false),
                                     WMS_1_1_0,
                                     Sector::fullSphere(),
                                     "image/jpeg",
                                     "EPSG:4326",
                                     "",
                                     false,
                                     new LevelTileCondition(7, 10),
                                     TimeInterval::fromDays(30),
                                     true);
  layerSet->addLayer(i3Landsat);

  WMSLayer* bing = new WMSLayer("ve",
                                URL("http://worldwind27.arc.nasa.gov/wms/virtualearth?", false),
                                WMS_1_1_0,
                                Sector::fullSphere(),
                                "image/jpeg",
                                "EPSG:4326",
                                "",
                                false,
                                new LevelTileCondition(11, 1000),
                                TimeInterval::fromDays(30),
                                true);
  layerSet->addLayer(bing);

  return layerSet;
}

/**
 * Returns an array with the names of the layers that make up the default layerSet
 *
 * @return layersNames: std::vector<std::string>
 */
std::vector<std::string> LayerBuilder::getDefaultLayersNames() {
  std::vector<std::string> layersNames;
  layersNames.push_back("bmng200405");
  layersNames.push_back("esat");
  layersNames.push_back("ve");

  return layersNames;
}

WMSLayer* LayerBuilder::createBingLayer(bool enabled) {
  WMSLayer* bing = new WMSLayer("ve",
                                URL("http://worldwind27.arc.nasa.gov/wms/virtualearth?", false),
                                WMS_1_1_0,
                                Sector::fullSphere(),
                                "image/jpeg",
                                "EPSG:4326",
                                "",
                                false,
                                NULL,
                                TimeInterval::fromDays(30),
                                true);
  bing->setEnable(enabled);

  return bing;
}

WMSLayer* LayerBuilder::createOSMLayer(bool enabled) {
  WMSLayer* osm = new WMSLayer("osm_auto:all",
                               URL("http://129.206.228.72/cached/osm", false),
                               WMS_1_1_0,
                               // Sector::fromDegrees(-85.05, -180.0, 85.05, 180.0),
                               Sector::fullSphere(),
                               "image/jpeg",
                               "EPSG:4326",
                               "",
                               false,
                               NULL,
                               TimeInterval::fromDays(30),
                               true);
  osm->setEnable(enabled);

  return osm;
}

WMSLayer* LayerBuilder::createPNOALayer(bool enabled) {
  WMSLayer *pnoa = new WMSLayer("PNOA",
                                URL("http://www.idee.es/wms/PNOA/PNOA", false),
                                WMS_1_1_0,
                                Sector::fromDegrees(21, -18, 45, 6),
                                "image/png",
                                "EPSG:4326",
                                "",
                                true,
                                NULL,
                                TimeInterval::fromDays(30),
                                true);
  pnoa->setEnable(enabled);

  return pnoa;
}

WMSLayer* LayerBuilder::createBlueMarbleLayer(bool enabled) {
  WMSLayer* blueMarble = new WMSLayer("bmng200405",
                                      URL("http://www.nasa.network.com/wms?", false),
                                      WMS_1_1_0,
                                      Sector::fullSphere(),
                                      "image/jpeg",
                                      "EPSG:4326",
                                      "",
                                      false,
                                      new LevelTileCondition(0, 6),
                                      TimeInterval::fromDays(30),
                                      true);
  blueMarble->setEnable(enabled);

  return blueMarble;
}

WMSLayer* LayerBuilder::createI3LandSatLayer(bool enabled) {
  WMSLayer* i3Landsat = new WMSLayer("esat",
                                     URL("http://data.worldwind.arc.nasa.gov/wms?", false),
                                     WMS_1_1_0,
                                     Sector::fullSphere(),
                                     "image/jpeg",
                                     "EPSG:4326",
                                     "",
                                     false,
                                     new LevelTileCondition(7, 100),
                                     TimeInterval::fromDays(30),
                                     true);
  i3Landsat->setEnable(enabled);

  return i3Landsat;
}

WMSLayer* LayerBuilder::createPoliticalLayer(bool enabled) {
  WMSLayer* political = new WMSLayer("topp:cia",
                                     URL("http://worldwind22.arc.nasa.gov/geoserver/wms?", false),
                                     WMS_1_1_0,
                                     Sector::fullSphere(),
                                     "image/png",
                                     "EPSG:4326",
                                     "countryboundaries",
                                     true,
                                     NULL,
                                     TimeInterval::fromDays(30),
                                     true);
  political->setEnable(enabled);

  return political;
}
<commit_msg>expired-images handling<commit_after>//
//  LayerBuilder.cpp
//  G3MiOSSDK
//
//  Created by Mari Luz Mateo on 21/12/12.
//
//

#include "LayerBuilder.hpp"
#include "LevelTileCondition.hpp"
#include "LayerSet.hpp"

LayerSet* LayerBuilder::createDefaultSatelliteImagery() {
  LayerSet* layerSet = new LayerSet();

  WMSLayer* blueMarble = new WMSLayer("bmng200405",
                                      URL("http://www.nasa.network.com/wms?", false),
                                      WMS_1_1_0,
                                      Sector::fullSphere(),
                                      "image/jpeg",
                                      "EPSG:4326",
                                      "",
                                      false,
                                      new LevelTileCondition(0, 6),
                                      TimeInterval::fromDays(30),
                                      true);
  layerSet->addLayer(blueMarble);

  WMSLayer* i3Landsat = new WMSLayer("esat",
                                     URL("http://data.worldwind.arc.nasa.gov/wms?", false),
                                     WMS_1_1_0,
                                     Sector::fullSphere(),
                                     "image/jpeg",
                                     "EPSG:4326",
                                     "",
                                     false,
                                     new LevelTileCondition(7, 10),
                                     TimeInterval::fromDays(30),
                                     true);
  layerSet->addLayer(i3Landsat);

  WMSLayer* bing = new WMSLayer("ve",
                                URL("http://worldwind27.arc.nasa.gov/wms/virtualearth?", false),
                                WMS_1_1_0,
                                Sector::fullSphere(),
                                "image/jpeg",
                                "EPSG:4326",
                                "",
                                false,
                                new LevelTileCondition(11, 1000),
                                TimeInterval::fromDays(30),
                                true);
  layerSet->addLayer(bing);

  return layerSet;
}

/**
 * Returns an array with the names of the layers that make up the default layerSet
 *
 * @return layersNames: std::vector<std::string>
 */
std::vector<std::string> LayerBuilder::getDefaultLayersNames() {
  std::vector<std::string> layersNames;
  layersNames.push_back("bmng200405");
  layersNames.push_back("esat");
  layersNames.push_back("ve");

  return layersNames;
}

WMSLayer* LayerBuilder::createBingLayer(bool enabled) {
  WMSLayer* bing = new WMSLayer("ve",
                                URL("http://worldwind27.arc.nasa.gov/wms/virtualearth?", false),
                                WMS_1_1_0,
                                Sector::fullSphere(),
                                "image/jpeg",
                                "EPSG:4326",
                                "",
                                false,
                                NULL,
                                TimeInterval::fromDays(30),
                                true);
  bing->setEnable(enabled);

  return bing;
}

WMSLayer* LayerBuilder::createOSMLayer(bool enabled) {
  WMSLayer* osm = new WMSLayer("osm_auto:all",
                               URL("http://129.206.228.72/cached/osm", false),
                               WMS_1_1_0,
                               // Sector::fromDegrees(-85.05, -180.0, 85.05, 180.0),
                               Sector::fullSphere(),
                               "image/jpeg",
                               "EPSG:4326",
                               "",
                               false,
                               NULL,
                               TimeInterval::fromDays(30),
                               true);
  osm->setEnable(enabled);

  return osm;
}

WMSLayer* LayerBuilder::createPNOALayer(bool enabled) {
  WMSLayer *pnoa = new WMSLayer("PNOA",
                                URL("http://www.idee.es/wms/PNOA/PNOA", false),
                                WMS_1_1_0,
                                Sector::fromDegrees(21, -18, 45, 6),
                                "image/png",
                                "EPSG:4326",
                                "",
                                true,
                                NULL,
                                TimeInterval::fromDays(30),
                                true);
  pnoa->setEnable(enabled);

  return pnoa;
}

WMSLayer* LayerBuilder::createBlueMarbleLayer(bool enabled) {
  WMSLayer* blueMarble = new WMSLayer("bmng200405",
                                      URL("http://www.nasa.network.com/wms?", false),
                                      WMS_1_1_0,
                                      Sector::fullSphere(),
                                      "image/jpeg",
                                      "EPSG:4326",
                                      "",
                                      false,
                                      new LevelTileCondition(0, 6),
                                      TimeInterval::fromDays(30),
                                      true);
  blueMarble->setEnable(enabled);

  return blueMarble;
}

WMSLayer* LayerBuilder::createI3LandSatLayer(bool enabled) {
  WMSLayer* i3Landsat = new WMSLayer("esat",
                                     URL("http://data.worldwind.arc.nasa.gov/wms?", false),
                                     WMS_1_1_0,
                                     Sector::fullSphere(),
                                     "image/jpeg",
                                     "EPSG:4326",
                                     "",
                                     false,
                                     new LevelTileCondition(7, 100),
                                     TimeInterval::fromDays(30),
                                     true);
  i3Landsat->setEnable(enabled);

  return i3Landsat;
}

WMSLayer* LayerBuilder::createPoliticalLayer(bool enabled) {
  WMSLayer* political = new WMSLayer("topp:cia",
                                     URL("http://worldwind22.arc.nasa.gov/geoserver/wms?", false),
                                     WMS_1_1_0,
                                     Sector::fullSphere(),
                                     "image/png",
                                     "EPSG:4326",
                                     "countryboundaries",
                                     true,
                                     NULL,
                                     TimeInterval::fromDays(30),
                                     true);
  political->setEnable(enabled);

  return political;
}
<|endoftext|>


<commit_before><commit_msg>Automated merge with http://hg.secondlife.com/viewer-development<commit_after><|endoftext|>


<commit_before>#pragma once

#include <vector>

#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/Point3f.hpp"

namespace dai {

struct Extrinsics {
    std::vector<std::vector<float>> rotationMatrix;
    /**
     *  (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket obtained through calibration
     */
    Point3f translation;
    /**
     *  (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket measured through CAD design
     */
    Point3f specTranslation;
    CameraBoardSocket toCameraSocket = CameraBoardSocket::AUTO;
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(Extrinsics, rotationMatrix, translation, specTranslation, toCameraSocket);
};

}  // namespace dai<commit_msg>Update 3<commit_after>#pragma once

#include <vector>

#include "depthai-shared/common/CameraBoardSocket.hpp"
#include "depthai-shared/common/Point3f.hpp"

namespace dai {

/// Extrinsics structure
struct Extrinsics {
    std::vector<std::vector<float>> rotationMatrix;
    /**
     *  (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket obtained through calibration
     */
    Point3f translation;
    /**
     *  (x, y, z) pose of destCameraSocket w.r.t currentCameraSocket measured through CAD design
     */
    Point3f specTranslation;
    CameraBoardSocket toCameraSocket = CameraBoardSocket::AUTO;
    NLOHMANN_DEFINE_TYPE_INTRUSIVE(Extrinsics, rotationMatrix, translation, specTranslation, toCameraSocket);
};

}  // namespace dai<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/

#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkKnownDriverIds.inl"

using namespace vk;

namespace vkt
{
namespace api
{
namespace
{

enum TestType
{
	TEST_TYPE_DRIVER_ID_MATCH			= 0,
	TEST_TYPE_NAME_IS_NOT_EMPTY,
	TEST_TYPE_NAME_ZERO_TERMINATED,
	TEST_TYPE_INFO_ZERO_TERMINATED,
	TEST_TYPE_VERSION,
};

static const VkConformanceVersionKHR knownConformanceVersions[] =
{
	makeConformanceVersion(1, 2, 6, 1),
	makeConformanceVersion(1, 2, 6, 0),
	makeConformanceVersion(1, 2, 5, 2),
	makeConformanceVersion(1, 2, 5, 1),
	makeConformanceVersion(1, 2, 5, 0),
	makeConformanceVersion(1, 2, 4, 1),
	makeConformanceVersion(1, 2, 4, 0),
	makeConformanceVersion(1, 2, 3, 3),
	makeConformanceVersion(1, 2, 3, 2),
	makeConformanceVersion(1, 2, 3, 1),
	makeConformanceVersion(1, 2, 3, 0),
	makeConformanceVersion(1, 2, 2, 2),
	makeConformanceVersion(1, 2, 2, 1),
	makeConformanceVersion(1, 2, 2, 0),
	makeConformanceVersion(1, 2, 1, 2),
	makeConformanceVersion(1, 2, 1, 1),
	makeConformanceVersion(1, 2, 1, 0),
	makeConformanceVersion(1, 2, 0, 2),
	makeConformanceVersion(1, 2, 0, 1),
	makeConformanceVersion(1, 2, 0, 0),
	makeConformanceVersion(1, 1, 6, 3),
	makeConformanceVersion(1, 1, 6, 2),
	makeConformanceVersion(1, 1, 6, 1),
	makeConformanceVersion(1, 1, 6, 0),
	makeConformanceVersion(1, 1, 5, 2),
	makeConformanceVersion(1, 1, 5, 1),
	makeConformanceVersion(1, 1, 5, 0),
	makeConformanceVersion(1, 1, 4, 3),
	makeConformanceVersion(1, 1, 4, 2),
	makeConformanceVersion(1, 1, 4, 1),
	makeConformanceVersion(1, 1, 4, 0),
	makeConformanceVersion(1, 1, 3, 3),
	makeConformanceVersion(1, 1, 3, 2),
	makeConformanceVersion(1, 1, 3, 1),
	makeConformanceVersion(1, 1, 3, 0),
};

DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
	return deStrnlen(str, maxSize) < maxSize;
}

DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
	return ((a.major == b.major)		&&
			(a.minor == b.minor)		&&
			(a.subminor == b.subminor)	&&
			(a.patch == b.patch));
}

void checkSupport (Context& context, const TestType config)
{
	DE_UNREF(config);
	context.requireDeviceFunctionality("VK_KHR_driver_properties");
}

void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)
	{
		if (deviceDriverProperties.driverID == driverIds[driverNdx].id)
			return;
	}

	TCU_FAIL("Driver ID did not match any known driver");
}

void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (deviceDriverProperties.driverName[0] == 0)
		TCU_FAIL("Driver name is empty");
}

void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
		TCU_FAIL("Driver name is not a null-terminated string");
}

void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
		TCU_FAIL("Driver info is not a null-terminated string");
}

void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
	const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);
	const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);

	if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
		(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
		 deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
	{
		TCU_FAIL("Wrong driver conformance version (older than used API version)");
	}

	for (const VkConformanceVersionKHR* pConformanceVersion  = knownConformanceVersions;
										pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
									  ++pConformanceVersion)
	{
		if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
			return;
	}

	TCU_FAIL("Wrong driver conformance version (not known)");
}

tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
	// Query the driver properties
	const VkPhysicalDevice				physDevice			= context.getPhysicalDevice();
	const int							memsetPattern		= 0xaa;
	VkPhysicalDeviceProperties2			deviceProperties2;
	VkPhysicalDeviceDriverProperties	deviceDriverProperties;

	deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
	deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
	deviceDriverProperties.pNext = DE_NULL;

	deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
	deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
	deviceProperties2.pNext = &deviceDriverProperties;

	context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);

	// Verify the returned values
	switch (testType)
	{
		case TEST_TYPE_DRIVER_ID_MATCH:			testDriverMatch			(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_IS_NOT_EMPTY:		testNameIsNotEmpty		(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_ZERO_TERMINATED:	testNameZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_INFO_ZERO_TERMINATED:	testInfoZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_VERSION:					testVersion				(deviceDriverProperties, context.getUsedApiVersion());	break;
		default:								TCU_THROW(InternalError, "Unknown test type specified");
	}

	return tcu::TestStatus::pass("Pass");
}

void createTestCases (tcu::TestCaseGroup* group)
{
	addFunctionCase(group, "driver_id_match",		"Check driverID is supported",					checkSupport,	testQueryProperties,	TEST_TYPE_DRIVER_ID_MATCH);
	addFunctionCase(group, "name_is_not_empty",		"Check name field is not empty",				checkSupport,	testQueryProperties,	TEST_TYPE_NAME_IS_NOT_EMPTY);
	addFunctionCase(group, "name_zero_terminated",	"Check name field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_NAME_ZERO_TERMINATED);
	addFunctionCase(group, "info_zero_terminated",	"Check info field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_INFO_ZERO_TERMINATED);
	addFunctionCase(group, "conformance_version",	"Check conformanceVersion reported by driver",	checkSupport,	testQueryProperties,	TEST_TYPE_VERSION);
}

} // anonymous

tcu::TestCaseGroup*	createDriverPropertiesTests(tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}

} // api
} // vkt
<commit_msg>Allow Vulkan CTS 1.2.6.2<commit_after>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/

#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"
#include "vkKnownDriverIds.inl"

using namespace vk;

namespace vkt
{
namespace api
{
namespace
{

enum TestType
{
	TEST_TYPE_DRIVER_ID_MATCH			= 0,
	TEST_TYPE_NAME_IS_NOT_EMPTY,
	TEST_TYPE_NAME_ZERO_TERMINATED,
	TEST_TYPE_INFO_ZERO_TERMINATED,
	TEST_TYPE_VERSION,
};

static const VkConformanceVersionKHR knownConformanceVersions[] =
{
	makeConformanceVersion(1, 2, 6, 2),
	makeConformanceVersion(1, 2, 6, 1),
	makeConformanceVersion(1, 2, 6, 0),
	makeConformanceVersion(1, 2, 5, 2),
	makeConformanceVersion(1, 2, 5, 1),
	makeConformanceVersion(1, 2, 5, 0),
	makeConformanceVersion(1, 2, 4, 1),
	makeConformanceVersion(1, 2, 4, 0),
	makeConformanceVersion(1, 2, 3, 3),
	makeConformanceVersion(1, 2, 3, 2),
	makeConformanceVersion(1, 2, 3, 1),
	makeConformanceVersion(1, 2, 3, 0),
	makeConformanceVersion(1, 2, 2, 2),
	makeConformanceVersion(1, 2, 2, 1),
	makeConformanceVersion(1, 2, 2, 0),
	makeConformanceVersion(1, 2, 1, 2),
	makeConformanceVersion(1, 2, 1, 1),
	makeConformanceVersion(1, 2, 1, 0),
	makeConformanceVersion(1, 2, 0, 2),
	makeConformanceVersion(1, 2, 0, 1),
	makeConformanceVersion(1, 2, 0, 0),
	makeConformanceVersion(1, 1, 6, 3),
	makeConformanceVersion(1, 1, 6, 2),
	makeConformanceVersion(1, 1, 6, 1),
	makeConformanceVersion(1, 1, 6, 0),
	makeConformanceVersion(1, 1, 5, 2),
	makeConformanceVersion(1, 1, 5, 1),
	makeConformanceVersion(1, 1, 5, 0),
	makeConformanceVersion(1, 1, 4, 3),
	makeConformanceVersion(1, 1, 4, 2),
	makeConformanceVersion(1, 1, 4, 1),
	makeConformanceVersion(1, 1, 4, 0),
	makeConformanceVersion(1, 1, 3, 3),
	makeConformanceVersion(1, 1, 3, 2),
	makeConformanceVersion(1, 1, 3, 1),
	makeConformanceVersion(1, 1, 3, 0),
};

DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
	return deStrnlen(str, maxSize) < maxSize;
}

DE_INLINE bool operator==(const VkConformanceVersion& a, const VkConformanceVersion& b)
{
	return ((a.major == b.major)		&&
			(a.minor == b.minor)		&&
			(a.subminor == b.subminor)	&&
			(a.patch == b.patch));
}

void checkSupport (Context& context, const TestType config)
{
	DE_UNREF(config);
	context.requireDeviceFunctionality("VK_KHR_driver_properties");
}

void testDriverMatch (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	for (deUint32 driverNdx = 0; driverNdx < DE_LENGTH_OF_ARRAY(driverIds); driverNdx++)
	{
		if (deviceDriverProperties.driverID == driverIds[driverNdx].id)
			return;
	}

	TCU_FAIL("Driver ID did not match any known driver");
}

void testNameIsNotEmpty (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (deviceDriverProperties.driverName[0] == 0)
		TCU_FAIL("Driver name is empty");
}

void testNameZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
		TCU_FAIL("Driver name is not a null-terminated string");
}

void testInfoZeroTerminated (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties)
{
	if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
		TCU_FAIL("Driver info is not a null-terminated string");
}

void testVersion (const VkPhysicalDeviceDriverPropertiesKHR& deviceDriverProperties, deUint32 usedApiVersion)
{
	const deUint32 apiMajorVersion = VK_API_VERSION_MAJOR(usedApiVersion);
	const deUint32 apiMinorVersion = VK_API_VERSION_MINOR(usedApiVersion);

	if (deviceDriverProperties.conformanceVersion.major < apiMajorVersion ||
		(deviceDriverProperties.conformanceVersion.major == apiMajorVersion &&
		 deviceDriverProperties.conformanceVersion.minor < apiMinorVersion))
	{
		TCU_FAIL("Wrong driver conformance version (older than used API version)");
	}

	for (const VkConformanceVersionKHR* pConformanceVersion  = knownConformanceVersions;
										pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
									  ++pConformanceVersion)
	{
		if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
			return;
	}

	TCU_FAIL("Wrong driver conformance version (not known)");
}

tcu::TestStatus testQueryProperties (Context& context, const TestType testType)
{
	// Query the driver properties
	const VkPhysicalDevice				physDevice			= context.getPhysicalDevice();
	const int							memsetPattern		= 0xaa;
	VkPhysicalDeviceProperties2			deviceProperties2;
	VkPhysicalDeviceDriverProperties	deviceDriverProperties;

	deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
	deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
	deviceDriverProperties.pNext = DE_NULL;

	deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
	deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
	deviceProperties2.pNext = &deviceDriverProperties;

	context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);

	// Verify the returned values
	switch (testType)
	{
		case TEST_TYPE_DRIVER_ID_MATCH:			testDriverMatch			(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_IS_NOT_EMPTY:		testNameIsNotEmpty		(deviceDriverProperties);								break;
		case TEST_TYPE_NAME_ZERO_TERMINATED:	testNameZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_INFO_ZERO_TERMINATED:	testInfoZeroTerminated	(deviceDriverProperties);								break;
		case TEST_TYPE_VERSION:					testVersion				(deviceDriverProperties, context.getUsedApiVersion());	break;
		default:								TCU_THROW(InternalError, "Unknown test type specified");
	}

	return tcu::TestStatus::pass("Pass");
}

void createTestCases (tcu::TestCaseGroup* group)
{
	addFunctionCase(group, "driver_id_match",		"Check driverID is supported",					checkSupport,	testQueryProperties,	TEST_TYPE_DRIVER_ID_MATCH);
	addFunctionCase(group, "name_is_not_empty",		"Check name field is not empty",				checkSupport,	testQueryProperties,	TEST_TYPE_NAME_IS_NOT_EMPTY);
	addFunctionCase(group, "name_zero_terminated",	"Check name field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_NAME_ZERO_TERMINATED);
	addFunctionCase(group, "info_zero_terminated",	"Check info field is zero-terminated",			checkSupport,	testQueryProperties,	TEST_TYPE_INFO_ZERO_TERMINATED);
	addFunctionCase(group, "conformance_version",	"Check conformanceVersion reported by driver",	checkSupport,	testQueryProperties,	TEST_TYPE_VERSION);
}

} // anonymous

tcu::TestCaseGroup*	createDriverPropertiesTests(tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}

} // api
} // vkt
<|endoftext|>


<commit_before>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#pragma once

#include <cstddef>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <string>
#include <utility>

#include <windows.h>
#include <winnt.h>

#include <hadesmem/config.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/pelib/nt_headers.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/pelib/tls_dir.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/read.hpp>
#include <hadesmem/write.hpp>

// TODO: Handle forwarded imports.

// TODO: Handle bound imports (both new way and old way).

// TODO: This should really be called ImportDescriptor.

namespace hadesmem
{

class ImportDir
{
public:
  explicit ImportDir(Process const& process,
                     PeFile const& pe_file,
                     PIMAGE_IMPORT_DESCRIPTOR imp_desc)
    : process_(&process),
      pe_file_(&pe_file),
      base_(reinterpret_cast<PBYTE>(imp_desc)),
      data_(),
      is_virtual_beg_(false)
  {
    if (!base_)
    {
      NtHeaders nt_headers(process, pe_file);
      DWORD const import_dir_rva =
        nt_headers.GetDataDirectoryVirtualAddress(PeDataDir::Import);
      // Windows will load images which don't specify a size for the import
      // directory.
      if (!import_dir_rva)
      {
        HADESMEM_DETAIL_THROW_EXCEPTION(
          Error() << ErrorString("Import directory is invalid."));
      }

      base_ = static_cast<PBYTE>(RvaToVa(process, pe_file, import_dir_rva));
      if (!base_)
      {
        // Try to detect import dirs with a partially virtual descriptor
        // (overlapped at the beginning). Up to the first 3 DWORDS can be
        // overlapped (because they're allowed to be zero without invalidating
        // the entry).
        // Sample: imports_virtdesc.exe (Corkami PE Corpus)
        void* desc_raw_beg = nullptr;
        int i = 3;
        do
        {
          auto const new_rva =
            static_cast<DWORD>(import_dir_rva + sizeof(DWORD) * i);
          auto const new_va = RvaToVa(process, pe_file, new_rva);
          if (!new_va)
          {
            break;
          }
          desc_raw_beg = new_va;
        } while (--i);

        if (desc_raw_beg)
        {
          auto const offset = sizeof(DWORD) * (i + 1);
          auto const len = sizeof(IMAGE_IMPORT_DESCRIPTOR) - offset;
          auto const buf =
            ReadVector<std::uint8_t>(*process_, desc_raw_beg, len);
          auto const data_beg =
            reinterpret_cast<std::uint8_t*>(&data_) + offset;
          ZeroMemory(&data_, sizeof(data_));
          std::copy(std::begin(buf), std::end(buf), data_beg);
          base_ = static_cast<std::uint8_t*>(desc_raw_beg) - offset;
          is_virtual_beg_ = true;
        }
        else
        {
          HADESMEM_DETAIL_THROW_EXCEPTION(
            Error() << ErrorString("Import directory is invalid."));
        }
      }
    }

    UpdateRead();
  }

  PVOID GetBase() const HADESMEM_DETAIL_NOEXCEPT
  {
    return base_;
  }

  void UpdateRead()
  {
    data_ = Read<IMAGE_IMPORT_DESCRIPTOR>(*process_, base_);
  }

  void UpdateWrite()
  {
    Write(*process_, base_, data_);
  }

  // Check for virtual descriptor overlap trick.
  bool IsVirtualBegin() const
  {
    return is_virtual_beg_;
  }

  // Check for virtual termination trick.
  // TODO: Think about what the best way to solve this is... Currently we're
  // forcing the user to thunk about it, which may not be ideal.
  bool IsVirtualTerminated() const
  {
    // It's possible for the last entry to be in virtual space, because it only
    // needs to have its Name or FirstThunk null.
    // Sample: imports_vterm.exe (Corkami PE Corpus)
    // TODO: Fix this for cases where a virtual descriptor is 'real', rather
    // than just used as a terminator.
    if (pe_file_->GetType() == PeFileType::Data &&
        (base_ + sizeof(IMAGE_IMPORT_DESCRIPTOR)) >=
          static_cast<PBYTE>(pe_file_->GetBase()) + pe_file_->GetSize())
    {
      return true;
    }

    return false;
  }

  // Check for TLS AOI trick.
  // Sample: manyimportsW7.exe (Corkami PE Corpus)
  // TODO: Think about what the best way to solve this is... Currently we're
  // forcing the user to thunk about it, which may not be ideal.
  bool IsTlsAoiTerminated() const
  {
    try
    {
      TlsDir tls_dir(*process_, *pe_file_);
      ULONG_PTR const image_base = GetRuntimeBase(*process_, *pe_file_);
      auto const address_of_index_raw =
        RvaToVa(*process_,
                *pe_file_,
                static_cast<DWORD>(tls_dir.GetAddressOfIndex() - image_base));
      return (address_of_index_raw ==
                base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, Name) ||
              address_of_index_raw ==
                base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, FirstThunk));
    }
    catch (std::exception const& /*e*/)
    {
      return false;
    }
  }

  DWORD GetOriginalFirstThunk() const
  {
    return data_.OriginalFirstThunk;
  }

  DWORD GetTimeDateStamp() const
  {
    return data_.TimeDateStamp;
  }

  DWORD GetForwarderChain() const
  {
    return data_.ForwarderChain;
  }

  DWORD GetNameRaw() const
  {
    return data_.Name;
  }

  std::string GetName() const
  {
    DWORD const name_rva = GetNameRaw();
    if (!name_rva)
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Name RVA is invalid."));
    }

    auto name_va =
      static_cast<std::uint8_t*>(RvaToVa(*process_, *pe_file_, name_rva));
    // It's possible for the RVA to be invalid on disk because it's fixed by
    // relocations.
    // TODO: Handle this case.
    // Sample: imports_relocW7.exe
    if (!name_va)
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Name VA is invalid."));
    }

    if (pe_file_->GetType() == PeFileType::Image)
    {
      return ReadString<char>(*process_, name_va);
    }
    else if (pe_file_->GetType() == PeFileType::Data)
    {
      std::string name;
      // Handle EOF termination.
      // Sample: maxsecXP.exe (Corkami PE Corpus)
      // TODO: Fix the perf of this.
      // TODO: Detect and handle the case where the string is terminated
      // virtually.
      void const* const file_end =
        static_cast<std::uint8_t const*>(pe_file_->GetBase()) +
        pe_file_->GetSize();
      while (name_va < file_end)
      {
        if (char const c = Read<char>(*process_, name_va++))
        {
          name.push_back(c);
        }
        else
        {
          break;
        }
      }
      return name;
    }
    else
    {
      HADESMEM_DETAIL_ASSERT(false);
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Unknown PE file type."));
    }
  }

  DWORD GetFirstThunk() const
  {
    return data_.FirstThunk;
  }

  void SetOriginalFirstThunk(DWORD original_first_thunk)
  {
    data_.OriginalFirstThunk = original_first_thunk;
  }

  void SetTimeDateStamp(DWORD time_date_stamp)
  {
    data_.TimeDateStamp = time_date_stamp;
  }

  void SetForwarderChain(DWORD forwarder_chain)
  {
    data_.ForwarderChain = forwarder_chain;
  }

  void SetNameRaw(DWORD name)
  {
    data_.Name = name;
  }

  void SetName(std::string const& name)
  {
    DWORD name_rva =
      Read<DWORD>(*process_, base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, Name));
    if (!name_rva)
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Name RVA is null."));
    }

    PVOID name_ptr = RvaToVa(*process_, *pe_file_, name_rva);
    if (!name_ptr)
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Name VA is null."));
    }

    std::string const cur_name = ReadString<char>(*process_, name_ptr);

    // TODO: Support allocating space for a new name rather than just
    // overwriting the existing one.
    if (name.size() > cur_name.size())
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(
        Error() << ErrorString("New name longer than existing name."));
    }

    return WriteString(*process_, name_ptr, name);
  }

  void SetFirstThunk(DWORD first_thunk)
  {
    data_.FirstThunk = first_thunk;
  }

private:
  Process const* process_;
  PeFile const* pe_file_;
  PBYTE base_;
  IMAGE_IMPORT_DESCRIPTOR data_;
  bool is_virtual_beg_;
};

inline bool operator==(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() == rhs.GetBase();
}

inline bool operator!=(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return !(lhs == rhs);
}

inline bool operator<(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() < rhs.GetBase();
}

inline bool operator<=(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() <= rhs.GetBase();
}

inline bool operator>(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() > rhs.GetBase();
}

inline bool operator>=(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() >= rhs.GetBase();
}

inline std::ostream& operator<<(std::ostream& lhs, ImportDir const& rhs)
{
  std::locale const old = lhs.imbue(std::locale::classic());
  lhs << rhs.GetBase();
  lhs.imbue(old);
  return lhs;
}

inline std::wostream& operator<<(std::wostream& lhs, ImportDir const& rhs)
{
  std::locale const old = lhs.imbue(std::locale::classic());
  lhs << rhs.GetBase();
  lhs.imbue(old);
  return lhs;
}
}
<commit_msg>* [ImportDir] Note to self.<commit_after>// Copyright (C) 2010-2013 Joshua Boyce.
// See the file COPYING for copying permission.

#pragma once

#include <cstddef>
#include <iosfwd>
#include <memory>
#include <ostream>
#include <string>
#include <utility>

#include <windows.h>
#include <winnt.h>

#include <hadesmem/config.hpp>
#include <hadesmem/error.hpp>
#include <hadesmem/pelib/nt_headers.hpp>
#include <hadesmem/pelib/pe_file.hpp>
#include <hadesmem/pelib/tls_dir.hpp>
#include <hadesmem/process.hpp>
#include <hadesmem/read.hpp>
#include <hadesmem/write.hpp>

// TODO: Handle forwarded imports.

// TODO: Handle bound imports (both new way and old way).

// TODO: This should really be called ImportDescriptor.

namespace hadesmem
{

class ImportDir
{
public:
  explicit ImportDir(Process const& process,
                     PeFile const& pe_file,
                     PIMAGE_IMPORT_DESCRIPTOR imp_desc)
    : process_(&process),
      pe_file_(&pe_file),
      base_(reinterpret_cast<PBYTE>(imp_desc)),
      data_(),
      is_virtual_beg_(false)
  {
    if (!base_)
    {
      NtHeaders nt_headers(process, pe_file);
      DWORD const import_dir_rva =
        nt_headers.GetDataDirectoryVirtualAddress(PeDataDir::Import);
      // Windows will load images which don't specify a size for the import
      // directory.
      if (!import_dir_rva)
      {
        HADESMEM_DETAIL_THROW_EXCEPTION(
          Error() << ErrorString("Import directory is invalid."));
      }

      base_ = static_cast<PBYTE>(RvaToVa(process, pe_file, import_dir_rva));
      if (!base_)
      {
        // Try to detect import dirs with a partially virtual descriptor
        // (overlapped at the beginning). Up to the first 3 DWORDS can be
        // overlapped (because they're allowed to be zero without invalidating
        // the entry).
        // Sample: imports_virtdesc.exe (Corkami PE Corpus)
        void* desc_raw_beg = nullptr;
        int i = 3;
        do
        {
          auto const new_rva =
            static_cast<DWORD>(import_dir_rva + sizeof(DWORD) * i);
          auto const new_va = RvaToVa(process, pe_file, new_rva);
          if (!new_va)
          {
            break;
          }
          desc_raw_beg = new_va;
        } while (--i);

        if (desc_raw_beg)
        {
          auto const offset = sizeof(DWORD) * (i + 1);
          auto const len = sizeof(IMAGE_IMPORT_DESCRIPTOR) - offset;
          auto const buf =
            ReadVector<std::uint8_t>(*process_, desc_raw_beg, len);
          auto const data_beg =
            reinterpret_cast<std::uint8_t*>(&data_) + offset;
          ZeroMemory(&data_, sizeof(data_));
          std::copy(std::begin(buf), std::end(buf), data_beg);
          base_ = static_cast<std::uint8_t*>(desc_raw_beg) - offset;
          is_virtual_beg_ = true;
        }
        else
        {
          HADESMEM_DETAIL_THROW_EXCEPTION(
            Error() << ErrorString("Import directory is invalid."));
        }
      }
    }

    UpdateRead();
  }

  PVOID GetBase() const HADESMEM_DETAIL_NOEXCEPT
  {
    return base_;
  }

  // TODO: Support virtual overlap trick properly, because currently we're
  // reading garbage memory.
  // TODO: Support virtual termination trick properly, because currently we're
  // reading garbage memory.
  void UpdateRead()
  {
    data_ = Read<IMAGE_IMPORT_DESCRIPTOR>(*process_, base_);
  }

  void UpdateWrite()
  {
    Write(*process_, base_, data_);
  }

  // Check for virtual descriptor overlap trick.
  bool IsVirtualBegin() const
  {
    return is_virtual_beg_;
  }

  // Check for virtual termination trick.
  // TODO: Think about what the best way to solve this is... Currently we're
  // forcing the user to thunk about it, which may not be ideal.
  bool IsVirtualTerminated() const
  {
    // It's possible for the last entry to be in virtual space, because it only
    // needs to have its Name or FirstThunk null.
    // Sample: imports_vterm.exe (Corkami PE Corpus)
    if (pe_file_->GetType() == PeFileType::Data &&
        (base_ + sizeof(IMAGE_IMPORT_DESCRIPTOR)) >=
          static_cast<PBYTE>(pe_file_->GetBase()) + pe_file_->GetSize())
    {
      return true;
    }

    return false;
  }

  // Check for TLS AOI trick.
  // Sample: manyimportsW7.exe (Corkami PE Corpus)
  // TODO: Think about what the best way to solve this is... Currently we're
  // forcing the user to thunk about it, which may not be ideal.
  bool IsTlsAoiTerminated() const
  {
    try
    {
      TlsDir tls_dir(*process_, *pe_file_);
      ULONG_PTR const image_base = GetRuntimeBase(*process_, *pe_file_);
      auto const address_of_index_raw =
        RvaToVa(*process_,
                *pe_file_,
                static_cast<DWORD>(tls_dir.GetAddressOfIndex() - image_base));
      return (address_of_index_raw ==
                base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, Name) ||
              address_of_index_raw ==
                base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, FirstThunk));
    }
    catch (std::exception const& /*e*/)
    {
      return false;
    }
  }

  DWORD GetOriginalFirstThunk() const
  {
    return data_.OriginalFirstThunk;
  }

  DWORD GetTimeDateStamp() const
  {
    return data_.TimeDateStamp;
  }

  DWORD GetForwarderChain() const
  {
    return data_.ForwarderChain;
  }

  DWORD GetNameRaw() const
  {
    return data_.Name;
  }

  std::string GetName() const
  {
    DWORD const name_rva = GetNameRaw();
    if (!name_rva)
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Name RVA is invalid."));
    }

    auto name_va =
      static_cast<std::uint8_t*>(RvaToVa(*process_, *pe_file_, name_rva));
    // It's possible for the RVA to be invalid on disk because it's fixed by
    // relocations.
    // TODO: Handle this case.
    // Sample: imports_relocW7.exe
    if (!name_va)
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Name VA is invalid."));
    }

    if (pe_file_->GetType() == PeFileType::Image)
    {
      return ReadString<char>(*process_, name_va);
    }
    else if (pe_file_->GetType() == PeFileType::Data)
    {
      std::string name;
      // Handle EOF termination.
      // Sample: maxsecXP.exe (Corkami PE Corpus)
      // TODO: Fix the perf of this.
      // TODO: Detect and handle the case where the string is terminated
      // virtually.
      void const* const file_end =
        static_cast<std::uint8_t const*>(pe_file_->GetBase()) +
        pe_file_->GetSize();
      while (name_va < file_end)
      {
        if (char const c = Read<char>(*process_, name_va++))
        {
          name.push_back(c);
        }
        else
        {
          break;
        }
      }
      return name;
    }
    else
    {
      HADESMEM_DETAIL_ASSERT(false);
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Unknown PE file type."));
    }
  }

  DWORD GetFirstThunk() const
  {
    return data_.FirstThunk;
  }

  void SetOriginalFirstThunk(DWORD original_first_thunk)
  {
    data_.OriginalFirstThunk = original_first_thunk;
  }

  void SetTimeDateStamp(DWORD time_date_stamp)
  {
    data_.TimeDateStamp = time_date_stamp;
  }

  void SetForwarderChain(DWORD forwarder_chain)
  {
    data_.ForwarderChain = forwarder_chain;
  }

  void SetNameRaw(DWORD name)
  {
    data_.Name = name;
  }

  void SetName(std::string const& name)
  {
    DWORD name_rva =
      Read<DWORD>(*process_, base_ + offsetof(IMAGE_IMPORT_DESCRIPTOR, Name));
    if (!name_rva)
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Name RVA is null."));
    }

    PVOID name_ptr = RvaToVa(*process_, *pe_file_, name_rva);
    if (!name_ptr)
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(Error()
                                      << ErrorString("Name VA is null."));
    }

    std::string const cur_name = ReadString<char>(*process_, name_ptr);

    // TODO: Support allocating space for a new name rather than just
    // overwriting the existing one.
    if (name.size() > cur_name.size())
    {
      HADESMEM_DETAIL_THROW_EXCEPTION(
        Error() << ErrorString("New name longer than existing name."));
    }

    return WriteString(*process_, name_ptr, name);
  }

  void SetFirstThunk(DWORD first_thunk)
  {
    data_.FirstThunk = first_thunk;
  }

private:
  Process const* process_;
  PeFile const* pe_file_;
  PBYTE base_;
  IMAGE_IMPORT_DESCRIPTOR data_;
  bool is_virtual_beg_;
};

inline bool operator==(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() == rhs.GetBase();
}

inline bool operator!=(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return !(lhs == rhs);
}

inline bool operator<(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() < rhs.GetBase();
}

inline bool operator<=(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() <= rhs.GetBase();
}

inline bool operator>(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() > rhs.GetBase();
}

inline bool operator>=(ImportDir const& lhs, ImportDir const& rhs)
  HADESMEM_DETAIL_NOEXCEPT
{
  return lhs.GetBase() >= rhs.GetBase();
}

inline std::ostream& operator<<(std::ostream& lhs, ImportDir const& rhs)
{
  std::locale const old = lhs.imbue(std::locale::classic());
  lhs << rhs.GetBase();
  lhs.imbue(old);
  return lhs;
}

inline std::wostream& operator<<(std::wostream& lhs, ImportDir const& rhs)
{
  std::locale const old = lhs.imbue(std::locale::classic());
  lhs << rhs.GetBase();
  lhs.imbue(old);
  return lhs;
}
}
<|endoftext|>


<commit_before><commit_msg>Added missing <limits> header<commit_after><|endoftext|>


<commit_before>#ifndef SIMDIFY_STRUCTURE_OF_ARRAYS
#define SIMDIFY_STRUCTURE_OF_ARRAYS

#include "../simdify.hpp"
#include "../containers.hpp"
#include "../util/inline.hpp"
#include "named_array.hpp"

namespace simd {
    template <typename Simd_t, id... Ids>
    struct structure_of_arrays;

    template <typename Mm_t, typename F_t, typename Simd_t, id...Ids>
    struct structure_of_arrays<simd_base<Mm_t, F_t, Simd_t>, Ids...> {
        static constexpr std::size_t N = sizeof...(Ids);
        using simd_t = Simd_t;
        using f_t = F_t;
        using mm_t = Mm_t;

        template <typename T>
        struct iterator_base : named_array<T, Ids...> {};

        struct iterator : iterator_base<simd_t> {};

        struct const_iterator : iterator_base<const simd_t> {};

        template <typename T>
        struct tail_iterator_base : named_array<T, Ids...> {};

        struct tail_iterator : tail_iterator_base<f_t&> {};

        struct const_tail_iterator : tail_iterator_base<const f_t&> {};

        iterator begin();
        iterator end();
        const_iterator begin() const;
        const_iterator end() const;
        const_iterator cbegin() const;
        const_iterator cend() const;
        iterator bodybegin();
        iterator bodyend();
        const_iterator bodybegin() const;
        const_iterator bodyend() const;
        const_iterator bodycbegin() const;
        const_iterator bodycend() const;
        tail_iterator tailbegin();
        tail_iterator tailend();
        const_tail_iterator tailbegin() const;
        const_tail_iterator tailend() const;
        const_tail_iterator tailcbegin() const;
        const_tail_iterator tailcend() const;
    };
}

#endif // SIMDIFY_STRUCTURE_OF_ARRAYS
<commit_msg>Iterators for structure_of_arrays (work in progress)<commit_after>#ifndef SIMDIFY_STRUCTURE_OF_ARRAYS
#define SIMDIFY_STRUCTURE_OF_ARRAYS

#include "../simdify.hpp"
#include "../containers.hpp"
#include "../util/inline.hpp"
#include "../util/malloc.hpp"
#include "expr.hpp"
#include "named_array.hpp"
#include <array>
#include <vector>

namespace simd {
    template <typename Simd_t, id... Ids>
    struct structure_of_arrays;

    template <typename Mm_t, typename F_t, typename Simd_t, id...Ids>
    struct structure_of_arrays<simd_base<Mm_t, F_t, Simd_t>, Ids...> {
        using simd_t = Simd_t;
        using f_t = F_t;
        using mm_t = Mm_t;
        enum : std::size_t { N = sizeof...(Ids), W = simd_t::W };

        struct iterator {
            using buffer_t = named_array<expr::aligned<f_t>, Ids...>;

            template <typename Func>
            struct TransformItem {
                iterator& m_it;
                Func m_f;

                SIMDIFY_FORCE_INLINE constexpr TransformItem(iterator& it, Func&& f) :
                    m_it(it), m_f(std::move(f)) {}

                template <std::size_t I>
                SIMDIFY_FORCE_INLINE constexpr void perform() const {
                    m_f(simd::get<I>(m_it.m_buf).ptr);
                }
            };

            iterator(structure_of_arrays& from, std::size_t index) {
                detail::ForEach(N)::perform(TransformItem(*this, [&from, index](f_t*& ptr) {
                    ptr = std::get<N>(from.m_data).data() + from;
                }));
            }

            iterator& operator++() {
                detail::ForEach(N)::perform(TransformItem(*this, [](f_t*& ptr) {
                    ptr += W;
                }));
                return *this;
            }

            bool operator==(const iterator& rhs) { return simd::get<0>(m_buf).ptr == simd::get<0>(rhs.m_buf).ptr; }
            bool operator!=(const iterator& rhs) { return simd::get<0>(m_buf).ptr != simd::get<0>(rhs.m_buf).ptr; }
            buffer_t& operator*() const { return m_buf; }
            buffer_t& operator->() const { return m_buf; }

        private:
            buffer_t m_buf;
        };

        //iterator begin();
        //iterator end();
        //const_iterator begin() const;
        //const_iterator end() const;
        //const_iterator cbegin() const;
        //const_iterator cend() const;
        //iterator bodybegin();
        //iterator bodyend();
        //const_iterator bodybegin() const;
        //const_iterator bodyend() const;
        //const_iterator bodycbegin() const;
        //const_iterator bodycend() const;
        //tail_iterator tailbegin();
        //tail_iterator tailend();
        //const_tail_iterator tailbegin() const;
        //const_tail_iterator tailend() const;
        //const_tail_iterator tailcbegin() const;
        //const_tail_iterator tailcend() const;
    private:
        std::array<std::vector<f_t, aligned_allocator<f_t, alignof(mm_t)>>, N> m_data;
    };
}

#endif // SIMDIFY_STRUCTURE_OF_ARRAYS
<|endoftext|>


<commit_before>
#ifndef INTERCOM_CPP_POSIX_IUNKNOWN_H
#define INTERCOM_CPP_POSIX_IUNKNOWN_H

#include "../callingconvention.hpp"
#include "../datatypes.hpp"
#include "../error_codes.hpp"
#include "../guiddef.hpp"

// MIDL_INTERFACE("00000000-0000-0000-C000-000000000046")
struct ISupportErrorInfo
{
public:

    virtual intercom::HRESULT INTERCOM_CC InterfaceSupportsErrorInfo(
        intercom::REFIID riid
    ) = 0;
};

static const intercom::IID IID_ISupportErrorInfo = { 0xDF0B3D60, 0x548F, 0x101B, { 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19 } };

#endif
<commit_msg>Add IErrorInfo definition to posix<commit_after>
#ifndef INTERCOM_CPP_POSIX_ISUPPORTERRORINFO_H
#define INTERCOM_CPP_POSIX_ISUPPORTERRORINFO_H

#include "../callingconvention.hpp"
#include "../datatypes.hpp"
#include "../error_codes.hpp"
#include "../guiddef.hpp"

#include "datatypes.hpp"

// MIDL_INTERFACE("1CF2B120-547D-101B-8E65-08002B2BD119")
struct IErrorInfo : public IUnknown
{
public:

	virtual intercom::HRESULT INTERCOM_CC GetGUID(
		intercom::GUID *pGUID) = 0;

	virtual intercom::HRESULT INTERCOM_CC GetSource(
		intercom::BSTR *pBstrSource) = 0;

	virtual intercom::HRESULT INTERCOM_CC GetDescription(
		intercom::BSTR *pBstrDescription) = 0;

	virtual intercom::HRESULT INTERCOM_CC GetHelpFile(
		intercom::BSTR *pBstrHelpFile) = 0;

	virtual intercom::HRESULT INTERCOM_CC GetHelpContext(
		intercom::DWORD *pdwHelpContext) = 0;
};

static const intercom::IID IID_IErrorInfo = {
		0x1CF2B120, 0x547D, 0x101B,
		{ 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19 } };

// MIDL_INTERFACE("DF0B3D60-548F-101B-8E65-08002B2BD119" )
struct ISupportErrorInfo : public IUnknown
{
public:

    virtual intercom::HRESULT INTERCOM_CC InterfaceSupportsErrorInfo(
        intercom::REFIID riid
    ) = 0;
};

static const intercom::IID IID_ISupportErrorInfo = { 0xDF0B3D60, 0x548F, 0x101B, { 0x8E, 0x65, 0x08, 0x00, 0x2B, 0x2B, 0xD1, 0x19 } };

#endif
<|endoftext|>