<commit_before>//===--- OwnershipModelEliminator.cpp - Eliminate SILOwnership Instr. -----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
///  \file
///
///  This file contains a small pass that lowers SIL ownership instructions to
///  their constituent operations. This will enable us to separate
///  implementation
///  of Semantic ARC in SIL and SILGen from ensuring that all of the optimizer
///  passes respect Semantic ARC. This is done by running this pass right after
///  SILGen and as the pass pipeline is updated, moving this pass further and
///  further back in the pipeline.
///
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-ownership-model-eliminator"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILVisitor.h"

using namespace swift;

//===----------------------------------------------------------------------===//
//                               Implementation
//===----------------------------------------------------------------------===//

namespace {

struct OwnershipModelEliminatorVisitor
    : SILInstructionVisitor<OwnershipModelEliminatorVisitor, bool> {
  SILBuilder &B;

  OwnershipModelEliminatorVisitor(SILBuilder &B) : B(B) {}
  void beforeVisit(ValueBase *V) {
    auto *I = cast<SILInstruction>(V);
    B.setInsertionPoint(I);
    B.setCurrentDebugScope(I->getDebugScope());
  }

  bool visitValueBase(ValueBase *V) { return false; }
  bool visitLoadInst(LoadInst *LI);
  bool visitStoreInst(StoreInst *SI);
  bool visitCopyValueInst(CopyValueInst *CVI);
  bool visitDestroyValueInst(DestroyValueInst *DVI);
  bool visitLoadBorrowInst(LoadBorrowInst *LBI);
  bool visitEndBorrowInst(EndBorrowInst *EBI) {
    EBI->eraseFromParent();
    return true;
  }
};

} // end anonymous namespace

bool OwnershipModelEliminatorVisitor::visitLoadInst(LoadInst *LI) {
  auto Qualifier = LI->getOwnershipQualifier();

  // If the qualifier is unqualified, there is nothing further to do
  // here. Just return.
  if (Qualifier == LoadOwnershipQualifier::Unqualified)
    return false;

  // Otherwise, we need to break down the load inst into its unqualified
  // components.
  auto *UnqualifiedLoad = B.createLoad(LI->getLoc(), LI->getOperand());

  // If we have a copy, insert a retain_value. All other copies do not require
  // more work.
  if (Qualifier == LoadOwnershipQualifier::Copy) {
    B.createRetainValue(UnqualifiedLoad->getLoc(), UnqualifiedLoad,
                        Atomicity::Atomic);
  }

  // Then remove the qualified load and use the unqualified load as the def of
  // all of LI's uses.
  LI->replaceAllUsesWith(UnqualifiedLoad);
  LI->eraseFromParent();
  return true;
}

bool OwnershipModelEliminatorVisitor::visitStoreInst(StoreInst *SI) {
  auto Qualifier = SI->getOwnershipQualifier();

  // If the qualifier is unqualified, there is nothing further to do
  // here. Just return.
  if (Qualifier == StoreOwnershipQualifier::Unqualified)
    return false;

  // Otherwise, we need to break down the store.
  if (Qualifier != StoreOwnershipQualifier::Assign) {
    // If the ownership qualifier is not an assign, we can just emit an
    // unqualified store.
    B.createStore(SI->getLoc(), SI->getSrc(), SI->getDest());
  } else {
    // If the ownership qualifier is [assign], then we need to eliminate the
    // old value.
    //
    // 1. Load old value.
    // 2. Store new value.
    // 3. Release old value.
    auto *Old = B.createLoad(SI->getLoc(), SI->getDest());
    B.createStore(SI->getLoc(), SI->getSrc(), SI->getDest());
    B.createReleaseValue(SI->getLoc(), Old, Atomicity::Atomic);
  }

  // Then remove the qualified store.
  SI->eraseFromParent();
  return true;
}

bool
OwnershipModelEliminatorVisitor::visitLoadBorrowInst(LoadBorrowInst *LBI) {
  // Break down the load borrow into an unqualified load.
  auto *UnqualifiedLoad = B.createLoad(LBI->getLoc(), LBI->getOperand());

  // Then remove the qualified load and use the unqualified load as the def of
  // all of LI's uses.
  LBI->replaceAllUsesWith(UnqualifiedLoad);
  LBI->eraseFromParent();
  return true;
}

bool OwnershipModelEliminatorVisitor::visitCopyValueInst(CopyValueInst *CVI) {
  B.createRetainValue(CVI->getLoc(), CVI->getOperand(), Atomicity::Atomic);
  CVI->replaceAllUsesWith(CVI->getOperand());
  CVI->eraseFromParent();
  return true;
}

bool OwnershipModelEliminatorVisitor::visitDestroyValueInst(DestroyValueInst *DVI) {
  B.createReleaseValue(DVI->getLoc(), DVI->getOperand(), Atomicity::Atomic);
  DVI->eraseFromParent();
  return true;
}

//===----------------------------------------------------------------------===//
//                           Top Level Entry Point
//===----------------------------------------------------------------------===//

namespace {

struct OwnershipModelEliminator : SILFunctionTransform {
  void run() override {
    SILFunction *F = getFunction();

    // Set F to have unqualified ownership.
    F->setUnqualifiedOwnership();

    bool MadeChange = false;
    SILBuilder B(*F);
    OwnershipModelEliminatorVisitor Visitor(B);

    for (auto &BB : *F) {
      for (auto II = BB.begin(), IE = BB.end(); II != IE;) {
        // Since we are going to be potentially removing instructions, we need
        // to make sure to grab out instruction and increment first.
        SILInstruction *I = &*II;
        ++II;

        MadeChange |= Visitor.visit(I);
      }
    }

    if (MadeChange) {
      // If we made any changes, we just changed instructions, so invalidate
      // that analysis.
      invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
    }
  }

  StringRef getName() override { return "Ownership Model Eliminator"; }
};

} // end anonymous namespace

SILTransform *swift::createOwnershipModelEliminator() {
  return new OwnershipModelEliminator();
}
<commit_msg>[semantic-arc] Make sure to use TypeLowering methods in the OwnershipModelEliminator when creating lowered ARC operations.<commit_after>//===--- OwnershipModelEliminator.cpp - Eliminate SILOwnership Instr. -----===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
///
///  \file
///
///  This file contains a small pass that lowers SIL ownership instructions to
///  their constituent operations. This will enable us to separate
///  implementation
///  of Semantic ARC in SIL and SILGen from ensuring that all of the optimizer
///  passes respect Semantic ARC. This is done by running this pass right after
///  SILGen and as the pass pipeline is updated, moving this pass further and
///  further back in the pipeline.
///
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "sil-ownership-model-eliminator"
#include "swift/SILOptimizer/PassManager/Transforms.h"
#include "swift/SIL/SILBuilder.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILVisitor.h"

using namespace swift;

//===----------------------------------------------------------------------===//
//                               Implementation
//===----------------------------------------------------------------------===//

namespace {

struct OwnershipModelEliminatorVisitor
    : SILInstructionVisitor<OwnershipModelEliminatorVisitor, bool> {
  SILBuilder &B;

  OwnershipModelEliminatorVisitor(SILBuilder &B) : B(B) {}
  void beforeVisit(ValueBase *V) {
    auto *I = cast<SILInstruction>(V);
    B.setInsertionPoint(I);
    B.setCurrentDebugScope(I->getDebugScope());
  }

  bool visitValueBase(ValueBase *V) { return false; }
  bool visitLoadInst(LoadInst *LI);
  bool visitStoreInst(StoreInst *SI);
  bool visitCopyValueInst(CopyValueInst *CVI);
  bool visitDestroyValueInst(DestroyValueInst *DVI);
  bool visitLoadBorrowInst(LoadBorrowInst *LBI);
  bool visitEndBorrowInst(EndBorrowInst *EBI) {
    EBI->eraseFromParent();
    return true;
  }
};

} // end anonymous namespace

bool OwnershipModelEliminatorVisitor::visitLoadInst(LoadInst *LI) {
  auto Qualifier = LI->getOwnershipQualifier();

  // If the qualifier is unqualified, there is nothing further to do
  // here. Just return.
  if (Qualifier == LoadOwnershipQualifier::Unqualified)
    return false;

  // Otherwise, we need to break down the load inst into its unqualified
  // components.
  auto *UnqualifiedLoad = B.createLoad(LI->getLoc(), LI->getOperand());

  // If we have a copy, insert a retain_value. All other copies do not require
  // more work.
  if (Qualifier == LoadOwnershipQualifier::Copy) {
    B.emitCopyValueOperation(UnqualifiedLoad->getLoc(), UnqualifiedLoad);
  }

  // Then remove the qualified load and use the unqualified load as the def of
  // all of LI's uses.
  LI->replaceAllUsesWith(UnqualifiedLoad);
  LI->eraseFromParent();
  return true;
}

bool OwnershipModelEliminatorVisitor::visitStoreInst(StoreInst *SI) {
  auto Qualifier = SI->getOwnershipQualifier();

  // If the qualifier is unqualified, there is nothing further to do
  // here. Just return.
  if (Qualifier == StoreOwnershipQualifier::Unqualified)
    return false;

  // Otherwise, we need to break down the store.
  if (Qualifier != StoreOwnershipQualifier::Assign) {
    // If the ownership qualifier is not an assign, we can just emit an
    // unqualified store.
    B.createStore(SI->getLoc(), SI->getSrc(), SI->getDest());
  } else {
    // If the ownership qualifier is [assign], then we need to eliminate the
    // old value.
    //
    // 1. Load old value.
    // 2. Store new value.
    // 3. Release old value.
    auto *Old = B.createLoad(SI->getLoc(), SI->getDest());
    B.createStore(SI->getLoc(), SI->getSrc(), SI->getDest());
    B.emitDestroyValueOperation(SI->getLoc(), Old);
  }

  // Then remove the qualified store.
  SI->eraseFromParent();
  return true;
}

bool
OwnershipModelEliminatorVisitor::visitLoadBorrowInst(LoadBorrowInst *LBI) {
  // Break down the load borrow into an unqualified load.
  auto *UnqualifiedLoad = B.createLoad(LBI->getLoc(), LBI->getOperand());

  // Then remove the qualified load and use the unqualified load as the def of
  // all of LI's uses.
  LBI->replaceAllUsesWith(UnqualifiedLoad);
  LBI->eraseFromParent();
  return true;
}

bool OwnershipModelEliminatorVisitor::visitCopyValueInst(CopyValueInst *CVI) {
  // Now that we have set the unqualified ownership flag, destroy value
  // operation will delegate to the appropriate strong_release, etc.
  B.emitCopyValueOperation(CVI->getLoc(), CVI->getOperand());
  CVI->replaceAllUsesWith(CVI->getOperand());
  CVI->eraseFromParent();
  return true;
}

bool OwnershipModelEliminatorVisitor::visitDestroyValueInst(DestroyValueInst *DVI) {
  // Now that we have set the unqualified ownership flag, destroy value
  // operation will delegate to the appropriate strong_release, etc.
  B.emitDestroyValueOperation(DVI->getLoc(), DVI->getOperand());
  DVI->eraseFromParent();
  return true;
}

//===----------------------------------------------------------------------===//
//                           Top Level Entry Point
//===----------------------------------------------------------------------===//

