<commit_before>#include "etl/attribute_macros.h"

#include "etl/armv7m/types.h"
#include "etl/armv7m/instructions.h"
#include "etl/armv7m/scb.h"
#include "etl/armv7m/scb_fp.h"

#include "etl/stm32f4xx/rcc.h"
#include "etl/stm32f4xx/syscfg.h"

using etl::armv7m::Word;

using etl::armv7m::scb;

using etl::stm32f4xx::ApbPeripheral;
using etl::stm32f4xx::rcc;
using etl::stm32f4xx::SysCfg;
using etl::stm32f4xx::syscfg;

extern "C" {
  extern etl::armv7m::Word _data_start;
}

/*
 * The type of things that can go into the preinit_array (void functions).
 */
typedef void (*InitFnPtr)();

/*
 * Turn on the CPU's fault reporting during preinit, e.g. before constructors
 * run.  Without this, memory violations, usage faults, etc. just show up as
 * Hard Fault and are a real pain to debug.
 */
static void enable_faults() {
  etl::armv7m::scb.enable_faults();
}

ETL_SECTION(".preinit_array") ETL_USED
InitFnPtr const preinit_enable_faults = enable_faults;

/*
 * Turn on the floating point unit for all execution contexts, with lazy
 * save enabled to make interrupts cheaper.
 *
 * We do this before running constructors so that everyone can just pretend
 * it's always on.  To do otherwise risks a Usage Fault.
 */
static void enable_floating_point() {
  // Enable floating point automatic/lazy state preservation.
  // The CONTROL bit governing FP will be set automatically when first used.
  etl::armv7m::scb_fp.write_fpccr(etl::armv7m::scb_fp.read_fpccr()
                                  .with_aspen(true)
                                  .with_lspen(true));

  // Enable access to the floating point coprocessor.
  etl::armv7m::scb.write_cpacr(etl::armv7m::scb.read_cpacr()
                               .with_cp11(etl::armv7m::Scb::CpAccess::full)
                               .with_cp10(etl::armv7m::Scb::CpAccess::full));
  etl::armv7m::instruction_synchronization_barrier();  // Now please.
}

ETL_SECTION(".preinit_array") ETL_USED
InitFnPtr const preinit_enable_floating_point = enable_floating_point;

/*
 * Remap SRAM112 to addresses starting at 0x00000000.  We do this before
 * running constructors to simplify the init process -- otherwise code would be
 * aware of its data being at address A one minute and address B the next.  In
 * particular, this lets us combine SRAM112 initialization with the rodata
 * initialization in the CRT startup.
 */
static void remap_sram() {
  // Remap SRAM.
  // Power on syscfg, so we can mess with its registers.
  rcc.enable_clock(ApbPeripheral::syscfg);

  // VTOR starts out at zero, which points to Flash and is good.
  // But now things are about to change.
  // Interrupts are disabled, but to be safe in case we fault (due to a bug),
  // go ahead and give VTOR the true address of the Flash table.
  // TODO(cbiffle): this is a no-op, remove it.
  scb.write_vtor(reinterpret_cast<unsigned>(&_data_start));
  etl::armv7m::data_synchronization_barrier();  // Write it now.
  etl::armv7m::instruction_synchronization_barrier();

  // Remap!
  auto mode = SysCfg::memrmp_value_t::mem_mode_t::embedded_sram;
  syscfg.write_memrmp(syscfg.read_memrmp()
                      .with_mem_mode(mode));
  etl::armv7m::data_synchronization_barrier();  // Write it now.
  etl::armv7m::instruction_synchronization_barrier();
}

ETL_SECTION(".preinit_array") ETL_USED
InitFnPtr const preinit_remap_sram = remap_sram;
<commit_msg>runtime/startup: fix subtle and stupid mistake.<commit_after>#include "etl/attribute_macros.h"

#include "etl/armv7m/types.h"
#include "etl/armv7m/instructions.h"
#include "etl/armv7m/scb.h"
#include "etl/armv7m/scb_fp.h"

#include "etl/stm32f4xx/rcc.h"
#include "etl/stm32f4xx/syscfg.h"

using etl::armv7m::Word;

using etl::armv7m::scb;

using etl::stm32f4xx::ApbPeripheral;
using etl::stm32f4xx::rcc;
using etl::stm32f4xx::SysCfg;
using etl::stm32f4xx::syscfg;

extern "C" {
  extern etl::armv7m::Word _data_start;
}

/*
 * The type of things that can go into the preinit_array (void functions).
 */
typedef void (*InitFnPtr)();

/*
 * Turn on the CPU's fault reporting during preinit, e.g. before constructors
 * run.  Without this, memory violations, usage faults, etc. just show up as
 * Hard Fault and are a real pain to debug.
 */
static void enable_faults() {
  etl::armv7m::scb.enable_faults();
}

ETL_SECTION(".preinit_array") ETL_USED
InitFnPtr const preinit_enable_faults = enable_faults;

/*
 * Turn on the floating point unit for all execution contexts, with lazy
 * save enabled to make interrupts cheaper.
 *
 * We do this before running constructors so that everyone can just pretend
 * it's always on.  To do otherwise risks a Usage Fault.
 */
static void enable_floating_point() {
  // Enable floating point automatic/lazy state preservation.
  // The CONTROL bit governing FP will be set automatically when first used.
  etl::armv7m::scb_fp.write_fpccr(etl::armv7m::scb_fp.read_fpccr()
                                  .with_aspen(true)
                                  .with_lspen(true));

  // Enable access to the floating point coprocessor.
  etl::armv7m::scb.write_cpacr(etl::armv7m::scb.read_cpacr()
                               .with_cp11(etl::armv7m::Scb::CpAccess::full)
                               .with_cp10(etl::armv7m::Scb::CpAccess::full));
  etl::armv7m::instruction_synchronization_barrier();  // Now please.
}

ETL_SECTION(".preinit_array") ETL_USED
InitFnPtr const preinit_enable_floating_point = enable_floating_point;

/*
 * Remap SRAM112 to addresses starting at 0x00000000.  We do this before
 * running constructors to simplify the init process -- otherwise code would be
 * aware of its data being at address A one minute and address B the next.  In
 * particular, this lets us combine SRAM112 initialization with the rodata
 * initialization in the CRT startup.
 */
static void remap_sram() {
  // Power on syscfg, so we can mess with its registers.
  rcc.enable_clock(ApbPeripheral::syscfg);

  // Note: we do not need to change VTOR here.
  //
  // It is initially zero.  At boot, this aliases the ROM copy of the table.
  //
  // The table has been copied to RAM *before* the preinit_array functions run.
  // The remapping we're about to perform will cause address zero (and thus the
  // VTOR) to alias the *RAM* copy of the vector table.

  // Remap!
  auto mode = SysCfg::memrmp_value_t::mem_mode_t::embedded_sram;
  syscfg.write_memrmp(syscfg.read_memrmp()
                      .with_mem_mode(mode));
  etl::armv7m::data_synchronization_barrier();  // Write it now.
  etl::armv7m::instruction_synchronization_barrier();
}

ETL_SECTION(".preinit_array") ETL_USED
InitFnPtr const preinit_remap_sram = remap_sram;
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: libcpp-no-exceptions
// <regex>

// template <class charT, class traits = regex_traits<charT>> class basic_regex;

// template <class ST, class SA>
//    basic_regex(const basic_string<charT, ST, SA>& s);

#include <regex>
#include <cassert>
#include "test_macros.h"

static bool error_range_thrown(const char *pat)
{
    bool result = false;
    try {
        std::regex re(pat);
    } catch (const std::regex_error &ex) {
        result = (ex.code() == std::regex_constants::error_range);
    }
    return result;
}

int main(int, char**)
{
    assert(error_range_thrown(R"([\w-a])"));
    assert(error_range_thrown(R"([a-\w])"));

  return 0;
}
<commit_msg>Fix test that used raw string literals. Doesn't work in C++03<commit_after>//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

// UNSUPPORTED: libcpp-no-exceptions
// <regex>

// template <class charT, class traits = regex_traits<charT>> class basic_regex;

// template <class ST, class SA>
//    basic_regex(const basic_string<charT, ST, SA>& s);

#include <regex>
#include <cassert>
#include "test_macros.h"

static bool error_range_thrown(const char *pat)
{
    bool result = false;
    try {
        std::regex re(pat);
    } catch (const std::regex_error &ex) {
        result = (ex.code() == std::regex_constants::error_range);
    }
    return result;
}

int main(int, char**)
{
    assert(error_range_thrown("([\\w-a])"));
    assert(error_range_thrown("([a-\\w])"));

  return 0;
}
<|endoftext|>


<commit_before>// mfcSimpleView.cpp : implementation of the CSimpleView class
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "stdafx.h"
#include "mfcSimple.h"

#include "mfcSimpleDoc.h"
#include "mfcSimpleView.h"

bool CreateScene();

// Header for the vtlib library
#include "vtlib/vtlib.h"
#include "vtlib/core/Terrain.h"
#include "vtlib/core/TerrainScene.h"
#include "vtlib/core/NavEngines.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CSimpleView

IMPLEMENT_DYNCREATE(CSimpleView, CView)

BEGIN_MESSAGE_MAP(CSimpleView, CView)
	//{{AFX_MSG_MAP(CSimpleView)
	ON_WM_DESTROY()
	ON_WM_CREATE()
	ON_WM_SIZE()
	ON_WM_PAINT()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_MOUSEMOVE()
	ON_WM_RBUTTONDOWN()
	ON_WM_RBUTTONUP()
	ON_WM_MBUTTONDOWN()
	ON_WM_MBUTTONUP()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSimpleView construction/destruction

CSimpleView::CSimpleView()
{
	m_hGLContext = NULL;
	m_GLPixelIndex = 0;
}

CSimpleView::~CSimpleView()
{
}

BOOL CSimpleView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return CView::PreCreateWindow(cs);
}

/////////////////////////////////////////////////////////////////////////////
// CSimpleView diagnostics

#ifdef _DEBUG
void CSimpleView::AssertValid() const
{
	CView::AssertValid();
}

void CSimpleView::Dump(CDumpContext& dc) const
{
	CView::Dump(dc);
}

CSimpleDoc* CSimpleView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSimpleDoc)));
	return (CSimpleDoc*)m_pDocument;
}
#endif //_DEBUG

void CSimpleView::OnDraw(CDC* pDC)
{
	CSimpleDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);

}
/////////////////////////////////////////////////////////////////////////////
// CSimpleView message handlers
// set Windows Pixel Format
BOOL CSimpleView::SetWindowPixelFormat(HDC hDC)
{
	PIXELFORMATDESCRIPTOR pixelDesc;

	pixelDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	pixelDesc.nVersion = 1;

	pixelDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |
		PFD_DOUBLEBUFFER | PFD_STEREO_DONTCARE;

	pixelDesc.iPixelType = PFD_TYPE_RGBA;
	pixelDesc.cColorBits = 32;
	pixelDesc.cRedBits = 8;
	pixelDesc.cRedShift = 16;
	pixelDesc.cGreenBits = 8;
	pixelDesc.cGreenShift = 8;
	pixelDesc.cBlueBits = 8;
	pixelDesc.cBlueShift = 0;
	pixelDesc.cAlphaBits = 0;
	pixelDesc.cAlphaShift = 0;
	pixelDesc.cAccumBits = 64;
	pixelDesc.cAccumRedBits = 16;
	pixelDesc.cAccumGreenBits = 16;
	pixelDesc.cAccumBlueBits = 16;
	pixelDesc.cAccumAlphaBits = 0;
	pixelDesc.cDepthBits = 32;
	pixelDesc.cStencilBits = 8;
	pixelDesc.cAuxBuffers = 0;
	pixelDesc.iLayerType = PFD_MAIN_PLANE;
	pixelDesc.bReserved = 0;
	pixelDesc.dwLayerMask = 0;
	pixelDesc.dwVisibleMask = 0;
	pixelDesc.dwDamageMask = 0;

	m_GLPixelIndex = ChoosePixelFormat(hDC,&pixelDesc);
	if (m_GLPixelIndex == 0) // Choose default
	{
		m_GLPixelIndex = 1;
		if (DescribePixelFormat(hDC,m_GLPixelIndex,
			sizeof(PIXELFORMATDESCRIPTOR),&pixelDesc)==0)
			return FALSE;
	}

	if (!SetPixelFormat(hDC,m_GLPixelIndex,&pixelDesc))
		return FALSE;

	return TRUE;
}

