<commit_before>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h"

namespace {

void ExpectVolumeNear(int expected, int actual) {
  // The hardware volume may be more coarsely quantized than [0, 255], so
  // it is not always reasonable to expect to get exactly what we set. This
  // allows for some error.
  const int kMaxVolumeError = 10;
  EXPECT_NEAR(expected, actual, kMaxVolumeError);
  EXPECT_GE(actual, 0);
  EXPECT_LE(actual, 255);
}

}  // namespace

class VolumeTest : public AfterStreamingFixture {
};

// TODO(phoglund): a number of tests are disabled here on Linux, all pending
// investigation in
// http://code.google.com/p/webrtc/issues/detail?id=367

TEST_F(VolumeTest, VerifyCorrectErrorReturns) {
  // All tests run on correct initialization which eliminates one possible error
  // return. In addition, we assume the audio_device returning values without
  // error, which eliminates another potential error.
  // Left to verify are sanity checks of set parameters.

  // Valid volume range: [0, 255]
  EXPECT_EQ(-1, voe_volume_control_->SetSpeakerVolume(256));
  EXPECT_EQ(-1, voe_volume_control_->SetMicVolume(256));

  // Valid panning rage: [0, 1]
  EXPECT_EQ(-1, voe_volume_control_->SetOutputVolumePan(channel_, -0.1f, 0.5f));
  EXPECT_EQ(-1, voe_volume_control_->SetOutputVolumePan(channel_, 1.1f, 0.5f));
  EXPECT_EQ(-1, voe_volume_control_->SetOutputVolumePan(channel_, 0.5f, -0.1f));
  EXPECT_EQ(-1, voe_volume_control_->SetOutputVolumePan(channel_, 0.5f, 1.1f));
}

TEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) {
  unsigned int volume = 1000;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  EXPECT_LE(volume, 255u);
}

TEST_F(VolumeTest, SetVolumeBeforePlayoutWorks) {
  // This is a rather specialized test, intended to exercise some PulseAudio
  // code. However, these conditions should be satisfied on any platform.
  unsigned int original_volume = 0;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));
  Sleep(1000);

  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(200));
  unsigned int volume;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(200u, volume);

  PausePlaying();
  ResumePlaying();
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  // Ensure the volume has not changed after resuming playout.
  ExpectVolumeNear(200u, volume);

  PausePlaying();
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));
  ResumePlaying();
  // Ensure the volume set while paused is retained.
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(100u, volume);

  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));
}

TEST_F(VolumeTest, ManualSetVolumeWorks) {
  unsigned int original_volume = 0;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));
  Sleep(1000);

  TEST_LOG("Setting speaker volume to 0 out of 255.\n");
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0));
  unsigned int volume;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(0u, volume);
  Sleep(1000);

  TEST_LOG("Setting speaker volume to 100 out of 255.\n");
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(100u, volume);
  Sleep(1000);

  // Set the volume to 255 very briefly so we don't blast the poor user
  // listening to this. This is just to test the call succeeds.
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255));
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(255u, volume);

  TEST_LOG("Setting speaker volume to the original %d out of 255.\n",
      original_volume);
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));
  Sleep(1000);
}

TEST_F(VolumeTest, DefaultMicrophoneVolumeIsAtMost255) {
  unsigned int volume = 1000;
  if (voe_volume_control_->GetMicVolume(volume) == 0)
    EXPECT_LE(volume, 255u);
  else
    EXPECT_EQ(1000u, volume);
}

TEST_F(VolumeTest, DISABLED_ON_LINUX(
          ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAcgOff)) {
  SwitchToManualMicrophone();
  EXPECT_EQ(0, voe_apm_->SetAgcStatus(false));

  unsigned int original_volume = 0;
  EXPECT_EQ(0, voe_volume_control_->GetMicVolume(original_volume));

  TEST_LOG("Setting microphone volume to 0.\n");
  EXPECT_EQ(0, voe_volume_control_->SetMicVolume(channel_));
  Sleep(1000);
  TEST_LOG("Setting microphone volume to 255.\n");
  EXPECT_EQ(0, voe_volume_control_->SetMicVolume(255));
  Sleep(1000);
  TEST_LOG("Setting microphone volume back to saved value.\n");
  EXPECT_EQ(0, voe_volume_control_->SetMicVolume(original_volume));
  Sleep(1000);
}

TEST_F(VolumeTest, ChannelScalingIsOneByDefault) {
  float scaling = -1.0f;

  EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(
      channel_, scaling));
  EXPECT_FLOAT_EQ(1.0f, scaling);
}

TEST_F(VolumeTest, ManualCanSetChannelScaling) {
  EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling(
      channel_, 0.1f));

  float scaling = 1.0f;
  EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(
      channel_, scaling));

  EXPECT_FLOAT_EQ(0.1f, scaling);

  TEST_LOG("Channel scaling set to 0.1: audio should be barely audible.\n");
  Sleep(2000);
}

TEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) {
  bool is_muted = true;
  EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
  EXPECT_FALSE(is_muted);
}

TEST_F(VolumeTest, DISABLED_ON_LINUX(ManualInputMutingMutesMicrophone)) {
  SwitchToManualMicrophone();

  // Enable muting.
  EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, true));
  bool is_muted = false;
  EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
  EXPECT_TRUE(is_muted);

  TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n");
  Sleep(2000);

  // Test that we can disable muting.
  EXPECT_EQ(0, voe_volume_control_->SetInputMute(channel_, false));
  EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
  EXPECT_FALSE(is_muted);

  TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n");
  Sleep(2000);
}

TEST_F(VolumeTest, ManualTestInputAndOutputLevels) {
  SwitchToManualMicrophone();

  TEST_LOG("Speak and verify that the following levels look right:\n");
  for (int i = 0; i < 5; i++) {
    Sleep(1000);
    unsigned int input_level = 0;
    unsigned int output_level = 0;
    unsigned int input_level_full_range = 0;
    unsigned int output_level_full_range = 0;

    EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel(
        input_level));
    EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel(
        channel_, output_level));
    EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange(
        input_level_full_range));
    EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange(
        channel_, output_level_full_range));

    TEST_LOG("    warped levels (0-9)    : in=%5d, out=%5d\n",
        input_level, output_level);
    TEST_LOG("    linear levels (0-32768): in=%5d, out=%5d\n",
        input_level_full_range, output_level_full_range);
  }
}

TEST_F(VolumeTest, ChannelsAreNotPannedByDefault) {
  float left = -1.0;
  float right = -1.0;

  EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));
  EXPECT_FLOAT_EQ(1.0, left);
  EXPECT_FLOAT_EQ(1.0, right);
}