namespace {

struct OwnershipModelEliminator : SILFunctionTransform {
  void run() override {
    SILFunction *F = getFunction();

    // Set F to have unqualified ownership.
    F->setUnqualifiedOwnership();

    bool MadeChange = false;
    SILBuilder B(*F);
    OwnershipModelEliminatorVisitor Visitor(B);

    for (auto &BB : *F) {
      for (auto II = BB.begin(), IE = BB.end(); II != IE;) {
        // Since we are going to be potentially removing instructions, we need
        // to make sure to grab out instruction and increment first.
        SILInstruction *I = &*II;
        ++II;

        MadeChange |= Visitor.visit(I);
      }
    }

    if (MadeChange) {
      // If we made any changes, we just changed instructions, so invalidate
      // that analysis.
      invalidateAnalysis(SILAnalysis::InvalidationKind::Instructions);
    }
  }

  StringRef getName() override { return "Ownership Model Eliminator"; }
};

} // end anonymous namespace

SILTransform *swift::createOwnershipModelEliminator() {
  return new OwnershipModelEliminator();
}
<|endoftext|>


<commit_before>/**
  ******************************************************************************
  * @file    main.c
  * @author  Ac6
  * @version V1.0
  * @date    01-December-2013
  * @brief   Default main function.
  ******************************************************************************
*/

#include "stm32f4xx.h"
#include "stm32f4xx_nucleo.h"
#include "ESP8266_UDP.h"

extern "C" void initialise_monitor_handles(void);

ESP8266_UDP *esp8266 = ESP8266_UDP::Instance();
IWDG_HandleTypeDef hiwdg;

extern "C" void HardFault_Handler(void)
{
	printf("hard fault\n");
}

extern "C" void DMA1_Stream1_IRQHandler(void)
{
	HAL_DMA_IRQHandler(&esp8266->hdma_usart3_rx);
}

uint32_t count = 0;

void IPD_Callback(uint8_t *data, uint16_t length) {
	//printf("IPD: %s\n", data);
}

extern "C" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
	//printf("a\n");
}

extern "C" void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) {
	//printf("a\n");
}

int main(void)
{
	HAL_Init();
	initialise_monitor_handles();

	printf("init\n");

	hiwdg.Instance = IWDG;
	hiwdg.Init.Prescaler = IWDG_PRESCALER_256;
	hiwdg.Init.Reload = 2047;

	if (HAL_IWDG_Init(&hiwdg) != HAL_OK)
	{
		printf("Could not start watchdog\n");
	}

	__GPIOA_CLK_ENABLE();
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.Pin = GPIO_PIN_5;
	GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
	GPIO_InitStructure.Pull = GPIO_NOPULL;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);

	// reset module
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_RESET);
	HAL_Delay(250);
	HAL_GPIO_WritePin(GPIOB, GPIO_PIN_7, GPIO_PIN_SET);

	while (!esp8266->ready)
		esp8266->WaitReady();

	esp8266->IPD_Callback = &IPD_Callback;
	//esp8266->output = true;
	esp8266->Init();

	printf("init complete\n");
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);

	while (true) {
		HAL_IWDG_Refresh(&hiwdg);
		esp8266->WaitReady(0);
	}
}
<commit_msg>For resetting ESP8266 module has been made a function<commit_after>/**
  ******************************************************************************
  * @file    main.c
  * @author  Ac6
  * @version V1.0
  * @date    01-December-2013
  * @brief   Default main function.
  ******************************************************************************
*/

#include "stm32f4xx.h"
#include "stm32f4xx_nucleo.h"
#include "ESP8266_UDP.h"

extern "C" void initialise_monitor_handles(void);

ESP8266_UDP *esp8266 = ESP8266_UDP::Instance();
IWDG_HandleTypeDef hiwdg;

extern "C" void HardFault_Handler(void)
{
	printf("hard fault\n");
}

extern "C" void DMA1_Stream1_IRQHandler(void)
{
	HAL_DMA_IRQHandler(&esp8266->hdma_usart3_rx);
}

uint32_t count = 0;

void IPD_Callback(uint8_t *data, uint16_t length) {
	//printf("IPD: %s\n", data);
}

extern "C" void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
	//printf("a\n");
}

extern "C" void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) {
	//printf("a\n");
}

int main(void)
{
	HAL_Init();
	initialise_monitor_handles();

	printf("init\n");

	hiwdg.Instance = IWDG;
	hiwdg.Init.Prescaler = IWDG_PRESCALER_256;
	hiwdg.Init.Reload = 2047;

	if (HAL_IWDG_Init(&hiwdg) != HAL_OK)
	{
		printf("Could not start watchdog\n");
	}

	__GPIOA_CLK_ENABLE();
	GPIO_InitTypeDef GPIO_InitStructure;
	GPIO_InitStructure.Pin = GPIO_PIN_5;
	GPIO_InitStructure.Mode = GPIO_MODE_OUTPUT_PP;
	GPIO_InitStructure.Speed = GPIO_SPEED_HIGH;
	GPIO_InitStructure.Pull = GPIO_NOPULL;
	HAL_GPIO_Init(GPIOA, &GPIO_InitStructure);

	esp8266->Reset();

	while (!esp8266->ready)
		esp8266->WaitReady();

	esp8266->IPD_Callback = &IPD_Callback;
	//esp8266->output = true;
	esp8266->Init();

	printf("init complete\n");
	HAL_GPIO_WritePin(GPIOA, GPIO_PIN_5, GPIO_PIN_SET);

	while (true) {
		HAL_IWDG_Refresh(&hiwdg);
		esp8266->WaitReady(0);
	}
}
<|endoftext|>


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

  Program:   Advanced Normalization Tools
  Module:    $RCSfile: MeasureImageSimilarity.cxx,v $
  Language:  C++
  Date:      $Date: 2009/01/05 20:09:47 $
  Version:   $Revision: 1.19 $

  Copyright (c) ConsortiumOfANTS. All rights reserved.
  See accompanying COPYING.txt or
 http://sourceforge.net/projects/advants/files/ANTS/ANTSCopyright.txt for

     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 "ReadWriteImage.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkAvantsMutualInformationRegistrationFunction.h"
#include "itkSpatialMutualInformationRegistrationFunction.h"
#include "itkProbabilisticRegistrationFunction.h"
#include "itkCrossCorrelationRegistrationFunction.h"
// #include "itkLandmarkCrossCorrelationRegistrationFunction.h"

template <unsigned int ImageDimension>
int MeasureImageSimilarity(unsigned int argc, char *argv[])
{
  typedef float                                                  PixelType;
  typedef itk::Vector<float, ImageDimension>                     VectorType;
  typedef itk::Image<VectorType, ImageDimension>                 FieldType;
  typedef itk::Image<PixelType, ImageDimension>                  ImageType;
  typedef itk::ImageFileWriter<ImageType>                        writertype;
  typedef typename ImageType::IndexType                          IndexType;
  typedef typename ImageType::SizeType                           SizeType;
  typedef typename ImageType::SpacingType                        SpacingType;
  typedef itk::AffineTransform<double, ImageDimension>           AffineTransformType;
  typedef itk::LinearInterpolateImageFunction<ImageType, double> InterpolatorType1;
  typedef itk::ImageRegionIteratorWithIndex<ImageType>           Iterator;

  typedef itk::Image<float, 2>                JointHistType;
  typedef itk::ImageFileWriter<JointHistType> jhwritertype;

// get command line params
  unsigned int argct = 2;
  unsigned int whichmetric = atoi(argv[argct]); argct++;
  std::string  fn1 = std::string(argv[argct]); argct++;
  std::string  fn2 = std::string(argv[argct]); argct++;
  std::string  logfilename = "";
  if( argc > argct )
    {
    logfilename = std::string(argv[argct]);
    }
  argct++;
  std::string imgfilename = "";
  if( argc > argct )
    {
    imgfilename = std::string(argv[argct]);
    }
  argct++;
  double targetvalue = 0;
  if( argc > argct )
    {
    targetvalue = atof(argv[argct]);
    }
  argct++;
  double epsilontolerance = 1.e20;
  if( argc > argct )
    {
    epsilontolerance = atof(argv[argct]);
    }
  argct++;

  typename ImageType::Pointer image1 = NULL;
  ReadImage<ImageType>(image1, fn1.c_str() );
  typename ImageType::Pointer image2 = NULL;
  ReadImage<ImageType>(image2, fn2.c_str() );

/*
  typedef itk::ImageRegionIteratorWithIndex<FieldType> VIterator;
  typename FieldType::Pointer field=FieldType::New();
  field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
  field->SetBufferedRegion( image1->GetLargestPossibleRegion() );
  field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
  field->Allocate();
  field->SetSpacing(image1->GetSpacing());
  field->SetOrigin(image1->GetOrigin());
  VectorType zero;
  zero.Fill(0);
  VIterator vfIter2( field,  field->GetLargestPossibleRegion() );
  for(  vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
    {
      IndexType index=vfIter2.GetIndex();
      vfIter2.Set(zero);
    }
*/
  typename ImageType::Pointer metricimg = ImageType::New();
  metricimg->SetRegions( image1->GetLargestPossibleRegion() );
  metricimg->Allocate();
  metricimg->SetSpacing(image1->GetSpacing() );
  metricimg->SetOrigin(image1->GetOrigin() );
  metricimg->SetDirection(image1->GetDirection() );
  Iterator iter( metricimg,  metricimg->GetLargestPossibleRegion() );
  for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
    {
    iter.Set(0);
    }

  typedef ImageType FixedImageType;
  typedef ImageType MovingImageType;
  typedef FieldType DisplacementFieldType;

  // Choose the similarity metric
  typedef itk::AvantsMutualInformationRegistrationFunction<FixedImageType, MovingImageType,
                                                           DisplacementFieldType>  MIMetricType;
  typedef itk::SpatialMutualInformationRegistrationFunction<FixedImageType, MovingImageType,
                                                            DisplacementFieldType> SMIMetricType;
  typedef itk::CrossCorrelationRegistrationFunction<FixedImageType, MovingImageType,
                                                    DisplacementFieldType>         CCMetricType;
  // typedef itk::LandmarkCrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DisplacementFieldType>
  // MetricType;
  // typename
  typename MIMetricType::Pointer mimet = MIMetricType::New();
  typename SMIMetricType::Pointer smimet = SMIMetricType::New();
  typename CCMetricType::Pointer ccmet = CCMetricType::New();

//  int nbins=32;

  typename CCMetricType::RadiusType hradius;
  typename CCMetricType::RadiusType ccradius;
  ccradius.Fill(4);
  typename MIMetricType::RadiusType miradius;
  miradius.Fill(0);

//  mimet->SetDisplacementField(field);
  mimet->SetFixedImage(image1);
  mimet->SetMovingImage(image2);
  mimet->SetRadius(miradius);
  mimet->SetGradientStep(1.e2);
  mimet->SetNormalizeGradient(false);

//  ccmet->SetDisplacementField(field);
  ccmet->SetFixedImage(image1);
  ccmet->SetMovingImage(image2);
  ccmet->SetRadius(ccradius);
  ccmet->SetGradientStep(1.e2);
  ccmet->SetNormalizeGradient(false);

  double      metricvalue = 0;
  std::string metricname = "";
  if( whichmetric  == 0 )
    {
    hradius = miradius;
    unsigned long ct = 0;
    for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
      {
      IndexType index = iter.GetIndex();
      double    fval = image1->GetPixel(index);
      double    mval = image2->GetPixel(index);
      metricvalue += fabs(fval - mval);
      metricimg->SetPixel(index, fabs(fval - mval) );
      ct++;
      }
    metricvalue /= (float)ct;
    metricname = "MSQ ";
    }
  else if( whichmetric == 1 ) // imagedifference
    {
    hradius = ccradius;
    metricname = "CC ";
    std::cout << metricname << std::endl;
    ccmet->InitializeIteration();
    metricimg = ccmet->MakeImage();
    metricvalue = ccmet->ComputeCrossCorrelation() * (1.0);
    }
  else if( whichmetric == 2 )
    {
    hradius = miradius;
    mimet->InitializeIteration();
    metricvalue = mimet->ComputeMutualInformation();
    metricname = "MI ";
    }
  else if( whichmetric == 3 )
    {
    hradius = miradius;
    smimet->InitializeIteration();
    metricvalue = smimet->ComputeSpatialMutualInformation();
    metricname = "SMI ";
    }
  std::cout << fn1 << " : " << fn2 << " => " <<  metricname << metricvalue << std::endl;
  if( logfilename.length() > 3 )
    {
    std::ofstream logfile;
    logfile.open(logfilename.c_str(), std::ofstream::app);
    if( logfile.good() )
      {
      logfile <<  fn1 << " : " << fn2 << " => " << metricname << metricvalue << std::endl;
      }
    else
      {
      std::cout << " cant open file ";
      }
    logfile.close();
    }

  if( imgfilename.length() > 3 )
    {
    std::cout << "Only Implemented for MSQ and CC " << std::endl;
    typedef itk::ImageFileWriter<ImageType> writertype;
    typename writertype::Pointer w = writertype::New();
    w->SetInput(metricimg);
    w->SetFileName(imgfilename.c_str() );
    w->Write(); //  met->WriteImages();

/*
  typename MetricType::NeighborhoodType   asamIt( hradius, field,field->GetLargestPossibleRegion());
  unsigned long ct = 0;
  double totval = 0;
  for(  vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
    {
      IndexType index=vfIter2.GetIndex();
      double val=0;
      asamIt.SetLocation(index);
      //      met->ComputeUpdate( asamIt,  gd);
      met->ComputeMetricAtPairB(index,  zero);
      metricimg->SetPixel(index, val);
      //if (ct % 10000 == 0)
      //        std::cout << val << " index " << index << std::endl;
      //      asamIt.SetLocation(index);
      //      totval+=met->localProbabilistic;
      ct++;
    }

  std::cout << " AvantsMI : " << totval/(double)ct << " E " <<  met->GetEnergy() <<  std::endl;
  std::cout << " write begin " << std::endl;

  std::cout << " write end " << std::endl;
*/
    }

  double diff = ( (double)metricvalue - (double) targetvalue);
  std::cout << " targetvalue " << targetvalue << " metricvalue " << metricvalue << " diff " << diff << " toler "
            << epsilontolerance << std::endl;

  if( diff < epsilontolerance )
    {
    return EXIT_SUCCESS;
    }
  else
    {
    return EXIT_FAILURE;
    }
}