//********************************************
// CreateViewGLContext
// Create an OpenGL rendering context
//********************************************
BOOL CSimpleView::CreateViewGLContext(HDC hDC)
{
	m_hGLContext = wglCreateContext(hDC);

	if (m_hGLContext==NULL)
		return FALSE;

	if (wglMakeCurrent(hDC,m_hGLContext)==FALSE)
		return FALSE;

	return TRUE;
}

void CSimpleView::OnDestroy()
{
	if (wglGetCurrentContext() != NULL)
		wglMakeCurrent(NULL,NULL);
	if (m_hGLContext != NULL)
	{
		wglDeleteContext(m_hGLContext);
		m_hGLContext = NULL;
	}
	CView::OnDestroy();
}

int CSimpleView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CView::OnCreate(lpCreateStruct) == -1)
		return -1;
	HWND hWnd = GetSafeHwnd();
	HDC hDC = ::GetDC(hWnd);

	if (SetWindowPixelFormat(hDC)==FALSE)
		return 0;

	if (CreateViewGLContext(hDC)==FALSE)
		return 0;
	return CreateScene();
}

void CSimpleView::OnSize(UINT nType, int cx, int cy)
{
	CView::OnSize(nType, cx, cy);
	glViewport(0,0,cx, cy);
	vtGetScene()->SetWindowSize(cx, cy);
}

void CSimpleView::OnPaint()
{
	CPaintDC dc(this); // device context for painting

	//Runtime code
	//In the main loop of your code, let vtlib do its culling and rendering:
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	// Render the scene
	vtGetScene()->DoUpdate();
	//this would occur, for example, after your call to glClear() and before calling SwapBuffers()
	SwapBuffers(dc.m_ps.hdc);
	InvalidateRect(NULL,FALSE);	//for Continuous Rendering
}

//-----------------------The Following is VTerrain Code-----------------
//
// Create the 3d scene
//
bool CreateScene()
{
	// Get a handle to the vtScene - one is already created for you
	vtScene *pScene = vtGetScene();
	pScene->Init();

	// Set the global data path
	vtTerrain::SetDataPath("Data/");

	// Look up the camera
	vtCamera *pCamera = pScene->GetCamera();
	pCamera->SetHither(20 * WORLD_SCALE);

	// Create a new terrain scene.  This will contain all the terrain
	// that are created.
	vtTerrainScene *ts = new vtTerrainScene();
	vtRoot *pTopGroup = ts->BeginTerrainScene(false);

	// Tell the scene graph to point to this terrain scene
	pScene->SetRoot(pTopGroup);

	// Create a new vtTerrain, read its paramters from a file
	vtTerrain *pTerr = new vtTerrain();
	pTerr->SetParamFile("Data/Simple.ini");

	// Add the terrain to the scene, and contruct it
	ts->AppendTerrain(pTerr);
	int iError;
	if (!pTerr->CreateScene(false, iError))
	{
		AfxMessageBox("Terrain creation failed.");
		return false;
	}
	ts->Finish("Data/");
	ts->SetTerrain(pTerr);

	// Create a navigation engine to move around on the terrain
	// Flight speed is 500 m/frame
	// Height over terrain is 100 m
	vtTerrainFlyer *pFlyer = new vtTerrainFlyer(400*WORLD_SCALE, 100*WORLD_SCALE, true);
	pFlyer->SetTarget(pCamera);
	pFlyer->SetHeightField(pTerr->GetHeightField());
	pScene->AddEngine(pFlyer);

	return true;
}

//--------------Mouse EVENTS-----------------

//
// turn MFC events flags in VT flags
//
int MFCFlagsToVT(int nFlags)
{
	int flags = 0;
	if ( (nFlags & MK_CONTROL)!=0 )
		flags |= VT_CONTROL;
	if ( (nFlags & MK_SHIFT)!=0 )
		flags |= VT_SHIFT;
	return flags;
}