TEST_F(VolumeTest, ManualTestChannelPanning) {
  TEST_LOG("Panning left.\n");
  EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f));
  Sleep(1000);

  TEST_LOG("Back to center.\n");
  EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f));
  Sleep(1000);

  TEST_LOG("Panning right.\n");
  EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f));
  Sleep(1000);

  // To finish, verify that the getter works.
  float left = 0.0f;
  float right = 0.0f;

  EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));
  EXPECT_FLOAT_EQ(0.1f, left);
  EXPECT_FLOAT_EQ(0.8f, right);
}
<commit_msg>VoEVolumeTest: Enabled Linux flaky tests<commit_after>/*
 *  Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "webrtc/voice_engine/test/auto_test/fixtures/after_streaming_fixture.h"

namespace {

void ExpectVolumeNear(int expected, int actual) {
  // The hardware volume may be more coarsely quantized than [0, 255], so
  // it is not always reasonable to expect to get exactly what we set. This
  // allows for some error.
  const int kMaxVolumeError = 10;
  EXPECT_NEAR(expected, actual, kMaxVolumeError);
  EXPECT_GE(actual, 0);
  EXPECT_LE(actual, 255);
}

}  // namespace

class VolumeTest : public AfterStreamingFixture {
 public:
  void SetAndVerifyMicVolume(unsigned int volume) {
    bool success = voe_volume_control_->SetMicVolume(volume) == 0;
#if !defined(WEBRTC_LINUX)
    EXPECT_TRUE(success);
#endif
    if (!success) {
      TEST_LOG("Failed to set microphone volume to %u.\n", volume);
      return;
    }

    unsigned int test_volume = 1000;
    success = voe_volume_control_->GetMicVolume(test_volume) == 0;
#if !defined(WEBRTC_LINUX)
    EXPECT_TRUE(success);
#endif
    if (success) {
      EXPECT_EQ(volume, test_volume);
    } else {
      TEST_LOG("Failed to get the microphone volume.");
      EXPECT_EQ(1000u, test_volume);
    }
  }

  void SetAndVerifyInputMute(bool enable) {
    bool success = voe_volume_control_->SetInputMute(channel_, enable) == 0;
#if !defined(WEBRTC_LINUX)
    EXPECT_TRUE(success);
#endif
    if (!success) {
      TEST_LOG("Failed to %smute input.\n", enable ? "" : "un");
      return;
    }

    bool is_muted = !enable;
    success = voe_volume_control_->GetInputMute(channel_, is_muted) == 0;
#if !defined(WEBRTC_LINUX)
    EXPECT_TRUE(success);
#endif
    if (success) {
      EXPECT_EQ(enable, is_muted);
    } else {
      TEST_LOG("Failed to mute the input.");
      EXPECT_NE(enable, is_muted);
    }
  }
};

// Some tests are flaky on Linux (Pulse Audio), which boils down to some system
// values not being acquired in time. In Pulse Audio we make one retry if
// needed, but if we fail then, a -1 is returned propagating up through VoE.
// To avoid possible bugs slipping through on other platforms we make adequate
// changes on Linux only.
TEST_F(VolumeTest, VerifyCorrectErrorReturns) {
  // All tests run on correct initialization which eliminates one possible error
  // return. In addition, we assume the audio_device returning values without
  // error, which eliminates another potential error.
  // Left to verify are sanity checks of set parameters.

  // Valid volume range: [0, 255]
  EXPECT_EQ(-1, voe_volume_control_->SetSpeakerVolume(256));
  EXPECT_EQ(-1, voe_volume_control_->SetMicVolume(256));

  // Valid panning rage: [0, 1]
  EXPECT_EQ(-1, voe_volume_control_->SetOutputVolumePan(channel_, -0.1f, 0.5f));
  EXPECT_EQ(-1, voe_volume_control_->SetOutputVolumePan(channel_, 1.1f, 0.5f));
  EXPECT_EQ(-1, voe_volume_control_->SetOutputVolumePan(channel_, 0.5f, -0.1f));
  EXPECT_EQ(-1, voe_volume_control_->SetOutputVolumePan(channel_, 0.5f, 1.1f));
}

TEST_F(VolumeTest, DefaultSpeakerVolumeIsAtMost255) {
  unsigned int volume = 1000;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  EXPECT_LE(volume, 255u);
}

TEST_F(VolumeTest, SetVolumeBeforePlayoutWorks) {
  // This is a rather specialized test, intended to exercise some PulseAudio
  // code. However, these conditions should be satisfied on any platform.
  unsigned int original_volume = 0;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));
  Sleep(1000);

  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(200));
  unsigned int volume;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(200u, volume);

  PausePlaying();
  ResumePlaying();
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  // Ensure the volume has not changed after resuming playout.
  ExpectVolumeNear(200u, volume);

  PausePlaying();
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));
  ResumePlaying();
  // Ensure the volume set while paused is retained.
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(100u, volume);

  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));
}

TEST_F(VolumeTest, ManualSetVolumeWorks) {
  unsigned int original_volume = 0;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(original_volume));
  Sleep(1000);

  TEST_LOG("Setting speaker volume to 0 out of 255.\n");
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(0));
  unsigned int volume;
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(0u, volume);
  Sleep(1000);

  TEST_LOG("Setting speaker volume to 100 out of 255.\n");
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(100));
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(100u, volume);
  Sleep(1000);

  // Set the volume to 255 very briefly so we don't blast the poor user
  // listening to this. This is just to test the call succeeds.
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(255));
  EXPECT_EQ(0, voe_volume_control_->GetSpeakerVolume(volume));
  ExpectVolumeNear(255u, volume);

  TEST_LOG("Setting speaker volume to the original %d out of 255.\n",
      original_volume);
  EXPECT_EQ(0, voe_volume_control_->SetSpeakerVolume(original_volume));
  Sleep(1000);
}

TEST_F(VolumeTest, DefaultMicrophoneVolumeIsAtMost255) {
  unsigned int volume = 1000;
  bool could_get_mic_volume = voe_volume_control_->GetMicVolume(volume) == 0;
#if !defined(WEBRTC_LINUX)
  EXPECT_TRUE(could_get_mic_volume);
#endif
  if (could_get_mic_volume) {
    EXPECT_LE(volume, 255u);
  } else {
    TEST_LOG("Failed to get the microphone volume.");
    EXPECT_EQ(1000u, volume);
  }
}

TEST_F(VolumeTest, ManualRequiresMicrophoneCanSetMicrophoneVolumeWithAgcOff) {
  SwitchToManualMicrophone();
  EXPECT_EQ(0, voe_apm_->SetAgcStatus(false));

  unsigned int original_volume = 0;
  bool could_get_mic_volume =
      (voe_volume_control_->GetMicVolume(original_volume) == 0);
#if !defined(WEBRTC_LINUX)
  EXPECT_TRUE(could_get_mic_volume);
#endif
  if (could_get_mic_volume)
    TEST_LOG("Current microphone volume is %u.\n", original_volume);
  else
    TEST_LOG("Failed to fetch current microphone volume.\n");

  TEST_LOG("Setting microphone volume to 0.\n");
  SetAndVerifyMicVolume(0);
  Sleep(1000);
  TEST_LOG("Setting microphone volume to 255.\n");
  SetAndVerifyMicVolume(255);
  Sleep(1000);
  if (could_get_mic_volume) {
    TEST_LOG("Setting microphone volume back to %u.\n", original_volume);
    SetAndVerifyMicVolume(original_volume);
    Sleep(1000);
  }
}

TEST_F(VolumeTest, ChannelScalingIsOneByDefault) {
  float scaling = -1.0f;

  EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(
      channel_, scaling));
  EXPECT_FLOAT_EQ(1.0f, scaling);
}

TEST_F(VolumeTest, ManualCanSetChannelScaling) {
  EXPECT_EQ(0, voe_volume_control_->SetChannelOutputVolumeScaling(
      channel_, 0.1f));

  float scaling = 1.0f;
  EXPECT_EQ(0, voe_volume_control_->GetChannelOutputVolumeScaling(
      channel_, scaling));

  EXPECT_FLOAT_EQ(0.1f, scaling);

  TEST_LOG("Channel scaling set to 0.1: audio should be barely audible.\n");
  Sleep(2000);
}

TEST_F(VolumeTest, InputMutingIsNotEnabledByDefault) {
  bool is_muted = true;
  EXPECT_EQ(0, voe_volume_control_->GetInputMute(channel_, is_muted));
  EXPECT_FALSE(is_muted);
}

TEST_F(VolumeTest, ManualInputMutingMutesMicrophone) {
  SwitchToManualMicrophone();
  // Enable muting.
  SetAndVerifyInputMute(true);
  TEST_LOG("Muted: talk into microphone and verify you can't hear yourself.\n");
  Sleep(2000);

  // Test that we can disable muting.
  SetAndVerifyInputMute(false);
  TEST_LOG("Unmuted: talk into microphone and verify you can hear yourself.\n");
  Sleep(2000);
}

TEST_F(VolumeTest, ManualTestInputAndOutputLevels) {
  SwitchToManualMicrophone();

  TEST_LOG("Speak and verify that the following levels look right:\n");
  for (int i = 0; i < 5; i++) {
    Sleep(1000);
    unsigned int input_level = 0;
    unsigned int output_level = 0;
    unsigned int input_level_full_range = 0;
    unsigned int output_level_full_range = 0;

    EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevel(
        input_level));
    EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevel(
        channel_, output_level));
    EXPECT_EQ(0, voe_volume_control_->GetSpeechInputLevelFullRange(
        input_level_full_range));
    EXPECT_EQ(0, voe_volume_control_->GetSpeechOutputLevelFullRange(
        channel_, output_level_full_range));

    TEST_LOG("    warped levels (0-9)    : in=%5d, out=%5d\n",
        input_level, output_level);
    TEST_LOG("    linear levels (0-32768): in=%5d, out=%5d\n",
        input_level_full_range, output_level_full_range);
  }
}

TEST_F(VolumeTest, ChannelsAreNotPannedByDefault) {
  float left = -1.0;
  float right = -1.0;

  EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));
  EXPECT_FLOAT_EQ(1.0, left);
  EXPECT_FLOAT_EQ(1.0, right);
}

TEST_F(VolumeTest, ManualTestChannelPanning) {
  TEST_LOG("Panning left.\n");
  EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.8f, 0.1f));
  Sleep(1000);

  TEST_LOG("Back to center.\n");
  EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 1.0f, 1.0f));
  Sleep(1000);

  TEST_LOG("Panning right.\n");
  EXPECT_EQ(0, voe_volume_control_->SetOutputVolumePan(channel_, 0.1f, 0.8f));
  Sleep(1000);

  // To finish, verify that the getter works.
  float left = 0.0f;
  float right = 0.0f;

  EXPECT_EQ(0, voe_volume_control_->GetOutputVolumePan(channel_, left, right));
  EXPECT_FLOAT_EQ(0.1f, left);
  EXPECT_FLOAT_EQ(0.8f, right);
}
<|endoftext|>


<commit_before>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file transaction.cpp
 * @author Dmitrii Khokhlov <winsvega@mail.ru>
 * @date 2015
 * Transaaction test functions.
 */

#include "TestHelper.h"

using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;

namespace dev {  namespace test {

void doTransactionTests(json_spirit::mValue& _v, bool _fillin)
{
	for (auto& i: _v.get_obj())
	{
		cerr << i.first << endl;
		mObject& o = i.second.get_obj();

		if (_fillin)
		{
			BOOST_REQUIRE(o.count("transaction") > 0);
			mObject tObj = o["transaction"].get_obj();

			//Construct Rlp of the given transaction
			RLPStream rlpStream = createRLPStreamFromTransactionFields(tObj);
			o["rlp"] = "0x" + toHex(rlpStream.out());

			try
			{
				Transaction txFromFields(rlpStream.out(), CheckTransaction::Everything);
				if (!txFromFields.signature().isValid())
					BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );

				o["sender"] = toString(txFromFields.sender());
				o["transaction"] = ImportTest::makeAllFieldsHex(tObj);
			}
			catch(Exception const& _e)
			{
				//Transaction is InValid
				cnote << "Transaction Exception: " << diagnostic_information(_e);
				o.erase(o.find("transaction"));
				if (o.count("expect") > 0)
				{
					bool expectInValid = (o["expect"].get_str() == "invalid");
					if (Options::get().checkState)
							BOOST_CHECK_MESSAGE(expectInValid, "Check state: Transaction '" << i.first << "' is expected to be valid!");
						else
							BOOST_WARN_MESSAGE(expectInValid, "Check state: Transaction '" << i.first << "' is expected to be valid!");

					o.erase(o.find("expect"));
				}
			}

			//Transaction is Valid
			if (o.count("expect") > 0)
			{
				bool expectValid = (o["expect"].get_str() == "valid");
				if (Options::get().checkState)
						BOOST_CHECK_MESSAGE(expectValid, "Check state: Transaction '" << i.first << "' is expected to be invalid!");
					else
						BOOST_WARN_MESSAGE(expectValid, "Check state: Transaction '" << i.first << "' is expected to be invalid!");

				o.erase(o.find("expect"));
			}

		}
		else
		{
			BOOST_REQUIRE(o.count("rlp") > 0);
			Transaction txFromRlp;
			try
			{
				bytes stream = importByteArray(o["rlp"].get_str());
				RLP rlp(stream);
				txFromRlp = Transaction(rlp.data(), CheckTransaction::Everything);
				if (!txFromRlp.signature().isValid())
					BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );
			}
			catch(Exception const& _e)
			{
				cnote << i.first;
				cnote << "Transaction Exception: " << diagnostic_information(_e);
				BOOST_CHECK_MESSAGE(o.count("transaction") == 0, "A transaction object should not be defined because the RLP is invalid!");
				continue;
			}
			catch(...)
			{
				BOOST_CHECK_MESSAGE(o.count("transaction") == 0, "A transaction object should not be defined because the RLP is invalid!");
				continue;
			}

			BOOST_REQUIRE(o.count("transaction") > 0);

			mObject tObj = o["transaction"].get_obj();
			Transaction txFromFields(createRLPStreamFromTransactionFields(tObj).out(), CheckTransaction::Everything);

			//Check the fields restored from RLP to original fields
			BOOST_CHECK_MESSAGE(txFromFields.data() == txFromRlp.data(), "Data in given RLP not matching the Transaction data!");
			BOOST_CHECK_MESSAGE(txFromFields.value() == txFromRlp.value(), "Value in given RLP not matching the Transaction value!");
			BOOST_CHECK_MESSAGE(txFromFields.gasPrice() == txFromRlp.gasPrice(), "GasPrice in given RLP not matching the Transaction gasPrice!");
			BOOST_CHECK_MESSAGE(txFromFields.gas() == txFromRlp.gas(),"Gas in given RLP not matching the Transaction gas!");
			BOOST_CHECK_MESSAGE(txFromFields.nonce() == txFromRlp.nonce(),"Nonce in given RLP not matching the Transaction nonce!");
			BOOST_CHECK_MESSAGE(txFromFields.receiveAddress() == txFromRlp.receiveAddress(), "Receive address in given RLP not matching the Transaction 'to' address!");
			BOOST_CHECK_MESSAGE(txFromFields.sender() == txFromRlp.sender(), "Transaction sender address in given RLP not matching the Transaction 'vrs' signature!");
			BOOST_CHECK_MESSAGE(txFromFields == txFromRlp, "However, txFromFields != txFromRlp!");
			BOOST_REQUIRE (o.count("sender") > 0);

			Address addressReaded = Address(o["sender"].get_str());
			BOOST_CHECK_MESSAGE(txFromFields.sender() == addressReaded || txFromRlp.sender() == addressReaded, "Signature address of sender does not match given sender address!");
		}
	}//for
}//doTransactionTests

} }// Namespace Close