int main(int argc, char *argv[])
{
  if( argc < 3 )
    {
    std::cout << "Basic useage ex: " << std::endl;
    std::cout << argv[0]
              <<
    " ImageDimension whichmetric image1.ext image2.ext {logfile} {outimage.ext}  {target-value}   {epsilon-tolerance}"
              << std::endl;
    std::cout << "  outimage (Not Implemented for MI yet)  and logfile are optional  " << std::endl;
    std::cout
      <<
    " target-value and epsilon-tolerance set goals for the metric value -- if the metric value is within epsilon-tolerance of the target-value, then the test succeeds "
      << std::endl;
    std::cout << "  Metric 0 - MeanSquareDifference, 1 - Cross-Correlation, 2-Mutual Information , 3-SMI " << std::endl;
    return 1;
    }

  int metricsuccess = EXIT_FAILURE;

  // Get the image dimension
  switch( atoi(argv[1]) )
    {
    case 2:
      {
      metricsuccess = MeasureImageSimilarity<2>(argc, argv);
      }
      break;
    case 3:
      {
      metricsuccess = MeasureImageSimilarity<3>(argc, argv);
      }
      break;
    default:
      std::cerr << "Unsupported dimension" << std::endl;
      exit( EXIT_FAILURE );
    }

  std::cout << " Failure? " << metricsuccess << std::endl;

  return metricsuccess;
}
<commit_msg>ENH: cc image metric update <commit_after>/*=========================================================================

  Program:   Advanced Normalization Tools
  Module:    $RCSfile: MeasureImageSimilarity.cxx,v $
  Language:  C++
  Date:      $Date: 2009/01/05 20:09:47 $
  Version:   $Revision: 1.19 $

  Copyright (c) ConsortiumOfANTS. All rights reserved.
  See accompanying COPYING.txt or
 http://sourceforge.net/projects/advants/files/ANTS/ANTSCopyright.txt for

     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 "ReadWriteImage.h"
#include "itkDiscreteGaussianImageFilter.h"
#include "itkAvantsMutualInformationRegistrationFunction.h"
#include "itkSpatialMutualInformationRegistrationFunction.h"
#include "itkProbabilisticRegistrationFunction.h"
#include "itkCrossCorrelationRegistrationFunction.h"
// #include "itkLandmarkCrossCorrelationRegistrationFunction.h"

template <unsigned int ImageDimension>
int MeasureImageSimilarity(unsigned int argc, char *argv[])
{
  typedef float                                                  PixelType;
  typedef itk::Vector<float, ImageDimension>                     VectorType;
  typedef itk::Image<VectorType, ImageDimension>                 FieldType;
  typedef itk::Image<PixelType, ImageDimension>                  ImageType;
  typedef itk::ImageFileWriter<ImageType>                        writertype;
  typedef typename ImageType::IndexType                          IndexType;
  typedef typename ImageType::SizeType                           SizeType;
  typedef typename ImageType::SpacingType                        SpacingType;
  typedef itk::AffineTransform<double, ImageDimension>           AffineTransformType;
  typedef itk::LinearInterpolateImageFunction<ImageType, double> InterpolatorType1;
  typedef itk::ImageRegionIteratorWithIndex<ImageType>           Iterator;

  typedef itk::Image<float, 2>                JointHistType;
  typedef itk::ImageFileWriter<JointHistType> jhwritertype;

// get command line params
  unsigned int argct = 2;
  unsigned int whichmetric = atoi(argv[argct]); argct++;
  std::string  fn1 = std::string(argv[argct]); argct++;
  std::string  fn2 = std::string(argv[argct]); argct++;
  std::string  logfilename = "";
  if( argc > argct )
    {
    logfilename = std::string(argv[argct]);
    }
  argct++;
  std::string imgfilename = "";
  if( argc > argct )
    {
    imgfilename = std::string(argv[argct]);
    }
  argct++;
  double targetvalue = 0;
  if( argc > argct )
    {
    targetvalue = atof(argv[argct]);
    }
  argct++;
  double epsilontolerance = 1.e20;
  if( argc > argct )
    {
    epsilontolerance = atof(argv[argct]);
    }
  argct++;

  typename ImageType::Pointer image1 = NULL;
  ReadImage<ImageType>(image1, fn1.c_str() );
  typename ImageType::Pointer image2 = NULL;
  ReadImage<ImageType>(image2, fn2.c_str() );

/*
  typedef itk::ImageRegionIteratorWithIndex<FieldType> VIterator;
  typename FieldType::Pointer field=FieldType::New();
  field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
  field->SetBufferedRegion( image1->GetLargestPossibleRegion() );
  field->SetLargestPossibleRegion( image1->GetLargestPossibleRegion() );
  field->Allocate();
  field->SetSpacing(image1->GetSpacing());
  field->SetOrigin(image1->GetOrigin());
  VectorType zero;
  zero.Fill(0);
  VIterator vfIter2( field,  field->GetLargestPossibleRegion() );
  for(  vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
    {
      IndexType index=vfIter2.GetIndex();
      vfIter2.Set(zero);
    }
*/
  typename ImageType::Pointer metricimg = ImageType::New();
  metricimg->SetRegions( image1->GetLargestPossibleRegion() );
  metricimg->Allocate();
  metricimg->SetSpacing(image1->GetSpacing() );
  metricimg->SetOrigin(image1->GetOrigin() );
  metricimg->SetDirection(image1->GetDirection() );
  Iterator iter( metricimg,  metricimg->GetLargestPossibleRegion() );
  for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
    {
    iter.Set(0);
    }

  typedef ImageType FixedImageType;
  typedef ImageType MovingImageType;
  typedef FieldType DisplacementFieldType;

  // Choose the similarity metric
  typedef itk::AvantsMutualInformationRegistrationFunction<FixedImageType, MovingImageType,
                                                           DisplacementFieldType>  MIMetricType;
  typedef itk::SpatialMutualInformationRegistrationFunction<FixedImageType, MovingImageType,
                                                            DisplacementFieldType> SMIMetricType;
  typedef itk::CrossCorrelationRegistrationFunction<FixedImageType, MovingImageType,
                                                    DisplacementFieldType>         CCMetricType;
  // typedef itk::LandmarkCrossCorrelationRegistrationFunction<FixedImageType,MovingImageType,DisplacementFieldType>
  // MetricType;
  // typename
  typename MIMetricType::Pointer mimet = MIMetricType::New();
  typename SMIMetricType::Pointer smimet = SMIMetricType::New();
  typename CCMetricType::Pointer ccmet = CCMetricType::New();

//  int nbins=32;

  typename CCMetricType::RadiusType hradius;
  typename CCMetricType::RadiusType ccradius;
  ccradius.Fill(4);
  typename MIMetricType::RadiusType miradius;
  miradius.Fill(0);

//  mimet->SetDisplacementField(field);
  mimet->SetFixedImage(image1);
  mimet->SetMovingImage(image2);
  mimet->SetRadius(miradius);
  mimet->SetGradientStep(1.e2);
  mimet->SetNormalizeGradient(false);