//
// turn MFC mouse events into VT mouse events
//
void CSimpleView::OnMouseMove(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_MOVE;
	event.button = VT_NONE;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnLButtonUp(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_UP;
	event.button = VT_LEFT;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnLButtonDown(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_DOWN;
	event.button = VT_LEFT;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnRButtonDown(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_DOWN;
	event.button = VT_RIGHT;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnRButtonUp(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_UP;
	event.button = VT_RIGHT;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnMButtonDown(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_DOWN;
	event.button = VT_MIDDLE;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnMButtonUp(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_UP;
	event.button = VT_MIDDLE;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

<commit_msg>removed glClear (already done in vtlib)<commit_after>// mfcSimpleView.cpp : implementation of the CSimpleView class
//
// Copyright (c) 2001 Virtual Terrain Project
// Free for all uses, see license.txt for details.
//

#include "stdafx.h"
#include "mfcSimple.h"

#include "mfcSimpleDoc.h"
#include "mfcSimpleView.h"

bool CreateScene();

// Header for the vtlib library
#include "vtlib/vtlib.h"
#include "vtlib/core/Terrain.h"
#include "vtlib/core/TerrainScene.h"
#include "vtlib/core/NavEngines.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CSimpleView

IMPLEMENT_DYNCREATE(CSimpleView, CView)

BEGIN_MESSAGE_MAP(CSimpleView, CView)
	//{{AFX_MSG_MAP(CSimpleView)
	ON_WM_DESTROY()
	ON_WM_CREATE()
	ON_WM_SIZE()
	ON_WM_PAINT()
	ON_WM_LBUTTONDOWN()
	ON_WM_LBUTTONUP()
	ON_WM_MOUSEMOVE()
	ON_WM_RBUTTONDOWN()
	ON_WM_RBUTTONUP()
	ON_WM_MBUTTONDOWN()
	ON_WM_MBUTTONUP()
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CSimpleView construction/destruction

CSimpleView::CSimpleView()
{
	m_hGLContext = NULL;
	m_GLPixelIndex = 0;
}

CSimpleView::~CSimpleView()
{
}

BOOL CSimpleView::PreCreateWindow(CREATESTRUCT& cs)
{
	// TODO: Modify the Window class or styles here by modifying
	//  the CREATESTRUCT cs

	return CView::PreCreateWindow(cs);
}

/////////////////////////////////////////////////////////////////////////////
// CSimpleView diagnostics

#ifdef _DEBUG
void CSimpleView::AssertValid() const
{
	CView::AssertValid();
}

void CSimpleView::Dump(CDumpContext& dc) const
{
	CView::Dump(dc);
}

CSimpleDoc* CSimpleView::GetDocument() // non-debug version is inline
{
	ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(CSimpleDoc)));
	return (CSimpleDoc*)m_pDocument;
}
#endif //_DEBUG

void CSimpleView::OnDraw(CDC* pDC)
{
	CSimpleDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);

}
/////////////////////////////////////////////////////////////////////////////
// CSimpleView message handlers
// set Windows Pixel Format
BOOL CSimpleView::SetWindowPixelFormat(HDC hDC)
{
	PIXELFORMATDESCRIPTOR pixelDesc;

	pixelDesc.nSize = sizeof(PIXELFORMATDESCRIPTOR);
	pixelDesc.nVersion = 1;

	pixelDesc.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL |
		PFD_DOUBLEBUFFER | PFD_STEREO_DONTCARE;

	pixelDesc.iPixelType = PFD_TYPE_RGBA;
	pixelDesc.cColorBits = 32;
	pixelDesc.cRedBits = 8;
	pixelDesc.cRedShift = 16;
	pixelDesc.cGreenBits = 8;
	pixelDesc.cGreenShift = 8;
	pixelDesc.cBlueBits = 8;
	pixelDesc.cBlueShift = 0;
	pixelDesc.cAlphaBits = 0;
	pixelDesc.cAlphaShift = 0;
	pixelDesc.cAccumBits = 64;
	pixelDesc.cAccumRedBits = 16;
	pixelDesc.cAccumGreenBits = 16;
	pixelDesc.cAccumBlueBits = 16;
	pixelDesc.cAccumAlphaBits = 0;
	pixelDesc.cDepthBits = 32;
	pixelDesc.cStencilBits = 8;
	pixelDesc.cAuxBuffers = 0;
	pixelDesc.iLayerType = PFD_MAIN_PLANE;
	pixelDesc.bReserved = 0;
	pixelDesc.dwLayerMask = 0;
	pixelDesc.dwVisibleMask = 0;
	pixelDesc.dwDamageMask = 0;

	m_GLPixelIndex = ChoosePixelFormat(hDC,&pixelDesc);
	if (m_GLPixelIndex == 0) // Choose default
	{
		m_GLPixelIndex = 1;
		if (DescribePixelFormat(hDC,m_GLPixelIndex,
			sizeof(PIXELFORMATDESCRIPTOR),&pixelDesc)==0)
			return FALSE;
	}

	if (!SetPixelFormat(hDC,m_GLPixelIndex,&pixelDesc))
		return FALSE;

	return TRUE;
}

//********************************************
// CreateViewGLContext
// Create an OpenGL rendering context
//********************************************
BOOL CSimpleView::CreateViewGLContext(HDC hDC)
{
	m_hGLContext = wglCreateContext(hDC);

	if (m_hGLContext==NULL)
		return FALSE;

	if (wglMakeCurrent(hDC,m_hGLContext)==FALSE)
		return FALSE;

	return TRUE;
}

void CSimpleView::OnDestroy()
{
	if (wglGetCurrentContext() != NULL)
		wglMakeCurrent(NULL,NULL);
	if (m_hGLContext != NULL)
	{
		wglDeleteContext(m_hGLContext);
		m_hGLContext = NULL;
	}
	CView::OnDestroy();
}

int CSimpleView::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
	if (CView::OnCreate(lpCreateStruct) == -1)
		return -1;
	HWND hWnd = GetSafeHwnd();
	HDC hDC = ::GetDC(hWnd);

	if (SetWindowPixelFormat(hDC)==FALSE)
		return 0;

	if (CreateViewGLContext(hDC)==FALSE)
		return 0;
	return CreateScene();
}

void CSimpleView::OnSize(UINT nType, int cx, int cy)
{
	CView::OnSize(nType, cx, cy);
	glViewport(0,0,cx, cy);
	vtGetScene()->SetWindowSize(cx, cy);
}

void CSimpleView::OnPaint()
{
	CPaintDC dc(this); // device context for painting

	// Render the scene
	vtGetScene()->DoUpdate();
	//this would occur, for example, after your call to glClear() and before calling SwapBuffers()
	SwapBuffers(dc.m_ps.hdc);
	InvalidateRect(NULL,FALSE);	//for Continuous Rendering
}

//-----------------------The Following is VTerrain Code-----------------
//
// Create the 3d scene
//
bool CreateScene()
{
	// Get a handle to the vtScene - one is already created for you
	vtScene *pScene = vtGetScene();
	pScene->Init();

	// Set the global data path
	vtTerrain::SetDataPath("Data/");

	// Look up the camera
	vtCamera *pCamera = pScene->GetCamera();
	pCamera->SetHither(20 * WORLD_SCALE);

	// Create a new terrain scene.  This will contain all the terrain
	// that are created.
	vtTerrainScene *ts = new vtTerrainScene();
	vtRoot *pTopGroup = ts->BeginTerrainScene(false);

	// Tell the scene graph to point to this terrain scene
	pScene->SetRoot(pTopGroup);

	// Create a new vtTerrain, read its paramters from a file
	vtTerrain *pTerr = new vtTerrain();
	pTerr->SetParamFile("Data/Simple.ini");

	// Add the terrain to the scene, and contruct it
	ts->AppendTerrain(pTerr);
	int iError;
	if (!pTerr->CreateScene(false, iError))
	{
		AfxMessageBox("Terrain creation failed.");
		return false;
	}
	ts->Finish("Data/");
	ts->SetTerrain(pTerr);

	// Create a navigation engine to move around on the terrain
	// Flight speed is 500 m/frame
	// Height over terrain is 100 m
	vtTerrainFlyer *pFlyer = new vtTerrainFlyer(400*WORLD_SCALE, 100*WORLD_SCALE, true);
	pFlyer->SetTarget(pCamera);
	pFlyer->SetHeightField(pTerr->GetHeightField());
	pScene->AddEngine(pFlyer);

	return true;
}

//--------------Mouse EVENTS-----------------

//
// turn MFC events flags in VT flags
//
int MFCFlagsToVT(int nFlags)
{
	int flags = 0;
	if ( (nFlags & MK_CONTROL)!=0 )
		flags |= VT_CONTROL;
	if ( (nFlags & MK_SHIFT)!=0 )
		flags |= VT_SHIFT;
	return flags;
}

//
// turn MFC mouse events into VT mouse events
//
void CSimpleView::OnMouseMove(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_MOVE;
	event.button = VT_NONE;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnLButtonUp(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_UP;
	event.button = VT_LEFT;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnLButtonDown(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_DOWN;
	event.button = VT_LEFT;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnRButtonDown(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_DOWN;
	event.button = VT_RIGHT;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnRButtonUp(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_UP;
	event.button = VT_RIGHT;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnMButtonDown(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_DOWN;
	event.button = VT_MIDDLE;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

void CSimpleView::OnMButtonUp(UINT nFlags, CPoint point)
{
	vtMouseEvent event;

	event.type = VT_UP;
	event.button = VT_MIDDLE;
	event.flags = MFCFlagsToVT(nFlags);
	event.pos.Set(point.x,point.y);

	vtGetScene()->OnMouse(event);
}

<|endoftext|>


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

#include "ui/gfx/platform_font_pango.h"

#include <string>

#include "base/memory/ref_counted.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/pango_util.h"

// Test that PlatformFontPango is able to cope with PangoFontDescriptions
// containing multiple font families.  The first family should be preferred.
TEST(PlatformFontPangoTest, FamilyList) {
  PangoFontDescription* desc =
      pango_font_description_from_string("Arial,Times New Roman, 13px");
  scoped_refptr<gfx::PlatformFontPango> font(new gfx::PlatformFontPango(desc));
  pango_font_description_free(desc);
  EXPECT_EQ("Arial", font->GetFontName());
  EXPECT_EQ(13, font->GetFontSize());

  desc = pango_font_description_from_string("Times New Roman,Arial, 15px");
  scoped_refptr<gfx::PlatformFontPango> font2(new gfx::PlatformFontPango(desc));
  pango_font_description_free(desc);
  EXPECT_EQ("Times New Roman", font2->GetFontName());
  EXPECT_EQ(15, font2->GetFontSize());
}
<commit_msg>Mark PlatformFontPangoTest.FamilyList as FAILS on cros<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/platform_font_pango.h"

#include <string>

#include "base/memory/ref_counted.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/gfx/pango_util.h"

// Fails on Chrome OS: http://crbug.com/124451
#if defined(OS_CHROMEOS)
#define MAYBE_FamilyList FAILS_FamilyList
#else
#define MAYBE_FamilyList FamilyList
#endif

// Test that PlatformFontPango is able to cope with PangoFontDescriptions
// containing multiple font families.  The first family should be preferred.
TEST(PlatformFontPangoTest, MAYBE_FamilyList) {
  PangoFontDescription* desc =
      pango_font_description_from_string("Arial,Times New Roman, 13px");
  scoped_refptr<gfx::PlatformFontPango> font(new gfx::PlatformFontPango(desc));
  pango_font_description_free(desc);
  EXPECT_EQ("Arial", font->GetFontName());
  EXPECT_EQ(13, font->GetFontSize());

  desc = pango_font_description_from_string("Times New Roman,Arial, 15px");
  scoped_refptr<gfx::PlatformFontPango> font2(new gfx::PlatformFontPango(desc));
  pango_font_description_free(desc);
  EXPECT_EQ("Times New Roman", font2->GetFontName());
  EXPECT_EQ(15, font2->GetFontSize());
}
<|endoftext|>


<commit_before>/*=========================================================================
*
*  Copyright Insight Software Consortium
*
*  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.txt
*
*  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 <SimpleITKTestHarness.h>
#include <itkHashImageFilter.h>
#include <itkImageFileReader.h>
#include <sitkCastImageFilter.h>

class HashImageFilterTest
  : public ::testing::Test {
public:

  template <typename TPixelType, unsigned int IDimension>
  void CheckImageHashMD5( const std::string &fname, const std::string &expectedHash )
  {

    typedef itk::ImageFileReader<itk::Image<TPixelType, IDimension > > ReaderType;
    typename ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName( dataFinder.GetFile ( fname ) );
    reader->Update();

    typedef itk::HashImageFilter< itk::Image<TPixelType, IDimension> > HasherType;
    typename HasherType::Pointer  hasher = HasherType::New();
    hasher->SetHashFunction( HasherType::MD5 );
    hasher->SetInput( reader->GetOutput() );
    hasher->Update();

    EXPECT_EQ ( expectedHash, hasher->GetHash() );

  }

  template <typename TPixelType, unsigned int IDimension>
  void CheckImageHashSHA1( const std::string &fname, const std::string &expectedHash )
  {

    typedef itk::ImageFileReader<itk::Image<TPixelType, IDimension > > ReaderType;
    typename ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName( dataFinder.GetFile ( fname ) );
    reader->Update();

    typedef itk::HashImageFilter< itk::Image<TPixelType, IDimension> > HasherType;
    typename HasherType::Pointer  hasher = HasherType::New();
    hasher->SetHashFunction( HasherType::SHA1 );
    hasher->SetInput( reader->GetOutput() );
    hasher->Update();

    EXPECT_EQ ( expectedHash, hasher->GetHash() );

  }
};

TEST_F(HashImageFilterTest, InstantiateTest) {

  typedef itk::HashImageFilter< itk::Image< unsigned char, 1> > UCHAR1HasherType;
  EXPECT_TRUE( UCHAR1HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image< unsigned char, 2> > UCHAR2HasherType;
  EXPECT_TRUE( UCHAR2HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image< unsigned char, 3> > UCHAR3HasherType;
  EXPECT_TRUE( UCHAR3HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image< unsigned int, 3> > UINT23HasherType;
  EXPECT_TRUE( UINT23HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image<int, 3> > INT23HasherType;
  EXPECT_TRUE( INT23HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image<float, 3> > FLOATHasherType;
  EXPECT_TRUE( INT23HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image<double, 3> > DOUBLEHasherType;
  EXPECT_TRUE( INT23HasherType::New().IsNotNull() );

};

TEST_F(HashImageFilterTest, MD5HashValues ) {

  this->CheckImageHashMD5<float,3>("Input/RA-Float.nrrd", "3ccccde44efaa3d688a86e94335c1f16");

  this->CheckImageHashMD5<float,2>("Input/RA-Float.nrrd", "16142594b185c50d64dd629750b94c90");

  this->CheckImageHashMD5<float,1>("Input/RA-Float.nrrd", "606f0ee67f5b181f90286e17e6f49926");

  this->CheckImageHashMD5<short, 3>("Input/Ramp-Down-Short.nrrd", "71f5c852a6251069fa1d60f796463343" );

  this->CheckImageHashMD5<int, 3>("Input/Ramp-Down-Short.nrrd", "f945b2b5384ba6f21a0fd50a970fb5ff");
}

TEST_F(HashImageFilterTest, SHA1HashValues ) {

  this->CheckImageHashSHA1<float,3>("Input/RA-Float.nrrd", "b187541bdcc89843d0a25a3761f344c358f3518a" );

  this->CheckImageHashSHA1<float,2>("Input/RA-Float.nrrd", "7bd2146732f1e6f38fe5ed387332d3ad3541b182" );

  this->CheckImageHashSHA1<float,1>("Input/RA-Float.nrrd",  "0eac9ac1f19b27743dfeabe76e69ae251c02b641" );

  this->CheckImageHashSHA1<short, 3>("Input/Ramp-Down-Short.nrrd", "4b0bd9dcf1f7d78101ce24da7f51de212f302ae9" );

  this->CheckImageHashSHA1<int, 3>("Input/Ramp-Down-Short.nrrd",  "3dc54908746f25fd42f17c5fe44935013e508b1b" );
}

TEST_F(HashImageFilterTest, VectorImages ) {

  // test image of vectors
  {
  typedef itk::Image<itk::Vector<float, 1>, 3 > VectorImageType;

  typedef itk::ImageFileReader<VectorImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( dataFinder.GetFile ( "Input/RA-Float.nrrd" ) );
  reader->Update();

  typedef itk::HashImageFilter< VectorImageType > HasherType;
  HasherType::Pointer  hasher = HasherType::New();
  hasher->SetHashFunction( HasherType::MD5 );
  hasher->SetInput( reader->GetOutput() );
  hasher->Update();

  EXPECT_EQ( hasher->GetHash(), "3ccccde44efaa3d688a86e94335c1f16" );
  }

  // test vector image
  {
  typedef itk::VectorImage<float, 3> VectorImageType;

  typedef itk::ImageFileReader<VectorImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( dataFinder.GetFile ( "Input/RA-Float.nrrd" ) );
  reader->Update();

  typedef itk::HashImageFilter< VectorImageType > HasherType;
  HasherType::Pointer  hasher = HasherType::New();
  hasher->SetHashFunction( HasherType::MD5 );
  hasher->SetInput( reader->GetOutput() );
  hasher->Update();

  EXPECT_EQ( hasher->GetHash(), "3ccccde44efaa3d688a86e94335c1f16" );
  }
}

TEST_F(HashImageFilterTest, LabelMap ) {

  itk::simple::Image img = itk::simple::ReadImage( dataFinder.GetFile ( "Input/2th_cthead1.png" ) );

  std::string hash;

  EXPECT_NO_THROW( hash = itk::simple::Hash( itk::simple::Cast( img, itk::simple::sitkLabelUInt16 ) ) );
  EXPECT_EQ( hash, "134248ff026387fe17bd0bfa62357fa390d52985" );

  EXPECT_NO_THROW( hash = itk::simple::Hash( itk::simple::Cast( img, itk::simple::sitkLabelUInt32 ) ) );
  EXPECT_EQ( hash, "c4dc6e128902159fe04cacec27b784cd995533af" );

}

TEST_F(HashImageFilterTest, Coverage ) {

 typedef itk::HashImageFilter< itk::Image< unsigned char, 2> > UCHAR2HasherType;
 UCHAR2HasherType::Pointer hasher = UCHAR2HasherType::New();

 // PrintSelf
 std::ostringstream out;
 out << hasher;
 EXPECT_NE ( out.str(), "" );  // So the test fails if we don’t have any print self output...

 // Set/Get Methods
 hasher->SetHashFunction( UCHAR2HasherType::MD5 );
 EXPECT_EQ(  hasher->GetHashFunction(), UCHAR2HasherType::MD5 ) << "expected default hash type to be MD5";

 hasher->SetHashFunction( UCHAR2HasherType::SHA1 );
 EXPECT_EQ(  hasher->GetHashFunction(), UCHAR2HasherType::SHA1 ) << "expected default hash type to be SHA1";
}
<commit_msg>Added 4D support to HashImageFilterTest<commit_after>/*=========================================================================
*
*  Copyright Insight Software Consortium
*
*  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.txt
*
*  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 <SimpleITKTestHarness.h>
#include <itkHashImageFilter.h>
#include <itkImageFileReader.h>
#include <sitkCastImageFilter.h>

class HashImageFilterTest
  : public ::testing::Test {
public:

  template <typename TPixelType, unsigned int IDimension>
  void CheckImageHashMD5( const std::string &fname, const std::string &expectedHash )
  {

    typedef itk::ImageFileReader<itk::Image<TPixelType, IDimension > > ReaderType;
    typename ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName( dataFinder.GetFile ( fname ) );
    reader->Update();

    typedef itk::HashImageFilter< itk::Image<TPixelType, IDimension> > HasherType;
    typename HasherType::Pointer  hasher = HasherType::New();
    hasher->SetHashFunction( HasherType::MD5 );
    hasher->SetInput( reader->GetOutput() );
    hasher->Update();

    EXPECT_EQ ( expectedHash, hasher->GetHash() );

  }

  template <typename TPixelType, unsigned int IDimension>
  void CheckImageHashSHA1( const std::string &fname, const std::string &expectedHash )
  {

    typedef itk::ImageFileReader<itk::Image<TPixelType, IDimension > > ReaderType;
    typename ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName( dataFinder.GetFile ( fname ) );
    reader->Update();

    typedef itk::HashImageFilter< itk::Image<TPixelType, IDimension> > HasherType;
    typename HasherType::Pointer  hasher = HasherType::New();
    hasher->SetHashFunction( HasherType::SHA1 );
    hasher->SetInput( reader->GetOutput() );
    hasher->Update();

    EXPECT_EQ ( expectedHash, hasher->GetHash() );

  }
};

TEST_F(HashImageFilterTest, InstantiateTest) {

  typedef itk::HashImageFilter< itk::Image< unsigned char, 1> > UCHAR1HasherType;
  EXPECT_TRUE( UCHAR1HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image< unsigned char, 2> > UCHAR2HasherType;
  EXPECT_TRUE( UCHAR2HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image< unsigned char, 3> > UCHAR3HasherType;
  EXPECT_TRUE( UCHAR3HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image< unsigned int, 3> > UINT23HasherType;
  EXPECT_TRUE( UINT23HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image<int, 3> > INT23HasherType;
  EXPECT_TRUE( INT23HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image<float, 3> > FLOATHasherType;
  EXPECT_TRUE( INT23HasherType::New().IsNotNull() );

  typedef itk::HashImageFilter< itk::Image<double, 3> > DOUBLEHasherType;
  EXPECT_TRUE( INT23HasherType::New().IsNotNull() );

#ifdef SITK_4D_IMAGES
  typedef itk::HashImageFilter< itk::Image<double, 4> > DOUBLE4DHasherType;
  EXPECT_TRUE( DOUBLE4DHasherType::New().IsNotNull() );
#endif
};

TEST_F(HashImageFilterTest, MD5HashValues ) {

  this->CheckImageHashMD5<float,3>("Input/RA-Float.nrrd", "3ccccde44efaa3d688a86e94335c1f16");

  this->CheckImageHashMD5<float,2>("Input/RA-Float.nrrd", "16142594b185c50d64dd629750b94c90");

  this->CheckImageHashMD5<float,1>("Input/RA-Float.nrrd", "606f0ee67f5b181f90286e17e6f49926");

  this->CheckImageHashMD5<short, 3>("Input/Ramp-Down-Short.nrrd", "71f5c852a6251069fa1d60f796463343" );

  this->CheckImageHashMD5<int, 3>("Input/Ramp-Down-Short.nrrd", "f945b2b5384ba6f21a0fd50a970fb5ff");
}

TEST_F(HashImageFilterTest, SHA1HashValues ) {

  this->CheckImageHashSHA1<float,3>("Input/RA-Float.nrrd", "b187541bdcc89843d0a25a3761f344c358f3518a" );

  this->CheckImageHashSHA1<float,2>("Input/RA-Float.nrrd", "7bd2146732f1e6f38fe5ed387332d3ad3541b182" );

  this->CheckImageHashSHA1<float,1>("Input/RA-Float.nrrd",  "0eac9ac1f19b27743dfeabe76e69ae251c02b641" );

  this->CheckImageHashSHA1<short, 3>("Input/Ramp-Down-Short.nrrd", "4b0bd9dcf1f7d78101ce24da7f51de212f302ae9" );

  this->CheckImageHashSHA1<int, 3>("Input/Ramp-Down-Short.nrrd",  "3dc54908746f25fd42f17c5fe44935013e508b1b" );

#ifdef SITK_4D_IMAGES
  this->CheckImageHashSHA1<short, 4>("Input/4D.nii.gz", "9e81d4b3cdf10a4da5d54c8cd7c4954449d76d5d" );
#endif
}

TEST_F(HashImageFilterTest, VectorImages ) {

  // test image of vectors
  {
  typedef itk::Image<itk::Vector<float, 1>, 3 > VectorImageType;

  typedef itk::ImageFileReader<VectorImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( dataFinder.GetFile ( "Input/RA-Float.nrrd" ) );
  reader->Update();

  typedef itk::HashImageFilter< VectorImageType > HasherType;
  HasherType::Pointer  hasher = HasherType::New();
  hasher->SetHashFunction( HasherType::MD5 );
  hasher->SetInput( reader->GetOutput() );
  hasher->Update();

  EXPECT_EQ( hasher->GetHash(), "3ccccde44efaa3d688a86e94335c1f16" );
  }

  // test vector image
  {
  typedef itk::VectorImage<float, 3> VectorImageType;

  typedef itk::ImageFileReader<VectorImageType > ReaderType;
  ReaderType::Pointer reader = ReaderType::New();
  reader->SetFileName( dataFinder.GetFile ( "Input/RA-Float.nrrd" ) );
  reader->Update();

  typedef itk::HashImageFilter< VectorImageType > HasherType;
  HasherType::Pointer  hasher = HasherType::New();
  hasher->SetHashFunction( HasherType::MD5 );
  hasher->SetInput( reader->GetOutput() );
  hasher->Update();

  EXPECT_EQ( hasher->GetHash(), "3ccccde44efaa3d688a86e94335c1f16" );
  }
}

TEST_F(HashImageFilterTest, LabelMap ) {

  itk::simple::Image img = itk::simple::ReadImage( dataFinder.GetFile ( "Input/2th_cthead1.png" ) );

  std::string hash;

  EXPECT_NO_THROW( hash = itk::simple::Hash( itk::simple::Cast( img, itk::simple::sitkLabelUInt16 ) ) );
  EXPECT_EQ( hash, "134248ff026387fe17bd0bfa62357fa390d52985" );

  EXPECT_NO_THROW( hash = itk::simple::Hash( itk::simple::Cast( img, itk::simple::sitkLabelUInt32 ) ) );
  EXPECT_EQ( hash, "c4dc6e128902159fe04cacec27b784cd995533af" );

}

TEST_F(HashImageFilterTest, Coverage ) {

 typedef itk::HashImageFilter< itk::Image< unsigned char, 2> > UCHAR2HasherType;
 UCHAR2HasherType::Pointer hasher = UCHAR2HasherType::New();

 // PrintSelf
 std::ostringstream out;
 out << hasher;
 EXPECT_NE ( out.str(), "" );  // So the test fails if we don’t have any print self output...

 // Set/Get Methods
 hasher->SetHashFunction( UCHAR2HasherType::MD5 );
 EXPECT_EQ(  hasher->GetHashFunction(), UCHAR2HasherType::MD5 ) << "expected default hash type to be MD5";

 hasher->SetHashFunction( UCHAR2HasherType::SHA1 );
 EXPECT_EQ(  hasher->GetHashFunction(), UCHAR2HasherType::SHA1 ) << "expected default hash type to be SHA1";
}
<|endoftext|>


<commit_before>/**
 * This is a implementation of the mapkeeper interface that uses
 * leveldb.
 *
 * http://leveldb.googlecode.com/svn/trunk/doc/index.html
 */
#include <cstdio>
#include "MapKeeper.h"
#include <leveldb/db.h>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>

#include <protocol/TBinaryProtocol.h>
#include <server/TSimpleServer.h>
#include <server/TThreadPoolServer.h>
#include <server/TNonblockingServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/PosixThreadFactory.h>

using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::concurrency;

using boost::shared_ptr;

using namespace mapkeeper;

class LevelDbServer: virtual public MapKeeperIf {
public:
    LevelDbServer(const std::string& directoryName) :
        directoryName_(directoryName) {
    }

    ResponseCode::type ping() {
        return ResponseCode::Success;
    }

    ResponseCode::type addMap(const std::string& mapName) {
        leveldb::DB* db;
        leveldb::Options options;
        options.create_if_missing = true;
        options.error_if_exists = true;
        leveldb::Status status = leveldb::DB::Open(options, directoryName_ + mapName, &db);
        if (!status.ok()) {
            // TODO check return code
            printf("status: %s\n", status.ToString().c_str());
            return ResponseCode::Error;
        }
        std::string mapName_ = mapName;
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        maps_.insert(mapName_, db);
        return ResponseCode::Success;
    }

    ResponseCode::type dropMap(const std::string& mapName) {
        std::string mapName_ = mapName;
        boost::ptr_map<std::string, leveldb::DB>::iterator itr;
        boost::unique_lock< boost::shared_mutex> writeLock(mutex_);;
        itr = maps_.find(mapName_);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        maps_.erase(itr);
        return ResponseCode::Success;
    }

    void listMaps(StringListResponse& _return) {
        DIR *dp;
        struct dirent *dirp;
        if((dp  = opendir(directoryName_.c_str())) == NULL) {
            _return.responseCode = ResponseCode::Success;
            return;
        }

        while ((dirp = readdir(dp)) != NULL) {
            _return.values.push_back(std::string(dirp->d_name));
        }
        closedir(dp);
        _return.responseCode = ResponseCode::Success;
    }

    void scan(RecordListResponse& _return, const std::string& mapName, const ScanOrder::type order,
              const std::string& startKey, const bool startKeyIncluded,
              const std::string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
    }

    void scanAscending(RecordListResponse& _return, std::map<std::string, std::string>& map,
              const std::string& startKey, const bool startKeyIncluded,
              const std::string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
        _return.responseCode = ResponseCode::ScanEnded;
    }

    void scanDescending(RecordListResponse& _return, std::map<std::string, std::string>& map,
              const std::string& startKey, const bool startKeyIncluded,
              const std::string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
        _return.responseCode = ResponseCode::ScanEnded;
    }

    void get(BinaryResponse& _return, const std::string& mapName, const std::string& key) {
        boost::shared_lock< boost::shared_mutex> readLock(mutex_);;
        boost::ptr_map<std::string, leveldb::DB>::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            _return.responseCode = ResponseCode::MapNotFound;
            return;
        }
        leveldb::Status status = itr->second->Get(leveldb::ReadOptions(), key, &(_return.value));
        if (status.IsNotFound()) {
            _return.responseCode = ResponseCode::RecordNotFound;
            return;
        } else if (!status.ok()) {
            _return.responseCode = ResponseCode::Error;
            return;
        }
        _return.responseCode = ResponseCode::Success;
    }

    ResponseCode::type put(const std::string& mapName, const std::string& key, const std::string& value) {
        std::string mapName_ = mapName;
        boost::ptr_map<std::string, leveldb::DB>::iterator itr;
        boost::shared_lock< boost::shared_mutex> readLock(mutex_);;
        itr = maps_.find(mapName_);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        leveldb::Status status = itr->second->Put(leveldb::WriteOptions(), key, value);
        if (!status.ok()) {
            return ResponseCode::Error;
        }
        return ResponseCode::Success;
    }

    ResponseCode::type insert(const std::string& mapName, const std::string& key, const std::string& value) {
        return ResponseCode::Success;
    }

    ResponseCode::type update(const std::string& mapName, const std::string& key, const std::string& value) {
        return ResponseCode::Success;
    }

    ResponseCode::type remove(const std::string& mapName, const std::string& key) {
        return ResponseCode::Success;
    }

private:
    std::string directoryName_; // directory to store db files.
    boost::ptr_map<std::string, leveldb::DB> maps_;
    boost::shared_mutex mutex_; // protect map_
};

int main(int argc, char **argv) {
    int port = 9091;
    size_t numThreads = 32;
    shared_ptr<LevelDbServer> handler(new LevelDbServer("."));
    shared_ptr<TProcessor> processor(new MapKeeperProcessor(handler));
    shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
    shared_ptr<TTransportFactory> transportFactory(new TFramedTransportFactory());
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
    shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(numThreads);
    shared_ptr<ThreadFactory> threadFactory(new PosixThreadFactory());
    threadManager->threadFactory(threadFactory);
    threadManager->start();
    TNonblockingServer server(processor, protocolFactory, port, threadManager);
    server.serve();
    return 0;
}
<commit_msg>added remove() method<commit_after>/**
 * This is a implementation of the mapkeeper interface that uses
 * leveldb.
 *
 * http://leveldb.googlecode.com/svn/trunk/doc/index.html
 */
#include <cstdio>
#include "MapKeeper.h"
#include <leveldb/db.h>
#include <boost/ptr_container/ptr_map.hpp>
#include <boost/thread/shared_mutex.hpp>
#include <sys/types.h>
#include <dirent.h>
#include <errno.h>

#include <protocol/TBinaryProtocol.h>
#include <server/TSimpleServer.h>
#include <server/TThreadPoolServer.h>
#include <server/TNonblockingServer.h>
#include <transport/TServerSocket.h>
#include <transport/TBufferTransports.h>
#include <thrift/concurrency/ThreadManager.h>
#include <thrift/concurrency/PosixThreadFactory.h>

using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
using namespace ::apache::thrift::server;
using namespace ::apache::thrift::concurrency;

using boost::shared_ptr;

using namespace mapkeeper;

class LevelDbServer: virtual public MapKeeperIf {
public:
    LevelDbServer(const std::string& directoryName) :
        directoryName_(directoryName) {
    }

    ResponseCode::type ping() {
        return ResponseCode::Success;
    }

    ResponseCode::type addMap(const std::string& mapName) {
        leveldb::DB* db;
        leveldb::Options options;
        options.create_if_missing = true;
        options.error_if_exists = true;
        leveldb::Status status = leveldb::DB::Open(options, directoryName_ + mapName, &db);
        if (!status.ok()) {
            // TODO check return code
            printf("status: %s\n", status.ToString().c_str());
            return ResponseCode::Error;
        }
        std::string mapName_ = mapName;
        boost::unique_lock< boost::shared_mutex > writeLock(mutex_);;
        maps_.insert(mapName_, db);
        return ResponseCode::Success;
    }

    ResponseCode::type dropMap(const std::string& mapName) {
        std::string mapName_ = mapName;
        boost::ptr_map<std::string, leveldb::DB>::iterator itr;
        boost::unique_lock< boost::shared_mutex> writeLock(mutex_);;
        itr = maps_.find(mapName_);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        maps_.erase(itr);
        return ResponseCode::Success;
    }

    void listMaps(StringListResponse& _return) {
        DIR *dp;
        struct dirent *dirp;
        if((dp  = opendir(directoryName_.c_str())) == NULL) {
            _return.responseCode = ResponseCode::Success;
            return;
        }

        while ((dirp = readdir(dp)) != NULL) {
            _return.values.push_back(std::string(dirp->d_name));
        }
        closedir(dp);
        _return.responseCode = ResponseCode::Success;
    }

    void scan(RecordListResponse& _return, const std::string& mapName, const ScanOrder::type order,
              const std::string& startKey, const bool startKeyIncluded,
              const std::string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
    }

    void scanAscending(RecordListResponse& _return, std::map<std::string, std::string>& map,
              const std::string& startKey, const bool startKeyIncluded,
              const std::string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
        _return.responseCode = ResponseCode::ScanEnded;
    }

    void scanDescending(RecordListResponse& _return, std::map<std::string, std::string>& map,
              const std::string& startKey, const bool startKeyIncluded,
              const std::string& endKey, const bool endKeyIncluded,
              const int32_t maxRecords, const int32_t maxBytes) {
        _return.responseCode = ResponseCode::ScanEnded;
    }

    void get(BinaryResponse& _return, const std::string& mapName, const std::string& key) {
        boost::shared_lock< boost::shared_mutex> readLock(mutex_);;
        boost::ptr_map<std::string, leveldb::DB>::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            _return.responseCode = ResponseCode::MapNotFound;
            return;
        }
        leveldb::Status status = itr->second->Get(leveldb::ReadOptions(), key, &(_return.value));
        if (status.IsNotFound()) {
            _return.responseCode = ResponseCode::RecordNotFound;
            return;
        } else if (!status.ok()) {
            _return.responseCode = ResponseCode::Error;
            return;
        }
        _return.responseCode = ResponseCode::Success;
    }

    ResponseCode::type put(const std::string& mapName, const std::string& key, const std::string& value) {
        std::string mapName_ = mapName;
        boost::ptr_map<std::string, leveldb::DB>::iterator itr;
        boost::shared_lock< boost::shared_mutex> readLock(mutex_);;
        itr = maps_.find(mapName_);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        leveldb::Status status = itr->second->Put(leveldb::WriteOptions(), key, value);
        if (!status.ok()) {
            return ResponseCode::Error;
        }
        return ResponseCode::Success;
    }

    ResponseCode::type insert(const std::string& mapName, const std::string& key, const std::string& value) {
        return ResponseCode::Success;
    }

    ResponseCode::type update(const std::string& mapName, const std::string& key, const std::string& value) {
        return ResponseCode::Success;
    }

    ResponseCode::type remove(const std::string& mapName, const std::string& key) {
        boost::shared_lock< boost::shared_mutex> readLock(mutex_);;
        boost::ptr_map<std::string, leveldb::DB>::iterator itr = maps_.find(mapName);
        if (itr == maps_.end()) {
            return ResponseCode::MapNotFound;
        }
        leveldb::Status status = itr->second->Delete(leveldb::WriteOptions(), key);
        if (status.IsNotFound()) {
            return ResponseCode::RecordNotFound;
        } else if (!status.ok()) {
            return ResponseCode::Error;
        }
        return ResponseCode::Success;
    }

private:
    std::string directoryName_; // directory to store db files.
    boost::ptr_map<std::string, leveldb::DB> maps_;
    boost::shared_mutex mutex_; // protect map_
};

int main(int argc, char **argv) {
    int port = 9091;
    size_t numThreads = 32;
    shared_ptr<LevelDbServer> handler(new LevelDbServer("."));
    shared_ptr<TProcessor> processor(new MapKeeperProcessor(handler));
    shared_ptr<TServerTransport> serverTransport(new TServerSocket(port));
    shared_ptr<TTransportFactory> transportFactory(new TFramedTransportFactory());
    shared_ptr<TProtocolFactory> protocolFactory(new TBinaryProtocolFactory());
    shared_ptr<ThreadManager> threadManager = ThreadManager::newSimpleThreadManager(numThreads);
    shared_ptr<ThreadFactory> threadFactory(new PosixThreadFactory());
    threadManager->threadFactory(threadFactory);
    threadManager->start();
    TNonblockingServer server(processor, protocolFactory, port, threadManager);
    server.serve();
    return 0;
}
<|endoftext|>


<commit_before>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.

#ifndef POSEIDON_CORE_ABSTRACT_FUTURE_HPP_
#define POSEIDON_CORE_ABSTRACT_FUTURE_HPP_

#include "../fwd.hpp"

namespace poseidon {

class Abstract_Future
  : public ::asteria::Rcfwd<Abstract_Future>
  {
  protected:
    mutable mutex m_mutex;

  public:
    Abstract_Future()
    noexcept
      { }

    ASTERIA_NONCOPYABLE_DESTRUCTOR(Abstract_Future);

  public:
    // Gets the state, which is any of `future_state_empty`, `future_state_value`
    // or `future_state_except`.
    ROCKET_PURE_FUNCTION virtual
    Future_State
    state()
    const noexcept
      = 0;
  };

}  // namespace poseidon

#endif
<commit_msg>core/abstract_future: More private!<commit_after>// This file is part of Poseidon.
// Copyleft 2020, LH_Mouse. All wrongs reserved.

#ifndef POSEIDON_CORE_ABSTRACT_FUTURE_HPP_
#define POSEIDON_CORE_ABSTRACT_FUTURE_HPP_

#include "../fwd.hpp"

namespace poseidon {

class Abstract_Future
  : public ::asteria::Rcfwd<Abstract_Future>
  {
    template<typename> friend class Promise;
    template<typename> friend class Future;

  private:
    mutable mutex m_mutex;

  public:
    Abstract_Future()
    noexcept
      { }

    ASTERIA_NONCOPYABLE_DESTRUCTOR(Abstract_Future);

  public:
    // Gets the state, which is any of `future_state_empty`, `future_state_value`
    // or `future_state_except`.
    ROCKET_PURE_FUNCTION virtual
    Future_State
    state()
    const noexcept
      = 0;
  };

}  // namespace poseidon

#endif
<|endoftext|>


<commit_before>//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the LoopInfo class that is used to identify natural loops
// and determine the loop depth of various nodes of the CFG.  Note that the
// loops identified may actually be several natural loops that share the same
// header node... not just a single natural loop.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/Streams.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SmallPtrSet.h"
#include <algorithm>
#include <ostream>
using namespace llvm;

char LoopInfo::ID = 0;
static RegisterPass<LoopInfo>
X("loops", "Natural Loop Construction", true, true);

//===----------------------------------------------------------------------===//
// Loop implementation
//

//===----------------------------------------------------------------------===//
// LoopInfo implementation
//
bool LoopInfo::runOnFunction(Function &) {
  releaseMemory();
  LI->Calculate(getAnalysis<DominatorTree>().getBase());    // Update
  return false;
}

void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
  AU.addRequired<DominatorTree>();
}
<commit_msg>Change the description string of the LoopInfo pass. "Construction" makes it sound like a pass that might modify the CFG to construct natural loops.<commit_after>//===- LoopInfo.cpp - Natural Loop Calculator -----------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the LoopInfo class that is used to identify natural loops
// and determine the loop depth of various nodes of the CFG.  Note that the
// loops identified may actually be several natural loops that share the same
// header node... not just a single natural loop.
//
//===----------------------------------------------------------------------===//

#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Constants.h"
#include "llvm/Instructions.h"
#include "llvm/Analysis/Dominators.h"
#include "llvm/Assembly/Writer.h"
#include "llvm/Support/CFG.h"
#include "llvm/Support/Streams.h"
#include "llvm/ADT/DepthFirstIterator.h"
#include "llvm/ADT/SmallPtrSet.h"
#include <algorithm>
#include <ostream>
using namespace llvm;

char LoopInfo::ID = 0;
static RegisterPass<LoopInfo>
X("loops", "Natural Loop Information", true, true);

//===----------------------------------------------------------------------===//
// Loop implementation
//

//===----------------------------------------------------------------------===//
// LoopInfo implementation
//
bool LoopInfo::runOnFunction(Function &) {
  releaseMemory();
  LI->Calculate(getAnalysis<DominatorTree>().getBase());    // Update
  return false;
}

void LoopInfo::getAnalysisUsage(AnalysisUsage &AU) const {
  AU.setPreservesAll();
  AU.addRequired<DominatorTree>();
}
<|endoftext|>


<commit_before>///===--- FileManager.cpp - File System Probing and Caching ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the FileManager interface.
//
//===----------------------------------------------------------------------===//
//
// TODO: This should index all interesting directories with dirent calls.
//  getdirentries ?
//  opendir/readdir_r/closedir ?
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Path.h"
#include "llvm/Config/config.h"
#include <map>
#include <set>
#include <string>
using namespace clang;

// FIXME: Enhance libsystem to support inode and other fields.
#include <sys/stat.h>

#if defined(_MSC_VER)
#define S_ISDIR(s) (_S_IFDIR & s)
#endif

/// NON_EXISTENT_DIR - A special value distinct from null that is used to
/// represent a dir name that doesn't exist on the disk.
#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)

//===----------------------------------------------------------------------===//
// Windows.
//===----------------------------------------------------------------------===//

#ifdef LLVM_ON_WIN32

#define DIR_SEPARATOR_CHARS "/\\"

namespace {
  static std::string GetFullPath(const char *relPath) {
    char *absPathStrPtr = _fullpath(NULL, relPath, 0);
    assert(absPathStrPtr && "_fullpath() returned NULL!");

    std::string absPath(absPathStrPtr);

    free(absPathStrPtr);
    return absPath;
  }
}

class FileManager::UniqueDirContainer {
  /// UniqueDirs - Cache from full path to existing directories/files.
  ///
  llvm::StringMap<DirectoryEntry> UniqueDirs;

public:
  DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
    std::string FullPath(GetFullPath(Name));
    return UniqueDirs.GetOrCreateValue(
                              FullPath.c_str(),
                              FullPath.c_str() + FullPath.size()
                                                                ).getValue();
  }

  size_t size() { return UniqueDirs.size(); }
};

class FileManager::UniqueFileContainer {
  /// UniqueFiles - Cache from full path to existing directories/files.
  ///
  llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;

public:
  FileEntry &getFile(const char *Name, struct stat &StatBuf) {
    std::string FullPath(GetFullPath(Name));

    // LowercaseString because Windows filesystem is case insensitive.
    FullPath = llvm::LowercaseString(FullPath);
    return UniqueFiles.GetOrCreateValue(
                               FullPath.c_str(),
                               FullPath.c_str() + FullPath.size()
                                                                 ).getValue();
  }

  size_t size() { return UniqueFiles.size(); }
};

//===----------------------------------------------------------------------===//
// Unix-like Systems.
//===----------------------------------------------------------------------===//

#else

#define DIR_SEPARATOR_CHARS "/"

class FileManager::UniqueDirContainer {
  /// UniqueDirs - Cache from ID's to existing directories/files.
  ///
  std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;

public:
  DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
    return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
  }

  size_t size() { return UniqueDirs.size(); }
};

class FileManager::UniqueFileContainer {
  /// UniqueFiles - Cache from ID's to existing directories/files.
  ///
  std::set<FileEntry> UniqueFiles;

public:
  FileEntry &getFile(const char *Name, struct stat &StatBuf) {
    return
      const_cast<FileEntry&>(
                    *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
                                                  StatBuf.st_ino,
                                                  StatBuf.st_mode)).first);
  }

  size_t size() { return UniqueFiles.size(); }
};

#endif

//===----------------------------------------------------------------------===//
// Common logic.
//===----------------------------------------------------------------------===//

FileManager::FileManager()
  : UniqueDirs(*new UniqueDirContainer),
    UniqueFiles(*new UniqueFileContainer),
    DirEntries(64), FileEntries(64), NextFileUID(0) {
  NumDirLookups = NumFileLookups = 0;
  NumDirCacheMisses = NumFileCacheMisses = 0;
}

FileManager::~FileManager() {
  delete &UniqueDirs;
  delete &UniqueFiles;
  for (llvm::SmallVectorImpl<FileEntry *>::iterator
         V = VirtualFileEntries.begin(),
         VEnd = VirtualFileEntries.end();
       V != VEnd;
       ++V)
    delete *V;
}

void FileManager::addStatCache(StatSysCallCache *statCache, bool AtBeginning) {
  assert(statCache && "No stat cache provided?");
  if (AtBeginning || StatCache.get() == 0) {
    statCache->setNextStatCache(StatCache.take());
    StatCache.reset(statCache);
    return;
  }

  StatSysCallCache *LastCache = StatCache.get();
  while (LastCache->getNextStatCache())
    LastCache = LastCache->getNextStatCache();

  LastCache->setNextStatCache(statCache);
}

void FileManager::removeStatCache(StatSysCallCache *statCache) {
  if (!statCache)
    return;

  if (StatCache.get() == statCache) {
    // This is the first stat cache.
    StatCache.reset(StatCache->takeNextStatCache());
    return;
  }

  // Find the stat cache in the list.
  StatSysCallCache *PrevCache = StatCache.get();
  while (PrevCache && PrevCache->getNextStatCache() != statCache)
    PrevCache = PrevCache->getNextStatCache();
  if (PrevCache)
    PrevCache->setNextStatCache(statCache->getNextStatCache());
  else
    assert(false && "Stat cache not found for removal");
}

/// \brief Retrieve the directory that the given file name resides in.
static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
                                                  llvm::StringRef Filename,
                                      const FileSystemOptions &FileSystemOpts) {
  // Figure out what directory it is in.   If the string contains a / in it,
  // strip off everything after it.
  // FIXME: this logic should be in sys::Path.
  size_t SlashPos = Filename.rfind(DIR_SEPARATOR_CHARS);

  // Use the current directory if file has no path component.
  if (SlashPos == llvm::StringRef::npos)
    return FileMgr.getDirectory(".", FileSystemOpts);

  if (SlashPos == Filename.size()-1)
    return 0;       // If filename ends with a /, it's a directory.

  // Ignore repeated //'s.
  while (SlashPos != 0 &&
         llvm::StringRef(DIR_SEPARATOR_CHARS).count(Filename[SlashPos-1]))
    --SlashPos;

  return FileMgr.getDirectory(Filename.substr(0, SlashPos), FileSystemOpts);
}

/// getDirectory - Lookup, cache, and verify the specified directory.  This
/// returns null if the directory doesn't exist.
///
const DirectoryEntry *FileManager::getDirectory(llvm::StringRef Filename,
                                      const FileSystemOptions &FileSystemOpts) {
  // stat doesn't like trailing separators (at least on Windows).
  if (Filename.size() > 1 &&
      (Filename.back() == '/' || Filename.back() == '\\'))
    Filename = Filename.substr(0, Filename.size()-1);

  ++NumDirLookups;
  llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
    DirEntries.GetOrCreateValue(Filename);

  // See if there is already an entry in the map.
  if (NamedDirEnt.getValue())
    return NamedDirEnt.getValue() == NON_EXISTENT_DIR
              ? 0 : NamedDirEnt.getValue();

  ++NumDirCacheMisses;

  // By default, initialize it to invalid.
  NamedDirEnt.setValue(NON_EXISTENT_DIR);

  // Get the null-terminated directory name as stored as the key of the
  // DirEntries map.
  const char *InterndDirName = NamedDirEnt.getKeyData();

  // Check to see if the directory exists.
  struct stat StatBuf;
  if (stat_cached(InterndDirName, &StatBuf, FileSystemOpts) ||   // Error stat'ing.
      !S_ISDIR(StatBuf.st_mode))          // Not a directory?
    return 0;

  // It exists.  See if we have already opened a directory with the same inode.
  // This occurs when one dir is symlinked to another, for example.
  DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf);

  NamedDirEnt.setValue(&UDE);
  if (UDE.getName()) // Already have an entry with this inode, return it.
    return &UDE;

  // Otherwise, we don't have this directory yet, add it.  We use the string
  // key from the DirEntries map as the string.
  UDE.Name  = InterndDirName;
  return &UDE;
}