BOOST_AUTO_TEST_SUITE(TransactionTests)

BOOST_AUTO_TEST_CASE(ttTransactionTest)
{
	dev::test::executeTests("ttTransactionTest", "/TransactionTests", dev::test::doTransactionTests);
}

BOOST_AUTO_TEST_CASE(ttWrongRLPTransaction)
{
	dev::test::executeTests("ttWrongRLPTransaction", "/TransactionTests", dev::test::doTransactionTests);
}

BOOST_AUTO_TEST_CASE(tt10mbDataField)
{
	if (test::Options::get().bigData)
	{
		auto start = chrono::steady_clock::now();

		dev::test::executeTests("tt10mbDataField", "/TransactionTests", dev::test::doTransactionTests);

		auto end = chrono::steady_clock::now();
		auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
		cnote << "test duration: " << duration.count() << " milliseconds.\n";
	}
}

BOOST_AUTO_TEST_CASE(ttCreateTest)
{
	for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
	{
		string arg = boost::unit_test::framework::master_test_suite().argv[i];
		if (arg == "--createtest")
		{
			if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
			{
				cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
				return;
			}
			try
			{
				cnote << "Populating tests...";
				json_spirit::mValue v;
				string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
				BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
				json_spirit::read_string(s, v);
				dev::test::doTransactionTests(v, true);
				writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
			}
			catch (Exception const& _e)
			{
				BOOST_ERROR("Failed transaction test with Exception: " << diagnostic_information(_e));
			}
			catch (std::exception const& _e)
			{
				BOOST_ERROR("Failed transaction test with Exception: " << _e.what());
			}
		}
	}
}

BOOST_AUTO_TEST_CASE(userDefinedFile)
{
	dev::test::userDefinedTest("--singletest", dev::test::doTransactionTests);
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>All Fields Hex: remove line<commit_after>/*
	This file is part of cpp-ethereum.

	cpp-ethereum is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	cpp-ethereum is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with cpp-ethereum.  If not, see <http://www.gnu.org/licenses/>.
*/
/** @file transaction.cpp
 * @author Dmitrii Khokhlov <winsvega@mail.ru>
 * @date 2015
 * Transaaction test functions.
 */

#include "TestHelper.h"

using namespace std;
using namespace json_spirit;
using namespace dev;
using namespace dev::eth;

namespace dev {  namespace test {

void doTransactionTests(json_spirit::mValue& _v, bool _fillin)
{
	for (auto& i: _v.get_obj())
	{
		cerr << i.first << endl;
		mObject& o = i.second.get_obj();

		if (_fillin)
		{
			BOOST_REQUIRE(o.count("transaction") > 0);
			mObject tObj = o["transaction"].get_obj();

			//Construct Rlp of the given transaction
			RLPStream rlpStream = createRLPStreamFromTransactionFields(tObj);
			o["rlp"] = "0x" + toHex(rlpStream.out());

			try
			{
				Transaction txFromFields(rlpStream.out(), CheckTransaction::Everything);
				if (!txFromFields.signature().isValid())
					BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );

				o["sender"] = toString(txFromFields.sender());
				o["transaction"] = ImportTest::makeAllFieldsHex(tObj);
			}
			catch(Exception const& _e)
			{
				//Transaction is InValid
				cnote << "Transaction Exception: " << diagnostic_information(_e);
				o.erase(o.find("transaction"));
				if (o.count("expect") > 0)
				{
					bool expectInValid = (o["expect"].get_str() == "invalid");
					if (Options::get().checkState)
							BOOST_CHECK_MESSAGE(expectInValid, "Check state: Transaction '" << i.first << "' is expected to be valid!");
						else
							BOOST_WARN_MESSAGE(expectInValid, "Check state: Transaction '" << i.first << "' is expected to be valid!");

					o.erase(o.find("expect"));
				}
			}

			//Transaction is Valid
			if (o.count("expect") > 0)
			{
				bool expectValid = (o["expect"].get_str() == "valid");
				if (Options::get().checkState)
						BOOST_CHECK_MESSAGE(expectValid, "Check state: Transaction '" << i.first << "' is expected to be invalid!");
					else
						BOOST_WARN_MESSAGE(expectValid, "Check state: Transaction '" << i.first << "' is expected to be invalid!");

				o.erase(o.find("expect"));
			}
		}
		else
		{
			BOOST_REQUIRE(o.count("rlp") > 0);
			Transaction txFromRlp;
			try
			{
				bytes stream = importByteArray(o["rlp"].get_str());
				RLP rlp(stream);
				txFromRlp = Transaction(rlp.data(), CheckTransaction::Everything);
				if (!txFromRlp.signature().isValid())
					BOOST_THROW_EXCEPTION(Exception() << errinfo_comment("transaction from RLP signature is invalid") );
			}
			catch(Exception const& _e)
			{
				cnote << i.first;
				cnote << "Transaction Exception: " << diagnostic_information(_e);
				BOOST_CHECK_MESSAGE(o.count("transaction") == 0, "A transaction object should not be defined because the RLP is invalid!");
				continue;
			}
			catch(...)
			{
				BOOST_CHECK_MESSAGE(o.count("transaction") == 0, "A transaction object should not be defined because the RLP is invalid!");
				continue;
			}

			BOOST_REQUIRE(o.count("transaction") > 0);

			mObject tObj = o["transaction"].get_obj();
			Transaction txFromFields(createRLPStreamFromTransactionFields(tObj).out(), CheckTransaction::Everything);

			//Check the fields restored from RLP to original fields
			BOOST_CHECK_MESSAGE(txFromFields.data() == txFromRlp.data(), "Data in given RLP not matching the Transaction data!");
			BOOST_CHECK_MESSAGE(txFromFields.value() == txFromRlp.value(), "Value in given RLP not matching the Transaction value!");
			BOOST_CHECK_MESSAGE(txFromFields.gasPrice() == txFromRlp.gasPrice(), "GasPrice in given RLP not matching the Transaction gasPrice!");
			BOOST_CHECK_MESSAGE(txFromFields.gas() == txFromRlp.gas(),"Gas in given RLP not matching the Transaction gas!");
			BOOST_CHECK_MESSAGE(txFromFields.nonce() == txFromRlp.nonce(),"Nonce in given RLP not matching the Transaction nonce!");
			BOOST_CHECK_MESSAGE(txFromFields.receiveAddress() == txFromRlp.receiveAddress(), "Receive address in given RLP not matching the Transaction 'to' address!");
			BOOST_CHECK_MESSAGE(txFromFields.sender() == txFromRlp.sender(), "Transaction sender address in given RLP not matching the Transaction 'vrs' signature!");
			BOOST_CHECK_MESSAGE(txFromFields == txFromRlp, "However, txFromFields != txFromRlp!");
			BOOST_REQUIRE (o.count("sender") > 0);

			Address addressReaded = Address(o["sender"].get_str());
			BOOST_CHECK_MESSAGE(txFromFields.sender() == addressReaded || txFromRlp.sender() == addressReaded, "Signature address of sender does not match given sender address!");
		}
	}//for
}//doTransactionTests

} }// Namespace Close

BOOST_AUTO_TEST_SUITE(TransactionTests)

BOOST_AUTO_TEST_CASE(ttTransactionTest)
{
	dev::test::executeTests("ttTransactionTest", "/TransactionTests", dev::test::doTransactionTests);
}

BOOST_AUTO_TEST_CASE(ttWrongRLPTransaction)
{
	dev::test::executeTests("ttWrongRLPTransaction", "/TransactionTests", dev::test::doTransactionTests);
}

BOOST_AUTO_TEST_CASE(tt10mbDataField)
{
	if (test::Options::get().bigData)
	{
		auto start = chrono::steady_clock::now();

		dev::test::executeTests("tt10mbDataField", "/TransactionTests", dev::test::doTransactionTests);

		auto end = chrono::steady_clock::now();
		auto duration(chrono::duration_cast<chrono::milliseconds>(end - start));
		cnote << "test duration: " << duration.count() << " milliseconds.\n";
	}
}

BOOST_AUTO_TEST_CASE(ttCreateTest)
{
	for (int i = 1; i < boost::unit_test::framework::master_test_suite().argc; ++i)
	{
		string arg = boost::unit_test::framework::master_test_suite().argv[i];
		if (arg == "--createtest")
		{
			if (boost::unit_test::framework::master_test_suite().argc <= i + 2)
			{
				cnote << "usage: ./testeth --createtest <PathToConstructor> <PathToDestiny>\n";
				return;
			}
			try
			{
				cnote << "Populating tests...";
				json_spirit::mValue v;
				string s = asString(dev::contents(boost::unit_test::framework::master_test_suite().argv[i + 1]));
				BOOST_REQUIRE_MESSAGE(s.length() > 0, "Content of " + (string)boost::unit_test::framework::master_test_suite().argv[i + 1] + " is empty.");
				json_spirit::read_string(s, v);
				dev::test::doTransactionTests(v, true);
				writeFile(boost::unit_test::framework::master_test_suite().argv[i + 2], asBytes(json_spirit::write_string(v, true)));
			}
			catch (Exception const& _e)
			{
				BOOST_ERROR("Failed transaction test with Exception: " << diagnostic_information(_e));
			}
			catch (std::exception const& _e)
			{
				BOOST_ERROR("Failed transaction test with Exception: " << _e.what());
			}
		}
	}
}

