<commit_before>//===- Cloning.cpp - Unit tests for the Cloner ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace {

class CloneInstruction : public ::testing::Test {
protected:
  virtual void SetUp() {
    V = NULL;
  }

  template <typename T>
  T *clone(T *V1) {
    Value *V2 = V1->clone();
    Orig.insert(V1);
    Clones.insert(V2);
    return cast<T>(V2);
  }

  void eraseClones() {
    DeleteContainerPointers(Clones);
  }

  virtual void TearDown() {
    eraseClones();
    DeleteContainerPointers(Orig);
    delete V;
  }

  SmallPtrSet<Value *, 4> Orig;   // Erase on exit
  SmallPtrSet<Value *, 4> Clones; // Erase in eraseClones

  LLVMContext context;
  Value *V;
};

TEST_F(CloneInstruction, OverflowBits) {
  V = new Argument(Type::getInt32Ty(context));

  BinaryOperator *Add = BinaryOperator::Create(Instruction::Add, V, V);
  BinaryOperator *Sub = BinaryOperator::Create(Instruction::Sub, V, V);
  BinaryOperator *Mul = BinaryOperator::Create(Instruction::Mul, V, V);

  BinaryOperator *AddClone = this->clone(Add);
  BinaryOperator *SubClone = this->clone(Sub);
  BinaryOperator *MulClone = this->clone(Mul);

  EXPECT_FALSE(AddClone->hasNoUnsignedWrap());
  EXPECT_FALSE(AddClone->hasNoSignedWrap());
  EXPECT_FALSE(SubClone->hasNoUnsignedWrap());
  EXPECT_FALSE(SubClone->hasNoSignedWrap());
  EXPECT_FALSE(MulClone->hasNoUnsignedWrap());
  EXPECT_FALSE(MulClone->hasNoSignedWrap());

  eraseClones();

  Add->setHasNoUnsignedWrap();
  Sub->setHasNoUnsignedWrap();
  Mul->setHasNoUnsignedWrap();

  AddClone = this->clone(Add);
  SubClone = this->clone(Sub);
  MulClone = this->clone(Mul);

  EXPECT_TRUE(AddClone->hasNoUnsignedWrap());
  EXPECT_FALSE(AddClone->hasNoSignedWrap());
  EXPECT_TRUE(SubClone->hasNoUnsignedWrap());
  EXPECT_FALSE(SubClone->hasNoSignedWrap());
  EXPECT_TRUE(MulClone->hasNoUnsignedWrap());
  EXPECT_FALSE(MulClone->hasNoSignedWrap());

  eraseClones();

  Add->setHasNoSignedWrap();
  Sub->setHasNoSignedWrap();
  Mul->setHasNoSignedWrap();

  AddClone = this->clone(Add);
  SubClone = this->clone(Sub);
  MulClone = this->clone(Mul);

  EXPECT_TRUE(AddClone->hasNoUnsignedWrap());
  EXPECT_TRUE(AddClone->hasNoSignedWrap());
  EXPECT_TRUE(SubClone->hasNoUnsignedWrap());
  EXPECT_TRUE(SubClone->hasNoSignedWrap());
  EXPECT_TRUE(MulClone->hasNoUnsignedWrap());
  EXPECT_TRUE(MulClone->hasNoSignedWrap());

  eraseClones();

  Add->setHasNoUnsignedWrap(false);
  Sub->setHasNoUnsignedWrap(false);
  Mul->setHasNoUnsignedWrap(false);

  AddClone = this->clone(Add);
  SubClone = this->clone(Sub);
  MulClone = this->clone(Mul);

  EXPECT_FALSE(AddClone->hasNoUnsignedWrap());
  EXPECT_TRUE(AddClone->hasNoSignedWrap());
  EXPECT_FALSE(SubClone->hasNoUnsignedWrap());
  EXPECT_TRUE(SubClone->hasNoSignedWrap());
  EXPECT_FALSE(MulClone->hasNoUnsignedWrap());
  EXPECT_TRUE(MulClone->hasNoSignedWrap());
}

TEST_F(CloneInstruction, Inbounds) {
  V = new Argument(Type::getInt32PtrTy(context));

  Constant *Z = Constant::getNullValue(Type::getInt32Ty(context));
  std::vector<Value *> ops;
  ops.push_back(Z);
  GetElementPtrInst *GEP = GetElementPtrInst::Create(V, ops);
  EXPECT_FALSE(this->clone(GEP)->isInBounds());

  GEP->setIsInBounds();
  EXPECT_TRUE(this->clone(GEP)->isInBounds());
}

TEST_F(CloneInstruction, Exact) {
  V = new Argument(Type::getInt32Ty(context));

  BinaryOperator *SDiv = BinaryOperator::Create(Instruction::SDiv, V, V);
  EXPECT_FALSE(this->clone(SDiv)->isExact());

  SDiv->setIsExact(true);
  EXPECT_TRUE(this->clone(SDiv)->isExact());
}

TEST_F(CloneInstruction, Attributes) {
  Type *ArgTy1[] = { Type::getInt32PtrTy(context) };
  FunctionType *FT1 =  FunctionType::get(Type::getVoidTy(context), ArgTy1, false);

  Function *F1 = Function::Create(FT1, Function::ExternalLinkage);
  BasicBlock *BB = BasicBlock::Create(context, "", F1);
  IRBuilder<> Builder(BB);
  Builder.CreateRetVoid();

  Function *F2 = Function::Create(FT1, Function::ExternalLinkage);

  Attribute::AttrKind AK[] = { Attribute::NoCapture };
  AttributeSet AS = AttributeSet::get(context, 0, AK);
  Argument *A = F1->arg_begin();
  A->addAttr(AS);

  SmallVector<ReturnInst*, 4> Returns;
  ValueToValueMapTy VMap;
  VMap[A] = UndefValue::get(A->getType());

  CloneFunctionInto(F2, F1, VMap, false, Returns);
  EXPECT_FALSE(F2->arg_begin()->hasNoCaptureAttr());

  delete F1;
  delete F2;
}

TEST_F(CloneInstruction, CallingConvention) {
  Type *ArgTy1[] = { Type::getInt32PtrTy(context) };
  FunctionType *FT1 =  FunctionType::get(Type::getVoidTy(context), ArgTy1, false);

  Function *F1 = Function::Create(FT1, Function::ExternalLinkage);
  F1->setCallingConv(CallingConv::Cold);
  BasicBlock *BB = BasicBlock::Create(context, "", F1);
  IRBuilder<> Builder(BB);
  Builder.CreateRetVoid();

  Function *F2 = Function::Create(FT1, Function::ExternalLinkage);

  SmallVector<ReturnInst*, 4> Returns;
  ValueToValueMapTy VMap;
  VMap[F1->arg_begin()] = F2->arg_begin();

  CloneFunctionInto(F2, F1, VMap, false, Returns);
  EXPECT_EQ(CallingConv::Cold, F2->getCallingConv());

  delete F1;
  delete F2;
}

class CloneFunc : public ::testing::Test {
protected:
  virtual void SetUp() {
    SetupModule();
    CreateOldFunc();
    CreateNewFunc();
    SetupFinder();
  }

  virtual void TearDown() {
    delete Finder;
  }

  void SetupModule() {
    M = new Module("", C);
  }

  void CreateOldFunc() {
    FunctionType* FuncType = FunctionType::get(Type::getVoidTy(C), false);
    OldFunc = Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", M);
    CreateOldFunctionBodyAndDI();
  }

  void CreateOldFunctionBodyAndDI() {
    DIBuilder DBuilder(*M);
    IRBuilder<> IBuilder(C);

    // Function DI
    DIFile File = DBuilder.createFile("filename.c", "/file/dir/");
    DIArray ParamTypes = DBuilder.getOrCreateArray(ArrayRef<Value*>());
    DICompositeType FuncType = DBuilder.createSubroutineType(File, ParamTypes);
    DICompileUnit CU = DBuilder.createCompileUnit(dwarf::DW_LANG_C99,
        "filename.c", "/file/dir", "CloneFunc", false, "", 0);

    DISubprogram Subprogram = DBuilder.createFunction(CU, "f", "f", File, 4,
        FuncType, true, true, 3, 0, false, OldFunc);

    // Function body
    BasicBlock* Entry = BasicBlock::Create(C, "", OldFunc);
    IBuilder.SetInsertPoint(Entry);
    DebugLoc Loc = DebugLoc::get(3, 2, Subprogram);
    IBuilder.SetCurrentDebugLocation(Loc);
    AllocaInst* Alloca = IBuilder.CreateAlloca(IntegerType::getInt32Ty(C));
    IBuilder.SetCurrentDebugLocation(DebugLoc::get(4, 2, Subprogram));
    Value* AllocaContent = IBuilder.getInt32(1);
    Instruction* Store = IBuilder.CreateStore(AllocaContent, Alloca);
    IBuilder.SetCurrentDebugLocation(DebugLoc::get(5, 2, Subprogram));
    Instruction* Terminator = IBuilder.CreateRetVoid();

    // Create a local variable around the alloca
    DIType IntType = DBuilder.createBasicType("int", 32, 0,
        dwarf::DW_ATE_signed);
    DIVariable Variable = DBuilder.createLocalVariable(
      dwarf::DW_TAG_auto_variable, Subprogram, "x", File, 5, IntType, true);
    DBuilder.insertDeclare(Alloca, Variable, Store);
    DBuilder.insertDbgValueIntrinsic(AllocaContent, 0, Variable, Terminator);
    // Finalize the debug info
    DBuilder.finalize();

    // Create another, empty, compile unit
    DIBuilder DBuilder2(*M);
    DBuilder2.createCompileUnit(dwarf::DW_LANG_C99,
        "extra.c", "/file/dir", "CloneFunc", false, "", 0);
    DBuilder2.finalize();
  }