/// NON_EXISTENT_FILE - A special value distinct from null that is used to
/// represent a filename that doesn't exist on the disk.
#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)

/// getFile - Lookup, cache, and verify the specified file.  This returns null
/// if the file doesn't exist.
///
const FileEntry *FileManager::getFile(llvm::StringRef Filename,
                                      const FileSystemOptions &FileSystemOpts) {
  ++NumFileLookups;

  // See if there is already an entry in the map.
  llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
    FileEntries.GetOrCreateValue(Filename);

  // See if there is already an entry in the map.
  if (NamedFileEnt.getValue())
    return NamedFileEnt.getValue() == NON_EXISTENT_FILE
                 ? 0 : NamedFileEnt.getValue();

  ++NumFileCacheMisses;

  // By default, initialize it to invalid.
  NamedFileEnt.setValue(NON_EXISTENT_FILE);

  // Get the null-terminated file name as stored as the key of the
  // FileEntries map.
  const char *InterndFileName = NamedFileEnt.getKeyData();

  const DirectoryEntry *DirInfo
    = getDirectoryFromFile(*this, Filename, FileSystemOpts);
  if (DirInfo == 0)  // Directory doesn't exist, file can't exist.
    return 0;

  // FIXME: Use the directory info to prune this, before doing the stat syscall.
  // FIXME: This will reduce the # syscalls.

  // Nope, there isn't.  Check to see if the file exists.
  struct stat StatBuf;
  //llvm::errs() << "STATING: " << Filename;
  if (stat_cached(InterndFileName, &StatBuf, FileSystemOpts) ||   // Error stat'ing.
        S_ISDIR(StatBuf.st_mode)) {           // A directory?
    // If this file doesn't exist, we leave a null in FileEntries for this path.
    //llvm::errs() << ": Not existing\n";
    return 0;
  }
  //llvm::errs() << ": exists\n";

  // It exists.  See if we have already opened a file with the same inode.
  // This occurs when one dir is symlinked to another, for example.
  FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf);

  NamedFileEnt.setValue(&UFE);
  if (UFE.getName())  // Already have an entry with this inode, return it.
    return &UFE;

  // Otherwise, we don't have this directory yet, add it.
  // FIXME: Change the name to be a char* that points back to the 'FileEntries'
  // key.
  UFE.Name    = InterndFileName;
  UFE.Size    = StatBuf.st_size;
  UFE.ModTime = StatBuf.st_mtime;
  UFE.Dir     = DirInfo;
  UFE.UID     = NextFileUID++;
  return &UFE;
}

