<commit_before>#include "moses/FF/Factory.h"
#include "moses/StaticData.h"

#include "moses/TranslationModel/PhraseDictionaryTreeAdaptor.h"
#include "moses/TranslationModel/RuleTable/PhraseDictionaryOnDisk.h"
#include "moses/TranslationModel/PhraseDictionaryMemory.h"
#include "moses/TranslationModel/PhraseDictionaryMultiModel.h"
#include "moses/TranslationModel/PhraseDictionaryMultiModelCounts.h"
#include "moses/TranslationModel/RuleTable/PhraseDictionaryALSuffixArray.h"
#include "moses/TranslationModel/PhraseDictionaryDynSuffixArray.h"
#include "moses/TranslationModel/PhraseDictionaryScope3.h"
#include "moses/TranslationModel/PhraseDictionaryTransliteration.h"

#include "moses/FF/LexicalReordering/LexicalReordering.h"

#include "moses/FF/BleuScoreFeature.h"
#include "moses/FF/TargetWordInsertionFeature.h"
#include "moses/FF/SourceWordDeletionFeature.h"
#include "moses/FF/GlobalLexicalModel.h"
#include "moses/FF/GlobalLexicalModelUnlimited.h"
#include "moses/FF/UnknownWordPenaltyProducer.h"
#include "moses/FF/WordTranslationFeature.h"
#include "moses/FF/TargetBigramFeature.h"
#include "moses/FF/TargetNgramFeature.h"
#include "moses/FF/PhraseBoundaryFeature.h"
#include "moses/FF/PhrasePairFeature.h"
#include "moses/FF/PhraseLengthFeature.h"
#include "moses/FF/DistortionScoreProducer.h"
#include "moses/FF/WordPenaltyProducer.h"
#include "moses/FF/InputFeature.h"
#include "moses/FF/PhrasePenalty.h"
#include "moses/FF/OSM-Feature/OpSequenceModel.h"
#include "moses/FF/ControlRecombination.h"
#include "moses/FF/ExternalFeature.h"
#include "moses/FF/ConstrainedDecoding.h"
#include "moses/FF/CoveredReferenceFeature.h"
#include "moses/FF/SyntaxConstraintFeature.h"
#include "moses/FF/SoftMatchingFeature.h"
#include "moses/FF/HyperParameterAsWeight.h"

#include "moses/FF/SkeletonStatelessFF.h"
#include "moses/FF/SkeletonStatefulFF.h"
#include "moses/LM/SkeletonLM.h"
#include "moses/TranslationModel/SkeletonPT.h"

#ifdef HAVE_CMPH
#include "moses/TranslationModel/CompactPT/PhraseDictionaryCompact.h"
#endif
#ifdef PT_UG
#include "moses/TranslationModel/mmsapt.h"
#endif
#ifdef HAVE_PROBINGPT
#include "moses/TranslationModel/ProbingPT.h"
#endif

#include "moses/LM/Ken.h"
#ifdef LM_IRST
#include "moses/LM/IRST.h"
#endif

#ifdef LM_SRI
#include "moses/LM/SRI.h"
#endif

#ifdef LM_MAXENT_SRI
#include "moses/LM/MaxEntSRI.h"
#endif

#ifdef LM_RAND
#include "moses/LM/Rand.h"
#endif

#ifdef HAVE_SYNLM
#include "moses/SyntacticLanguageModel.h"
#endif

#ifdef LM_NEURAL
#include "moses/LM/NeuralLMWrapper.h"
#endif

#ifdef LM_DALM
#include "moses/LM/DALMWrapper.h"
#endif

#include "util/exception.hh"

#include <vector>

namespace Moses
{

class FeatureFactory
{
public:
  virtual ~FeatureFactory() {}

  virtual void Create(const std::string &line) = 0;

protected:
  template <class F> static void DefaultSetup(F *feature);

  FeatureFactory() {}
};

template <class F> void FeatureFactory::DefaultSetup(F *feature)
{
  StaticData &static_data = StaticData::InstanceNonConst();
  const string &featureName = feature->GetScoreProducerDescription();
  std::vector<float> weights = static_data.GetParameter()->GetWeights(featureName);

  if (feature->IsTuneable() || weights.size()) {
    // if it's tuneable, ini file MUST have weights
    // even it it's not tuneable, people can still set the weights in the ini file
    static_data.SetWeights(feature, weights);
  } else if (feature->GetNumScoreComponents() > 0) {
    std::vector<float> defaultWeights = feature->DefaultWeights();
    static_data.SetWeights(feature, defaultWeights);
  }
}

namespace
{

template <class F> class DefaultFeatureFactory : public FeatureFactory
{
public:
  void Create(const std::string &line) {
    DefaultSetup(new F(line));
  }
};

class KenFactory : public FeatureFactory
{
public:
  void Create(const std::string &line) {
    DefaultSetup(ConstructKenLM(line));
  }
};

} // namespace

FeatureRegistry::FeatureRegistry()
{
// Feature with same name as class
#define MOSES_FNAME(name) Add(#name, new DefaultFeatureFactory< name >());
// Feature with different name than class.
#define MOSES_FNAME2(name, type) Add(name, new DefaultFeatureFactory< type >());
  MOSES_FNAME(GlobalLexicalModel);
  //MOSES_FNAME(GlobalLexicalModelUnlimited); This was commented out in the original
  MOSES_FNAME(SourceWordDeletionFeature);
  MOSES_FNAME(TargetWordInsertionFeature);
  MOSES_FNAME(PhraseBoundaryFeature);
  MOSES_FNAME(PhraseLengthFeature);
  MOSES_FNAME(WordTranslationFeature);
  MOSES_FNAME(TargetBigramFeature);
  MOSES_FNAME(TargetNgramFeature);
  MOSES_FNAME(PhrasePairFeature);
  MOSES_FNAME(LexicalReordering);
  MOSES_FNAME2("Generation", GenerationDictionary);
  MOSES_FNAME(BleuScoreFeature);
  MOSES_FNAME2("Distortion", DistortionScoreProducer);
  MOSES_FNAME2("WordPenalty", WordPenaltyProducer);
  MOSES_FNAME(InputFeature);
  MOSES_FNAME2("PhraseDictionaryBinary", PhraseDictionaryTreeAdaptor);
  MOSES_FNAME(PhraseDictionaryOnDisk);
  MOSES_FNAME(PhraseDictionaryMemory);
  MOSES_FNAME(PhraseDictionaryScope3);
  MOSES_FNAME(PhraseDictionaryMultiModel);
  MOSES_FNAME(PhraseDictionaryMultiModelCounts);
  MOSES_FNAME(PhraseDictionaryALSuffixArray);
  MOSES_FNAME(PhraseDictionaryDynSuffixArray);
  MOSES_FNAME(PhraseDictionaryTransliteration);
  MOSES_FNAME(OpSequenceModel);
  MOSES_FNAME(PhrasePenalty);
  MOSES_FNAME2("UnknownWordPenalty", UnknownWordPenaltyProducer);
  MOSES_FNAME(ControlRecombination);
  MOSES_FNAME(ConstrainedDecoding);
  MOSES_FNAME(CoveredReferenceFeature);
  MOSES_FNAME(ExternalFeature);
  MOSES_FNAME(SyntaxConstraintFeature);
  MOSES_FNAME(SoftMatchingFeature);
  MOSES_FNAME(HyperParameterAsWeight);

  MOSES_FNAME(SkeletonStatelessFF);
  MOSES_FNAME(SkeletonStatefulFF);
  MOSES_FNAME(SkeletonLM);
  MOSES_FNAME(SkeletonPT);

#ifdef HAVE_CMPH
  MOSES_FNAME(PhraseDictionaryCompact);
#endif
#ifdef PT_UG
  MOSES_FNAME(Mmsapt);
#endif
#ifdef HAVE_PROBINGPT
  MOSES_FNAME(ProbingPT);
#endif

#ifdef HAVE_SYNLM
  MOSES_FNAME(SyntacticLanguageModel);
#endif
#ifdef LM_IRST
  MOSES_FNAME2("IRSTLM", LanguageModelIRST);
#endif
#ifdef LM_SRI
  MOSES_FNAME2("SRILM", LanguageModelSRI);
#endif
#ifdef LM_MAXENT_SRI
  MOSES_FNAME2("MaxEntLM", LanguageModelMaxEntSRI);
#endif
#ifdef LM_RAND
  MOSES_FNAME2("RANDLM", LanguageModelRandLM);
#endif
#ifdef LM_NEURAL
  MOSES_FNAME2("NeuralLM", NeuralLMWrapper);
#endif
#ifdef LM_DALM
  MOSES_FNAME2("DALM", LanguageModelDALM);
#endif

  Add("KENLM", new KenFactory());
}

FeatureRegistry::~FeatureRegistry()
{
}

void FeatureRegistry::Add(const std::string &name, FeatureFactory *factory)
{
  std::pair<std::string, boost::shared_ptr<FeatureFactory> > to_ins(name, boost::shared_ptr<FeatureFactory>(factory));
  UTIL_THROW_IF2(!registry_.insert(to_ins).second, "Duplicate feature name " << name);
}

namespace
{
class UnknownFeatureException : public util::Exception {};
}

void FeatureRegistry::Construct(const std::string &name, const std::string &line)
{
  Map::iterator i = registry_.find(name);
  UTIL_THROW_IF(i == registry_.end(), UnknownFeatureException, "Feature name " << name << " is not registered.");
  i->second->Create(line);
}

void FeatureRegistry::PrintFF() const
{
	std::cerr << "Available feature functions:" << std::endl;
	Map::const_iterator iter;
	for (iter = registry_.begin(); iter != registry_.end(); ++iter) {
		const string &ffName = iter->first;
		std::cerr << ffName << std::endl;
	}

}

} // namespace Moses
<commit_msg>moved<commit_after>#include "moses/FF/Factory.h"
#include "moses/StaticData.h"