  void CreateNewFunc() {
    ValueToValueMapTy VMap;
    NewFunc = CloneFunction(OldFunc, VMap, true, NULL);
    M->getFunctionList().push_back(NewFunc);
  }

  void SetupFinder() {
    Finder = new DebugInfoFinder();
    Finder->processModule(*M);
  }

  LLVMContext C;
  Function* OldFunc;
  Function* NewFunc;
  Module* M;
  DebugInfoFinder* Finder;
};

// Test that a new, distinct function was created.
TEST_F(CloneFunc, NewFunctionCreated) {
  EXPECT_NE(OldFunc, NewFunc);
}

// Test that a new subprogram entry was added and is pointing to the new
// function, while the original subprogram still points to the old one.
TEST_F(CloneFunc, Subprogram) {
  unsigned SubprogramCount = Finder->subprogram_count();
  EXPECT_EQ(2U, SubprogramCount);

  auto Iter = Finder->subprograms().begin();
  DISubprogram Sub1(*Iter);
  EXPECT_TRUE(Sub1.Verify());
  Iter++;
  DISubprogram Sub2(*Iter);
  EXPECT_TRUE(Sub2.Verify());

  EXPECT_TRUE((Sub1.getFunction() == OldFunc && Sub2.getFunction() == NewFunc)
           || (Sub1.getFunction() == NewFunc && Sub2.getFunction() == OldFunc));
}

// Test that the new subprogram entry was not added to the CU which doesn't
// contain the old subprogram entry.
TEST_F(CloneFunc, SubprogramInRightCU) {
  EXPECT_EQ(2U, Finder->compile_unit_count());

  auto Iter = Finder->compile_units().begin();
  DICompileUnit CU1(*Iter);
  EXPECT_TRUE(CU1.Verify());
  Iter++;
  DICompileUnit CU2(*Iter);
  EXPECT_TRUE(CU2.Verify());
  EXPECT_TRUE(CU1.getSubprograms().getNumElements() == 0
           || CU2.getSubprograms().getNumElements() == 0);
}

// Test that instructions in the old function still belong to it in the
// metadata, while instruction in the new function belong to the new one.
TEST_F(CloneFunc, InstructionOwnership) {
  inst_iterator OldIter = inst_begin(OldFunc);
  inst_iterator OldEnd = inst_end(OldFunc);
  inst_iterator NewIter = inst_begin(NewFunc);
  inst_iterator NewEnd = inst_end(NewFunc);
  while (OldIter != OldEnd && NewIter != NewEnd) {
    Instruction& OldI = *OldIter;
    Instruction& NewI = *NewIter;
    EXPECT_NE(&OldI, &NewI);

    EXPECT_EQ(OldI.hasMetadata(), NewI.hasMetadata());
    if (OldI.hasMetadata()) {
      const DebugLoc& OldDL = OldI.getDebugLoc();
      const DebugLoc& NewDL = NewI.getDebugLoc();

      // Verify that the debug location data is the same
      EXPECT_EQ(OldDL.getLine(), NewDL.getLine());
      EXPECT_EQ(OldDL.getCol(), NewDL.getCol());

      // But that they belong to different functions
      DISubprogram OldSubprogram(OldDL.getScope(C));
      DISubprogram NewSubprogram(NewDL.getScope(C));
      EXPECT_TRUE(OldSubprogram.Verify());
      EXPECT_TRUE(NewSubprogram.Verify());
      EXPECT_EQ(OldFunc, OldSubprogram.getFunction());
      EXPECT_EQ(NewFunc, NewSubprogram.getFunction());
    }

    ++OldIter;
    ++NewIter;
  }
  EXPECT_EQ(OldEnd, OldIter);
  EXPECT_EQ(NewEnd, NewIter);
}

// Test that the arguments for debug intrinsics in the new function were
// properly cloned
TEST_F(CloneFunc, DebugIntrinsics) {
  inst_iterator OldIter = inst_begin(OldFunc);
  inst_iterator OldEnd = inst_end(OldFunc);
  inst_iterator NewIter = inst_begin(NewFunc);
  inst_iterator NewEnd = inst_end(NewFunc);
  while (OldIter != OldEnd && NewIter != NewEnd) {
    Instruction& OldI = *OldIter;
    Instruction& NewI = *NewIter;
    if (DbgDeclareInst* OldIntrin = dyn_cast<DbgDeclareInst>(&OldI)) {
      DbgDeclareInst* NewIntrin = dyn_cast<DbgDeclareInst>(&NewI);
      EXPECT_TRUE(NewIntrin);

      // Old address must belong to the old function
      EXPECT_EQ(OldFunc, cast<AllocaInst>(OldIntrin->getAddress())->
                         getParent()->getParent());
      // New address must belong to the new function
      EXPECT_EQ(NewFunc, cast<AllocaInst>(NewIntrin->getAddress())->
                         getParent()->getParent());

      // Old variable must belong to the old function
      EXPECT_EQ(OldFunc, DISubprogram(DIVariable(OldIntrin->getVariable())
                         .getContext()).getFunction());
      // New variable must belong to the New function
      EXPECT_EQ(NewFunc, DISubprogram(DIVariable(NewIntrin->getVariable())
                         .getContext()).getFunction());
    } else if (DbgValueInst* OldIntrin = dyn_cast<DbgValueInst>(&OldI)) {
      DbgValueInst* NewIntrin = dyn_cast<DbgValueInst>(&NewI);
      EXPECT_TRUE(NewIntrin);

      // Old variable must belong to the old function
      EXPECT_EQ(OldFunc, DISubprogram(DIVariable(OldIntrin->getVariable())
                         .getContext()).getFunction());
      // New variable must belong to the New function
      EXPECT_EQ(NewFunc, DISubprogram(DIVariable(NewIntrin->getVariable())
                         .getContext()).getFunction());
    }

    ++OldIter;
    ++NewIter;
  }
}

}
<commit_msg>Use unique_ptr to handle ownership of Value*s in Cloning unit tests.<commit_after>//===- Cloning.cpp - Unit tests for the Cloner ----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/Transforms/Utils/Cloning.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/IR/Argument.h"
#include "llvm/IR/Constant.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DIBuilder.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstIterator.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LLVMContext.h"
#include "gtest/gtest.h"

#include <set>

using namespace llvm;

namespace {

class CloneInstruction : public ::testing::Test {
protected:
  virtual void SetUp() {
    V = NULL;
  }

  template <typename T>
  T *clone(T *V1) {
    Value *V2 = V1->clone();
    std::unique_ptr<Value> V(V1);
    if (!Orig.insert(std::move(V)).second)
      V.release(); // this wasn't the first time we added the element, so the
                   // set already had ownership
    Clones.insert(std::unique_ptr<Value>(V2));
    return cast<T>(V2);
  }

  void eraseClones() { Clones.clear(); }

  virtual void TearDown() {
    eraseClones();
    Orig.clear();
    V.reset();
  }

  std::set<std::unique_ptr<Value>> Orig;   // Erase on exit
  std::set<std::unique_ptr<Value>> Clones; // Erase in eraseClones