const FileEntry *
FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size,
                            time_t ModificationTime,
                            const FileSystemOptions &FileSystemOpts) {
  ++NumFileLookups;

  // See if there is already an entry in the map.
  llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
    FileEntries.GetOrCreateValue(Filename);

  // See if there is already an entry in the map.
  if (NamedFileEnt.getValue())
    return NamedFileEnt.getValue() == NON_EXISTENT_FILE
                 ? 0 : NamedFileEnt.getValue();

  ++NumFileCacheMisses;

  // By default, initialize it to invalid.
  NamedFileEnt.setValue(NON_EXISTENT_FILE);

  const DirectoryEntry *DirInfo
    = getDirectoryFromFile(*this, Filename, FileSystemOpts);
  if (DirInfo == 0)  // Directory doesn't exist, file can't exist.
    return 0;

  FileEntry *UFE = new FileEntry();
  VirtualFileEntries.push_back(UFE);
  NamedFileEnt.setValue(UFE);

  UFE->Name    = NamedFileEnt.getKeyData();
  UFE->Size    = Size;
  UFE->ModTime = ModificationTime;
  UFE->Dir     = DirInfo;
  UFE->UID     = NextFileUID++;

  // If this virtual file resolves to a file, also map that file to the
  // newly-created file entry.
  const char *InterndFileName = NamedFileEnt.getKeyData();
  struct stat StatBuf;
  if (!stat_cached(InterndFileName, &StatBuf, FileSystemOpts) &&
      !S_ISDIR(StatBuf.st_mode)) {
    llvm::sys::Path FilePath(InterndFileName);
    FilePath.makeAbsolute();
    FileEntries[FilePath.str()] = UFE;
  }

  return UFE;
}