BOOST_AUTO_TEST_CASE(userDefinedFile)
{
	dev::test::userDefinedTest("--singletest", dev::test::doTransactionTests);
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>//===-- Language.cpp -------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include <functional>
#include <map>
#include <mutex>

#include "lldb/Target/Language.h"

#include "lldb/Host/Mutex.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Stream.h"

using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::formatters;

typedef std::unique_ptr<Language> LanguageUP;
typedef std::map<lldb::LanguageType, LanguageUP> LanguagesMap;

static LanguagesMap&
GetLanguagesMap ()
{
    static LanguagesMap *g_map = nullptr;
    static std::once_flag g_initialize;

    std::call_once(g_initialize, [] {
        g_map = new LanguagesMap(); // NOTE: INTENTIONAL LEAK due to global destructor chain
    });

    return *g_map;
}
static Mutex&
GetLanguagesMutex ()
{
    static Mutex *g_mutex = nullptr;
    static std::once_flag g_initialize;

    std::call_once(g_initialize, [] {
        g_mutex = new Mutex(); // NOTE: INTENTIONAL LEAK due to global destructor chain
    });

    return *g_mutex;
}

Language*
Language::FindPlugin (lldb::LanguageType language)
{
    Mutex::Locker locker(GetLanguagesMutex());
    LanguagesMap& map(GetLanguagesMap());
    auto iter = map.find(language), end = map.end();
    if (iter != end)
        return iter->second.get();

    Language *language_ptr = nullptr;
    LanguageCreateInstance create_callback;

    for (uint32_t idx = 0;
         (create_callback = PluginManager::GetLanguageCreateCallbackAtIndex(idx)) != nullptr;
         ++idx)
    {
        language_ptr = create_callback(language);

        if (language_ptr)
        {
            map[language] = std::unique_ptr<Language>(language_ptr);
            return language_ptr;
        }
    }

    return nullptr;
}

void
Language::ForEach (std::function<bool(Language*)> callback)
{
    Mutex::Locker locker(GetLanguagesMutex());
    LanguagesMap& map(GetLanguagesMap());
    for (const auto& entry : map)
    {
        if (!callback(entry.second.get()))
            break;
    }
}

bool
Language::IsTopLevelFunction (Function& function)
{
    return false;
}

lldb::TypeCategoryImplSP
Language::GetFormatters ()
{
    return nullptr;
}

HardcodedFormatters::HardcodedFormatFinder
Language::GetHardcodedFormats ()
{
    return {};
}

HardcodedFormatters::HardcodedSummaryFinder
Language::GetHardcodedSummaries ()
{
    return {};
}

HardcodedFormatters::HardcodedSyntheticFinder
Language::GetHardcodedSynthetics ()
{
    return {};
}

HardcodedFormatters::HardcodedValidatorFinder
Language::GetHardcodedValidators ()
{
    return {};
}

std::vector<ConstString>
Language::GetPossibleFormattersMatches (ValueObject& valobj, lldb::DynamicValueType use_dynamic)
{
    return {};
}

lldb_private::formatters::StringPrinter::EscapingHelper
Language::GetStringPrinterEscapingHelper (lldb_private::formatters::StringPrinter::GetPrintableElementType elem_type)
{
    return StringPrinter::GetDefaultEscapingHelper(elem_type);
}

struct language_name_pair {
    const char *name;
    LanguageType type;
};

struct language_name_pair language_names[] =
{
    // To allow GetNameForLanguageType to be a simple array lookup, the first
    // part of this array must follow enum LanguageType exactly.
    {   "unknown",          eLanguageTypeUnknown        },
    {   "c89",              eLanguageTypeC89            },
    {   "c",                eLanguageTypeC              },
    {   "ada83",            eLanguageTypeAda83          },
    {   "c++",              eLanguageTypeC_plus_plus    },
    {   "cobol74",          eLanguageTypeCobol74        },
    {   "cobol85",          eLanguageTypeCobol85        },
    {   "fortran77",        eLanguageTypeFortran77      },
    {   "fortran90",        eLanguageTypeFortran90      },
    {   "pascal83",         eLanguageTypePascal83       },
    {   "modula2",          eLanguageTypeModula2        },
    {   "java",             eLanguageTypeJava           },
    {   "c99",              eLanguageTypeC99            },
    {   "ada95",            eLanguageTypeAda95          },
    {   "fortran95",        eLanguageTypeFortran95      },
    {   "pli",              eLanguageTypePLI            },
    {   "objective-c",      eLanguageTypeObjC           },
    {   "objective-c++",    eLanguageTypeObjC_plus_plus },
    {   "upc",              eLanguageTypeUPC            },
    {   "d",                eLanguageTypeD              },
    {   "python",           eLanguageTypePython         },
    {   "opencl",           eLanguageTypeOpenCL         },
    {   "go",               eLanguageTypeGo             },
    {   "modula3",          eLanguageTypeModula3        },
    {   "haskell",          eLanguageTypeHaskell        },
    {   "c++03",            eLanguageTypeC_plus_plus_03 },
    {   "c++11",            eLanguageTypeC_plus_plus_11 },
    {   "ocaml",            eLanguageTypeOCaml          },
    {   "rust",             eLanguageTypeRust           },
    {   "c11",              eLanguageTypeC11            },
    {   "swift",            eLanguageTypeSwift          },
    {   "julia",            eLanguageTypeJulia          },
    {   "dylan",            eLanguageTypeDylan          },
    {   "c++14",            eLanguageTypeC_plus_plus_14 },
    {   "fortran03",        eLanguageTypeFortran03      },
    {   "fortran08",        eLanguageTypeFortran08      },
    // Vendor Extensions
    {   "mipsassem",        eLanguageTypeMipsAssembler  },
    {   "renderscript",     eLanguageTypeExtRenderScript},
    // Now synonyms, in arbitrary order
    {   "objc",             eLanguageTypeObjC           },
    {   "objc++",           eLanguageTypeObjC_plus_plus },
    {   "pascal",           eLanguageTypePascal83       }
};

static uint32_t num_languages = sizeof(language_names) / sizeof (struct language_name_pair);

LanguageType
Language::GetLanguageTypeFromString (const char *string)
{
    for (uint32_t i = 0; i < num_languages; i++)
    {
        if (strcasecmp (language_names[i].name, string) == 0)
            return (LanguageType) language_names[i].type;
    }
    return eLanguageTypeUnknown;
}

const char *
Language::GetNameForLanguageType (LanguageType language)
{
    if (language < num_languages)
        return language_names[language].name;
    else
        return language_names[eLanguageTypeUnknown].name;
}

void
Language::PrintAllLanguages (Stream &s, const char *prefix, const char *suffix)
{
    for (uint32_t i = 1; i < num_languages; i++)
    {
        s.Printf("%s%s%s", prefix, language_names[i].name, suffix);
    }
}

void
Language::ForAllLanguages (std::function<bool(lldb::LanguageType)> callback)
{
    for (uint32_t i = 1; i < num_languages; i++)
    {
        if (!callback(language_names[i].type))
            break;
    }
}

bool
Language::LanguageIsCPlusPlus (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypeC_plus_plus:
        case eLanguageTypeC_plus_plus_03:
        case eLanguageTypeC_plus_plus_11:
        case eLanguageTypeC_plus_plus_14:
            return true;
        default:
            return false;
    }
}

bool
Language::LanguageIsObjC (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypeObjC:
        case eLanguageTypeObjC_plus_plus:
            return true;
        default:
            return false;
    }
}

bool
Language::LanguageIsC (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypeC:
        case eLanguageTypeC89:
        case eLanguageTypeC99:
        case eLanguageTypeC11:
            return true;
        default:
            return false;
    }
}

bool
Language::LanguageIsPascal (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypePascal83:
            return true;
        default:
            return false;
    }
}

LanguageType
Language::GetPrimaryLanguage (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypeC_plus_plus:
        case eLanguageTypeC_plus_plus_03:
        case eLanguageTypeC_plus_plus_11:
        case eLanguageTypeC_plus_plus_14:
            return eLanguageTypeC_plus_plus;
        case eLanguageTypeC:
        case eLanguageTypeC89:
        case eLanguageTypeC99:
        case eLanguageTypeC11:
            return eLanguageTypeC;
        case eLanguageTypeObjC:
        case eLanguageTypeObjC_plus_plus:
            return eLanguageTypeObjC;
        case eLanguageTypePascal83:
        case eLanguageTypeCobol74:
        case eLanguageTypeCobol85:
        case eLanguageTypeFortran77:
        case eLanguageTypeFortran90:
        case eLanguageTypeFortran95:
        case eLanguageTypeFortran03:
        case eLanguageTypeFortran08:
        case eLanguageTypeAda83:
        case eLanguageTypeAda95:
        case eLanguageTypeModula2:
        case eLanguageTypeJava:
        case eLanguageTypePLI:
        case eLanguageTypeUPC:
        case eLanguageTypeD:
        case eLanguageTypePython:
        case eLanguageTypeOpenCL:
        case eLanguageTypeGo:
        case eLanguageTypeModula3:
        case eLanguageTypeHaskell:
        case eLanguageTypeOCaml:
        case eLanguageTypeRust:
        case eLanguageTypeSwift:
        case eLanguageTypeJulia:
        case eLanguageTypeDylan:
        case eLanguageTypeMipsAssembler:
        case eLanguageTypeExtRenderScript:
        case eLanguageTypeUnknown:
        default:
            return language;
    }
}

void
Language::GetLanguagesSupportingTypeSystems (std::set<lldb::LanguageType> &languages,
                                             std::set<lldb::LanguageType> &languages_for_expressions)
{
    uint32_t idx = 0;

    while (TypeSystemEnumerateSupportedLanguages enumerate = PluginManager::GetTypeSystemEnumerateSupportedLanguagesCallbackAtIndex(idx++))
    {
        (*enumerate)(languages, languages_for_expressions);
    }
}

void
Language::GetLanguagesSupportingREPLs (std::set<lldb::LanguageType> &languages)
{
    uint32_t idx = 0;

    while (REPLEnumerateSupportedLanguages enumerate = PluginManager::GetREPLEnumerateSupportedLanguagesCallbackAtIndex(idx++))
    {
        (*enumerate)(languages);
    }
}

std::unique_ptr<Language::TypeScavenger>
Language::GetTypeScavenger ()
{
    return nullptr;
}