  LLVMContext context;
  std::unique_ptr<Value> V;
};

TEST_F(CloneInstruction, OverflowBits) {
  V = make_unique<Argument>(Type::getInt32Ty(context));

  BinaryOperator *Add =
      BinaryOperator::Create(Instruction::Add, V.get(), V.get());
  BinaryOperator *Sub =
      BinaryOperator::Create(Instruction::Sub, V.get(), V.get());
  BinaryOperator *Mul =
      BinaryOperator::Create(Instruction::Mul, V.get(), V.get());

  BinaryOperator *AddClone = this->clone(Add);
  BinaryOperator *SubClone = this->clone(Sub);
  BinaryOperator *MulClone = this->clone(Mul);

  EXPECT_FALSE(AddClone->hasNoUnsignedWrap());
  EXPECT_FALSE(AddClone->hasNoSignedWrap());
  EXPECT_FALSE(SubClone->hasNoUnsignedWrap());
  EXPECT_FALSE(SubClone->hasNoSignedWrap());
  EXPECT_FALSE(MulClone->hasNoUnsignedWrap());
  EXPECT_FALSE(MulClone->hasNoSignedWrap());

  eraseClones();

  Add->setHasNoUnsignedWrap();
  Sub->setHasNoUnsignedWrap();
  Mul->setHasNoUnsignedWrap();

  AddClone = this->clone(Add);
  SubClone = this->clone(Sub);
  MulClone = this->clone(Mul);

  EXPECT_TRUE(AddClone->hasNoUnsignedWrap());
  EXPECT_FALSE(AddClone->hasNoSignedWrap());
  EXPECT_TRUE(SubClone->hasNoUnsignedWrap());
  EXPECT_FALSE(SubClone->hasNoSignedWrap());
  EXPECT_TRUE(MulClone->hasNoUnsignedWrap());
  EXPECT_FALSE(MulClone->hasNoSignedWrap());

  eraseClones();

  Add->setHasNoSignedWrap();
  Sub->setHasNoSignedWrap();
  Mul->setHasNoSignedWrap();

  AddClone = this->clone(Add);
  SubClone = this->clone(Sub);
  MulClone = this->clone(Mul);

  EXPECT_TRUE(AddClone->hasNoUnsignedWrap());
  EXPECT_TRUE(AddClone->hasNoSignedWrap());
  EXPECT_TRUE(SubClone->hasNoUnsignedWrap());
  EXPECT_TRUE(SubClone->hasNoSignedWrap());
  EXPECT_TRUE(MulClone->hasNoUnsignedWrap());
  EXPECT_TRUE(MulClone->hasNoSignedWrap());

  eraseClones();

  Add->setHasNoUnsignedWrap(false);
  Sub->setHasNoUnsignedWrap(false);
  Mul->setHasNoUnsignedWrap(false);

  AddClone = this->clone(Add);
  SubClone = this->clone(Sub);
  MulClone = this->clone(Mul);

  EXPECT_FALSE(AddClone->hasNoUnsignedWrap());
  EXPECT_TRUE(AddClone->hasNoSignedWrap());
  EXPECT_FALSE(SubClone->hasNoUnsignedWrap());
  EXPECT_TRUE(SubClone->hasNoSignedWrap());
  EXPECT_FALSE(MulClone->hasNoUnsignedWrap());
  EXPECT_TRUE(MulClone->hasNoSignedWrap());
}

TEST_F(CloneInstruction, Inbounds) {
  V = make_unique<Argument>(Type::getInt32PtrTy(context));

  Constant *Z = Constant::getNullValue(Type::getInt32Ty(context));
  std::vector<Value *> ops;
  ops.push_back(Z);
  GetElementPtrInst *GEP = GetElementPtrInst::Create(V.get(), ops);
  EXPECT_FALSE(this->clone(GEP)->isInBounds());

  GEP->setIsInBounds();
  EXPECT_TRUE(this->clone(GEP)->isInBounds());
}

TEST_F(CloneInstruction, Exact) {
  V = make_unique<Argument>(Type::getInt32Ty(context));

  BinaryOperator *SDiv =
      BinaryOperator::Create(Instruction::SDiv, V.get(), V.get());
  EXPECT_FALSE(this->clone(SDiv)->isExact());

  SDiv->setIsExact(true);
  EXPECT_TRUE(this->clone(SDiv)->isExact());
}

TEST_F(CloneInstruction, Attributes) {
  Type *ArgTy1[] = { Type::getInt32PtrTy(context) };
  FunctionType *FT1 =  FunctionType::get(Type::getVoidTy(context), ArgTy1, false);

  Function *F1 = Function::Create(FT1, Function::ExternalLinkage);
  BasicBlock *BB = BasicBlock::Create(context, "", F1);
  IRBuilder<> Builder(BB);
  Builder.CreateRetVoid();

  Function *F2 = Function::Create(FT1, Function::ExternalLinkage);

  Attribute::AttrKind AK[] = { Attribute::NoCapture };
  AttributeSet AS = AttributeSet::get(context, 0, AK);
  Argument *A = F1->arg_begin();
  A->addAttr(AS);

  SmallVector<ReturnInst*, 4> Returns;
  ValueToValueMapTy VMap;
  VMap[A] = UndefValue::get(A->getType());

  CloneFunctionInto(F2, F1, VMap, false, Returns);
  EXPECT_FALSE(F2->arg_begin()->hasNoCaptureAttr());

  delete F1;
  delete F2;
}

TEST_F(CloneInstruction, CallingConvention) {
  Type *ArgTy1[] = { Type::getInt32PtrTy(context) };
  FunctionType *FT1 =  FunctionType::get(Type::getVoidTy(context), ArgTy1, false);

  Function *F1 = Function::Create(FT1, Function::ExternalLinkage);
  F1->setCallingConv(CallingConv::Cold);
  BasicBlock *BB = BasicBlock::Create(context, "", F1);
  IRBuilder<> Builder(BB);
  Builder.CreateRetVoid();

  Function *F2 = Function::Create(FT1, Function::ExternalLinkage);

  SmallVector<ReturnInst*, 4> Returns;
  ValueToValueMapTy VMap;
  VMap[F1->arg_begin()] = F2->arg_begin();

  CloneFunctionInto(F2, F1, VMap, false, Returns);
  EXPECT_EQ(CallingConv::Cold, F2->getCallingConv());

  delete F1;
  delete F2;
}

class CloneFunc : public ::testing::Test {
protected:
  virtual void SetUp() {
    SetupModule();
    CreateOldFunc();
    CreateNewFunc();
    SetupFinder();
  }

  virtual void TearDown() {
    delete Finder;
  }

  void SetupModule() {
    M = new Module("", C);
  }

  void CreateOldFunc() {
    FunctionType* FuncType = FunctionType::get(Type::getVoidTy(C), false);
    OldFunc = Function::Create(FuncType, GlobalValue::PrivateLinkage, "f", M);
    CreateOldFunctionBodyAndDI();
  }

  void CreateOldFunctionBodyAndDI() {
    DIBuilder DBuilder(*M);
    IRBuilder<> IBuilder(C);

    // Function DI
    DIFile File = DBuilder.createFile("filename.c", "/file/dir/");
    DIArray ParamTypes = DBuilder.getOrCreateArray(ArrayRef<Value*>());
    DICompositeType FuncType = DBuilder.createSubroutineType(File, ParamTypes);
    DICompileUnit CU = DBuilder.createCompileUnit(dwarf::DW_LANG_C99,
        "filename.c", "/file/dir", "CloneFunc", false, "", 0);

    DISubprogram Subprogram = DBuilder.createFunction(CU, "f", "f", File, 4,
        FuncType, true, true, 3, 0, false, OldFunc);

    // Function body
    BasicBlock* Entry = BasicBlock::Create(C, "", OldFunc);
    IBuilder.SetInsertPoint(Entry);
    DebugLoc Loc = DebugLoc::get(3, 2, Subprogram);
    IBuilder.SetCurrentDebugLocation(Loc);
    AllocaInst* Alloca = IBuilder.CreateAlloca(IntegerType::getInt32Ty(C));
    IBuilder.SetCurrentDebugLocation(DebugLoc::get(4, 2, Subprogram));
    Value* AllocaContent = IBuilder.getInt32(1);
    Instruction* Store = IBuilder.CreateStore(AllocaContent, Alloca);
    IBuilder.SetCurrentDebugLocation(DebugLoc::get(5, 2, Subprogram));
    Instruction* Terminator = IBuilder.CreateRetVoid();

    // Create a local variable around the alloca
    DIType IntType = DBuilder.createBasicType("int", 32, 0,
        dwarf::DW_ATE_signed);
    DIVariable Variable = DBuilder.createLocalVariable(
      dwarf::DW_TAG_auto_variable, Subprogram, "x", File, 5, IntType, true);
    DBuilder.insertDeclare(Alloca, Variable, Store);
    DBuilder.insertDbgValueIntrinsic(AllocaContent, 0, Variable, Terminator);
    // Finalize the debug info
    DBuilder.finalize();

    // Create another, empty, compile unit
    DIBuilder DBuilder2(*M);
    DBuilder2.createCompileUnit(dwarf::DW_LANG_C99,
        "extra.c", "/file/dir", "CloneFunc", false, "", 0);
    DBuilder2.finalize();
  }

  void CreateNewFunc() {
    ValueToValueMapTy VMap;
    NewFunc = CloneFunction(OldFunc, VMap, true, NULL);
    M->getFunctionList().push_back(NewFunc);
  }

  void SetupFinder() {
    Finder = new DebugInfoFinder();
    Finder->processModule(*M);
  }

  LLVMContext C;
  Function* OldFunc;
  Function* NewFunc;
  Module* M;
  DebugInfoFinder* Finder;
};

// Test that a new, distinct function was created.
TEST_F(CloneFunc, NewFunctionCreated) {
  EXPECT_NE(OldFunc, NewFunc);
}

// Test that a new subprogram entry was added and is pointing to the new
// function, while the original subprogram still points to the old one.
TEST_F(CloneFunc, Subprogram) {
  unsigned SubprogramCount = Finder->subprogram_count();
  EXPECT_EQ(2U, SubprogramCount);

  auto Iter = Finder->subprograms().begin();
  DISubprogram Sub1(*Iter);
  EXPECT_TRUE(Sub1.Verify());
  Iter++;
  DISubprogram Sub2(*Iter);
  EXPECT_TRUE(Sub2.Verify());

  EXPECT_TRUE((Sub1.getFunction() == OldFunc && Sub2.getFunction() == NewFunc)
           || (Sub1.getFunction() == NewFunc && Sub2.getFunction() == OldFunc));
}

// Test that the new subprogram entry was not added to the CU which doesn't
// contain the old subprogram entry.
TEST_F(CloneFunc, SubprogramInRightCU) {
  EXPECT_EQ(2U, Finder->compile_unit_count());

  auto Iter = Finder->compile_units().begin();
  DICompileUnit CU1(*Iter);
  EXPECT_TRUE(CU1.Verify());
  Iter++;
  DICompileUnit CU2(*Iter);
  EXPECT_TRUE(CU2.Verify());
  EXPECT_TRUE(CU1.getSubprograms().getNumElements() == 0
           || CU2.getSubprograms().getNumElements() == 0);
}

// Test that instructions in the old function still belong to it in the
// metadata, while instruction in the new function belong to the new one.
TEST_F(CloneFunc, InstructionOwnership) {
  inst_iterator OldIter = inst_begin(OldFunc);
  inst_iterator OldEnd = inst_end(OldFunc);
  inst_iterator NewIter = inst_begin(NewFunc);
  inst_iterator NewEnd = inst_end(NewFunc);
  while (OldIter != OldEnd && NewIter != NewEnd) {
    Instruction& OldI = *OldIter;
    Instruction& NewI = *NewIter;
    EXPECT_NE(&OldI, &NewI);

    EXPECT_EQ(OldI.hasMetadata(), NewI.hasMetadata());
    if (OldI.hasMetadata()) {
      const DebugLoc& OldDL = OldI.getDebugLoc();
      const DebugLoc& NewDL = NewI.getDebugLoc();

      // Verify that the debug location data is the same
      EXPECT_EQ(OldDL.getLine(), NewDL.getLine());
      EXPECT_EQ(OldDL.getCol(), NewDL.getCol());

      // But that they belong to different functions
      DISubprogram OldSubprogram(OldDL.getScope(C));
      DISubprogram NewSubprogram(NewDL.getScope(C));
      EXPECT_TRUE(OldSubprogram.Verify());
      EXPECT_TRUE(NewSubprogram.Verify());
      EXPECT_EQ(OldFunc, OldSubprogram.getFunction());
      EXPECT_EQ(NewFunc, NewSubprogram.getFunction());
    }

    ++OldIter;
    ++NewIter;
  }
  EXPECT_EQ(OldEnd, OldIter);
  EXPECT_EQ(NewEnd, NewIter);
}

// Test that the arguments for debug intrinsics in the new function were
// properly cloned
TEST_F(CloneFunc, DebugIntrinsics) {
  inst_iterator OldIter = inst_begin(OldFunc);
  inst_iterator OldEnd = inst_end(OldFunc);
  inst_iterator NewIter = inst_begin(NewFunc);
  inst_iterator NewEnd = inst_end(NewFunc);
  while (OldIter != OldEnd && NewIter != NewEnd) {
    Instruction& OldI = *OldIter;
    Instruction& NewI = *NewIter;
    if (DbgDeclareInst* OldIntrin = dyn_cast<DbgDeclareInst>(&OldI)) {
      DbgDeclareInst* NewIntrin = dyn_cast<DbgDeclareInst>(&NewI);
      EXPECT_TRUE(NewIntrin);

      // Old address must belong to the old function
      EXPECT_EQ(OldFunc, cast<AllocaInst>(OldIntrin->getAddress())->
                         getParent()->getParent());
      // New address must belong to the new function
      EXPECT_EQ(NewFunc, cast<AllocaInst>(NewIntrin->getAddress())->
                         getParent()->getParent());

      // Old variable must belong to the old function
      EXPECT_EQ(OldFunc, DISubprogram(DIVariable(OldIntrin->getVariable())
                         .getContext()).getFunction());
      // New variable must belong to the New function
      EXPECT_EQ(NewFunc, DISubprogram(DIVariable(NewIntrin->getVariable())
                         .getContext()).getFunction());
    } else if (DbgValueInst* OldIntrin = dyn_cast<DbgValueInst>(&OldI)) {
      DbgValueInst* NewIntrin = dyn_cast<DbgValueInst>(&NewI);
      EXPECT_TRUE(NewIntrin);

      // Old variable must belong to the old function
      EXPECT_EQ(OldFunc, DISubprogram(DIVariable(OldIntrin->getVariable())
                         .getContext()).getFunction());
      // New variable must belong to the New function
      EXPECT_EQ(NewFunc, DISubprogram(DIVariable(NewIntrin->getVariable())
                         .getContext()).getFunction());
    }

    ++OldIter;
    ++NewIter;
  }
}

}
<|endoftext|>