//  ccmet->SetDisplacementField(field);
  ccmet->SetFixedImage(image1);
  ccmet->SetMovingImage(image2);
  ccmet->SetRadius(ccradius);
  ccmet->SetGradientStep(1.e2);
  ccmet->SetNormalizeGradient(false);

  double      metricvalue = 0;
  std::string metricname = "";
  if( whichmetric  == 0 )
    {
    hradius = miradius;
    unsigned long ct = 0;
    for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
      {
      IndexType index = iter.GetIndex();
      double    fval = image1->GetPixel(index);
      double    mval = image2->GetPixel(index);
      metricvalue += fabs(fval - mval);
      metricimg->SetPixel(index, fabs(fval - mval) );
      ct++;
      }
    metricvalue /= (float)ct;
    metricname = "MSQ ";
    }
  else if( whichmetric == 1 ) // imagedifference
    {
    double ccval = 0;
    hradius = ccradius;
    metricname = "CC ";
    typedef itk::ConstNeighborhoodIterator<FixedImageType> ScanIteratorType;
    typename FixedImageType::RegionType region = image1->GetLargestPossibleRegion();
    ScanIteratorType   asamIt( hradius, image1, region);
    unsigned long      ct = 0;
    const unsigned int hoodlen = asamIt.Size();
    double             totval = 0;
    for(  iter.GoToBegin(); !iter.IsAtEnd(); ++iter )
      {
      IndexType index = iter.GetIndex();
      double    val = 0;
      double    fmip = 0, mmip = 0, ffip = 0;
      asamIt.SetLocation(index);
      for( unsigned int i = 0; i < asamIt.Size(); i++ )
        {
        IndexType locind = asamIt.GetIndex(i);
        if( region.IsInside( locind ) )
          {
          double f = image1->GetPixel(locind);
          double m = image2->GetPixel(locind);
          fmip += (f * m);  mmip += (m * m);  ffip += (f * f);
          }
        }
      double denom = mmip * ffip;
      if( denom == 0 )
        {
        val = 1;
        }
      else
        {
        val = fmip / sqrt(denom);
        }
      metricimg->SetPixel(index, val);
      // if (ct % 10000 == 0)
      //        std::cout << val << " index " << index << std::endl;
      //      asamIt.SetLocation(index);
      //      totval+=met->localProbabilistic;
      ccval += val;
      ct++;
      }
    if( ct >  0 )
      {
      metricvalue = ccval / ct;
      }
    else
      {
      metricvalue = 0;
      }
    /*
    std::cout << metricname << std::endl;
    ccmet->InitializeIteration();
    metricimg=ccmet->MakeImage();
    metricvalue=ccmet->ComputeCrossCorrelation()*(1.0);
    */
    }
  else if( whichmetric == 2 )
    {
    hradius = miradius;
    mimet->InitializeIteration();
    metricvalue = mimet->ComputeMutualInformation();
    metricname = "MI ";
    }
  else if( whichmetric == 3 )
    {
    hradius = miradius;
    smimet->InitializeIteration();
    metricvalue = smimet->ComputeSpatialMutualInformation();
    metricname = "SMI ";
    }
  std::cout << fn1 << " : " << fn2 << " => " <<  metricname << metricvalue << std::endl;
  if( logfilename.length() > 3 )
    {
    std::ofstream logfile;
    logfile.open(logfilename.c_str(), std::ofstream::app);
    if( logfile.good() )
      {
      logfile <<  fn1 << " : " << fn2 << " => " << metricname << metricvalue << std::endl;
      }
    else
      {
      std::cout << " cant open file ";
      }
    logfile.close();
    }

  if( imgfilename.length() > 3 )
    {
    std::cout << "Only Implemented for MSQ and CC " << std::endl;
    typedef itk::ImageFileWriter<ImageType> writertype;
    typename writertype::Pointer w = writertype::New();
    w->SetInput(metricimg);
    w->SetFileName(imgfilename.c_str() );
    w->Write(); //  met->WriteImages();

/*
  typename MetricType::NeighborhoodType   asamIt( hradius, field,field->GetLargestPossibleRegion());
  unsigned long ct = 0;
  double totval = 0;
  for(  vfIter2.GoToBegin(); !vfIter2.IsAtEnd(); ++vfIter2 )
    {
      IndexType index=vfIter2.GetIndex();
      double val=0;
      asamIt.SetLocation(index);
      //      met->ComputeUpdate( asamIt,  gd);
      met->ComputeMetricAtPairB(index,  zero);
      metricimg->SetPixel(index, val);
      //if (ct % 10000 == 0)
      //        std::cout << val << " index " << index << std::endl;
      //      asamIt.SetLocation(index);
      //      totval+=met->localProbabilistic;
      ct++;
    }

  std::cout << " AvantsMI : " << totval/(double)ct << " E " <<  met->GetEnergy() <<  std::endl;
  std::cout << " write begin " << std::endl;

  std::cout << " write end " << std::endl;
*/
    }

  double diff = ( (double)metricvalue - (double) targetvalue);
  std::cout << " targetvalue " << targetvalue << " metricvalue " << metricvalue << " diff " << diff << " toler "
            << epsilontolerance << std::endl;

  if( diff < epsilontolerance )
    {
    return EXIT_SUCCESS;
    }
  else
    {
    return EXIT_FAILURE;
    }
}

int main(int argc, char *argv[])
{
  if( argc < 3 )
    {
    std::cout << "Basic useage ex: " << std::endl;
    std::cout << argv[0]
              <<
    " ImageDimension whichmetric image1.ext image2.ext {logfile} {outimage.ext}  {target-value}   {epsilon-tolerance}"
              << std::endl;
    std::cout << "  outimage (Not Implemented for MI yet)  and logfile are optional  " << std::endl;
    std::cout
      <<
    " target-value and epsilon-tolerance set goals for the metric value -- if the metric value is within epsilon-tolerance of the target-value, then the test succeeds "
      << std::endl;
    std::cout << "  Metric 0 - MeanSquareDifference, 1 - Cross-Correlation, 2-Mutual Information , 3-SMI " << std::endl;
    return 1;
    }

  int metricsuccess = EXIT_FAILURE;

  // Get the image dimension
  switch( atoi(argv[1]) )
    {
    case 2:
      {
      metricsuccess = MeasureImageSimilarity<2>(argc, argv);
      }
      break;
    case 3:
      {
      metricsuccess = MeasureImageSimilarity<3>(argc, argv);
      }
      break;
    default:
      std::cerr << "Unsupported dimension" << std::endl;
      exit( EXIT_FAILURE );
    }

  std::cout << " Failure? " << metricsuccess << std::endl;

  return metricsuccess;
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkImageToImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.

=========================================================================*/
#include "vtkImageToImageFilter.h"

#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkMultiThreader.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"

vtkCxxRevisionMacro(vtkImageToImageFilter, "1.53");

//----------------------------------------------------------------------------
vtkImageToImageFilter::vtkImageToImageFilter()
{
  this->NumberOfRequiredInputs = 1;
  this->Bypass = 0;
  this->Threader = vtkMultiThreader::New();
  this->NumberOfThreads = this->Threader->GetNumberOfThreads();
  this->InputScalarsSelection = NULL;
}

//----------------------------------------------------------------------------
vtkImageToImageFilter::~vtkImageToImageFilter()
{
  this->Threader->Delete();
  this->SetInputScalarsSelection(NULL);
}

//----------------------------------------------------------------------------
void vtkImageToImageFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "NumberOfThreads: " << this->NumberOfThreads << "\n";

  if ( this->Bypass )
    {
    os << indent << "Bypass: On\n";
    }
  else
    {
    os << indent << "Bypass: Off\n";
    }
}

//----------------------------------------------------------------------------
void vtkImageToImageFilter::SetInput(vtkImageData *input)
{
  this->vtkProcessObject::SetNthInput(0, input);
}

//----------------------------------------------------------------------------
vtkImageData *vtkImageToImageFilter::GetInput()
{
  if (this->NumberOfInputs < 1)
    {
    return NULL;
    }

  return (vtkImageData *)(this->Inputs[0]);
}

//----------------------------------------------------------------------------
// This method can be overriden in a subclass to compute the output
// Information: WholeExtent, Spacing, Origin, ScalarType and
// NumberOfScalarComponents.
void vtkImageToImageFilter::ExecuteInformation()
{
  vtkImageData *input = this->GetInput();
  vtkImageData *output = this->GetOutput();

  // Make sure the Input has been set.
  if ( input == NULL || output == NULL)
    {
    vtkErrorMacro(<< "ExecuteInformation: Input is not set.");
    return;
    }

  // Start with some defaults.
  output->CopyTypeSpecificInformation( input );

  vtkDataArray *inArray = input->GetPointData()->GetScalars(this->InputScalarsSelection);
  if (inArray)
    {
    output->SetScalarType(inArray->GetDataType());
    }

  // take this opportunity to modify the defaults

  this->ExecuteInformation(input, output);
}

//----------------------------------------------------------------------------
void vtkImageToImageFilter::ExecuteInformation(
           vtkImageData *vtkNotUsed(inData), vtkImageData *vtkNotUsed(outData))
{
}

//----------------------------------------------------------------------------

// Call the alternate version of this method, and use the returned input
// update extent for all inputs
void vtkImageToImageFilter::ComputeInputUpdateExtents( vtkDataObject *output )
{
  int outExt[6], inExt[6];

  output->GetUpdateExtent( outExt );

  if (this->NumberOfInputs)
    {
    this->ComputeInputUpdateExtent( inExt, outExt );
    }

  for (int idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] != NULL)
      {
      if (this->Inputs[idx]->GetRequestExactExtent())
        {
        int *currentExt = this->Inputs[idx]->GetUpdateExtent();
        for (int i = 0; i < 6; i += 2)
          {
          if (inExt[i] < currentExt[i] ||
              inExt[i+1] > currentExt[i+1])
            {
            this->Inputs[idx]->SetUpdateExtent( inExt );
            break;
            }
          }
        }
      else
        {
        this->Inputs[idx]->SetUpdateExtent( inExt );
        }
      }
    }
}

// By default, simply set the input update extent to match the given output
// extent
void vtkImageToImageFilter::ComputeInputUpdateExtent( int inExt[6],
                                                      int outExt[6] )
{
  memcpy(inExt,outExt,sizeof(int)*6);
}

struct vtkImageThreadStruct
{
  vtkImageToImageFilter *Filter;
  vtkImageData   *Input;
  vtkImageData   *Output;
};

// this mess is really a simple function. All it does is call
// the ThreadedExecute method after setting the correct
// extent for this thread. Its just a pain to calculate
// the correct extent.
VTK_THREAD_RETURN_TYPE vtkImageThreadedExecute( void *arg )
{
  vtkImageThreadStruct *str;
  int ext[6], splitExt[6], total;
  int threadId, threadCount;
  vtkImageData *output;

  threadId = ((vtkMultiThreader::ThreadInfo *)(arg))->ThreadID;
  threadCount = ((vtkMultiThreader::ThreadInfo *)(arg))->NumberOfThreads;

  str = (vtkImageThreadStruct *)(((vtkMultiThreader::ThreadInfo *)(arg))->UserData);
  output = str->Output;
  output->GetUpdateExtent( ext );

  // execute the actual method with appropriate extent
  // first find out how many pieces extent can be split into.
  total = str->Filter->SplitExtent(splitExt, ext, threadId, threadCount);
  //total = 1;

  if (threadId < total)
    {
    str->Filter->ThreadedExecute(str->Input, str->Output, splitExt, threadId);
    }
  // else
  //   {
  //   otherwise don't use this thread. Sometimes the threads dont
  //   break up very well and it is just as efficient to leave a
  //   few threads idle.
  //   }

  return VTK_THREAD_RETURN_VALUE;
}