#include "moses/TranslationModel/PhraseDictionaryTreeAdaptor.h"
#include "moses/TranslationModel/RuleTable/PhraseDictionaryOnDisk.h"
#include "moses/TranslationModel/PhraseDictionaryMemory.h"
#include "moses/TranslationModel/PhraseDictionaryMultiModel.h"
#include "moses/TranslationModel/PhraseDictionaryMultiModelCounts.h"
#include "moses/TranslationModel/RuleTable/PhraseDictionaryALSuffixArray.h"
#include "moses/TranslationModel/PhraseDictionaryDynSuffixArray.h"
#include "moses/TranslationModel/PhraseDictionaryScope3.h"
#include "moses/TranslationModel/PhraseDictionaryTransliteration.h"

#include "moses/FF/LexicalReordering/LexicalReordering.h"

#include "moses/FF/BleuScoreFeature.h"
#include "moses/FF/TargetWordInsertionFeature.h"
#include "moses/FF/SourceWordDeletionFeature.h"
#include "moses/FF/GlobalLexicalModel.h"
#include "moses/FF/GlobalLexicalModelUnlimited.h"
#include "moses/FF/UnknownWordPenaltyProducer.h"
#include "moses/FF/WordTranslationFeature.h"
#include "moses/FF/TargetBigramFeature.h"
#include "moses/FF/TargetNgramFeature.h"
#include "moses/FF/PhraseBoundaryFeature.h"
#include "moses/FF/PhrasePairFeature.h"
#include "moses/FF/PhraseLengthFeature.h"
#include "moses/FF/DistortionScoreProducer.h"
#include "moses/FF/WordPenaltyProducer.h"
#include "moses/FF/InputFeature.h"
#include "moses/FF/PhrasePenalty.h"
#include "moses/FF/OSM-Feature/OpSequenceModel.h"
#include "moses/FF/ControlRecombination.h"
#include "moses/FF/ExternalFeature.h"
#include "moses/FF/ConstrainedDecoding.h"
#include "moses/FF/CoveredReferenceFeature.h"
#include "moses/FF/SyntaxConstraintFeature.h"
#include "moses/FF/SoftMatchingFeature.h"
#include "moses/FF/HyperParameterAsWeight.h"

#include "moses/FF/SkeletonStatelessFF.h"
#include "moses/FF/SkeletonStatefulFF.h"
#include "moses/LM/SkeletonLM.h"
#include "moses/TranslationModel/SkeletonPT.h"

#ifdef HAVE_CMPH
#include "moses/TranslationModel/CompactPT/PhraseDictionaryCompact.h"
#endif
#ifdef PT_UG
#include "moses/TranslationModel/mmsapt.h"
#endif
#ifdef HAVE_PROBINGPT
#include "moses/TranslationModel/ProbingPT/ProbingPT.h"
#endif

#include "moses/LM/Ken.h"
#ifdef LM_IRST
#include "moses/LM/IRST.h"
#endif

#ifdef LM_SRI
#include "moses/LM/SRI.h"
#endif

#ifdef LM_MAXENT_SRI
#include "moses/LM/MaxEntSRI.h"
#endif

#ifdef LM_RAND
#include "moses/LM/Rand.h"
#endif

#ifdef HAVE_SYNLM
#include "moses/SyntacticLanguageModel.h"
#endif

#ifdef LM_NEURAL
#include "moses/LM/NeuralLMWrapper.h"
#endif

#ifdef LM_DALM
#include "moses/LM/DALMWrapper.h"
#endif

#include "util/exception.hh"

#include <vector>

namespace Moses
{

class FeatureFactory
{
public:
  virtual ~FeatureFactory() {}

  virtual void Create(const std::string &line) = 0;

protected:
  template <class F> static void DefaultSetup(F *feature);

  FeatureFactory() {}
};

template <class F> void FeatureFactory::DefaultSetup(F *feature)
{
  StaticData &static_data = StaticData::InstanceNonConst();
  const string &featureName = feature->GetScoreProducerDescription();
  std::vector<float> weights = static_data.GetParameter()->GetWeights(featureName);

  if (feature->IsTuneable() || weights.size()) {
    // if it's tuneable, ini file MUST have weights
    // even it it's not tuneable, people can still set the weights in the ini file
    static_data.SetWeights(feature, weights);
  } else if (feature->GetNumScoreComponents() > 0) {
    std::vector<float> defaultWeights = feature->DefaultWeights();
    static_data.SetWeights(feature, defaultWeights);
  }
}

namespace
{

template <class F> class DefaultFeatureFactory : public FeatureFactory
{
public:
  void Create(const std::string &line) {
    DefaultSetup(new F(line));
  }
};

class KenFactory : public FeatureFactory
{
public:
  void Create(const std::string &line) {
    DefaultSetup(ConstructKenLM(line));
  }
};

} // namespace

FeatureRegistry::FeatureRegistry()
{
// Feature with same name as class
#define MOSES_FNAME(name) Add(#name, new DefaultFeatureFactory< name >());
// Feature with different name than class.
#define MOSES_FNAME2(name, type) Add(name, new DefaultFeatureFactory< type >());
  MOSES_FNAME(GlobalLexicalModel);
  //MOSES_FNAME(GlobalLexicalModelUnlimited); This was commented out in the original
  MOSES_FNAME(SourceWordDeletionFeature);
  MOSES_FNAME(TargetWordInsertionFeature);
  MOSES_FNAME(PhraseBoundaryFeature);
  MOSES_FNAME(PhraseLengthFeature);
  MOSES_FNAME(WordTranslationFeature);
  MOSES_FNAME(TargetBigramFeature);
  MOSES_FNAME(TargetNgramFeature);
  MOSES_FNAME(PhrasePairFeature);
  MOSES_FNAME(LexicalReordering);
  MOSES_FNAME2("Generation", GenerationDictionary);
  MOSES_FNAME(BleuScoreFeature);
  MOSES_FNAME2("Distortion", DistortionScoreProducer);
  MOSES_FNAME2("WordPenalty", WordPenaltyProducer);
  MOSES_FNAME(InputFeature);
  MOSES_FNAME2("PhraseDictionaryBinary", PhraseDictionaryTreeAdaptor);
  MOSES_FNAME(PhraseDictionaryOnDisk);
  MOSES_FNAME(PhraseDictionaryMemory);
  MOSES_FNAME(PhraseDictionaryScope3);
  MOSES_FNAME(PhraseDictionaryMultiModel);
  MOSES_FNAME(PhraseDictionaryMultiModelCounts);
  MOSES_FNAME(PhraseDictionaryALSuffixArray);
  MOSES_FNAME(PhraseDictionaryDynSuffixArray);
  MOSES_FNAME(PhraseDictionaryTransliteration);
  MOSES_FNAME(OpSequenceModel);
  MOSES_FNAME(PhrasePenalty);
  MOSES_FNAME2("UnknownWordPenalty", UnknownWordPenaltyProducer);
  MOSES_FNAME(ControlRecombination);
  MOSES_FNAME(ConstrainedDecoding);
  MOSES_FNAME(CoveredReferenceFeature);
  MOSES_FNAME(ExternalFeature);
  MOSES_FNAME(SyntaxConstraintFeature);
  MOSES_FNAME(SoftMatchingFeature);
  MOSES_FNAME(HyperParameterAsWeight);

  MOSES_FNAME(SkeletonStatelessFF);
  MOSES_FNAME(SkeletonStatefulFF);
  MOSES_FNAME(SkeletonLM);
  MOSES_FNAME(SkeletonPT);

#ifdef HAVE_CMPH
  MOSES_FNAME(PhraseDictionaryCompact);
#endif
#ifdef PT_UG
  MOSES_FNAME(Mmsapt);
#endif
#ifdef HAVE_PROBINGPT
  MOSES_FNAME(ProbingPT);
#endif

#ifdef HAVE_SYNLM
  MOSES_FNAME(SyntacticLanguageModel);
#endif
#ifdef LM_IRST
  MOSES_FNAME2("IRSTLM", LanguageModelIRST);
#endif
#ifdef LM_SRI
  MOSES_FNAME2("SRILM", LanguageModelSRI);
#endif
#ifdef LM_MAXENT_SRI
  MOSES_FNAME2("MaxEntLM", LanguageModelMaxEntSRI);
#endif
#ifdef LM_RAND
  MOSES_FNAME2("RANDLM", LanguageModelRandLM);
#endif
#ifdef LM_NEURAL
  MOSES_FNAME2("NeuralLM", NeuralLMWrapper);
#endif
#ifdef LM_DALM
  MOSES_FNAME2("DALM", LanguageModelDALM);
#endif

  Add("KENLM", new KenFactory());
}

FeatureRegistry::~FeatureRegistry()
{
}

void FeatureRegistry::Add(const std::string &name, FeatureFactory *factory)
{
  std::pair<std::string, boost::shared_ptr<FeatureFactory> > to_ins(name, boost::shared_ptr<FeatureFactory>(factory));
  UTIL_THROW_IF2(!registry_.insert(to_ins).second, "Duplicate feature name " << name);
}

namespace
{
class UnknownFeatureException : public util::Exception {};
}

void FeatureRegistry::Construct(const std::string &name, const std::string &line)
{
  Map::iterator i = registry_.find(name);
  UTIL_THROW_IF(i == registry_.end(), UnknownFeatureException, "Feature name " << name << " is not registered.");
  i->second->Create(line);
}

void FeatureRegistry::PrintFF() const
{
	std::cerr << "Available feature functions:" << std::endl;
	Map::const_iterator iter;
	for (iter = registry_.begin(); iter != registry_.end(); ++iter) {
		const string &ffName = iter->first;
		std::cerr << ffName << std::endl;
	}

}

} // namespace Moses
<|endoftext|>