<commit_before>#include <functional>
#include "Common.h"

#include "CGame.h"
#include "CRenderer.h"
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>

#include <iostream>

namespace odb {

    SDL_Surface *video;

    CRenderer::CRenderer(CControlCallback keyPressedCallback, CControlCallback keyReleasedCallback) :
            mOnKeyPressedCallback(keyPressedCallback), mOnKeyReleasedCallback(keyReleasedCallback) {
        SDL_Init(SDL_INIT_EVERYTHING);
        video = SDL_SetVideoMode(640, 480, 0, 0);
    }

    void CRenderer::sleep(long ms) {
        SDL_Delay(33);
    }

    void CRenderer::handleSystemEvents() {
        SDL_Event event;

        while (SDL_PollEvent(&event)) {

            if (event.type == SDL_QUIT) {
#ifndef __EMSCRIPTEN__
                exit(0);
#endif
            }

            if (event.type == SDL_KEYUP) {
                switch (event.key.keysym.sym) {
                    case SDLK_q:
#ifndef __EMSCRIPTEN__
                        exit(0);
#endif
                    case SDLK_LEFT:
                        mOnKeyReleasedCallback(ECommand::kLeft);
                        break;

                    case SDLK_RIGHT:
                        mOnKeyReleasedCallback(ECommand::kRight);
                        break;

                    case SDLK_UP:
                        mOnKeyReleasedCallback(ECommand::kUp);
                        break;

                    case SDLK_DOWN:
                        mOnKeyReleasedCallback(ECommand::kDown);
                        break;
                    case SDLK_SPACE:
                        mOnKeyReleasedCallback(ECommand::kFire1);
                        break;
                    default:
                        break;
                }
            }

            if (event.type == SDL_KEYDOWN) {
                switch (event.key.keysym.sym) {
                    case SDLK_LEFT:
                        mOnKeyPressedCallback(ECommand::kLeft);
                        break;
                    case SDLK_RIGHT:
                        mOnKeyPressedCallback(ECommand::kRight);
                        break;

                    case SDLK_UP:
                        mOnKeyPressedCallback(ECommand::kUp);
                        break;

                    case SDLK_DOWN:
                        mOnKeyPressedCallback(ECommand::kDown);
                        break;
                    case SDLK_SPACE:
                        mOnKeyPressedCallback(ECommand::kFire1);
                        break;
                    default:
                        break;
                }
            }

        }
    }

    void CRenderer::render(const CGame &game, long ms) {

        SDL_Rect rect;

        switch (game.gameState) {
            case CGame::EGameState::kTitleScreen:
            case CGame::EGameState::kVictory:
            case CGame::EGameState::kGameOver:
            case CGame::EGameState::kGame:

                rect = {0, 0, 640, 241};
                SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 0, 255));

                int delta = 0;

                if (game.track[ game.elementIndex ] == ')') {
                    delta = -1;
                }

                if ( game.track[ game.elementIndex ] == '(') {
                    delta = 1;
                }

                int distance = 0;

                if ( game.distanceToNextElement > 50 ) {
                    distance = ( 100 - game.distanceToNextElement );
                } else {
                    distance = ( game.distanceToNextElement );
                }

                for ( int y = 1; y < 240; ++y ) {
                    int curveFactor = ( (240 * distance * delta) / y );
                    int cameraFactor = - ( (y * game.x) / 240);
                    int roadX =  curveFactor  + 320 - (y) + cameraFactor;
                    int roadDeltaX = 32 + (y * 2);
                    int shade = ( y / 4);
                    bool stripe = (( ( 240 / y) % 2)) == 0;

                    rect = {0, y, 640, 1};
                    SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 0, 128 + shade / 2));

                    if ( stripe ) {
                        shade = shade * 4;
                    }

                    rect = {0, 240 + y, 640, 1};
                    SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 128 + shade / 2, 0));

                    rect = { roadX, 240 + y, roadDeltaX, 1};

                    SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 64 + shade, 64 + shade, 64 + shade));

                }

                rect = SDL_Rect{0, 0, 80, 40};
                rect.x = 320 + (game.x );
                rect.y = 440;

                SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 0, 0));

                SDL_Flip(video);
        }
    }
}
<commit_msg>Add 3D projection code<commit_after>#include <functional>
#include "Common.h"

#include "CGame.h"
#include "CRenderer.h"
#include <SDL/SDL.h>
#include <SDL/SDL_mixer.h>

#include <iostream>

namespace odb {

    SDL_Surface *video;

    CRenderer::CRenderer(CControlCallback keyPressedCallback, CControlCallback keyReleasedCallback) :
            mOnKeyPressedCallback(keyPressedCallback), mOnKeyReleasedCallback(keyReleasedCallback) {
        SDL_Init(SDL_INIT_EVERYTHING);
        video = SDL_SetVideoMode(640, 480, 0, 0);
    }

    void CRenderer::sleep(long ms) {
        SDL_Delay(33);
    }

    void CRenderer::handleSystemEvents() {
        SDL_Event event;

        while (SDL_PollEvent(&event)) {

            if (event.type == SDL_QUIT) {
#ifndef __EMSCRIPTEN__
                exit(0);
#endif
            }

            if (event.type == SDL_KEYUP) {
                switch (event.key.keysym.sym) {
                    case SDLK_q:
#ifndef __EMSCRIPTEN__
                        exit(0);
#endif
                    case SDLK_LEFT:
                        mOnKeyReleasedCallback(ECommand::kLeft);
                        break;

                    case SDLK_RIGHT:
                        mOnKeyReleasedCallback(ECommand::kRight);
                        break;

                    case SDLK_UP:
                        mOnKeyReleasedCallback(ECommand::kUp);
                        break;

                    case SDLK_DOWN:
                        mOnKeyReleasedCallback(ECommand::kDown);
                        break;
                    case SDLK_SPACE:
                        mOnKeyReleasedCallback(ECommand::kFire1);
                        break;
                    default:
                        break;
                }
            }

            if (event.type == SDL_KEYDOWN) {
                switch (event.key.keysym.sym) {
                    case SDLK_LEFT:
                        mOnKeyPressedCallback(ECommand::kLeft);
                        break;
                    case SDLK_RIGHT:
                        mOnKeyPressedCallback(ECommand::kRight);
                        break;

                    case SDLK_UP:
                        mOnKeyPressedCallback(ECommand::kUp);
                        break;

                    case SDLK_DOWN:
                        mOnKeyPressedCallback(ECommand::kDown);
                        break;
                    case SDLK_SPACE:
                        mOnKeyPressedCallback(ECommand::kFire1);
                        break;
                    default:
                        break;
                }
            }

        }
    }

    struct vec3 {
        vec3(float aX, float aY, float aZ) : x(aX), y(aY), z(aZ) {
        }

        float x = 0;
        float y = 0;
        float z = 0;
    };

    struct vec2 {
        vec2(float aX, float aY) : x(aX), y(aY) {
        }

        float x = 0;
        float y = 0;
    };