//----------------------------------------------------------------------------
// For streaming and threads.  Splits output update extent into num pieces.
// This method needs to be called num times.  Results must not overlap for
// consistent starting extent.  Subclass can override this method.
// This method returns the number of peices resulting from a successful split.
// This can be from 1 to "total".
// If 1 is returned, the extent cannot be split.
int vtkImageToImageFilter::SplitExtent(int splitExt[6], int startExt[6],
                                       int num, int total)
{
  int splitAxis;
  int min, max;

  vtkDebugMacro("SplitExtent: ( " << startExt[0] << ", " << startExt[1] << ", "
                << startExt[2] << ", " << startExt[3] << ", "
                << startExt[4] << ", " << startExt[5] << "), "
                << num << " of " << total);

  // start with same extent
  memcpy(splitExt, startExt, 6 * sizeof(int));

  splitAxis = 2;
  min = startExt[4];
  max = startExt[5];
  while (min == max)
    {
    --splitAxis;
    if (splitAxis < 0)
      { // cannot split
      vtkDebugMacro("  Cannot Split");
      return 1;
      }
    min = startExt[splitAxis*2];
    max = startExt[splitAxis*2+1];
    }

  // determine the actual number of pieces that will be generated
  int range = max - min + 1;
  int valuesPerThread = (int)ceil(range/(double)total);
  int maxThreadIdUsed = (int)ceil(range/(double)valuesPerThread) - 1;
  if (num < maxThreadIdUsed)
    {
    splitExt[splitAxis*2] = splitExt[splitAxis*2] + num*valuesPerThread;
    splitExt[splitAxis*2+1] = splitExt[splitAxis*2] + valuesPerThread - 1;
    }
  if (num == maxThreadIdUsed)
    {
    splitExt[splitAxis*2] = splitExt[splitAxis*2] + num*valuesPerThread;
    }

  vtkDebugMacro("  Split Piece: ( " <<splitExt[0]<< ", " <<splitExt[1]<< ", "
                << splitExt[2] << ", " << splitExt[3] << ", "
                << splitExt[4] << ", " << splitExt[5] << ")");

  return maxThreadIdUsed + 1;
}

//----------------------------------------------------------------------------
vtkImageData *vtkImageToImageFilter::AllocateOutputData(vtkDataObject *out)
{
  vtkImageData *output = vtkImageData::SafeDownCast(out);
  vtkImageData *input = this->GetInput();
  int inExt[6];
  int outExt[6];
  vtkDataArray *inArray;
  vtkDataArray *outArray;

  input->GetExtent(inExt);
  output->SetExtent(output->GetUpdateExtent());
  output->GetExtent(outExt);

  // Do not copy the array we will be generating.
  inArray = input->GetPointData()->GetScalars(this->InputScalarsSelection);

  // Conditionally copy point and cell data.
  // Only copy if corresponding indexes refer to identical points.
  float *oIn = input->GetOrigin();
  float *sIn = input->GetSpacing();
  float *oOut = output->GetOrigin();
  float *sOut = output->GetSpacing();
  if (oIn[0] == oOut[0] && oIn[1] == oOut[1] && oIn[2] == oOut[2] &&
      sIn[0] == sOut[0] && sIn[1] == sOut[1] && sIn[2] == sOut[2])
    {
    output->GetPointData()->CopyAllOn();
    output->GetCellData()->CopyAllOn();
    // Scalar copy flag trumps the array copy flag.
    if (inArray == input->GetPointData()->GetScalars())
      {
      output->GetPointData()->CopyScalarsOff();
      }
    else
      {
      output->GetPointData()->CopyFieldOff(this->InputScalarsSelection);
      }

    // If the extents are the same, then pass the attribute data for efficiency.
    if (inExt[0] == outExt[0] && inExt[1] == outExt[1] &&
        inExt[2] == outExt[2] && inExt[3] == outExt[3] &&
        inExt[4] == outExt[4] && inExt[5] == outExt[5])
      {// Pass
      output->GetPointData()->PassData(input->GetPointData());
      output->GetCellData()->PassData(input->GetCellData());
      }
    else
      {// Copy
      // Copy the point data.
      output->GetPointData()->CopyAllocate(input->GetPointData(),
                                           output->GetNumberOfPoints());
      // Now Copy The cell data, but only if output is a subextent of the input.
      if (outExt[0] >= inExt[0] && outExt[1] <= inExt[1] &&
          outExt[2] >= inExt[2] && outExt[3] <= inExt[3] &&
          outExt[4] >= inExt[4] && outExt[5] <= inExt[5])
        {
        output->GetPointData()->CopyStructuredData(input->GetPointData(),
                                                   inExt, outExt);
        }

      output->GetCellData()->CopyAllocate(input->GetCellData(),
                                          output->GetNumberOfCells());
      // Cell extent is one less than point extent.
      // Conditional to handle a colapsed axis (lower dimensional cells).
      if (inExt[0] < inExt[1]) {--inExt[1];}
      if (inExt[2] < inExt[3]) {--inExt[3];}
      if (inExt[4] < inExt[5]) {--inExt[5];}
      // Cell extent is one less than point extent.
      if (outExt[0] < outExt[1]) {--outExt[1];}
      if (outExt[2] < outExt[3]) {--outExt[3];}
      if (outExt[4] < outExt[5]) {--outExt[5];}
      // Now Copy The cell data, but only if output is a subextent of the input.
      if (outExt[0] >= inExt[0] && outExt[1] <= inExt[1] &&
          outExt[2] >= inExt[2] && outExt[3] <= inExt[3] &&
          outExt[4] >= inExt[4] && outExt[5] <= inExt[5])
        {
        output->GetCellData()->CopyStructuredData(input->GetCellData(),
                                                    inExt, outExt);
        }
      }
    }

  // Now create the scalars array that will hold the output data.
  this->ExecuteInformation();
  output->AllocateScalars();
  outArray = output->GetPointData()->GetScalars();
  if (inArray)
    {
    outArray->SetName(inArray->GetName());
    }
  return output;
}

//----------------------------------------------------------------------------
// This is the superclasses style of Execute method.  Convert it into
// an imaging style Execute method.
void vtkImageToImageFilter::ExecuteData(vtkDataObject *out)
{
  vtkImageData *outData = this->AllocateOutputData(out);
  this->MultiThread(this->GetInput(),outData);
}

void vtkImageToImageFilter::MultiThread(vtkImageData *inData,
                                        vtkImageData *outData)
{
  vtkImageThreadStruct str;

  str.Filter = this;
  str.Input = inData;
  str.Output = outData;

  this->Threader->SetNumberOfThreads(this->NumberOfThreads);

  // setup threading and the invoke threadedExecute
  this->Threader->SetSingleMethod(vtkImageThreadedExecute, &str);
  this->Threader->SingleMethodExecute();
}

//----------------------------------------------------------------------------
// The execute method created by the subclass.
void vtkImageToImageFilter::ThreadedExecute(vtkImageData *vtkNotUsed(inData),
                                            vtkImageData *vtkNotUsed(outData),
                                            int extent[6], int threadId)
{
  extent = extent;
  if (threadId == 0)
    {
    vtkErrorMacro("subclass should override ThreadedExecute!!!");
    }
}

<commit_msg>charles fix<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkImageToImageFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm 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 notice for more information.

=========================================================================*/
#include "vtkImageToImageFilter.h"

#include "vtkCellData.h"
#include "vtkDataArray.h"
#include "vtkImageData.h"
#include "vtkMultiThreader.h"
#include "vtkObjectFactory.h"
#include "vtkPointData.h"

vtkCxxRevisionMacro(vtkImageToImageFilter, "1.53.2.1");

//----------------------------------------------------------------------------
vtkImageToImageFilter::vtkImageToImageFilter()
{
  this->NumberOfRequiredInputs = 1;
  this->Bypass = 0;
  this->Threader = vtkMultiThreader::New();
  this->NumberOfThreads = this->Threader->GetNumberOfThreads();
  this->InputScalarsSelection = NULL;
}

//----------------------------------------------------------------------------
vtkImageToImageFilter::~vtkImageToImageFilter()
{
  this->Threader->Delete();
  this->SetInputScalarsSelection(NULL);
}

//----------------------------------------------------------------------------
void vtkImageToImageFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

  os << indent << "NumberOfThreads: " << this->NumberOfThreads << "\n";

  if ( this->Bypass )
    {
    os << indent << "Bypass: On\n";
    }
  else
    {
    os << indent << "Bypass: Off\n";
    }
}

//----------------------------------------------------------------------------
void vtkImageToImageFilter::SetInput(vtkImageData *input)
{
  this->vtkProcessObject::SetNthInput(0, input);
}

//----------------------------------------------------------------------------
vtkImageData *vtkImageToImageFilter::GetInput()
{
  if (this->NumberOfInputs < 1)
    {
    return NULL;
    }

  return (vtkImageData *)(this->Inputs[0]);
}

//----------------------------------------------------------------------------
// This method can be overriden in a subclass to compute the output
// Information: WholeExtent, Spacing, Origin, ScalarType and
// NumberOfScalarComponents.
void vtkImageToImageFilter::ExecuteInformation()
{
  vtkImageData *input = this->GetInput();
  vtkImageData *output = this->GetOutput();

  // Make sure the Input has been set.
  if ( input == NULL || output == NULL)
    {
    vtkErrorMacro(<< "ExecuteInformation: Input is not set.");
    return;
    }

  // Start with some defaults.
  output->CopyTypeSpecificInformation( input );

  vtkDataArray *inArray = input->GetPointData()->GetScalars(this->InputScalarsSelection);
  if (inArray)
    {
    output->SetScalarType(inArray->GetDataType());
    }

  // take this opportunity to modify the defaults

  this->ExecuteInformation(input, output);
}

//----------------------------------------------------------------------------
void vtkImageToImageFilter::ExecuteInformation(
           vtkImageData *vtkNotUsed(inData), vtkImageData *vtkNotUsed(outData))
{
}

//----------------------------------------------------------------------------

// Call the alternate version of this method, and use the returned input
// update extent for all inputs
void vtkImageToImageFilter::ComputeInputUpdateExtents( vtkDataObject *output )
{
  int outExt[6], inExt[6];

  output->GetUpdateExtent( outExt );

  if (this->NumberOfInputs)
    {
    this->ComputeInputUpdateExtent( inExt, outExt );
    }

  for (int idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] != NULL)
      {
      if (this->Inputs[idx]->GetRequestExactExtent())
        {
        int *currentExt = this->Inputs[idx]->GetUpdateExtent();
        for (int i = 0; i < 6; i += 2)
          {
          if (inExt[i] < currentExt[i] ||
              inExt[i+1] > currentExt[i+1])
            {
            this->Inputs[idx]->SetUpdateExtent( inExt );
            break;
            }
          }
        }
      else
        {
        this->Inputs[idx]->SetUpdateExtent( inExt );
        }
      }
    }
}

// By default, simply set the input update extent to match the given output
// extent
void vtkImageToImageFilter::ComputeInputUpdateExtent( int inExt[6],
                                                      int outExt[6] )
{
  memcpy(inExt,outExt,sizeof(int)*6);
}

struct vtkImageThreadStruct
{
  vtkImageToImageFilter *Filter;
  vtkImageData   *Input;
  vtkImageData   *Output;
};

// this mess is really a simple function. All it does is call
// the ThreadedExecute method after setting the correct
// extent for this thread. Its just a pain to calculate
// the correct extent.
VTK_THREAD_RETURN_TYPE vtkImageThreadedExecute( void *arg )
{
  vtkImageThreadStruct *str;
  int ext[6], splitExt[6], total;
  int threadId, threadCount;
  vtkImageData *output;

  threadId = ((vtkMultiThreader::ThreadInfo *)(arg))->ThreadID;
  threadCount = ((vtkMultiThreader::ThreadInfo *)(arg))->NumberOfThreads;

  str = (vtkImageThreadStruct *)(((vtkMultiThreader::ThreadInfo *)(arg))->UserData);
  output = str->Output;
  output->GetUpdateExtent( ext );

  // execute the actual method with appropriate extent
  // first find out how many pieces extent can be split into.
  total = str->Filter->SplitExtent(splitExt, ext, threadId, threadCount);
  //total = 1;

  if (threadId < total)
    {
    str->Filter->ThreadedExecute(str->Input, str->Output, splitExt, threadId);
    }
  // else
  //   {
  //   otherwise don't use this thread. Sometimes the threads dont
  //   break up very well and it is just as efficient to leave a
  //   few threads idle.
  //   }

  return VTK_THREAD_RETURN_VALUE;
}