<commit_before><commit_msg>fix previous commit (pdb and raw_headers)<commit_after><|endoftext|>


<commit_before>/**
 * @file AbstractMotion.cpp
 *
 * @author Xu, Yuan
 */

#include "AbstractMotion.h"

using namespace naoth;

AbstractMotion::AbstractMotion(motion::MotionID id, MotionLock& lock)
: theId(id),
  lock(lock),
  currentState(motion::stopped)
{
  //assert(lock.state == motion::stopped || id == motion::dead);
  // occupy lock
  lock.id = id;
  lock.state = currentState;

  init();
}

bool AbstractMotion::setStiffness(
  naoth::MotorJointData& theMotorJointData,
  const naoth::SensorJointData& theSensorJointData,
  double* stiffness,
  double delta,
  JointData::JointID begin, JointData::JointID end)
{
  int readyJointNum = 0;
  for (int i = begin; i < end; i++)
  {
    double d = stiffness[i] - theSensorJointData.stiffness[i];
    if (fabs(d) < delta || i == JointData::HeadPitch || i==JointData::HeadYaw )
    {
      readyJointNum++;
      theMotorJointData.stiffness[i] = stiffness[i];
    } else
    {
      d = Math::clamp(d, -delta, delta);
      theMotorJointData.stiffness[i] = theMotorJointData.stiffness[i] + d;

      // ensure that we always get a valid stiffness, i.e, -1 or [0,1]
      if (theMotorJointData.stiffness[i] < 0) // -1 is the special case
      {
        theMotorJointData.stiffness[i] = (d < 0)?-1:0;
      } else {
        theMotorJointData.stiffness[i] = std::min(theMotorJointData.stiffness[i],1.0);
      }
    }
  }//end for

  return readyJointNum == (end - begin);
}//end setStiffness
<commit_msg>bugfix: corrected setting of the stiffness<commit_after>/**
 * @file AbstractMotion.cpp
 *
 * @author Xu, Yuan
 */

#include "AbstractMotion.h"

using namespace naoth;

AbstractMotion::AbstractMotion(motion::MotionID id, MotionLock& lock)
: theId(id),
  lock(lock),
  currentState(motion::stopped)
{
  //assert(lock.state == motion::stopped || id == motion::dead);
  // occupy lock
  lock.id = id;
  lock.state = currentState;

  init();
}

bool AbstractMotion::setStiffness(
  naoth::MotorJointData& theMotorJointData,
  const naoth::SensorJointData& theSensorJointData,
  double* stiffness,
  double delta,
  JointData::JointID begin, JointData::JointID end)
{
  int readyJointNum = 0;
  for (int i = begin; i < end; i++)
  {
    double d = stiffness[i] - theSensorJointData.stiffness[i];
    if (fabs(d) < 1e-2 || i == JointData::HeadPitch || i==JointData::HeadYaw )
    {
      readyJointNum++;
      theMotorJointData.stiffness[i] = stiffness[i];
    } else {
      d = Math::clamp(d, -delta, delta);
      theMotorJointData.stiffness[i] = theMotorJointData.stiffness[i] + d;
    }

    // ensure that we always get a valid stiffness, i.e, -1 or [0,1]
    if (theMotorJointData.stiffness[i] < 0) // -1 is the special case
    {
      theMotorJointData.stiffness[i] = (d > 0)?0:-1;
    } else {
      theMotorJointData.stiffness[i] = std::min(theMotorJointData.stiffness[i],1.0);
    }
  }//end for

  return readyJointNum == (end - begin);
}//end setStiffness
<|endoftext|>


<commit_before><commit_msg>Don't crash if one opens a message with a vcal attachment.<commit_after><|endoftext|>


<commit_before>/***************************************************************************/ /**
  * \file       DfaTest.cc
  * OVERVIEW:   Provides the implementation for the DfaTest class, which
  *                tests the data flow based type analysis code
  */
#include "DfaTest.h"

#include "boomerang.h"
#include "type.h"

#include <QtCore/QDir>
#include <QtCore/QProcessEnvironment>
#include <QtCore/QDebug>
#include <sstream>

static bool logset = false;
QString TEST_BASE;
QDir baseDir;

void DfaTest::initTestCase() {
    if (!logset) {
        TEST_BASE = QProcessEnvironment::systemEnvironment().value("BOOMERANG_TEST_BASE", "");
        baseDir = QDir(TEST_BASE);
        if (TEST_BASE.isEmpty()) {
            qWarning() << "BOOMERANG_TEST_BASE environment variable not set, will assume '..', many test may fail";
            TEST_BASE = "..";
            baseDir = QDir("..");
        }
        logset = true;
        Boomerang::get()->setProgPath(TEST_BASE);
        Boomerang::get()->setPluginPath(TEST_BASE + "/out");
        Boomerang::get()->setLogger(new NullLogger());
    }
}

/***************************************************************************/ /**
  * \fn        DfaTest::testMeetInt
  * OVERVIEW:        Test meeting IntegerTypes with various other types
  ******************************************************************************/
void DfaTest::testMeetInt() {
    IntegerType *i32 = IntegerType::get(32, 1);
    IntegerType *j32 = IntegerType::get(32, 0);
    IntegerType *u32 = IntegerType::get(32, -1);
    IntegerType *xint = IntegerType::get(0);
    IntegerType *j16 = IntegerType::get(16, 0);
    SizeType s32(32);
    SizeType s64(64);
    FloatType *flt = FloatType::get(32);
    PointerType pt(flt);
    VoidType v;

    bool ch = false;
    i32->meetWith(i32, ch, false);
    QVERIFY(ch == false);
    QString actual;
    QTextStream ost1(&actual);
    ost1 << i32;
    QString expected("i32");
    QCOMPARE(actual,expected);
    actual.clear();

    i32->meetWith(j32, ch, false);
    QVERIFY(ch == false);
    j32->meetWith(i32, ch, false);
    QVERIFY(ch == true);

    ost1 << i32;
    QCOMPARE(actual,QString("i32"));
    actual.clear();

    ch = false;
    j32->setSigned(0);
    j32->meetWith(&v, ch, false);
    QVERIFY(ch == false);

    ost1 << j32;
    QCOMPARE(actual,QString("j32"));
    actual.clear();

    ch = false;
    j32->meetWith(u32, ch, false);
    QVERIFY(ch == true);

    ost1 << j32;
    QCOMPARE(actual,QString("u32"));
    actual.clear();

    ch = false;
    u32->meetWith(&s32, ch, false);
    QVERIFY(ch == false);

    ost1 << u32;
    QCOMPARE(actual,QString("u32"));
    actual.clear();

    u32->meetWith(&s64, ch, false);
    QVERIFY(ch == true);

    ost1 << u32;
    QCOMPARE(actual,QString("u64"));
    actual.clear();

    ch = false;
    Type *res = i32->meetWith(flt, ch, false);
    QVERIFY(ch == true);

    ost1 << res;
    QCOMPARE(actual,QString("union"));
    actual.clear();

    ch = false;
    res = i32->meetWith(&pt, ch, false);
    QVERIFY(ch == true);

    ost1 << res;
    QCOMPARE(actual,QString("union"));
    actual.clear();
}