    vec2 project(vec3 v) {
        float xz = v.x / (1.0f - v.z);
        float yz = v.y / (1.0f - v.z);

        vec2 v2(320 + (xz * 640), 240 - (yz * 480));
        return v2;
    }
    void CRenderer::render(const CGame &game, long ms) {

        SDL_Rect rect;

        switch (game.gameState) {
            case CGame::EGameState::kTitleScreen:
            case CGame::EGameState::kVictory:
            case CGame::EGameState::kGameOver:
            case CGame::EGameState::kGame:

                rect = {0, 0, 640, 241};
                SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 0, 255));

                int delta = 0;

                if (game.track[ game.elementIndex ] == ')') {
                    delta = -1;
                }

                if ( game.track[ game.elementIndex ] == '(') {
                    delta = 1;
                }

                int distance = 0;

                if ( game.distanceToNextElement > 50 ) {
                    distance = ( 100 - game.distanceToNextElement );
                } else {
                    distance = ( game.distanceToNextElement );
                }

                for ( int y = 1; y < 240; ++y ) {
                    int curveFactor = ( (240 * distance * delta) / y );
                    int cameraFactor = - ( (y * game.x) / 240);
                    int roadX =  curveFactor  + 320 - (y) + cameraFactor;
                    int roadDeltaX = 32 + (y * 2);
                    int shade = ( y / 4);
                    bool stripe = (( ( 240 / y) % 2)) == 0;

                    rect = {0, y, 640, 1};
                    SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 0, 128 + shade / 2));

                    if ( stripe ) {
                        shade = shade * 4;
                    }

                    rect = {0, 240 + y, 640, 1};
                    SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 0, 128 + shade / 2, 0));

                    rect = { roadX, 240 + y, roadDeltaX, 1};

                    SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 64 + shade, 64 + shade, 64 + shade));

                }

                rect = SDL_Rect{0, 0, 80, 40};
                rect.x = 320 + (game.x );
                rect.y = 440;

                SDL_FillRect(video, &rect, SDL_MapRGB(video->format, 255, 0, 0));

                SDL_Flip(video);
        }
    }
}
<|endoftext|>


<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Framework/Assert.h"
#include "SurgSim/Framework/Timer.h"

namespace SurgSim {
namespace Framework {

Timer::Timer() :
	m_stopped(true), m_numberOfFrames(100), m_clockFails(0)
{
	start();
}

void Timer::start()
{
	m_frameDurations.clear();
	m_clockFails = 0;
	beginFrame();
}

void Timer::beginFrame()
{
	m_lastTime = now();
}

void Timer::endFrame()
{
	TimerTimePoint currentTime = now();
	m_frameDurations.push_back(currentTime - m_lastTime);
	if (m_frameDurations.size() > m_numberOfFrames)
	{
		m_frameDurations.pop_front();
	}
	m_lastTime = currentTime;
}

double Timer::getAverageFramePeriod() const
{
	SURGSIM_ASSERT(m_frameDurations.size() > 0) << "Attempted to access the last frame period for a Timer with no frames.\n";
	TimerDuration cumulativeTime;
	for (auto it = m_frameDurations.begin(); it != m_frameDurations.end(); ++it)
	{
		cumulativeTime += *it;
	}
	return cumulativeTime.count() / m_frameDurations.size();
}

double Timer::getAverageFrameRate() const
{
	return 1.0 / getAverageFramePeriod();
}

double Timer::getLastFramePeriod() const
{
	SURGSIM_ASSERT(m_frameDurations.size() > 0) << "Attempted to access the last frame period for a Timer with no frames.\n";
	return m_frameDurations.back().count();
}

double Timer::getLastFrameRate() const
{
	return 1.0 / getLastFramePeriod();
}

void Timer::setNumberOfFrames(size_t numberOfFrames)
{
	m_numberOfFrames = (numberOfFrames > 0) ? numberOfFrames : 1;
	while (m_frameDurations.size() > m_numberOfFrames)
	{
		m_frameDurations.pop_front();
	}
}

size_t Timer::getCurrentNumberOfFrames() const
{
	return m_frameDurations.size();
}

size_t Timer::getNumberOfClockFails() const
{
	return m_clockFails;
}

Timer::TimerTimePoint Timer::now()
{
	boost::system::error_code ec;
	TimerTimePoint currentTime = m_clock.now(ec);
	if (ec.value() != 0)
	{
		int failsThisCall = 0;
		while (ec.value() != 0)
		{
			SURGSIM_ASSERT(++failsThisCall < 4) << "A Timer's clock failed four consecutive calls.";
			currentTime = m_clock.now(ec);
		}
		m_clockFails += failsThisCall;
	}
	return currentTime;
}

}; // namespace Framework
}; // namespace SurgSim
<commit_msg>Remove while-loop waiting for non-failed clock time in Timer::now.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Framework/Assert.h"
#include "SurgSim/Framework/Timer.h"

namespace SurgSim {
namespace Framework {

Timer::Timer() :
	m_stopped(true), m_numberOfFrames(100), m_clockFails(0)
{
	start();
}

void Timer::start()
{
	m_frameDurations.clear();
	m_clockFails = 0;
	beginFrame();
}

void Timer::beginFrame()
{
	m_lastTime = now();
}

void Timer::endFrame()
{
	TimerTimePoint currentTime = now();
	m_frameDurations.push_back(currentTime - m_lastTime);
	if (m_frameDurations.size() > m_numberOfFrames)
	{
		m_frameDurations.pop_front();
	}
	m_lastTime = currentTime;
}

double Timer::getAverageFramePeriod() const
{
	SURGSIM_ASSERT(m_frameDurations.size() > 0) << "Attempted to access the last frame period for a Timer with no frames.\n";
	TimerDuration cumulativeTime;
	for (auto it = m_frameDurations.begin(); it != m_frameDurations.end(); ++it)
	{
		cumulativeTime += *it;
	}
	return cumulativeTime.count() / m_frameDurations.size();
}

double Timer::getAverageFrameRate() const
{
	return 1.0 / getAverageFramePeriod();
}

double Timer::getLastFramePeriod() const
{
	SURGSIM_ASSERT(m_frameDurations.size() > 0) << "Attempted to access the last frame period for a Timer with no frames.\n";
	return m_frameDurations.back().count();
}

double Timer::getLastFrameRate() const
{
	return 1.0 / getLastFramePeriod();
}

void Timer::setNumberOfFrames(size_t numberOfFrames)
{
	m_numberOfFrames = (numberOfFrames > 0) ? numberOfFrames : 1;
	while (m_frameDurations.size() > m_numberOfFrames)
	{
		m_frameDurations.pop_front();
	}
}

size_t Timer::getCurrentNumberOfFrames() const
{
	return m_frameDurations.size();
}

size_t Timer::getNumberOfClockFails() const
{
	return m_clockFails;
}

Timer::TimerTimePoint Timer::now()
{
	boost::system::error_code ec;
	TimerTimePoint currentTime = m_clock.now(ec);
	if (ec.value() != 0)
	{
		++ m_clockFails;
	}
	return currentTime;
}

}; // namespace Framework
}; // namespace SurgSim
<|endoftext|>


<commit_before>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "asset.h"
#include "game.h"

#include <core/metainfo.h>

#include <QtGui/QAction>
#include <QtCore/QStringList>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QMimeData>

REGISTER_OBJECTTYPE( GluonEngine, Asset )

using namespace GluonEngine;

class GluonEngine::AssetPrivate
{
    public:
        AssetPrivate()
        {
            loaded = false;
            mime = 0;
        }

        QUrl file;
        bool loaded;
        QMimeData* mime;
};

Asset::Asset( QObject* parent )
    : GluonObject( parent )
    , d( new AssetPrivate )
{
    d->mime = new QMimeData;
}

Asset::~Asset()
{
    delete d->mime;
    delete d;
}

void
Asset::setName( const QString& newName )
{
    QString oldName( name() );

    GluonCore::GluonObject::setName( newName );

    // Rename the underlying file, if one exists...
    if( !d->file.isEmpty() )
    {
        // If we use QDir::current(), .exists will throw debug crap... this works around that particular annoyance
        if( QDir( QDir::currentPath() ).exists( d->file.toLocalFile() ) )
        {
            QUrl newFile = Asset::fullyQualifiedFileName( this, QFileInfo( d->file.toLocalFile() ).completeSuffix() );

            QString oldPath = d->file.toLocalFile().section( '/', 0, -2 );
            QString newPath = newFile.toLocalFile().section( '/', 0, -2 );
            QDir::current().mkpath( newPath );

            if( QDir::current().rename( d->file.toLocalFile(), newFile.toLocalFile() ) )
            {
                if( QDir::current().exists( oldPath ) )
                    QDir::current().rmpath( oldPath );
                setFile( newFile );
            }
        }
    }
}

void
Asset::setFile( const QUrl& newFile )
{
    if(!d->file.isEmpty())
    {
        QString oldPath = d->file.toLocalFile().section( '/', 0, -2 );
        if( QDir::current().exists( oldPath ) )
            QDir::current().rmpath( oldPath );
    }
    QString newPath = newFile.toLocalFile().section( '/', 0, -2 );
    QDir::current().mkpath( newPath );
    d->file = newFile;
    emit dataChanged();
}

QUrl
Asset::file() const
{
    return d->file;
}

QString
Asset::absolutePath() const
{
    return d->file.toLocalFile();
}

QIcon
Asset::icon() const
{
    return QIcon();
}

const QMimeData *
Asset::data() const
{
    return d->mime;
}

const QList<AssetTemplate*>
Asset::templates()
{
    QList<AssetTemplate*> templates;
    return templates;
}

QList<QAction*>
Asset::actions()
{
    return QList<QAction*>();
}

bool
Asset::isLoaded() const
{
    return d->loaded;
}

void
Asset::load()
{
    d->loaded = true;
    emit dataChanged();
}