size_t
Language::TypeScavenger::Find (ExecutionContextScope *exe_scope,
                               const char *key,
                               ResultSet &results,
                               bool append)
{
    if (!exe_scope || !exe_scope->CalculateTarget().get())
        return false;

    if (!key || !key[0])
        return false;

    if (!append)
        results.clear();

    size_t old_size = results.size();

    if (this->Find_Impl(exe_scope, key, results))
        return results.size() - old_size;
    return 0;
}

bool
Language::GetFormatterPrefixSuffix (ValueObject& valobj, ConstString type_hint,
                                    std::string& prefix, std::string& suffix)
{
    return false;
}

DumpValueObjectOptions::DeclPrintingHelper
Language::GetDeclPrintingHelper ()
{
    return nullptr;
}

LazyBool
Language::IsLogicalTrue (ValueObject& valobj,
                         Error& error)
{
    return eLazyBoolCalculate;
}

bool
Language::IsNilReference (ValueObject& valobj)
{
    return false;
}

bool
Language::IsUninitializedReference (ValueObject& valobj)
{
    return false;
}

bool
Language::GetFunctionDisplayName (const SymbolContext *sc,
                                  const ExecutionContext *exe_ctx,
                                  FunctionNameRepresentation representation,
                                  Stream& s)
{
    return false;
}

void
Language::GetExceptionResolverDescription(bool catch_on, bool throw_on, Stream &s)
{
    GetDefaultExceptionResolverDescription(catch_on, throw_on, s);
}

void
Language::GetDefaultExceptionResolverDescription(bool catch_on, bool throw_on, Stream &s)
{
       s.Printf ("Exception breakpoint (catch: %s throw: %s)",
                 catch_on ? "on" : "off",
                 throw_on ? "on" : "off");
}
//----------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------
Language::Language()
{
}

//----------------------------------------------------------------------
// Destructor
//----------------------------------------------------------------------
Language::~Language()
{
}
<commit_msg>Fix formatting for last commit.<commit_after>//===-- Language.cpp -------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include <functional>
#include <map>
#include <mutex>

#include "lldb/Target/Language.h"

#include "lldb/Host/Mutex.h"
#include "lldb/Core/PluginManager.h"
#include "lldb/Core/Stream.h"

using namespace lldb;
using namespace lldb_private;
using namespace lldb_private::formatters;

typedef std::unique_ptr<Language> LanguageUP;
typedef std::map<lldb::LanguageType, LanguageUP> LanguagesMap;

static LanguagesMap&
GetLanguagesMap ()
{
    static LanguagesMap *g_map = nullptr;
    static std::once_flag g_initialize;

    std::call_once(g_initialize, [] {
        g_map = new LanguagesMap(); // NOTE: INTENTIONAL LEAK due to global destructor chain
    });

    return *g_map;
}
static Mutex&
GetLanguagesMutex ()
{
    static Mutex *g_mutex = nullptr;
    static std::once_flag g_initialize;

    std::call_once(g_initialize, [] {
        g_mutex = new Mutex(); // NOTE: INTENTIONAL LEAK due to global destructor chain
    });

    return *g_mutex;
}

Language*
Language::FindPlugin (lldb::LanguageType language)
{
    Mutex::Locker locker(GetLanguagesMutex());
    LanguagesMap& map(GetLanguagesMap());
    auto iter = map.find(language), end = map.end();
    if (iter != end)
        return iter->second.get();

    Language *language_ptr = nullptr;
    LanguageCreateInstance create_callback;

    for (uint32_t idx = 0;
         (create_callback = PluginManager::GetLanguageCreateCallbackAtIndex(idx)) != nullptr;
         ++idx)
    {
        language_ptr = create_callback(language);

        if (language_ptr)
        {
            map[language] = std::unique_ptr<Language>(language_ptr);
            return language_ptr;
        }
    }

    return nullptr;
}

void
Language::ForEach (std::function<bool(Language*)> callback)
{
    Mutex::Locker locker(GetLanguagesMutex());
    LanguagesMap& map(GetLanguagesMap());
    for (const auto& entry : map)
    {
        if (!callback(entry.second.get()))
            break;
    }
}

bool
Language::IsTopLevelFunction (Function& function)
{
    return false;
}

lldb::TypeCategoryImplSP
Language::GetFormatters ()
{
    return nullptr;
}

HardcodedFormatters::HardcodedFormatFinder
Language::GetHardcodedFormats ()
{
    return {};
}

HardcodedFormatters::HardcodedSummaryFinder
Language::GetHardcodedSummaries ()
{
    return {};
}

HardcodedFormatters::HardcodedSyntheticFinder
Language::GetHardcodedSynthetics ()
{
    return {};
}

HardcodedFormatters::HardcodedValidatorFinder
Language::GetHardcodedValidators ()
{
    return {};
}

std::vector<ConstString>
Language::GetPossibleFormattersMatches (ValueObject& valobj, lldb::DynamicValueType use_dynamic)
{
    return {};
}

lldb_private::formatters::StringPrinter::EscapingHelper
Language::GetStringPrinterEscapingHelper (lldb_private::formatters::StringPrinter::GetPrintableElementType elem_type)
{
    return StringPrinter::GetDefaultEscapingHelper(elem_type);
}

struct language_name_pair {
    const char *name;
    LanguageType type;
};

struct language_name_pair language_names[] =
{
    // To allow GetNameForLanguageType to be a simple array lookup, the first
    // part of this array must follow enum LanguageType exactly.
    {   "unknown",          eLanguageTypeUnknown        },
    {   "c89",              eLanguageTypeC89            },
    {   "c",                eLanguageTypeC              },
    {   "ada83",            eLanguageTypeAda83          },
    {   "c++",              eLanguageTypeC_plus_plus    },
    {   "cobol74",          eLanguageTypeCobol74        },
    {   "cobol85",          eLanguageTypeCobol85        },
    {   "fortran77",        eLanguageTypeFortran77      },
    {   "fortran90",        eLanguageTypeFortran90      },
    {   "pascal83",         eLanguageTypePascal83       },
    {   "modula2",          eLanguageTypeModula2        },
    {   "java",             eLanguageTypeJava           },
    {   "c99",              eLanguageTypeC99            },
    {   "ada95",            eLanguageTypeAda95          },
    {   "fortran95",        eLanguageTypeFortran95      },
    {   "pli",              eLanguageTypePLI            },
    {   "objective-c",      eLanguageTypeObjC           },
    {   "objective-c++",    eLanguageTypeObjC_plus_plus },
    {   "upc",              eLanguageTypeUPC            },
    {   "d",                eLanguageTypeD              },
    {   "python",           eLanguageTypePython         },
    {   "opencl",           eLanguageTypeOpenCL         },
    {   "go",               eLanguageTypeGo             },
    {   "modula3",          eLanguageTypeModula3        },
    {   "haskell",          eLanguageTypeHaskell        },
    {   "c++03",            eLanguageTypeC_plus_plus_03 },
    {   "c++11",            eLanguageTypeC_plus_plus_11 },
    {   "ocaml",            eLanguageTypeOCaml          },
    {   "rust",             eLanguageTypeRust           },
    {   "c11",              eLanguageTypeC11            },
    {   "swift",            eLanguageTypeSwift          },
    {   "julia",            eLanguageTypeJulia          },
    {   "dylan",            eLanguageTypeDylan          },
    {   "c++14",            eLanguageTypeC_plus_plus_14 },
    {   "fortran03",        eLanguageTypeFortran03      },
    {   "fortran08",        eLanguageTypeFortran08      },
    // Vendor Extensions
    {   "mipsassem",        eLanguageTypeMipsAssembler  },
    {   "renderscript",     eLanguageTypeExtRenderScript},
    // Now synonyms, in arbitrary order
    {   "objc",             eLanguageTypeObjC           },
    {   "objc++",           eLanguageTypeObjC_plus_plus },
    {   "pascal",           eLanguageTypePascal83       }
};

static uint32_t num_languages = sizeof(language_names) / sizeof (struct language_name_pair);

LanguageType
Language::GetLanguageTypeFromString (const char *string)
{
    for (uint32_t i = 0; i < num_languages; i++)
    {
        if (strcasecmp (language_names[i].name, string) == 0)
            return (LanguageType) language_names[i].type;
    }
    return eLanguageTypeUnknown;
}

const char *
Language::GetNameForLanguageType (LanguageType language)
{
    if (language < num_languages)
        return language_names[language].name;
    else
        return language_names[eLanguageTypeUnknown].name;
}

void
Language::PrintAllLanguages (Stream &s, const char *prefix, const char *suffix)
{
    for (uint32_t i = 1; i < num_languages; i++)
    {
        s.Printf("%s%s%s", prefix, language_names[i].name, suffix);
    }
}

void
Language::ForAllLanguages (std::function<bool(lldb::LanguageType)> callback)
{
    for (uint32_t i = 1; i < num_languages; i++)
    {
        if (!callback(language_names[i].type))
            break;
    }
}

bool
Language::LanguageIsCPlusPlus (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypeC_plus_plus:
        case eLanguageTypeC_plus_plus_03:
        case eLanguageTypeC_plus_plus_11:
        case eLanguageTypeC_plus_plus_14:
            return true;
        default:
            return false;
    }
}

bool
Language::LanguageIsObjC (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypeObjC:
        case eLanguageTypeObjC_plus_plus:
            return true;
        default:
            return false;
    }
}

bool
Language::LanguageIsC (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypeC:
        case eLanguageTypeC89:
        case eLanguageTypeC99:
        case eLanguageTypeC11:
            return true;
        default:
            return false;
    }
}

bool
Language::LanguageIsPascal (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypePascal83:
            return true;
        default:
            return false;
    }
}

LanguageType
Language::GetPrimaryLanguage (LanguageType language)
{
    switch (language)
    {
        case eLanguageTypeC_plus_plus:
        case eLanguageTypeC_plus_plus_03:
        case eLanguageTypeC_plus_plus_11:
        case eLanguageTypeC_plus_plus_14:
            return eLanguageTypeC_plus_plus;
        case eLanguageTypeC:
        case eLanguageTypeC89:
        case eLanguageTypeC99:
        case eLanguageTypeC11:
            return eLanguageTypeC;
        case eLanguageTypeObjC:
        case eLanguageTypeObjC_plus_plus:
            return eLanguageTypeObjC;
        case eLanguageTypePascal83:
        case eLanguageTypeCobol74:
        case eLanguageTypeCobol85:
        case eLanguageTypeFortran77:
        case eLanguageTypeFortran90:
        case eLanguageTypeFortran95:
        case eLanguageTypeFortran03:
        case eLanguageTypeFortran08:
        case eLanguageTypeAda83:
        case eLanguageTypeAda95:
        case eLanguageTypeModula2:
        case eLanguageTypeJava:
        case eLanguageTypePLI:
        case eLanguageTypeUPC:
        case eLanguageTypeD:
        case eLanguageTypePython:
        case eLanguageTypeOpenCL:
        case eLanguageTypeGo:
        case eLanguageTypeModula3:
        case eLanguageTypeHaskell:
        case eLanguageTypeOCaml:
        case eLanguageTypeRust:
        case eLanguageTypeSwift:
        case eLanguageTypeJulia:
        case eLanguageTypeDylan:
        case eLanguageTypeMipsAssembler:
        case eLanguageTypeExtRenderScript:
        case eLanguageTypeUnknown:
        default:
            return language;
    }
}