/***************************************************************************/ /**
  * \fn        DfaTest::testMeetSize
  * OVERVIEW:        Test meeting IntegerTypes with various other types
  ******************************************************************************/
void DfaTest::testMeetSize() {
    QString actual;
    QTextStream ost1(&actual);
    IntegerType *i32 = IntegerType::get(32, 1);
    SizeType s32(32);
    SizeType s16(16);
    FloatType *flt = FloatType::get(32);
    VoidType v;

    bool ch = false;
    Type *res = s32.meetWith(i32, ch, false);
    QVERIFY(ch == true);

    ost1 << res;
    QCOMPARE(actual,QString("i32"));
    actual.clear();

    ch = false;
    res = s32.meetWith(&s16, ch, false);
    QVERIFY(ch == false);

    // There is a known failure here; to show the warning, use ErrLogger
    Boomerang::get()->setLogger(new ErrLogger);

    res = s16.meetWith(flt, ch, false);
    QVERIFY(ch == true);

    ost1 << res;
    QCOMPARE(actual,QString("union"));
    actual.clear();

    ch = false;
    res = s16.meetWith(&v, ch, false);
    QVERIFY(ch == false);

    ost1 << res;
    QCOMPARE(actual,QString("16"));
    actual.clear();
}

/***************************************************************************/ /**
  * \fn        DfaTest::testMeetPointer
  * OVERVIEW:        Test meeting IntegerTypes with various other types
  ******************************************************************************/
void DfaTest::testMeetPointer() {
    IntegerType *i32 = IntegerType::get(32, 1);
    IntegerType *u32 = IntegerType::get(32, -1);
    PointerType pi32(i32);
    PointerType pu32(u32);
    VoidType v;
    QString actual;
    QTextStream ost1(&actual);

    ost1 << pu32.getCtype();
    QCOMPARE(actual,QString("unsigned int *"));
    actual.clear();

    bool ch = false;
    Type *res = pi32.meetWith(&pu32, ch, false);
    QVERIFY(ch == true);

    ost1 << res->getCtype();
    QCOMPARE(actual,QString("/*signed?*/int *"));
    actual.clear();

    ch = false;
    res = pi32.meetWith(&v, ch, false);
    QVERIFY(ch == false);

    res = pi32.meetWith(i32, ch, false);

    ost1 << res->getCtype();
    QCOMPARE(actual,QString("union"));
    actual.clear();
}

/***************************************************************************/ /**
  * \fn        DfaTest::testMeetUnion
  * OVERVIEW:        Test meeting IntegerTypes with various other types
  ******************************************************************************/
void DfaTest::testMeetUnion() {
    UnionType u1;
    IntegerType *i32 = IntegerType::get(32, 1);
    IntegerType *j32 = IntegerType::get(32, 0);
    IntegerType *u32 = IntegerType::get(32, -1);
    FloatType *flt = FloatType::get(32);
    u1.addType(i32, "bow");
    u1.addType(flt, "wow");

    std::ostringstream ost1;
    ost1 << u1.getCtype().toStdString();
    std::string actual(ost1.str());
    std::string expected("union { int bow; float wow; }");
    QCOMPARE(actual,expected);

    bool ch = false;
    Type *res = u1.meetWith(j32, ch, false);
    QVERIFY(ch == false);
    std::ostringstream ost2;
    ost2 << res->getCtype().toStdString();
    actual = ost2.str();
    expected = "union { int bow; float wow; }";
    QCOMPARE(actual,expected);

    res = u1.meetWith(j32, ch, false);
    QVERIFY(ch == false);
    std::ostringstream ost3;
    ost3 << u1.getCtype().toStdString();
    actual = ost3.str();
    expected = "union { int bow; float wow; }";
    QCOMPARE(actual,expected);

    // Note: this test relies on the int in the union having signedness 1
    res = u1.meetWith(u32, ch, false);
    QVERIFY(ch == true);
    std::ostringstream ost4;
    ost4 << u1.getCtype().toStdString();
    actual = ost4.str();
    expected = "union { /*signed?*/int bow; float wow; }";
    QCOMPARE(actual,expected);
}
QTEST_MAIN(DfaTest)
<commit_msg>Fixing DfaTest::testMeetPointer<commit_after>/***************************************************************************/ /**
  * \file       DfaTest.cc
  * OVERVIEW:   Provides the implementation for the DfaTest class, which
  *                tests the data flow based type analysis code
  */
#include "DfaTest.h"

#include "boomerang.h"
#include "type.h"

#include <QtCore/QDir>
#include <QtCore/QProcessEnvironment>
#include <QtCore/QDebug>
#include <sstream>

static bool logset = false;
QString TEST_BASE;
QDir baseDir;

void DfaTest::initTestCase() {
    if (!logset) {
        TEST_BASE = QProcessEnvironment::systemEnvironment().value("BOOMERANG_TEST_BASE", "");
        baseDir = QDir(TEST_BASE);
        if (TEST_BASE.isEmpty()) {
            qWarning() << "BOOMERANG_TEST_BASE environment variable not set, will assume '..', many test may fail";
            TEST_BASE = "..";
            baseDir = QDir("..");
        }
        logset = true;
        Boomerang::get()->setProgPath(TEST_BASE);
        Boomerang::get()->setPluginPath(TEST_BASE + "/out");
        Boomerang::get()->setLogger(new NullLogger());
    }
}

/***************************************************************************/ /**
  * \fn        DfaTest::testMeetInt
  * OVERVIEW:        Test meeting IntegerTypes with various other types
  ******************************************************************************/
void DfaTest::testMeetInt() {
    IntegerType *i32 = IntegerType::get(32, 1);
    IntegerType *j32 = IntegerType::get(32, 0);
    IntegerType *u32 = IntegerType::get(32, -1);
    IntegerType *xint = IntegerType::get(0);
    IntegerType *j16 = IntegerType::get(16, 0);
    SizeType s32(32);
    SizeType s64(64);
    FloatType *flt = FloatType::get(32);
    PointerType pt(flt);
    VoidType v;

    bool ch = false;
    i32->meetWith(i32, ch, false);
    QVERIFY(ch == false);
    QString actual;
    QTextStream ost1(&actual);
    ost1 << i32;
    QString expected("i32");
    QCOMPARE(actual,expected);
    actual.clear();

    i32->meetWith(j32, ch, false);
    QVERIFY(ch == false);
    j32->meetWith(i32, ch, false);
    QVERIFY(ch == true);

    ost1 << i32;
    QCOMPARE(actual,QString("i32"));
    actual.clear();

    ch = false;
    j32->setSigned(0);
    j32->meetWith(&v, ch, false);
    QVERIFY(ch == false);

    ost1 << j32;
    QCOMPARE(actual,QString("j32"));
    actual.clear();

    ch = false;
    j32->meetWith(u32, ch, false);
    QVERIFY(ch == true);

    ost1 << j32;
    QCOMPARE(actual,QString("u32"));
    actual.clear();

    ch = false;
    u32->meetWith(&s32, ch, false);
    QVERIFY(ch == false);

    ost1 << u32;
    QCOMPARE(actual,QString("u32"));
    actual.clear();

    u32->meetWith(&s64, ch, false);
    QVERIFY(ch == true);

    ost1 << u32;
    QCOMPARE(actual,QString("u64"));
    actual.clear();

    ch = false;
    Type *res = i32->meetWith(flt, ch, false);
    QVERIFY(ch == true);

    ost1 << res;
    QCOMPARE(actual,QString("union"));
    actual.clear();

    ch = false;
    res = i32->meetWith(&pt, ch, false);
    QVERIFY(ch == true);

    ost1 << res;
    QCOMPARE(actual,QString("union"));
    actual.clear();
}

/***************************************************************************/ /**
  * \fn        DfaTest::testMeetSize
  * OVERVIEW:        Test meeting IntegerTypes with various other types
  ******************************************************************************/