void Asset::unload()
{
    d->loaded = false;
}

void
Asset::reload()
{
    unload();
    load();
}

bool
Asset::shouldSerializeChildren( ) const
{
    // We do not recurse here - this allows the assets to handle their own
    // children
    return false;
}

QMimeData *
Asset::mimeData() const
{
    return d->mime;
}

void
Asset::setLoaded( bool loaded )
{
    d->loaded = loaded;
}

QUrl
Asset::fullyQualifiedFileName(GluonCore::GluonObject* obj, const QString& extension)
{
    DEBUG_FUNC_NAME
    QStringList parts = obj->fullyQualifiedName().split('/');
    if(parts.count() > 1 && parts.first() == obj->gameProject()->name())
        parts.removeFirst();

    QRegExp filter("[^a-z0-9_]+");

    QString file = parts.last().toLower().replace(' ','_').replace(filter, "");
    parts.removeLast();

    QStringList path;
    foreach(const QString& part, parts)
    {
        path.append(part.toLower().replace(' ', '_').replace(filter, ""));
    }

    QString dir = path.join("/");
    if(dir.length() > 0)
        dir.append('/');

    QString ext = extension.isEmpty() ? obj->metaInfo()->defaultExtension() : extension;
    return QUrl( QString("%1%2.%3").arg(dir, file, ext) );
}

#include "asset.moc"