//----------------------------------------------------------------------------
// For streaming and threads.  Splits output update extent into num pieces.
// This method needs to be called num times.  Results must not overlap for
// consistent starting extent.  Subclass can override this method.
// This method returns the number of peices resulting from a successful split.
// This can be from 1 to "total".
// If 1 is returned, the extent cannot be split.
int vtkImageToImageFilter::SplitExtent(int splitExt[6], int startExt[6],
                                       int num, int total)
{
  int splitAxis;
  int min, max;

  vtkDebugMacro("SplitExtent: ( " << startExt[0] << ", " << startExt[1] << ", "
                << startExt[2] << ", " << startExt[3] << ", "
                << startExt[4] << ", " << startExt[5] << "), "
                << num << " of " << total);

  // start with same extent
  memcpy(splitExt, startExt, 6 * sizeof(int));

  splitAxis = 2;
  min = startExt[4];
  max = startExt[5];
  while (min == max)
    {
    --splitAxis;
    if (splitAxis < 0)
      { // cannot split
      vtkDebugMacro("  Cannot Split");
      return 1;
      }
    min = startExt[splitAxis*2];
    max = startExt[splitAxis*2+1];
    }

  // determine the actual number of pieces that will be generated
  int range = max - min + 1;
  int valuesPerThread = (int)ceil(range/(double)total);
  int maxThreadIdUsed = (int)ceil(range/(double)valuesPerThread) - 1;
  if (num < maxThreadIdUsed)
    {
    splitExt[splitAxis*2] = splitExt[splitAxis*2] + num*valuesPerThread;
    splitExt[splitAxis*2+1] = splitExt[splitAxis*2] + valuesPerThread - 1;
    }
  if (num == maxThreadIdUsed)
    {
    splitExt[splitAxis*2] = splitExt[splitAxis*2] + num*valuesPerThread;
    }

  vtkDebugMacro("  Split Piece: ( " <<splitExt[0]<< ", " <<splitExt[1]<< ", "
                << splitExt[2] << ", " << splitExt[3] << ", "
                << splitExt[4] << ", " << splitExt[5] << ")");

  return maxThreadIdUsed + 1;
}

//----------------------------------------------------------------------------
vtkImageData *vtkImageToImageFilter::AllocateOutputData(vtkDataObject *out)
{
  vtkImageData *output = vtkImageData::SafeDownCast(out);
  vtkImageData *input = this->GetInput();
  int inExt[6];
  int outExt[6];
  vtkDataArray *inArray;
  vtkDataArray *outArray;

  input->GetExtent(inExt);
  output->SetExtent(output->GetUpdateExtent());
  output->GetExtent(outExt);

  // Do not copy the array we will be generating.
  inArray = input->GetPointData()->GetScalars(this->InputScalarsSelection);

  // Conditionally copy point and cell data.
  // Only copy if corresponding indexes refer to identical points.
  float *oIn = input->GetOrigin();
  float *sIn = input->GetSpacing();
  float *oOut = output->GetOrigin();
  float *sOut = output->GetSpacing();
  if (oIn[0] == oOut[0] && oIn[1] == oOut[1] && oIn[2] == oOut[2] &&
      sIn[0] == sOut[0] && sIn[1] == sOut[1] && sIn[2] == sOut[2])
    {
    output->GetPointData()->CopyAllOn();
    output->GetCellData()->CopyAllOn();
    // Scalar copy flag trumps the array copy flag.
    if (inArray == input->GetPointData()->GetScalars())
      {
      output->GetPointData()->CopyScalarsOff();
      }
    else
      {
      output->GetPointData()->CopyFieldOff(this->InputScalarsSelection);
      }

    // If the extents are the same, then pass the attribute data for efficiency.
    if (inExt[0] == outExt[0] && inExt[1] == outExt[1] &&
        inExt[2] == outExt[2] && inExt[3] == outExt[3] &&
        inExt[4] == outExt[4] && inExt[5] == outExt[5])
      {// Pass
      output->GetPointData()->PassData(input->GetPointData());
      output->GetCellData()->PassData(input->GetCellData());
      }
    else
      {// Copy
       // Since this can be expensive to copy all of these values,
       // lets make sure there are arrays to copy (other than the scalars)
      if (input->GetPointData()->GetNumberOfArrays() > 1)
        {
        // Copy the point data.
        // CopyAllocate frees all arrays.
        // Keep the old scalar array (not being copied).
        // This is a hack, but avoids reallocation ...
        vtkDataArray *tmp = NULL;
        if ( ! output->GetPointData()->GetCopyScalars() )
          {
          tmp = output->GetPointData()->GetScalars();
          }
        output->GetPointData()->CopyAllocate(input->GetPointData(),
                                             output->GetNumberOfPoints());
        if (tmp)
          { // Restore the array.
          output->GetPointData()->SetScalars(tmp);
          }
        // Now Copy The point data, but only if output is a subextent of the input.
        if (outExt[0] >= inExt[0] && outExt[1] <= inExt[1] &&
            outExt[2] >= inExt[2] && outExt[3] <= inExt[3] &&
            outExt[4] >= inExt[4] && outExt[5] <= inExt[5])
          {
          output->GetPointData()->CopyStructuredData(input->GetPointData(),
                                                     inExt, outExt);
          }
        }

      if (input->GetCellData()->GetNumberOfArrays() > 0)
        {
        output->GetCellData()->CopyAllocate(input->GetCellData(),
                                            output->GetNumberOfCells());
        // Cell extent is one less than point extent.
        // Conditional to handle a colapsed axis (lower dimensional cells).
        if (inExt[0] < inExt[1]) {--inExt[1];}
        if (inExt[2] < inExt[3]) {--inExt[3];}
        if (inExt[4] < inExt[5]) {--inExt[5];}
        // Cell extent is one less than point extent.
        if (outExt[0] < outExt[1]) {--outExt[1];}
        if (outExt[2] < outExt[3]) {--outExt[3];}
        if (outExt[4] < outExt[5]) {--outExt[5];}
        // Now Copy The cell data, but only if output is a subextent of the input.
        if (outExt[0] >= inExt[0] && outExt[1] <= inExt[1] &&
            outExt[2] >= inExt[2] && outExt[3] <= inExt[3] &&
            outExt[4] >= inExt[4] && outExt[5] <= inExt[5])
          {
          output->GetCellData()->CopyStructuredData(input->GetCellData(),
                                                    inExt, outExt);
          }
        }
      }
    }

  // Now create the scalars array that will hold the output data.
  this->ExecuteInformation();
  output->AllocateScalars();
  outArray = output->GetPointData()->GetScalars();
  if (inArray)
    {
    outArray->SetName(inArray->GetName());
    }
  return output;
}

//----------------------------------------------------------------------------
// This is the superclasses style of Execute method.  Convert it into
// an imaging style Execute method.
void vtkImageToImageFilter::ExecuteData(vtkDataObject *out)
{
  vtkImageData *outData = this->AllocateOutputData(out);
  this->MultiThread(this->GetInput(),outData);
}

void vtkImageToImageFilter::MultiThread(vtkImageData *inData,
                                        vtkImageData *outData)
{
  vtkImageThreadStruct str;

  str.Filter = this;
  str.Input = inData;
  str.Output = outData;

  this->Threader->SetNumberOfThreads(this->NumberOfThreads);

  // setup threading and the invoke threadedExecute
  this->Threader->SetSingleMethod(vtkImageThreadedExecute, &str);
  this->Threader->SingleMethodExecute();
}

//----------------------------------------------------------------------------
// The execute method created by the subclass.
void vtkImageToImageFilter::ThreadedExecute(vtkImageData *vtkNotUsed(inData),
                                            vtkImageData *vtkNotUsed(outData),
                                            int extent[6], int threadId)
{
  extent = extent;
  if (threadId == 0)
    {
    vtkErrorMacro("subclass should override ThreadedExecute!!!");
    }
}

<|endoftext|>


<commit_before><commit_msg>Optimize ocean generation<commit_after><|endoftext|>


<commit_before>//Created by: Sec-Mini-Projects (2015) under the MIT License - See "LICENSE" for Details.
//Description: Checks whether shellcode is running within a program by hooking API calls using anti-anti-API Hooking techniques and memory forensics.
//Usage: Please run the program without any parameters to show the usage menu.
//TitanEngine is used as the debugging engine in this program - http://reversinglabs.com/open-source/titanengine.html.

#include "stdafx.h"
#define MAX_WHITELIST_ENTRIES 80
#define MAX_EXCLUDE_ADDRS 20
ULONG_PTR ep = NULL;
PROCESS_INFORMATION * info = NULL;
LPSTR api_file = NULL;
LPSTR addr_exclude_file = NULL;
bool found_shellcode = false;
unsigned long exclude_addrs[MAX_WHITELIST_ENTRIES];
LPSTR exclude_libs[MAX_EXCLUDE_ADDRS];
bool debug_mode = false;

//Checks for shellcode located at the current IP
void __stdcall CheckForShellcode()
{
	if(found_shellcode == false)
	{
		int buf_len = 600;
		ULONG_PTR ip = (ULONG_PTR)GetContextData(UE_EIP);
		LPSTR temp = (char*)calloc(255,sizeof(char));
		LPSTR mod_name = (LPSTR)calloc(1,buf_len);
		ThreaderPauseAllThreads(false);
		GetMappedFileName(info->hProcess,(LPVOID)ip,(LPSTR)mod_name,buf_len);
		ThreaderResumeAllThreads(false);
		unsigned short last_16_bits = (unsigned short)(ip);
		bool is_Avoid = false;

		//This will need to be changed for x64 bit code due to ALSR and other differences, as will other sections of this code.
		//The existing code deals with Microsoft doing something weird when processing OLE objects embedded in a DOCX/XLSX/etc file.
		int x = 0;
		while (x < MAX_WHITELIST_ENTRIES && exclude_addrs[x] != NULL && is_Avoid == false)
		{
			char * dll_name = strrchr(mod_name,'\\');
			if(dll_name != NULL)
			{
				if(StrCmpI(dll_name+1,exclude_libs[x]) == NULL)
				{
					if(last_16_bits == exclude_addrs[x])
					{
						is_Avoid = true;
					}
				}
			}
			x++;
		}
		if(is_Avoid == false)
		{
			LPSTR instr = _strlwr((char*)Disassemble((LPVOID)ip));
			MEMORY_BASIC_INFORMATION * mem_info = (MEMORY_BASIC_INFORMATION*)calloc(1,sizeof(MEMORY_BASIC_INFORMATION));
			ThreaderPauseAllThreads(false);
			SIZE_T temp = VirtualQueryEx(info->hProcess,(LPCVOID)ip,mem_info,sizeof(*mem_info));
			ThreaderResumeAllThreads(false);
			if(temp && mem_info)
			{
				if(mod_name == NULL || mem_info->Protect > 0x20 || StrRChr(mod_name,NULL,'.') == NULL)
				{
					LPSTR seg_dump_name = (LPSTR)calloc(buf_len,sizeof(char));
					sprintf_s(seg_dump_name,buf_len,"%x Seg Dump.bin",mem_info->BaseAddress);
					printf("Found exploit - creating full and partial dumps. %s %x\n",mod_name, mem_info->Protect);
					DumpMemory(info->hProcess,mem_info->BaseAddress,mem_info->RegionSize,seg_dump_name);
					DumpRegions(info->hProcess,"Full Region Dump Files",false);
					DumpProcess(info->hProcess,(LPVOID)GetDebuggedFileBaseAddress(),"Full Memory Image Dump.bin",ep);
					found_shellcode = true;
					if(seg_dump_name)
						free(seg_dump_name);
					StopDebug();
					exit(1);
				}
				if(debug_mode == true)
					ThreaderPauseAllThreads(false);
					printf("Checked for shellcode %s %x %s 4\n",instr,ip,mod_name);
					ThreaderResumeAllThreads(false);
			}
			if(mem_info)
				free(mem_info);
			StepOver(OnStep);
		}
		if(mod_name)
			free(mod_name);
		if(temp)
			free(temp);
	}
}