void DfaTest::testMeetSize() {
    QString actual;
    QTextStream ost1(&actual);
    IntegerType *i32 = IntegerType::get(32, 1);
    SizeType s32(32);
    SizeType s16(16);
    FloatType *flt = FloatType::get(32);
    VoidType v;

    bool ch = false;
    Type *res = s32.meetWith(i32, ch, false);
    QVERIFY(ch == true);

    ost1 << res;
    QCOMPARE(actual,QString("i32"));
    actual.clear();

    ch = false;
    res = s32.meetWith(&s16, ch, false);
    QVERIFY(ch == false);

    // There is a known failure here; to show the warning, use ErrLogger
    Boomerang::get()->setLogger(new ErrLogger);

    res = s16.meetWith(flt, ch, false);
    QVERIFY(ch == true);

    ost1 << res;
    QCOMPARE(actual,QString("union"));
    actual.clear();

    ch = false;
    res = s16.meetWith(&v, ch, false);
    QVERIFY(ch == false);

    ost1 << res;
    QCOMPARE(actual,QString("16"));
    actual.clear();
}

/***************************************************************************/ /**
  * \fn        DfaTest::testMeetPointer
  * OVERVIEW:        Test meeting IntegerTypes with various other types
  ******************************************************************************/
void DfaTest::testMeetPointer() {
    IntegerType *i32 = IntegerType::get(32, 1);
    IntegerType *u32 = IntegerType::get(32, -1);
    PointerType pi32(i32);
    PointerType pu32(u32);
    VoidType v;
    QString actual;
    QTextStream ost1(&actual);

    ost1 << pu32.getCtype();
    QCOMPARE(actual,QString("unsigned int *"));
    actual.clear();

    bool ch = false;
    Type *res = pi32.meetWith(&pu32, ch, false);
    QVERIFY(ch == true);

    ost1 << res->getCtype();
    QCOMPARE(actual,QString("/*signed?*/int *"));
    actual.clear();

    ch = false;
    res = pi32.meetWith(&v, ch, false);
    QVERIFY(ch == false);

    res = pi32.meetWith(i32, ch, false);
    QVERIFY(res->isUnion());
}

/***************************************************************************/ /**
  * \fn        DfaTest::testMeetUnion
  * OVERVIEW:        Test meeting IntegerTypes with various other types
  ******************************************************************************/
void DfaTest::testMeetUnion() {
    UnionType u1;
    IntegerType *i32 = IntegerType::get(32, 1);
    IntegerType *j32 = IntegerType::get(32, 0);
    IntegerType *u32 = IntegerType::get(32, -1);
    FloatType *flt = FloatType::get(32);
    u1.addType(i32, "bow");
    u1.addType(flt, "wow");

    std::ostringstream ost1;
    ost1 << u1.getCtype().toStdString();
    std::string actual(ost1.str());
    std::string expected("union { int bow; float wow; }");
    QCOMPARE(actual,expected);

    bool ch = false;
    Type *res = u1.meetWith(j32, ch, false);
    QVERIFY(ch == false);
    std::ostringstream ost2;
    ost2 << res->getCtype().toStdString();
    actual = ost2.str();
    expected = "union { int bow; float wow; }";
    QCOMPARE(actual,expected);

    res = u1.meetWith(j32, ch, false);
    QVERIFY(ch == false);
    std::ostringstream ost3;
    ost3 << u1.getCtype().toStdString();
    actual = ost3.str();
    expected = "union { int bow; float wow; }";
    QCOMPARE(actual,expected);

    // Note: this test relies on the int in the union having signedness 1
    res = u1.meetWith(u32, ch, false);
    QVERIFY(ch == true);
    std::ostringstream ost4;
    ost4 << u1.getCtype().toStdString();
    actual = ost4.str();
    expected = "union { /*signed?*/int bow; float wow; }";
    QCOMPARE(actual,expected);
}
QTEST_MAIN(DfaTest)
<|endoftext|>


<commit_before><commit_msg>fixed: now testing in read every field, if it is valid fixed: now seting atom radius massive cosmetic changes<commit_after><|endoftext|>


<commit_before>#include "sshtunnelout.h"
#include "sshclient.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QEventLoop>

SshTunnelOut::SshTunnelOut(SshClient *client, QTcpSocket *tcpSocket, QString port_identifier, quint16 port, QObject *parent):
    QObject(parent),
    m_opened(false),
    m_port(port),
    m_name(port_identifier),
    m_tcpsocket(tcpSocket),
    m_client(client),
    m_sshChannel(nullptr),
    m_dataSsh(16384, 0),
    m_dataSocket(16384, 0),
    m_callDepth(0)
{
#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : SshTunnelOut::SshTunnelOut() " << m_name;
#endif

    m_sshChannel = qssh2_channel_direct_tcpip(m_client->session(), "127.0.0.1", m_port);
    if(m_sshChannel == nullptr)
    {
        int ret = qssh2_session_last_error(m_client->session(), nullptr, nullptr, 0);
        if(ret != LIBSSH2_ERROR_CHANNEL_FAILURE)
        {
            qDebug() << "ERROR: Can't connect direct tcpip " << ret << " for port " << m_port;
        }
#if defined(DEBUG_SSHCHANNEL)
        else
        {
            qDebug() << "DEBUG: Can't connect direct tcpip " << ret << " for port " << m_port;
        }
#endif
        return;
    }

    QObject::connect(m_client,    &SshClient::sshDataReceived, this, &SshTunnelOut::sshDataReceived, Qt::QueuedConnection);
    QObject::connect(m_tcpsocket, &QTcpSocket::readyRead,      this, &SshTunnelOut::tcpDataReceived);
    QObject::connect(m_tcpsocket, &QTcpSocket::disconnected,   this, &SshTunnelOut::tcpDisconnected);
    QObject::connect(m_tcpsocket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &SshTunnelOut::displayError);

    m_opened = true;

#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : SshTunnelOut::SshTunnelOut() OK " << m_name;
#endif
    tcpDataReceived();
}

SshTunnelOut::~SshTunnelOut()
{
#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : ~SshTunnelOut() " << m_name;
#endif
    _stopSocket();
    _stopChannel();
}

QString SshTunnelOut::name() const
{
    return m_name;
}

void SshTunnelOut::sshDataReceived()
{
    ssize_t len = 0,wr = 0;
    int i;

    do
    {
        /* Read data from SSH */
        /*
         * In this case, we must not used qssh2_channel_read
         * beacause we don't need to ProcessEvent to be locked
         * We can return, we will be recall at the next sshDataReceived
         */
        len = libssh2_channel_read(m_sshChannel, m_dataSsh.data(), m_dataSsh.size());
        if(len == LIBSSH2_ERROR_EAGAIN)
        {
            return;
        }
        if (len < 0)
        {
            qDebug() << "ERROR : " << m_name << " remote failed to read (" << len << ")";
            return;
        }
        if(len == 0)
            return;

        /* Write data into output local socket */
        wr = 0;
        if(m_tcpsocket != nullptr)
        {
            while (wr < len)
            {
                i = m_tcpsocket->write( m_dataSsh.mid(wr, len));
                if (i <= 0)
                {
                    qDebug() << "ERROR : " << m_name << " local failed to write (" << i << ")";
                    return;
                }
                wr += i;
            }
        }
        else
        {
            if(m_opened) qDebug() << "ERROR : Data loose";
        }

        if (qssh2_channel_eof(m_sshChannel) && m_opened)
        {
#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : Disconnected from ssh";
#endif
            emit disconnected();
        }
    }
    while(len == m_dataSsh.size());
}

void SshTunnelOut::tcpDataReceived()
{
    qint64 len = 0;
    ssize_t wr = 0;
    ssize_t i = 0;

    if (m_tcpsocket == nullptr || m_sshChannel == nullptr)
    {
        qDebug() << "ERROR : SshTunnelOut(" << m_name << ") : received TCP data but not seems to be a valid Tcp socket or channel not ready";
        return;
    }

    do
    {
        /* Read data from local socket */
        len = m_tcpsocket->read(m_dataSocket.data(), m_dataSocket.size());
#ifndef ANDROID
        if (-EAGAIN == len)
        {
            break;
        }
        else
#endif
        if (len < 0)
        {
            qDebug() << "ERROR : " << m_name << " local failed to read (" << len << ")";
            return;
        }

        do
        {
            i = qssh2_channel_write(m_sshChannel, m_dataSocket.data(), static_cast<quint64>(len));
            if (i < 0)
            {
                qDebug() << "ERROR : " << m_name << " remote failed to write (" << i << ")";
                return;
            }
            wr += i;
        } while(i > 0 && wr < len);
    }
    while(len > 0);
}

void SshTunnelOut::tcpDisconnected()
{
#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : Disconnected from socket";
#endif
    emit disconnected();
}

bool SshTunnelOut::ready() const
{
    return m_opened;
}