llvm::MemoryBuffer *FileManager::
getBufferForFile(const char *FilenameStart, const char *FilenameEnd,
                 const FileSystemOptions &FileSystemOpts,
                 std::string *ErrorStr,
                 int64_t FileSize,
                 struct stat *FileInfo) {
  llvm::sys::Path FilePath(llvm::StringRef(FilenameStart,
                                           FilenameEnd-FilenameStart));
  FixupRelativePath(FilePath, FileSystemOpts);

  return llvm::MemoryBuffer::getFile(FilePath.c_str(), ErrorStr,
                                     FileSize, FileInfo);
}

int FileManager::stat_cached(const char* path, struct stat* buf,
                             const FileSystemOptions &FileSystemOpts) {
  llvm::sys::Path FilePath(path);
  FixupRelativePath(FilePath, FileSystemOpts);

  return StatCache.get() ? StatCache->stat(FilePath.c_str(), buf)
                         : stat(FilePath.c_str(), buf);
}

void FileManager::FixupRelativePath(llvm::sys::Path &path,
                                    const FileSystemOptions &FSOpts) {
  if (!FSOpts.WorkingDir.empty() && !path.isAbsolute()) {
    llvm::sys::Path NewPath(FSOpts.WorkingDir);
    NewPath.appendComponent(path.str());
    path = NewPath;
  }
}