//Steps over code, determining whether a return instruction has been encountered, if not, just keeps on stepping over.
void  __stdcall OnStep()
{
	ULONG_PTR ip = (ULONG_PTR)GetContextData(UE_EIP);
	LPSTR mod_name = NULL;
	unsigned char instr= NULL;
	SIZE_T bytes_read = NULL;
	bool is_ret = false;
	ReadProcessMemory(info->hProcess,(LPCVOID)ip,&instr,sizeof(instr),&bytes_read);
	if(bytes_read != NULL)
	{
		if(instr ==0xC2 || instr ==0xC3 || instr ==0xCA || instr ==0xCB)
		{
			StepOver(CheckForShellcode);
		}
		else
		{
			StepOver(OnStep);
		}
	}
}

void __stdcall OnSingleStepException(void* ExceptionData)
{
	SetNextDbgContinueStatus(DBG_CONTINUE);
	printf("***###Received### - Single step exception.***\n");
}

//Creates a thread for each breakpoint hit to reduce bottlenecks.
void __stdcall BPHandler()
{
	StepOver(OnStep);
}

//Searches for the first JXX or call and creates a breakpoint.
bool  __stdcall SetAPIBP(ULONG_PTR api_addr)
{
	bool found = false;
	ULONG_PTR addr = api_addr;
	LPSTR instr = NULL;
	if(addr != NULL)
	{
		while(found == false)
		{
			instr = _strlwr((LPSTR)Disassemble((LPVOID)addr));
			if(StrStrI(instr,"j") == NULL && StrStrI(instr,"call") == NULL && StrStrI(instr,"ret") == NULL)
			{
				addr = addr + LengthDisassembleEx(info->hProcess,(LPVOID)addr);
			}
			else
			{
				found = true;
			}
		}
		SetBPX(addr,UE_BREAKPOINT,BPHandler);
		//printf("Breakpoing set for instr %s at %x \n",instr,api_addr);
	}
	else
	{
		found = false;
	}
	return found;
}

//Entry point handler for the program, reads the APIS to be hooked and applies them through the SetAPIBP fucntion.
void __stdcall OnEntry()
{
	ep = GetContextData(UE_EIP);
	int buf_len = 500;
    LPSTR buf = (LPSTR)calloc(buf_len,sizeof(char));
	LPSTR exclude_buf = (LPSTR)calloc(buf_len,sizeof(char));
	int temp = strlen(buf);
	FILE * f_api_file = fopen(api_file,"r");
	FILE * f_exclude_file = NULL;
	if (addr_exclude_file == NULL)
	{
		if(debug_mode == true)
			printf("***###LOGGING### - Address exclude file could not be found.***\n");
	}
	else
	{
		f_exclude_file = fopen(addr_exclude_file,"r");
		int x = 0;
		while (fgets(exclude_buf,buf_len/sizeof(*exclude_buf), f_exclude_file) && x < MAX_WHITELIST_ENTRIES)
		{
			LPSTR exclude_lib = strtok(exclude_buf,",");
			LPSTR exclude_addr = strtok(NULL,",");
			if(exclude_lib != NULL && exclude_addr != NULL)
			{
				bool dll_failed =false;
				if(exclude_addr[strlen(exclude_addr)-1] == 0x0a)
					exclude_addr[strlen(exclude_addr)-1] = 0x00;
				if(exclude_lib[strlen(exclude_lib)-1] == 0x0a)
					exclude_lib[strlen(exclude_lib)-1] = 0x00;
				long exclude_this_addr = strtol(exclude_addr,NULL,16);
				exclude_libs[x] = (LPSTR)calloc(buf_len,sizeof(char));
				exclude_addrs[x] = exclude_this_addr;
				strcpy_s(exclude_libs[x],buf_len,exclude_lib);
				if(debug_mode == true)
					printf("***###LOGGING### - Read exclude addr entry: %s %x***\n",exclude_lib,exclude_this_addr);
				x++;
			}
		}
	}

	if (f_api_file == NULL)
	{
		printf("***###FATAL### - API's to hook file could not be found.***\n");
		StopDebug();
		exit(1);
	}
	else
	{
		while (fgets(buf,buf_len/sizeof(*buf), f_api_file)!=NULL)
		{
			LPSTR lib_name = strtok(buf,",");
			LPSTR api_name = strtok(NULL,",");
			bool dll_failed =false;
			if(api_name[strlen(api_name)-1] == 0x0a)
				api_name[strlen(api_name)-1] = 0x00;
			if(LoadLibrary(lib_name) == NULL)
			{
				if(debug_mode == true)
					printf("***###FAILED### - Could not load %s locally.***\n",lib_name);
			}
			else
			{
				if(debug_mode == true)
					printf("***###LOGGING### - Loaded %s locally.***\n",lib_name);
				if(LibrarianGetLibraryInfo(lib_name) == NULL)
				{
					if(RemoteLoadLibrary(info->hProcess,lib_name,false) == NULL)
					{
						if(debug_mode == true)
							printf("***###FAILED### - Could not load %s into the remote address space.***\n",lib_name);
						dll_failed = true;
					}
				}
				else
				{
					if(debug_mode == true)
						printf("***###LOGGING### - %s already loaded within the remote address space.***\n",lib_name);
				}
				if(!dll_failed)
				{
					ULONG_PTR api_addr = (ULONG_PTR)ImporterGetRemoteAPIAddressEx(lib_name,api_name);
					if(SetAPIBP(api_addr))
					{
						if(debug_mode == true)
							printf("***###LOGGING### - Breakpoint set for %s %x.***\n",api_name,api_addr);
					}
					else
					{
						if(debug_mode == true)
							printf("***###FAILED### - Breakpoint could not be set for %s.***\n",api_name);
					}
				}
			}
		}
	}
	if(f_api_file)
		fclose(f_api_file);
	if(f_exclude_file)
		fclose(f_exclude_file);
	if(buf)
		free(buf);
}