void SshTunnelOut::displayError(QAbstractSocket::SocketError error)
{
    if(error != QAbstractSocket::RemoteHostClosedError)
    qDebug() << "ERROR : SshTunnelOut(" << m_name << ") : redirection socket error=" << error;
}
void SshTunnelOut::_stopChannel()
{
    if (m_sshChannel == nullptr)
        return;

    QObject::disconnect(m_client,    &SshClient::sshDataReceived, this, &SshTunnelOut::sshDataReceived);

    int ret = qssh2_channel_close(m_sshChannel);

    if(ret)
    {
#if defined(DEBUG_SSHCLIENT)
        qDebug() << "DEBUG : SshChannel() : Failed to channel_close: LIBSSH2_ERROR_SOCKET_SEND";
#endif
        return;
    }

    ret = qssh2_channel_wait_closed(m_sshChannel);
    if(ret)
    {
#if defined(DEBUG_SSHCLIENT)
        qDebug() << "DEBUG : SshChannel() : Failed to channel_wait_closed";
#endif
        return;
    }

    ret = qssh2_channel_free(m_sshChannel);
    if(ret)
    {
#if defined(DEBUG_SSHCLIENT)
        qDebug() << "DEBUG : SshChannel() : Failed to channel_free";
#endif
        return;
    }
    m_sshChannel = nullptr;
}

void SshTunnelOut::_stopSocket()
{
    if(m_tcpsocket)
    {
        QObject::disconnect(m_tcpsocket, &QTcpSocket::readyRead, this,  &SshTunnelOut::tcpDataReceived);
        QObject::disconnect(m_tcpsocket, SIGNAL(disconnected()),                        this, SLOT(tcpDisconnected()));
        QObject::disconnect(m_tcpsocket, SIGNAL(error(QAbstractSocket::SocketError)),   this, SLOT(displayError(QAbstractSocket::SocketError)));
        if(m_tcpsocket->state() == QAbstractSocket::ConnectedState)
        {
            m_tcpsocket->disconnectFromHost();
        }
        m_tcpsocket->deleteLater();
        m_tcpsocket = nullptr;
    }
}
<commit_msg>sshtunnelout: Add include errno to build with iOS and Android system<commit_after>#include "sshtunnelout.h"
#include "sshclient.h"
#include <errno.h>
#include <QTcpServer>
#include <QTcpSocket>
#include <QEventLoop>

SshTunnelOut::SshTunnelOut(SshClient *client, QTcpSocket *tcpSocket, QString port_identifier, quint16 port, QObject *parent):
    QObject(parent),
    m_opened(false),
    m_port(port),
    m_name(port_identifier),
    m_tcpsocket(tcpSocket),
    m_client(client),
    m_sshChannel(nullptr),
    m_dataSsh(16384, 0),
    m_dataSocket(16384, 0),
    m_callDepth(0)
{
#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : SshTunnelOut::SshTunnelOut() " << m_name;
#endif

    m_sshChannel = qssh2_channel_direct_tcpip(m_client->session(), "127.0.0.1", m_port);
    if(m_sshChannel == nullptr)
    {
        int ret = qssh2_session_last_error(m_client->session(), nullptr, nullptr, 0);
        if(ret != LIBSSH2_ERROR_CHANNEL_FAILURE)
        {
            qDebug() << "ERROR: Can't connect direct tcpip " << ret << " for port " << m_port;
        }
#if defined(DEBUG_SSHCHANNEL)
        else
        {
            qDebug() << "DEBUG: Can't connect direct tcpip " << ret << " for port " << m_port;
        }
#endif
        return;
    }

    QObject::connect(m_client,    &SshClient::sshDataReceived, this, &SshTunnelOut::sshDataReceived, Qt::QueuedConnection);
    QObject::connect(m_tcpsocket, &QTcpSocket::readyRead,      this, &SshTunnelOut::tcpDataReceived);
    QObject::connect(m_tcpsocket, &QTcpSocket::disconnected,   this, &SshTunnelOut::tcpDisconnected);
    QObject::connect(m_tcpsocket, QOverload<QAbstractSocket::SocketError>::of(&QAbstractSocket::error), this, &SshTunnelOut::displayError);

    m_opened = true;

#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : SshTunnelOut::SshTunnelOut() OK " << m_name;
#endif
    tcpDataReceived();
}

SshTunnelOut::~SshTunnelOut()
{
#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : ~SshTunnelOut() " << m_name;
#endif
    _stopSocket();
    _stopChannel();
}

QString SshTunnelOut::name() const
{
    return m_name;
}

void SshTunnelOut::sshDataReceived()
{
    ssize_t len = 0,wr = 0;
    int i;

    do
    {
        /* Read data from SSH */
        /*
         * In this case, we must not used qssh2_channel_read
         * beacause we don't need to ProcessEvent to be locked
         * We can return, we will be recall at the next sshDataReceived
         */
        len = libssh2_channel_read(m_sshChannel, m_dataSsh.data(), m_dataSsh.size());
        if(len == LIBSSH2_ERROR_EAGAIN)
        {
            return;
        }
        if (len < 0)
        {
            qDebug() << "ERROR : " << m_name << " remote failed to read (" << len << ")";
            return;
        }
        if(len == 0)
            return;

        /* Write data into output local socket */
        wr = 0;
        if(m_tcpsocket != nullptr)
        {
            while (wr < len)
            {
                i = m_tcpsocket->write( m_dataSsh.mid(wr, len));
                if (i <= 0)
                {
                    qDebug() << "ERROR : " << m_name << " local failed to write (" << i << ")";
                    return;
                }
                wr += i;
            }
        }
        else
        {
            if(m_opened) qDebug() << "ERROR : Data loose";
        }

        if (qssh2_channel_eof(m_sshChannel) && m_opened)
        {
#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : Disconnected from ssh";
#endif
            emit disconnected();
        }
    }
    while(len == m_dataSsh.size());
}

void SshTunnelOut::tcpDataReceived()
{
    qint64 len = 0;
    ssize_t wr = 0;
    ssize_t i = 0;

    if (m_tcpsocket == nullptr || m_sshChannel == nullptr)
    {
        qDebug() << "ERROR : SshTunnelOut(" << m_name << ") : received TCP data but not seems to be a valid Tcp socket or channel not ready";
        return;
    }

    do
    {
        /* Read data from local socket */
        len = m_tcpsocket->read(m_dataSocket.data(), m_dataSocket.size());
        if (-EAGAIN == len)
        {
            break;
        }
        else if (len < 0)
        {
            qDebug() << "ERROR : " << m_name << " local failed to read (" << len << ")";
            return;
        }

        do
        {
            i = qssh2_channel_write(m_sshChannel, m_dataSocket.data(), static_cast<quint64>(len));
            if (i < 0)
            {
                qDebug() << "ERROR : " << m_name << " remote failed to write (" << i << ")";
                return;
            }
            wr += i;
        } while(i > 0 && wr < len);
    }
    while(len > 0);
}

void SshTunnelOut::tcpDisconnected()
{
#if defined(DEBUG_SSHCHANNEL)
    qDebug() << "DEBUG : SshTunnelOut : Disconnected from socket";
#endif
    emit disconnected();
}

bool SshTunnelOut::ready() const
{
    return m_opened;
}

void SshTunnelOut::displayError(QAbstractSocket::SocketError error)
{
    if(error != QAbstractSocket::RemoteHostClosedError)
    qDebug() << "ERROR : SshTunnelOut(" << m_name << ") : redirection socket error=" << error;
}
void SshTunnelOut::_stopChannel()
{
    if (m_sshChannel == nullptr)
        return;

    QObject::disconnect(m_client,    &SshClient::sshDataReceived, this, &SshTunnelOut::sshDataReceived);

    int ret = qssh2_channel_close(m_sshChannel);

    if(ret)
    {
#if defined(DEBUG_SSHCLIENT)
        qDebug() << "DEBUG : SshChannel() : Failed to channel_close: LIBSSH2_ERROR_SOCKET_SEND";
#endif
        return;
    }

    ret = qssh2_channel_wait_closed(m_sshChannel);
    if(ret)
    {
#if defined(DEBUG_SSHCLIENT)
        qDebug() << "DEBUG : SshChannel() : Failed to channel_wait_closed";
#endif
        return;
    }

    ret = qssh2_channel_free(m_sshChannel);
    if(ret)
    {
#if defined(DEBUG_SSHCLIENT)
        qDebug() << "DEBUG : SshChannel() : Failed to channel_free";
#endif
        return;
    }
    m_sshChannel = nullptr;
}

void SshTunnelOut::_stopSocket()
{
    if(m_tcpsocket)
    {
        QObject::disconnect(m_tcpsocket, &QTcpSocket::readyRead, this,  &SshTunnelOut::tcpDataReceived);
        QObject::disconnect(m_tcpsocket, SIGNAL(disconnected()),                        this, SLOT(tcpDisconnected()));
        QObject::disconnect(m_tcpsocket, SIGNAL(error(QAbstractSocket::SocketError)),   this, SLOT(displayError(QAbstractSocket::SocketError)));
        if(m_tcpsocket->state() == QAbstractSocket::ConnectedState)
        {
            m_tcpsocket->disconnectFromHost();
        }
        m_tcpsocket->deleteLater();
        m_tcpsocket = nullptr;
    }
}
<|endoftext|>