void
Language::GetLanguagesSupportingTypeSystems (std::set<lldb::LanguageType> &languages,
                                             std::set<lldb::LanguageType> &languages_for_expressions)
{
    uint32_t idx = 0;

    while (TypeSystemEnumerateSupportedLanguages enumerate = PluginManager::GetTypeSystemEnumerateSupportedLanguagesCallbackAtIndex(idx++))
    {
        (*enumerate)(languages, languages_for_expressions);
    }
}

void
Language::GetLanguagesSupportingREPLs (std::set<lldb::LanguageType> &languages)
{
    uint32_t idx = 0;

    while (REPLEnumerateSupportedLanguages enumerate = PluginManager::GetREPLEnumerateSupportedLanguagesCallbackAtIndex(idx++))
    {
        (*enumerate)(languages);
    }
}

std::unique_ptr<Language::TypeScavenger>
Language::GetTypeScavenger ()
{
    return nullptr;
}

size_t
Language::TypeScavenger::Find (ExecutionContextScope *exe_scope,
                               const char *key,
                               ResultSet &results,
                               bool append)
{
    if (!exe_scope || !exe_scope->CalculateTarget().get())
        return false;

    if (!key || !key[0])
        return false;

    if (!append)
        results.clear();

    size_t old_size = results.size();

    if (this->Find_Impl(exe_scope, key, results))
        return results.size() - old_size;
    return 0;
}

bool
Language::GetFormatterPrefixSuffix (ValueObject& valobj, ConstString type_hint,
                                    std::string& prefix, std::string& suffix)
{
    return false;
}

DumpValueObjectOptions::DeclPrintingHelper
Language::GetDeclPrintingHelper ()
{
    return nullptr;
}

LazyBool
Language::IsLogicalTrue (ValueObject& valobj,
                         Error& error)
{
    return eLazyBoolCalculate;
}

bool
Language::IsNilReference (ValueObject& valobj)
{
    return false;
}

bool
Language::IsUninitializedReference (ValueObject& valobj)
{
    return false;
}

bool
Language::GetFunctionDisplayName (const SymbolContext *sc,
                                  const ExecutionContext *exe_ctx,
                                  FunctionNameRepresentation representation,
                                  Stream& s)
{
    return false;
}

void
Language::GetExceptionResolverDescription(bool catch_on, bool throw_on, Stream &s)
{
    GetDefaultExceptionResolverDescription(catch_on, throw_on, s);
}

void
Language::GetDefaultExceptionResolverDescription(bool catch_on, bool throw_on, Stream &s)
{
     s.Printf ("Exception breakpoint (catch: %s throw: %s)",
               catch_on ? "on" : "off",
               throw_on ? "on" : "off");
}
//----------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------
Language::Language()
{
}

//----------------------------------------------------------------------
// Destructor
//----------------------------------------------------------------------
Language::~Language()
{
}
<|endoftext|>


<commit_before><commit_msg>io: use new TMemFile constructor in TBufferMerger::Merge()<commit_after><|endoftext|>