void FileManager::PrintStats() const {
  llvm::errs() << "\n*** File Manager Stats:\n";
  llvm::errs() << UniqueFiles.size() << " files found, "
               << UniqueDirs.size() << " dirs found.\n";
  llvm::errs() << NumDirLookups << " dir lookups, "
               << NumDirCacheMisses << " dir cache misses.\n";
  llvm::errs() << NumFileLookups << " file lookups, "
               << NumFileCacheMisses << " file cache misses.\n";

  //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
}

int MemorizeStatCalls::stat(const char *path, struct stat *buf) {
  int result = StatSysCallCache::stat(path, buf);

  // Do not cache failed stats, it is easy to construct common inconsistent
  // situations if we do, and they are not important for PCH performance (which
  // currently only needs the stats to construct the initial FileManager
  // entries).
  if (result != 0)
    return result;

  // Cache file 'stat' results and directories with absolutely paths.
  if (!S_ISDIR(buf->st_mode) || llvm::sys::Path(path).isAbsolute())
    StatCalls[path] = StatResult(result, *buf);

  return result;
}
<commit_msg>Filename.rfind("/\\") won't give us the position of the last directory seperator.<commit_after>///===--- FileManager.cpp - File System Probing and Caching ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
//  This file implements the FileManager interface.
//
//===----------------------------------------------------------------------===//
//
// TODO: This should index all interesting directories with dirent calls.
//  getdirentries ?
//  opendir/readdir_r/closedir ?
//
//===----------------------------------------------------------------------===//

#include "clang/Basic/FileManager.h"
#include "clang/Basic/FileSystemOptions.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/System/Path.h"
#include "llvm/Config/config.h"
#include <map>
#include <set>
#include <string>
using namespace clang;

// FIXME: Enhance libsystem to support inode and other fields.
#include <sys/stat.h>

#if defined(_MSC_VER)
#define S_ISDIR(s) (_S_IFDIR & s)
#endif

/// NON_EXISTENT_DIR - A special value distinct from null that is used to
/// represent a dir name that doesn't exist on the disk.
#define NON_EXISTENT_DIR reinterpret_cast<DirectoryEntry*>((intptr_t)-1)

//===----------------------------------------------------------------------===//
// Windows.
//===----------------------------------------------------------------------===//

#ifdef LLVM_ON_WIN32

#define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/' || (x) == '\\')

namespace {
  static std::string GetFullPath(const char *relPath) {
    char *absPathStrPtr = _fullpath(NULL, relPath, 0);
    assert(absPathStrPtr && "_fullpath() returned NULL!");

    std::string absPath(absPathStrPtr);

    free(absPathStrPtr);
    return absPath;
  }
}

class FileManager::UniqueDirContainer {
  /// UniqueDirs - Cache from full path to existing directories/files.
  ///
  llvm::StringMap<DirectoryEntry> UniqueDirs;

public:
  DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
    std::string FullPath(GetFullPath(Name));
    return UniqueDirs.GetOrCreateValue(
                              FullPath.c_str(),
                              FullPath.c_str() + FullPath.size()
                                                                ).getValue();
  }

  size_t size() { return UniqueDirs.size(); }
};

class FileManager::UniqueFileContainer {
  /// UniqueFiles - Cache from full path to existing directories/files.
  ///
  llvm::StringMap<FileEntry, llvm::BumpPtrAllocator> UniqueFiles;

public:
  FileEntry &getFile(const char *Name, struct stat &StatBuf) {
    std::string FullPath(GetFullPath(Name));

    // LowercaseString because Windows filesystem is case insensitive.
    FullPath = llvm::LowercaseString(FullPath);
    return UniqueFiles.GetOrCreateValue(
                               FullPath.c_str(),
                               FullPath.c_str() + FullPath.size()
                                                                 ).getValue();
  }

  size_t size() { return UniqueFiles.size(); }
};

//===----------------------------------------------------------------------===//
// Unix-like Systems.
//===----------------------------------------------------------------------===//

#else

#define IS_DIR_SEPARATOR_CHAR(x) ((x) == '/')

class FileManager::UniqueDirContainer {
  /// UniqueDirs - Cache from ID's to existing directories/files.
  ///
  std::map<std::pair<dev_t, ino_t>, DirectoryEntry> UniqueDirs;

public:
  DirectoryEntry &getDirectory(const char *Name, struct stat &StatBuf) {
    return UniqueDirs[std::make_pair(StatBuf.st_dev, StatBuf.st_ino)];
  }

  size_t size() { return UniqueDirs.size(); }
};

class FileManager::UniqueFileContainer {
  /// UniqueFiles - Cache from ID's to existing directories/files.
  ///
  std::set<FileEntry> UniqueFiles;

public:
  FileEntry &getFile(const char *Name, struct stat &StatBuf) {
    return
      const_cast<FileEntry&>(
                    *UniqueFiles.insert(FileEntry(StatBuf.st_dev,
                                                  StatBuf.st_ino,
                                                  StatBuf.st_mode)).first);
  }

  size_t size() { return UniqueFiles.size(); }
};

#endif

//===----------------------------------------------------------------------===//
// Common logic.
//===----------------------------------------------------------------------===//

FileManager::FileManager()
  : UniqueDirs(*new UniqueDirContainer),
    UniqueFiles(*new UniqueFileContainer),
    DirEntries(64), FileEntries(64), NextFileUID(0) {
  NumDirLookups = NumFileLookups = 0;
  NumDirCacheMisses = NumFileCacheMisses = 0;
}

FileManager::~FileManager() {
  delete &UniqueDirs;
  delete &UniqueFiles;
  for (llvm::SmallVectorImpl<FileEntry *>::iterator
         V = VirtualFileEntries.begin(),
         VEnd = VirtualFileEntries.end();
       V != VEnd;
       ++V)
    delete *V;
}

void FileManager::addStatCache(StatSysCallCache *statCache, bool AtBeginning) {
  assert(statCache && "No stat cache provided?");
  if (AtBeginning || StatCache.get() == 0) {
    statCache->setNextStatCache(StatCache.take());
    StatCache.reset(statCache);
    return;
  }

  StatSysCallCache *LastCache = StatCache.get();
  while (LastCache->getNextStatCache())
    LastCache = LastCache->getNextStatCache();

  LastCache->setNextStatCache(statCache);
}

void FileManager::removeStatCache(StatSysCallCache *statCache) {
  if (!statCache)
    return;

  if (StatCache.get() == statCache) {
    // This is the first stat cache.
    StatCache.reset(StatCache->takeNextStatCache());
    return;
  }

  // Find the stat cache in the list.
  StatSysCallCache *PrevCache = StatCache.get();
  while (PrevCache && PrevCache->getNextStatCache() != statCache)
    PrevCache = PrevCache->getNextStatCache();
  if (PrevCache)
    PrevCache->setNextStatCache(statCache->getNextStatCache());
  else
    assert(false && "Stat cache not found for removal");
}