//Inits the debugger library and callbacks.
int main(int argc, char * argv[])
{

	int x = 1;
	LPSTR program = NULL;
	LPSTR working = NULL;
	LPSTR cmd_line = NULL;
	while (x < argc)
	{
		if(StrCmpI(argv[x],"--program") == 0 || StrCmpI(argv[x],"-p") ==0)
		{
			program = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--working_dir") == 0 || StrCmpI(argv[x],"-w") == 0)
		{
			working = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--cmd_line") == 0 || StrCmpI(argv[x],"-c") == 0)
		{
			cmd_line = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--api_list") == 0 || StrCmpI(argv[x],"-a") == 0)
		{
			api_file = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--addr_exclude") == 0 || StrCmpI(argv[x],"-e") == 0)
		{
			addr_exclude_file = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--debug_mode") == 0 || StrCmpI(argv[x],"-d") == 0)
		{
			debug_mode = true;
			x--;
		}
		x = x+2;
	}
	if(program != NULL && working != NULL && api_file != NULL)
	{
		info = (PROCESS_INFORMATION *)InitDebugEx(program,cmd_line,working,OnEntry);
		SetCustomHandler(UE_CH_SINGLESTEP,OnSingleStepException);
		SetBPXOptions(UE_BREAKPOINT_INT3);
		if(info == NULL)
		{
			printf("***###FATAL### - Failed init.***\n");
		}
		else
		{
			DebugLoop();
		}
		printf("***###LOGGING### - Exiting.***\n");
	}
	else
	{
		printf("\nFlyOnAShellcode V3.0.\n");
		printf("Sec-Mini-Projects (2015) under the MIT License - See \"LICENSE\" for Details.\n");
		printf("TitanEngine is used as the debugging engine in this program - http://reversinglabs.com/open-source/titanengine.html.\n");
		printf("***WARNING*** - This program will RUN the supplied executable and malicious input file. USE ONLY IN MALWARE RESEARCH LABS.\n\n");
		printf("Note 1 - This program can be anywhere from very stable to very unstable depending on which APIs are hooked.\n\n");
		printf("Note 2 - Avoid manually navigating the \"File Open\", etc dialogs from within the program will help eliminate crashes.\n\n");
		printf("Usage: \n--program[-p] <Program full path and name> \n--working_dir[-w] <working directory> \n--cmd_line[-c] <Command line arguments> (Optional)\n--api_list[-a] <API hook list path and name> \n--addr_exclude[-e] <address exclude file> (Optional)\n--debug_mode[-d] - Enables debug mode(Optional)\n\n");
		printf("Usage - API library/names format is for each API call a new line matching (without the quotes) \"<lib name>,<api name>\"\n\n");
	}
	//printf("%x",argc);
	return 0;
}

<commit_msg>Update FlyOnAShellcode.cpp<commit_after>//Created by: Sec-Mini-Projects (2015) under the MIT License - See "LICENSE" for Details.
//Description: Checks whether shellcode is running within a program by hooking API calls using anti-anti-API Hooking techniques and memory forensics.
//Usage: Please run the program without any parameters to show the usage menu.
//TitanEngine is used as the debugging engine in this program - http://reversinglabs.com/open-source/titanengine.html.

#include "stdafx.h"
#define MAX_WHITELIST 200
ULONG_PTR ep = NULL;
PROCESS_INFORMATION * info = NULL;
LPSTR api_file = NULL;
LPSTR addr_exclude_file = NULL;
bool found_shellcode = false;
unsigned long exclude_addrs[MAX_WHITELIST];
LPSTR exclude_libs[MAX_WHITELIST];
bool debug_mode = false;

//Checks for shellcode located at the current IP
void __stdcall CheckForShellcode()
{
	if(found_shellcode == false)
	{
		int buf_len = 600;
		ULONG_PTR ip = (ULONG_PTR)GetContextData(UE_EIP);
		LPSTR temp = (char*)calloc(255,sizeof(char));
		LPSTR mod_name = (LPSTR)calloc(1,buf_len);
		ThreaderPauseAllThreads(false);
		GetMappedFileName(info->hProcess,(LPVOID)ip,(LPSTR)mod_name,buf_len);
		ThreaderResumeAllThreads(false);
		unsigned short last_16_bits = (unsigned short)(ip);
		bool is_Avoid = false;

		//This will need to be changed for x64 bit code due to ALSR and other differences, as will other sections of this code.
		//The existing code deals with Microsoft doing something weird when processing OLE objects embedded in a DOCX/XLSX/etc file.
		int x = 0;
		while (x < MAX_WHITELIST && exclude_addrs[x] != NULL && exclude_libs[x] != NULL && is_Avoid == false)
		{
			char * dll_name = strrchr(mod_name,'\\');
			if(dll_name != NULL)
			{
				if(StrCmpI(dll_name+1,exclude_libs[x]) == NULL)
				{
					if(last_16_bits == exclude_addrs[x])
					{
						is_Avoid = true;
					}
				}
			}
			x++;
		}
		if(is_Avoid == false)
		{
			LPSTR instr = _strlwr((char*)Disassemble((LPVOID)ip));
			MEMORY_BASIC_INFORMATION * mem_info = (MEMORY_BASIC_INFORMATION*)calloc(1,sizeof(MEMORY_BASIC_INFORMATION));
			ThreaderPauseAllThreads(false);
			SIZE_T temp = VirtualQueryEx(info->hProcess,(LPCVOID)ip,mem_info,sizeof(*mem_info));
			ThreaderResumeAllThreads(false);
			if(temp && mem_info)
			{
				if(mod_name == NULL || mem_info->Protect > 0x20 || StrRChr(mod_name,NULL,'.') == NULL)
				{
					LPSTR seg_dump_name = (LPSTR)calloc(buf_len,sizeof(char));
					sprintf_s(seg_dump_name,buf_len,"%x Seg Dump.bin",mem_info->BaseAddress);
					printf("Found exploit - creating full and partial dumps. %s %x\n",mod_name, mem_info->Protect);
					DumpMemory(info->hProcess,mem_info->BaseAddress,mem_info->RegionSize,seg_dump_name);
					DumpRegions(info->hProcess,"Full Region Dump Files",false);
					DumpProcess(info->hProcess,(LPVOID)GetDebuggedFileBaseAddress(),"Full Memory Image Dump.bin",ep);
					found_shellcode = true;
					if(seg_dump_name)
						free(seg_dump_name);
					StopDebug();
					exit(1);
				}
				if(debug_mode == true)
				{
					ThreaderPauseAllThreads(false);
					printf("Checked for shellcode %s %x %s 4\n",instr,ip,mod_name);
					ThreaderResumeAllThreads(false);
				}
			}
			if(mem_info)
				free(mem_info);
			StepOver(OnStep);
		}
		if(mod_name)
			free(mod_name);
		if(temp)
			free(temp);
	}
}

//Steps over code, determining whether a return instruction has been encountered, if not, just keeps on stepping over.
void  __stdcall OnStep()
{
	ULONG_PTR ip = (ULONG_PTR)GetContextData(UE_EIP);
	LPSTR mod_name = NULL;
	unsigned char instr= NULL;
	SIZE_T bytes_read = NULL;
	bool is_ret = false;
	ReadProcessMemory(info->hProcess,(LPCVOID)ip,&instr,sizeof(instr),&bytes_read);
	if(bytes_read != NULL)
	{
		if(instr ==0xC2 || instr ==0xC3 || instr ==0xCA || instr ==0xCB)
		{
			StepOver(CheckForShellcode);
		}
		else
		{
			StepOver(OnStep);
		}
	}
}

void __stdcall OnSingleStepException(void* ExceptionData)
{
	SetNextDbgContinueStatus(DBG_CONTINUE);
	printf("***###Received### - Single step exception.***\n");
}

//Creates a thread for each breakpoint hit to reduce bottlenecks.
void __stdcall BPHandler()
{
	StepOver(OnStep);
}

//Searches for the first JXX or call and creates a breakpoint.
bool  __stdcall SetAPIBP(ULONG_PTR api_addr)
{
	bool found = false;
	ULONG_PTR addr = api_addr;
	LPSTR instr = NULL;
	if(addr != NULL)
	{
		while(found == false)
		{
			instr = _strlwr((LPSTR)Disassemble((LPVOID)addr));
			if(StrStrI(instr,"j") == NULL && StrStrI(instr,"call") == NULL && StrStrI(instr,"ret") == NULL)
			{
				addr = addr + LengthDisassembleEx(info->hProcess,(LPVOID)addr);
			}
			else
			{
				found = true;
			}
		}
		SetBPX(addr,UE_BREAKPOINT,BPHandler);
		//printf("Breakpoing set for instr %s at %x \n",instr,api_addr);
	}
	else
	{
		found = false;
	}
	return found;
}

//Entry point handler for the program, reads the APIS to be hooked and applies them through the SetAPIBP fucntion.
void __stdcall OnEntry()
{
	ep = GetContextData(UE_EIP);
	int buf_len = 500;
    LPSTR buf = (LPSTR)calloc(buf_len,sizeof(char));
	LPSTR exclude_buf = (LPSTR)calloc(buf_len,sizeof(char));
	int temp = strlen(buf);
	FILE * f_api_file = fopen(api_file,"r");
	FILE * f_exclude_file = NULL;
	if (addr_exclude_file == NULL)
	{
		if(debug_mode == true)
			printf("***###LOGGING### - Address exclude file could not be found.***\n");
	}
	else
	{
		f_exclude_file = fopen(addr_exclude_file,"r");
		int x = 0;
		while (fgets(exclude_buf,buf_len/sizeof(*exclude_buf), f_exclude_file) && x < MAX_WHITELIST)
		{
			LPSTR exclude_lib = strtok(exclude_buf,",");
			LPSTR exclude_addr = strtok(NULL,",");
			if(exclude_lib != NULL && exclude_addr != NULL)
			{
				bool dll_failed =false;
				if(exclude_addr[strlen(exclude_addr)-1] == 0x0a)
					exclude_addr[strlen(exclude_addr)-1] = 0x00;
				if(exclude_lib[strlen(exclude_lib)-1] == 0x0a)
					exclude_lib[strlen(exclude_lib)-1] = 0x00;
				long exclude_this_addr = strtol(exclude_addr,NULL,16);
				exclude_libs[x] = (LPSTR)calloc(buf_len,sizeof(char));
				exclude_addrs[x] = exclude_this_addr;
				strcpy_s(exclude_libs[x],buf_len,exclude_lib);
				if(debug_mode == true)
					printf("***###LOGGING### - Read exclude addr entry: %s %x***\n",exclude_lib,exclude_this_addr);
				x++;
			}
		}
	}

	if (f_api_file == NULL)
	{
		printf("***###FATAL### - API's to hook file could not be found.***\n");
		StopDebug();
		exit(1);
	}
	else
	{
		while (fgets(buf,buf_len/sizeof(*buf), f_api_file)!=NULL)
		{
			LPSTR lib_name = strtok(buf,",");
			LPSTR api_name = strtok(NULL,",");
			bool dll_failed =false;
			if(api_name[strlen(api_name)-1] == 0x0a)
				api_name[strlen(api_name)-1] = 0x00;
			if(LoadLibrary(lib_name) == NULL)
			{
				if(debug_mode == true)
					printf("***###FAILED### - Could not load %s locally.***\n",lib_name);
			}
			else
			{
				if(debug_mode == true)
					printf("***###LOGGING### - Loaded %s locally.***\n",lib_name);
				if(LibrarianGetLibraryInfo(lib_name) == NULL)
				{
					if(RemoteLoadLibrary(info->hProcess,lib_name,false) == NULL)
					{
						if(debug_mode == true)
							printf("***###FAILED### - Could not load %s into the remote address space.***\n",lib_name);
						dll_failed = true;
					}
				}
				else
				{
					if(debug_mode == true)
						printf("***###LOGGING### - %s already loaded within the remote address space.***\n",lib_name);
				}
				if(!dll_failed)
				{
					ULONG_PTR api_addr = (ULONG_PTR)ImporterGetRemoteAPIAddressEx(lib_name,api_name);
					if(SetAPIBP(api_addr))
					{
						if(debug_mode == true)
							printf("***###LOGGING### - Breakpoint set for %s %x.***\n",api_name,api_addr);
					}
					else
					{
						if(debug_mode == true)
							printf("***###FAILED### - Breakpoint could not be set for %s.***\n",api_name);
					}
				}
			}
		}
	}
	if(f_api_file)
		fclose(f_api_file);
	if(f_exclude_file)
		fclose(f_exclude_file);
	if(buf)
		free(buf);
}

//Inits the debugger library and callbacks.
int main(int argc, char * argv[])
{

	int x = 1;
	LPSTR program = NULL;
	LPSTR working = NULL;
	LPSTR cmd_line = NULL;
	while (x < argc)
	{
		if(StrCmpI(argv[x],"--program") == 0 || StrCmpI(argv[x],"-p") ==0)
		{
			program = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--working_dir") == 0 || StrCmpI(argv[x],"-w") == 0)
		{
			working = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--cmd_line") == 0 || StrCmpI(argv[x],"-c") == 0)
		{
			cmd_line = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--api_list") == 0 || StrCmpI(argv[x],"-a") == 0)
		{
			api_file = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--addr_exclude") == 0 || StrCmpI(argv[x],"-e") == 0)
		{
			addr_exclude_file = argv[x+1];
		}
		else if(StrCmpI(argv[x],"--debug_mode") == 0 || StrCmpI(argv[x],"-d") == 0)
		{
			debug_mode = true;
			x--;
		}
		x = x+2;
	}
	if(program != NULL && working != NULL && api_file != NULL)
	{
		info = (PROCESS_INFORMATION *)InitDebugEx(program,cmd_line,working,OnEntry);
		SetCustomHandler(UE_CH_SINGLESTEP,OnSingleStepException);
		SetBPXOptions(UE_BREAKPOINT_INT3);
		if(info == NULL)
		{
			printf("***###FATAL### - Failed init.***\n");
		}
		else
		{
			DebugLoop();
		}
		printf("***###LOGGING### - Exiting.***\n");
	}
	else
	{
		printf("\nFlyOnAShellcode V3.0.\n");
		printf("Sec-Mini-Projects (2015) under the MIT License - See \"LICENSE\" for Details.\n");
		printf("TitanEngine is used as the debugging engine in this program - http://reversinglabs.com/open-source/titanengine.html.\n");
		printf("***WARNING*** - This program will RUN the supplied executable and malicious input file. USE ONLY IN MALWARE RESEARCH LABS.\n\n");
		printf("Note 1 - This program can be anywhere from very stable to very unstable depending on which APIs are hooked.\n\n");
		printf("Note 2 - Avoid manually navigating the \"File Open\", etc dialogs from within the program will help eliminate crashes.\n\n");
		printf("Usage: \n--program[-p] <Program full path and name> \n--working_dir[-w] <working directory> \n--cmd_line[-c] <Command line arguments> (Optional)\n--api_list[-a] <API hook list path and name> \n--addr_exclude[-e] <address exclude file> (Optional)\n--debug_mode[-d] - Enables debug mode(Optional)\n\n");
		printf("Usage - API library/names format is for each API call a new line matching (without the quotes) \"<lib name>,<api name>\"\n\n");
	}
	//printf("%x",argc);
	return 0;
}

<|endoftext|>