<commit_before><commit_msg>typo, thanks Guest70165 :-)<commit_after><|endoftext|>


<commit_before>/*
MIT License

Copyright (c) 2017 Chris McArthur, prince.chrismc(at)gmail(dot)com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "Script.h"
#include <iostream>

// http://www.cplusplus.com/forum/general/102587/#msg551994
// https://stackoverflow.com/a/10044348/8480874
BOOL Script::ExecuteScript()
{
   STARTUPINFO si;
   PROCESS_INFORMATION pi;
   LPTSTR szCmdline = _tcsdup(std::wstring(L"cmd /C " + m_FileName).c_str());

   ZeroMemory(&si, sizeof(si));
   si.cb = sizeof(si);
   ZeroMemory(&pi, sizeof(pi));
   if (!CreateProcess(NULL, szCmdline,
      NULL, NULL, FALSE, 0, NULL, NULL,
      &si, &pi)
      )
   {
      printf("CreateProcess failed (%d)\n", GetLastError());
      return FALSE;
   }

   WaitForSingleObject(pi.hProcess, INFINITE);
   CloseHandle(pi.hProcess);
   CloseHandle(pi.hThread);

   return TRUE;
}

// https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534(v=vs.85).aspx
// https://stackoverflow.com/a/21606502/8480874
BOOL SetEnvVarScript::CreateScript()
{
   HANDLE hFile;

   std::wstring script = L"@ECHO OFF\n\n:: Setting Env Vars For COMP371\n";

   for (auto env_path : m_VarsAndPaths)
   {
      script += std::wstring(L"setx " + env_path.first + env_path.second + L" /m\n");
   }

   DWORD dwBytesToWrite = (DWORD)script.length();
   DWORD dwBytesWritten = 0;
   BOOL bErrorFlag = FALSE;

   hFile = CreateFile(m_FileName.c_str(),       // name of the write
      GENERIC_WRITE,                            // open for writing
      0,                                        // do not share
      NULL,                                     // default security
      CREATE_ALWAYS,                            // create new file only
      FILE_ATTRIBUTE_NORMAL,                    // normal file
      NULL);                                    // no attr. template

   if (hFile == INVALID_HANDLE_VALUE)
   {
      std::cout << "Terminal failure: Unable to create file \"" << m_FileName.c_str() << "\" for write.\n";
      return FALSE;
   }

   std::cout << "Writing " << dwBytesToWrite << " bytes to " << m_FileName.c_str() << ".\n";

   bErrorFlag = WriteFile(hFile,                // open file handle
      script.c_str(),                           // start of data to write
      dwBytesToWrite,                           // number of bytes to write
      &dwBytesWritten,                          // number of bytes that were written
      NULL);                                    // no overlapped structure

   if (FALSE == bErrorFlag)
   {
      printf("Terminal failure: Unable to write to file.\n");
      return FALSE;
   }
   else
   {
      if (dwBytesWritten != dwBytesToWrite)
      {
         // This is an error because a synchronous write that results in
         // success (WriteFile returns TRUE) should write all data as
         // requested. This would not necessarily be the case for
         // asynchronous writes.
         printf("Error: dwBytesWritten != dwBytesToWrite\n");
         return FALSE;
      }
      else
      {
         std::cout << "Wrote " << dwBytesToWrite << " bytes to " << m_FileName.c_str() << "successfully.\n";
      }
   }

   CloseHandle(hFile);
   return TRUE;
}
<commit_msg>correcting script writting<commit_after>/*
MIT License

Copyright (c) 2017 Chris McArthur, prince.chrismc(at)gmail(dot)com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "Script.h"
#include <iostream>

// http://www.cplusplus.com/forum/general/102587/#msg551994
// https://stackoverflow.com/a/10044348/8480874
BOOL Script::ExecuteScript()
{
   STARTUPINFO si;
   PROCESS_INFORMATION pi;
   LPTSTR szCmdline = _tcsdup(std::wstring(L"cmd /C " + m_FileName).c_str());

   ZeroMemory(&si, sizeof(si));
   si.cb = sizeof(si);
   ZeroMemory(&pi, sizeof(pi));
   if (!CreateProcess(NULL, szCmdline,
      NULL, NULL, FALSE, 0, NULL, NULL,
      &si, &pi)
      )
   {
      printf("CreateProcess failed (%d)\n", GetLastError());
      return FALSE;
   }

   WaitForSingleObject(pi.hProcess, INFINITE);
   CloseHandle(pi.hProcess);
   CloseHandle(pi.hThread);

   return TRUE;
}

// https://msdn.microsoft.com/en-us/library/windows/desktop/bb540534(v=vs.85).aspx
// https://stackoverflow.com/a/21606502/8480874
BOOL SetEnvVarScript::CreateScript()
{
   HANDLE hFile;

   std::wstring script = L"@ECHO OFF\n\n:: Setting Env Vars For COMP371\n";

   for (auto env_path : m_VarsAndPaths)
   {
      script += std::wstring(L"setx " + env_path.first + L" " + env_path.second + L" /m\n");
   }

   std::string buff = std::string(script.begin(), script.end());

   DWORD dwBytesToWrite = (DWORD)strlen(buff.c_str());
   DWORD dwBytesWritten = 0;
   BOOL bErrorFlag = FALSE;

   hFile = CreateFile(m_FileName.c_str(),       // name of the write
      GENERIC_WRITE,                            // open for writing
      0,                                        // do not share
      NULL,                                     // default security
      CREATE_ALWAYS,                            // create new file only
      FILE_ATTRIBUTE_NORMAL,                    // normal file
      NULL);                                    // no attr. template

   if (hFile == INVALID_HANDLE_VALUE)
   {
      std::cout << "Terminal failure: Unable to create file \"" << m_FileName.c_str() << "\" for write.\n";
      return FALSE;
   }

   std::cout << "Writing " << dwBytesToWrite << " bytes to " << m_FileName.c_str() << ".\n";

   bErrorFlag = WriteFile(hFile,                // open file handle
      buff.c_str(),                             // start of data to write
      dwBytesToWrite,                           // number of bytes to write
      &dwBytesWritten,                          // number of bytes that were written
      NULL);                                    // no overlapped structure

   if (FALSE == bErrorFlag)
   {
      printf("Terminal failure: Unable to write to file.\n");
      return FALSE;
   }
   else
   {
      if (dwBytesWritten != dwBytesToWrite)
      {
         // This is an error because a synchronous write that results in
         // success (WriteFile returns TRUE) should write all data as
         // requested. This would not necessarily be the case for
         // asynchronous writes.
         printf("Error: dwBytesWritten != dwBytesToWrite\n");
         return FALSE;
      }
      else
      {
         std::cout << "Wrote " << dwBytesToWrite << " bytes to " << m_FileName.c_str() << "successfully.\n";
      }
   }

   CloseHandle(hFile);
   return TRUE;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <QmitkFunctionalityTesting.h>

#include <QmitkFctMediator.h>

#include <qapplication.h>
#include <qtimer.h>
#include <qwidgetlist.h>
#include <qobjectlist.h>
#include <qmessagebox.h>

#include <stdlib.h>
#include <iostream>

QmitkFunctionalityTesting::QmitkFunctionalityTesting( QmitkFctMediator* qfm, QObject * parent, const char * name )
  : QObject(parent, name), m_QmitkFctMediator(qfm)
{
  QObject::connect( &m_ActivateTimer, SIGNAL(timeout()), this, SLOT(ActivateNextFunctionality()) );
  QObject::connect( &m_CloseMessagesTimer, SIGNAL(timeout()), this, SLOT(CloseFirstMessageBox()) );
}

QmitkFunctionalityTesting::~QmitkFunctionalityTesting()
{

}

void QmitkFunctionalityTesting::CloseFirstMessageBox() {
    bool boxClosed = false;
    QWidgetList* topWidgets = QApplication::topLevelWidgets();
    QWidgetListIt topWidgetsIt(*topWidgets);
    QWidget* widget;
    while ( ( widget = topWidgetsIt.current()) != 0 ) {
       ++topWidgetsIt;
       if (widget->isA("QMessageBox")) {
        std::cout << "Found a toplevel message box! Give it a parent! Closing it ..." << std::endl;
         ((QMessageBox*)widget)->close();
         boxClosed=true;
         break;
       }
    QObjectList *l = widget->queryList( "QMessageBox" );
    QObjectListIt it( *l );
    QObject *obj;
    while ( (obj = it.current()) != 0 ) {
        ++it;
        std::cout << "Found a message box! Closing it ..." << std::endl;
        ((QMessageBox*)obj)->close();
        boxClosed = true;
        break;
    }
    delete l; // delete the list, not the objects
    if (boxClosed) {
      break;
    }
  }
  delete topWidgets;
  if (boxClosed) {
    // let everything redraw and call self
    m_CloseMessagesTimer.start(5000,true);
  } else {
    std::cout << "No message box closed" << std::endl;
  }
}

void QmitkFunctionalityTesting::ActivateNextFunctionality()
{
  // last one passed
  std::cout<<"[PASSED]"<<std::endl;

#ifdef BUILD_TESTING
  std::cout << "GUI test for \"" << m_QmitkFctMediator->GetActiveFunctionality()->className() <<"\": "<< std::flush;
  QmitkFunctionality* activeFunctionality = m_QmitkFctMediator->GetActiveFunctionality();
  if (activeFunctionality)
  {
    if ( activeFunctionality->TestYourself() )
    {
      std::cout<<"[PASSED]"<<std::endl;
    }
    else
    {
      std::cout<<"[FAILED]"<<std::endl;
      ++m_NumberOfFunctionalitiesFailed;
      m_NamesOfFailedFunctionalities.push_back( activeFunctionality->className() );
    }
  }
#endif

  // activate next functionality
  int nextId = m_QmitkFctMediator->GetActiveFunctionalityId()+1;
  QmitkFunctionality * nextFunctionality = m_QmitkFctMediator->GetFunctionalityById(nextId);
  if(nextFunctionality != NULL)
  {
    std::cout << "Activating \"" << nextFunctionality->className() <<"\" "<< std::flush;
    m_CloseMessagesTimer.start(5000,true); // close message boxes if RaiseFunctionality doesn't return
    m_QmitkFctMediator->RaiseFunctionality(nextId);
    m_CloseMessagesTimer.stop();
    m_ActivateTimer.start(2000,true); // after redraw activate next
  }
  else
  {
    qApp->quit();
  }
}

int StartQmitkFunctionalityTesting(QmitkFctMediator* qfm)
{
  QmitkFunctionalityTesting *testing = new QmitkFunctionalityTesting(qfm);
  testing->m_NumberOfFunctionalitiesFailed = 0;

  QTimer::singleShot(2000,testing,SLOT(ActivateNextFunctionality())); // 2 seconds single-shot timer
  testing->m_CloseMessagesTimer.start(5000,true); // close message boxes if RaiseFunctionality doesn't return

  std::cout << "Starting QmitkFunctionalityTesting ... " << std::endl;
  if (qfm->GetActiveFunctionality()) {
    std::cout << "Activating \"" << qfm->GetActiveFunctionality()->className() <<"\": "<< std::flush;
  }
  else
  {
    std::cout << "No active functionality yet ..." << std::endl << std::flush;
  }
  qApp->exec();

  if (testing->m_NumberOfFunctionalitiesFailed > 0)
  {
    std::cout<<"No crashes, but " << testing->m_NumberOfFunctionalitiesFailed << " functionalities failed during testing themselves:" <<std::endl;
    for ( std::list<std::string>::iterator iter = testing->m_NamesOfFailedFunctionalities.begin();
          iter != testing->m_NamesOfFailedFunctionalities.end();
          ++iter )
    {
      std::cout << *iter << std::endl;
    }
    std::cout<<"Test done [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout<<"Test done [PASSED]"<<std::endl;
    return EXIT_SUCCESS;
  }
}
<commit_msg>FIX: Missing header<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Module:    $RCSfile$
Language:  C++
Date:      $Date$
Version:   $Revision$

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include <QmitkFunctionalityTesting.h>

#include <QmitkFctMediator.h>

#include <qapplication.h>
#include <qtimer.h>
#include <qwidgetlist.h>
#include <qobjectlist.h>
#include <qmessagebox.h>

#include <stdlib.h>
#include <iostream>

#include <mitkTestingConfig.h>

QmitkFunctionalityTesting::QmitkFunctionalityTesting( QmitkFctMediator* qfm, QObject * parent, const char * name )
  : QObject(parent, name), m_QmitkFctMediator(qfm)
{
  QObject::connect( &m_ActivateTimer, SIGNAL(timeout()), this, SLOT(ActivateNextFunctionality()) );
  QObject::connect( &m_CloseMessagesTimer, SIGNAL(timeout()), this, SLOT(CloseFirstMessageBox()) );
}

QmitkFunctionalityTesting::~QmitkFunctionalityTesting()
{

}

void QmitkFunctionalityTesting::CloseFirstMessageBox() {
    bool boxClosed = false;
    QWidgetList* topWidgets = QApplication::topLevelWidgets();
    QWidgetListIt topWidgetsIt(*topWidgets);
    QWidget* widget;
    while ( ( widget = topWidgetsIt.current()) != 0 ) {
       ++topWidgetsIt;
       if (widget->isA("QMessageBox")) {
        std::cout << "Found a toplevel message box! Give it a parent! Closing it ..." << std::endl;
         ((QMessageBox*)widget)->close();
         boxClosed=true;
         break;
       }
    QObjectList *l = widget->queryList( "QMessageBox" );
    QObjectListIt it( *l );
    QObject *obj;
    while ( (obj = it.current()) != 0 ) {
        ++it;
        std::cout << "Found a message box! Closing it ..." << std::endl;
        ((QMessageBox*)obj)->close();
        boxClosed = true;
        break;
    }
    delete l; // delete the list, not the objects
    if (boxClosed) {
      break;
    }
  }
  delete topWidgets;
  if (boxClosed) {
    // let everything redraw and call self
    m_CloseMessagesTimer.start(5000,true);
  } else {
    std::cout << "No message box closed" << std::endl;
  }
}

void QmitkFunctionalityTesting::ActivateNextFunctionality()
{
  // last one passed
  std::cout<<"[PASSED]"<<std::endl;

#ifdef BUILD_TESTING
  std::cout << "GUI test for \"" << m_QmitkFctMediator->GetActiveFunctionality()->className() <<"\": "<< std::flush;
  QmitkFunctionality* activeFunctionality = m_QmitkFctMediator->GetActiveFunctionality();
  if (activeFunctionality)
  {
    if ( activeFunctionality->TestYourself() )
    {
      std::cout<<"[PASSED]"<<std::endl;
    }
    else
    {
      std::cout<<"[FAILED]"<<std::endl;
      ++m_NumberOfFunctionalitiesFailed;
      m_NamesOfFailedFunctionalities.push_back( activeFunctionality->className() );
    }
  }
#endif

  // activate next functionality
  int nextId = m_QmitkFctMediator->GetActiveFunctionalityId()+1;
  QmitkFunctionality * nextFunctionality = m_QmitkFctMediator->GetFunctionalityById(nextId);
  if(nextFunctionality != NULL)
  {
    std::cout << "Activating \"" << nextFunctionality->className() <<"\" "<< std::flush;
    m_CloseMessagesTimer.start(5000,true); // close message boxes if RaiseFunctionality doesn't return
    m_QmitkFctMediator->RaiseFunctionality(nextId);
    m_CloseMessagesTimer.stop();
    m_ActivateTimer.start(2000,true); // after redraw activate next
  }
  else
  {
    qApp->quit();
  }
}

int StartQmitkFunctionalityTesting(QmitkFctMediator* qfm)
{
  QmitkFunctionalityTesting *testing = new QmitkFunctionalityTesting(qfm);
  testing->m_NumberOfFunctionalitiesFailed = 0;

  QTimer::singleShot(2000,testing,SLOT(ActivateNextFunctionality())); // 2 seconds single-shot timer
  testing->m_CloseMessagesTimer.start(5000,true); // close message boxes if RaiseFunctionality doesn't return

  std::cout << "Starting QmitkFunctionalityTesting ... " << std::endl;
  if (qfm->GetActiveFunctionality()) {
    std::cout << "Activating \"" << qfm->GetActiveFunctionality()->className() <<"\": "<< std::flush;
  }
  else
  {
    std::cout << "No active functionality yet ..." << std::endl << std::flush;
  }
  qApp->exec();

  if (testing->m_NumberOfFunctionalitiesFailed > 0)
  {
    std::cout<<"No crashes, but " << testing->m_NumberOfFunctionalitiesFailed << " functionalities failed during testing themselves:" <<std::endl;
    for ( std::list<std::string>::iterator iter = testing->m_NamesOfFailedFunctionalities.begin();
          iter != testing->m_NamesOfFailedFunctionalities.end();
          ++iter )
    {
      std::cout << *iter << std::endl;
    }
    std::cout<<"Test done [FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  else
  {
    std::cout<<"Test done [PASSED]"<<std::endl;
    return EXIT_SUCCESS;
  }
}
<|endoftext|>