<commit_msg>Revert the previous commit about the filepath since that is relative<commit_after>/******************************************************************************
 * This file is part of the Gluon Development Platform
 * Copyright (c) 2010 Arjen Hiemstra <ahiemstra@heimr.nl>
 * Copyright (C) 2010 Dan Leinir Turthra Jensen <admin@leinir.dk>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "asset.h"
#include "game.h"

#include <core/metainfo.h>

#include <QtGui/QAction>
#include <QtCore/QStringList>
#include <QtCore/QFile>
#include <QtCore/QDir>
#include <QtCore/QMimeData>

REGISTER_OBJECTTYPE( GluonEngine, Asset )

using namespace GluonEngine;

class GluonEngine::AssetPrivate
{
    public:
        AssetPrivate()
        {
            loaded = false;
            mime = 0;
        }

        QUrl file;
        bool loaded;
        QMimeData* mime;
};

Asset::Asset( QObject* parent )
    : GluonObject( parent )
    , d( new AssetPrivate )
{
    d->mime = new QMimeData;
}

Asset::~Asset()
{
    delete d->mime;
    delete d;
}

void
Asset::setName( const QString& newName )
{
    QString oldName( name() );

    GluonCore::GluonObject::setName( newName );

    // Rename the underlying file, if one exists...
    if( !d->file.isEmpty() )
    {
        // If we use QDir::current(), .exists will throw debug crap... this works around that particular annoyance
        if( QDir( QDir::currentPath() ).exists( d->file.toLocalFile() ) )
        {
            QUrl newFile = Asset::fullyQualifiedFileName( this, QFileInfo( d->file.toLocalFile() ).completeSuffix() );

            QString oldPath = d->file.toLocalFile().section( '/', 0, -2 );
            QString newPath = newFile.toLocalFile().section( '/', 0, -2 );
            QDir::current().mkpath( newPath );

            if( QDir::current().rename( d->file.toLocalFile(), newFile.toLocalFile() ) )
            {
                if( QDir::current().exists( oldPath ) )
                    QDir::current().rmpath( oldPath );
                setFile( newFile );
            }
        }
    }
}

void
Asset::setFile( const QUrl& newFile )
{
    if(!d->file.isEmpty())
    {
        QString oldPath = d->file.toLocalFile().section( '/', 0, -2 );
        if( QDir::current().exists( oldPath ) )
            QDir::current().rmpath( oldPath );
    }
    QString newPath = newFile.toLocalFile().section( '/', 0, -2 );
    QDir::current().mkpath( newPath );
    d->file = newFile;
    emit dataChanged();
}

QUrl
Asset::file() const
{
    return d->file;
}

QString
Asset::absolutePath() const
{
    return GluonEngine::Game::instance()->gameProject()->dirname().toLocalFile() + '/' + d->file.toLocalFile();
}

QIcon
Asset::icon() const
{
    return QIcon();
}

const QMimeData *
Asset::data() const
{
    return d->mime;
}

const QList<AssetTemplate*>
Asset::templates()
{
    QList<AssetTemplate*> templates;
    return templates;
}

QList<QAction*>
Asset::actions()
{
    return QList<QAction*>();
}

bool
Asset::isLoaded() const
{
    return d->loaded;
}

void
Asset::load()
{
    d->loaded = true;
    emit dataChanged();
}

void Asset::unload()
{
    d->loaded = false;
}

void
Asset::reload()
{
    unload();
    load();
}

bool
Asset::shouldSerializeChildren( ) const
{
    // We do not recurse here - this allows the assets to handle their own
    // children
    return false;
}

QMimeData *
Asset::mimeData() const
{
    return d->mime;
}

void
Asset::setLoaded( bool loaded )
{
    d->loaded = loaded;
}

QUrl
Asset::fullyQualifiedFileName(GluonCore::GluonObject* obj, const QString& extension)
{
    DEBUG_FUNC_NAME
    QStringList parts = obj->fullyQualifiedName().split('/');
    if(parts.count() > 1 && parts.first() == obj->gameProject()->name())
        parts.removeFirst();

    QRegExp filter("[^a-z0-9_]+");

    QString file = parts.last().toLower().replace(' ','_').replace(filter, "");
    parts.removeLast();

    QStringList path;
    foreach(const QString& part, parts)
    {
        path.append(part.toLower().replace(' ', '_').replace(filter, ""));
    }

    QString dir = path.join("/");
    if(dir.length() > 0)
        dir.append('/');

    QString ext = extension.isEmpty() ? obj->metaInfo()->defaultExtension() : extension;
    return QUrl( QString("%1%2.%3").arg(dir, file, ext) );
}

#include "asset.moc"

<|endoftext|>


<commit_before>/*
 * Skaffari - a mail account administration web interface based on Cutelyst
 * Copyright (C) 2017 Matthias Fehring <kontakt@buschmann23.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "timezoneconverttag.h"

#include <grantlee/exception.h>
#include <grantlee/parser.h>
#include <grantlee/safestring.h>

#include <Cutelyst/Context>
#include <Cutelyst/Plugins/Session/Session>

#include <QLocale>
#include <QDateTime>
#include <QTimeZone>

Grantlee::Node *TimeZoneConvertTag::getNode(const QString &tagContent, Grantlee::Parser *p) const
{
    QStringList parts = smartSplit(tagContent);
    parts.removeFirst();
    if (parts.empty()) {
        throw Grantlee::Exception(Grantlee::TagSyntaxError, QStringLiteral("sk_tzc requires at least the date or time"));
    }

    Grantlee::FilterExpression dateTime(parts.at(0), p);

    Grantlee::FilterExpression format;
    if (parts.size() > 1) {
        format = Grantlee::FilterExpression(parts.at(1), p);
    }

    return new TimeZoneConvert(dateTime, format, p);
}

TimeZoneConvert::TimeZoneConvert(const Grantlee::FilterExpression &dateTime, const Grantlee::FilterExpression &format, Grantlee::Parser *parser) :
    Grantlee::Node(parser), m_dateTime(dateTime), m_format(format)
{

}

void TimeZoneConvert::render(Grantlee::OutputStream *stream, Grantlee::Context *gc) const
{
    const QVariant dtVar = m_dateTime.resolve(gc);
    const int dtVarType = dtVar.userType();
    if (dtVarType == qMetaTypeId<Grantlee::SafeString>()) {
        *stream << dtVar.value<Grantlee::SafeString>().get();
        return;
    } else if (dtVarType == QVariant::String) {
        *stream << dtVar.toString();
        return;
    } else {
        if (dtVar.userType() != QVariant::DateTime) {
            qWarning("%s", "sk_tzc can only operate on QDateTime values.");
            return;
        }
    }

    auto c = gc->lookup(m_cutelystContext).value<Cutelyst::Context *>();
    if (!c) {
        const QVariantHash hash = gc->stackHash(0);
        auto it = hash.constBegin();
        while (it != hash.constEnd()) {
            if (it.value().userType() == qMetaTypeId<Cutelyst::Context *>()) {
                c = it.value().value<Cutelyst::Context *>();
                if (c) {
                    m_cutelystContext = it.key();
                    break;
                }
            }
            ++it;
        }
    }

    if (!c) {
        qWarning("%s", "Can not find Cutelyst context.");
        return;
    }

    QDateTime dtVal = dtVar.toDateTime();
    QDateTime retVal;

    QTimeZone userTz(Cutelyst::Session::value(c, QStringLiteral("tz"), QStringLiteral("UTZ")).toByteArray());
    if (Q_UNLIKELY(!userTz.isValid())) {
        userTz = QTimeZone::utc();
    }

    if (userTz != QTimeZone::utc()) {
        dtVal.setTimeSpec(Qt::UTC);
        retVal = dtVal.toTimeZone(userTz);
    } else {
        retVal = dtVal;
    }

    QString formatString;
    if (m_format.isValid()) {
        const QVariant formatVar = m_format.resolve(gc);
        const int formatVarType = formatVar.userType();
        if (formatVarType == qMetaTypeId<Grantlee::SafeString>()) {
            formatString = formatVar.value<Grantlee::SafeString>().get();
        } else if (formatVarType == QVariant::String) {
            formatString = formatVar.toString();
        }
    }

    if (formatString.isEmpty()) {
        *stream << c->locale().toString(retVal, QLocale::ShortFormat);
    } else {
        *stream << c->locale().toString(retVal, formatString);
    }
}
<commit_msg>Fix typo<commit_after>/*
 * Skaffari - a mail account administration web interface based on Cutelyst
 * Copyright (C) 2017 Matthias Fehring <kontakt@buschmann23.de>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "timezoneconverttag.h"

#include <grantlee/exception.h>
#include <grantlee/parser.h>
#include <grantlee/safestring.h>

#include <Cutelyst/Context>
#include <Cutelyst/Plugins/Session/Session>

#include <QLocale>
#include <QDateTime>
#include <QTimeZone>

Grantlee::Node *TimeZoneConvertTag::getNode(const QString &tagContent, Grantlee::Parser *p) const
{
    QStringList parts = smartSplit(tagContent);
    parts.removeFirst();
    if (parts.empty()) {
        throw Grantlee::Exception(Grantlee::TagSyntaxError, QStringLiteral("sk_tzc requires at least the date or time"));
    }

    Grantlee::FilterExpression dateTime(parts.at(0), p);

    Grantlee::FilterExpression format;
    if (parts.size() > 1) {
        format = Grantlee::FilterExpression(parts.at(1), p);
    }

    return new TimeZoneConvert(dateTime, format, p);
}

TimeZoneConvert::TimeZoneConvert(const Grantlee::FilterExpression &dateTime, const Grantlee::FilterExpression &format, Grantlee::Parser *parser) :
    Grantlee::Node(parser), m_dateTime(dateTime), m_format(format)
{

}

void TimeZoneConvert::render(Grantlee::OutputStream *stream, Grantlee::Context *gc) const
{
    const QVariant dtVar = m_dateTime.resolve(gc);
    const int dtVarType = dtVar.userType();
    if (dtVarType == qMetaTypeId<Grantlee::SafeString>()) {
        *stream << dtVar.value<Grantlee::SafeString>().get();
        return;
    } else if (dtVarType == QVariant::String) {
        *stream << dtVar.toString();
        return;
    } else {
        if (dtVar.userType() != QVariant::DateTime) {
            qWarning("%s", "sk_tzc can only operate on QDateTime values.");
            return;
        }
    }

    auto c = gc->lookup(m_cutelystContext).value<Cutelyst::Context *>();
    if (!c) {
        const QVariantHash hash = gc->stackHash(0);
        auto it = hash.constBegin();
        while (it != hash.constEnd()) {
            if (it.value().userType() == qMetaTypeId<Cutelyst::Context *>()) {
                c = it.value().value<Cutelyst::Context *>();
                if (c) {
                    m_cutelystContext = it.key();
                    break;
                }
            }
            ++it;
        }
    }

    if (!c) {
        qWarning("%s", "Can not find Cutelyst context.");
        return;
    }

    QDateTime dtVal = dtVar.toDateTime();
    QDateTime retVal;

    QTimeZone userTz(Cutelyst::Session::value(c, QStringLiteral("tz"), QStringLiteral("UTC")).toByteArray());
    if (Q_UNLIKELY(!userTz.isValid())) {
        userTz = QTimeZone::utc();
    }

    if (userTz != QTimeZone::utc()) {
        dtVal.setTimeSpec(Qt::UTC);
        retVal = dtVal.toTimeZone(userTz);
    } else {
        retVal = dtVal;
    }

    QString formatString;
    if (m_format.isValid()) {
        const QVariant formatVar = m_format.resolve(gc);
        const int formatVarType = formatVar.userType();
        if (formatVarType == qMetaTypeId<Grantlee::SafeString>()) {
            formatString = formatVar.value<Grantlee::SafeString>().get();
        } else if (formatVarType == QVariant::String) {
            formatString = formatVar.toString();
        }
    }

    if (formatString.isEmpty()) {
        *stream << c->locale().toString(retVal, QLocale::ShortFormat);
    } else {
        *stream << c->locale().toString(retVal, formatString);
    }
}
<|endoftext|>


<commit_before>// bsls_assert.cpp                                                    -*-C++-*-
#include <bsls_assert.h>

#include <bsls_ident.h>
BSLS_IDENT("$Id$ $CSID$")

#include <bsls_asserttestexception.h>
#include <bsls_pointercastutil.h>
#include <bsls_types.h>
#include <bsls_log.h>
#include <bsls_logseverity.h>

#include <exception>

#include <cstdio>
#include <cstdlib>
#include <cstring>

#ifdef BSLS_PLATFORM_OS_AIX
#include <signal.h>
#endif

#ifdef BSLS_PLATFORM_OS_UNIX
#include <unistd.h>    // 'sleep'
#endif

#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h>   // IsDebbugerPresent
#include <crtdbg.h>    // '_CrtSetReportMode', to suppress pop-ups

typedef unsigned long DWORD;

extern "C" {
    __declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds);
};
#endif

#ifdef BSLS_ASSERT_NORETURN
#error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file
#endif

// Note that a portable syntax for 'noreturn' will be available once we have
// access to conforming C++0x compilers.
//# define BSLS_ASSERT_NORETURN [[noreturn]]

#ifdef BSLS_PLATFORM_CMP_MSVC
#   define BSLS_ASSERT_NORETURN __declspec(noreturn)
#else
#   define BSLS_ASSERT_NORETURN
#endif

namespace BloombergLP {

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// We want to print the error message to 'stderr', not 'stdout'.   The old
// documentation for 'printError' is:
//..
//  Print a formatted error message to standard output.  (Most Bloomberg
//  processes will send standard output to a log file.)
//..
// TBD: find out whether 'stderr' goes to 'act.log'.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

static
void printError(const char *text, const char *file, int line)
    // Print a formatted error message to 'stderr' using the specified
    // expression 'text', 'file' name, and 'line' number.  If either
    // 'text' or 'file' is empty ("") or null (0), replace it with some
    // informative, "human-readable" text, before formatting.
{
    if (!text) {
        text = "(* Unspecified Expression Text *)";
    }
    else if (!*text) {
        text = "(* Empty Expression Text *)";
    }

    if (!file) {
        file = "(* Unspecified File Name *)";
    }
    else if (!*file) {
        file = "(* Empty File Name *)";
    }

    bsls::Log::logFormattedMessage(
        bsls::LogSeverity::e_ERROR, file, line, "Assertion failed: %s", text);
}

namespace bsls {

                                // ------------
                                // class Assert
                                // ------------

// CLASS DATA
bsls::AtomicOperations::AtomicTypes::Pointer
    Assert::s_handler = {(void *) &Assert::failAbort};
bsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0};

// CLASS METHODS
void Assert::setFailureHandlerRaw(Assert::Handler function)
{
    bsls::AtomicOperations::setPtrRelease(
        &s_handler, PointerCastUtil::cast<void *>(function));
}

void Assert::setFailureHandler(Assert::Handler function)
{
    if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) {
        setFailureHandlerRaw(function);
    }
}

void Assert::lockAssertAdministration()
{
    bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1);
}

Assert::Handler Assert::failureHandler()
{
    return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler);
}

                       // Macro Dispatcher Method

#define IS_POWER_OF_TWO(X) (0 == ((X) & ((X) - 1)))

BSLS_ASSERT_NORETURN_INVOKE_HANDLER
void Assert::invokeHandler(const char *text, const char *file, int line)
{
    static AtomicOperations::AtomicTypes::Int failureReturnCount = {0};

    Assert::Handler currentHandlerAddress = failureHandler();

    currentHandlerAddress(text, file, line);

    // The failure handler should not return.  If a returning failure handler
    // has been installed, alert the user that the program is continuing to
    // run.

    unsigned count = static_cast<unsigned>(
                AtomicOperations::incrementIntNvAcqRel(&failureReturnCount));

    if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(IS_POWER_OF_TWO(count))) {
        BSLS_PERFORMANCEHINT_UNLIKELY_HINT;

        // Log when 'count' is a power of 2.

        if (count == (1 << 30)) {
            // Avoid undefined behavior by resetting the counter.

            AtomicOperations::setInt(&failureReturnCount, 1 << 29);
        }

        Log::logFormattedMessage(LogSeverity::e_FATAL,
                                 file,
                                 line,
                                 "BSLS_ASSERT failure: '%s'",
                                 text);

        BSLS_LOG_FATAL("Bad 'bsls_assert' configuration: "
                       "violation handler at %p failed to prevent program "
                       "from continuing.",
                       currentHandlerAddress);
    }

#ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER
    std::abort();
#endif
}

                     // Standard Assertion-Failure Handlers

BSLS_ASSERT_NORETURN
void Assert::failAbort(const char *text, const char *file, int line)
{
    printError(text, file, line);

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
    // See DRQS 8923441: The following is a work-around for a Fortran compiler bug.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

#ifdef BSLS_PLATFORM_OS_AIX
    sigset_t newset;
    sigemptyset(&newset);
    sigaddset(&newset, SIGABRT);
#if defined(BDE_BUILD_TARGET_MT)
    pthread_sigmask(SIG_UNBLOCK, &newset, 0);
#else
    sigprocmask(SIG_UNBLOCK, &newset, 0);
#endif
#endif

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
    // See DRQS 13882128: Note that (according to Oleg) the first line alone may be
    // sufficient.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

#ifdef BSLS_PLATFORM_OS_WINDOWS
    // The following configures the runtime library on how to report asserts,
    // errors, and warnings in order to avoid pop-up windows when 'abort' is
    // called.
    if (!IsDebuggerPresent()) {
        _CrtSetReportMode(_CRT_ASSERT, 0);
        _CrtSetReportMode(_CRT_ERROR, 0);
        _CrtSetReportMode(_CRT_WARN, 0);
    }
#endif

    std::abort();
}

BSLS_ASSERT_NORETURN
void Assert::failSleep(const char *text, const char *file, int line)
{
    printError(text, file, line);

    volatile int sleepDuration = 1;

    while (1 == sleepDuration) {

#if defined(BSLS_PLATFORM_OS_UNIX)
        sleep(sleepDuration);
#elif defined(BSLS_PLATFORM_OS_WINDOWS)
        Sleep(sleepDuration * 1000);  // milliseconds
#else
        #error "Do not know how to sleep on this platform."
#endif

    }

    // We will never reach this line, but it is needed to let the compiler know
    // that this function does not return.

    std::abort();
}

BSLS_ASSERT_NORETURN
void Assert::failThrow(const char *text, const char *file, int line)
{

#ifdef BDE_BUILD_TARGET_EXC
    if (!std::uncaught_exception()) {
        throw AssertTestException(text, file, line);
    }
    else {
        bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line,
                "BSLS_ASSERT: An uncaught exception is pending;"
                " cannot throw 'AssertTestException'.");
    }
#endif

    failAbort(text, file, line);
}

}  // close package namespace

#undef BSLS_ASSERT_NORETURN

namespace bsls {

                    // -------------------------------
                    // class AssertFailureHandlerGuard
                    // -------------------------------

AssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary)
: d_original(Assert::failureHandler())
{
    Assert::setFailureHandlerRaw(temporary);
}

AssertFailureHandlerGuard::~AssertFailureHandlerGuard()
{
    Assert::setFailureHandlerRaw(d_original);
}

}  // close package namespace

}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<commit_msg>Update log message.<commit_after>// bsls_assert.cpp                                                    -*-C++-*-
#include <bsls_assert.h>

#include <bsls_ident.h>
BSLS_IDENT("$Id$ $CSID$")

#include <bsls_asserttestexception.h>
#include <bsls_pointercastutil.h>
#include <bsls_types.h>
#include <bsls_log.h>
#include <bsls_logseverity.h>

#include <exception>

#include <cstdio>
#include <cstdlib>
#include <cstring>

#ifdef BSLS_PLATFORM_OS_AIX
#include <signal.h>
#endif

#ifdef BSLS_PLATFORM_OS_UNIX
#include <unistd.h>    // 'sleep'
#endif

#ifdef BSLS_PLATFORM_OS_WINDOWS
#include <windows.h>   // IsDebbugerPresent
#include <crtdbg.h>    // '_CrtSetReportMode', to suppress pop-ups

typedef unsigned long DWORD;

extern "C" {
    __declspec(dllimport) void __stdcall Sleep(DWORD dwMilliseconds);
};
#endif

#ifdef BSLS_ASSERT_NORETURN
#error BSLS_ASSERT_NORETURN must be a macro scoped locally to this file
#endif

// Note that a portable syntax for 'noreturn' will be available once we have
// access to conforming C++0x compilers.
//# define BSLS_ASSERT_NORETURN [[noreturn]]

#ifdef BSLS_PLATFORM_CMP_MSVC
#   define BSLS_ASSERT_NORETURN __declspec(noreturn)
#else
#   define BSLS_ASSERT_NORETURN
#endif

namespace BloombergLP {

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
// We want to print the error message to 'stderr', not 'stdout'.   The old
// documentation for 'printError' is:
//..
//  Print a formatted error message to standard output.  (Most Bloomberg
//  processes will send standard output to a log file.)
//..
// TBD: find out whether 'stderr' goes to 'act.log'.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

static
void printError(const char *text, const char *file, int line)
    // Print a formatted error message to 'stderr' using the specified
    // expression 'text', 'file' name, and 'line' number.  If either
    // 'text' or 'file' is empty ("") or null (0), replace it with some
    // informative, "human-readable" text, before formatting.
{
    if (!text) {
        text = "(* Unspecified Expression Text *)";
    }
    else if (!*text) {
        text = "(* Empty Expression Text *)";
    }

    if (!file) {
        file = "(* Unspecified File Name *)";
    }
    else if (!*file) {
        file = "(* Empty File Name *)";
    }

    bsls::Log::logFormattedMessage(
        bsls::LogSeverity::e_ERROR, file, line, "Assertion failed: %s", text);
}

namespace bsls {

                                // ------------
                                // class Assert
                                // ------------

// CLASS DATA
bsls::AtomicOperations::AtomicTypes::Pointer
    Assert::s_handler = {(void *) &Assert::failAbort};
bsls::AtomicOperations::AtomicTypes::Int Assert::s_lockedFlag = {0};

// CLASS METHODS
void Assert::setFailureHandlerRaw(Assert::Handler function)
{
    bsls::AtomicOperations::setPtrRelease(
        &s_handler, PointerCastUtil::cast<void *>(function));
}

void Assert::setFailureHandler(Assert::Handler function)
{
    if (!bsls::AtomicOperations::getIntRelaxed(&s_lockedFlag)) {
        setFailureHandlerRaw(function);
    }
}

void Assert::lockAssertAdministration()
{
    bsls::AtomicOperations::setIntRelaxed(&s_lockedFlag, 1);
}

Assert::Handler Assert::failureHandler()
{
    return (Handler) bsls::AtomicOperations::getPtrAcquire(&s_handler);
}

                       // Macro Dispatcher Method

#define IS_POWER_OF_TWO(X) (0 == ((X) & ((X) - 1)))

BSLS_ASSERT_NORETURN_INVOKE_HANDLER
void Assert::invokeHandler(const char *text, const char *file, int line)
{
    static AtomicOperations::AtomicTypes::Int failureReturnCount = {0};

    Assert::Handler currentHandlerAddress = failureHandler();

    currentHandlerAddress(text, file, line);

    // The failure handler should not return.  If a returning failure handler
    // has been installed, alert the user that the program is continuing to
    // run.

    unsigned count = static_cast<unsigned>(
                AtomicOperations::incrementIntNvAcqRel(&failureReturnCount));

    if (BSLS_PERFORMANCEHINT_PREDICT_UNLIKELY(IS_POWER_OF_TWO(count))) {
        BSLS_PERFORMANCEHINT_UNLIKELY_HINT;

        // Log when 'count' is a power of 2.

        if (count == (1 << 30)) {
            // Avoid undefined behavior by resetting the counter.

            AtomicOperations::setInt(&failureReturnCount, 1 << 29);
        }

        Log::logFormattedMessage(LogSeverity::e_FATAL,
                                 file,
                                 line,
                                 "BSLS_ASSERT failure: '%s'",
                                 text);

        BSLS_LOG_FATAL("Bad 'bsls_assert' configuration: "
                       "violation handler at %p must not return.",
                       currentHandlerAddress);
    }

#ifdef BSLS_ASSERT_ENABLE_NORETURN_FOR_INVOKE_HANDLER
    std::abort();
#endif
}

                     // Standard Assertion-Failure Handlers

BSLS_ASSERT_NORETURN
void Assert::failAbort(const char *text, const char *file, int line)
{
    printError(text, file, line);

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
    // See DRQS 8923441: The following is a work-around for a Fortran compiler bug.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

#ifdef BSLS_PLATFORM_OS_AIX
    sigset_t newset;
    sigemptyset(&newset);
    sigaddset(&newset, SIGABRT);
#if defined(BDE_BUILD_TARGET_MT)
    pthread_sigmask(SIG_UNBLOCK, &newset, 0);
#else
    sigprocmask(SIG_UNBLOCK, &newset, 0);
#endif
#endif

#ifndef BDE_OMIT_INTERNAL_DEPRECATED
    // See DRQS 13882128: Note that (according to Oleg) the first line alone may be
    // sufficient.
#endif // BDE_OMIT_INTERNAL_DEPRECATED

#ifdef BSLS_PLATFORM_OS_WINDOWS
    // The following configures the runtime library on how to report asserts,
    // errors, and warnings in order to avoid pop-up windows when 'abort' is
    // called.
    if (!IsDebuggerPresent()) {
        _CrtSetReportMode(_CRT_ASSERT, 0);
        _CrtSetReportMode(_CRT_ERROR, 0);
        _CrtSetReportMode(_CRT_WARN, 0);
    }
#endif

    std::abort();
}

BSLS_ASSERT_NORETURN
void Assert::failSleep(const char *text, const char *file, int line)
{
    printError(text, file, line);

    volatile int sleepDuration = 1;

    while (1 == sleepDuration) {

#if defined(BSLS_PLATFORM_OS_UNIX)
        sleep(sleepDuration);
#elif defined(BSLS_PLATFORM_OS_WINDOWS)
        Sleep(sleepDuration * 1000);  // milliseconds
#else
        #error "Do not know how to sleep on this platform."
#endif

    }

    // We will never reach this line, but it is needed to let the compiler know
    // that this function does not return.

    std::abort();
}

BSLS_ASSERT_NORETURN
void Assert::failThrow(const char *text, const char *file, int line)
{

#ifdef BDE_BUILD_TARGET_EXC
    if (!std::uncaught_exception()) {
        throw AssertTestException(text, file, line);
    }
    else {
        bsls::Log::logMessage(bsls::LogSeverity::e_ERROR, file, line,
                "BSLS_ASSERT: An uncaught exception is pending;"
                " cannot throw 'AssertTestException'.");
    }
#endif

    failAbort(text, file, line);
}

}  // close package namespace

#undef BSLS_ASSERT_NORETURN

namespace bsls {

                    // -------------------------------
                    // class AssertFailureHandlerGuard
                    // -------------------------------

AssertFailureHandlerGuard::AssertFailureHandlerGuard(Assert::Handler temporary)
: d_original(Assert::failureHandler())
{
    Assert::setFailureHandlerRaw(temporary);
}

AssertFailureHandlerGuard::~AssertFailureHandlerGuard()
{
    Assert::setFailureHandlerRaw(d_original);
}

}  // close package namespace

}  // close enterprise namespace

// ----------------------------------------------------------------------------
// Copyright 2013 Bloomberg Finance L.P.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------- END-OF-FILE ----------------------------------
<|endoftext|>