/// \brief Retrieve the directory that the given file name resides in.
static const DirectoryEntry *getDirectoryFromFile(FileManager &FileMgr,
                                                  llvm::StringRef Filename,
                                      const FileSystemOptions &FileSystemOpts) {
  // Figure out what directory it is in.   If the string contains a / in it,
  // strip off everything after it.
  // FIXME: this logic should be in sys::Path.
  size_t SlashPos = Filename.size();
  while (SlashPos != 0 && !IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
    --SlashPos;

  // Use the current directory if file has no path component.
  if (SlashPos == 0)
    return FileMgr.getDirectory(".", FileSystemOpts);

  if (SlashPos == Filename.size()-1)
    return 0;       // If filename ends with a /, it's a directory.

  // Ignore repeated //'s.
  while (SlashPos != 0 && IS_DIR_SEPARATOR_CHAR(Filename[SlashPos-1]))
    --SlashPos;

  return FileMgr.getDirectory(Filename.substr(0, SlashPos), FileSystemOpts);
}

/// getDirectory - Lookup, cache, and verify the specified directory.  This
/// returns null if the directory doesn't exist.
///
const DirectoryEntry *FileManager::getDirectory(llvm::StringRef Filename,
                                      const FileSystemOptions &FileSystemOpts) {
  // stat doesn't like trailing separators (at least on Windows).
  if (Filename.size() > 1 && IS_DIR_SEPARATOR_CHAR(Filename.back()))
    Filename = Filename.substr(0, Filename.size()-1);

  ++NumDirLookups;
  llvm::StringMapEntry<DirectoryEntry *> &NamedDirEnt =
    DirEntries.GetOrCreateValue(Filename);

  // See if there is already an entry in the map.
  if (NamedDirEnt.getValue())
    return NamedDirEnt.getValue() == NON_EXISTENT_DIR
              ? 0 : NamedDirEnt.getValue();

  ++NumDirCacheMisses;

  // By default, initialize it to invalid.
  NamedDirEnt.setValue(NON_EXISTENT_DIR);

  // Get the null-terminated directory name as stored as the key of the
  // DirEntries map.
  const char *InterndDirName = NamedDirEnt.getKeyData();

  // Check to see if the directory exists.
  struct stat StatBuf;
  if (stat_cached(InterndDirName, &StatBuf, FileSystemOpts) ||   // Error stat'ing.
      !S_ISDIR(StatBuf.st_mode))          // Not a directory?
    return 0;

  // It exists.  See if we have already opened a directory with the same inode.
  // This occurs when one dir is symlinked to another, for example.
  DirectoryEntry &UDE = UniqueDirs.getDirectory(InterndDirName, StatBuf);

  NamedDirEnt.setValue(&UDE);
  if (UDE.getName()) // Already have an entry with this inode, return it.
    return &UDE;

  // Otherwise, we don't have this directory yet, add it.  We use the string
  // key from the DirEntries map as the string.
  UDE.Name  = InterndDirName;
  return &UDE;
}

/// NON_EXISTENT_FILE - A special value distinct from null that is used to
/// represent a filename that doesn't exist on the disk.
#define NON_EXISTENT_FILE reinterpret_cast<FileEntry*>((intptr_t)-1)

/// getFile - Lookup, cache, and verify the specified file.  This returns null
/// if the file doesn't exist.
///
const FileEntry *FileManager::getFile(llvm::StringRef Filename,
                                      const FileSystemOptions &FileSystemOpts) {
  ++NumFileLookups;

  // See if there is already an entry in the map.
  llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
    FileEntries.GetOrCreateValue(Filename);

  // See if there is already an entry in the map.
  if (NamedFileEnt.getValue())
    return NamedFileEnt.getValue() == NON_EXISTENT_FILE
                 ? 0 : NamedFileEnt.getValue();

  ++NumFileCacheMisses;

  // By default, initialize it to invalid.
  NamedFileEnt.setValue(NON_EXISTENT_FILE);

  // Get the null-terminated file name as stored as the key of the
  // FileEntries map.
  const char *InterndFileName = NamedFileEnt.getKeyData();

  const DirectoryEntry *DirInfo
    = getDirectoryFromFile(*this, Filename, FileSystemOpts);
  if (DirInfo == 0)  // Directory doesn't exist, file can't exist.
    return 0;

  // FIXME: Use the directory info to prune this, before doing the stat syscall.
  // FIXME: This will reduce the # syscalls.

  // Nope, there isn't.  Check to see if the file exists.
  struct stat StatBuf;
  //llvm::errs() << "STATING: " << Filename;
  if (stat_cached(InterndFileName, &StatBuf, FileSystemOpts) ||   // Error stat'ing.
        S_ISDIR(StatBuf.st_mode)) {           // A directory?
    // If this file doesn't exist, we leave a null in FileEntries for this path.
    //llvm::errs() << ": Not existing\n";
    return 0;
  }
  //llvm::errs() << ": exists\n";

  // It exists.  See if we have already opened a file with the same inode.
  // This occurs when one dir is symlinked to another, for example.
  FileEntry &UFE = UniqueFiles.getFile(InterndFileName, StatBuf);

  NamedFileEnt.setValue(&UFE);
  if (UFE.getName())  // Already have an entry with this inode, return it.
    return &UFE;

  // Otherwise, we don't have this directory yet, add it.
  // FIXME: Change the name to be a char* that points back to the 'FileEntries'
  // key.
  UFE.Name    = InterndFileName;
  UFE.Size    = StatBuf.st_size;
  UFE.ModTime = StatBuf.st_mtime;
  UFE.Dir     = DirInfo;
  UFE.UID     = NextFileUID++;
  return &UFE;
}

const FileEntry *
FileManager::getVirtualFile(llvm::StringRef Filename, off_t Size,
                            time_t ModificationTime,
                            const FileSystemOptions &FileSystemOpts) {
  ++NumFileLookups;

  // See if there is already an entry in the map.
  llvm::StringMapEntry<FileEntry *> &NamedFileEnt =
    FileEntries.GetOrCreateValue(Filename);

  // See if there is already an entry in the map.
  if (NamedFileEnt.getValue())
    return NamedFileEnt.getValue() == NON_EXISTENT_FILE
                 ? 0 : NamedFileEnt.getValue();

  ++NumFileCacheMisses;

  // By default, initialize it to invalid.
  NamedFileEnt.setValue(NON_EXISTENT_FILE);

  const DirectoryEntry *DirInfo
    = getDirectoryFromFile(*this, Filename, FileSystemOpts);
  if (DirInfo == 0)  // Directory doesn't exist, file can't exist.
    return 0;

  FileEntry *UFE = new FileEntry();
  VirtualFileEntries.push_back(UFE);
  NamedFileEnt.setValue(UFE);

  UFE->Name    = NamedFileEnt.getKeyData();
  UFE->Size    = Size;
  UFE->ModTime = ModificationTime;
  UFE->Dir     = DirInfo;
  UFE->UID     = NextFileUID++;

  // If this virtual file resolves to a file, also map that file to the
  // newly-created file entry.
  const char *InterndFileName = NamedFileEnt.getKeyData();
  struct stat StatBuf;
  if (!stat_cached(InterndFileName, &StatBuf, FileSystemOpts) &&
      !S_ISDIR(StatBuf.st_mode)) {
    llvm::sys::Path FilePath(InterndFileName);
    FilePath.makeAbsolute();
    FileEntries[FilePath.str()] = UFE;
  }

  return UFE;
}

llvm::MemoryBuffer *FileManager::
getBufferForFile(const char *FilenameStart, const char *FilenameEnd,
                 const FileSystemOptions &FileSystemOpts,
                 std::string *ErrorStr,
                 int64_t FileSize,
                 struct stat *FileInfo) {
  llvm::sys::Path FilePath(llvm::StringRef(FilenameStart,
                                           FilenameEnd-FilenameStart));
  FixupRelativePath(FilePath, FileSystemOpts);

  return llvm::MemoryBuffer::getFile(FilePath.c_str(), ErrorStr,
                                     FileSize, FileInfo);
}

int FileManager::stat_cached(const char* path, struct stat* buf,
                             const FileSystemOptions &FileSystemOpts) {
  llvm::sys::Path FilePath(path);
  FixupRelativePath(FilePath, FileSystemOpts);

  return StatCache.get() ? StatCache->stat(FilePath.c_str(), buf)
                         : stat(FilePath.c_str(), buf);
}

void FileManager::FixupRelativePath(llvm::sys::Path &path,
                                    const FileSystemOptions &FSOpts) {
  if (!FSOpts.WorkingDir.empty() && !path.isAbsolute()) {
    llvm::sys::Path NewPath(FSOpts.WorkingDir);
    NewPath.appendComponent(path.str());
    path = NewPath;
  }
}

void FileManager::PrintStats() const {
  llvm::errs() << "\n*** File Manager Stats:\n";
  llvm::errs() << UniqueFiles.size() << " files found, "
               << UniqueDirs.size() << " dirs found.\n";
  llvm::errs() << NumDirLookups << " dir lookups, "
               << NumDirCacheMisses << " dir cache misses.\n";
  llvm::errs() << NumFileLookups << " file lookups, "
               << NumFileCacheMisses << " file cache misses.\n";

  //llvm::errs() << PagesMapped << BytesOfPagesMapped << FSLookups;
}

int MemorizeStatCalls::stat(const char *path, struct stat *buf) {
  int result = StatSysCallCache::stat(path, buf);

  // Do not cache failed stats, it is easy to construct common inconsistent
  // situations if we do, and they are not important for PCH performance (which
  // currently only needs the stats to construct the initial FileManager
  // entries).
  if (result != 0)
    return result;

  // Cache file 'stat' results and directories with absolutely paths.
  if (!S_ISDIR(buf->st_mode) || llvm::sys::Path(path).isAbsolute())
    StatCalls[path] = StatResult(result, *buf);

  return result;
}
<|endoftext|>


<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief force symbols into programm
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2009-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Basics/Initialise.h"

#include "BasicsC/init.h"
#include "BasicsC/error.h"
#include "BasicsC/hashes.h"
#include "BasicsC/random.h"

#include "Logger/Logger.h"
#include "Basics/Random.h"

#ifdef TRI_BROKEN_CXA_GUARD
#include <pthread.h>
#endif

#include <build.h>

namespace triagens {
  namespace basics {
    void InitialiseBasics (int argv, char* argc[]) {
      TRIAGENS_C_INITIALISE(argv, argc);

      Random::random_e v = Random::selectVersion(Random::RAND_MERSENNE);
      Random::UniformInteger random(0, 1);
      random.random();
      Random::selectVersion(v);

      string revision = "$Revision: BASICS " TRIAGENS_VERSION " (c) triAGENS GmbH $";
      LOGGER_TRACE << revision;

#ifdef TRI_BROKEN_CXA_GUARD
      pthread_cond_t cond;
      pthread_cond_init(&cond, 0);
      pthread_cond_broadcast(&cond);
#endif
    }

    void ShutdownBasics () {
      TRIAGENS_C_SHUTDOWN;
    }
  }
}

<commit_msg>added comment<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief force symbols into programm
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2012 triagens GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Copyright 2009-2012, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////

#include "Basics/Initialise.h"

#include "BasicsC/init.h"
#include "BasicsC/error.h"
#include "BasicsC/hashes.h"
#include "BasicsC/random.h"

#include "Logger/Logger.h"
#include "Basics/Random.h"

#ifdef TRI_BROKEN_CXA_GUARD
#include <pthread.h>
#endif

#include <build.h>

namespace triagens {
  namespace basics {
    void InitialiseBasics (int argv, char* argc[]) {
      TRIAGENS_C_INITIALISE(argv, argc);

      // use the rng so the linker does not remove it from the executable
      // we might need it later because .so files might refer to the symbols
      Random::random_e v = Random::selectVersion(Random::RAND_MERSENNE);
      Random::UniformInteger random(0, 1);
      random.random();
      Random::selectVersion(v);

      string revision = "$Revision: BASICS " TRIAGENS_VERSION " (c) triAGENS GmbH $";
      LOGGER_TRACE << revision;

#ifdef TRI_BROKEN_CXA_GUARD
      pthread_cond_t cond;
      pthread_cond_init(&cond, 0);
      pthread_cond_broadcast(&cond);
#endif
    }

    void ShutdownBasics () {
      TRIAGENS_C_SHUTDOWN;
    }
  }
}

<|endoftext|>