<commit_before>#include "GHIElectronics_TinyCLR_Devices.h"
#include "GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h"

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::SetParallelConfiguration___BOOLEAN__U4__U4__GHIElectronicsTinyCLRDevicesDisplayDisplayDataFormat__BOOLEAN__BOOLEAN__BOOLEAN__U4__BOOLEAN__U4__U4__U4__BOOLEAN__U4__U4__U4(const TinyCLR_Interop_MethodData md) {
    TinyCLR_Display_ParallelConfiguration config;

    uint32_t width = TinyCLR_Interop_GetArguments(md, 1).Data.Numeric->U4;
    uint32_t height = TinyCLR_Interop_GetArguments(md, 2).Data.Numeric->U4;
    auto type = (TinyCLR_Display_DataFormat)TinyCLR_Interop_GetArguments(md, 3).Data.Numeric->U4;

    config.DataEnableIsFixed = TinyCLR_Interop_GetArguments(md, 4).Data.Numeric->U1 != 0;
    config.DataEnablePolarity = TinyCLR_Interop_GetArguments(md, 5).Data.Numeric->U1 != 0;
    config.PixelPolarity = TinyCLR_Interop_GetArguments(md, 6).Data.Numeric->U1 != 0;
    config.PixelClockRate = TinyCLR_Interop_GetArguments(md, 7).Data.Numeric->U4;
    config.HorizontalSyncPolarity = TinyCLR_Interop_GetArguments(md, 8).Data.Numeric->U1 != 0;
    config.HorizontalSyncPulseWidth = TinyCLR_Interop_GetArguments(md, 9).Data.Numeric->U4;
    config.HorizontalFrontPorch = TinyCLR_Interop_GetArguments(md, 10).Data.Numeric->U4;
    config.HorizontalBackPorch = TinyCLR_Interop_GetArguments(md, 11).Data.Numeric->U4;
    config.VerticalSyncPolarity = TinyCLR_Interop_GetArguments(md, 12).Data.Numeric->U1 != 0;
    config.VerticalSyncPulseWidth = TinyCLR_Interop_GetArguments(md, 13).Data.Numeric->U4;
    config.VerticalFrontPorch = TinyCLR_Interop_GetArguments(md, 14).Data.Numeric->U4;
    config.VerticalBackPorch = TinyCLR_Interop_GetArguments(md, 15).Data.Numeric->U4;

    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    auto res = provider->Acquire(provider, controller);

    TinyCLR_Interop_ClrValue ret = TinyCLR_Interop_GetReturn(md);

    if (res == TinyCLR_Result::Success) {
        res = provider->SetConfiguration(provider, controller, type, width, height, &config);

        if (res == TinyCLR_Result::Success) {
            res = provider->Enable(provider, controller);

            ret.Data.Numeric->Boolean = (res == TinyCLR_Result::Success) ? true : false;
        }
        else {
            ret.Data.Numeric->Boolean = false;
        }
    }
    else {
        ret.Data.Numeric->Boolean = false;
    }

    return TinyCLR_Result::Success;
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::SetSpiConfiguration___BOOLEAN__U4__U4__GHIElectronicsTinyCLRDevicesDisplayDisplayDataFormat__STRING(const TinyCLR_Interop_MethodData md) {
    TinyCLR_Display_SpiConfiguration config;

    uint32_t width = TinyCLR_Interop_GetArguments(md, 1).Data.Numeric->U4;
    uint32_t height = TinyCLR_Interop_GetArguments(md, 2).Data.Numeric->U4;
    auto type = (TinyCLR_Display_DataFormat)TinyCLR_Interop_GetArguments(md, 3).Data.Numeric->U4;

    config.SpiSelector = TinyCLR_Interop_GetArguments(md, 4).Data.String.Data;

    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    auto res = provider->Acquire(provider, controller);

    TinyCLR_Interop_ClrValue ret = TinyCLR_Interop_GetReturn(md);

    if (res == TinyCLR_Result::Success) {
        res = provider->SetConfiguration(provider, controller, type, width, height, &config);

        if (res == TinyCLR_Result::Success) {
            res = provider->Enable(provider, controller);

            ret.Data.Numeric->Boolean = (res == TinyCLR_Result::Success) ? true : false;
        }
        else {
            ret.Data.Numeric->Boolean = false;
        }
    }
    else {
        ret.Data.Numeric->Boolean = false;
    }

    return TinyCLR_Result::Success;
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::get_Interface___GHIElectronicsTinyCLRDevicesDisplayDisplayInterface(const TinyCLR_Interop_MethodData md) {
    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    TinyCLR_Display_InterfaceType type;

    const TinyCLR_Display_DataFormat* supportedDataFormats;

    size_t supportedDataFormatCount;

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    auto res = provider->GetCapabilities(provider, controller, type, supportedDataFormats, supportedDataFormatCount);

    auto ret = TinyCLR_Interop_GetReturn(md);

    ret.Data.Numeric->I4 = (int32_t)type;

    return res;
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::get_SupportedDataFormats___SZARRAY_GHIElectronicsTinyCLRDevicesDisplayDisplayDataFormat(const TinyCLR_Interop_MethodData md) {
    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    TinyCLR_Display_InterfaceType type;

    const TinyCLR_Display_DataFormat* supportedDataFormats;

    size_t supportedDataFormatCount;

    auto ret = TinyCLR_Interop_GetReturn(md);

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    auto res = provider->GetCapabilities(provider, controller, type, supportedDataFormats, supportedDataFormatCount);

    auto interop = (const TinyCLR_Interop_Provider*)md.ApiProvider.FindDefault(&md.ApiProvider, TinyCLR_Api_Type::InteropProvider);

    const TinyCLR_Interop_ClrObject* self;

    TinyCLR_Interop_ClrValue arr;
    TinyCLR_Interop_ClrTypeId idx;

    if (res == TinyCLR_Result::Success) {
        interop->GetThisObject(interop, md.Stack, self);

        interop->FindType(interop, "GHIElectronics.TinyCLR.Devices", "GHIElectronics.TinyCLR.Devices.Display", "DisplayDataFormat", idx);

        auto top = TinyCLR_Interop_GetReturn(md);

        interop->GetField(interop, top.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_DisplayControllerSettings::FIELD___DataFormat__BackingField___GHIElectronicsTinyCLRDevicesDisplayDisplayDataFormat, arr);

        interop->CreateArray(interop, supportedDataFormatCount, idx, arr);

        auto p = (TinyCLR_Display_DataFormat*)(arr.Data.SzArray.Data);

        for (auto i = 0; i < supportedDataFormatCount; i++)
            p[i] = supportedDataFormats[i];
    }

    return res;
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::WriteString___VOID__STRING(const TinyCLR_Interop_MethodData md) {
    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    auto data = TinyCLR_Interop_GetArguments(md, 1).Data.String;

    auto stringType = TinyCLR_Interop_GetArguments(md, 1).Data.String;

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    return provider->WriteString(provider, controller, stringType.Data, stringType.Length);
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::GetControllerCount___STATIC___I4__I(const TinyCLR_Interop_MethodData md) {
    auto arg = TinyCLR_Interop_GetArguments(md, 0);

    auto ret = TinyCLR_Interop_GetReturn(md);

    auto provider = (const TinyCLR_Display_Provider*)(arg.Data.Numeric->I4);

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    int32_t count;

    if (provider->GetControllerCount(provider, controller, count) == TinyCLR_Result::Success) {
        ret.Data.Numeric->I4 = count;

        return TinyCLR_Result::Success;
    }

    return TinyCLR_Result::InvalidOperation;
}<commit_msg>GetControllerCount has no controller param<commit_after>#include "GHIElectronics_TinyCLR_Devices.h"
#include "GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Interop.h"

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::SetParallelConfiguration___BOOLEAN__U4__U4__GHIElectronicsTinyCLRDevicesDisplayDisplayDataFormat__BOOLEAN__BOOLEAN__BOOLEAN__U4__BOOLEAN__U4__U4__U4__BOOLEAN__U4__U4__U4(const TinyCLR_Interop_MethodData md) {
    TinyCLR_Display_ParallelConfiguration config;

    uint32_t width = TinyCLR_Interop_GetArguments(md, 1).Data.Numeric->U4;
    uint32_t height = TinyCLR_Interop_GetArguments(md, 2).Data.Numeric->U4;
    auto type = (TinyCLR_Display_DataFormat)TinyCLR_Interop_GetArguments(md, 3).Data.Numeric->U4;

    config.DataEnableIsFixed = TinyCLR_Interop_GetArguments(md, 4).Data.Numeric->U1 != 0;
    config.DataEnablePolarity = TinyCLR_Interop_GetArguments(md, 5).Data.Numeric->U1 != 0;
    config.PixelPolarity = TinyCLR_Interop_GetArguments(md, 6).Data.Numeric->U1 != 0;
    config.PixelClockRate = TinyCLR_Interop_GetArguments(md, 7).Data.Numeric->U4;
    config.HorizontalSyncPolarity = TinyCLR_Interop_GetArguments(md, 8).Data.Numeric->U1 != 0;
    config.HorizontalSyncPulseWidth = TinyCLR_Interop_GetArguments(md, 9).Data.Numeric->U4;
    config.HorizontalFrontPorch = TinyCLR_Interop_GetArguments(md, 10).Data.Numeric->U4;
    config.HorizontalBackPorch = TinyCLR_Interop_GetArguments(md, 11).Data.Numeric->U4;
    config.VerticalSyncPolarity = TinyCLR_Interop_GetArguments(md, 12).Data.Numeric->U1 != 0;
    config.VerticalSyncPulseWidth = TinyCLR_Interop_GetArguments(md, 13).Data.Numeric->U4;
    config.VerticalFrontPorch = TinyCLR_Interop_GetArguments(md, 14).Data.Numeric->U4;
    config.VerticalBackPorch = TinyCLR_Interop_GetArguments(md, 15).Data.Numeric->U4;

    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    auto res = provider->Acquire(provider, controller);

    TinyCLR_Interop_ClrValue ret = TinyCLR_Interop_GetReturn(md);

    if (res == TinyCLR_Result::Success) {
        res = provider->SetConfiguration(provider, controller, type, width, height, &config);

        if (res == TinyCLR_Result::Success) {
            res = provider->Enable(provider, controller);

            ret.Data.Numeric->Boolean = (res == TinyCLR_Result::Success) ? true : false;
        }
        else {
            ret.Data.Numeric->Boolean = false;
        }
    }
    else {
        ret.Data.Numeric->Boolean = false;
    }

    return TinyCLR_Result::Success;
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::SetSpiConfiguration___BOOLEAN__U4__U4__GHIElectronicsTinyCLRDevicesDisplayDisplayDataFormat__STRING(const TinyCLR_Interop_MethodData md) {
    TinyCLR_Display_SpiConfiguration config;

    uint32_t width = TinyCLR_Interop_GetArguments(md, 1).Data.Numeric->U4;
    uint32_t height = TinyCLR_Interop_GetArguments(md, 2).Data.Numeric->U4;
    auto type = (TinyCLR_Display_DataFormat)TinyCLR_Interop_GetArguments(md, 3).Data.Numeric->U4;

    config.SpiSelector = TinyCLR_Interop_GetArguments(md, 4).Data.String.Data;

    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    auto res = provider->Acquire(provider, controller);

    TinyCLR_Interop_ClrValue ret = TinyCLR_Interop_GetReturn(md);

    if (res == TinyCLR_Result::Success) {
        res = provider->SetConfiguration(provider, controller, type, width, height, &config);

        if (res == TinyCLR_Result::Success) {
            res = provider->Enable(provider, controller);

            ret.Data.Numeric->Boolean = (res == TinyCLR_Result::Success) ? true : false;
        }
        else {
            ret.Data.Numeric->Boolean = false;
        }
    }
    else {
        ret.Data.Numeric->Boolean = false;
    }

    return TinyCLR_Result::Success;
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::get_Interface___GHIElectronicsTinyCLRDevicesDisplayDisplayInterface(const TinyCLR_Interop_MethodData md) {
    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    TinyCLR_Display_InterfaceType type;

    const TinyCLR_Display_DataFormat* supportedDataFormats;

    size_t supportedDataFormatCount;

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    auto res = provider->GetCapabilities(provider, controller, type, supportedDataFormats, supportedDataFormatCount);

    auto ret = TinyCLR_Interop_GetReturn(md);

    ret.Data.Numeric->I4 = (int32_t)type;

    return res;
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::get_SupportedDataFormats___SZARRAY_GHIElectronicsTinyCLRDevicesDisplayDisplayDataFormat(const TinyCLR_Interop_MethodData md) {
    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    TinyCLR_Display_InterfaceType type;

    const TinyCLR_Display_DataFormat* supportedDataFormats;

    size_t supportedDataFormatCount;

    auto ret = TinyCLR_Interop_GetReturn(md);

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    auto res = provider->GetCapabilities(provider, controller, type, supportedDataFormats, supportedDataFormatCount);

    auto interop = (const TinyCLR_Interop_Provider*)md.ApiProvider.FindDefault(&md.ApiProvider, TinyCLR_Api_Type::InteropProvider);

    const TinyCLR_Interop_ClrObject* self;

    TinyCLR_Interop_ClrValue arr;
    TinyCLR_Interop_ClrTypeId idx;

    if (res == TinyCLR_Result::Success) {
        interop->GetThisObject(interop, md.Stack, self);

        interop->FindType(interop, "GHIElectronics.TinyCLR.Devices", "GHIElectronics.TinyCLR.Devices.Display", "DisplayDataFormat", idx);

        auto top = TinyCLR_Interop_GetReturn(md);

        interop->GetField(interop, top.Object, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_DisplayControllerSettings::FIELD___DataFormat__BackingField___GHIElectronicsTinyCLRDevicesDisplayDisplayDataFormat, arr);

        interop->CreateArray(interop, supportedDataFormatCount, idx, arr);

        auto p = (TinyCLR_Display_DataFormat*)(arr.Data.SzArray.Data);

        for (auto i = 0; i < supportedDataFormatCount; i++)
            p[i] = supportedDataFormats[i];
    }

    return res;
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::WriteString___VOID__STRING(const TinyCLR_Interop_MethodData md) {
    auto provider = (const TinyCLR_Display_Provider*)TinyCLR_Interop_GetProvider(md, FIELD___nativeProvider___I);

    auto data = TinyCLR_Interop_GetArguments(md, 1).Data.String;

    auto stringType = TinyCLR_Interop_GetArguments(md, 1).Data.String;

    auto controller = TinyCLR_Interop_GetFieldInMethodData(md, Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::FIELD___idx___I).Data.Numeric->I;

    return provider->WriteString(provider, controller, stringType.Data, stringType.Length);
}

TinyCLR_Result Interop_GHIElectronics_TinyCLR_Devices_GHIElectronics_TinyCLR_Devices_Display_Provider_DefaultDisplayControllerProvider::GetControllerCount___STATIC___I4__I(const TinyCLR_Interop_MethodData md) {
    auto arg = TinyCLR_Interop_GetArguments(md, 0);

    auto ret = TinyCLR_Interop_GetReturn(md);

    auto provider = (const TinyCLR_Display_Provider*)(arg.Data.Numeric->I4);

    int32_t count;

    if (provider->GetControllerCount(provider, count) == TinyCLR_Result::Success) {
        ret.Data.Numeric->I4 = count;

        return TinyCLR_Result::Success;
    }

    return TinyCLR_Result::InvalidOperation;
}<|endoftext|>


<commit_before>#include <cstring>

#include <iostream>
#include <thread>
#include <iomanip>
#include <net/ethernet.h>
#include <netinet/ether.h>
#include <linux/ip.h>
#include <netinet/udp.h>
#include <netinet/in.h>
#include <netpacket/packet.h>

#include "ipproto.h"
#include "ospf.h"

#include "colors.h"
#include "helpers.h"
#include "interface.h"
#include "print.h"

using namespace std;
using namespace Colors;

void sigint_handler(int);
void sniff(const int, const ifreq&);
void answer_to_ospf_hello(int, ether_header&, iphdr&, ospfhdr&);

struct ifreq ifr;
bool stop = false;
static pthread_mutex_t cs_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;

int main(int argc, char* argv[])
{
  if (argc != 2)
  {
    std::cerr << "Usage: phantom <interface>" << endl;
    exit(-1);
  }

  if (initSignal(sigint_handler) < 0)
    exit(-1);

  int socket;
  if (initSocket(socket) < 0)
    exit(-1);

  strcpy(ifr.ifr_name, argv[1]);

  if (initInterface(socket, ifr) < 0)
    exit(-1);

  std::thread sniffer(sniff, socket, ifr);
  sniffer.join();

  if (resetInterface(socket, ifr) < 0)
    exit(-1);

  if (closeSocket(socket) < 0)
    exit(-1);

  return 0;
}

       // Tipo Descrição
       // ________________________________
       // 1      Hello
       // 2      Database Description
       // 3      Link State Request
       // 4      Link State Update
       // 5      Link State Acknowledgment

void send_ospf();
void send_hello();
void send_db();
void send_lsr();
void send_lsu();
void send_lsa();

void sigint_handler(int)
{
  cout << yellow << "Received SIGINT to interrupt execution." << reset << endl;
  pthread_mutex_lock(&cs_mutex);
  stop = true;
  pthread_mutex_unlock(&cs_mutex);
}

void sniff(const int socket, const ifreq& ifr)
{
  cout << ifreq_to_str(ifr);

  u_char buff[ETHER_MAX_LEN];

  for (;;)
  {
    pthread_mutex_lock(&cs_mutex);
    if (stop)
    {
      pthread_mutex_unlock(&cs_mutex);
      break;
    }
    pthread_mutex_unlock(&cs_mutex);

    if (recv(socket, (char*)&buff, sizeof(buff), 0x00) < ETHER_MIN_LEN)
      continue;

    struct ether_header ether;
    memcpy(&ether, &buff, sizeof(ether));

    if (ntohs(ether.ether_type) == ETHERTYPE_IP)
    {

      struct iphdr ip;
      memcpy(&ip, &buff[ETHER_HDR_LEN], 1);
      const int IP_HDR_LEN = ip.ihl * 4;
      memcpy(&ip, &buff[ETHER_HDR_LEN], IP_HDR_LEN);

      if (ip.protocol == IPPROTO_OSPF)
      {
        struct ospfhdr ospf;
        memcpy(&ospf, &buff[ETHER_HDR_LEN + IP_HDR_LEN], sizeof(ospfhdr));

        cout << ether_to_str(ether);
        cout << ip_to_str(ip);
        cout << ospf_to_str(ospf);

        switch (ospf.ospf_type)
        {
    			case 1:
            //cout << "Hello" << endl;
            cout << ospf_hello_to_str(ospf);
            answer_to_ospf_hello(socket, ether, ip, ospf);
      			break;
    			case 2:
      			//cout << "Database Description" << endl;
      			cout << ospf_db_to_str(ospf);
      			break;
    			case 3:
      			//cout << "Link State Request" << endl;
      			cout << ospf_lsr_to_str(ospf);
      			break;
    			case 4:
      			//cout << "Link State Update" << endl;
      			cout << ospf_lsu_to_str(ospf);
      			break;
    			case 5:
      			//cout << "Link State Acknowledgment" << endl;
      			cout << ospf_lsa_to_str(ospf);
      			break;
		    }

       // Tipo Descrição
       // ________________________________
       // 1      Hello
       // 2      Database Description
       // 3      Link State Request
       // 4      Link State Update
       // 5      Link State Acknowledgment

       // Pacote de aviso. (Hello packet)
       // Pacote de informações do Banco de Dados (Database Description packet)
       // Requisição de estado de link (Link State Request packet)
       // Atualização de estado de link (Link State Update packet)
       // Recebimento de informações de link (Link State Acknowledgment packet)
      }
    }
  }
}

void answer_to_ospf_hello(int socket, ether_header& ethernet, iphdr& ip, ospfhdr& ospf)
{
  u_char buff[ETHER_MAX_LEN];

  // Altera os headers pro pacote de resposta

  memcpy(ethernet.ether_dhost, ethernet.ether_shost, 6);
  memcpy(ethernet.ether_shost, ifr.ifr_hwaddr.sa_data, 6);

  ip.daddr = ip.saddr;
  ip.saddr = ip.saddr;

  cout << ip_to_str(ip);

  // Monta o pacote com os dados

  memcpy(&buff[0], &ethernet, ETHER_HDR_LEN);
  const int IP_HDR_LEN = ip.ihl * 4;
  memcpy(&buff[ETHER_HDR_LEN], &ip, IP_HDR_LEN);
  memcpy(&buff[ETHER_HDR_LEN + IP_HDR_LEN], &ospf, sizeof(ospfhdr));

  struct sockaddr_ll destAddr;
  destAddr.sll_family = htons(PF_PACKET);
  destAddr.sll_protocol = htons(ETH_P_ALL);
  destAddr.sll_halen = ETH_ALEN;
  destAddr.sll_ifindex = ifr.ifr_ifindex;

  memcpy(&destAddr.sll_addr, ethernet.ether_shost, ETH_ALEN);
  std::cout << green << "Answering..." << std::endl;

  int size = ETHER_HDR_LEN + IP_HDR_LEN + sizeof(ospfhdr);
  if (sendto(socket, buff, size, 0, (struct sockaddr *)&destAddr, sizeof(struct sockaddr_ll)) < 0)
  {
    error();
    return;
  }

  ok();
}
<commit_msg>Update.<commit_after>#include <cstring>

#include <iostream>
#include <thread>
#include <iomanip>
#include <net/ethernet.h>
#include <netinet/ether.h>
#include <linux/ip.h>
#include <netinet/udp.h>
#include <netinet/in.h>
#include <netpacket/packet.h>

#include "ipproto.h"
#include "ospf.h"

#include "colors.h"
#include "helpers.h"
#include "interface.h"
#include "print.h"

using namespace std;
using namespace Colors;

void sigint_handler(int);
void sniff(const int, const ifreq&);
void answer_to_ospf_hello(int, ether_header&, iphdr&, ospfhdr&);

struct ifreq ifr;
bool stop = false;
static pthread_mutex_t cs_mutex = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;

int main(int argc, char* argv[])
{
  if (argc != 2)
  {
    std::cerr << "Usage: phantom <interface>" << endl;
    exit(-1);
  }

  if (initSignal(sigint_handler) < 0)
    exit(-1);

  int socket;
  if (initSocket(socket) < 0)
    exit(-1);

  strcpy(ifr.ifr_name, argv[1]);

  if (initInterface(socket, ifr) < 0)
    exit(-1);

  std::thread sniffer(sniff, socket, ifr);
  sniffer.join();

  if (resetInterface(socket, ifr) < 0)
    exit(-1);

  if (closeSocket(socket) < 0)
    exit(-1);

  return 0;
}

       // Tipo Descrição
       // ________________________________
       // 1      Hello
       // 2      Database Description
       // 3      Link State Request
       // 4      Link State Update
       // 5      Link State Acknowledgment

void send_ospf();
void send_hello();
void send_db();
void send_lsr();
void send_lsu();
void send_lsa();

void sigint_handler(int)
{
  cout << yellow << "Received SIGINT to interrupt execution." << reset << endl;
  pthread_mutex_lock(&cs_mutex);
  stop = true;
  pthread_mutex_unlock(&cs_mutex);
}

void sniff(const int socket, const ifreq& ifr)
{
  cout << ifreq_to_str(ifr);

  u_char buff[ETHER_MAX_LEN];

  for (;;)
  {
    pthread_mutex_lock(&cs_mutex);
    if (stop)
    {
      pthread_mutex_unlock(&cs_mutex);
      break;
    }
    pthread_mutex_unlock(&cs_mutex);

    if (recv(socket, (char*)&buff, sizeof(buff), 0x00) < ETHER_MIN_LEN)
      continue;

    struct ether_header ether;
    memcpy(&ether, &buff, sizeof(ether));

    if (ntohs(ether.ether_type) == ETHERTYPE_IP)
    {

      struct iphdr ip;
      memcpy(&ip, &buff[ETHER_HDR_LEN], 1);
      const int IP_HDR_LEN = ip.ihl * 4;
      memcpy(&ip, &buff[ETHER_HDR_LEN], IP_HDR_LEN);

      if (ip.protocol == IPPROTO_OSPF)
      {
        struct ospfhdr ospf;
        memcpy(&ospf, &buff[ETHER_HDR_LEN + IP_HDR_LEN], sizeof(ospfhdr));

        //cout << ether_to_str(ether);
        //cout << ip_to_str(ip);
        //cout << ospf_to_str(ospf);

        switch (ospf.ospf_type)
        {
    			case 1:
            //cout << "Hello" << endl;
            //cout << ospf_hello_to_str(ospf);
            answer_to_ospf_hello(socket, ether, ip, ospf);
      			break;
    			case 2:
      			//cout << "Database Description" << endl;
      			//cout << ospf_db_to_str(ospf);
      			break;
    			case 3:
      			//cout << "Link State Request" << endl;
      			//cout << ospf_lsr_to_str(ospf);
      			break;
    			case 4:
      			//cout << "Link State Update" << endl;
      			//cout << ospf_lsu_to_str(ospf);
      			break;
    			case 5:
      			//cout << "Link State Acknowledgment" << endl;
      			//cout << ospf_lsa_to_str(ospf);
      			break;
		    }

       // Tipo Descrição
       // ________________________________
       // 1      Hello
       // 2      Database Description
       // 3      Link State Request
       // 4      Link State Update
       // 5      Link State Acknowledgment

       // Pacote de aviso. (Hello packet)
       // Pacote de informações do Banco de Dados (Database Description packet)
       // Requisição de estado de link (Link State Request packet)
       // Atualização de estado de link (Link State Update packet)
       // Recebimento de informações de link (Link State Acknowledgment packet)
      }
    }
  }
}

void answer_to_ospf_hello(int sockt, ether_header& ethernet, iphdr& ip, ospfhdr& ospf)
{
  char buff[ETHER_MAX_LEN];

  // Altera os headers pro pacote de resposta
  memcpy(ethernet.ether_dhost, ethernet.ether_shost, 6);
  memcpy(ethernet.ether_shost, ifr.ifr_hwaddr.sa_data, 6);
  ip.daddr = ip.saddr;
  ip.saddr = ip.saddr;

  cout << ether_to_str(ethernet);
  cout << ip_to_str(ip);

  // Monta o pacote com os dados
  memcpy(&buff[0], &ethernet, ETHER_HDR_LEN);
  const int IP_HDR_LEN = ip.ihl * 4;
  memcpy(&buff[ETHER_HDR_LEN], &ip, IP_HDR_LEN);
  memcpy(&buff[ETHER_HDR_LEN + IP_HDR_LEN], &ospf, sizeof(ospfhdr));

  struct sockaddr_ll destAddr;
  destAddr.sll_family = htons(PF_PACKET);
  destAddr.sll_protocol = htons(ETH_P_ALL);
  destAddr.sll_halen = ETH_ALEN;
  destAddr.sll_ifindex = 2;

  memcpy(&destAddr.sll_addr, &ethernet.ether_shost, ETH_ALEN);
  std::cout << "Answering...";

  char bla[12] = {0xff, 0xf6, 0x00, 0x03, 0x00, 0x01, 0x00, 0x04, 0x00, 0x00, 0x00, 0x01};

  for (int i = 0; i < 12; i++)
    buff[ETHER_HDR_LEN + IP_HDR_LEN + sizeof(ospfhdr) + i] = bla[i];

  int size = ETHER_HDR_LEN + IP_HDR_LEN + sizeof(ospfhdr) + 12;
  if (sendto(sockt, buff, size, 0, (struct sockaddr *)&destAddr, sizeof(struct sockaddr_ll)) < 0)
  {
    error();
    return;
  }

  ok();
}
<|endoftext|>