KWSys 2012-05-02 (719638e2)

Extract upstream KWSys using the following shell code.

$ sha1=719638e233b560afb0d9a0afdcf23469dc1827fe &&
git archive --prefix=KWSys-snapshot/ $sha1 |
tar x
This commit is contained in:
KWSys Robot 2012-05-02 08:46:10 -04:00 committed by Brad King
commit 7d3c2959fa
79 changed files with 33403 additions and 0 deletions

279
Base64.c Normal file
View File

@ -0,0 +1,279 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Base64.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "Base64.h.in"
#endif
/*--------------------------------------------------------------------------*/
static const unsigned char kwsysBase64EncodeTable[65] =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
/*--------------------------------------------------------------------------*/
static const unsigned char kwsysBase64DecodeTable[256] =
{
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0x3E,0xFF,0xFF,0xFF,0x3F,
0x34,0x35,0x36,0x37,0x38,0x39,0x3A,0x3B,
0x3C,0x3D,0xFF,0xFF,0xFF,0x00,0xFF,0xFF,
0xFF,0x00,0x01,0x02,0x03,0x04,0x05,0x06,
0x07,0x08,0x09,0x0A,0x0B,0x0C,0x0D,0x0E,
0x0F,0x10,0x11,0x12,0x13,0x14,0x15,0x16,
0x17,0x18,0x19,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0x1A,0x1B,0x1C,0x1D,0x1E,0x1F,0x20,
0x21,0x22,0x23,0x24,0x25,0x26,0x27,0x28,
0x29,0x2A,0x2B,0x2C,0x2D,0x2E,0x2F,0x30,
0x31,0x32,0x33,0xFF,0xFF,0xFF,0xFF,0xFF,
/*------------------------------------*/
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF
};
/*--------------------------------------------------------------------------*/
static unsigned char kwsysBase64EncodeChar(int c)
{
return kwsysBase64EncodeTable[(unsigned char)c];
}
/*--------------------------------------------------------------------------*/
static unsigned char kwsysBase64DecodeChar(unsigned char c)
{
return kwsysBase64DecodeTable[c];
}
/*--------------------------------------------------------------------------*/
/* Encode 3 bytes into a 4 byte string. */
void kwsysBase64_Encode3(const unsigned char *src, unsigned char *dest)
{
dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30)|((src[1] >> 4) & 0x0F));
dest[2] = kwsysBase64EncodeChar(((src[1] << 2) & 0x3C)|((src[2] >> 6) & 0x03));
dest[3] = kwsysBase64EncodeChar(src[2] & 0x3F);
}
/*--------------------------------------------------------------------------*/
/* Encode 2 bytes into a 4 byte string. */
void kwsysBase64_Encode2(const unsigned char *src, unsigned char *dest)
{
dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30)|((src[1] >> 4) & 0x0F));
dest[2] = kwsysBase64EncodeChar(((src[1] << 2) & 0x3C));
dest[3] = '=';
}
/*--------------------------------------------------------------------------*/
/* Encode 1 bytes into a 4 byte string. */
void kwsysBase64_Encode1(const unsigned char *src, unsigned char *dest)
{
dest[0] = kwsysBase64EncodeChar((src[0] >> 2) & 0x3F);
dest[1] = kwsysBase64EncodeChar(((src[0] << 4) & 0x30));
dest[2] = '=';
dest[3] = '=';
}
/*--------------------------------------------------------------------------*/
/* Encode 'length' bytes from the input buffer and store the
encoded stream into the output buffer. Return the length of the encoded
buffer (output). Note that the output buffer must be allocated by the caller
(length * 1.5 should be a safe estimate). If 'mark_end' is true than an
extra set of 4 bytes is added to the end of the stream if the input is a
multiple of 3 bytes. These bytes are invalid chars and therefore they will
stop the decoder thus enabling the caller to decode a stream without
actually knowing how much data to expect (if the input is not a multiple of
3 bytes then the extra padding needed to complete the encode 4 bytes will
stop the decoding anyway). */
unsigned long kwsysBase64_Encode(const unsigned char *input,
unsigned long length,
unsigned char *output,
int mark_end)
{
const unsigned char *ptr = input;
const unsigned char *end = input + length;
unsigned char *optr = output;
/* Encode complete triplet */
while ((end - ptr) >= 3)
{
kwsysBase64_Encode3(ptr, optr);
ptr += 3;
optr += 4;
}
/* Encodes a 2-byte ending into 3 bytes and 1 pad byte and writes. */
if (end - ptr == 2)
{
kwsysBase64_Encode2(ptr, optr);
optr += 4;
}
/* Encodes a 1-byte ending into 2 bytes and 2 pad bytes */
else if (end - ptr == 1)
{
kwsysBase64_Encode1(ptr, optr);
optr += 4;
}
/* Do we need to mark the end */
else if (mark_end)
{
optr[0] = optr[1] = optr[2] = optr[3] = '=';
optr += 4;
}
return (unsigned long)(optr - output);
}
/*--------------------------------------------------------------------------*/
/* Decode 4 bytes into a 3 byte string. */
int kwsysBase64_Decode3(const unsigned char *src, unsigned char *dest)
{
unsigned char d0, d1, d2, d3;
d0 = kwsysBase64DecodeChar(src[0]);
d1 = kwsysBase64DecodeChar(src[1]);
d2 = kwsysBase64DecodeChar(src[2]);
d3 = kwsysBase64DecodeChar(src[3]);
/* Make sure all characters were valid */
if (d0 == 0xFF || d1 == 0xFF || d2 == 0xFF || d3 == 0xFF)
{
return 0;
}
/* Decode the 3 bytes */
dest[0] = (unsigned char)(((d0 << 2) & 0xFC) | ((d1 >> 4) & 0x03));
dest[1] = (unsigned char)(((d1 << 4) & 0xF0) | ((d2 >> 2) & 0x0F));
dest[2] = (unsigned char)(((d2 << 6) & 0xC0) | ((d3 >> 0) & 0x3F));
/* Return the number of bytes actually decoded */
if (src[2] == '=')
{
return 1;
}
if (src[3] == '=')
{
return 2;
}
return 3;
}
/*--------------------------------------------------------------------------*/
/* Decode bytes from the input buffer and store the decoded stream
into the output buffer until 'length' bytes have been decoded. Return the
real length of the decoded stream (which should be equal to 'length'). Note
that the output buffer must be allocated by the caller. If
'max_input_length' is not null, then it specifies the number of encoded
bytes that should be at most read from the input buffer. In that case the
'length' parameter is ignored. This enables the caller to decode a stream
without actually knowing how much decoded data to expect (of course, the
buffer must be large enough). */
unsigned long kwsysBase64_Decode(const unsigned char *input,
unsigned long length,
unsigned char *output,
unsigned long max_input_length)
{
const unsigned char *ptr = input;
unsigned char *optr = output;
/* Decode complete triplet */
if (max_input_length)
{
const unsigned char *end = input + max_input_length;
while (ptr < end)
{
int len = kwsysBase64_Decode3(ptr, optr);
optr += len;
if(len < 3)
{
return (unsigned long)(optr - output);
}
ptr += 4;
}
}
else
{
unsigned char *oend = output + length;
while ((oend - optr) >= 3)
{
int len = kwsysBase64_Decode3(ptr, optr);
optr += len;
if(len < 3)
{
return (unsigned long)(optr - output);
}
ptr += 4;
}
/* Decode the last triplet */
if (oend - optr == 2)
{
unsigned char temp[3];
int len = kwsysBase64_Decode3(ptr, temp);
if(len >= 2)
{
optr[0] = temp[0];
optr[1] = temp[1];
optr += 2;
}
else if(len > 0)
{
optr[0] = temp[0];
optr += 1;
}
}
else if (oend - optr == 1)
{
unsigned char temp[3];
int len = kwsysBase64_Decode3(ptr, temp);
if(len > 0)
{
optr[0] = temp[0];
optr += 1;
}
}
}
return (unsigned long)(optr - output);
}

120
Base64.h.in Normal file
View File

@ -0,0 +1,120 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_Base64_h
#define @KWSYS_NAMESPACE@_Base64_h
#include <@KWSYS_NAMESPACE@/Configure.h>
/* Redefine all public interface symbol names to be in the proper
namespace. These macros are used internally to kwsys only, and are
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysBase64 kwsys_ns(Base64)
# define kwsysBase64_Decode kwsys_ns(Base64_Decode)
# define kwsysBase64_Decode3 kwsys_ns(Base64_Decode3)
# define kwsysBase64_Encode kwsys_ns(Base64_Encode)
# define kwsysBase64_Encode1 kwsys_ns(Base64_Encode1)
# define kwsysBase64_Encode2 kwsys_ns(Base64_Encode2)
# define kwsysBase64_Encode3 kwsys_ns(Base64_Encode3)
#endif
#if defined(__cplusplus)
extern "C"
{
#endif
/**
* Encode 3 bytes into a 4 byte string.
*/
kwsysEXPORT void kwsysBase64_Encode3(const unsigned char *src,
unsigned char *dest);
/**
* Encode 2 bytes into a 4 byte string.
*/
kwsysEXPORT void kwsysBase64_Encode2(const unsigned char *src,
unsigned char *dest);
/**
* Encode 1 bytes into a 4 byte string.
*/
kwsysEXPORT void kwsysBase64_Encode1(const unsigned char *src,
unsigned char *dest);
/**
* Encode 'length' bytes from the input buffer and store the encoded
* stream into the output buffer. Return the length of the encoded
* buffer (output). Note that the output buffer must be allocated by
* the caller (length * 1.5 should be a safe estimate). If 'mark_end'
* is true than an extra set of 4 bytes is added to the end of the
* stream if the input is a multiple of 3 bytes. These bytes are
* invalid chars and therefore they will stop the decoder thus
* enabling the caller to decode a stream without actually knowing how
* much data to expect (if the input is not a multiple of 3 bytes then
* the extra padding needed to complete the encode 4 bytes will stop
* the decoding anyway).
*/
kwsysEXPORT unsigned long kwsysBase64_Encode(const unsigned char *input,
unsigned long length,
unsigned char *output,
int mark_end);
/**
* Decode 4 bytes into a 3 byte string. Returns the number of bytes
* actually decoded.
*/
kwsysEXPORT int kwsysBase64_Decode3(const unsigned char *src,
unsigned char *dest);
/**
* Decode bytes from the input buffer and store the decoded stream
* into the output buffer until 'length' bytes have been decoded.
* Return the real length of the decoded stream (which should be equal
* to 'length'). Note that the output buffer must be allocated by the
* caller. If 'max_input_length' is not null, then it specifies the
* number of encoded bytes that should be at most read from the input
* buffer. In that case the 'length' parameter is ignored. This
* enables the caller to decode a stream without actually knowing how
* much decoded data to expect (of course, the buffer must be large
* enough).
*/
kwsysEXPORT unsigned long kwsysBase64_Decode(const unsigned char *input,
unsigned long length,
unsigned char *output,
unsigned long max_input_length);
#if defined(__cplusplus)
} /* extern "C" */
#endif
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
# undef kwsys_ns
# undef kwsysEXPORT
# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysBase64
# undef kwsysBase64_Decode
# undef kwsysBase64_Decode3
# undef kwsysBase64_Encode
# undef kwsysBase64_Encode1
# undef kwsysBase64_Encode2
# undef kwsysBase64_Encode3
# endif
#endif
#endif

1
CMakeEmptyInputFile.in Normal file
View File

@ -0,0 +1 @@
@CMAKE_EMPTY_INPUT_FILE_CONTENT@

1042
CMakeLists.txt Normal file

File diff suppressed because it is too large Load Diff

117
CPU.h.in Normal file
View File

@ -0,0 +1,117 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_CPU_h
#define @KWSYS_NAMESPACE@_CPU_h
#include <@KWSYS_NAMESPACE@/Configure.h>
/* Identify possible endian cases. The macro
@KWSYS_NAMESPACE@_CPU_ENDIAN_ID will be defined to one of these, or
0 if unknown. */
#define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG 4321
#define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE 1234
/* Apple always defines one of these. */
#if defined(__LITTLE_ENDIAN__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
#elif defined(__BIG_ENDIAN__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* Alpha */
#elif defined(__alpha) || defined(__alpha__) || defined(_M_ALPHA)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
/* Arm */
#elif defined(__arm__)
# if !defined(__ARMEB__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
# else
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
# endif
/* Intel x86 */
#elif defined(__i386) || defined(__i386__) || defined(_M_IX86)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
#elif defined(_X86_) || defined(__THW_INTEL__) || defined(__I86__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
#elif defined(__MWERKS__) && defined(__INTEL__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
/* Intel x86-64 */
#elif defined(__x86_64) || defined(__x86_64__) || defined(_M_X64)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
#elif defined(__amd64) || defined(__amd64__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
/* Intel Architecture-64 (Itanium) */
#elif defined(__ia64) || defined(__ia64__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
#elif defined(_IA64) || defined(__IA64__) || defined(_M_IA64)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
/* PowerPC */
#elif defined(__powerpc) || defined(__powerpc__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
#elif defined(__ppc) || defined(__ppc__) || defined(__POWERPC__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* SPARC */
#elif defined(__sparc) || defined(__sparc__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* HP/PA RISC */
#elif defined(__hppa) || defined(__hppa__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* Motorola 68k */
#elif defined(__m68k__) || defined(M68000)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* MIPS */
#elif defined(__mips) || defined(__mips__) || defined(__MIPS__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* RS/6000 */
#elif defined(__THW_RS600) || defined(_IBMR2) || defined(_POWER)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
#elif defined(_ARCH_PWR) || defined(_ARCH_PWR2)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* System/370 */
#elif defined(__370__) || defined(__THW_370__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* System/390 */
#elif defined(__s390__) || defined(__s390x__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* z/Architecture */
#elif defined(__SYSC_ZARCH__)
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
/* Unknown CPU */
#else
# define @KWSYS_NAMESPACE@_CPU_ENDIAN_ID 0
# if !defined(@KWSYS_NAMESPACE@_CPU_UNKNOWN_OKAY)
# error "The target CPU architecture is not known."
# endif
#endif
/* If building a C or C++ file in kwsys itself, give the source file
access to the macros without a configured namespace. */
#if defined(KWSYS_NAMESPACE)
# define KWSYS_CPU_ENDIAN_ID @KWSYS_NAMESPACE@_CPU_ENDIAN_ID
# define KWSYS_CPU_ENDIAN_ID_BIG @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_BIG
# define KWSYS_CPU_ENDIAN_ID_LITTLE @KWSYS_NAMESPACE@_CPU_ENDIAN_ID_LITTLE
#endif
#endif

18
CTestConfig.cmake Normal file
View File

@ -0,0 +1,18 @@
#=============================================================================
# KWSys - Kitware System Library
# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
set (CTEST_PROJECT_NAME "kwsys")
set (CTEST_NIGHTLY_START_TIME "21:00:00 EDT")
set (CTEST_DART_SERVER_VERSION "2")
set(CTEST_DROP_METHOD "http")
set(CTEST_DROP_SITE "www.cdash.org")
set(CTEST_DROP_LOCATION "/CDash/submit.php?project=PublicDashboard")
set(CTEST_DROP_SITE_CDASH TRUE)

859
CommandLineArguments.cxx Normal file
View File

@ -0,0 +1,859 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(CommandLineArguments.hxx)
#include KWSYS_HEADER(Configure.hxx)
#include KWSYS_HEADER(String.hxx)
#include KWSYS_HEADER(stl/vector)
#include KWSYS_HEADER(stl/map)
#include KWSYS_HEADER(stl/set)
#include KWSYS_HEADER(ios/sstream)
#include KWSYS_HEADER(ios/iostream)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "CommandLineArguments.hxx.in"
# include "Configure.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_ios_sstream.h.in"
# include "kwsys_ios_iostream.h.in"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _MSC_VER
# pragma warning (disable: 4786)
#endif
#if defined(__sgi) && !defined(__GNUC__)
# pragma set woff 1375 /* base class destructor not virtual */
#endif
#if 0
# define CommandLineArguments_DEBUG(x) \
kwsys_ios::cout << __LINE__ << " CLA: " << x << kwsys_ios::endl
#else
# define CommandLineArguments_DEBUG(x)
#endif
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
//============================================================================
struct CommandLineArgumentsCallbackStructure
{
const char* Argument;
int ArgumentType;
CommandLineArguments::CallbackType Callback;
void* CallData;
void* Variable;
int VariableType;
const char* Help;
};
class CommandLineArgumentsVectorOfStrings :
public kwsys_stl::vector<kwsys::String> {};
class CommandLineArgumentsSetOfStrings :
public kwsys_stl::set<kwsys::String> {};
class CommandLineArgumentsMapOfStrucs :
public kwsys_stl::map<kwsys::String,
CommandLineArgumentsCallbackStructure> {};
class CommandLineArgumentsInternal
{
public:
CommandLineArgumentsInternal()
{
this->UnknownArgumentCallback = 0;
this->ClientData = 0;
this->LastArgument = 0;
}
typedef CommandLineArgumentsVectorOfStrings VectorOfStrings;
typedef CommandLineArgumentsMapOfStrucs CallbacksMap;
typedef kwsys::String String;
typedef CommandLineArgumentsSetOfStrings SetOfStrings;
VectorOfStrings Argv;
String Argv0;
CallbacksMap Callbacks;
CommandLineArguments::ErrorCallbackType UnknownArgumentCallback;
void* ClientData;
VectorOfStrings::size_type LastArgument;
VectorOfStrings UnusedArguments;
};
//============================================================================
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
CommandLineArguments::CommandLineArguments()
{
this->Internals = new CommandLineArguments::Internal;
this->Help = "";
this->LineLength = 80;
this->StoreUnusedArgumentsFlag = false;
}
//----------------------------------------------------------------------------
CommandLineArguments::~CommandLineArguments()
{
delete this->Internals;
}
//----------------------------------------------------------------------------
void CommandLineArguments::Initialize(int argc, const char* const argv[])
{
int cc;
this->Initialize();
this->Internals->Argv0 = argv[0];
for ( cc = 1; cc < argc; cc ++ )
{
this->ProcessArgument(argv[cc]);
}
}
//----------------------------------------------------------------------------
void CommandLineArguments::Initialize(int argc, char* argv[])
{
this->Initialize(argc, static_cast<const char* const*>(argv));
}
//----------------------------------------------------------------------------
void CommandLineArguments::Initialize()
{
this->Internals->Argv.clear();
this->Internals->LastArgument = 0;
}
//----------------------------------------------------------------------------
void CommandLineArguments::ProcessArgument(const char* arg)
{
this->Internals->Argv.push_back(arg);
}
//----------------------------------------------------------------------------
bool CommandLineArguments::GetMatchedArguments(
kwsys_stl::vector<kwsys_stl::string>* matches,
const kwsys_stl::string& arg)
{
matches->clear();
CommandLineArguments::Internal::CallbacksMap::iterator it;
// Does the argument match to any we know about?
for ( it = this->Internals->Callbacks.begin();
it != this->Internals->Callbacks.end();
it ++ )
{
const CommandLineArguments::Internal::String& parg = it->first;
CommandLineArgumentsCallbackStructure *cs = &it->second;
if (cs->ArgumentType == CommandLineArguments::NO_ARGUMENT ||
cs->ArgumentType == CommandLineArguments::SPACE_ARGUMENT)
{
if ( arg == parg )
{
matches->push_back(parg);
}
}
else if ( arg.find( parg ) == 0 )
{
matches->push_back(parg);
}
}
return matches->size() > 0;
}
//----------------------------------------------------------------------------
int CommandLineArguments::Parse()
{
kwsys_stl::vector<kwsys_stl::string>::size_type cc;
kwsys_stl::vector<kwsys_stl::string> matches;
if ( this->StoreUnusedArgumentsFlag )
{
this->Internals->UnusedArguments.clear();
}
for ( cc = 0; cc < this->Internals->Argv.size(); cc ++ )
{
const kwsys_stl::string& arg = this->Internals->Argv[cc];
CommandLineArguments_DEBUG("Process argument: " << arg);
this->Internals->LastArgument = cc;
if ( this->GetMatchedArguments(&matches, arg) )
{
// Ok, we found one or more arguments that match what user specified.
// Let's find the longest one.
CommandLineArguments::Internal::VectorOfStrings::size_type kk;
CommandLineArguments::Internal::VectorOfStrings::size_type maxidx = 0;
CommandLineArguments::Internal::String::size_type maxlen = 0;
for ( kk = 0; kk < matches.size(); kk ++ )
{
if ( matches[kk].size() > maxlen )
{
maxlen = matches[kk].size();
maxidx = kk;
}
}
// So, the longest one is probably the right one. Now see if it has any
// additional value
CommandLineArgumentsCallbackStructure *cs
= &this->Internals->Callbacks[matches[maxidx]];
const kwsys_stl::string& sarg = matches[maxidx];
if ( cs->Argument != sarg )
{
abort();
}
switch ( cs->ArgumentType )
{
case NO_ARGUMENT:
// No value
if ( !this->PopulateVariable(cs, 0) )
{
return 0;
}
break;
case SPACE_ARGUMENT:
if ( cc == this->Internals->Argv.size()-1 )
{
this->Internals->LastArgument --;
return 0;
}
CommandLineArguments_DEBUG("This is a space argument: " << arg
<< " value: " << this->Internals->Argv[cc+1].c_str());
// Value is the next argument
if ( !this->PopulateVariable(cs, this->Internals->Argv[cc+1].c_str()) )
{
return 0;
}
cc ++;
break;
case EQUAL_ARGUMENT:
if ( arg.size() == sarg.size() || *(arg.c_str() + sarg.size()) != '=' )
{
this->Internals->LastArgument --;
return 0;
}
// Value is everythng followed the '=' sign
if ( !this->PopulateVariable(cs, arg.c_str() + sarg.size() + 1) )
{
return 0;
}
break;
case CONCAT_ARGUMENT:
// Value is whatever follows the argument
if ( !this->PopulateVariable(cs, arg.c_str() + sarg.size()) )
{
return 0;
}
break;
case MULTI_ARGUMENT:
// Suck in all the rest of the arguments
CommandLineArguments_DEBUG("This is a multi argument: " << arg);
for (cc++; cc < this->Internals->Argv.size(); ++ cc )
{
const kwsys_stl::string& marg = this->Internals->Argv[cc];
CommandLineArguments_DEBUG(" check multi argument value: " << marg);
if ( this->GetMatchedArguments(&matches, marg) )
{
CommandLineArguments_DEBUG("End of multi argument " << arg << " with value: " << marg);
break;
}
CommandLineArguments_DEBUG(" populate multi argument value: " << marg);
if ( !this->PopulateVariable(cs, marg.c_str()) )
{
return 0;
}
}
if ( cc != this->Internals->Argv.size() )
{
CommandLineArguments_DEBUG("Again End of multi argument " << arg);
cc--;
continue;
}
break;
default:
kwsys_ios::cerr << "Got unknown argument type: \"" << cs->ArgumentType << "\"" << kwsys_ios::endl;
this->Internals->LastArgument --;
return 0;
}
}
else
{
// Handle unknown arguments
if ( this->Internals->UnknownArgumentCallback )
{
if ( !this->Internals->UnknownArgumentCallback(arg.c_str(),
this->Internals->ClientData) )
{
this->Internals->LastArgument --;
return 0;
}
return 1;
}
else if ( this->StoreUnusedArgumentsFlag )
{
CommandLineArguments_DEBUG("Store unused argument " << arg);
this->Internals->UnusedArguments.push_back(arg.c_str());
}
else
{
kwsys_ios::cerr << "Got unknown argument: \"" << arg.c_str() << "\"" << kwsys_ios::endl;
this->Internals->LastArgument --;
return 0;
}
}
}
return 1;
}
//----------------------------------------------------------------------------
void CommandLineArguments::GetRemainingArguments(int* argc, char*** argv)
{
CommandLineArguments::Internal::VectorOfStrings::size_type size
= this->Internals->Argv.size() - this->Internals->LastArgument + 1;
CommandLineArguments::Internal::VectorOfStrings::size_type cc;
// Copy Argv0 as the first argument
char** args = new char*[ size ];
args[0] = new char[ this->Internals->Argv0.size() + 1 ];
strcpy(args[0], this->Internals->Argv0.c_str());
int cnt = 1;
// Copy everything after the LastArgument, since that was not parsed.
for ( cc = this->Internals->LastArgument+1;
cc < this->Internals->Argv.size(); cc ++ )
{
args[cnt] = new char[ this->Internals->Argv[cc].size() + 1];
strcpy(args[cnt], this->Internals->Argv[cc].c_str());
cnt ++;
}
*argc = cnt;
*argv = args;
}
//----------------------------------------------------------------------------
void CommandLineArguments::GetUnusedArguments(int* argc, char*** argv)
{
CommandLineArguments::Internal::VectorOfStrings::size_type size
= this->Internals->UnusedArguments.size() + 1;
CommandLineArguments::Internal::VectorOfStrings::size_type cc;
// Copy Argv0 as the first argument
char** args = new char*[ size ];
args[0] = new char[ this->Internals->Argv0.size() + 1 ];
strcpy(args[0], this->Internals->Argv0.c_str());
int cnt = 1;
// Copy everything after the LastArgument, since that was not parsed.
for ( cc = 0;
cc < this->Internals->UnusedArguments.size(); cc ++ )
{
kwsys::String &str = this->Internals->UnusedArguments[cc];
args[cnt] = new char[ str.size() + 1];
strcpy(args[cnt], str.c_str());
cnt ++;
}
*argc = cnt;
*argv = args;
}
//----------------------------------------------------------------------------
void CommandLineArguments::DeleteRemainingArguments(int argc, char*** argv)
{
int cc;
for ( cc = 0; cc < argc; ++ cc )
{
delete [] (*argv)[cc];
}
delete [] *argv;
}
//----------------------------------------------------------------------------
void CommandLineArguments::AddCallback(const char* argument, ArgumentTypeEnum type,
CallbackType callback, void* call_data, const char* help)
{
CommandLineArgumentsCallbackStructure s;
s.Argument = argument;
s.ArgumentType = type;
s.Callback = callback;
s.CallData = call_data;
s.VariableType = CommandLineArguments::NO_VARIABLE_TYPE;
s.Variable = 0;
s.Help = help;
this->Internals->Callbacks[argument] = s;
this->GenerateHelp();
}
//----------------------------------------------------------------------------
void CommandLineArguments::AddArgument(const char* argument, ArgumentTypeEnum type,
VariableTypeEnum vtype, void* variable, const char* help)
{
CommandLineArgumentsCallbackStructure s;
s.Argument = argument;
s.ArgumentType = type;
s.Callback = 0;
s.CallData = 0;
s.VariableType = vtype;
s.Variable = variable;
s.Help = help;
this->Internals->Callbacks[argument] = s;
this->GenerateHelp();
}
//----------------------------------------------------------------------------
#define CommandLineArgumentsAddArgumentMacro(type, ctype) \
void CommandLineArguments::AddArgument(const char* argument, ArgumentTypeEnum type, \
ctype* variable, const char* help) \
{ \
this->AddArgument(argument, type, CommandLineArguments::type##_TYPE, variable, help); \
}
CommandLineArgumentsAddArgumentMacro(BOOL, bool)
CommandLineArgumentsAddArgumentMacro(INT, int)
CommandLineArgumentsAddArgumentMacro(DOUBLE, double)
CommandLineArgumentsAddArgumentMacro(STRING, char*)
CommandLineArgumentsAddArgumentMacro(STL_STRING, kwsys_stl::string)
CommandLineArgumentsAddArgumentMacro(VECTOR_BOOL, kwsys_stl::vector<bool>)
CommandLineArgumentsAddArgumentMacro(VECTOR_INT, kwsys_stl::vector<int>)
CommandLineArgumentsAddArgumentMacro(VECTOR_DOUBLE, kwsys_stl::vector<double>)
CommandLineArgumentsAddArgumentMacro(VECTOR_STRING, kwsys_stl::vector<char*>)
CommandLineArgumentsAddArgumentMacro(VECTOR_STL_STRING, kwsys_stl::vector<kwsys_stl::string>)
//----------------------------------------------------------------------------
#define CommandLineArgumentsAddBooleanArgumentMacro(type, ctype) \
void CommandLineArguments::AddBooleanArgument(const char* argument, \
ctype* variable, const char* help) \
{ \
this->AddArgument(argument, CommandLineArguments::NO_ARGUMENT, \
CommandLineArguments::type##_TYPE, variable, help); \
}
CommandLineArgumentsAddBooleanArgumentMacro(BOOL, bool)
CommandLineArgumentsAddBooleanArgumentMacro(INT, int)
CommandLineArgumentsAddBooleanArgumentMacro(DOUBLE, double)
CommandLineArgumentsAddBooleanArgumentMacro(STRING, char*)
CommandLineArgumentsAddBooleanArgumentMacro(STL_STRING, kwsys_stl::string)
//----------------------------------------------------------------------------
void CommandLineArguments::SetClientData(void* client_data)
{
this->Internals->ClientData = client_data;
}
//----------------------------------------------------------------------------
void CommandLineArguments::SetUnknownArgumentCallback(
CommandLineArguments::ErrorCallbackType callback)
{
this->Internals->UnknownArgumentCallback = callback;
}
//----------------------------------------------------------------------------
const char* CommandLineArguments::GetHelp(const char* arg)
{
CommandLineArguments::Internal::CallbacksMap::iterator it
= this->Internals->Callbacks.find(arg);
if ( it == this->Internals->Callbacks.end() )
{
return 0;
}
// Since several arguments may point to the same argument, find the one this
// one point to if this one is pointing to another argument.
CommandLineArgumentsCallbackStructure *cs = &(it->second);
for(;;)
{
CommandLineArguments::Internal::CallbacksMap::iterator hit
= this->Internals->Callbacks.find(cs->Help);
if ( hit == this->Internals->Callbacks.end() )
{
break;
}
cs = &(hit->second);
}
return cs->Help;
}
//----------------------------------------------------------------------------
void CommandLineArguments::SetLineLength(unsigned int ll)
{
if ( ll < 9 || ll > 1000 )
{
return;
}
this->LineLength = ll;
this->GenerateHelp();
}
//----------------------------------------------------------------------------
const char* CommandLineArguments::GetArgv0()
{
return this->Internals->Argv0.c_str();
}
//----------------------------------------------------------------------------
unsigned int CommandLineArguments::GetLastArgument()
{
return static_cast<unsigned int>(this->Internals->LastArgument + 1);
}
//----------------------------------------------------------------------------
void CommandLineArguments::GenerateHelp()
{
kwsys_ios::ostringstream str;
// Collapse all arguments into the map of vectors of all arguments that do
// the same thing.
CommandLineArguments::Internal::CallbacksMap::iterator it;
typedef kwsys_stl::map<CommandLineArguments::Internal::String,
CommandLineArguments::Internal::SetOfStrings > MapArgs;
MapArgs mp;
MapArgs::iterator mpit, smpit;
for ( it = this->Internals->Callbacks.begin();
it != this->Internals->Callbacks.end();
it ++ )
{
CommandLineArgumentsCallbackStructure *cs = &(it->second);
mpit = mp.find(cs->Help);
if ( mpit != mp.end() )
{
mpit->second.insert(it->first);
mp[it->first].insert(it->first);
}
else
{
mp[it->first].insert(it->first);
}
}
for ( it = this->Internals->Callbacks.begin();
it != this->Internals->Callbacks.end();
it ++ )
{
CommandLineArgumentsCallbackStructure *cs = &(it->second);
mpit = mp.find(cs->Help);
if ( mpit != mp.end() )
{
mpit->second.insert(it->first);
smpit = mp.find(it->first);
CommandLineArguments::Internal::SetOfStrings::iterator sit;
for ( sit = smpit->second.begin(); sit != smpit->second.end(); sit++ )
{
mpit->second.insert(*sit);
}
mp.erase(smpit);
}
else
{
mp[it->first].insert(it->first);
}
}
// Find the length of the longest string
CommandLineArguments::Internal::String::size_type maxlen = 0;
for ( mpit = mp.begin();
mpit != mp.end();
mpit ++ )
{
CommandLineArguments::Internal::SetOfStrings::iterator sit;
for ( sit = mpit->second.begin(); sit != mpit->second.end(); sit++ )
{
CommandLineArguments::Internal::String::size_type clen = sit->size();
switch ( this->Internals->Callbacks[*sit].ArgumentType )
{
case CommandLineArguments::NO_ARGUMENT: clen += 0; break;
case CommandLineArguments::CONCAT_ARGUMENT: clen += 3; break;
case CommandLineArguments::SPACE_ARGUMENT: clen += 4; break;
case CommandLineArguments::EQUAL_ARGUMENT: clen += 4; break;
}
if ( clen > maxlen )
{
maxlen = clen;
}
}
}
// Create format for that string
char format[80];
sprintf(format, " %%-%us ", static_cast<unsigned int>(maxlen));
maxlen += 4; // For the space before and after the option
// Print help for each option
for ( mpit = mp.begin();
mpit != mp.end();
mpit ++ )
{
CommandLineArguments::Internal::SetOfStrings::iterator sit;
for ( sit = mpit->second.begin(); sit != mpit->second.end(); sit++ )
{
str << kwsys_ios::endl;
char argument[100];
sprintf(argument, "%s", sit->c_str());
switch ( this->Internals->Callbacks[*sit].ArgumentType )
{
case CommandLineArguments::NO_ARGUMENT: break;
case CommandLineArguments::CONCAT_ARGUMENT: strcat(argument, "opt"); break;
case CommandLineArguments::SPACE_ARGUMENT: strcat(argument, " opt"); break;
case CommandLineArguments::EQUAL_ARGUMENT: strcat(argument, "=opt"); break;
case CommandLineArguments::MULTI_ARGUMENT: strcat(argument, " opt opt ..."); break;
}
char buffer[80];
sprintf(buffer, format, argument);
str << buffer;
}
const char* ptr = this->Internals->Callbacks[mpit->first].Help;
size_t len = strlen(ptr);
int cnt = 0;
while ( len > 0)
{
// If argument with help is longer than line length, split it on previous
// space (or tab) and continue on the next line
CommandLineArguments::Internal::String::size_type cc;
for ( cc = 0; ptr[cc]; cc ++ )
{
if ( *ptr == ' ' || *ptr == '\t' )
{
ptr ++;
len --;
}
}
if ( cnt > 0 )
{
for ( cc = 0; cc < maxlen; cc ++ )
{
str << " ";
}
}
CommandLineArguments::Internal::String::size_type skip = len;
if ( skip > this->LineLength - maxlen )
{
skip = this->LineLength - maxlen;
for ( cc = skip-1; cc > 0; cc -- )
{
if ( ptr[cc] == ' ' || ptr[cc] == '\t' )
{
break;
}
}
if ( cc != 0 )
{
skip = cc;
}
}
str.write(ptr, static_cast<kwsys_ios::streamsize>(skip));
str << kwsys_ios::endl;
ptr += skip;
len -= skip;
cnt ++;
}
}
/*
// This can help debugging help string
str << endl;
unsigned int cc;
for ( cc = 0; cc < this->LineLength; cc ++ )
{
str << cc % 10;
}
str << endl;
*/
this->Help = str.str();
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
bool* variable, const kwsys_stl::string& value)
{
if ( value == "1" || value == "ON" || value == "on" || value == "On" ||
value == "TRUE" || value == "true" || value == "True" ||
value == "yes" || value == "Yes" || value == "YES" )
{
*variable = true;
}
else
{
*variable = false;
}
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
int* variable, const kwsys_stl::string& value)
{
char* res = 0;
*variable = static_cast<int>(strtol(value.c_str(), &res, 10));
//if ( res && *res )
// {
// Can handle non-int
// }
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
double* variable, const kwsys_stl::string& value)
{
char* res = 0;
*variable = strtod(value.c_str(), &res);
//if ( res && *res )
// {
// Can handle non-double
// }
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
char** variable, const kwsys_stl::string& value)
{
if ( *variable )
{
delete [] *variable;
*variable = 0;
}
*variable = new char[ value.size() + 1 ];
strcpy(*variable, value.c_str());
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
kwsys_stl::string* variable, const kwsys_stl::string& value)
{
*variable = value;
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
kwsys_stl::vector<bool>* variable, const kwsys_stl::string& value)
{
bool val = false;
if ( value == "1" || value == "ON" || value == "on" || value == "On" ||
value == "TRUE" || value == "true" || value == "True" ||
value == "yes" || value == "Yes" || value == "YES" )
{
val = true;
}
variable->push_back(val);
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
kwsys_stl::vector<int>* variable, const kwsys_stl::string& value)
{
char* res = 0;
variable->push_back(static_cast<int>(strtol(value.c_str(), &res, 10)));
//if ( res && *res )
// {
// Can handle non-int
// }
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
kwsys_stl::vector<double>* variable, const kwsys_stl::string& value)
{
char* res = 0;
variable->push_back(strtod(value.c_str(), &res));
//if ( res && *res )
// {
// Can handle non-int
// }
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
kwsys_stl::vector<char*>* variable, const kwsys_stl::string& value)
{
char* var = new char[ value.size() + 1 ];
strcpy(var, value.c_str());
variable->push_back(var);
}
//----------------------------------------------------------------------------
void CommandLineArguments::PopulateVariable(
kwsys_stl::vector<kwsys_stl::string>* variable,
const kwsys_stl::string& value)
{
variable->push_back(value);
}
//----------------------------------------------------------------------------
bool CommandLineArguments::PopulateVariable(CommandLineArgumentsCallbackStructure* cs,
const char* value)
{
// Call the callback
if ( cs->Callback )
{
if ( !cs->Callback(cs->Argument, value, cs->CallData) )
{
this->Internals->LastArgument --;
return 0;
}
}
CommandLineArguments_DEBUG("Set argument: " << cs->Argument << " to " << value);
if ( cs->Variable )
{
kwsys_stl::string var = "1";
if ( value )
{
var = value;
}
switch ( cs->VariableType )
{
case CommandLineArguments::INT_TYPE:
this->PopulateVariable(static_cast<int*>(cs->Variable), var);
break;
case CommandLineArguments::DOUBLE_TYPE:
this->PopulateVariable(static_cast<double*>(cs->Variable), var);
break;
case CommandLineArguments::STRING_TYPE:
this->PopulateVariable(static_cast<char**>(cs->Variable), var);
break;
case CommandLineArguments::STL_STRING_TYPE:
this->PopulateVariable(static_cast<kwsys_stl::string*>(cs->Variable), var);
break;
case CommandLineArguments::BOOL_TYPE:
this->PopulateVariable(static_cast<bool*>(cs->Variable), var);
break;
case CommandLineArguments::VECTOR_BOOL_TYPE:
this->PopulateVariable(static_cast<kwsys_stl::vector<bool>*>(cs->Variable), var);
break;
case CommandLineArguments::VECTOR_INT_TYPE:
this->PopulateVariable(static_cast<kwsys_stl::vector<int>*>(cs->Variable), var);
break;
case CommandLineArguments::VECTOR_DOUBLE_TYPE:
this->PopulateVariable(static_cast<kwsys_stl::vector<double>*>(cs->Variable), var);
break;
case CommandLineArguments::VECTOR_STRING_TYPE:
this->PopulateVariable(static_cast<kwsys_stl::vector<char*>*>(cs->Variable), var);
break;
case CommandLineArguments::VECTOR_STL_STRING_TYPE:
this->PopulateVariable(static_cast<kwsys_stl::vector<kwsys_stl::string>*>(cs->Variable), var);
break;
default:
kwsys_ios::cerr << "Got unknown variable type: \"" << cs->VariableType << "\"" << kwsys_ios::endl;
this->Internals->LastArgument --;
return 0;
}
}
return 1;
}
} // namespace KWSYS_NAMESPACE

286
CommandLineArguments.hxx.in Normal file
View File

@ -0,0 +1,286 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_CommandLineArguments_hxx
#define @KWSYS_NAMESPACE@_CommandLineArguments_hxx
#include <@KWSYS_NAMESPACE@/Configure.h>
#include <@KWSYS_NAMESPACE@/Configure.hxx>
#include <@KWSYS_NAMESPACE@/stl/string>
#include <@KWSYS_NAMESPACE@/stl/vector>
/* Define this macro temporarily to keep the code readable. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsys_stl @KWSYS_NAMESPACE@_stl
#endif
namespace @KWSYS_NAMESPACE@
{
class CommandLineArgumentsInternal;
struct CommandLineArgumentsCallbackStructure;
/** \class CommandLineArguments
* \brief Command line arguments processing code.
*
* Find specified arguments with optional options and execute specified methods
* or set given variables.
*
* The two interfaces it knows are callback based and variable based. For
* callback based, you have to register callback for particular argument using
* AddCallback method. When that argument is passed, the callback will be
* called with argument, value, and call data. For boolean (NO_ARGUMENT)
* arguments, the value is "1". If the callback returns 0 the argument parsing
* will stop with an error.
*
* For the variable interface you associate variable with each argument. When
* the argument is specified, the variable is set to the specified value casted
* to the apropriate type. For boolean (NO_ARGUMENT), the value is "1".
*
* Both interfaces can be used at the same time.
*
* Possible argument types are:
* NO_ARGUMENT - The argument takes no value : --A
* CONCAT_ARGUMENT - The argument takes value after no space : --Aval
* SPACE_ARGUMENT - The argument takes value after space : --A val
* EQUAL_ARGUMENT - The argument takes value after equal : --A=val
* MULTI_ARGUMENT - The argument takes values after space : --A val1 val2 val3 ...
*
* Example use:
*
* kwsys::CommandLineArguments arg;
* arg.Initialize(argc, argv);
* typedef kwsys::CommandLineArguments argT;
* arg.AddArgument("--something", argT::EQUAL_ARGUMENT, &some_variable,
* "This is help string for --something");
* if ( !arg.Parse() )
* {
* kwsys_ios::cerr << "Problem parsing arguments" << kwsys_ios::endl;
* res = 1;
* }
*
*/
class @KWSYS_NAMESPACE@_EXPORT CommandLineArguments
{
public:
CommandLineArguments();
~CommandLineArguments();
/**
* Various argument types.
*/
enum ArgumentTypeEnum {
NO_ARGUMENT,
CONCAT_ARGUMENT,
SPACE_ARGUMENT,
EQUAL_ARGUMENT,
MULTI_ARGUMENT
};
/**
* Various variable types. When using the variable interface, this specifies
* what type the variable is.
*/
enum VariableTypeEnum {
NO_VARIABLE_TYPE = 0, // The variable is not specified
INT_TYPE, // The variable is integer (int)
BOOL_TYPE, // The variable is boolean (bool)
DOUBLE_TYPE, // The variable is float (double)
STRING_TYPE, // The variable is string (char*)
STL_STRING_TYPE, // The variable is string (char*)
VECTOR_INT_TYPE, // The variable is integer (int)
VECTOR_BOOL_TYPE, // The vairable is boolean (bool)
VECTOR_DOUBLE_TYPE, // The variable is float (double)
VECTOR_STRING_TYPE, // The variable is string (char*)
VECTOR_STL_STRING_TYPE, // The variable is string (char*)
LAST_VARIABLE_TYPE
};
/**
* Prototypes for callbacks for callback interface.
*/
typedef int(*CallbackType)(const char* argument, const char* value,
void* call_data);
typedef int(*ErrorCallbackType)(const char* argument, void* client_data);
/**
* Initialize internal data structures. This should be called before parsing.
*/
void Initialize(int argc, const char* const argv[]);
void Initialize(int argc, char* argv[]);
/**
* Initialize internal data structure and pass arguments one by one. This is
* convenience method for use from scripting languages where argc and argv
* are not available.
*/
void Initialize();
void ProcessArgument(const char* arg);
/**
* This method will parse arguments and call apropriate methods.
*/
int Parse();
/**
* This method will add a callback for a specific argument. The arguments to
* it are argument, argument type, callback method, and call data. The
* argument help specifies the help string used with this option. The
* callback and call_data can be skipped.
*/
void AddCallback(const char* argument, ArgumentTypeEnum type,
CallbackType callback, void* call_data, const char* help);
/**
* Add handler for argument which is going to set the variable to the
* specified value. If the argument is specified, the option is casted to the
* apropriate type.
*/
void AddArgument(const char* argument, ArgumentTypeEnum type,
bool* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
int* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
double* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
char** variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
kwsys_stl::string* variable, const char* help);
/**
* Add handler for argument which is going to set the variable to the
* specified value. If the argument is specified, the option is casted to the
* apropriate type. This will handle the multi argument values.
*/
void AddArgument(const char* argument, ArgumentTypeEnum type,
kwsys_stl::vector<bool>* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
kwsys_stl::vector<int>* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
kwsys_stl::vector<double>* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
kwsys_stl::vector<char*>* variable, const char* help);
void AddArgument(const char* argument, ArgumentTypeEnum type,
kwsys_stl::vector<kwsys_stl::string>* variable, const char* help);
/**
* Add handler for boolean argument. The argument does not take any option
* and if it is specified, the value of the variable is true/1, otherwise it
* is false/0.
*/
void AddBooleanArgument(const char* argument,
bool* variable, const char* help);
void AddBooleanArgument(const char* argument,
int* variable, const char* help);
void AddBooleanArgument(const char* argument,
double* variable, const char* help);
void AddBooleanArgument(const char* argument,
char** variable, const char* help);
void AddBooleanArgument(const char* argument,
kwsys_stl::string* variable, const char* help);
/**
* Set the callbacks for error handling.
*/
void SetClientData(void* client_data);
void SetUnknownArgumentCallback(ErrorCallbackType callback);
/**
* Get remaining arguments. It allocates space for argv, so you have to call
* delete[] on it.
*/
void GetRemainingArguments(int* argc, char*** argv);
void DeleteRemainingArguments(int argc, char*** argv);
/**
* If StoreUnusedArguments is set to true, then all unknown arguments will be
* stored and the user can access the modified argc, argv without known
* arguments.
*/
void StoreUnusedArguments(bool val) { this->StoreUnusedArgumentsFlag = val; }
void GetUnusedArguments(int* argc, char*** argv);
/**
* Return string containing help. If the argument is specified, only return
* help for that argument.
*/
const char* GetHelp() { return this->Help.c_str(); }
const char* GetHelp(const char* arg);
/**
* Get / Set the help line length. This length is used when generating the
* help page. Default length is 80.
*/
void SetLineLength(unsigned int);
unsigned int GetLineLength();
/**
* Get the executable name (argv0). This is only available when using
* Initialize with argc/argv.
*/
const char* GetArgv0();
/**
* Get index of the last argument parsed. This is the last argument that was
* parsed ok in the original argc/argv list.
*/
unsigned int GetLastArgument();
protected:
void GenerateHelp();
//! This is internal method that registers variable with argument
void AddArgument(const char* argument, ArgumentTypeEnum type,
VariableTypeEnum vtype, void* variable, const char* help);
bool GetMatchedArguments(kwsys_stl::vector<kwsys_stl::string>* matches,
const kwsys_stl::string& arg);
//! Populate individual variables
bool PopulateVariable(CommandLineArgumentsCallbackStructure* cs,
const char* value);
//! Populate individual variables of type ...
void PopulateVariable(bool* variable, const kwsys_stl::string& value);
void PopulateVariable(int* variable, const kwsys_stl::string& value);
void PopulateVariable(double* variable, const kwsys_stl::string& value);
void PopulateVariable(char** variable, const kwsys_stl::string& value);
void PopulateVariable(kwsys_stl::string* variable, const kwsys_stl::string& value);
void PopulateVariable(kwsys_stl::vector<bool>* variable, const kwsys_stl::string& value);
void PopulateVariable(kwsys_stl::vector<int>* variable, const kwsys_stl::string& value);
void PopulateVariable(kwsys_stl::vector<double>* variable, const kwsys_stl::string& value);
void PopulateVariable(kwsys_stl::vector<char*>* variable, const kwsys_stl::string& value);
void PopulateVariable(kwsys_stl::vector<kwsys_stl::string>* variable, const kwsys_stl::string& value);
typedef CommandLineArgumentsInternal Internal;
Internal* Internals;
kwsys_stl::string Help;
unsigned int LineLength;
bool StoreUnusedArgumentsFlag;
};
} // namespace @KWSYS_NAMESPACE@
/* Undefine temporary macro. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsys_stl
#endif
#endif

145
Configure.h.in Normal file
View File

@ -0,0 +1,145 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_Configure_h
#define @KWSYS_NAMESPACE@_Configure_h
/* If we are building a kwsys .c or .cxx file, let it use the kwsys
namespace. When not building a kwsys source file these macros are
temporarily defined inside the headers that use them. */
#if defined(KWSYS_NAMESPACE)
# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
/* Disable some warnings inside kwsys source files. */
#if defined(KWSYS_NAMESPACE)
# if defined(__BORLANDC__)
# pragma warn -8027 /* function not inlined. */
# endif
# if defined(__INTEL_COMPILER)
# pragma warning (disable: 1572) /* floating-point equality test */
# endif
# if defined(__sgi) && !defined(__GNUC__)
# pragma set woff 3970 /* pointer to int conversion */
# pragma set woff 3968 /* 64 bit conversion */
# endif
#endif
/* Whether kwsys namespace is "kwsys". */
#define @KWSYS_NAMESPACE@_NAME_IS_KWSYS @KWSYS_NAME_IS_KWSYS@
/* If we are building a kwsys .c or .cxx file, suppress the Microsoft
deprecation warnings. */
#if defined(KWSYS_NAMESPACE)
# ifndef _CRT_NONSTDC_NO_DEPRECATE
# define _CRT_NONSTDC_NO_DEPRECATE
# endif
# ifndef _CRT_SECURE_NO_DEPRECATE
# define _CRT_SECURE_NO_DEPRECATE
# endif
# ifndef _SCL_SECURE_NO_DEPRECATE
# define _SCL_SECURE_NO_DEPRECATE
# endif
#endif
/* Whether Large File Support is requested. */
#define @KWSYS_NAMESPACE@_LFS_REQUESTED @KWSYS_LFS_REQUESTED@
/* Whether Large File Support is available. */
#if @KWSYS_NAMESPACE@_LFS_REQUESTED
# define @KWSYS_NAMESPACE@_LFS_AVAILABLE @KWSYS_LFS_AVAILABLE@
#endif
/* Setup Large File Support if requested. */
#if @KWSYS_NAMESPACE@_LFS_REQUESTED
/* Since LFS is requested this header must be included before system
headers whether or not LFS is available. */
# if 0 && (defined(_SYS_TYPES_H) || defined(_SYS_TYPES_INCLUDED))
# error "@KWSYS_NAMESPACE@/Configure.h must be included before sys/types.h"
# endif
/* Enable the large file API if it is available. */
# if @KWSYS_NAMESPACE@_LFS_AVAILABLE && \
!defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINES)
# if !defined(_LARGEFILE_SOURCE) && \
!defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGEFILE_SOURCE)
# define _LARGEFILE_SOURCE
# endif
# if !defined(_LARGEFILE64_SOURCE) && \
!defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGEFILE64_SOURCE)
# define _LARGEFILE64_SOURCE
# endif
# if !defined(_LARGE_FILES) && \
!defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_LARGE_FILES)
# define _LARGE_FILES
# endif
# if !defined(_FILE_OFFSET_BITS) && \
!defined(@KWSYS_NAMESPACE@_LFS_NO_DEFINE_FILE_OFFSET_BITS)
# define _FILE_OFFSET_BITS 64
# endif
# if 0 && (defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS < 64)
# error "_FILE_OFFSET_BITS must be defined to at least 64"
# endif
# endif
#endif
/* Setup the export macro. */
#if @KWSYS_BUILD_SHARED@
# if defined(_WIN32) || defined(__CYGWIN__)
# if defined(@KWSYS_NAMESPACE@_EXPORTS)
# define @KWSYS_NAMESPACE@_EXPORT __declspec(dllexport)
# else
# define @KWSYS_NAMESPACE@_EXPORT __declspec(dllimport)
# endif
# elif __GNUC__ >= 4
# define @KWSYS_NAMESPACE@_EXPORT __attribute__ ((visibility("default")))
# else
# define @KWSYS_NAMESPACE@_EXPORT
# endif
#else
# define @KWSYS_NAMESPACE@_EXPORT
#endif
/* Enable warnings that are off by default but are useful. */
#if !defined(@KWSYS_NAMESPACE@_NO_WARNING_ENABLE)
# if defined(_MSC_VER)
# pragma warning ( default : 4263 ) /* no override, call convention differs */
# endif
#endif
/* Disable warnings that are on by default but occur in valid code. */
#if !defined(@KWSYS_NAMESPACE@_NO_WARNING_DISABLE)
# if defined(_MSC_VER)
# pragma warning (disable: 4097) /* typedef is synonym for class */
# pragma warning (disable: 4127) /* conditional expression is constant */
# pragma warning (disable: 4244) /* possible loss in conversion */
# pragma warning (disable: 4251) /* missing DLL-interface */
# pragma warning (disable: 4305) /* truncation from type1 to type2 */
# pragma warning (disable: 4309) /* truncation of constant value */
# pragma warning (disable: 4514) /* unreferenced inline function */
# pragma warning (disable: 4706) /* assignment in conditional expression */
# pragma warning (disable: 4710) /* function not inlined */
# pragma warning (disable: 4786) /* identifier truncated in debug info */
# endif
#endif
/* MSVC 6.0 in release mode will warn about code it produces with its
optimizer. Disable the warnings specifically for this
configuration. Real warnings will be revealed by a debug build or
by other compilers. */
#if !defined(@KWSYS_NAMESPACE@_NO_WARNING_DISABLE_BOGUS)
# if defined(_MSC_VER) && (_MSC_VER < 1300) && defined(NDEBUG)
# pragma warning ( disable : 4701 ) /* Variable may be used uninitialized. */
# pragma warning ( disable : 4702 ) /* Unreachable code. */
# endif
#endif
#endif

175
Configure.hxx.in Normal file
View File

@ -0,0 +1,175 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_Configure_hxx
#define @KWSYS_NAMESPACE@_Configure_hxx
/* Include C configuration. */
#include <@KWSYS_NAMESPACE@/Configure.h>
/* Whether ANSI C++ stream headers are to be used. */
#define @KWSYS_NAMESPACE@_IOS_USE_ANSI @KWSYS_IOS_USE_ANSI@
/* Whether ANSI C++ streams are in std namespace. */
#define @KWSYS_NAMESPACE@_IOS_HAVE_STD @KWSYS_IOS_HAVE_STD@
/* Whether ANSI C++ <sstream> header is to be used. */
#define @KWSYS_NAMESPACE@_IOS_USE_SSTREAM @KWSYS_IOS_USE_SSTREAM@
/* Whether old C++ <strstream.h> header is to be used. */
#define @KWSYS_NAMESPACE@_IOS_USE_STRSTREAM_H @KWSYS_IOS_USE_STRSTREAM_H@
/* Whether old C++ <strstrea.h> header is to be used. */
#define @KWSYS_NAMESPACE@_IOS_USE_STRSTREA_H @KWSYS_IOS_USE_STRSTREA_H@
/* Whether C++ streams support the ios::binary openmode. */
#define @KWSYS_NAMESPACE@_IOS_HAVE_BINARY @KWSYS_IOS_HAVE_BINARY@
/* Whether STL is in std namespace. */
#define @KWSYS_NAMESPACE@_STL_HAVE_STD @KWSYS_STL_HAVE_STD@
/* Whether the STL string has operator<< for ostream. */
#define @KWSYS_NAMESPACE@_STL_STRING_HAVE_OSTREAM @KWSYS_STL_STRING_HAVE_OSTREAM@
/* Whether the STL string has operator>> for istream. */
#define @KWSYS_NAMESPACE@_STL_STRING_HAVE_ISTREAM @KWSYS_STL_STRING_HAVE_ISTREAM@
/* Whether the STL string has operator!= for char*. */
#define @KWSYS_NAMESPACE@_STL_STRING_HAVE_NEQ_CHAR @KWSYS_STL_STRING_HAVE_NEQ_CHAR@
/* Define the stl namespace macro. */
#if @KWSYS_NAMESPACE@_STL_HAVE_STD
# define @KWSYS_NAMESPACE@_stl std
#else
# define @KWSYS_NAMESPACE@_stl
#endif
/* Define the ios namespace macro. */
#if @KWSYS_NAMESPACE@_IOS_HAVE_STD
# define @KWSYS_NAMESPACE@_ios_namespace std
#else
# define @KWSYS_NAMESPACE@_ios_namespace
#endif
#if @KWSYS_NAMESPACE@_IOS_USE_SSTREAM
# define @KWSYS_NAMESPACE@_ios @KWSYS_NAMESPACE@_ios_namespace
#else
# define @KWSYS_NAMESPACE@_ios @KWSYS_NAMESPACE@_ios
#endif
/* Define the ios::binary openmode macro. */
#if @KWSYS_NAMESPACE@_IOS_HAVE_BINARY
# define @KWSYS_NAMESPACE@_ios_binary @KWSYS_NAMESPACE@_ios::ios::binary
#else
# define @KWSYS_NAMESPACE@_ios_binary 0
#endif
/* Whether the cstddef header is available. */
#define @KWSYS_NAMESPACE@_CXX_HAS_CSTDDEF @KWSYS_CXX_HAS_CSTDDEF@
/* Whether the compiler supports null template arguments. */
#define @KWSYS_NAMESPACE@_CXX_HAS_NULL_TEMPLATE_ARGS @KWSYS_CXX_HAS_NULL_TEMPLATE_ARGS@
/* Define the null template arguments macro. */
#if @KWSYS_NAMESPACE@_CXX_HAS_NULL_TEMPLATE_ARGS
# define @KWSYS_NAMESPACE@_CXX_NULL_TEMPLATE_ARGS <>
#else
# define @KWSYS_NAMESPACE@_CXX_NULL_TEMPLATE_ARGS
#endif
/* Whether the compiler supports member templates. */
#define @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES @KWSYS_CXX_HAS_MEMBER_TEMPLATES@
/* Whether the compiler supports argument dependent lookup. */
#define @KWSYS_NAMESPACE@_CXX_HAS_ARGUMENT_DEPENDENT_LOOKUP @KWSYS_CXX_HAS_ARGUMENT_DEPENDENT_LOOKUP@
/* Whether the compiler supports standard full specialization syntax. */
#define @KWSYS_NAMESPACE@_CXX_HAS_FULL_SPECIALIZATION @KWSYS_CXX_HAS_FULL_SPECIALIZATION@
/* Define the specialization definition macro. */
#if @KWSYS_NAMESPACE@_CXX_HAS_FULL_SPECIALIZATION
# define @KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION template <>
#else
# define @KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
#endif
/* Define typename keyword macro for use in declarations. */
#if defined(_MSC_VER) && _MSC_VER < 1300
# define @KWSYS_NAMESPACE@_CXX_DECL_TYPENAME
#else
# define @KWSYS_NAMESPACE@_CXX_DECL_TYPENAME typename
#endif
/* Whether the stl has iterator_traits. */
#define @KWSYS_NAMESPACE@_STL_HAS_ITERATOR_TRAITS @KWSYS_STL_HAS_ITERATOR_TRAITS@
/* Whether the stl has iterator_category. */
#define @KWSYS_NAMESPACE@_STL_HAS_ITERATOR_CATEGORY @KWSYS_STL_HAS_ITERATOR_CATEGORY@
/* Whether the stl has __iterator_category. */
#define @KWSYS_NAMESPACE@_STL_HAS___ITERATOR_CATEGORY @KWSYS_STL_HAS___ITERATOR_CATEGORY@
/* Whether the stl allocator is the standard template. */
#define @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_TEMPLATE @KWSYS_STL_HAS_ALLOCATOR_TEMPLATE@
/* Whether the stl allocator is not a template. */
#define @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_NONTEMPLATE @KWSYS_STL_HAS_ALLOCATOR_NONTEMPLATE@
/* Whether the stl allocator has rebind. */
#define @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_REBIND @KWSYS_STL_HAS_ALLOCATOR_REBIND@
/* Whether the stl allocator has a size argument for max_size. */
#define @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_MAX_SIZE_ARGUMENT @KWSYS_STL_HAS_ALLOCATOR_MAX_SIZE_ARGUMENT@
/* Whether the stl containers support allocator objects. */
#define @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_OBJECTS @KWSYS_STL_HAS_ALLOCATOR_OBJECTS@
/* Whether struct stat has the st_mtim member for high resolution times. */
#define @KWSYS_NAMESPACE@_STAT_HAS_ST_MTIM @KWSYS_STAT_HAS_ST_MTIM@
/* If building a C++ file in kwsys itself, give the source file
access to the macros without a configured namespace. */
#if defined(KWSYS_NAMESPACE)
# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsys_stl @KWSYS_NAMESPACE@_stl
# define kwsys_ios @KWSYS_NAMESPACE@_ios
# define kwsys @KWSYS_NAMESPACE@
# define kwsys_ios_binary @KWSYS_NAMESPACE@_ios_binary
# endif
# define KWSYS_NAME_IS_KWSYS @KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define KWSYS_STL_HAVE_STD @KWSYS_NAMESPACE@_STL_HAVE_STD
# define KWSYS_IOS_HAVE_STD @KWSYS_NAMESPACE@_IOS_HAVE_STD
# define KWSYS_IOS_USE_ANSI @KWSYS_NAMESPACE@_IOS_USE_ANSI
# define KWSYS_IOS_USE_SSTREAM @KWSYS_NAMESPACE@_IOS_USE_SSTREAM
# define KWSYS_IOS_USE_STRSTREAM_H @KWSYS_NAMESPACE@_IOS_USE_STRSTREAM_H
# define KWSYS_IOS_USE_STRSTREA_H @KWSYS_NAMESPACE@_IOS_USE_STRSTREA_H
# define KWSYS_IOS_HAVE_BINARY @KWSYS_NAMESPACE@_IOS_HAVE_BINARY
# define KWSYS_STAT_HAS_ST_MTIM @KWSYS_NAMESPACE@_STAT_HAS_ST_MTIM
# define KWSYS_CXX_HAS_CSTDDEF @KWSYS_NAMESPACE@_CXX_HAS_CSTDDEF
# define KWSYS_STL_STRING_HAVE_OSTREAM @KWSYS_NAMESPACE@_STL_STRING_HAVE_OSTREAM
# define KWSYS_STL_STRING_HAVE_ISTREAM @KWSYS_NAMESPACE@_STL_STRING_HAVE_ISTREAM
# define KWSYS_STL_STRING_HAVE_NEQ_CHAR @KWSYS_NAMESPACE@_STL_STRING_HAVE_NEQ_CHAR
# define KWSYS_CXX_NULL_TEMPLATE_ARGS @KWSYS_NAMESPACE@_CXX_NULL_TEMPLATE_ARGS
# define KWSYS_CXX_HAS_MEMBER_TEMPLATES @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
# define KWSYS_CXX_HAS_FULL_SPECIALIZATION @KWSYS_NAMESPACE@_CXX_HAS_FULL_SPECIALIZATION
# define KWSYS_CXX_DEFINE_SPECIALIZATION @KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
# define KWSYS_CXX_DECL_TYPENAME @KWSYS_NAMESPACE@_CXX_DECL_TYPENAME
# define KWSYS_STL_HAS_ALLOCATOR_REBIND @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_REBIND
# define KWSYS_STL_HAS_ALLOCATOR_MAX_SIZE_ARGUMENT @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_MAX_SIZE_ARGUMENT
# define KWSYS_CXX_HAS_ARGUMENT_DEPENDENT_LOOKUP @KWSYS_NAMESPACE@_CXX_HAS_ARGUMENT_DEPENDENT_LOOKUP
# define KWSYS_STL_HAS_ITERATOR_TRAITS @KWSYS_NAMESPACE@_STL_HAS_ITERATOR_TRAITS
# define KWSYS_STL_HAS_ITERATOR_CATEGORY @KWSYS_NAMESPACE@_STL_HAS_ITERATOR_CATEGORY
# define KWSYS_STL_HAS___ITERATOR_CATEGORY @KWSYS_NAMESPACE@_STL_HAS___ITERATOR_CATEGORY
# define KWSYS_STL_HAS_ALLOCATOR_TEMPLATE @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_TEMPLATE
# define KWSYS_STL_HAS_ALLOCATOR_NONTEMPLATE @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_NONTEMPLATE
# define KWSYS_STL_HAS_ALLOCATOR_OBJECTS @KWSYS_NAMESPACE@_STL_HAS_ALLOCATOR_OBJECTS
#endif
#endif

31
Copyright.txt Normal file
View File

@ -0,0 +1,31 @@
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the names of Kitware, Inc., the Insight Software Consortium,
nor the names of their contributors may be used to endorse or promote
products derived from this software without specific prior written
permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

250
Directory.cxx Normal file
View File

@ -0,0 +1,250 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(Configure.hxx)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/vector)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "Directory.hxx.in"
# include "Configure.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_stl_string.hxx.in"
# include "kwsys_stl_vector.hxx.in"
#endif
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
class DirectoryInternals
{
public:
// Array of Files
kwsys_stl::vector<kwsys_stl::string> Files;
// Path to Open'ed directory
kwsys_stl::string Path;
};
//----------------------------------------------------------------------------
Directory::Directory()
{
this->Internal = new DirectoryInternals;
}
//----------------------------------------------------------------------------
Directory::~Directory()
{
delete this->Internal;
}
//----------------------------------------------------------------------------
unsigned long Directory::GetNumberOfFiles() const
{
return static_cast<unsigned long>(this->Internal->Files.size());
}
//----------------------------------------------------------------------------
const char* Directory::GetFile(unsigned long dindex) const
{
if ( dindex >= this->Internal->Files.size() )
{
return 0;
}
return this->Internal->Files[dindex].c_str();
}
//----------------------------------------------------------------------------
const char* Directory::GetPath() const
{
return this->Internal->Path.c_str();
}
//----------------------------------------------------------------------------
void Directory::Clear()
{
this->Internal->Path.resize(0);
this->Internal->Files.clear();
}
} // namespace KWSYS_NAMESPACE
// First microsoft compilers
#if defined(_MSC_VER) || defined(__WATCOMC__)
#include <windows.h>
#include <io.h>
#include <ctype.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
namespace KWSYS_NAMESPACE
{
bool Directory::Load(const char* name)
{
this->Clear();
#if _MSC_VER < 1300
long srchHandle;
#else
intptr_t srchHandle;
#endif
char* buf;
size_t n = strlen(name);
if ( name[n - 1] == '/' )
{
buf = new char[n + 1 + 1];
sprintf(buf, "%s*", name);
}
else
{
buf = new char[n + 2 + 1];
sprintf(buf, "%s/*", name);
}
struct _finddata_t data; // data of current file
// Now put them into the file array
srchHandle = _findfirst(buf, &data);
delete [] buf;
if ( srchHandle == -1 )
{
return 0;
}
// Loop through names
do
{
this->Internal->Files.push_back(data.name);
}
while ( _findnext(srchHandle, &data) != -1 );
this->Internal->Path = name;
return _findclose(srchHandle) != -1;
}
unsigned long Directory::GetNumberOfFilesInDirectory(const char* name)
{
#if _MSC_VER < 1300
long srchHandle;
#else
intptr_t srchHandle;
#endif
char* buf;
size_t n = strlen(name);
if ( name[n - 1] == '/' )
{
buf = new char[n + 1 + 1];
sprintf(buf, "%s*", name);
}
else
{
buf = new char[n + 2 + 1];
sprintf(buf, "%s/*", name);
}
struct _finddata_t data; // data of current file
// Now put them into the file array
srchHandle = _findfirst(buf, &data);
delete [] buf;
if ( srchHandle == -1 )
{
return 0;
}
// Loop through names
unsigned long count = 0;
do
{
count++;
}
while ( _findnext(srchHandle, &data) != -1 );
_findclose(srchHandle);
return count;
}
} // namespace KWSYS_NAMESPACE
#else
// Now the POSIX style directory access
#include <sys/types.h>
#include <dirent.h>
/* There is a problem with the Portland compiler, large file
support and glibc/Linux system headers:
http://www.pgroup.com/userforum/viewtopic.php?
p=1992&sid=f16167f51964f1a68fe5041b8eb213b6
*/
#if defined(__PGI) && defined(__USE_FILE_OFFSET64)
# define dirent dirent64
#endif
namespace KWSYS_NAMESPACE
{
bool Directory::Load(const char* name)
{
this->Clear();
if (!name)
{
return 0;
}
DIR* dir = opendir(name);
if (!dir)
{
return 0;
}
for (dirent* d = readdir(dir); d; d = readdir(dir) )
{
this->Internal->Files.push_back(d->d_name);
}
this->Internal->Path = name;
closedir(dir);
return 1;
}
unsigned long Directory::GetNumberOfFilesInDirectory(const char* name)
{
DIR* dir = opendir(name);
if (!dir)
{
return 0;
}
unsigned long count = 0;
for (dirent* d = readdir(dir); d; d = readdir(dir) )
{
count++;
}
closedir(dir);
return count;
}
} // namespace KWSYS_NAMESPACE
#endif

80
Directory.hxx.in Normal file
View File

@ -0,0 +1,80 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_Directory_hxx
#define @KWSYS_NAMESPACE@_Directory_hxx
#include <@KWSYS_NAMESPACE@/Configure.h>
namespace @KWSYS_NAMESPACE@
{
class DirectoryInternals;
/** \class Directory
* \brief Portable directory/filename traversal.
*
* Directory provides a portable way of finding the names of the files
* in a system directory.
*
* Directory currently works with Windows and Unix operating systems.
*/
class @KWSYS_NAMESPACE@_EXPORT Directory
{
public:
Directory();
~Directory();
/**
* Load the specified directory and load the names of the files
* in that directory. 0 is returned if the directory can not be
* opened, 1 if it is opened.
*/
bool Load(const char*);
/**
* Return the number of files in the current directory.
*/
unsigned long GetNumberOfFiles() const;
/**
* Return the number of files in the specified directory.
* A higher performance static method.
*/
static unsigned long GetNumberOfFilesInDirectory(const char*);
/**
* Return the file at the given index, the indexing is 0 based
*/
const char* GetFile(unsigned long) const;
/**
* Return the path to Open'ed directory
*/
const char* GetPath() const;
/**
* Clear the internal structure. Used internally at beginning of Load(...)
* to clear the cache.
*/
void Clear();
private:
// Private implementation details.
DirectoryInternals* Internal;
Directory(const Directory&); // Not implemented.
void operator=(const Directory&); // Not implemented.
}; // End Class: Directory
} // namespace @KWSYS_NAMESPACE@
#endif

482
DynamicLoader.cxx Normal file
View File

@ -0,0 +1,482 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#include KWSYS_HEADER(Configure.hxx)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "DynamicLoader.hxx.in"
# include "Configure.hxx.in"
#endif
// This file is actually 3 different implementations.
// 1. HP machines which uses shl_load
// 2. Mac OS X 10.2.x and earlier which uses NSLinkModule
// 3. Windows which uses LoadLibrary
// 4. Most unix systems (including Mac OS X 10.3 and later) which use dlopen
// (default) Each part of the ifdef contains a complete implementation for
// the static methods of DynamicLoader.
// ---------------------------------------------------------------
// 1. Implementation for HPUX machines
#ifdef __hpux
#include <errno.h>
#include <dl.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
return shl_load(libname, BIND_DEFERRED | DYNAMIC_PATH, 0L);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
return !shl_unload(lib);
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer
DynamicLoader::GetSymbolAddress(DynamicLoader::LibraryHandle lib, const char* sym)
{
void* addr;
int status;
/* TYPE_PROCEDURE Look for a function or procedure. (This used to be default)
* TYPE_DATA Look for a symbol in the data segment (for example, variables).
* TYPE_UNDEFINED Look for any symbol.
*/
status = shl_findsym (&lib, sym, TYPE_UNDEFINED, &addr);
void* result = (status < 0) ? (void*)0 : addr;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
const char* DynamicLoader::LastError()
{
// TODO: Need implementation with errno/strerror
/* If successful, shl_findsym returns an integer (int) value zero. If
* shl_findsym cannot find sym, it returns -1 and sets errno to zero.
* If any other errors occur, shl_findsym returns -1 and sets errno to one
* of these values (defined in <errno.h>):
* ENOEXEC
* A format error was detected in the specified library.
* ENOSYM
* A symbol on which sym depends could not be found.
* EINVAL
* The specified handle is invalid.
*/
if( errno == ENOEXEC
|| errno == ENOSYM
|| errno == EINVAL )
{
return strerror(errno);
}
// else
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif //__hpux
// ---------------------------------------------------------------
// 2. Implementation for Mac OS X 10.2.x and earlier
#ifdef __APPLE__
#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
#include <string.h> // for strlen
#include <mach-o/dyld.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
NSObjectFileImageReturnCode rc;
NSObjectFileImage image = 0;
rc = NSCreateObjectFileImageFromFile(libname, &image);
// rc == NSObjectFileImageInappropriateFile when trying to load a dylib file
if( rc != NSObjectFileImageSuccess )
{
return 0;
}
NSModule handle = NSLinkModule(image, libname,
NSLINKMODULE_OPTION_BINDNOW|NSLINKMODULE_OPTION_RETURN_ON_ERROR);
NSDestroyObjectFileImage(image);
return handle;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary( DynamicLoader::LibraryHandle lib)
{
// NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
// With this option the memory for the module is not deallocated
// allowing pointers into the module to still be valid.
// You should use this option instead if your code experience some problems
// reported against Panther 10.3.9 (fixed in Tiger 10.4.2 and up)
bool success = NSUnLinkModule(lib, NSUNLINKMODULE_OPTION_NONE);
return success;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
void *result=0;
// Need to prepend symbols with '_' on Apple-gcc compilers
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym+1, sym);
NSSymbol symbol = NSLookupSymbolInModule(lib, rsym);
if(symbol)
{
result = NSAddressOfSymbol(symbol);
}
delete[] rsym;
// Hack to cast pointer-to-data to pointer-to-function.
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return 0;
}
} // namespace KWSYS_NAMESPACE
#endif // MAC_OS_X_VERSION_MAX_ALLOWED < 1030
#endif // __APPLE__
// ---------------------------------------------------------------
// 3. Implementation for Windows win32 code but not cygwin
#if defined(_WIN32) && !defined(__CYGWIN__)
#include <windows.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname)
{
DynamicLoader::LibraryHandle lh;
#ifdef UNICODE
wchar_t libn[MB_CUR_MAX];
mbstowcs(libn, libname, MB_CUR_MAX);
lh = LoadLibrary(libn);
#else
lh = LoadLibrary(libname);
#endif
return lh;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
return (int)FreeLibrary(lib);
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
// TODO: The calling convention affects the name of the symbol. We
// should have a tool to help get the symbol with the desired
// calling convention. Currently we assume cdecl.
//
// Borland:
// __cdecl = "_func" (default)
// __fastcall = "@_func"
// __stdcall = "func"
//
// Watcom:
// __cdecl = "_func"
// __fastcall = "@_func@X"
// __stdcall = "_func@X"
// __watcall = "func_" (default)
//
// MSVC:
// __cdecl = "func" (default)
// __fastcall = "@_func@X"
// __stdcall = "_func@X"
//
// Note that the "@X" part of the name above is the total size (in
// bytes) of the arguments on the stack.
void *result;
#if defined(__BORLANDC__) || defined(__WATCOMC__)
// Need to prepend symbols with '_'
size_t len = strlen(sym);
char *rsym = new char[len + 1 + 1];
strcpy(rsym, "_");
strcat(rsym, sym);
#else
const char *rsym = sym;
#endif
#ifdef UNICODE
wchar_t wsym[MB_CUR_MAX];
mbstowcs(wsym, rsym, MB_CUR_MAX);
result = GetProcAddress(lib, wsym);
#else
result = (void*)GetProcAddress(lib, rsym);
#endif
#if defined(__BORLANDC__) || defined(__WATCOMC__)
delete[] rsym;
#endif
// Hack to cast pointer-to-data to pointer-to-function.
#ifdef __WATCOMC__
return *(DynamicLoader::SymbolPointer*)(&result);
#else
return *reinterpret_cast<DynamicLoader::SymbolPointer*>(&result);
#endif
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
LPVOID lpMsgBuf=NULL;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
if(!lpMsgBuf)
{
return NULL;
}
static char* str = 0;
delete [] str;
str = strcpy(new char[strlen((char*)lpMsgBuf)+1], (char*)lpMsgBuf);
// Free the buffer.
LocalFree( lpMsgBuf );
return str;
}
} // namespace KWSYS_NAMESPACE
#endif //_WIN32
// ---------------------------------------------------------------
// 4. Implementation for BeOS
#if defined __BEOS__
#include <string.h> // for strerror()
#include <be/kernel/image.h>
#include <be/support/Errors.h>
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
static image_id last_dynamic_err = B_OK;
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
// image_id's are integers, errors are negative. Add one just in case we
// get a valid image_id of zero (is that even possible?).
image_id rc = load_add_on(libname);
if (rc < 0)
{
last_dynamic_err = rc;
return 0;
}
return rc+1;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
if (!lib)
{
last_dynamic_err = B_BAD_VALUE;
return 0;
}
else
{
// The function dlclose() returns 0 on success, and non-zero on error.
status_t rc = unload_add_on(lib-1);
if (rc != B_OK)
{
last_dynamic_err = rc;
return 0;
}
}
return 1;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
// Hack to cast pointer-to-data to pointer-to-function.
union
{
void* pvoid;
DynamicLoader::SymbolPointer psym;
} result;
result.psym = NULL;
if (!lib)
{
last_dynamic_err = B_BAD_VALUE;
}
else
{
// !!! FIXME: BeOS can do function-only lookups...does this ever
// !!! FIXME: actually _want_ a data symbol lookup, or was this union
// !!! FIXME: a leftover of dlsym()? (s/ANY/TEXT for functions only).
status_t rc = get_image_symbol(lib-1,sym,B_SYMBOL_TYPE_ANY,&result.pvoid);
if (rc != B_OK)
{
last_dynamic_err = rc;
result.psym = NULL;
}
}
return result.psym;
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
const char *retval = strerror(last_dynamic_err);
last_dynamic_err = B_OK;
return retval;
}
} // namespace KWSYS_NAMESPACE
#endif
// ---------------------------------------------------------------
// 5. Implementation for systems without dynamic libs
// __gnu_blrts__ is IBM BlueGene/L
// __LIBCATAMOUNT__ is defined on Catamount on Cray compute nodes
#if defined(__gnu_blrts__) || defined(__LIBCATAMOUNT__) || defined(__CRAYXT_COMPUTE_LINUX_TARGET)
#include <string.h> // for strerror()
#define DYNAMICLOADER_DEFINED 1
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
return 0;
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
if (!lib)
{
return 0;
}
return 1;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
return 0;
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return "General error";
}
} // namespace KWSYS_NAMESPACE
#endif
// ---------------------------------------------------------------
// 6. Implementation for default UNIX machines.
// if nothing has been defined then use this
#ifndef DYNAMICLOADER_DEFINED
#define DYNAMICLOADER_DEFINED 1
// Setup for most unix machines
#include <dlfcn.h>
namespace KWSYS_NAMESPACE
{
//----------------------------------------------------------------------------
DynamicLoader::LibraryHandle DynamicLoader::OpenLibrary(const char* libname )
{
return dlopen(libname, RTLD_LAZY);
}
//----------------------------------------------------------------------------
int DynamicLoader::CloseLibrary(DynamicLoader::LibraryHandle lib)
{
if (lib)
{
// The function dlclose() returns 0 on success, and non-zero on error.
return !dlclose(lib);
}
// else
return 0;
}
//----------------------------------------------------------------------------
DynamicLoader::SymbolPointer DynamicLoader::GetSymbolAddress(
DynamicLoader::LibraryHandle lib, const char* sym)
{
// Hack to cast pointer-to-data to pointer-to-function.
union
{
void* pvoid;
DynamicLoader::SymbolPointer psym;
} result;
result.pvoid = dlsym(lib, sym);
return result.psym;
}
//----------------------------------------------------------------------------
const char* DynamicLoader::LastError()
{
return dlerror();
}
} // namespace KWSYS_NAMESPACE
#endif

101
DynamicLoader.hxx.in Normal file
View File

@ -0,0 +1,101 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_DynamicLoader_hxx
#define @KWSYS_NAMESPACE@_DynamicLoader_hxx
#include <@KWSYS_NAMESPACE@/Configure.h>
#if defined(__hpux)
#include <dl.h>
#elif defined(_WIN32) && !defined(__CYGWIN__)
#include <windows.h>
#elif defined(__APPLE__)
#include <AvailabilityMacros.h>
#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
#include <mach-o/dyld.h>
#endif
#elif defined(__BEOS__)
#include <be/kernel/image.h>
#endif
namespace @KWSYS_NAMESPACE@
{
/** \class DynamicLoader
* \brief Portable loading of dynamic libraries or dll's.
*
* DynamicLoader provides a portable interface to loading dynamic
* libraries or dll's into a process.
*
* Directory currently works with Windows, Apple, HP-UX and Unix (POSIX)
* operating systems
*
* \warning dlopen on *nix system works the following way:
* If filename contains a slash ("/"), then it is interpreted as a (relative
* or absolute) pathname. Otherwise, the dynamic linker searches for the
* library as follows : see ld.so(8) for further details):
* Whereas this distinction does not exist on Win32. Therefore ideally you
* should be doing full path to garantee to have a consistent way of dealing
* with dynamic loading of shared library.
*
* \warning the Cygwin implementation do not use the Win32 HMODULE. Put extra
* condition so that we can include the correct declaration (POSIX)
*/
class @KWSYS_NAMESPACE@_EXPORT DynamicLoader
{
public:
// Ugly stuff for library handles
// They are different on several different OS's
#if defined(__hpux)
typedef shl_t LibraryHandle;
#elif defined(_WIN32) && !defined(__CYGWIN__)
typedef HMODULE LibraryHandle;
#elif defined(__APPLE__)
#if MAC_OS_X_VERSION_MAX_ALLOWED < 1030
typedef NSModule LibraryHandle;
#else
typedef void* LibraryHandle;
#endif
#elif defined(__BEOS__)
typedef image_id LibraryHandle;
#else // POSIX
typedef void* LibraryHandle;
#endif
// Return type from DynamicLoader::GetSymbolAddress.
typedef void (*SymbolPointer)();
/** Load a dynamic library into the current process.
* The returned LibraryHandle can be used to access the symbols in the
* library. */
static LibraryHandle OpenLibrary(const char*);
/** Attempt to detach a dynamic library from the
* process. A value of true is returned if it is sucessful. */
static int CloseLibrary(LibraryHandle);
/** Find the address of the symbol in the given library. */
static SymbolPointer GetSymbolAddress(LibraryHandle, const char*);
/** Return the default module prefix for the current platform. */
static const char* LibPrefix() { return "@KWSYS_DynamicLoader_PREFIX@"; }
/** Return the default module suffix for the current platform. */
static const char* LibExtension() { return "@KWSYS_DynamicLoader_SUFFIX@"; }
/** Return the last error produced from a calls made on this class. */
static const char* LastError();
}; // End Class: DynamicLoader
} // namespace @KWSYS_NAMESPACE@
#endif

114
EncodeExecutable.c Normal file
View File

@ -0,0 +1,114 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include <stdio.h>
#ifdef __WATCOMC__
#define _unlink unlink
#endif
int main(int argc, char* argv[])
{
FILE* ifp;
FILE* ofp;
int i;
int n;
int count = 0;
unsigned char buffer[1024];
/* Check arguments. */
if(argc != 5)
{
fprintf(stderr, "Usage: %s <input> <output> <kwsys-name> <array>\n",
argv[0]);
return 1;
}
/* Open the input file. */
ifp = fopen(argv[1], "rb");
if(!ifp)
{
fprintf(stderr, "Cannot open input file: \"%s\"\n", argv[1]);
return 2;
}
ofp = fopen(argv[2], "w");
if(!ofp)
{
fprintf(stderr, "Cannot open output file: \"%s\"\n", argv[2]);
fclose(ifp);
return 2;
}
/* Prepend header comment. */
fprintf(ofp, "/*\n * DO NOT EDIT\n * This file is generated by:\n");
fprintf(ofp, " * %s\n */\n\n", argv[0]);
fprintf(ofp, "#include \"kwsysPrivate.h\"\n");
fprintf(ofp, "#include KWSYS_HEADER(Configure.h)\n\n");
fprintf(ofp, "#include <stdio.h>\n\n");
fprintf(ofp, "#if defined(_WIN32)\n");
fprintf(ofp, "# include <io.h>\n");
fprintf(ofp, "#else\n");
fprintf(ofp, "# include <unistd.h>\n");
fprintf(ofp, "#endif\n");
fprintf(ofp, "\n");
fprintf(ofp, "static void kwsys_unlink(const char* fname)\n");
fprintf(ofp, "{\n");
fprintf(ofp, "#if defined(__WATCOMC__)\n");
fprintf(ofp, " unlink(fname);\n");
fprintf(ofp, "#else\n");
fprintf(ofp, " _unlink(fname);\n");
fprintf(ofp, "#endif\n");
fprintf(ofp, "}\n");
fprintf(ofp, "\n");
/* Split file up in 1024-byte chunks. */
while((n = (int)fread(buffer, 1, 1024, ifp)) > 0)
{
fprintf(ofp, "static unsigned char kwsysEncodedArray%s_%d[%d] = {\n",
argv[4], count++, n);
for(i=0; i < n-1; ++i)
{
fprintf(ofp, "0x%02X", buffer[i]);
if(i%10 == 9)
{
fprintf(ofp, ",\n");
}
else
{
fprintf(ofp, ", ");
}
}
fprintf(ofp, "0x%02X};\n\n", buffer[n-1]);
}
fclose(ifp);
/* Provide a function to write the data to a file. */
fprintf(ofp, "extern %s_EXPORT int %sEncodedWriteArray%s(const char* fname)\n",
argv[3], argv[3], argv[4]);
fprintf(ofp, "{\n");
fprintf(ofp, " FILE* ofp = fopen(fname, \"wb\");\n");
fprintf(ofp, " if(!ofp) { return 0; }\n");
for(i=0; i < count; ++i)
{
fprintf(ofp, " if(fwrite(kwsysEncodedArray%s_%d, 1,\n"
" sizeof(kwsysEncodedArray%s_%d), ofp) !=\n"
" sizeof(kwsysEncodedArray%s_%d))\n",
argv[4], i, argv[4], i, argv[4], i);
fprintf(ofp, " {\n");
fprintf(ofp, " fclose(ofp);\n");
fprintf(ofp, " kwsys_unlink(fname);\n");
fprintf(ofp, " return 0;\n");
fprintf(ofp, " }\n");
}
fprintf(ofp, " fclose(ofp);\n");
fprintf(ofp, " return 1;\n");
fprintf(ofp, "}\n");
fclose(ofp);
return 0;
}

1
ExtraTest.cmake.in Normal file
View File

@ -0,0 +1 @@
MESSAGE("*** This message is generated by message inside a file that is included in DartTestfile.txt ***")

146
FundamentalType.h.in Normal file
View File

@ -0,0 +1,146 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_FundamentalType_h
#define @KWSYS_NAMESPACE@_FundamentalType_h
#include <@KWSYS_NAMESPACE@/Configure.h>
/* Redefine all public interface symbol names to be in the proper
namespace. These macros are used internally to kwsys only, and are
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysFundamentalType kwsys_ns(FundamentalType)
# define kwsysFundamentalType_Int8 kwsys_ns(FundamentalType_Int8)
# define kwsysFundamentalType_UInt8 kwsys_ns(FundamentalType_UInt8)
# define kwsysFundamentalType_Int16 kwsys_ns(FundamentalType_Int16)
# define kwsysFundamentalType_UInt16 kwsys_ns(FundamentalType_UInt16)
# define kwsysFundamentalType_Int32 kwsys_ns(FundamentalType_Int32)
# define kwsysFundamentalType_UInt32 kwsys_ns(FundamentalType_UInt32)
# define kwsysFundamentalType_Int64 kwsys_ns(FundamentalType_Int64)
# define kwsysFundamentalType_UInt64 kwsys_ns(FundamentalType_UInt64)
#endif
/* The size of fundamental types. Types that do not exist have size 0. */
@KWSYS_C_CODE_SIZEOF_CHAR@
@KWSYS_C_CODE_SIZEOF_SHORT@
@KWSYS_C_CODE_SIZEOF_INT@
@KWSYS_C_CODE_SIZEOF_LONG@
@KWSYS_C_CODE_SIZEOF_LONG_LONG@
@KWSYS_C_CODE_SIZEOF___INT64@
/* Whether types "long long" and "__int64" are enabled. If a type is
enabled then it is a unique fundamental type. */
#define @KWSYS_NAMESPACE@_USE_LONG_LONG @KWSYS_USE_LONG_LONG@
#define @KWSYS_NAMESPACE@_USE___INT64 @KWSYS_USE___INT64@
/* Whether type "char" is signed (it may be signed or unsigned). */
#define @KWSYS_NAMESPACE@_CHAR_IS_SIGNED @KWSYS_CHAR_IS_SIGNED@
#if defined(__cplusplus)
extern "C"
{
#endif
/* Select an 8-bit integer type. */
#if @KWSYS_NAMESPACE@_SIZEOF_CHAR == 1
typedef signed char kwsysFundamentalType_Int8;
typedef unsigned char kwsysFundamentalType_UInt8;
#else
# error "No native data type can represent an 8-bit integer."
#endif
/* Select a 16-bit integer type. */
#if @KWSYS_NAMESPACE@_SIZEOF_SHORT == 2
typedef short kwsysFundamentalType_Int16;
typedef unsigned short kwsysFundamentalType_UInt16;
#elif @KWSYS_NAMESPACE@_SIZEOF_INT == 2
typedef int kwsysFundamentalType_Int16;
typedef unsigned int kwsysFundamentalType_UInt16;
#else
# error "No native data type can represent a 16-bit integer."
#endif
/* Select a 32-bit integer type. */
#if @KWSYS_NAMESPACE@_SIZEOF_INT == 4
typedef int kwsysFundamentalType_Int32;
typedef unsigned int kwsysFundamentalType_UInt32;
#elif @KWSYS_NAMESPACE@_SIZEOF_LONG == 4
typedef long kwsysFundamentalType_Int32;
typedef unsigned long kwsysFundamentalType_UInt32;
#else
# error "No native data type can represent a 32-bit integer."
#endif
/* Select a 64-bit integer type. */
#if @KWSYS_NAMESPACE@_SIZEOF_LONG == 8
typedef signed long kwsysFundamentalType_Int64;
typedef unsigned long kwsysFundamentalType_UInt64;
/* Whether UInt64 can be converted to double. */
# define @KWSYS_NAMESPACE@_CAN_CONVERT_UI64_TO_DOUBLE 1
#elif @KWSYS_NAMESPACE@_USE_LONG_LONG && @KWSYS_NAMESPACE@_SIZEOF_LONG_LONG == 8
typedef signed long long kwsysFundamentalType_Int64;
typedef unsigned long long kwsysFundamentalType_UInt64;
/* Whether UInt64 can be converted to double. */
# define @KWSYS_NAMESPACE@_CAN_CONVERT_UI64_TO_DOUBLE 1
#elif @KWSYS_NAMESPACE@_USE___INT64 && @KWSYS_NAMESPACE@_SIZEOF___INT64 == 8
typedef signed __int64 kwsysFundamentalType_Int64;
typedef unsigned __int64 kwsysFundamentalType_UInt64;
/* Whether UInt64 can be converted to double. */
# define @KWSYS_NAMESPACE@_CAN_CONVERT_UI64_TO_DOUBLE @KWSYS_CAN_CONVERT_UI64_TO_DOUBLE@
#else
# error "No native data type can represent a 64-bit integer."
#endif
#if defined(__cplusplus)
} /* extern "C" */
#endif
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
# undef kwsys_ns
# undef kwsysEXPORT
# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysFundamentalType
# undef kwsysFundamentalType_Int8
# undef kwsysFundamentalType_UInt8
# undef kwsysFundamentalType_Int16
# undef kwsysFundamentalType_UInt16
# undef kwsysFundamentalType_Int32
# undef kwsysFundamentalType_UInt32
# undef kwsysFundamentalType_Int64
# undef kwsysFundamentalType_UInt64
# endif
#endif
/* If building a C or C++ file in kwsys itself, give the source file
access to the configured macros without a configured namespace. */
#if defined(KWSYS_NAMESPACE)
# define KWSYS_SIZEOF_CHAR @KWSYS_NAMESPACE@_SIZEOF_CHAR
# define KWSYS_SIZEOF_SHORT @KWSYS_NAMESPACE@_SIZEOF_SHORT
# define KWSYS_SIZEOF_INT @KWSYS_NAMESPACE@_SIZEOF_INT
# define KWSYS_SIZEOF_LONG @KWSYS_NAMESPACE@_SIZEOF_LONG
# define KWSYS_SIZEOF_LONG_LONG @KWSYS_NAMESPACE@_SIZEOF_LONG_LONG
# define KWSYS_SIZEOF___INT64 @KWSYS_NAMESPACE@_SIZEOF___INT64
# define KWSYS_USE_LONG_LONG @KWSYS_NAMESPACE@_USE_LONG_LONG
# define KWSYS_USE___INT64 @KWSYS_NAMESPACE@_USE___INT64
# define KWSYS_CHAR_IS_SIGNED @KWSYS_NAMESPACE@_CHAR_IS_SIGNED
# define KWSYS_CAN_CONVERT_UI64_TO_DOUBLE @KWSYS_NAMESPACE@_CAN_CONVERT_UI64_TO_DOUBLE
#endif
#endif

516
Glob.cxx Normal file
View File

@ -0,0 +1,516 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Glob.hxx)
#include KWSYS_HEADER(Configure.hxx)
#include KWSYS_HEADER(RegularExpression.hxx)
#include KWSYS_HEADER(SystemTools.hxx)
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/vector)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "Glob.hxx.in"
# include "Directory.hxx.in"
# include "Configure.hxx.in"
# include "RegularExpression.hxx.in"
# include "SystemTools.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_stl_string.hxx.in"
#endif
#include <ctype.h>
#include <stdio.h>
#include <string.h>
namespace KWSYS_NAMESPACE
{
#if defined(_WIN32) || defined(__APPLE__) || defined(__CYGWIN__)
// On Windows and apple, no difference between lower and upper case
# define KWSYS_GLOB_CASE_INDEPENDENT
#endif
#if defined(_WIN32) || defined(__CYGWIN__)
// Handle network paths
# define KWSYS_GLOB_SUPPORT_NETWORK_PATHS
#endif
//----------------------------------------------------------------------------
class GlobInternals
{
public:
kwsys_stl::vector<kwsys_stl::string> Files;
kwsys_stl::vector<kwsys::RegularExpression> Expressions;
};
//----------------------------------------------------------------------------
Glob::Glob()
{
this->Internals = new GlobInternals;
this->Recurse = false;
this->Relative = "";
this->RecurseThroughSymlinks = true;
// RecurseThroughSymlinks is true by default for backwards compatibility,
// not because it's a good idea...
this->FollowedSymlinkCount = 0;
}
//----------------------------------------------------------------------------
Glob::~Glob()
{
delete this->Internals;
}
//----------------------------------------------------------------------------
kwsys_stl::vector<kwsys_stl::string>& Glob::GetFiles()
{
return this->Internals->Files;
}
//----------------------------------------------------------------------------
kwsys_stl::string Glob::PatternToRegex(const kwsys_stl::string& pattern,
bool require_whole_string,
bool preserve_case)
{
// Incrementally build the regular expression from the pattern.
kwsys_stl::string regex = require_whole_string? "^" : "";
kwsys_stl::string::const_iterator pattern_first = pattern.begin();
kwsys_stl::string::const_iterator pattern_last = pattern.end();
for(kwsys_stl::string::const_iterator i = pattern_first;
i != pattern_last; ++i)
{
int c = *i;
if(c == '*')
{
// A '*' (not between brackets) matches any string.
// We modify this to not match slashes since the orignal glob
// pattern documentation was meant for matching file name
// components separated by slashes.
regex += "[^/]*";
}
else if(c == '?')
{
// A '?' (not between brackets) matches any single character.
// We modify this to not match slashes since the orignal glob
// pattern documentation was meant for matching file name
// components separated by slashes.
regex += "[^/]";
}
else if(c == '[')
{
// Parse out the bracket expression. It begins just after the
// opening character.
kwsys_stl::string::const_iterator bracket_first = i+1;
kwsys_stl::string::const_iterator bracket_last = bracket_first;
// The first character may be complementation '!' or '^'.
if(bracket_last != pattern_last &&
(*bracket_last == '!' || *bracket_last == '^'))
{
++bracket_last;
}
// If the next character is a ']' it is included in the brackets
// because the bracket string may not be empty.
if(bracket_last != pattern_last && *bracket_last == ']')
{
++bracket_last;
}
// Search for the closing ']'.
while(bracket_last != pattern_last && *bracket_last != ']')
{
++bracket_last;
}
// Check whether we have a complete bracket string.
if(bracket_last == pattern_last)
{
// The bracket string did not end, so it was opened simply by
// a '[' that is supposed to be matched literally.
regex += "\\[";
}
else
{
// Convert the bracket string to its regex equivalent.
kwsys_stl::string::const_iterator k = bracket_first;
// Open the regex block.
regex += "[";
// A regex range complement uses '^' instead of '!'.
if(k != bracket_last && *k == '!')
{
regex += "^";
++k;
}
// Convert the remaining characters.
for(; k != bracket_last; ++k)
{
// Backslashes must be escaped.
if(*k == '\\')
{
regex += "\\";
}
// Store this character.
regex += *k;
}
// Close the regex block.
regex += "]";
// Jump to the end of the bracket string.
i = bracket_last;
}
}
else
{
// A single character matches itself.
int ch = c;
if(!(('a' <= ch && ch <= 'z') ||
('A' <= ch && ch <= 'Z') ||
('0' <= ch && ch <= '9')))
{
// Escape the non-alphanumeric character.
regex += "\\";
}
#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
else
{
// On case-insensitive systems file names are converted to lower
// case before matching.
if(!preserve_case)
{
ch = tolower(ch);
}
}
#endif
(void)preserve_case;
// Store the character.
regex.append(1, static_cast<char>(ch));
}
}
if(require_whole_string)
{
regex += "$";
}
return regex;
}
//----------------------------------------------------------------------------
void Glob::RecurseDirectory(kwsys_stl::string::size_type start,
const kwsys_stl::string& dir)
{
kwsys::Directory d;
if ( !d.Load(dir.c_str()) )
{
return;
}
unsigned long cc;
kwsys_stl::string fullname;
kwsys_stl::string realname;
kwsys_stl::string fname;
for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
{
fname = d.GetFile(cc);
if ( strcmp(fname.c_str(), ".") == 0 ||
strcmp(fname.c_str(), "..") == 0 )
{
continue;
}
if ( start == 0 )
{
realname = dir + fname;
}
else
{
realname = dir + "/" + fname;
}
#if defined( KWSYS_GLOB_CASE_INDEPENDENT )
// On Windows and apple, no difference between lower and upper case
fname = kwsys::SystemTools::LowerCase(fname);
#endif
if ( start == 0 )
{
fullname = dir + fname;
}
else
{
fullname = dir + "/" + fname;
}
bool isDir = kwsys::SystemTools::FileIsDirectory(realname.c_str());
bool isSymLink = kwsys::SystemTools::FileIsSymlink(realname.c_str());
if ( isDir && (!isSymLink || this->RecurseThroughSymlinks) )
{
if (isSymLink)
{
++this->FollowedSymlinkCount;
}
this->RecurseDirectory(start+1, realname);
}
else
{
if ( (this->Internals->Expressions.size() > 0) &&
this->Internals->Expressions[
this->Internals->Expressions.size()-1].find(fname.c_str()) )
{
this->AddFile(this->Internals->Files, realname.c_str());
}
}
}
}
//----------------------------------------------------------------------------
void Glob::ProcessDirectory(kwsys_stl::string::size_type start,
const kwsys_stl::string& dir)
{
//kwsys_ios::cout << "ProcessDirectory: " << dir << kwsys_ios::endl;
bool last = ( start == this->Internals->Expressions.size()-1 );
if ( last && this->Recurse )
{
this->RecurseDirectory(start, dir);
return;
}
if ( start >= this->Internals->Expressions.size() )
{
return;
}
kwsys::Directory d;
if ( !d.Load(dir.c_str()) )
{
return;
}
unsigned long cc;
kwsys_stl::string fullname;
kwsys_stl::string realname;
kwsys_stl::string fname;
for ( cc = 0; cc < d.GetNumberOfFiles(); cc ++ )
{
fname = d.GetFile(cc);
if ( strcmp(fname.c_str(), ".") == 0 ||
strcmp(fname.c_str(), "..") == 0 )
{
continue;
}
if ( start == 0 )
{
realname = dir + fname;
}
else
{
realname = dir + "/" + fname;
}
#if defined(KWSYS_GLOB_CASE_INDEPENDENT)
// On case-insensitive file systems convert to lower case for matching.
fname = kwsys::SystemTools::LowerCase(fname);
#endif
if ( start == 0 )
{
fullname = dir + fname;
}
else
{
fullname = dir + "/" + fname;
}
//kwsys_ios::cout << "Look at file: " << fname << kwsys_ios::endl;
//kwsys_ios::cout << "Match: "
// << this->Internals->TextExpressions[start].c_str() << kwsys_ios::endl;
//kwsys_ios::cout << "Full name: " << fullname << kwsys_ios::endl;
if ( !last &&
!kwsys::SystemTools::FileIsDirectory(realname.c_str()) )
{
continue;
}
if ( this->Internals->Expressions[start].find(fname.c_str()) )
{
if ( last )
{
this->AddFile(this->Internals->Files, realname.c_str());
}
else
{
this->ProcessDirectory(start+1, realname + "/");
}
}
}
}
//----------------------------------------------------------------------------
bool Glob::FindFiles(const kwsys_stl::string& inexpr)
{
kwsys_stl::string cexpr;
kwsys_stl::string::size_type cc;
kwsys_stl::string expr = inexpr;
this->Internals->Expressions.clear();
this->Internals->Files.clear();
if ( !kwsys::SystemTools::FileIsFullPath(expr.c_str()) )
{
expr = kwsys::SystemTools::GetCurrentWorkingDirectory();
expr += "/" + inexpr;
}
kwsys_stl::string fexpr = expr;
kwsys_stl::string::size_type skip = 0;
kwsys_stl::string::size_type last_slash = 0;
for ( cc = 0; cc < expr.size(); cc ++ )
{
if ( cc > 0 && expr[cc] == '/' && expr[cc-1] != '\\' )
{
last_slash = cc;
}
if ( cc > 0 &&
(expr[cc] == '[' || expr[cc] == '?' || expr[cc] == '*') &&
expr[cc-1] != '\\' )
{
break;
}
}
if ( last_slash > 0 )
{
//kwsys_ios::cout << "I can skip: " << fexpr.substr(0, last_slash)
//<< kwsys_ios::endl;
skip = last_slash;
}
if ( skip == 0 )
{
#if defined( KWSYS_GLOB_SUPPORT_NETWORK_PATHS )
// Handle network paths
if ( expr[0] == '/' && expr[1] == '/' )
{
int cnt = 0;
for ( cc = 2; cc < expr.size(); cc ++ )
{
if ( expr[cc] == '/' )
{
cnt ++;
if ( cnt == 2 )
{
break;
}
}
}
skip = int(cc + 1);
}
else
#endif
// Handle drive letters on Windows
if ( expr[1] == ':' && expr[0] != '/' )
{
skip = 2;
}
}
if ( skip > 0 )
{
expr = expr.substr(skip);
}
cexpr = "";
for ( cc = 0; cc < expr.size(); cc ++ )
{
int ch = expr[cc];
if ( ch == '/' )
{
if ( cexpr.size() > 0 )
{
this->AddExpression(cexpr.c_str());
}
cexpr = "";
}
else
{
cexpr.append(1, static_cast<char>(ch));
}
}
if ( cexpr.size() > 0 )
{
this->AddExpression(cexpr.c_str());
}
// Handle network paths
if ( skip > 0 )
{
this->ProcessDirectory(0, fexpr.substr(0, skip) + "/");
}
else
{
this->ProcessDirectory(0, "/");
}
return true;
}
//----------------------------------------------------------------------------
void Glob::AddExpression(const char* expr)
{
this->Internals->Expressions.push_back(
kwsys::RegularExpression(
this->PatternToRegex(expr).c_str()));
}
//----------------------------------------------------------------------------
void Glob::SetRelative(const char* dir)
{
if ( !dir )
{
this->Relative = "";
return;
}
this->Relative = dir;
}
//----------------------------------------------------------------------------
const char* Glob::GetRelative()
{
if ( this->Relative.empty() )
{
return 0;
}
return this->Relative.c_str();
}
//----------------------------------------------------------------------------
void Glob::AddFile(kwsys_stl::vector<kwsys_stl::string>& files, const char* file)
{
if ( !this->Relative.empty() )
{
files.push_back(kwsys::SystemTools::RelativePath(this->Relative.c_str(), file));
}
else
{
files.push_back(file);
}
}
} // namespace KWSYS_NAMESPACE

117
Glob.hxx.in Normal file
View File

@ -0,0 +1,117 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_Glob_hxx
#define @KWSYS_NAMESPACE@_Glob_hxx
#include <@KWSYS_NAMESPACE@/Configure.h>
#include <@KWSYS_NAMESPACE@/Configure.hxx>
#include <@KWSYS_NAMESPACE@/stl/string>
#include <@KWSYS_NAMESPACE@/stl/vector>
/* Define this macro temporarily to keep the code readable. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsys_stl @KWSYS_NAMESPACE@_stl
#endif
namespace @KWSYS_NAMESPACE@
{
class GlobInternals;
/** \class Glob
* \brief Portable globbing searches.
*
* Globbing expressions are much simpler than regular
* expressions. This class will search for files using
* globbing expressions.
*
* Finds all files that match a given globbing expression.
*/
class @KWSYS_NAMESPACE@_EXPORT Glob
{
public:
Glob();
~Glob();
//! Find all files that match the pattern.
bool FindFiles(const kwsys_stl::string& inexpr);
//! Return the list of files that matched.
kwsys_stl::vector<kwsys_stl::string>& GetFiles();
//! Set recurse to true to match subdirectories.
void RecurseOn() { this->SetRecurse(true); }
void RecurseOff() { this->SetRecurse(false); }
void SetRecurse(bool i) { this->Recurse = i; }
bool GetRecurse() { return this->Recurse; }
//! Set recurse through symlinks to true if recursion should traverse the
// linked-to directories
void RecurseThroughSymlinksOn() { this->SetRecurseThroughSymlinks(true); }
void RecurseThroughSymlinksOff() { this->SetRecurseThroughSymlinks(false); }
void SetRecurseThroughSymlinks(bool i) { this->RecurseThroughSymlinks = i; }
bool GetRecurseThroughSymlinks() { return this->RecurseThroughSymlinks; }
//! Get the number of symlinks followed through recursion
unsigned int GetFollowedSymlinkCount() { return this->FollowedSymlinkCount; }
//! Set relative to true to only show relative path to files.
void SetRelative(const char* dir);
const char* GetRelative();
/** Convert the given globbing pattern to a regular expression.
There is no way to quote meta-characters. The
require_whole_string argument specifies whether the regex is
automatically surrounded by "^" and "$" to match the whole
string. This is on by default because patterns always match
whole strings, but may be disabled to support concatenating
expressions more easily (regex1|regex2|etc). */
static kwsys_stl::string PatternToRegex(const kwsys_stl::string& pattern,
bool require_whole_string = true,
bool preserve_case = false);
protected:
//! Process directory
void ProcessDirectory(kwsys_stl::string::size_type start,
const kwsys_stl::string& dir);
//! Process last directory, but only when recurse flags is on. That is
// effectively like saying: /path/to/file/**/file
void RecurseDirectory(kwsys_stl::string::size_type start,
const kwsys_stl::string& dir);
//! Add regular expression
void AddExpression(const char* expr);
//! Add a file to the list
void AddFile(kwsys_stl::vector<kwsys_stl::string>& files, const char* file);
GlobInternals* Internals;
bool Recurse;
kwsys_stl::string Relative;
bool RecurseThroughSymlinks;
unsigned int FollowedSymlinkCount;
private:
Glob(const Glob&); // Not implemented.
void operator=(const Glob&); // Not implemented.
};
} // namespace @KWSYS_NAMESPACE@
/* Undefine temporary macro. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsys_stl
#endif
#endif

281
IOStream.cxx Normal file
View File

@ -0,0 +1,281 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Configure.hxx)
// Configure the implementation for the current streams library.
#if !KWSYS_IOS_USE_ANSI
# define ios_base ios
# if defined(__HP_aCC)
# define protected public
# include <iostream.h> // Hack access to some private stream methods.
# undef protected
# endif
#endif
// Include the streams library.
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(IOStream.hxx)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "Configure.hxx.in"
# include "kwsys_ios_iostream.hxx.in"
# include "IOStream.hxx.in"
#endif
// Implement the rest of this file only if it is needed.
#if KWSYS_IOS_NEED_OPERATORS_LL
# include <stdio.h> // sscanf, sprintf
# include <string.h> // memchr
# if defined(_MAX_INT_DIG)
# define KWSYS_IOS_INT64_MAX_DIG _MAX_INT_DIG
# else
# define KWSYS_IOS_INT64_MAX_DIG 32
# endif
namespace KWSYS_NAMESPACE
{
// Scan an input stream for an integer value.
static int IOStreamScanStream(kwsys_ios::istream& is, char* buffer)
{
// Prepare to write to buffer.
char* out = buffer;
char* end = buffer + KWSYS_IOS_INT64_MAX_DIG - 1;
// Look for leading sign.
if(is.peek() == '+') { *out++ = '+'; is.ignore(); }
else if(is.peek() == '-') { *out++ = '-'; is.ignore(); }
// Determine the base. If not specified in the stream, try to
// detect it from the input. A leading 0x means hex, and a leading
// 0 alone means octal.
int base = 0;
int flags = is.flags() & kwsys_ios::ios_base::basefield;
if(flags == kwsys_ios::ios_base::oct) { base = 8; }
else if(flags == kwsys_ios::ios_base::dec) { base = 10; }
else if(flags == kwsys_ios::ios_base::hex) { base = 16; }
bool foundDigit = false;
bool foundNonZero = false;
if(is.peek() == '0')
{
foundDigit = true;
is.ignore();
if((is.peek() == 'x' || is.peek() == 'X') && (base == 0 || base == 16))
{
base = 16;
foundDigit = false;
is.ignore();
}
else if (base == 0)
{
base = 8;
}
}
// Determine the range of digits allowed for this number.
const char* digits = "0123456789abcdefABCDEF";
int maxDigitIndex = 10;
if(base == 8)
{
maxDigitIndex = 8;
}
else if(base == 16)
{
maxDigitIndex = 10+6+6;
}
// Scan until an invalid digit is found.
for(;is.peek() != EOF; is.ignore())
{
if(memchr(digits, *out = (char)is.peek(), maxDigitIndex) != 0)
{
if((foundNonZero || *out != '0') && out < end)
{
++out;
foundNonZero = true;
}
foundDigit = true;
}
else
{
break;
}
}
// Correct the buffer contents for degenerate cases.
if(foundDigit && !foundNonZero)
{
*out++ = '0';
}
else if (!foundDigit)
{
out = buffer;
}
// Terminate the string in the buffer.
*out = '\0';
return base;
}
// Read an integer value from an input stream.
template <class T>
kwsys_ios::istream&
IOStreamScanTemplate(kwsys_ios::istream& is, T& value, char type)
{
int state = kwsys_ios::ios_base::goodbit;
// Skip leading whitespace.
# if KWSYS_IOS_USE_ANSI
kwsys_ios::istream::sentry okay(is);
# else
is.eatwhite();
kwsys_ios::istream& okay = is;
# endif
if(okay)
{
# if KWSYS_IOS_USE_ANSI
try {
# endif
// Copy the string to a buffer and construct the format string.
char buffer[KWSYS_IOS_INT64_MAX_DIG];
# if defined(_MSC_VER)
char format[] = "%I64_";
const int typeIndex = 4;
# else
char format[] = "%ll_";
const int typeIndex = 3;
# endif
switch(IOStreamScanStream(is, buffer))
{
case 8: format[typeIndex] = 'o'; break;
case 0: // Default to decimal if not told otherwise.
case 10: format[typeIndex] = type; break;
case 16: format[typeIndex] = 'x'; break;
};
// Use sscanf to parse the number from the buffer.
T result;
int success = (sscanf(buffer, format, &result) == 1)?1:0;
// Set flags for resulting state.
if(is.peek() == EOF) { state |= kwsys_ios::ios_base::eofbit; }
if(!success) { state |= kwsys_ios::ios_base::failbit; }
else { value = result; }
# if KWSYS_IOS_USE_ANSI
} catch(...) { state |= kwsys_ios::ios_base::badbit; }
# endif
}
# if KWSYS_IOS_USE_ANSI
is.setstate(kwsys_ios::ios_base::iostate(state));
# else
is.clear(state);
# endif
return is;
}
// Print an integer value to an output stream.
template <class T>
kwsys_ios::ostream&
IOStreamPrintTemplate(kwsys_ios::ostream& os, T value, char type)
{
# if KWSYS_IOS_USE_ANSI
kwsys_ios::ostream::sentry okay(os);
# else
kwsys_ios::ostream& okay = os;
# endif
if(okay)
{
# if KWSYS_IOS_USE_ANSI
try {
# endif
// Construct the format string.
char format[8];
char* f = format;
*f++ = '%';
if(os.flags() & kwsys_ios::ios_base::showpos) { *f++ = '+'; }
if(os.flags() & kwsys_ios::ios_base::showbase) { *f++ = '#'; }
# if defined(_MSC_VER)
*f++ = 'I'; *f++ = '6'; *f++ = '4';
# else
*f++ = 'l'; *f++ = 'l';
# endif
long bflags = os.flags() & kwsys_ios::ios_base::basefield;
if(bflags == kwsys_ios::ios_base::oct) { *f++ = 'o'; }
else if(bflags != kwsys_ios::ios_base::hex) { *f++ = type; }
else if(os.flags() & kwsys_ios::ios_base::uppercase) { *f++ = 'X'; }
else { *f++ = 'x'; }
*f = '\0';
// Use sprintf to print to a buffer and then write the
// buffer to the stream.
char buffer[2*KWSYS_IOS_INT64_MAX_DIG];
sprintf(buffer, format, value);
os << buffer;
# if KWSYS_IOS_USE_ANSI
} catch(...) { os.clear(os.rdstate() | kwsys_ios::ios_base::badbit); }
# endif
}
return os;
}
# if !KWSYS_IOS_HAS_ISTREAM_LONG_LONG
// Implement input stream operator for IOStreamSLL.
kwsys_ios::istream& IOStreamScan(kwsys_ios::istream& is, IOStreamSLL& value)
{
return IOStreamScanTemplate(is, value, 'd');
}
// Implement input stream operator for IOStreamULL.
kwsys_ios::istream& IOStreamScan(kwsys_ios::istream& is, IOStreamULL& value)
{
return IOStreamScanTemplate(is, value, 'u');
}
# endif
# if !KWSYS_IOS_HAS_OSTREAM_LONG_LONG
// Implement output stream operator for IOStreamSLL.
kwsys_ios::ostream& IOStreamPrint(kwsys_ios::ostream& os, IOStreamSLL value)
{
return IOStreamPrintTemplate(os, value, 'd');
}
// Implement output stream operator for IOStreamULL.
kwsys_ios::ostream& IOStreamPrint(kwsys_ios::ostream& os, IOStreamULL value)
{
return IOStreamPrintTemplate(os, value, 'u');
}
# endif
} // namespace KWSYS_NAMESPACE
#else
namespace KWSYS_NAMESPACE
{
// Create one public symbol in this object file to avoid warnings from
// archivers.
void IOStreamSymbolToAvoidWarning()
{
}
} // namespace KWSYS_NAMESPACE
#endif // KWSYS_IOS_NEED_OPERATORS_LL

146
IOStream.hxx.in Normal file
View File

@ -0,0 +1,146 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_IOStream_hxx
#define @KWSYS_NAMESPACE@_IOStream_hxx
#include <@KWSYS_NAMESPACE@/ios/iosfwd>
/* Define these macros temporarily to keep the code readable. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
# define kwsys_ios @KWSYS_NAMESPACE@_ios
#endif
/* Whether istream supports long long. */
#define @KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG @KWSYS_IOS_HAS_ISTREAM_LONG_LONG@
/* Whether ostream supports long long. */
#define @KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG @KWSYS_IOS_HAS_OSTREAM_LONG_LONG@
/* Size of type long long and 0 if not available. */
#define @KWSYS_NAMESPACE@_IOS_SIZEOF_LONG_LONG @KWSYS_SIZEOF_LONG_LONG@
/* Determine whether we need to define the streaming operators for
long long or __int64. */
#if @KWSYS_NAMESPACE@_IOS_SIZEOF_LONG_LONG
# if !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG || \
!@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 1
namespace @KWSYS_NAMESPACE@
{
typedef long long IOStreamSLL;
typedef unsigned long long IOStreamULL;
}
# endif
#elif defined(_MSC_VER) && _MSC_VER < 1300
# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 1
namespace @KWSYS_NAMESPACE@
{
typedef __int64 IOStreamSLL;
typedef unsigned __int64 IOStreamULL;
}
#endif
#if !defined(@KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL)
# define @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL 0
#endif
#if @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL
# if !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG
/* Input stream operator implementation functions. */
namespace @KWSYS_NAMESPACE@
{
kwsysEXPORT kwsys_ios::istream& IOStreamScan(kwsys_ios::istream&,
IOStreamSLL&);
kwsysEXPORT kwsys_ios::istream& IOStreamScan(kwsys_ios::istream&,
IOStreamULL&);
}
/* Provide input stream operator for long long. */
# if !defined(@KWSYS_NAMESPACE@_IOS_NO_ISTREAM_LONG_LONG) && \
!defined(KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED)
# define KWSYS_IOS_ISTREAM_LONG_LONG_DEFINED
# define @KWSYS_NAMESPACE@_IOS_ISTREAM_LONG_LONG_DEFINED
inline kwsys_ios::istream&
operator>>(kwsys_ios::istream& is, @KWSYS_NAMESPACE@::IOStreamSLL& value)
{
return @KWSYS_NAMESPACE@::IOStreamScan(is, value);
}
# endif
/* Provide input stream operator for unsigned long long. */
# if !defined(@KWSYS_NAMESPACE@_IOS_NO_ISTREAM_UNSIGNED_LONG_LONG) && \
!defined(KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED)
# define KWSYS_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
# define @KWSYS_NAMESPACE@_IOS_ISTREAM_UNSIGNED_LONG_LONG_DEFINED
inline kwsys_ios::istream&
operator>>(kwsys_ios::istream& is, @KWSYS_NAMESPACE@::IOStreamULL& value)
{
return @KWSYS_NAMESPACE@::IOStreamScan(is, value);
}
# endif
# endif /* !@KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG */
# if !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
/* Output stream operator implementation functions. */
namespace @KWSYS_NAMESPACE@
{
kwsysEXPORT kwsys_ios::ostream& IOStreamPrint(kwsys_ios::ostream&,
IOStreamSLL);
kwsysEXPORT kwsys_ios::ostream& IOStreamPrint(kwsys_ios::ostream&,
IOStreamULL);
}
/* Provide output stream operator for long long. */
# if !defined(@KWSYS_NAMESPACE@_IOS_NO_OSTREAM_LONG_LONG) && \
!defined(KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED)
# define KWSYS_IOS_OSTREAM_LONG_LONG_DEFINED
# define @KWSYS_NAMESPACE@_IOS_OSTREAM_LONG_LONG_DEFINED
inline kwsys_ios::ostream&
operator<<(kwsys_ios::ostream& os, @KWSYS_NAMESPACE@::IOStreamSLL value)
{
return @KWSYS_NAMESPACE@::IOStreamPrint(os, value);
}
# endif
/* Provide output stream operator for unsigned long long. */
# if !defined(@KWSYS_NAMESPACE@_IOS_NO_OSTREAM_UNSIGNED_LONG_LONG) && \
!defined(KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED)
# define KWSYS_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
# define @KWSYS_NAMESPACE@_IOS_OSTREAM_UNSIGNED_LONG_LONG_DEFINED
inline kwsys_ios::ostream&
operator<<(kwsys_ios::ostream& os, @KWSYS_NAMESPACE@::IOStreamULL value)
{
return @KWSYS_NAMESPACE@::IOStreamPrint(os, value);
}
# endif
# endif /* !@KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG */
#endif /* @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL */
/* Undefine temporary macros. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysEXPORT
# undef kwsys_ios
#endif
/* If building a C++ file in kwsys itself, give the source file
access to the macros without a configured namespace. */
#if defined(KWSYS_NAMESPACE)
# define KWSYS_IOS_SIZEOF_LONG_LONG @KWSYS_NAMESPACE@_IOS_SIZEOF_LONG_LONG
# define KWSYS_IOS_HAS_ISTREAM_LONG_LONG @KWSYS_NAMESPACE@_IOS_HAS_ISTREAM_LONG_LONG
# define KWSYS_IOS_HAS_OSTREAM_LONG_LONG @KWSYS_NAMESPACE@_IOS_HAS_OSTREAM_LONG_LONG
# define KWSYS_IOS_NEED_OPERATORS_LL @KWSYS_NAMESPACE@_IOS_NEED_OPERATORS_LL
#endif
#endif

518
MD5.c Normal file
View File

@ -0,0 +1,518 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(MD5.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "MD5.h.in"
#endif
#include <stddef.h> /* size_t */
#include <stdlib.h> /* malloc, free */
#include <string.h> /* memcpy, strlen */
/*--------------------------------------------------------------------------*/
/* This MD5 implementation has been taken from a third party. Slight
modifications to the arrangement of the code have been made to put
it in a single source file instead of a separate header and
implementation file. */
#if defined(__clang__)
# pragma clang diagnostic push
# pragma clang diagnostic ignored "-Wcast-align"
#endif
/*
Copyright (C) 1999, 2000, 2002 Aladdin Enterprises. All rights reserved.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
L. Peter Deutsch
ghost@aladdin.com
*/
/*
Independent implementation of MD5 (RFC 1321).
This code implements the MD5 Algorithm defined in RFC 1321, whose
text is available at
http://www.ietf.org/rfc/rfc1321.txt
The code is derived from the text of the RFC, including the test suite
(section A.5) but excluding the rest of Appendix A. It does not include
any code or documentation that is identified in the RFC as being
copyrighted.
The original and principal author of md5.c is L. Peter Deutsch
<ghost@aladdin.com>. Other authors are noted in the change history
that follows (in reverse chronological order):
2002-04-13 lpd Clarified derivation from RFC 1321; now handles byte order
either statically or dynamically; added missing #include <string.h>
in library.
2002-03-11 lpd Corrected argument list for main(), and added int return
type, in test program and T value program.
2002-02-21 lpd Added missing #include <stdio.h> in test program.
2000-07-03 lpd Patched to eliminate warnings about "constant is
unsigned in ANSI C, signed in traditional"; made test program
self-checking.
1999-11-04 lpd Edited comments slightly for automatic TOC extraction.
1999-10-18 lpd Fixed typo in header comment (ansi2knr rather than md5).
1999-05-03 lpd Original version.
*/
/*
* This package supports both compile-time and run-time determination of CPU
* byte order. If ARCH_IS_BIG_ENDIAN is defined as 0, the code will be
* compiled to run only on little-endian CPUs; if ARCH_IS_BIG_ENDIAN is
* defined as non-zero, the code will be compiled to run only on big-endian
* CPUs; if ARCH_IS_BIG_ENDIAN is not defined, the code will be compiled to
* run on either big- or little-endian CPUs, but will run slightly less
* efficiently on either one than if ARCH_IS_BIG_ENDIAN is defined.
*/
typedef unsigned char md5_byte_t; /* 8-bit byte */
typedef unsigned int md5_word_t; /* 32-bit word */
/* Define the state of the MD5 Algorithm. */
typedef struct md5_state_s {
md5_word_t count[2]; /* message length in bits, lsw first */
md5_word_t abcd[4]; /* digest buffer */
md5_byte_t buf[64]; /* accumulate block */
} md5_state_t;
#undef BYTE_ORDER /* 1 = big-endian, -1 = little-endian, 0 = unknown */
#ifdef ARCH_IS_BIG_ENDIAN
# define BYTE_ORDER (ARCH_IS_BIG_ENDIAN ? 1 : -1)
#else
# define BYTE_ORDER 0
#endif
#define T_MASK ((md5_word_t)~0)
#define T1 /* 0xd76aa478 */ (T_MASK ^ 0x28955b87)
#define T2 /* 0xe8c7b756 */ (T_MASK ^ 0x173848a9)
#define T3 0x242070db
#define T4 /* 0xc1bdceee */ (T_MASK ^ 0x3e423111)
#define T5 /* 0xf57c0faf */ (T_MASK ^ 0x0a83f050)
#define T6 0x4787c62a
#define T7 /* 0xa8304613 */ (T_MASK ^ 0x57cfb9ec)
#define T8 /* 0xfd469501 */ (T_MASK ^ 0x02b96afe)
#define T9 0x698098d8
#define T10 /* 0x8b44f7af */ (T_MASK ^ 0x74bb0850)
#define T11 /* 0xffff5bb1 */ (T_MASK ^ 0x0000a44e)
#define T12 /* 0x895cd7be */ (T_MASK ^ 0x76a32841)
#define T13 0x6b901122
#define T14 /* 0xfd987193 */ (T_MASK ^ 0x02678e6c)
#define T15 /* 0xa679438e */ (T_MASK ^ 0x5986bc71)
#define T16 0x49b40821
#define T17 /* 0xf61e2562 */ (T_MASK ^ 0x09e1da9d)
#define T18 /* 0xc040b340 */ (T_MASK ^ 0x3fbf4cbf)
#define T19 0x265e5a51
#define T20 /* 0xe9b6c7aa */ (T_MASK ^ 0x16493855)
#define T21 /* 0xd62f105d */ (T_MASK ^ 0x29d0efa2)
#define T22 0x02441453
#define T23 /* 0xd8a1e681 */ (T_MASK ^ 0x275e197e)
#define T24 /* 0xe7d3fbc8 */ (T_MASK ^ 0x182c0437)
#define T25 0x21e1cde6
#define T26 /* 0xc33707d6 */ (T_MASK ^ 0x3cc8f829)
#define T27 /* 0xf4d50d87 */ (T_MASK ^ 0x0b2af278)
#define T28 0x455a14ed
#define T29 /* 0xa9e3e905 */ (T_MASK ^ 0x561c16fa)
#define T30 /* 0xfcefa3f8 */ (T_MASK ^ 0x03105c07)
#define T31 0x676f02d9
#define T32 /* 0x8d2a4c8a */ (T_MASK ^ 0x72d5b375)
#define T33 /* 0xfffa3942 */ (T_MASK ^ 0x0005c6bd)
#define T34 /* 0x8771f681 */ (T_MASK ^ 0x788e097e)
#define T35 0x6d9d6122
#define T36 /* 0xfde5380c */ (T_MASK ^ 0x021ac7f3)
#define T37 /* 0xa4beea44 */ (T_MASK ^ 0x5b4115bb)
#define T38 0x4bdecfa9
#define T39 /* 0xf6bb4b60 */ (T_MASK ^ 0x0944b49f)
#define T40 /* 0xbebfbc70 */ (T_MASK ^ 0x4140438f)
#define T41 0x289b7ec6
#define T42 /* 0xeaa127fa */ (T_MASK ^ 0x155ed805)
#define T43 /* 0xd4ef3085 */ (T_MASK ^ 0x2b10cf7a)
#define T44 0x04881d05
#define T45 /* 0xd9d4d039 */ (T_MASK ^ 0x262b2fc6)
#define T46 /* 0xe6db99e5 */ (T_MASK ^ 0x1924661a)
#define T47 0x1fa27cf8
#define T48 /* 0xc4ac5665 */ (T_MASK ^ 0x3b53a99a)
#define T49 /* 0xf4292244 */ (T_MASK ^ 0x0bd6ddbb)
#define T50 0x432aff97
#define T51 /* 0xab9423a7 */ (T_MASK ^ 0x546bdc58)
#define T52 /* 0xfc93a039 */ (T_MASK ^ 0x036c5fc6)
#define T53 0x655b59c3
#define T54 /* 0x8f0ccc92 */ (T_MASK ^ 0x70f3336d)
#define T55 /* 0xffeff47d */ (T_MASK ^ 0x00100b82)
#define T56 /* 0x85845dd1 */ (T_MASK ^ 0x7a7ba22e)
#define T57 0x6fa87e4f
#define T58 /* 0xfe2ce6e0 */ (T_MASK ^ 0x01d3191f)
#define T59 /* 0xa3014314 */ (T_MASK ^ 0x5cfebceb)
#define T60 0x4e0811a1
#define T61 /* 0xf7537e82 */ (T_MASK ^ 0x08ac817d)
#define T62 /* 0xbd3af235 */ (T_MASK ^ 0x42c50dca)
#define T63 0x2ad7d2bb
#define T64 /* 0xeb86d391 */ (T_MASK ^ 0x14792c6e)
static void
md5_process(md5_state_t *pms, const md5_byte_t *data /*[64]*/)
{
md5_word_t
a = pms->abcd[0], b = pms->abcd[1],
c = pms->abcd[2], d = pms->abcd[3];
md5_word_t t;
#if BYTE_ORDER > 0
/* Define storage only for big-endian CPUs. */
md5_word_t X[16];
#else
/* Define storage for little-endian or both types of CPUs. */
md5_word_t xbuf[16];
const md5_word_t *X;
#endif
{
#if BYTE_ORDER == 0
/*
* Determine dynamically whether this is a big-endian or
* little-endian machine, since we can use a more efficient
* algorithm on the latter.
*/
static const int w = 1;
if (*((const md5_byte_t *)&w)) /* dynamic little-endian */
#endif
#if BYTE_ORDER <= 0 /* little-endian */
{
/*
* On little-endian machines, we can process properly aligned
* data without copying it.
*/
if (!((data - (const md5_byte_t *)0) & 3)) {
/* data are properly aligned */
X = (const md5_word_t *)data;
} else {
/* not aligned */
memcpy(xbuf, data, 64);
X = xbuf;
}
}
#endif
#if BYTE_ORDER == 0
else /* dynamic big-endian */
#endif
#if BYTE_ORDER >= 0 /* big-endian */
{
/*
* On big-endian machines, we must arrange the bytes in the
* right order.
*/
const md5_byte_t *xp = data;
int i;
# if BYTE_ORDER == 0
X = xbuf; /* (dynamic only) */
# else
# define xbuf X /* (static only) */
# endif
for (i = 0; i < 16; ++i, xp += 4)
xbuf[i] = (md5_word_t)(xp[0] + (xp[1] << 8) +
(xp[2] << 16) + (xp[3] << 24));
}
#endif
}
#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n))))
/* Round 1. */
/* Let [abcd k s i] denote the operation
a = b + ((a + F(b,c,d) + X[k] + T[i]) <<< s). */
#define F(x, y, z) (((x) & (y)) | (~(x) & (z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + F(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 7, T1);
SET(d, a, b, c, 1, 12, T2);
SET(c, d, a, b, 2, 17, T3);
SET(b, c, d, a, 3, 22, T4);
SET(a, b, c, d, 4, 7, T5);
SET(d, a, b, c, 5, 12, T6);
SET(c, d, a, b, 6, 17, T7);
SET(b, c, d, a, 7, 22, T8);
SET(a, b, c, d, 8, 7, T9);
SET(d, a, b, c, 9, 12, T10);
SET(c, d, a, b, 10, 17, T11);
SET(b, c, d, a, 11, 22, T12);
SET(a, b, c, d, 12, 7, T13);
SET(d, a, b, c, 13, 12, T14);
SET(c, d, a, b, 14, 17, T15);
SET(b, c, d, a, 15, 22, T16);
#undef SET
/* Round 2. */
/* Let [abcd k s i] denote the operation
a = b + ((a + G(b,c,d) + X[k] + T[i]) <<< s). */
#define G(x, y, z) (((x) & (z)) | ((y) & ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + G(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 1, 5, T17);
SET(d, a, b, c, 6, 9, T18);
SET(c, d, a, b, 11, 14, T19);
SET(b, c, d, a, 0, 20, T20);
SET(a, b, c, d, 5, 5, T21);
SET(d, a, b, c, 10, 9, T22);
SET(c, d, a, b, 15, 14, T23);
SET(b, c, d, a, 4, 20, T24);
SET(a, b, c, d, 9, 5, T25);
SET(d, a, b, c, 14, 9, T26);
SET(c, d, a, b, 3, 14, T27);
SET(b, c, d, a, 8, 20, T28);
SET(a, b, c, d, 13, 5, T29);
SET(d, a, b, c, 2, 9, T30);
SET(c, d, a, b, 7, 14, T31);
SET(b, c, d, a, 12, 20, T32);
#undef SET
/* Round 3. */
/* Let [abcd k s t] denote the operation
a = b + ((a + H(b,c,d) + X[k] + T[i]) <<< s). */
#define H(x, y, z) ((x) ^ (y) ^ (z))
#define SET(a, b, c, d, k, s, Ti)\
t = a + H(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 5, 4, T33);
SET(d, a, b, c, 8, 11, T34);
SET(c, d, a, b, 11, 16, T35);
SET(b, c, d, a, 14, 23, T36);
SET(a, b, c, d, 1, 4, T37);
SET(d, a, b, c, 4, 11, T38);
SET(c, d, a, b, 7, 16, T39);
SET(b, c, d, a, 10, 23, T40);
SET(a, b, c, d, 13, 4, T41);
SET(d, a, b, c, 0, 11, T42);
SET(c, d, a, b, 3, 16, T43);
SET(b, c, d, a, 6, 23, T44);
SET(a, b, c, d, 9, 4, T45);
SET(d, a, b, c, 12, 11, T46);
SET(c, d, a, b, 15, 16, T47);
SET(b, c, d, a, 2, 23, T48);
#undef SET
/* Round 4. */
/* Let [abcd k s t] denote the operation
a = b + ((a + I(b,c,d) + X[k] + T[i]) <<< s). */
#define I(x, y, z) ((y) ^ ((x) | ~(z)))
#define SET(a, b, c, d, k, s, Ti)\
t = a + I(b,c,d) + X[k] + Ti;\
a = ROTATE_LEFT(t, s) + b
/* Do the following 16 operations. */
SET(a, b, c, d, 0, 6, T49);
SET(d, a, b, c, 7, 10, T50);
SET(c, d, a, b, 14, 15, T51);
SET(b, c, d, a, 5, 21, T52);
SET(a, b, c, d, 12, 6, T53);
SET(d, a, b, c, 3, 10, T54);
SET(c, d, a, b, 10, 15, T55);
SET(b, c, d, a, 1, 21, T56);
SET(a, b, c, d, 8, 6, T57);
SET(d, a, b, c, 15, 10, T58);
SET(c, d, a, b, 6, 15, T59);
SET(b, c, d, a, 13, 21, T60);
SET(a, b, c, d, 4, 6, T61);
SET(d, a, b, c, 11, 10, T62);
SET(c, d, a, b, 2, 15, T63);
SET(b, c, d, a, 9, 21, T64);
#undef SET
/* Then perform the following additions. (That is increment each
of the four registers by the value it had before this block
was started.) */
pms->abcd[0] += a;
pms->abcd[1] += b;
pms->abcd[2] += c;
pms->abcd[3] += d;
}
/* Initialize the algorithm. */
static void md5_init(md5_state_t *pms)
{
pms->count[0] = pms->count[1] = 0;
pms->abcd[0] = 0x67452301;
pms->abcd[1] = /*0xefcdab89*/ T_MASK ^ 0x10325476;
pms->abcd[2] = /*0x98badcfe*/ T_MASK ^ 0x67452301;
pms->abcd[3] = 0x10325476;
}
/* Append a string to the message. */
static void md5_append(md5_state_t *pms, const md5_byte_t *data, size_t nbytes)
{
const md5_byte_t *p = data;
size_t left = nbytes;
size_t offset = (pms->count[0] >> 3) & 63;
md5_word_t nbits = (md5_word_t)(nbytes << 3);
if (nbytes <= 0)
return;
/* Update the message length. */
pms->count[1] += (md5_word_t)(nbytes >> 29);
pms->count[0] += nbits;
if (pms->count[0] < nbits)
pms->count[1]++;
/* Process an initial partial block. */
if (offset) {
size_t copy = (offset + nbytes > 64 ? 64 - offset : nbytes);
memcpy(pms->buf + offset, p, copy);
if (offset + copy < 64)
return;
p += copy;
left -= copy;
md5_process(pms, pms->buf);
}
/* Process full blocks. */
for (; left >= 64; p += 64, left -= 64)
md5_process(pms, p);
/* Process a final partial block. */
if (left)
memcpy(pms->buf, p, left);
}
/* Finish the message and return the digest. */
static void md5_finish(md5_state_t *pms, md5_byte_t digest[16])
{
static const md5_byte_t pad[64] = {
0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
};
md5_byte_t data[8];
int i;
/* Save the length before padding. */
for (i = 0; i < 8; ++i)
data[i] = (md5_byte_t)(pms->count[i >> 2] >> ((i & 3) << 3));
/* Pad to 56 bytes mod 64. */
md5_append(pms, pad, ((55 - (pms->count[0] >> 3)) & 63) + 1);
/* Append the length. */
md5_append(pms, data, 8);
for (i = 0; i < 16; ++i)
digest[i] = (md5_byte_t)(pms->abcd[i >> 2] >> ((i & 3) << 3));
}
#if defined(__clang__)
# pragma clang diagnostic pop
#endif
/*--------------------------------------------------------------------------*/
/* Wrap up the MD5 state in our opaque structure. */
struct kwsysMD5_s
{
md5_state_t md5_state;
};
/*--------------------------------------------------------------------------*/
kwsysMD5* kwsysMD5_New(void)
{
/* Allocate a process control structure. */
kwsysMD5* md5 = (kwsysMD5*)malloc(sizeof(kwsysMD5));
if(!md5)
{
return 0;
}
return md5;
}
/*--------------------------------------------------------------------------*/
void kwsysMD5_Delete(kwsysMD5* md5)
{
/* Make sure we have an instance. */
if(!md5)
{
return;
}
/* Free memory. */
free(md5);
}
/*--------------------------------------------------------------------------*/
void kwsysMD5_Initialize(kwsysMD5* md5)
{
md5_init(&md5->md5_state);
}
/*--------------------------------------------------------------------------*/
void kwsysMD5_Append(kwsysMD5* md5, unsigned char const* data, int length)
{
if(length < 0)
{
length = (int)strlen((char const*)data);
}
md5_append(&md5->md5_state, (md5_byte_t const*)data, (size_t)length);
}
/*--------------------------------------------------------------------------*/
void kwsysMD5_Finalize(kwsysMD5* md5, unsigned char digest[16])
{
md5_finish(&md5->md5_state, (md5_byte_t*)digest);
}
/*--------------------------------------------------------------------------*/
void kwsysMD5_FinalizeHex(kwsysMD5* md5, char buffer[32])
{
unsigned char digest[16];
kwsysMD5_Finalize(md5, digest);
kwsysMD5_DigestToHex(digest, buffer);
}
/*--------------------------------------------------------------------------*/
void kwsysMD5_DigestToHex(unsigned char const digest[16], char buffer[32])
{
/* Map from 4-bit index to hexadecimal representation. */
static char const hex[16] =
{'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/* Map each 4-bit block separately. */
char* out = buffer;
int i;
for(i=0; i < 16; ++i)
{
*out++ = hex[digest[i] >> 4];
*out++ = hex[digest[i] & 0xF];
}
}

107
MD5.h.in Normal file
View File

@ -0,0 +1,107 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_MD5_h
#define @KWSYS_NAMESPACE@_MD5_h
#include <@KWSYS_NAMESPACE@/Configure.h>
/* Redefine all public interface symbol names to be in the proper
namespace. These macros are used internally to kwsys only, and are
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysMD5 kwsys_ns(MD5)
# define kwsysMD5_s kwsys_ns(MD5_s)
# define kwsysMD5_New kwsys_ns(MD5_New)
# define kwsysMD5_Delete kwsys_ns(MD5_Delete)
# define kwsysMD5_Initialize kwsys_ns(MD5_Initialize)
# define kwsysMD5_Append kwsys_ns(MD5_Append)
# define kwsysMD5_Finalize kwsys_ns(MD5_Finalize)
# define kwsysMD5_FinalizeHex kwsys_ns(MD5_FinalizeHex)
# define kwsysMD5_DigestToHex kwsys_ns(MD5_DigestToHex)
#endif
#if defined(__cplusplus)
extern "C"
{
#endif
/**
* MD5 state data structure.
*/
typedef struct kwsysMD5_s kwsysMD5;
/**
* Create a new MD5 instance. The returned instance is not initialized.
*/
kwsysEXPORT kwsysMD5* kwsysMD5_New(void);
/**
* Delete an old MD5 instance.
*/
kwsysEXPORT void kwsysMD5_Delete(kwsysMD5* md5);
/**
* Initialize a new MD5 digest.
*/
kwsysEXPORT void kwsysMD5_Initialize(kwsysMD5* md5);
/**
* Append data to an MD5 digest. If the given length is negative,
* data will be read up to but not including a terminating null.
*/
kwsysEXPORT void kwsysMD5_Append(kwsysMD5* md5, unsigned char const* data,
int length);
/**
* Finalize a MD5 digest and get the 16-byte hash value.
*/
kwsysEXPORT void kwsysMD5_Finalize(kwsysMD5* md5, unsigned char digest[16]);
/**
* Finalize a MD5 digest and get the 32-bit hexadecimal representation.
*/
kwsysEXPORT void kwsysMD5_FinalizeHex(kwsysMD5* md5, char buffer[32]);
/**
* Convert a MD5 digest 16-byte value to a 32-byte hexadecimal representation.
*/
kwsysEXPORT void kwsysMD5_DigestToHex(unsigned char const digest[16],
char buffer[32]);
#if defined(__cplusplus)
} /* extern "C" */
#endif
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
# undef kwsys_ns
# undef kwsysEXPORT
# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysMD5
# undef kwsysMD5_s
# undef kwsysMD5_New
# undef kwsysMD5_Delete
# undef kwsysMD5_Initialize
# undef kwsysMD5_Append
# undef kwsysMD5_Finalize
# undef kwsysMD5_FinalizeHex
# undef kwsysMD5_DigestToHex
# endif
#endif
#endif

428
Process.h.in Normal file
View File

@ -0,0 +1,428 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_Process_h
#define @KWSYS_NAMESPACE@_Process_h
#include <@KWSYS_NAMESPACE@/Configure.h>
/* Redefine all public interface symbol names to be in the proper
namespace. These macros are used internally to kwsys only, and are
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysProcess kwsys_ns(Process)
# define kwsysProcess_s kwsys_ns(Process_s)
# define kwsysProcess_New kwsys_ns(Process_New)
# define kwsysProcess_Delete kwsys_ns(Process_Delete)
# define kwsysProcess_SetCommand kwsys_ns(Process_SetCommand)
# define kwsysProcess_AddCommand kwsys_ns(Process_AddCommand)
# define kwsysProcess_SetTimeout kwsys_ns(Process_SetTimeout)
# define kwsysProcess_SetWorkingDirectory kwsys_ns(Process_SetWorkingDirectory)
# define kwsysProcess_SetPipeFile kwsys_ns(Process_SetPipeFile)
# define kwsysProcess_SetPipeNative kwsys_ns(Process_SetPipeNative)
# define kwsysProcess_SetPipeShared kwsys_ns(Process_SetPipeShared)
# define kwsysProcess_Option_Detach kwsys_ns(Process_Option_Detach)
# define kwsysProcess_Option_HideWindow kwsys_ns(Process_Option_HideWindow)
# define kwsysProcess_Option_Verbatim kwsys_ns(Process_Option_Verbatim)
# define kwsysProcess_GetOption kwsys_ns(Process_GetOption)
# define kwsysProcess_SetOption kwsys_ns(Process_SetOption)
# define kwsysProcess_Option_e kwsys_ns(Process_Option_e)
# define kwsysProcess_State_Starting kwsys_ns(Process_State_Starting)
# define kwsysProcess_State_Error kwsys_ns(Process_State_Error)
# define kwsysProcess_State_Exception kwsys_ns(Process_State_Exception)
# define kwsysProcess_State_Executing kwsys_ns(Process_State_Executing)
# define kwsysProcess_State_Exited kwsys_ns(Process_State_Exited)
# define kwsysProcess_State_Expired kwsys_ns(Process_State_Expired)
# define kwsysProcess_State_Killed kwsys_ns(Process_State_Killed)
# define kwsysProcess_State_Disowned kwsys_ns(Process_State_Disowned)
# define kwsysProcess_GetState kwsys_ns(Process_GetState)
# define kwsysProcess_State_e kwsys_ns(Process_State_e)
# define kwsysProcess_Exception_None kwsys_ns(Process_Exception_None)
# define kwsysProcess_Exception_Fault kwsys_ns(Process_Exception_Fault)
# define kwsysProcess_Exception_Illegal kwsys_ns(Process_Exception_Illegal)
# define kwsysProcess_Exception_Interrupt kwsys_ns(Process_Exception_Interrupt)
# define kwsysProcess_Exception_Numerical kwsys_ns(Process_Exception_Numerical)
# define kwsysProcess_Exception_Other kwsys_ns(Process_Exception_Other)
# define kwsysProcess_GetExitException kwsys_ns(Process_GetExitException)
# define kwsysProcess_Exception_e kwsys_ns(Process_Exception_e)
# define kwsysProcess_GetExitCode kwsys_ns(Process_GetExitCode)
# define kwsysProcess_GetExitValue kwsys_ns(Process_GetExitValue)
# define kwsysProcess_GetErrorString kwsys_ns(Process_GetErrorString)
# define kwsysProcess_GetExceptionString kwsys_ns(Process_GetExceptionString)
# define kwsysProcess_Execute kwsys_ns(Process_Execute)
# define kwsysProcess_Disown kwsys_ns(Process_Disown)
# define kwsysProcess_WaitForData kwsys_ns(Process_WaitForData)
# define kwsysProcess_Pipes_e kwsys_ns(Process_Pipes_e)
# define kwsysProcess_Pipe_None kwsys_ns(Process_Pipe_None)
# define kwsysProcess_Pipe_STDIN kwsys_ns(Process_Pipe_STDIN)
# define kwsysProcess_Pipe_STDOUT kwsys_ns(Process_Pipe_STDOUT)
# define kwsysProcess_Pipe_STDERR kwsys_ns(Process_Pipe_STDERR)
# define kwsysProcess_Pipe_Timeout kwsys_ns(Process_Pipe_Timeout)
# define kwsysProcess_Pipe_Handle kwsys_ns(Process_Pipe_Handle)
# define kwsysProcess_WaitForExit kwsys_ns(Process_WaitForExit)
# define kwsysProcess_Kill kwsys_ns(Process_Kill)
#endif
#if defined(__cplusplus)
extern "C"
{
#endif
/**
* Process control data structure.
*/
typedef struct kwsysProcess_s kwsysProcess;
/* Platform-specific pipe handle type. */
#if defined(_WIN32) && !defined(__CYGWIN__)
typedef void* kwsysProcess_Pipe_Handle;
#else
typedef int kwsysProcess_Pipe_Handle;
#endif
/**
* Create a new Process instance.
*/
kwsysEXPORT kwsysProcess* kwsysProcess_New(void);
/**
* Delete an existing Process instance. If the instance is currently
* executing a process, this blocks until the process terminates.
*/
kwsysEXPORT void kwsysProcess_Delete(kwsysProcess* cp);
/**
* Set the command line to be executed. Argument is an array of
* pointers to the command and each argument. The array must end with
* a NULL pointer. Any previous command lines are removed. Returns
* 1 for success and 0 otherwise.
*/
kwsysEXPORT int kwsysProcess_SetCommand(kwsysProcess* cp,
char const* const* command);
/**
* Add a command line to be executed. Argument is an array of
* pointers to the command and each argument. The array must end with
* a NULL pointer. If this is not the first command added, its
* standard input will be connected to the standard output of the
* previous command. Returns 1 for success and 0 otherwise.
*/
kwsysEXPORT int kwsysProcess_AddCommand(kwsysProcess* cp,
char const* const* command);
/**
* Set the timeout in seconds for the child process. The timeout
* period begins when the child is executed. If the child has not
* terminated when the timeout expires, it will be killed. A
* non-positive (<= 0) value will disable the timeout.
*/
kwsysEXPORT void kwsysProcess_SetTimeout(kwsysProcess* cp, double timeout);
/**
* Set the working directory for the child process. The working
* directory can be absolute or relative to the current directory.
* Returns 1 for success and 0 for failure.
*/
kwsysEXPORT int kwsysProcess_SetWorkingDirectory(kwsysProcess* cp,
const char* dir);
/**
* Set the name of a file to be attached to the given pipe. Returns 1
* for success and 0 for failure.
*/
kwsysEXPORT int kwsysProcess_SetPipeFile(kwsysProcess* cp, int pipe,
const char* file);
/**
* Set whether the given pipe in the child is shared with the parent
* process. The default is no for Pipe_STDOUT and Pipe_STDERR and yes
* for Pipe_STDIN.
*/
kwsysEXPORT void kwsysProcess_SetPipeShared(kwsysProcess* cp, int pipe,
int shared);
/**
* Specify a platform-specific native pipe for use as one of the child
* interface pipes. The native pipe is specified by an array of two
* descriptors or handles. The first entry in the array (index 0)
* should be the read end of the pipe. The second entry in the array
* (index 1) should be the write end of the pipe. If a null pointer
* is given the option will be disabled.
*
* For Pipe_STDIN the native pipe is connected to the first child in
* the pipeline as its stdin. After the children are created the
* write end of the pipe will be closed in the child process and the
* read end will be closed in the parent process.
*
* For Pipe_STDOUT and Pipe_STDERR the pipe is connected to the last
* child as its stdout or stderr. After the children are created the
* write end of the pipe will be closed in the parent process and the
* read end will be closed in the child process.
*/
kwsysEXPORT void kwsysProcess_SetPipeNative(kwsysProcess* cp, int pipe,
kwsysProcess_Pipe_Handle p[2]);
/**
* Get/Set a possibly platform-specific option. Possible options are:
*
* kwsysProcess_Option_Detach = Whether to detach the process.
* 0 = No (default)
* 1 = Yes
*
* kwsysProcess_Option_HideWindow = Whether to hide window on Windows.
* 0 = No (default)
* 1 = Yes
*
* kwsysProcess_Option_Verbatim = Whether SetCommand and AddCommand
* should treat the first argument
* as a verbatim command line
* and ignore the rest of the arguments.
* 0 = No (default)
* 1 = Yes
*/
kwsysEXPORT int kwsysProcess_GetOption(kwsysProcess* cp, int optionId);
kwsysEXPORT void kwsysProcess_SetOption(kwsysProcess* cp, int optionId,
int value);
enum kwsysProcess_Option_e
{
kwsysProcess_Option_HideWindow,
kwsysProcess_Option_Detach,
kwsysProcess_Option_Verbatim
};
/**
* Get the current state of the Process instance. Possible states are:
*
* kwsysProcess_State_Starting = Execute has not yet been called.
* kwsysProcess_State_Error = Error administrating the child process.
* kwsysProcess_State_Exception = Child process exited abnormally.
* kwsysProcess_State_Executing = Child process is currently running.
* kwsysProcess_State_Exited = Child process exited normally.
* kwsysProcess_State_Expired = Child process's timeout expired.
* kwsysProcess_State_Killed = Child process terminated by Kill method.
* kwsysProcess_State_Disowned = Child is no longer managed by this object.
*/
kwsysEXPORT int kwsysProcess_GetState(kwsysProcess* cp);
enum kwsysProcess_State_e
{
kwsysProcess_State_Starting,
kwsysProcess_State_Error,
kwsysProcess_State_Exception,
kwsysProcess_State_Executing,
kwsysProcess_State_Exited,
kwsysProcess_State_Expired,
kwsysProcess_State_Killed,
kwsysProcess_State_Disowned
};
/**
* When GetState returns "Exception", this method returns a
* platform-independent description of the exceptional behavior that
* caused the child to terminate abnormally. Possible exceptions are:
*
* kwsysProcess_Exception_None = No exceptional behavior occurred.
* kwsysProcess_Exception_Fault = Child crashed with a memory fault.
* kwsysProcess_Exception_Illegal = Child crashed with an illegal instruction.
* kwsysProcess_Exception_Interrupt = Child was interrupted by user (Cntl-C/Break).
* kwsysProcess_Exception_Numerical = Child crashed with a numerical exception.
* kwsysProcess_Exception_Other = Child terminated for another reason.
*/
kwsysEXPORT int kwsysProcess_GetExitException(kwsysProcess* cp);
enum kwsysProcess_Exception_e
{
kwsysProcess_Exception_None,
kwsysProcess_Exception_Fault,
kwsysProcess_Exception_Illegal,
kwsysProcess_Exception_Interrupt,
kwsysProcess_Exception_Numerical,
kwsysProcess_Exception_Other
};
/**
* When GetState returns "Exited" or "Exception", this method returns
* the platform-specific raw exit code of the process. UNIX platforms
* should use WIFEXITED/WEXITSTATUS and WIFSIGNALED/WTERMSIG to access
* this value. Windows users should compare the value to the various
* EXCEPTION_* values.
*
* If GetState returns "Exited", use GetExitValue to get the
* platform-independent child return value.
*/
kwsysEXPORT int kwsysProcess_GetExitCode(kwsysProcess* cp);
/**
* When GetState returns "Exited", this method returns the child's
* platform-independent exit code (such as the value returned by the
* child's main).
*/
kwsysEXPORT int kwsysProcess_GetExitValue(kwsysProcess* cp);
/**
* When GetState returns "Error", this method returns a string
* describing the problem. Otherwise, it returns NULL.
*/
kwsysEXPORT const char* kwsysProcess_GetErrorString(kwsysProcess* cp);
/**
* When GetState returns "Exception", this method returns a string
* describing the problem. Otherwise, it returns NULL.
*/
kwsysEXPORT const char* kwsysProcess_GetExceptionString(kwsysProcess* cp);
/**
* Start executing the child process.
*/
kwsysEXPORT void kwsysProcess_Execute(kwsysProcess* cp);
/**
* Stop management of a detached child process. This closes any pipes
* being read. If the child was not created with the
* kwsysProcess_Option_Detach option, this method does nothing. This
* is because disowning a non-detached process will cause the child
* exit signal to be left unhandled until this process exits.
*/
kwsysEXPORT void kwsysProcess_Disown(kwsysProcess* cp);
/**
* Block until data are available on a pipe, a timeout expires, or the
* child process terminates. Arguments are as follows:
*
* data = If data are read, the pointer to which this points is
* set to point to the data.
* length = If data are read, the integer to which this points is
* set to the length of the data read.
* timeout = Specifies the maximum time this call may block. Upon
* return after reading data, the time elapsed is subtracted
* from the timeout value. If this timeout expires, the
* value is set to 0. A NULL pointer passed for this argument
* indicates no timeout for the call. A negative or zero
* value passed for this argument may be used for polling
* and will always return immediately.
*
* Return value will be one of:
*
* Pipe_None = No more data will be available from the child process,
* ( == 0) or no process has been executed. WaitForExit should
* be called to wait for the process to terminate.
* Pipe_STDOUT = Data have been read from the child's stdout pipe.
* Pipe_STDERR = Data have been read from the child's stderr pipe.
* Pipe_Timeout = No data available within timeout specified for the
* call. Time elapsed has been subtracted from timeout
* argument.
*/
kwsysEXPORT int kwsysProcess_WaitForData(kwsysProcess* cp, char** data,
int* length, double* timeout);
enum kwsysProcess_Pipes_e
{
kwsysProcess_Pipe_None,
kwsysProcess_Pipe_STDIN,
kwsysProcess_Pipe_STDOUT,
kwsysProcess_Pipe_STDERR,
kwsysProcess_Pipe_Timeout=255
};
/**
* Block until the child process terminates or the given timeout
* expires. If no process is running, returns immediatly. The
* argument is:
*
* timeout = Specifies the maximum time this call may block. Upon
* returning due to child termination, the elapsed time
* is subtracted from the given value. A NULL pointer
* passed for this argument indicates no timeout for the
* call.
*
* Return value will be one of:
*
* 0 = Child did not terminate within timeout specified for
* the call. Time elapsed has been subtracted from timeout
* argument.
* 1 = Child has terminated or was not running.
*/
kwsysEXPORT int kwsysProcess_WaitForExit(kwsysProcess* cp, double* timeout);
/**
* Forcefully terminate the child process that is currently running.
* The caller should call WaitForExit after this returns to wait for
* the child to terminate.
*/
kwsysEXPORT void kwsysProcess_Kill(kwsysProcess* cp);
#if defined(__cplusplus)
} /* extern "C" */
#endif
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
# undef kwsys_ns
# undef kwsysEXPORT
# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysProcess
# undef kwsysProcess_s
# undef kwsysProcess_New
# undef kwsysProcess_Delete
# undef kwsysProcess_SetCommand
# undef kwsysProcess_AddCommand
# undef kwsysProcess_SetTimeout
# undef kwsysProcess_SetWorkingDirectory
# undef kwsysProcess_SetPipeFile
# undef kwsysProcess_SetPipeNative
# undef kwsysProcess_SetPipeShared
# undef kwsysProcess_Option_Detach
# undef kwsysProcess_Option_HideWindow
# undef kwsysProcess_Option_Verbatim
# undef kwsysProcess_GetOption
# undef kwsysProcess_SetOption
# undef kwsysProcess_Option_e
# undef kwsysProcess_State_Starting
# undef kwsysProcess_State_Error
# undef kwsysProcess_State_Exception
# undef kwsysProcess_State_Executing
# undef kwsysProcess_State_Exited
# undef kwsysProcess_State_Expired
# undef kwsysProcess_State_Killed
# undef kwsysProcess_State_Disowned
# undef kwsysProcess_GetState
# undef kwsysProcess_State_e
# undef kwsysProcess_Exception_None
# undef kwsysProcess_Exception_Fault
# undef kwsysProcess_Exception_Illegal
# undef kwsysProcess_Exception_Interrupt
# undef kwsysProcess_Exception_Numerical
# undef kwsysProcess_Exception_Other
# undef kwsysProcess_GetExitException
# undef kwsysProcess_Exception_e
# undef kwsysProcess_GetExitCode
# undef kwsysProcess_GetExitValue
# undef kwsysProcess_GetErrorString
# undef kwsysProcess_GetExceptionString
# undef kwsysProcess_Execute
# undef kwsysProcess_Disown
# undef kwsysProcess_WaitForData
# undef kwsysProcess_Pipes_e
# undef kwsysProcess_Pipe_None
# undef kwsysProcess_Pipe_STDIN
# undef kwsysProcess_Pipe_STDOUT
# undef kwsysProcess_Pipe_STDERR
# undef kwsysProcess_Pipe_Timeout
# undef kwsysProcess_Pipe_Handle
# undef kwsysProcess_WaitForExit
# undef kwsysProcess_Kill
# endif
#endif
#endif

211
ProcessFwd9x.c Normal file
View File

@ -0,0 +1,211 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
/*
On Windows9x platforms, this executable is spawned between a parent
process and the child it is invoking to work around a bug. See the
Win32 implementation file for details.
Future Work: This executable must be linked statically against the C
runtime library before being encoded into the library. Building it
in this way may be hard because CMake has limited abilities to build
different targets with different configurations in the same
directory. We may just have to create and encode the executable
once instead of generating it during the build. This would be an
acceptable solution because the forwarding executable should not
change very often and is pretty simple.
*/
#ifdef _MSC_VER
#pragma warning (push, 1)
#endif
#include <windows.h>
#include <stdio.h>
void ReportLastError(HANDLE errorPipe);
int main()
{
/* Process startup information for the real child. */
STARTUPINFO si;
PROCESS_INFORMATION pi;
/* The result of waiting for the child to exit. */
DWORD waitResult;
/* The child's process return code. */
DWORD retVal;
/* The command line used to invoke this process. */
LPSTR commandLine = GetCommandLine();
/* Pointer that will be advanced to the beginning of the command
line of the real child process. */
LPSTR cmdLine = commandLine;
/* Handle to the error reporting pipe provided by the parent. This
is parsed off the command line. */
HANDLE errorPipe = 0;
HANDLE errorPipeOrig = 0;
/* Handle to the event the parent uses to tell us to resume the child.
This is parsed off the command line. */
HANDLE resumeEvent = 0;
/* Handle to the event the parent uses to tell us to kill the child.
This is parsed off the command line. */
HANDLE killEvent = 0;
/* Flag for whether to hide window of child process. */
int hideWindow = 0;
/* An array of the handles on which we wait when the child is
running. */
HANDLE waitHandles[2] = {0, 0};
/* Move the pointer past the name of this executable. */
if(*cmdLine == '"')
{
++cmdLine;
while(*cmdLine && *cmdLine != '"') { ++cmdLine; }
if(*cmdLine) { ++cmdLine; }
}
else
{
while(*cmdLine && *cmdLine != ' ') { ++cmdLine; }
}
/* Parse the error pipe handle. */
while(*cmdLine && *cmdLine == ' ') { ++cmdLine; }
sscanf(cmdLine, "%p", &errorPipeOrig);
/* Parse the resume event handle. */
while(*cmdLine && *cmdLine != ' ') { ++cmdLine; }
while(*cmdLine && *cmdLine == ' ') { ++cmdLine; }
sscanf(cmdLine, "%p", &resumeEvent);
/* Parse the kill event handle. */
while(*cmdLine && *cmdLine != ' ') { ++cmdLine; }
while(*cmdLine && *cmdLine == ' ') { ++cmdLine; }
sscanf(cmdLine, "%p", &killEvent);
/* Parse the hide window flag. */
while(*cmdLine && *cmdLine != ' ') { ++cmdLine; }
while(*cmdLine && *cmdLine == ' ') { ++cmdLine; }
sscanf(cmdLine, "%d", &hideWindow);
/* Skip to the beginning of the command line of the real child. */
while(*cmdLine && *cmdLine != ' ') { ++cmdLine; }
while(*cmdLine && *cmdLine == ' ') { ++cmdLine; }
/* Create a non-inherited copy of the error pipe. We do not want
the child to get it. */
if(DuplicateHandle(GetCurrentProcess(), errorPipeOrig,
GetCurrentProcess(), &errorPipe,
0, FALSE, DUPLICATE_SAME_ACCESS))
{
/* Have a non-inherited duplicate. Close the inherited one. */
CloseHandle(errorPipeOrig);
}
else
{
/* Could not duplicate handle. Report the error. */
ReportLastError(errorPipeOrig);
return 1;
}
/* Create the subprocess. */
ZeroMemory(&si, sizeof(si));
ZeroMemory(&pi, sizeof(pi));
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES|STARTF_USESHOWWINDOW;
si.wShowWindow = hideWindow?SW_HIDE:SW_SHOWDEFAULT;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
si.hStdError = GetStdHandle(STD_ERROR_HANDLE);
if(CreateProcess(0, cmdLine, 0, 0, TRUE, CREATE_SUSPENDED, 0, 0, &si, &pi))
{
/* Process created successfully. Close the error reporting pipe
to notify the parent of success. */
CloseHandle(errorPipe);
}
else
{
/* Error creating the process. Report the error to the parent
process through the special error reporting pipe. */
ReportLastError(errorPipe);
return 1;
}
/* Wait for resume or kill event from parent. */
waitHandles[0] = killEvent;
waitHandles[1] = resumeEvent;
waitResult = WaitForMultipleObjects(2, waitHandles, 0, INFINITE);
/* Check what happened. */
if(waitResult == WAIT_OBJECT_0)
{
/* We were asked to kill the child. */
TerminateProcess(pi.hProcess, 255);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
return 1;
}
else
{
/* We were asked to resume the child. */
ResumeThread(pi.hThread);
CloseHandle(pi.hThread);
}
/* Wait for subprocess to exit or for kill event from parent. */
waitHandles[0] = killEvent;
waitHandles[1] = pi.hProcess;
waitResult = WaitForMultipleObjects(2, waitHandles, 0, INFINITE);
/* Check what happened. */
if(waitResult == WAIT_OBJECT_0)
{
/* We were asked to kill the child. */
TerminateProcess(pi.hProcess, 255);
WaitForSingleObject(pi.hProcess, INFINITE);
CloseHandle(pi.hProcess);
return 1;
}
else
{
/* The child exited. Get the return code. */
GetExitCodeProcess(pi.hProcess, &retVal);
CloseHandle(pi.hProcess);
return retVal;
}
}
void ReportLastError(HANDLE errorPipe)
{
LPVOID lpMsgBuf;
DWORD n;
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
GetLastError(),
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language
(LPTSTR) &lpMsgBuf,
0,
NULL
);
WriteFile(errorPipe, lpMsgBuf, strlen(lpMsgBuf)+1, &n, 0);
LocalFree( lpMsgBuf );
}

2753
ProcessUNIX.c Normal file

File diff suppressed because it is too large Load Diff

2952
ProcessWin32.c Normal file

File diff suppressed because it is too large Load Diff

10
README.txt Normal file
View File

@ -0,0 +1,10 @@
KWSys provides a platform-independent API to many common system
features that are implemented differently on every platform. This
library is intended to be shared among many projects, so it has a
configurable namespace. Each project should configure KWSys to use a
namespace unique to itself. See comments in CMakeLists.txt for
details.
You are probably reading this file in the source tree of a surrounding
project. In that case, see "../README.kwsys" for details of using
KWSys in your project.

818
Registry.cxx Normal file
View File

@ -0,0 +1,818 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Registry.hxx)
#include KWSYS_HEADER(Configure.hxx)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(stl/string)
#include KWSYS_HEADER(stl/map)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(ios/fstream)
#include KWSYS_HEADER(ios/sstream)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "Registry.hxx.in"
# include "Configure.hxx.in"
# include "kwsys_stl.hxx.in"
# include "kwsys_stl_string.hxx.in"
# include "kwsys_stl_map.hxx.in"
# include "kwsys_ios_iostream.h.in"
# include "kwsys_ios_fstream.h.in"
# include "kwsys_ios_sstream.h.in"
#endif
#include <ctype.h> // for isspace
#include <stdio.h>
#include <string.h> /* strlen, strncpy */
#include <stdlib.h> /* getenv */
#ifdef _WIN32
# include <windows.h>
#endif
namespace KWSYS_NAMESPACE
{
class RegistryHelper {
public:
RegistryHelper(Registry::RegistryType registryType);
virtual ~RegistryHelper();
// Read a value from the registry.
virtual bool ReadValue(const char *key, const char **value);
// Delete a key from the registry.
virtual bool DeleteKey(const char *key);
// Delete a value from a given key.
virtual bool DeleteValue(const char *key);
// Set value in a given key.
virtual bool SetValue(const char *key, const char *value);
// Open the registry at toplevel/subkey.
virtual bool Open(const char *toplevel, const char *subkey,
int readonly);
// Close the registry.
virtual bool Close();
// Set the value of changed
void SetChanged(bool b) { m_Changed = b; }
void SetTopLevel(const char* tl);
const char* GetTopLevel() { return m_TopLevel.c_str(); }
//! Read from local or global scope. On Windows this mean from local machine
// or local user. On unix this will read from $HOME/.Projectrc or
// /etc/Project
void SetGlobalScope(bool b);
bool GetGlobalScope();
kwsys_stl::string EncodeKey(const char* str);
kwsys_stl::string EncodeValue(const char* str);
kwsys_stl::string DecodeValue(const char* str);
protected:
bool m_Changed;
kwsys_stl::string m_TopLevel;
bool m_GlobalScope;
#ifdef _WIN32
HKEY HKey;
#endif
// Strip trailing and ending spaces.
char *Strip(char *str);
void SetSubKey(const char* sk);
kwsys_stl::string CreateKey(const char *key);
typedef kwsys_stl::map<kwsys_stl::string, kwsys_stl::string> StringToStringMap;
StringToStringMap EntriesMap;
kwsys_stl::string m_SubKey;
bool m_Empty;
bool m_SubKeySpecified;
kwsys_stl::string m_HomeDirectory;
Registry::RegistryType m_RegistryType;
};
//----------------------------------------------------------------------------
#define Registry_BUFFER_SIZE 8192
//----------------------------------------------------------------------------
Registry::Registry(Registry::RegistryType registryType)
{
m_Opened = false;
m_Locked = false;
this->Helper = 0;
this->Helper = new RegistryHelper(registryType);
}
//----------------------------------------------------------------------------
Registry::~Registry()
{
if ( m_Opened )
{
kwsys_ios::cerr << "Registry::Close should be "
"called here. The registry is not closed."
<< kwsys_ios::endl;
}
delete this->Helper;
}
//----------------------------------------------------------------------------
void Registry::SetGlobalScope(bool b)
{
this->Helper->SetGlobalScope(b);
}
//----------------------------------------------------------------------------
bool Registry::GetGlobalScope()
{
return this->Helper->GetGlobalScope();
}
//----------------------------------------------------------------------------
bool Registry::Open(const char *toplevel,
const char *subkey, int readonly)
{
bool res = false;
if ( m_Locked )
{
return res;
}
if ( m_Opened )
{
if ( !this->Close() )
{
return res;
}
}
if ( !toplevel || !*toplevel )
{
kwsys_ios::cerr << "Registry::Opened() Toplevel not defined"
<< kwsys_ios::endl;
return res;
}
if ( isspace(toplevel[0]) ||
isspace(toplevel[strlen(toplevel)-1]) )
{
kwsys_ios::cerr << "Toplevel has to start with letter or number and end"
" with one" << kwsys_ios::endl;
return res;
}
res = this->Helper->Open(toplevel, subkey, readonly);
if ( readonly != Registry::READONLY )
{
m_Locked = true;
}
if ( res )
{
m_Opened = true;
this->Helper->SetTopLevel(toplevel);
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::Close()
{
bool res = false;
if ( m_Opened )
{
res = this->Helper->Close();
}
if ( res )
{
m_Opened = false;
m_Locked = false;
this->Helper->SetChanged(false);
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::ReadValue(const char *subkey,
const char *key,
const char **value)
{
bool res = false;
bool open = false;
if ( ! value )
{
return res;
}
*value = 0;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READONLY) )
{
return res;
}
open = true;
}
res = this->Helper->ReadValue(key, value);
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::DeleteKey(const char *subkey, const char *key)
{
bool res = false;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return res;
}
open = true;
}
res = this->Helper->DeleteKey(key);
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::DeleteValue(const char *subkey, const char *key)
{
bool res = false;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return res;
}
open = true;
}
res = this->Helper->DeleteValue(key);
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
bool Registry::SetValue(const char *subkey, const char *key,
const char *value)
{
bool res = false;
bool open = false;
if ( !m_Opened )
{
if ( !this->Open(this->GetTopLevel(), subkey,
Registry::READWRITE) )
{
return res;
}
open = true;
}
res = this->Helper->SetValue( key, value );
if ( res )
{
this->Helper->SetChanged(true);
}
if ( open )
{
if ( !this->Close() )
{
res = false;
}
}
return res;
}
//----------------------------------------------------------------------------
const char* Registry::GetTopLevel()
{
return this->Helper->GetTopLevel();
}
//----------------------------------------------------------------------------
void Registry::SetTopLevel(const char* tl)
{
this->Helper->SetTopLevel(tl);
}
//----------------------------------------------------------------------------
void RegistryHelper::SetTopLevel(const char* tl)
{
if ( tl )
{
m_TopLevel = tl;
}
else
{
m_TopLevel = "";
}
}
//----------------------------------------------------------------------------
RegistryHelper::RegistryHelper(Registry::RegistryType registryType)
{
m_Changed = false;
m_TopLevel = "";
m_SubKey = "";
m_SubKeySpecified = false;
m_Empty = true;
m_GlobalScope = false;
m_RegistryType = registryType;
}
//----------------------------------------------------------------------------
RegistryHelper::~RegistryHelper()
{
}
//----------------------------------------------------------------------------
bool RegistryHelper::Open(const char *toplevel, const char *subkey,
int readonly)
{
this->EntriesMap.clear();
m_Empty = 1;
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
HKEY scope = HKEY_CURRENT_USER;
if ( this->GetGlobalScope() )
{
scope = HKEY_LOCAL_MACHINE;
}
int res = 0;
kwsys_ios::ostringstream str;
DWORD dwDummy;
str << "Software\\Kitware\\" << toplevel << "\\" << subkey;
if ( readonly == Registry::READONLY )
{
res = ( RegOpenKeyEx(scope, str.str().c_str(),
0, KEY_READ, &this->HKey) == ERROR_SUCCESS );
}
else
{
char lpClass[] = "";
res = ( RegCreateKeyEx(scope, str.str().c_str(),
0, lpClass, REG_OPTION_NON_VOLATILE, KEY_READ|KEY_WRITE,
NULL, &this->HKey, &dwDummy) == ERROR_SUCCESS );
}
if ( res != 0 )
{
this->SetSubKey( subkey );
}
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
bool res = false;
int cc;
kwsys_ios::ostringstream str;
const char* homeDirectory;
if ( (homeDirectory = getenv("HOME")) == 0 )
{
if ( (homeDirectory = getenv("USERPROFILE")) == 0 )
{
return false;
}
}
m_HomeDirectory = homeDirectory;
str << m_HomeDirectory.c_str() << "/." << toplevel << "rc";
if ( readonly == Registry::READWRITE )
{
kwsys_ios::ofstream ofs( str.str().c_str(), kwsys_ios::ios::out|kwsys_ios::ios::app );
if ( ofs.fail() )
{
return false;
}
ofs.close();
}
kwsys_ios::ifstream *ifs = new kwsys_ios::ifstream(str.str().c_str(), kwsys_ios::ios::in
#ifndef KWSYS_IOS_USE_ANSI
| kwsys_ios::ios::nocreate
#endif
);
if ( !ifs )
{
return false;
}
if ( ifs->fail())
{
delete ifs;
return false;
}
res = true;
char buffer[Registry_BUFFER_SIZE];
while( !ifs->fail() )
{
ifs->getline(buffer, Registry_BUFFER_SIZE);
if ( ifs->fail() || ifs->eof() )
{
break;
}
char *line = this->Strip(buffer);
if ( *line == '#' || *line == 0 )
{
// Comment
continue;
}
int linelen = static_cast<int>(strlen(line));
for ( cc = 0; cc < linelen; cc++ )
{
if ( line[cc] == '=' )
{
char *key = new char[ cc+1 ];
strncpy( key, line, cc );
key[cc] = 0;
char *value = line + cc + 1;
char *nkey = this->Strip(key);
char *nvalue = this->Strip(value);
this->EntriesMap[nkey] = this->DecodeValue(nvalue);
m_Empty = 0;
delete [] key;
break;
}
}
}
ifs->close();
this->SetSubKey( subkey );
delete ifs;
return res;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::Close()
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res;
res = ( RegCloseKey(this->HKey) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
if ( !m_Changed )
{
this->SetSubKey(0);
return true;
}
kwsys_ios::ostringstream str;
str << m_HomeDirectory.c_str() << "/." << this->GetTopLevel() << "rc";
kwsys_ios::ofstream *ofs = new kwsys_ios::ofstream(str.str().c_str(), kwsys_ios::ios::out);
if ( !ofs )
{
return false;
}
if ( ofs->fail())
{
delete ofs;
return false;
}
*ofs << "# This file is automatically generated by the application" << kwsys_ios::endl
<< "# If you change any lines or add new lines, note that all" << kwsys_ios::endl
<< "# comments and empty lines will be deleted. Every line has" << kwsys_ios::endl
<< "# to be in format: " << kwsys_ios::endl
<< "# key = value" << kwsys_ios::endl
<< "#" << kwsys_ios::endl;
if ( !this->EntriesMap.empty() )
{
RegistryHelper::StringToStringMap::iterator it;
for ( it = this->EntriesMap.begin();
it != this->EntriesMap.end();
++ it )
{
*ofs << it->first.c_str() << " = " << this->EncodeValue(it->second.c_str()).c_str() << kwsys_ios::endl;
}
}
this->EntriesMap.clear();
ofs->close();
delete ofs;
this->SetSubKey(0);
m_Empty = 1;
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::ReadValue(const char *skey, const char **value)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
DWORD dwType, dwSize;
dwType = REG_SZ;
char buffer[1024]; // Replace with RegQueryInfoKey
dwSize = sizeof(buffer);
int res = ( RegQueryValueEx(this->HKey, skey, NULL, &dwType,
(BYTE *)buffer, &dwSize) == ERROR_SUCCESS );
if ( !res )
{
return false;
}
this->EntriesMap[key] = buffer;
RegistryHelper::StringToStringMap::iterator it
= this->EntriesMap.find(key);
*value = it->second.c_str();
return true;
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
bool res = false;
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
RegistryHelper::StringToStringMap::iterator it
= this->EntriesMap.find(key);
if ( it != this->EntriesMap.end() )
{
*value = it->second.c_str();
res = true;
}
return res;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::DeleteKey(const char* skey)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res = ( RegDeleteKey( this->HKey, skey ) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
this->EntriesMap.erase(key);
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::DeleteValue(const char *skey)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
int res = ( RegDeleteValue( this->HKey, skey ) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return false;
}
this->EntriesMap.erase(key);
return true;
}
return false;
}
//----------------------------------------------------------------------------
bool RegistryHelper::SetValue(const char *skey, const char *value)
{
#ifdef _WIN32
if ( m_RegistryType == Registry::WIN32_REGISTRY)
{
DWORD len = (DWORD)(value ? strlen(value) : 0);
int res = ( RegSetValueEx(this->HKey, skey, 0, REG_SZ,
(CONST BYTE *)(const char *)value,
len+1) == ERROR_SUCCESS );
return (res != 0);
}
#endif
if ( m_RegistryType == Registry::FILE_REGISTRY )
{
kwsys_stl::string key = this->CreateKey( skey );
if ( key.empty() )
{
return 0;
}
this->EntriesMap[key] = value;
return 1;
}
return false;
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::CreateKey( const char *key )
{
if ( !m_SubKeySpecified || m_SubKey.empty() || !key )
{
return "";
}
kwsys_ios::ostringstream ostr;
ostr << this->EncodeKey(this->m_SubKey.c_str()).c_str()
<< "\\" << this->EncodeKey(key).c_str();
return ostr.str();
}
//----------------------------------------------------------------------------
void RegistryHelper::SetSubKey(const char* sk)
{
if ( !sk )
{
m_SubKey = "";
m_SubKeySpecified = false;
}
else
{
m_SubKey = sk;
m_SubKeySpecified = true;
}
}
//----------------------------------------------------------------------------
char *RegistryHelper::Strip(char *str)
{
int cc;
size_t len;
char *nstr;
if ( !str )
{
return NULL;
}
len = strlen(str);
nstr = str;
for( cc=0; cc < static_cast<int>(len); cc++ )
{
if ( !isspace( *nstr ) )
{
break;
}
nstr ++;
}
for( cc= static_cast<int>(strlen(nstr))-1; cc>=0; cc-- )
{
if ( !isspace( nstr[cc] ) )
{
nstr[cc+1] = 0;
break;
}
}
return nstr;
}
//----------------------------------------------------------------------------
void RegistryHelper::SetGlobalScope(bool b)
{
m_GlobalScope = b;
}
//----------------------------------------------------------------------------
bool RegistryHelper::GetGlobalScope()
{
return m_GlobalScope;
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::EncodeKey(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
switch ( *str )
{
case '%': case '=': case '\n': case '\r': case '\t':
char buffer[4];
sprintf(buffer, "%%%02X", *str);
ostr << buffer;
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::EncodeValue(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
switch ( *str )
{
case '%': case '=': case '\n': case '\r': case '\t':
char buffer[4];
sprintf(buffer, "%%%02X", *str);
ostr << buffer;
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
//----------------------------------------------------------------------------
kwsys_stl::string RegistryHelper::DecodeValue(const char* str)
{
kwsys_ios::ostringstream ostr;
while ( *str )
{
unsigned int val;
switch ( *str )
{
case '%':
if ( *(str+1) && *(str+2) && sscanf(str+1, "%x", &val) == 1 )
{
ostr << static_cast<char>(val);
str += 2;
}
else
{
ostr << *str;
}
break;
default:
ostr << *str;
}
str ++;
}
return ostr.str();
}
} // namespace KWSYS_NAMESPACE

107
Registry.hxx.in Normal file
View File

@ -0,0 +1,107 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_Registry_hxx
#define @KWSYS_NAMESPACE@_Registry_hxx
#include <@KWSYS_NAMESPACE@/Configure.h>
#include <@KWSYS_NAMESPACE@/stl/string>
namespace @KWSYS_NAMESPACE@
{
class RegistryHelper;
/** \class Registry
* \brief Portable registry class
*
* This class abstracts the storing of data that can be restored
* when the program executes again. On Win32 platform it is
* implemented using the registry and on unix as a file in
* the user's home directory.
*/
class @KWSYS_NAMESPACE@_EXPORT Registry
{
public:
enum RegistryType
{
#ifdef _WIN32
WIN32_REGISTRY,
#endif
FILE_REGISTRY
};
#ifdef _WIN32
Registry(RegistryType registryType = WIN32_REGISTRY);
#else
Registry(RegistryType registryType = FILE_REGISTRY);
#endif
virtual ~Registry();
//! Read a value from the registry.
bool ReadValue(const char *subkey, const char *key, const char **value);
//! Delete a key from the registry.
bool DeleteKey(const char *subkey, const char *key);
//! Delete a value from a given key.
bool DeleteValue(const char *subkey, const char *key);
//! Set value in a given key.
bool SetValue(const char *subkey, const char *key,
const char *value);
//! Open the registry at toplevel/subkey.
bool Open(const char *toplevel, const char *subkey,
int readonly);
//! Close the registry.
bool Close();
//! Read from local or global scope. On Windows this mean from local machine
// or local user. On unix this will read from $HOME/.Projectrc or
// /etc/Project
void GlobalScopeOn() { this->SetGlobalScope(1); }
void GlobalScopeOff() { this->SetGlobalScope(0); }
void SetGlobalScope(bool b);
bool GetGlobalScope();
// Set or get the toplevel registry key.
void SetTopLevel(const char* tl);
const char* GetTopLevel();
// Return true if registry opened
bool GetOpened() { return m_Opened; }
// Should the registry be locked?
bool GetLocked() { return m_Locked; }
enum {
READONLY,
READWRITE
};
// Return true if the character is space.
int IsSpace(char c);
private:
RegistryHelper* Helper;
bool m_Opened;
bool m_Locked;
}; // End Class: Registry
} // namespace @KWSYS_NAMESPACE@
#endif

1251
RegularExpression.cxx Normal file

File diff suppressed because it is too large Load Diff

414
RegularExpression.hxx.in Normal file
View File

@ -0,0 +1,414 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
// Original Copyright notice:
// Copyright (C) 1991 Texas Instruments Incorporated.
//
// Permission is granted to any individual or institution to use, copy, modify,
// and distribute this software, provided that this complete copyright and
// permission notice is maintained, intact, in all copies and supporting
// documentation.
//
// Texas Instruments Incorporated provides this software "as is" without
// express or implied warranty.
//
// Created: MNF 06/13/89 Initial Design and Implementation
// Updated: LGO 08/09/89 Inherit from Generic
// Updated: MBN 09/07/89 Added conditional exception handling
// Updated: MBN 12/15/89 Sprinkled "const" qualifiers all over the place!
// Updated: DLS 03/22/91 New lite version
//
#ifndef @KWSYS_NAMESPACE@_RegularExpression_hxx
#define @KWSYS_NAMESPACE@_RegularExpression_hxx
#include <@KWSYS_NAMESPACE@/Configure.h>
#include <@KWSYS_NAMESPACE@/Configure.hxx>
#include <@KWSYS_NAMESPACE@/stl/string>
/* Define this macro temporarily to keep the code readable. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsys_stl @KWSYS_NAMESPACE@_stl
#endif
/* Disable useless Borland warnings. KWSys tries not to force things
on its includers, but there is no choice here. */
#if defined(__BORLANDC__)
# pragma warn -8027 /* function not inlined. */
#endif
namespace @KWSYS_NAMESPACE@
{
/** \class RegularExpression
* \brief Implements pattern matching with regular expressions.
*
* This is the header file for the regular expression class. An object of
* this class contains a regular expression, in a special "compiled" format.
* This compiled format consists of several slots all kept as the objects
* private data. The RegularExpression class provides a convenient way to
* represent regular expressions. It makes it easy to search for the same
* regular expression in many different strings without having to compile a
* string to regular expression format more than necessary.
*
* This class implements pattern matching via regular expressions.
* A regular expression allows a programmer to specify complex
* patterns that can be searched for and matched against the
* character string of a string object. In its simplest form, a
* regular expression is a sequence of characters used to
* search for exact character matches. However, many times the
* exact sequence to be found is not known, or only a match at
* the beginning or end of a string is desired. The RegularExpression regu-
* lar expression class implements regular expression pattern
* matching as is found and implemented in many UNIX commands
* and utilities.
*
* Example: The perl code
*
* $filename =~ m"([a-z]+)\.cc";
* print $1;
*
* Is written as follows in C++
*
* RegularExpression re("([a-z]+)\\.cc");
* re.find(filename);
* cerr << re.match(1);
*
*
* The regular expression class provides a convenient mechanism
* for specifying and manipulating regular expressions. The
* regular expression object allows specification of such pat-
* terns by using the following regular expression metacharac-
* ters:
*
* ^ Matches at beginning of a line
*
* $ Matches at end of a line
*
* . Matches any single character
*
* [ ] Matches any character(s) inside the brackets
*
* [^ ] Matches any character(s) not inside the brackets
*
* - Matches any character in range on either side of a dash
*
* * Matches preceding pattern zero or more times
*
* + Matches preceding pattern one or more times
*
* ? Matches preceding pattern zero or once only
*
* () Saves a matched expression and uses it in a later match
*
* Note that more than one of these metacharacters can be used
* in a single regular expression in order to create complex
* search patterns. For example, the pattern [^ab1-9] says to
* match any character sequence that does not begin with the
* characters "ab" followed by numbers in the series one
* through nine.
*
* There are three constructors for RegularExpression. One just creates an
* empty RegularExpression object. Another creates a RegularExpression
* object and initializes it with a regular expression that is given in the
* form of a char*. The third takes a reference to a RegularExpression
* object as an argument and creates an object initialized with the
* information from the given RegularExpression object.
*
* The find member function finds the first occurence of the regualr
* expression of that object in the string given to find as an argument. Find
* returns a boolean, and if true, mutates the private data appropriately.
* Find sets pointers to the beginning and end of the thing last found, they
* are pointers into the actual string that was searched. The start and end
* member functions return indicies into the searched string that correspond
* to the beginning and end pointers respectively. The compile member
* function takes a char* and puts the compiled version of the char* argument
* into the object's private data fields. The == and != operators only check
* the to see if the compiled regular expression is the same, and the
* deep_equal functions also checks to see if the start and end pointers are
* the same. The is_valid function returns false if program is set to NULL,
* (i.e. there is no valid compiled exression). The set_invalid function sets
* the program to NULL (Warning: this deletes the compiled expression). The
* following examples may help clarify regular expression usage:
*
* * The regular expression "^hello" matches a "hello" only at the
* beginning of a line. It would match "hello there" but not "hi,
* hello there".
*
* * The regular expression "long$" matches a "long" only at the end
* of a line. It would match "so long\0", but not "long ago".
*
* * The regular expression "t..t..g" will match anything that has a
* "t" then any two characters, another "t", any two characters and
* then a "g". It will match "testing", or "test again" but would
* not match "toasting"
*
* * The regular expression "[1-9ab]" matches any number one through
* nine, and the characters "a" and "b". It would match "hello 1"
* or "begin", but would not match "no-match".
*
* * The regular expression "[^1-9ab]" matches any character that is
* not a number one through nine, or an "a" or "b". It would NOT
* match "hello 1" or "begin", but would match "no-match".
*
* * The regular expression "br* " matches something that begins with
* a "b", is followed by zero or more "r"s, and ends in a space. It
* would match "brrrrr ", and "b ", but would not match "brrh ".
*
* * The regular expression "br+ " matches something that begins with
* a "b", is followed by one or more "r"s, and ends in a space. It
* would match "brrrrr ", and "br ", but would not match "b " or
* "brrh ".
*
* * The regular expression "br? " matches something that begins with
* a "b", is followed by zero or one "r"s, and ends in a space. It
* would match "br ", and "b ", but would not match "brrrr " or
* "brrh ".
*
* * The regular expression "(..p)b" matches something ending with pb
* and beginning with whatever the two characters before the first p
* encounterd in the line were. It would find "repb" in "rep drepa
* qrepb". The regular expression "(..p)a" would find "repa qrepb"
* in "rep drepa qrepb"
*
* * The regular expression "d(..p)" matches something ending with p,
* beginning with d, and having two characters in between that are
* the same as the two characters before the first p encounterd in
* the line. It would match "drepa qrepb" in "rep drepa qrepb".
*
*/
class @KWSYS_NAMESPACE@_EXPORT RegularExpression
{
public:
/**
* Instantiate RegularExpression with program=NULL.
*/
inline RegularExpression ();
/**
* Instantiate RegularExpression with compiled char*.
*/
inline RegularExpression (char const*);
/**
* Instantiate RegularExpression as a copy of another regular expression.
*/
RegularExpression (RegularExpression const&);
/**
* Destructor.
*/
inline ~RegularExpression();
/**
* Compile a regular expression into internal code
* for later pattern matching.
*/
bool compile (char const*);
/**
* Matches the regular expression to the given string.
* Returns true if found, and sets start and end indexes accordingly.
*/
bool find (char const*);
/**
* Matches the regular expression to the given std string.
* Returns true if found, and sets start and end indexes accordingly.
*/
bool find (kwsys_stl::string const&);
/**
* Index to start of first find.
*/
inline kwsys_stl::string::size_type start() const;
/**
* Index to end of first find.
*/
inline kwsys_stl::string::size_type end() const;
/**
* Copy the given regular expression.
*/
RegularExpression& operator= (const RegularExpression& rxp);
/**
* Returns true if two regular expressions have the same
* compiled program for pattern matching.
*/
bool operator== (RegularExpression const&) const;
/**
* Returns true if two regular expressions have different
* compiled program for pattern matching.
*/
inline bool operator!= (RegularExpression const&) const;
/**
* Returns true if have the same compiled regular expressions
* and the same start and end pointers.
*/
bool deep_equal (RegularExpression const&) const;
/**
* True if the compiled regexp is valid.
*/
inline bool is_valid() const;
/**
* Marks the regular expression as invalid.
*/
inline void set_invalid();
/**
* Destructor.
*/
// awf added
kwsys_stl::string::size_type start(int n) const;
kwsys_stl::string::size_type end(int n) const;
kwsys_stl::string match(int n) const;
enum { NSUBEXP = 10 };
private:
const char* startp[NSUBEXP];
const char* endp[NSUBEXP];
char regstart; // Internal use only
char reganch; // Internal use only
const char* regmust; // Internal use only
kwsys_stl::string::size_type regmlen; // Internal use only
char* program;
int progsize;
const char* searchstring;
};
/**
* Create an empty regular expression.
*/
inline RegularExpression::RegularExpression ()
{
this->program = 0;
}
/**
* Creates a regular expression from string s, and
* compiles s.
*/
inline RegularExpression::RegularExpression (const char* s)
{
this->program = 0;
if ( s )
{
this->compile(s);
}
}
/**
* Destroys and frees space allocated for the regular expression.
*/
inline RegularExpression::~RegularExpression ()
{
//#ifndef WIN32
delete [] this->program;
//#endif
}
/**
* Set the start position for the regular expression.
*/
inline kwsys_stl::string::size_type RegularExpression::start () const
{
return static_cast<kwsys_stl::string::size_type>(
this->startp[0] - searchstring);
}
/**
* Returns the start/end index of the last item found.
*/
inline kwsys_stl::string::size_type RegularExpression::end () const
{
return static_cast<kwsys_stl::string::size_type>(
this->endp[0] - searchstring);
}
/**
* Returns true if two regular expressions have different
* compiled program for pattern matching.
*/
inline bool RegularExpression::operator!= (const RegularExpression& r) const
{
return(!(*this == r));
}
/**
* Returns true if a valid regular expression is compiled
* and ready for pattern matching.
*/
inline bool RegularExpression::is_valid () const
{
return (this->program != 0);
}
inline void RegularExpression::set_invalid ()
{
//#ifndef WIN32
delete [] this->program;
//#endif
this->program = 0;
}
/**
* Return start index of nth submatch. start(0) is the start of the full match.
*/
inline kwsys_stl::string::size_type RegularExpression::start(int n) const
{
return static_cast<kwsys_stl::string::size_type>(
this->startp[n] - searchstring);
}
/**
* Return end index of nth submatch. end(0) is the end of the full match.
*/
inline kwsys_stl::string::size_type RegularExpression::end(int n) const
{
return static_cast<kwsys_stl::string::size_type>(
this->endp[n] - searchstring);
}
/**
* Return nth submatch as a string.
*/
inline kwsys_stl::string RegularExpression::match(int n) const
{
if (this->startp[n]==0)
{
return kwsys_stl::string("");
}
else
{
return kwsys_stl::string(this->startp[n],
static_cast<kwsys_stl::string::size_type>(
this->endp[n] - this->startp[n]));
}
}
} // namespace @KWSYS_NAMESPACE@
/* Undefine temporary macro. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsys_stl
#endif
#endif

922
SharedForward.h.in Normal file
View File

@ -0,0 +1,922 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_SharedForward_h
#define @KWSYS_NAMESPACE@_SharedForward_h
/*
This header is used to create a forwarding executable sets up the
shared library search path and replaces itself with a real
executable. This is useful when creating installations on UNIX with
shared libraries that will run from any install directory. Typical
usage:
#if defined(CMAKE_INTDIR)
# define CONFIG_DIR_PRE CMAKE_INTDIR "/"
# define CONFIG_DIR_POST "/" CMAKE_INTDIR
#else
# define CONFIG_DIR_PRE ""
# define CONFIG_DIR_POST ""
#endif
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD "/path/to/foo-build/bin"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD "." CONFIG_DIR_POST
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL "../lib/foo-1.2"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD CONFIG_DIR_PRE "foo-real"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL "../lib/foo-1.2/foo-real"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND "--command"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT "--print"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD "--ldd"
#if defined(CMAKE_INTDIR)
# define @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME CMAKE_INTDIR
#endif
#include <@KWSYS_NAMESPACE@/SharedForward.h>
int main(int argc, char** argv)
{
return @KWSYS_NAMESPACE@_shared_forward_to_real(argc, argv);
}
Specify search and executable paths relative to the forwarding
executable location or as full paths. Include no trailing slash.
In the case of a multi-configuration build, when CMAKE_INTDIR is
defined, the DIR_BUILD setting should point at the directory above
the executable (the one containing the per-configuration
subdirectory specified by CMAKE_INTDIR). Then PATH_BUILD entries
and EXE_BUILD should be specified relative to this location and use
CMAKE_INTDIR as necessary. In the above example imagine appending
the PATH_BUILD or EXE_BUILD setting to the DIR_BUILD setting. The
result should form a valid path with per-configuration subdirectory.
Additional paths may be specified in the PATH_BUILD and PATH_INSTALL
variables by using comma-separated strings. For example:
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD \
"." CONFIG_DIR_POST, "/path/to/bar-build" CONFIG_DIR_POST
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL \
"../lib/foo-1.2", "../lib/bar-4.5"
See the comments below for specific explanations of each macro.
*/
/*--------------------------------------------------------------------------*/
/* Full path to the directory in which this executable is built. Do
not include a trailing slash. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD)
# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD"
#endif
#if !defined(KWSYS_SHARED_FORWARD_DIR_BUILD)
# define KWSYS_SHARED_FORWARD_DIR_BUILD @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD
#endif
/* Library search path for build tree. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD)
# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD"
#endif
#if !defined(KWSYS_SHARED_FORWARD_PATH_BUILD)
# define KWSYS_SHARED_FORWARD_PATH_BUILD @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD
#endif
/* Library search path for install tree. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL)
# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL"
#endif
#if !defined(KWSYS_SHARED_FORWARD_PATH_INSTALL)
# define KWSYS_SHARED_FORWARD_PATH_INSTALL @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL
#endif
/* The real executable to which to forward in the build tree. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD)
# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD"
#endif
#if !defined(KWSYS_SHARED_FORWARD_EXE_BUILD)
# define KWSYS_SHARED_FORWARD_EXE_BUILD @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD
#endif
/* The real executable to which to forward in the install tree. */
#if !defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL)
# error "Must define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL"
#endif
#if !defined(KWSYS_SHARED_FORWARD_EXE_INSTALL)
# define KWSYS_SHARED_FORWARD_EXE_INSTALL @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL
#endif
/* The configuration name with which this executable was built (Debug/Release). */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME)
# define KWSYS_SHARED_FORWARD_CONFIG_NAME @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME
#else
# undef KWSYS_SHARED_FORWARD_CONFIG_NAME
#endif
/* Create command line option to replace executable. */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND)
# if !defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
# define KWSYS_SHARED_FORWARD_OPTION_COMMAND @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND
# endif
#else
# undef KWSYS_SHARED_FORWARD_OPTION_COMMAND
#endif
/* Create command line option to print environment setting and exit. */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT)
# if !defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
# define KWSYS_SHARED_FORWARD_OPTION_PRINT @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT
# endif
#else
# undef KWSYS_SHARED_FORWARD_OPTION_PRINT
#endif
/* Create command line option to run ldd or equivalent. */
#if defined(@KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD)
# if !defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
# define KWSYS_SHARED_FORWARD_OPTION_LDD @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD
# endif
#else
# undef KWSYS_SHARED_FORWARD_OPTION_LDD
#endif
/*--------------------------------------------------------------------------*/
/* Include needed system headers. */
#include <stddef.h> /* size_t */
#include <limits.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
#if defined(_WIN32) && !defined(__CYGWIN__)
# include <io.h>
# include <windows.h>
# include <process.h>
# define KWSYS_SHARED_FORWARD_ESCAPE_ARGV /* re-escape argv for execvp */
#else
# include <unistd.h>
# include <sys/stat.h>
#endif
/*--------------------------------------------------------------------------*/
/* Configuration for this platform. */
/* The path separator for this platform. */
#if defined(_WIN32) && !defined(__CYGWIN__)
# define KWSYS_SHARED_FORWARD_PATH_SEP ';'
# define KWSYS_SHARED_FORWARD_PATH_SLASH '\\'
#else
# define KWSYS_SHARED_FORWARD_PATH_SEP ':'
# define KWSYS_SHARED_FORWARD_PATH_SLASH '/'
#endif
static const char kwsys_shared_forward_path_sep[2] = {KWSYS_SHARED_FORWARD_PATH_SEP, 0};
static const char kwsys_shared_forward_path_slash[2] = {KWSYS_SHARED_FORWARD_PATH_SLASH, 0};
/* The maximum length of a file name. */
#if defined(PATH_MAX)
# define KWSYS_SHARED_FORWARD_MAXPATH PATH_MAX
#elif defined(MAXPATHLEN)
# define KWSYS_SHARED_FORWARD_MAXPATH MAXPATHLEN
#else
# define KWSYS_SHARED_FORWARD_MAXPATH 16384
#endif
/* Select the environment variable holding the shared library runtime
search path for this platform and build configuration. Also select
ldd command equivalent. */
/* Linux */
#if defined(__linux)
# define KWSYS_SHARED_FORWARD_LDD "ldd"
# define KWSYS_SHARED_FORWARD_LDD_N 1
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
/* FreeBSD */
#elif defined(__FreeBSD__)
# define KWSYS_SHARED_FORWARD_LDD "ldd"
# define KWSYS_SHARED_FORWARD_LDD_N 1
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
/* OpenBSD */
#elif defined(__OpenBSD__)
# define KWSYS_SHARED_FORWARD_LDD "ldd"
# define KWSYS_SHARED_FORWARD_LDD_N 1
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
/* OSX */
#elif defined(__APPLE__)
# define KWSYS_SHARED_FORWARD_LDD "otool", "-L"
# define KWSYS_SHARED_FORWARD_LDD_N 2
# define KWSYS_SHARED_FORWARD_LDPATH "DYLD_LIBRARY_PATH"
/* AIX */
#elif defined(_AIX)
# define KWSYS_SHARED_FORWARD_LDD "dump", "-H"
# define KWSYS_SHARED_FORWARD_LDD_N 2
# define KWSYS_SHARED_FORWARD_LDPATH "LIBPATH"
/* SUN */
#elif defined(__sun)
# define KWSYS_SHARED_FORWARD_LDD "ldd"
# define KWSYS_SHARED_FORWARD_LDD_N 1
# include <sys/isa_defs.h>
# if defined(_ILP32)
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
# elif defined(_LP64)
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH_64"
# endif
/* HP-UX */
#elif defined(__hpux)
# define KWSYS_SHARED_FORWARD_LDD "chatr"
# define KWSYS_SHARED_FORWARD_LDD_N 1
# if defined(__LP64__)
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
# else
# define KWSYS_SHARED_FORWARD_LDPATH "SHLIB_PATH"
# endif
/* SGI MIPS */
#elif defined(__sgi) && defined(_MIPS_SIM)
# define KWSYS_SHARED_FORWARD_LDD "ldd"
# define KWSYS_SHARED_FORWARD_LDD_N 1
# if _MIPS_SIM == _ABIO32
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
# elif _MIPS_SIM == _ABIN32
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARYN32_PATH"
# elif _MIPS_SIM == _ABI64
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY64_PATH"
# endif
/* Cygwin */
#elif defined(__CYGWIN__)
# define KWSYS_SHARED_FORWARD_LDD "cygcheck" /* TODO: cygwin 1.7 has ldd */
# define KWSYS_SHARED_FORWARD_LDD_N 1
# define KWSYS_SHARED_FORWARD_LDPATH "PATH"
/* Windows */
#elif defined(_WIN32)
# define KWSYS_SHARED_FORWARD_LDPATH "PATH"
/* Guess on this unknown system. */
#else
# define KWSYS_SHARED_FORWARD_LDD "ldd"
# define KWSYS_SHARED_FORWARD_LDD_N 1
# define KWSYS_SHARED_FORWARD_LDPATH "LD_LIBRARY_PATH"
#endif
#ifdef KWSYS_SHARED_FORWARD_ESCAPE_ARGV
/*--------------------------------------------------------------------------*/
typedef struct kwsys_sf_arg_info_s
{
const char* arg;
int size;
int quote;
} kwsys_sf_arg_info;
/*--------------------------------------------------------------------------*/
static kwsys_sf_arg_info kwsys_sf_get_arg_info(const char* in)
{
/* Initialize information. */
kwsys_sf_arg_info info;
/* String iterator. */
const char* c;
/* Keep track of how many backslashes have been encountered in a row. */
int windows_backslashes = 0;
/* Start with the length of the original argument, plus one for
either a terminating null or a separating space. */
info.arg = in;
info.size = (int)strlen(in) + 1;
info.quote = 0;
/* Scan the string for characters that require escaping or quoting. */
for(c=in; *c; ++c)
{
/* Check whether this character needs quotes. */
if(strchr(" \t?'#&<>|^", *c))
{
info.quote = 1;
}
/* On Windows only backslashes and double-quotes need escaping. */
if(*c == '\\')
{
/* Found a backslash. It may need to be escaped later. */
++windows_backslashes;
}
else if(*c == '"')
{
/* Found a double-quote. We need to escape it and all
immediately preceding backslashes. */
info.size += windows_backslashes + 1;
windows_backslashes = 0;
}
else
{
/* Found another character. This eliminates the possibility
that any immediately preceding backslashes will be
escaped. */
windows_backslashes = 0;
}
}
/* Check whether the argument needs surrounding quotes. */
if(info.quote)
{
/* Surrounding quotes are needed. Allocate space for them. */
info.size += 2;
/* We must escape all ending backslashes when quoting on windows. */
info.size += windows_backslashes;
}
return info;
}
/*--------------------------------------------------------------------------*/
static char* kwsys_sf_get_arg(kwsys_sf_arg_info info, char* out)
{
/* String iterator. */
const char* c;
/* Keep track of how many backslashes have been encountered in a row. */
int windows_backslashes = 0;
/* Whether the argument must be quoted. */
if(info.quote)
{
/* Add the opening quote for this argument. */
*out++ = '"';
}
/* Scan the string for characters that require escaping or quoting. */
for(c=info.arg; *c; ++c)
{
/* On Windows only backslashes and double-quotes need escaping. */
if(*c == '\\')
{
/* Found a backslash. It may need to be escaped later. */
++windows_backslashes;
}
else if(*c == '"')
{
/* Found a double-quote. Escape all immediately preceding
backslashes. */
while(windows_backslashes > 0)
{
--windows_backslashes;
*out++ = '\\';
}
/* Add the backslash to escape the double-quote. */
*out++ = '\\';
}
else
{
/* We encountered a normal character. This eliminates any
escaping needed for preceding backslashes. */
windows_backslashes = 0;
}
/* Store this character. */
*out++ = *c;
}
if(info.quote)
{
/* Add enough backslashes to escape any trailing ones. */
while(windows_backslashes > 0)
{
--windows_backslashes;
*out++ = '\\';
}
/* Add the closing quote for this argument. */
*out++ = '"';
}
/* Store a terminating null without incrementing. */
*out = 0;
return out;
}
#endif
/*--------------------------------------------------------------------------*/
/* Function to convert a logical or relative path to a physical full path. */
static int kwsys_shared_forward_realpath(const char* in_path, char* out_path)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
/* Implementation for Windows. */
DWORD n = GetFullPathName(in_path, KWSYS_SHARED_FORWARD_MAXPATH,
out_path, 0);
return n > 0 && n <= KWSYS_SHARED_FORWARD_MAXPATH;
#else
/* Implementation for UNIX. */
return realpath(in_path, out_path) != 0;
#endif
}
/*--------------------------------------------------------------------------*/
static int kwsys_shared_forward_samepath(const char* file1, const char* file2)
{
#if defined(_WIN32)
int result = 0;
HANDLE h1 = CreateFile(file1, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
HANDLE h2 = CreateFile(file2, GENERIC_READ, FILE_SHARE_READ, NULL,
OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL);
if(h1 != INVALID_HANDLE_VALUE && h2 != INVALID_HANDLE_VALUE)
{
BY_HANDLE_FILE_INFORMATION fi1;
BY_HANDLE_FILE_INFORMATION fi2;
GetFileInformationByHandle(h1, &fi1);
GetFileInformationByHandle(h2, &fi2);
result = (fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber &&
fi1.nFileIndexHigh == fi2.nFileIndexHigh &&
fi1.nFileIndexLow == fi2.nFileIndexLow);
}
CloseHandle(h1);
CloseHandle(h2);
return result;
#else
struct stat fs1, fs2;
return (stat(file1, &fs1) == 0 && stat(file2, &fs2) == 0 &&
memcmp(&fs2.st_dev, &fs1.st_dev, sizeof(fs1.st_dev)) == 0 &&
memcmp(&fs2.st_ino, &fs1.st_ino, sizeof(fs1.st_ino)) == 0 &&
fs2.st_size == fs1.st_size);
#endif
}
/*--------------------------------------------------------------------------*/
/* Function to report a system error message. */
static void kwsys_shared_forward_strerror(char* message)
{
#if defined(_WIN32) && !defined(__CYGWIN__)
/* Implementation for Windows. */
DWORD original = GetLastError();
DWORD length = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS, 0, original,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
message, KWSYS_SHARED_FORWARD_MAXPATH, 0);
if(length < 1 || length > KWSYS_SHARED_FORWARD_MAXPATH)
{
/* FormatMessage failed. Use a default message. */
_snprintf(message, KWSYS_SHARED_FORWARD_MAXPATH,
"Error 0x%X (FormatMessage failed with error 0x%X)",
original, GetLastError());
}
#else
/* Implementation for UNIX. */
strcpy(message, strerror(errno));
#endif
}
/*--------------------------------------------------------------------------*/
/* Functions to execute a child process. */
static void kwsys_shared_forward_execvp(const char* cmd,
char const* const* argv)
{
#ifdef KWSYS_SHARED_FORWARD_ESCAPE_ARGV
/* Count the number of arguments. */
int argc = 0;
{
char const* const* argvc;
for(argvc = argv; *argvc; ++argvc,++argc) {}
}
/* Create the escaped arguments. */
{
char** nargv = (char**)malloc((argc+1) * sizeof(char*));
int i;
for(i=0; i < argc; ++i)
{
kwsys_sf_arg_info info = kwsys_sf_get_arg_info(argv[i]);
nargv[i] = (char*)malloc(info.size);
kwsys_sf_get_arg(info, nargv[i]);
}
nargv[argc] = 0;
/* Replace the command line to be used. */
argv = (char const* const*)nargv;
}
#endif
/* Invoke the child process. */
#if defined(_MSC_VER)
_execvp(cmd, argv);
#elif defined(__MINGW32__)
execvp(cmd, argv);
#else
execvp(cmd, (char* const*)argv);
#endif
}
/*--------------------------------------------------------------------------*/
/* Function to get the directory containing the given file or directory. */
static void kwsys_shared_forward_dirname(const char* begin, char* result)
{
/* Find the location of the last slash. */
int last_slash_index = -1;
const char* end = begin + strlen(begin);
for(;begin <= end && last_slash_index < 0; --end)
{
if(*end == '/' || *end == '\\')
{
last_slash_index = (int)(end-begin);
}
}
/* Handle each case of the index of the last slash. */
if(last_slash_index < 0)
{
/* No slashes. */
strcpy(result, ".");
}
else if(last_slash_index == 0)
{
/* Only one leading slash. */
strcpy(result, kwsys_shared_forward_path_slash);
}
#if defined(_WIN32)
else if(last_slash_index == 2 && begin[1] == ':')
{
/* Only one leading drive letter and slash. */
strncpy(result, begin, (size_t)last_slash_index);
result[last_slash_index] = KWSYS_SHARED_FORWARD_PATH_SLASH;
result[last_slash_index+1] = 0;
}
#endif
else
{
/* A non-leading slash. */
strncpy(result, begin, (size_t)last_slash_index);
result[last_slash_index] = 0;
}
}
/*--------------------------------------------------------------------------*/
/* Function to check if a file exists and is executable. */
static int kwsys_shared_forward_is_executable(const char* f)
{
#if defined(_MSC_VER)
# define KWSYS_SHARED_FORWARD_ACCESS _access
#else
# define KWSYS_SHARED_FORWARD_ACCESS access
#endif
#if defined(X_OK)
# define KWSYS_SHARED_FORWARD_ACCESS_OK X_OK
#else
# define KWSYS_SHARED_FORWARD_ACCESS_OK 04
#endif
if(KWSYS_SHARED_FORWARD_ACCESS(f, KWSYS_SHARED_FORWARD_ACCESS_OK) == 0)
{
return 1;
}
else
{
return 0;
}
}
/*--------------------------------------------------------------------------*/
/* Function to locate the executable currently running. */
static int kwsys_shared_forward_self_path(const char* argv0, char* result)
{
/* Check whether argv0 has a slash. */
int has_slash = 0;
const char* p = argv0;
for(;*p && !has_slash; ++p)
{
if(*p == '/' || *p == '\\')
{
has_slash = 1;
}
}
if(has_slash)
{
/* There is a slash. Use the dirname of the given location. */
kwsys_shared_forward_dirname(argv0, result);
return 1;
}
else
{
/* There is no slash. Search the PATH for the executable. */
const char* path = getenv("PATH");
const char* begin = path;
const char* end = begin + (begin?strlen(begin):0);
const char* first = begin;
while(first != end)
{
/* Store the end of this path entry. */
const char* last;
/* Skip all path separators. */
for(;*first && *first == KWSYS_SHARED_FORWARD_PATH_SEP; ++first);
/* Find the next separator. */
for(last = first;*last && *last != KWSYS_SHARED_FORWARD_PATH_SEP; ++last);
/* If we got a non-empty directory, look for the executable there. */
if(first < last)
{
/* Determine the length without trailing slash. */
size_t length = (size_t)(last-first);
if(*(last-1) == '/' || *(last-1) == '\\')
{
--length;
}
/* Construct the name of the executable in this location. */
strncpy(result, first, length);
result[length] = KWSYS_SHARED_FORWARD_PATH_SLASH;
strcpy(result+(length)+1, argv0);
/* Check if it exists and is executable. */
if(kwsys_shared_forward_is_executable(result))
{
/* Found it. */
result[length] = 0;
return 1;
}
}
/* Move to the next directory in the path. */
first = last;
}
}
/* We could not find the executable. */
return 0;
}
/*--------------------------------------------------------------------------*/
/* Function to convert a specified path to a full path. If it is not
already full, it is taken relative to the self path. */
static int kwsys_shared_forward_fullpath(const char* self_path,
const char* in_path,
char* result,
const char* desc)
{
/* Check the specified path type. */
if(in_path[0] == '/')
{
/* Already a full path. */
strcpy(result, in_path);
}
#if defined(_WIN32)
else if(in_path[0] && in_path[1] == ':')
{
/* Already a full path. */
strcpy(result, in_path);
}
#endif
else
{
/* Relative to self path. */
char temp_path[KWSYS_SHARED_FORWARD_MAXPATH];
strcpy(temp_path, self_path);
strcat(temp_path, kwsys_shared_forward_path_slash);
strcat(temp_path, in_path);
if(!kwsys_shared_forward_realpath(temp_path, result))
{
if(desc)
{
char msgbuf[KWSYS_SHARED_FORWARD_MAXPATH];
kwsys_shared_forward_strerror(msgbuf);
fprintf(stderr, "Error converting %s \"%s\" to real path: %s\n",
desc, temp_path, msgbuf);
}
return 0;
}
}
return 1;
}
/*--------------------------------------------------------------------------*/
/* Function to compute the library search path and executable name
based on the self path. */
static int kwsys_shared_forward_get_settings(const char* self_path,
char* ldpath, char* exe)
{
/* Possible search paths. */
static const char* search_path_build[] = {KWSYS_SHARED_FORWARD_PATH_BUILD, 0};
static const char* search_path_install[] = {KWSYS_SHARED_FORWARD_PATH_INSTALL, 0};
/* Chosen paths. */
const char** search_path;
const char* exe_path;
/* Get the real name of the build and self paths. */
#if defined(KWSYS_SHARED_FORWARD_CONFIG_NAME)
char build_path[] = KWSYS_SHARED_FORWARD_DIR_BUILD "/" KWSYS_SHARED_FORWARD_CONFIG_NAME;
char self_path_logical[KWSYS_SHARED_FORWARD_MAXPATH];
#else
char build_path[] = KWSYS_SHARED_FORWARD_DIR_BUILD;
const char* self_path_logical = self_path;
#endif
char build_path_real[KWSYS_SHARED_FORWARD_MAXPATH];
char self_path_real[KWSYS_SHARED_FORWARD_MAXPATH];
if(!kwsys_shared_forward_realpath(self_path, self_path_real))
{
char msgbuf[KWSYS_SHARED_FORWARD_MAXPATH];
kwsys_shared_forward_strerror(msgbuf);
fprintf(stderr, "Error converting self path \"%s\" to real path: %s\n",
self_path, msgbuf);
return 0;
}
/* Check whether we are running in the build tree or an install tree. */
if(kwsys_shared_forward_realpath(build_path, build_path_real) &&
kwsys_shared_forward_samepath(self_path_real, build_path_real))
{
/* Running in build tree. Use the build path and exe. */
search_path = search_path_build;
#if defined(_WIN32)
exe_path = KWSYS_SHARED_FORWARD_EXE_BUILD ".exe";
#else
exe_path = KWSYS_SHARED_FORWARD_EXE_BUILD;
#endif
#if defined(KWSYS_SHARED_FORWARD_CONFIG_NAME)
/* Remove the configuration directory from self_path. */
kwsys_shared_forward_dirname(self_path, self_path_logical);
#endif
}
else
{
/* Running in install tree. Use the install path and exe. */
search_path = search_path_install;
#if defined(_WIN32)
exe_path = KWSYS_SHARED_FORWARD_EXE_INSTALL ".exe";
#else
exe_path = KWSYS_SHARED_FORWARD_EXE_INSTALL;
#endif
#if defined(KWSYS_SHARED_FORWARD_CONFIG_NAME)
/* Use the original self path directory. */
strcpy(self_path_logical, self_path);
#endif
}
/* Construct the runtime search path. */
{
const char** dir;
for(dir = search_path; *dir; ++dir)
{
/* Add seperator between path components. */
if(dir != search_path)
{
strcat(ldpath, kwsys_shared_forward_path_sep);
}
/* Add this path component. */
if(!kwsys_shared_forward_fullpath(self_path_logical, *dir,
ldpath+strlen(ldpath),
"runtime path entry"))
{
return 0;
}
}
}
/* Construct the executable location. */
if(!kwsys_shared_forward_fullpath(self_path_logical, exe_path, exe,
"executable file"))
{
return 0;
}
return 1;
}
/*--------------------------------------------------------------------------*/
/* Function to print why execution of a command line failed. */
static void kwsys_shared_forward_print_failure(char const* const* argv)
{
char msg[KWSYS_SHARED_FORWARD_MAXPATH];
char const* const* arg = argv;
kwsys_shared_forward_strerror(msg);
fprintf(stderr, "Error running");
for(; *arg; ++arg)
{
fprintf(stderr, " \"%s\"", *arg);
}
fprintf(stderr, ": %s\n", msg);
}
/* Static storage space to store the updated environment variable. */
static char kwsys_shared_forward_ldpath[KWSYS_SHARED_FORWARD_MAXPATH*16] = KWSYS_SHARED_FORWARD_LDPATH "=";
/*--------------------------------------------------------------------------*/
/* Main driver function to be called from main. */
static int @KWSYS_NAMESPACE@_shared_forward_to_real(int argc, char** argv_in)
{
char const** argv = (char const**)argv_in;
/* Get the directory containing this executable. */
char self_path[KWSYS_SHARED_FORWARD_MAXPATH];
if(kwsys_shared_forward_self_path(argv[0], self_path))
{
/* Found this executable. Use it to get the library directory. */
char exe[KWSYS_SHARED_FORWARD_MAXPATH];
if(kwsys_shared_forward_get_settings(self_path,
kwsys_shared_forward_ldpath, exe))
{
/* Append the old runtime search path. */
const char* old_ldpath = getenv(KWSYS_SHARED_FORWARD_LDPATH);
if(old_ldpath)
{
strcat(kwsys_shared_forward_ldpath, kwsys_shared_forward_path_sep);
strcat(kwsys_shared_forward_ldpath, old_ldpath);
}
/* Store the environment variable. */
putenv(kwsys_shared_forward_ldpath);
#if defined(KWSYS_SHARED_FORWARD_OPTION_COMMAND)
/* Look for the command line replacement option. */
if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_COMMAND) == 0)
{
if(argc > 2)
{
/* Use the command line given. */
strcpy(exe, argv[2]);
argv += 2;
argc -= 2;
}
else
{
/* The option was not given an executable. */
fprintf(stderr, "Option " KWSYS_SHARED_FORWARD_OPTION_COMMAND
" must be followed by a command line.\n");
return 1;
}
}
#endif
#if defined(KWSYS_SHARED_FORWARD_OPTION_PRINT)
/* Look for the print command line option. */
if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_PRINT) == 0)
{
fprintf(stdout, "%s\n", kwsys_shared_forward_ldpath);
fprintf(stdout, "%s\n", exe);
return 0;
}
#endif
#if defined(KWSYS_SHARED_FORWARD_OPTION_LDD)
/* Look for the ldd command line option. */
if(argc > 1 && strcmp(argv[1], KWSYS_SHARED_FORWARD_OPTION_LDD) == 0)
{
# if defined(KWSYS_SHARED_FORWARD_LDD)
/* Use the named ldd-like executable and arguments. */
char const* ldd_argv[] = {KWSYS_SHARED_FORWARD_LDD, 0, 0};
ldd_argv[KWSYS_SHARED_FORWARD_LDD_N] = exe;
kwsys_shared_forward_execvp(ldd_argv[0], ldd_argv);
/* Report why execution failed. */
kwsys_shared_forward_print_failure(ldd_argv);
return 1;
# else
/* We have no ldd-like executable available on this platform. */
fprintf(stderr, "No ldd-like tool is known to this executable.\n");
return 1;
# endif
}
#endif
/* Replace this process with the real executable. */
argv[0] = exe;
kwsys_shared_forward_execvp(argv[0], argv);
/* Report why execution failed. */
kwsys_shared_forward_print_failure(argv);
}
else
{
/* Could not convert self path to the library directory. */
}
}
else
{
/* Could not find this executable. */
fprintf(stderr, "Error locating executable \"%s\".\n", argv[0]);
}
/* Avoid unused argument warning. */
(void)argc;
/* Exit with failure. */
return 1;
}
#else
# error "@KWSYS_NAMESPACE@/SharedForward.h should be included only once."
#endif

115
String.c Normal file
View File

@ -0,0 +1,115 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifdef KWSYS_STRING_C
/*
All code in this source file is conditionally compiled to work-around
template definition auto-search on VMS. Other source files in this
directory that use the stl string cause the compiler to load this
source to try to get the definition of the string template. This
condition blocks the compiler from seeing the symbols defined here.
*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(String.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "String.h.in"
#endif
/* Select an implementation for strcasecmp. */
#if defined(_MSC_VER)
# define KWSYS_STRING_USE_STRICMP
# include <string.h>
#elif defined(__GNUC__)
# define KWSYS_STRING_USE_STRCASECMP
# include <strings.h>
#else
/* Table to convert upper case letters to lower case and leave all
other characters alone. */
static char kwsysString_strcasecmp_tolower[] =
{
'\000', '\001', '\002', '\003', '\004', '\005', '\006', '\007',
'\010', '\011', '\012', '\013', '\014', '\015', '\016', '\017',
'\020', '\021', '\022', '\023', '\024', '\025', '\026', '\027',
'\030', '\031', '\032', '\033', '\034', '\035', '\036', '\037',
'\040', '\041', '\042', '\043', '\044', '\045', '\046', '\047',
'\050', '\051', '\052', '\053', '\054', '\055', '\056', '\057',
'\060', '\061', '\062', '\063', '\064', '\065', '\066', '\067',
'\070', '\071', '\072', '\073', '\074', '\075', '\076', '\077',
'\100', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
'\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
'\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
'\170', '\171', '\172', '\133', '\134', '\135', '\136', '\137',
'\140', '\141', '\142', '\143', '\144', '\145', '\146', '\147',
'\150', '\151', '\152', '\153', '\154', '\155', '\156', '\157',
'\160', '\161', '\162', '\163', '\164', '\165', '\166', '\167',
'\170', '\171', '\172', '\173', '\174', '\175', '\176', '\177',
'\200', '\201', '\202', '\203', '\204', '\205', '\206', '\207',
'\210', '\211', '\212', '\213', '\214', '\215', '\216', '\217',
'\220', '\221', '\222', '\223', '\224', '\225', '\226', '\227',
'\230', '\231', '\232', '\233', '\234', '\235', '\236', '\237',
'\240', '\241', '\242', '\243', '\244', '\245', '\246', '\247',
'\250', '\251', '\252', '\253', '\254', '\255', '\256', '\257',
'\260', '\261', '\262', '\263', '\264', '\265', '\266', '\267',
'\270', '\271', '\272', '\273', '\274', '\275', '\276', '\277',
'\300', '\301', '\302', '\303', '\304', '\305', '\306', '\307',
'\310', '\311', '\312', '\313', '\314', '\315', '\316', '\317',
'\320', '\321', '\322', '\323', '\324', '\325', '\326', '\327',
'\330', '\331', '\332', '\333', '\334', '\335', '\336', '\337',
'\340', '\341', '\342', '\343', '\344', '\345', '\346', '\347',
'\350', '\351', '\352', '\353', '\354', '\355', '\356', '\357',
'\360', '\361', '\362', '\363', '\364', '\365', '\366', '\367',
'\370', '\371', '\372', '\373', '\374', '\375', '\376', '\377'
};
#endif
/*--------------------------------------------------------------------------*/
int kwsysString_strcasecmp(const char* lhs, const char* rhs)
{
#if defined(KWSYS_STRING_USE_STRICMP)
return _stricmp(lhs, rhs);
#elif defined(KWSYS_STRING_USE_STRCASECMP)
return strcasecmp(lhs, rhs);
#else
const char* const lower = kwsysString_strcasecmp_tolower;
unsigned char const* us1 = (unsigned char const*)lhs;
unsigned char const* us2 = (unsigned char const*)rhs;
int result;
while((result = lower[*us1] - lower[*us2++], result == 0) && *us1++)
{
}
return result;
#endif
}
/*--------------------------------------------------------------------------*/
int kwsysString_strncasecmp(const char* lhs, const char* rhs, size_t n)
{
#if defined(KWSYS_STRING_USE_STRICMP)
return _strnicmp(lhs, rhs, n);
#elif defined(KWSYS_STRING_USE_STRCASECMP)
return strncasecmp(lhs, rhs, n);
#else
const char* const lower = kwsysString_strcasecmp_tolower;
unsigned char const* us1 = (unsigned char const*)lhs;
unsigned char const* us2 = (unsigned char const*)rhs;
int result = 0;
while(n && (result = lower[*us1] - lower[*us2++], result == 0) && *us1++)
{
--n;
}
return result;
#endif
}
#endif /* KWSYS_STRING_C */

67
String.h.in Normal file
View File

@ -0,0 +1,67 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_String_h
#define @KWSYS_NAMESPACE@_String_h
#include <@KWSYS_NAMESPACE@/Configure.h>
#include <stddef.h> /* size_t */
/* Redefine all public interface symbol names to be in the proper
namespace. These macros are used internally to kwsys only, and are
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysString_strcasecmp kwsys_ns(String_strcasecmp)
# define kwsysString_strncasecmp kwsys_ns(String_strncasecmp)
#endif
#if defined(__cplusplus)
extern "C"
{
#endif
/**
* Compare two strings ignoring the case of the characters. The
* integer returned is negative, zero, or positive if the first string
* is found to be less than, equal to, or greater than the second
* string, respectively.
*/
kwsysEXPORT int kwsysString_strcasecmp(const char* lhs, const char* rhs);
/**
* Identical to String_strcasecmp except that only the first n
* characters are considered.
*/
kwsysEXPORT int kwsysString_strncasecmp(const char* lhs, const char* rhs,
size_t n);
#if defined(__cplusplus)
} /* extern "C" */
#endif
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
# undef kwsys_ns
# undef kwsysEXPORT
# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysString_strcasecmp
# undef kwsysString_strncasecmp
# endif
#endif
#endif

65
String.hxx.in Normal file
View File

@ -0,0 +1,65 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_String_hxx
#define @KWSYS_NAMESPACE@_String_hxx
#include <@KWSYS_NAMESPACE@/stl/string>
namespace @KWSYS_NAMESPACE@
{
/** \class String
* \brief Short-name version of the STL basic_string class template.
*
* The standard library "string" type is actually a typedef for
* "basic_string<..long argument list..>". This string class is
* simply a subclass of this type with the same interface so that the
* name is shorter in debugging symbols and error messages.
*/
class String: public @KWSYS_NAMESPACE@_stl::string
{
/** The original string type. */
typedef @KWSYS_NAMESPACE@_stl::string stl_string;
public:
/** String member types. */
typedef stl_string::value_type value_type;
typedef stl_string::pointer pointer;
typedef stl_string::reference reference;
typedef stl_string::const_reference const_reference;
typedef stl_string::size_type size_type;
typedef stl_string::difference_type difference_type;
typedef stl_string::iterator iterator;
typedef stl_string::const_iterator const_iterator;
typedef stl_string::reverse_iterator reverse_iterator;
typedef stl_string::const_reverse_iterator const_reverse_iterator;
/** String constructors. */
String(): stl_string() {}
String(const value_type* s): stl_string(s) {}
String(const value_type* s, size_type n): stl_string(s, n) {}
String(const stl_string& s, size_type pos=0, size_type n=npos):
stl_string(s, pos, n) {}
}; // End Class: String
#if defined(__WATCOMC__)
inline bool operator<(String const& l, String const& r)
{
return (static_cast<@KWSYS_NAMESPACE@_stl::string const&>(l) <
static_cast<@KWSYS_NAMESPACE@_stl::string const&>(r));
}
#endif
} // namespace @KWSYS_NAMESPACE@
#endif

856
System.c Normal file
View File

@ -0,0 +1,856 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(System.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "System.h.in"
#endif
#include <stddef.h> /* ptrdiff_t */
#include <stdlib.h> /* malloc, free */
#include <string.h> /* strlen */
#include <ctype.h> /* isalpha */
#include <stdio.h>
#if defined(KWSYS_C_HAS_PTRDIFF_T) && KWSYS_C_HAS_PTRDIFF_T
typedef ptrdiff_t kwsysSystem_ptrdiff_t;
#else
typedef int kwsysSystem_ptrdiff_t;
#endif
/*
Notes:
Make variable replacements open a can of worms. Sometimes they should
be quoted and sometimes not. Sometimes their replacement values are
already quoted.
VS variables cause problems. In order to pass the referenced value
with spaces the reference must be quoted. If the variable value ends
in a backslash then it will escape the ending quote! In order to make
the ending backslash appear we need this:
"$(InputDir)\"
However if there is not a trailing backslash then this will put a
quote in the value so we need:
"$(InputDir)"
Make variable references are platform specific so we should probably
just NOT quote them and let the listfile author deal with it.
*/
/*
TODO: For windows echo:
To display a pipe (|) or redirection character (< or >) when using the
echo command, use a caret character immediately before the pipe or
redirection character (for example, ^>, ^<, or ^| ). If you need to
use the caret character itself (^), use two in a row (^^).
*/
/*--------------------------------------------------------------------------*/
static int kwsysSystem_Shell__CharIsWhitespace(char c)
{
return ((c == ' ') || (c == '\t'));
}
/*--------------------------------------------------------------------------*/
static int kwsysSystem_Shell__CharNeedsQuotesOnUnix(char c)
{
return ((c == '\'') || (c == '`') || (c == ';') || (c == '#') ||
(c == '&') || (c == '$') || (c == '(') || (c == ')') ||
(c == '~') || (c == '<') || (c == '>') || (c == '|') ||
(c == '*') || (c == '^') || (c == '\\'));
}
/*--------------------------------------------------------------------------*/
static int kwsysSystem_Shell__CharNeedsQuotesOnWindows(char c)
{
return ((c == '\'') || (c == '#') || (c == '&') ||
(c == '<') || (c == '>') || (c == '|') || (c == '^'));
}
/*--------------------------------------------------------------------------*/
static int kwsysSystem_Shell__CharNeedsQuotes(char c, int isUnix, int flags)
{
/* On Windows the built-in command shell echo never needs quotes. */
if(!isUnix && (flags & kwsysSystem_Shell_Flag_EchoWindows))
{
return 0;
}
/* On all platforms quotes are needed to preserve whitespace. */
if(kwsysSystem_Shell__CharIsWhitespace(c))
{
return 1;
}
if(isUnix)
{
/* On UNIX several special characters need quotes to preserve them. */
if(kwsysSystem_Shell__CharNeedsQuotesOnUnix(c))
{
return 1;
}
}
else
{
/* On Windows several special characters need quotes to preserve them. */
if(kwsysSystem_Shell__CharNeedsQuotesOnWindows(c))
{
return 1;
}
}
return 0;
}
/*--------------------------------------------------------------------------*/
static int kwsysSystem_Shell__CharIsMakeVariableName(char c)
{
return c && (c == '_' || isalpha(((int)c)));
}
/*--------------------------------------------------------------------------*/
static const char* kwsysSystem_Shell__SkipMakeVariables(const char* c)
{
while(*c == '$' && *(c+1) == '(')
{
const char* skip = c+2;
while(kwsysSystem_Shell__CharIsMakeVariableName(*skip))
{
++skip;
}
if(*skip == ')')
{
c = skip+1;
}
else
{
break;
}
}
return c;
}
/*
Allowing make variable replacements opens a can of worms. Sometimes
they should be quoted and sometimes not. Sometimes their replacement
values are already quoted or contain escapes.
Some Visual Studio variables cause problems. In order to pass the
referenced value with spaces the reference must be quoted. If the
variable value ends in a backslash then it will escape the ending
quote! In order to make the ending backslash appear we need this:
"$(InputDir)\"
However if there is not a trailing backslash then this will put a
quote in the value so we need:
"$(InputDir)"
This macro decides whether we quote an argument just because it
contains a make variable reference. This should be replaced with a
flag later when we understand applications of this better.
*/
#define KWSYS_SYSTEM_SHELL_QUOTE_MAKE_VARIABLES 0
/*--------------------------------------------------------------------------*/
static int kwsysSystem_Shell__ArgumentNeedsQuotes(const char* in, int isUnix,
int flags)
{
/* The empty string needs quotes. */
if(!*in)
{
return 1;
}
/* Scan the string for characters that require quoting. */
{
const char* c;
for(c=in; *c; ++c)
{
/* Look for $(MAKEVAR) syntax if requested. */
if(flags & kwsysSystem_Shell_Flag_AllowMakeVariables)
{
#if KWSYS_SYSTEM_SHELL_QUOTE_MAKE_VARIABLES
const char* skip = kwsysSystem_Shell__SkipMakeVariables(c);
if(skip != c)
{
/* We need to quote make variable references to preserve the
string with contents substituted in its place. */
return 1;
}
#else
/* Skip over the make variable references if any are present. */
c = kwsysSystem_Shell__SkipMakeVariables(c);
/* Stop if we have reached the end of the string. */
if(!*c)
{
break;
}
#endif
}
/* Check whether this character needs quotes. */
if(kwsysSystem_Shell__CharNeedsQuotes(*c, isUnix, flags))
{
return 1;
}
}
}
/* On Windows some single character arguments need quotes. */
if(!isUnix && *in && !*(in+1))
{
char c = *in;
if((c == '?') || (c == '&') || (c == '^') || (c == '|') || (c == '#'))
{
return 1;
}
}
return 0;
}
/*--------------------------------------------------------------------------*/
static int kwsysSystem_Shell__GetArgumentSize(const char* in,
int isUnix, int flags)
{
/* Start with the length of the original argument, plus one for
either a terminating null or a separating space. */
int size = (int)strlen(in) + 1;
/* String iterator. */
const char* c;
/* Keep track of how many backslashes have been encountered in a row. */
int windows_backslashes = 0;
/* Scan the string for characters that require escaping or quoting. */
for(c=in; *c; ++c)
{
/* Look for $(MAKEVAR) syntax if requested. */
if(flags & kwsysSystem_Shell_Flag_AllowMakeVariables)
{
/* Skip over the make variable references if any are present. */
c = kwsysSystem_Shell__SkipMakeVariables(c);
/* Stop if we have reached the end of the string. */
if(!*c)
{
break;
}
}
/* Check whether this character needs escaping for the shell. */
if(isUnix)
{
/* On Unix a few special characters need escaping even inside a
quoted argument. */
if(*c == '\\' || *c == '"' || *c == '`' || *c == '$')
{
/* This character needs a backslash to escape it. */
++size;
}
}
else if(flags & kwsysSystem_Shell_Flag_EchoWindows)
{
/* On Windows the built-in command shell echo never needs escaping. */
}
else
{
/* On Windows only backslashes and double-quotes need escaping. */
if(*c == '\\')
{
/* Found a backslash. It may need to be escaped later. */
++windows_backslashes;
}
else if(*c == '"')
{
/* Found a double-quote. We need to escape it and all
immediately preceding backslashes. */
size += windows_backslashes + 1;
windows_backslashes = 0;
}
else
{
/* Found another character. This eliminates the possibility
that any immediately preceding backslashes will be
escaped. */
windows_backslashes = 0;
}
}
/* Check whether this character needs escaping for a make tool. */
if(*c == '$')
{
if(flags & kwsysSystem_Shell_Flag_Make)
{
/* In Makefiles a dollar is written $$ so we need one extra
character. */
++size;
}
else if(flags & kwsysSystem_Shell_Flag_VSIDE)
{
/* In a VS IDE a dollar is written "$" so we need two extra
characters. */
size += 2;
}
}
else if(*c == '#')
{
if((flags & kwsysSystem_Shell_Flag_Make) &&
(flags & kwsysSystem_Shell_Flag_WatcomWMake))
{
/* In Watcom WMake makefiles a pound is written $# so we need
one extra character. */
++size;
}
}
else if(*c == '%')
{
if((flags & kwsysSystem_Shell_Flag_VSIDE) ||
((flags & kwsysSystem_Shell_Flag_Make) &&
((flags & kwsysSystem_Shell_Flag_MinGWMake) ||
(flags & kwsysSystem_Shell_Flag_NMake))))
{
/* In the VS IDE, NMake, or MinGW make a percent is written %%
so we need one extra characters. */
size += 1;
}
}
else if(*c == ';')
{
if(flags & kwsysSystem_Shell_Flag_VSIDE)
{
/* In a VS IDE a semicolon is written ";" so we need two extra
characters. */
size += 2;
}
}
}
/* Check whether the argument needs surrounding quotes. */
if(kwsysSystem_Shell__ArgumentNeedsQuotes(in, isUnix, flags))
{
/* Surrounding quotes are needed. Allocate space for them. */
size += 2;
/* We must escape all ending backslashes when quoting on windows. */
size += windows_backslashes;
}
return size;
}
/*--------------------------------------------------------------------------*/
static char* kwsysSystem_Shell__GetArgument(const char* in, char* out,
int isUnix, int flags)
{
/* String iterator. */
const char* c;
/* Keep track of how many backslashes have been encountered in a row. */
int windows_backslashes = 0;
/* Whether the argument must be quoted. */
int needQuotes = kwsysSystem_Shell__ArgumentNeedsQuotes(in, isUnix, flags);
if(needQuotes)
{
/* Add the opening quote for this argument. */
*out++ = '"';
}
/* Scan the string for characters that require escaping or quoting. */
for(c=in; *c; ++c)
{
/* Look for $(MAKEVAR) syntax if requested. */
if(flags & kwsysSystem_Shell_Flag_AllowMakeVariables)
{
const char* skip = kwsysSystem_Shell__SkipMakeVariables(c);
if(skip != c)
{
/* Copy to the end of the make variable references. */
while(c != skip)
{
*out++ = *c++;
}
/* The make variable reference eliminates any escaping needed
for preceding backslashes. */
windows_backslashes = 0;
/* Stop if we have reached the end of the string. */
if(!*c)
{
break;
}
}
}
/* Check whether this character needs escaping for the shell. */
if(isUnix)
{
/* On Unix a few special characters need escaping even inside a
quoted argument. */
if(*c == '\\' || *c == '"' || *c == '`' || *c == '$')
{
/* This character needs a backslash to escape it. */
*out++ = '\\';
}
}
else if(flags & kwsysSystem_Shell_Flag_EchoWindows)
{
/* On Windows the built-in command shell echo never needs escaping. */
}
else
{
/* On Windows only backslashes and double-quotes need escaping. */
if(*c == '\\')
{
/* Found a backslash. It may need to be escaped later. */
++windows_backslashes;
}
else if(*c == '"')
{
/* Found a double-quote. Escape all immediately preceding
backslashes. */
while(windows_backslashes > 0)
{
--windows_backslashes;
*out++ = '\\';
}
/* Add the backslash to escape the double-quote. */
*out++ = '\\';
}
else
{
/* We encountered a normal character. This eliminates any
escaping needed for preceding backslashes. */
windows_backslashes = 0;
}
}
/* Check whether this character needs escaping for a make tool. */
if(*c == '$')
{
if(flags & kwsysSystem_Shell_Flag_Make)
{
/* In Makefiles a dollar is written $$. The make tool will
replace it with just $ before passing it to the shell. */
*out++ = '$';
*out++ = '$';
}
else if(flags & kwsysSystem_Shell_Flag_VSIDE)
{
/* In a VS IDE a dollar is written "$". If this is written in
an un-quoted argument it starts a quoted segment, inserts
the $ and ends the segment. If it is written in a quoted
argument it ends quoting, inserts the $ and restarts
quoting. Either way the $ is isolated from surrounding
text to avoid looking like a variable reference. */
*out++ = '"';
*out++ = '$';
*out++ = '"';
}
else
{
/* Otherwise a dollar is written just $. */
*out++ = '$';
}
}
else if(*c == '#')
{
if((flags & kwsysSystem_Shell_Flag_Make) &&
(flags & kwsysSystem_Shell_Flag_WatcomWMake))
{
/* In Watcom WMake makefiles a pound is written $#. The make
tool will replace it with just # before passing it to the
shell. */
*out++ = '$';
*out++ = '#';
}
else
{
/* Otherwise a pound is written just #. */
*out++ = '#';
}
}
else if(*c == '%')
{
if((flags & kwsysSystem_Shell_Flag_VSIDE) ||
((flags & kwsysSystem_Shell_Flag_Make) &&
((flags & kwsysSystem_Shell_Flag_MinGWMake) ||
(flags & kwsysSystem_Shell_Flag_NMake))))
{
/* In the VS IDE, NMake, or MinGW make a percent is written %%. */
*out++ = '%';
*out++ = '%';
}
else
{
/* Otherwise a percent is written just %. */
*out++ = '%';
}
}
else if(*c == ';')
{
if(flags & kwsysSystem_Shell_Flag_VSIDE)
{
/* In a VS IDE a semicolon is written ";". If this is written
in an un-quoted argument it starts a quoted segment,
inserts the ; and ends the segment. If it is written in a
quoted argument it ends quoting, inserts the ; and restarts
quoting. Either way the ; is isolated. */
*out++ = '"';
*out++ = ';';
*out++ = '"';
}
else
{
/* Otherwise a semicolon is written just ;. */
*out++ = ';';
}
}
else
{
/* Store this character. */
*out++ = *c;
}
}
if(needQuotes)
{
/* Add enough backslashes to escape any trailing ones. */
while(windows_backslashes > 0)
{
--windows_backslashes;
*out++ = '\\';
}
/* Add the closing quote for this argument. */
*out++ = '"';
}
/* Store a terminating null without incrementing. */
*out = 0;
return out;
}
/*--------------------------------------------------------------------------*/
char* kwsysSystem_Shell_GetArgumentForWindows(const char* in,
char* out,
int flags)
{
return kwsysSystem_Shell__GetArgument(in, out, 0, flags);
}
/*--------------------------------------------------------------------------*/
char* kwsysSystem_Shell_GetArgumentForUnix(const char* in,
char* out,
int flags)
{
return kwsysSystem_Shell__GetArgument(in, out, 1, flags);
}
/*--------------------------------------------------------------------------*/
int kwsysSystem_Shell_GetArgumentSizeForWindows(const char* in, int flags)
{
return kwsysSystem_Shell__GetArgumentSize(in, 0, flags);
}
/*--------------------------------------------------------------------------*/
int kwsysSystem_Shell_GetArgumentSizeForUnix(const char* in, int flags)
{
return kwsysSystem_Shell__GetArgumentSize(in, 1, flags);
}
/*--------------------------------------------------------------------------*/
static int kwsysSystem__AppendByte(char* local,
char** begin, char** end,
int* size, char c)
{
/* Allocate space for the character. */
if((*end - *begin) >= *size)
{
kwsysSystem_ptrdiff_t length = *end - *begin;
char* newBuffer = (char*)malloc((size_t)(*size*2));
if(!newBuffer)
{
return 0;
}
memcpy(newBuffer, *begin, (size_t)(length)*sizeof(char));
if(*begin != local)
{
free(*begin);
}
*begin = newBuffer;
*end = *begin + length;
*size *= 2;
}
/* Store the character. */
*(*end)++ = c;
return 1;
}
/*--------------------------------------------------------------------------*/
static int kwsysSystem__AppendArgument(char** local,
char*** begin, char*** end,
int* size,
char* arg_local,
char** arg_begin, char** arg_end,
int* arg_size)
{
/* Append a null-terminator to the argument string. */
if(!kwsysSystem__AppendByte(arg_local, arg_begin, arg_end, arg_size, '\0'))
{
return 0;
}
/* Allocate space for the argument pointer. */
if((*end - *begin) >= *size)
{
kwsysSystem_ptrdiff_t length = *end - *begin;
char** newPointers = (char**)malloc((size_t)(*size)*2*sizeof(char*));
if(!newPointers)
{
return 0;
}
memcpy(newPointers, *begin, (size_t)(length)*sizeof(char*));
if(*begin != local)
{
free(*begin);
}
*begin = newPointers;
*end = *begin + length;
*size *= 2;
}
/* Allocate space for the argument string. */
**end = (char*)malloc((size_t)(*arg_end - *arg_begin));
if(!**end)
{
return 0;
}
/* Store the argument in the command array. */
memcpy(**end, *arg_begin,(size_t)(*arg_end - *arg_begin));
++(*end);
/* Reset the argument to be empty. */
*arg_end = *arg_begin;
return 1;
}
/*--------------------------------------------------------------------------*/
#define KWSYSPE_LOCAL_BYTE_COUNT 1024
#define KWSYSPE_LOCAL_ARGS_COUNT 32
static char** kwsysSystem__ParseUnixCommand(const char* command, int flags)
{
/* Create a buffer for argument pointers during parsing. */
char* local_pointers[KWSYSPE_LOCAL_ARGS_COUNT];
int pointers_size = KWSYSPE_LOCAL_ARGS_COUNT;
char** pointer_begin = local_pointers;
char** pointer_end = pointer_begin;
/* Create a buffer for argument strings during parsing. */
char local_buffer[KWSYSPE_LOCAL_BYTE_COUNT];
int buffer_size = KWSYSPE_LOCAL_BYTE_COUNT;
char* buffer_begin = local_buffer;
char* buffer_end = buffer_begin;
/* Parse the command string. Try to behave like a UNIX shell. */
char** newCommand = 0;
const char* c = command;
int in_argument = 0;
int in_escape = 0;
int in_single = 0;
int in_double = 0;
int failed = 0;
for(;*c; ++c)
{
if(in_escape)
{
/* This character is escaped so do no special handling. */
if(!in_argument)
{
in_argument = 1;
}
if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
&buffer_end, &buffer_size, *c))
{
failed = 1;
break;
}
in_escape = 0;
}
else if(*c == '\\')
{
/* The next character should be escaped. */
in_escape = 1;
}
else if(*c == '\'' && !in_double)
{
/* Enter or exit single-quote state. */
if(in_single)
{
in_single = 0;
}
else
{
in_single = 1;
if(!in_argument)
{
in_argument = 1;
}
}
}
else if(*c == '"' && !in_single)
{
/* Enter or exit double-quote state. */
if(in_double)
{
in_double = 0;
}
else
{
in_double = 1;
if(!in_argument)
{
in_argument = 1;
}
}
}
else if(isspace((unsigned char) *c))
{
if(in_argument)
{
if(in_single || in_double)
{
/* This space belongs to a quoted argument. */
if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
&buffer_end, &buffer_size, *c))
{
failed = 1;
break;
}
}
else
{
/* This argument has been terminated by whitespace. */
if(!kwsysSystem__AppendArgument(local_pointers, &pointer_begin,
&pointer_end, &pointers_size,
local_buffer, &buffer_begin,
&buffer_end, &buffer_size))
{
failed = 1;
break;
}
in_argument = 0;
}
}
}
else
{
/* This character belong to an argument. */
if(!in_argument)
{
in_argument = 1;
}
if(!kwsysSystem__AppendByte(local_buffer, &buffer_begin,
&buffer_end, &buffer_size, *c))
{
failed = 1;
break;
}
}
}
/* Finish the last argument. */
if(in_argument)
{
if(!kwsysSystem__AppendArgument(local_pointers, &pointer_begin,
&pointer_end, &pointers_size,
local_buffer, &buffer_begin,
&buffer_end, &buffer_size))
{
failed = 1;
}
}
/* If we still have memory allocate space for the new command
buffer. */
if(!failed)
{
kwsysSystem_ptrdiff_t n = pointer_end - pointer_begin;
newCommand = (char**)malloc((size_t)(n+1)*sizeof(char*));
}
if(newCommand)
{
/* Copy the arguments into the new command buffer. */
kwsysSystem_ptrdiff_t n = pointer_end - pointer_begin;
memcpy(newCommand, pointer_begin, sizeof(char*)*(size_t)(n));
newCommand[n] = 0;
}
else
{
/* Free arguments already allocated. */
while(pointer_end != pointer_begin)
{
free(*(--pointer_end));
}
}
/* Free temporary buffers. */
if(pointer_begin != local_pointers)
{
free(pointer_begin);
}
if(buffer_begin != local_buffer)
{
free(buffer_begin);
}
/* The flags argument is currently unused. */
(void)flags;
/* Return the final command buffer. */
return newCommand;
}
/*--------------------------------------------------------------------------*/
char** kwsysSystem_Parse_CommandForUnix(const char* command, int flags)
{
/* Validate the flags. */
if(flags != 0)
{
return 0;
}
/* Forward to our internal implementation. */
return kwsysSystem__ParseUnixCommand(command, flags);
}

162
System.h.in Normal file
View File

@ -0,0 +1,162 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_System_h
#define @KWSYS_NAMESPACE@_System_h
#include <@KWSYS_NAMESPACE@/Configure.h>
/* Redefine all public interface symbol names to be in the proper
namespace. These macros are used internally to kwsys only, and are
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysSystem_Parse_CommandForUnix kwsys_ns(System_Parse_CommandForUnix)
# define kwsysSystem_Shell_GetArgumentForWindows kwsys_ns(System_Shell_GetArgumentForWindows)
# define kwsysSystem_Shell_GetArgumentForUnix kwsys_ns(System_Shell_GetArgumentForUnix)
# define kwsysSystem_Shell_GetArgumentSizeForWindows kwsys_ns(System_Shell_GetArgumentSizeForWindows)
# define kwsysSystem_Shell_GetArgumentSizeForUnix kwsys_ns(System_Shell_GetArgumentSizeForUnix)
# define kwsysSystem_Shell_Flag_e kwsys_ns(System_Shell_Flag_e)
# define kwsysSystem_Shell_Flag_Make kwsys_ns(System_Shell_Flag_Make)
# define kwsysSystem_Shell_Flag_VSIDE kwsys_ns(System_Shell_Flag_VSIDE)
# define kwsysSystem_Shell_Flag_EchoWindows kwsys_ns(System_Shell_Flag_EchoWindows)
# define kwsysSystem_Shell_Flag_WatcomWMake kwsys_ns(System_Shell_Flag_WatcomWMake)
# define kwsysSystem_Shell_Flag_MinGWMake kwsys_ns(System_Shell_Flag_MinGWMake)
# define kwsysSystem_Shell_Flag_NMake kwsys_ns(System_Shell_Flag_NMake)
# define kwsysSystem_Shell_Flag_AllowMakeVariables kwsys_ns(System_Shell_Flag_AllowMakeVariables)
#endif
#ifdef __VMS
#define @KWSYS_NAMESPACE@System_Shell_GetArgumentForUnix \
@KWSYS_NAMESPACE@System_Shell_UnixGA
#define @KWSYS_NAMESPACE@System_Shell_GetArgumentSizeForUnix \
@KWSYS_NAMESPACE@System_Shell_UnixGAS
#define @KWSYS_NAMESPACE@System_Shell_GetArgumentForWindows \
@KWSYS_NAMESPACE@System_Shell_WindowsGA
#endif
#if defined(__cplusplus)
extern "C"
{
#endif
/**
* Transform the given command line argument for use in a Windows or
* Unix shell. Returns a pointer to the end of the command line
* argument in the provided output buffer. Flags may be passed to
* modify the generated quoting and escape sequences to work under
* alternative environments.
*/
kwsysEXPORT char* kwsysSystem_Shell_GetArgumentForWindows(const char* in,
char* out,
int flags);
kwsysEXPORT char* kwsysSystem_Shell_GetArgumentForUnix(const char* in,
char* out,
int flags);
/**
* Compute the size of the buffer required to store the output from
* kwsysSystem_Shell_GetArgumentForWindows or
* kwsysSystem_Shell_GetArgumentForUnix. The flags passed must be
* identical between the two calls.
*/
kwsysEXPORT int kwsysSystem_Shell_GetArgumentSizeForWindows(const char* in,
int flags);
kwsysEXPORT int kwsysSystem_Shell_GetArgumentSizeForUnix(const char* in,
int flags);
/**
* Flags to pass to kwsysSystem_Shell_GetArgumentForWindows or
* kwsysSystem_Shell_GetArgumentForUnix. These modify the generated
* quoting and escape sequences to work under alternative
* environments.
*/
enum kwsysSystem_Shell_Flag_e
{
/** The target shell is in a makefile. */
kwsysSystem_Shell_Flag_Make = (1<<0),
/** The target shell is in a VS project file. Do not use with
Shell_Flag_Make. */
kwsysSystem_Shell_Flag_VSIDE = (1<<1),
/** In a windows shell the argument is being passed to "echo". */
kwsysSystem_Shell_Flag_EchoWindows = (1<<2),
/** The target shell is in a Watcom WMake makefile. */
kwsysSystem_Shell_Flag_WatcomWMake = (1<<3),
/** The target shell is in a MinGW Make makefile. */
kwsysSystem_Shell_Flag_MinGWMake = (1<<4),
/** The target shell is in a NMake makefile. */
kwsysSystem_Shell_Flag_NMake = (1<<6),
/** Make variable reference syntax $(MAKEVAR) should not be escaped
to allow a build tool to replace it. Replacement values
containing spaces, quotes, backslashes, or other
non-alphanumeric characters that have significance to some makes
or shells produce undefined behavior. */
kwsysSystem_Shell_Flag_AllowMakeVariables = (1<<5)
};
/**
* Parse a unix-style command line string into separate arguments.
*
* On success, returns a pointer to an array of pointers to individual
* argument strings. Each string is null-terminated and the last
* entry in the array is a NULL pointer (just like argv). It is the
* caller's responsibility to free() the strings and the array of
* pointers to them.
*
* On failure, returns NULL. Failure occurs only on invalid flags or
* when memory cannot be allocated; never due to content of the input
* string. Missing close-quotes are treated as if the necessary
* closing quote appears.
*
* By default single- and double-quoted arguments are supported, and
* any character may be escaped by a backslash. The flags argument is
* reserved for future use, and must be zero (or the call will fail).
*/
kwsysEXPORT char** kwsysSystem_Parse_CommandForUnix(const char* command,
int flags);
#if defined(__cplusplus)
} /* extern "C" */
#endif
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
# undef kwsys_ns
# undef kwsysEXPORT
# if !defined(KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysSystem_Parse_CommandForUnix
# undef kwsysSystem_Shell_GetArgumentForWindows
# undef kwsysSystem_Shell_GetArgumentForUnix
# undef kwsysSystem_Shell_GetArgumentSizeForWindows
# undef kwsysSystem_Shell_GetArgumentSizeForUnix
# undef kwsysSystem_Shell_Flag_e
# undef kwsysSystem_Shell_Flag_Make
# undef kwsysSystem_Shell_Flag_VSIDE
# undef kwsysSystem_Shell_Flag_EchoWindows
# undef kwsysSystem_Shell_Flag_WatcomWMake
# undef kwsysSystem_Shell_Flag_MinGWMake
# undef kwsysSystem_Shell_Flag_NMake
# undef kwsysSystem_Shell_Flag_AllowMakeVariables
# endif
#endif
#endif

3675
SystemInformation.cxx Normal file

File diff suppressed because it is too large Load Diff

88
SystemInformation.hxx.in Normal file
View File

@ -0,0 +1,88 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_SystemInformation_h
#define @KWSYS_NAMESPACE@_SystemInformation_h
/* Define these macros temporarily to keep the code readable. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsys_stl @KWSYS_NAMESPACE@_stl
# define kwsys_ios @KWSYS_NAMESPACE@_ios
#endif
#include <@KWSYS_NAMESPACE@/stl/string>
#include <stddef.h> /* size_t */
namespace @KWSYS_NAMESPACE@
{
// forward declare the implementation class
class SystemInformationImplementation;
class @KWSYS_NAMESPACE@_EXPORT SystemInformation
{
public:
SystemInformation ();
~SystemInformation ();
const char * GetVendorString();
const char * GetVendorID();
kwsys_stl::string GetTypeID();
kwsys_stl::string GetFamilyID();
kwsys_stl::string GetModelID();
kwsys_stl::string GetSteppingCode();
const char * GetExtendedProcessorName();
const char * GetProcessorSerialNumber();
int GetProcessorCacheSize();
unsigned int GetLogicalProcessorsPerPhysical();
float GetProcessorClockFrequency();
int GetProcessorAPICID();
int GetProcessorCacheXSize(long int);
bool DoesCPUSupportFeature(long int);
const char * GetOSName();
const char * GetHostname();
const char * GetOSRelease();
const char * GetOSVersion();
const char * GetOSPlatform();
bool Is64Bits();
unsigned int GetNumberOfLogicalCPU(); // per physical cpu
unsigned int GetNumberOfPhysicalCPU();
bool DoesCPUSupportCPUID();
// Retrieve memory information in megabyte.
size_t GetTotalVirtualMemory();
size_t GetAvailableVirtualMemory();
size_t GetTotalPhysicalMemory();
size_t GetAvailablePhysicalMemory();
/** Run the different checks */
void RunCPUCheck();
void RunOSCheck();
void RunMemoryCheck();
private:
SystemInformationImplementation* Implementation;
};
} // namespace @KWSYS_NAMESPACE@
/* Undefine temporary macros. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsys_stl
# undef kwsys_ios
#endif
#endif

4860
SystemTools.cxx Normal file

File diff suppressed because it is too large Load Diff

904
SystemTools.hxx.in Normal file
View File

@ -0,0 +1,904 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_SystemTools_hxx
#define @KWSYS_NAMESPACE@_SystemTools_hxx
#include <@KWSYS_NAMESPACE@/ios/iosfwd>
#include <@KWSYS_NAMESPACE@/stl/string>
#include <@KWSYS_NAMESPACE@/stl/vector>
#include <@KWSYS_NAMESPACE@/stl/map>
#include <@KWSYS_NAMESPACE@/Configure.h>
#include <@KWSYS_NAMESPACE@/String.hxx>
#include <sys/types.h>
// Required for va_list
#include <stdarg.h>
#if @KWSYS_NAMESPACE@_STL_HAVE_STD && !defined(va_list)
// Some compilers move va_list into the std namespace and there is no way to
// tell that this has been done. Playing with things being included before or
// after stdarg.h does not solve things because we do not have control over
// what the user does. This hack solves this problem by moving va_list to our
// own namespace that is local for kwsys.
namespace std {} // Required for platforms that do not have std namespace
namespace @KWSYS_NAMESPACE@_VA_LIST
{
using namespace std;
typedef va_list hack_va_list;
}
namespace @KWSYS_NAMESPACE@
{
typedef @KWSYS_NAMESPACE@_VA_LIST::hack_va_list va_list;
}
#endif // va_list
#if defined( _MSC_VER )
typedef unsigned short mode_t;
#endif
/* Define these macros temporarily to keep the code readable. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsys_stl @KWSYS_NAMESPACE@_stl
# define kwsys_ios @KWSYS_NAMESPACE@_ios
#endif
namespace @KWSYS_NAMESPACE@
{
class SystemToolsTranslationMap;
/** \class SystemToolsManager
* \brief Use to make sure SystemTools is initialized before it is used
* and is the last static object destroyed
*/
class @KWSYS_NAMESPACE@_EXPORT SystemToolsManager
{
public:
SystemToolsManager();
~SystemToolsManager();
};
// This instance will show up in any translation unit that uses
// SystemTools. It will make sure SystemTools is initialized
// before it is used and is the last static object destroyed.
static SystemToolsManager SystemToolsManagerInstance;
/** \class SystemTools
* \brief A collection of useful platform-independent system functions.
*/
class @KWSYS_NAMESPACE@_EXPORT SystemTools
{
public:
/** -----------------------------------------------------------------
* String Manipulation Routines
* -----------------------------------------------------------------
*/
/**
* Replace symbols in str that are not valid in C identifiers as
* defined by the 1999 standard, ie. anything except [A-Za-z0-9_].
* They are replaced with `_' and if the first character is a digit
* then an underscore is prepended. Note that this can produce
* identifiers that the standard reserves (_[A-Z].* and __.*).
*/
static kwsys_stl::string MakeCindentifier(const char* s);
/**
* Replace replace all occurences of the string in the source string.
*/
static void ReplaceString(kwsys_stl::string& source,
const char* replace,
const char* with);
/**
* Return a capitalized string (i.e the first letter is uppercased,
* all other are lowercased).
*/
static kwsys_stl::string Capitalized(const kwsys_stl::string&);
/**
* Return a 'capitalized words' string (i.e the first letter of each word
* is uppercased all other are left untouched though).
*/
static kwsys_stl::string CapitalizedWords(const kwsys_stl::string&);
/**
* Return a 'uncapitalized words' string (i.e the first letter of each word
* is lowercased all other are left untouched though).
*/
static kwsys_stl::string UnCapitalizedWords(const kwsys_stl::string&);
/**
* Return a lower case string
*/
static kwsys_stl::string LowerCase(const kwsys_stl::string&);
/**
* Return a lower case string
*/
static kwsys_stl::string UpperCase(const kwsys_stl::string&);
/**
* Count char in string
*/
static size_t CountChar(const char* str, char c);
/**
* Remove some characters from a string.
* Return a pointer to the new resulting string (allocated with 'new')
*/
static char* RemoveChars(const char* str, const char *toremove);
/**
* Remove remove all but 0->9, A->F characters from a string.
* Return a pointer to the new resulting string (allocated with 'new')
*/
static char* RemoveCharsButUpperHex(const char* str);
/**
* Replace some characters by another character in a string (in-place)
* Return a pointer to string
*/
static char* ReplaceChars(char* str, const char *toreplace,char replacement);
/**
* Returns true if str1 starts (respectively ends) with str2
*/
static bool StringStartsWith(const char* str1, const char* str2);
static bool StringEndsWith(const char* str1, const char* str2);
/**
* Returns a pointer to the last occurence of str2 in str1
*/
static const char* FindLastString(const char* str1, const char* str2);
/**
* Make a duplicate of the string similar to the strdup C function
* but use new to create the 'new' string, so one can use
* 'delete' to remove it. Returns 0 if the input is empty.
*/
static char* DuplicateString(const char* str);
/**
* Return the string cropped to a given length by removing chars in the
* center of the string and replacing them with an ellipsis (...)
*/
static kwsys_stl::string CropString(const kwsys_stl::string&,size_t max_len);
/** split a path by separator into an array of strings, default is /.
If isPath is true then the string is treated like a path and if
s starts with a / then the first element of the returned array will
be /, so /foo/bar will be [/, foo, bar]
*/
static kwsys_stl::vector<String> SplitString(const char* s, char separator = '/',
bool isPath = false);
/**
* Perform a case-independent string comparison
*/
static int Strucmp(const char *s1, const char *s2);
/**
* Convert a string in __DATE__ or __TIMESTAMP__ format into a time_t.
* Return false on error, true on success
*/
static bool ConvertDateMacroString(const char *str, time_t *tmt);
static bool ConvertTimeStampMacroString(const char *str, time_t *tmt);
/**
* Split a string on its newlines into multiple lines
* Return false only if the last line stored had no newline
*/
static bool Split(const char* s, kwsys_stl::vector<kwsys_stl::string>& l);
static bool Split(const char* s, kwsys_stl::vector<kwsys_stl::string>& l, char separator);
/**
* Return string with space added between capitalized words
* (i.e. EatMyShorts becomes Eat My Shorts )
* (note that IEatShorts becomes IEat Shorts)
*/
static kwsys_stl::string AddSpaceBetweenCapitalizedWords(
const kwsys_stl::string&);
/**
* Append two or more strings and produce new one.
* Programmer must 'delete []' the resulting string, which was allocated
* with 'new'.
* Return 0 if inputs are empty or there was an error
*/
static char* AppendStrings(
const char* str1, const char* str2);
static char* AppendStrings(
const char* str1, const char* str2, const char* str3);
/**
* Estimate the length of the string that will be produced
* from printing the given format string and arguments. The
* returned length will always be at least as large as the string
* that will result from printing.
* WARNING: since va_arg is called to iterate of the argument list,
* you will not be able to use this 'ap' anymore from the beginning.
* It's up to you to call va_end though.
*/
static int EstimateFormatLength(const char *format, va_list ap);
/**
* Escape specific characters in 'str'.
*/
static kwsys_stl::string EscapeChars(
const char *str, const char *chars_to_escape, char escape_char = '\\');
/** -----------------------------------------------------------------
* Filename Manipulation Routines
* -----------------------------------------------------------------
*/
/**
* Replace Windows file system slashes with Unix-style slashes.
*/
static void ConvertToUnixSlashes(kwsys_stl::string& path);
/**
* For windows this calls ConvertToWindowsOutputPath and for unix
* it calls ConvertToUnixOutputPath
*/
static kwsys_stl::string ConvertToOutputPath(const char*);
/**
* Convert the path to a string that can be used in a unix makefile.
* double slashes are removed, and spaces are escaped.
*/
static kwsys_stl::string ConvertToUnixOutputPath(const char*);
/**
* Convert the path to string that can be used in a windows project or
* makefile. Double slashes are removed if they are not at the start of
* the string, the slashes are converted to windows style backslashes, and
* if there are spaces in the string it is double quoted.
*/
static kwsys_stl::string ConvertToWindowsOutputPath(const char*);
/**
* Return true if a file exists in the current directory.
* If isFile = true, then make sure the file is a file and
* not a directory. If isFile = false, then return true
* if it is a file or a directory.
*/
static bool FileExists(const char* filename, bool isFile);
static bool FileExists(const char* filename);
/**
* Converts Cygwin path to Win32 path. Uses dictionary container for
* caching and calls to cygwin_conv_to_win32_path from Cygwin dll
* for actual translation. Returns true on success, else false.
*/
#ifdef __CYGWIN__
static bool PathCygwinToWin32(const char *path, char *win32_path);
#endif
/**
* Return file length
*/
static unsigned long FileLength(const char *filename);
/**
Change the modification time or create a file
*/
static bool Touch(const char* filename, bool create);
/**
* Compare file modification times.
* Return true for successful comparison and false for error.
* When true is returned, result has -1, 0, +1 for
* f1 older, same, or newer than f2.
*/
static bool FileTimeCompare(const char* f1, const char* f2,
int* result);
/**
* Get the file extension (including ".") needed for an executable
* on the current platform ("" for unix, ".exe" for Windows).
*/
static const char* GetExecutableExtension();
/**
* Given a path that exists on a windows machine, return the
* actuall case of the path as it was created. If the file
* does not exist path is returned unchanged. This does nothing
* on unix but return path.
*/
static kwsys_stl::string GetActualCaseForPath(const char* path);
/**
* Given the path to a program executable, get the directory part of
* the path with the file stripped off. If there is no directory
* part, the empty string is returned.
*/
static kwsys_stl::string GetProgramPath(const char*);
static bool SplitProgramPath(const char* in_name,
kwsys_stl::string& dir,
kwsys_stl::string& file,
bool errorReport = true);
/**
* Given argv[0] for a unix program find the full path to a running
* executable. argv0 can be null for windows WinMain programs
* in this case GetModuleFileName will be used to find the path
* to the running executable. If argv0 is not a full path,
* then this will try to find the full path. If the path is not
* found false is returned, if found true is returned. An error
* message of the attempted paths is stored in errorMsg.
* exeName is the name of the executable.
* buildDir is a possibly null path to the build directory.
* installPrefix is a possibly null pointer to the install directory.
*/
static bool FindProgramPath(const char* argv0,
kwsys_stl::string& pathOut,
kwsys_stl::string& errorMsg,
const char* exeName = 0,
const char* buildDir = 0,
const char* installPrefix = 0);
/**
* Given a path to a file or directory, convert it to a full path.
* This collapses away relative paths relative to the cwd argument
* (which defaults to the current working directory). The full path
* is returned.
*/
static kwsys_stl::string CollapseFullPath(const char* in_relative);
static kwsys_stl::string CollapseFullPath(const char* in_relative,
const char* in_base);
/**
* Get the real path for a given path, removing all symlinks. In
* the event of an error (non-existent path, permissions issue,
* etc.) the original path is returned.
*/
static kwsys_stl::string GetRealPath(const char* path);
/**
* Split a path name into its root component and the rest of the
* path. The root component is one of the following:
* "/" = UNIX full path
* "c:/" = Windows full path (can be any drive letter)
* "c:" = Windows drive-letter relative path (can be any drive letter)
* "//" = Network path
* "~/" = Home path for current user
* "~u/" = Home path for user 'u'
* "" = Relative path
*
* A pointer to the rest of the path after the root component is
* returned. The root component is stored in the "root" string if
* given.
*/
static const char* SplitPathRootComponent(const char* p,
kwsys_stl::string* root=0);
/**
* Split a path name into its basic components. The first component
* always exists and is the root returned by SplitPathRootComponent.
* The remaining components form the path. If there is a trailing
* slash then the last component is the empty string. The
* components can be recombined as "c[0]c[1]/c[2]/.../c[n]" to
* produce the original path. Home directory references are
* automatically expanded if expand_home_dir is true and this
* platform supports them.
*/
static void SplitPath(const char* p,
kwsys_stl::vector<kwsys_stl::string>& components,
bool expand_home_dir = true);
/**
* Join components of a path name into a single string. See
* SplitPath for the format of the components.
*/
static kwsys_stl::string JoinPath(
const kwsys_stl::vector<kwsys_stl::string>& components);
static kwsys_stl::string JoinPath(
kwsys_stl::vector<kwsys_stl::string>::const_iterator first,
kwsys_stl::vector<kwsys_stl::string>::const_iterator last);
/**
* Compare a path or components of a path.
*/
static bool ComparePath(const char* c1, const char* c2);
/**
* Return path of a full filename (no trailing slashes)
*/
static kwsys_stl::string GetFilenamePath(const kwsys_stl::string&);
/**
* Return file name of a full filename (i.e. file name without path)
*/
static kwsys_stl::string GetFilenameName(const kwsys_stl::string&);
/**
* Split a program from its arguments and handle spaces in the paths
*/
static void SplitProgramFromArgs(
const char* path,
kwsys_stl::string& program, kwsys_stl::string& args);
/**
* Return longest file extension of a full filename (dot included)
*/
static kwsys_stl::string GetFilenameExtension(const kwsys_stl::string&);
/**
* Return shortest file extension of a full filename (dot included)
*/
static kwsys_stl::string GetFilenameLastExtension(
const kwsys_stl::string& filename);
/**
* Return file name without extension of a full filename
*/
static kwsys_stl::string GetFilenameWithoutExtension(
const kwsys_stl::string&);
/**
* Return file name without its last (shortest) extension
*/
static kwsys_stl::string GetFilenameWithoutLastExtension(
const kwsys_stl::string&);
/**
* Return whether the path represents a full path (not relative)
*/
static bool FileIsFullPath(const char*);
/**
* For windows return the short path for the given path,
* Unix just a pass through
*/
static bool GetShortPath(const char* path, kwsys_stl::string& result);
/**
* Read line from file. Make sure to get everything. Due to a buggy stream
* library on the HP and another on Mac OS X, we need this very carefully
* written version of getline. Returns true if any data were read before the
* end-of-file was reached. If the has_newline argument is specified, it will
* be true when the line read had a newline character.
*/
static bool GetLineFromStream(kwsys_ios::istream& istr,
kwsys_stl::string& line,
bool* has_newline=0,
long sizeLimit=-1);
/**
* Get the parent directory of the directory or file
*/
static kwsys_stl::string GetParentDirectory(const char* fileOrDir);
/**
* Check if the given file or directory is in subdirectory of dir
*/
static bool IsSubDirectory(const char* fileOrDir, const char* dir);
/** -----------------------------------------------------------------
* File Manipulation Routines
* -----------------------------------------------------------------
*/
/**
* Make a new directory if it is not there. This function
* can make a full path even if none of the directories existed
* prior to calling this function.
*/
static bool MakeDirectory(const char* path);
/**
* Copy the source file to the destination file only
* if the two files differ.
*/
static bool CopyFileIfDifferent(const char* source,
const char* destination);
/**
* Compare the contents of two files. Return true if different
*/
static bool FilesDiffer(const char* source, const char* destination);
/**
* Return true if the two files are the same file
*/
static bool SameFile(const char* file1, const char* file2);
/**
* Copy a file.
*/
static bool CopyFileAlways(const char* source, const char* destination);
/**
* Copy a file. If the "always" argument is true the file is always
* copied. If it is false, the file is copied only if it is new or
* has changed.
*/
static bool CopyAFile(const char* source, const char* destination,
bool always = true);
/**
* Copy content directory to another directory with all files and
* subdirectories. If the "always" argument is true all files are
* always copied. If it is false, only files that have changed or
* are new are copied.
*/
static bool CopyADirectory(const char* source, const char* destination,
bool always = true);
/**
* Remove a file
*/
static bool RemoveFile(const char* source);
/**
* Remove a directory
*/
static bool RemoveADirectory(const char* source);
/**
* Get the maximum full file path length
*/
static size_t GetMaximumFilePathLength();
/**
* Find a file in the system PATH, with optional extra paths
*/
static kwsys_stl::string FindFile(
const char* name,
const kwsys_stl::vector<kwsys_stl::string>& path =
kwsys_stl::vector<kwsys_stl::string>(),
bool no_system_path = false);
/**
* Find a directory in the system PATH, with optional extra paths
*/
static kwsys_stl::string FindDirectory(
const char* name,
const kwsys_stl::vector<kwsys_stl::string>& path =
kwsys_stl::vector<kwsys_stl::string>(),
bool no_system_path = false);
/**
* Find an executable in the system PATH, with optional extra paths
*/
static kwsys_stl::string FindProgram(
const char* name,
const kwsys_stl::vector<kwsys_stl::string>& path =
kwsys_stl::vector<kwsys_stl::string>(),
bool no_system_path = false);
static kwsys_stl::string FindProgram(
const kwsys_stl::vector<kwsys_stl::string>& names,
const kwsys_stl::vector<kwsys_stl::string>& path =
kwsys_stl::vector<kwsys_stl::string>(),
bool no_system_path = false);
/**
* Find a library in the system PATH, with optional extra paths
*/
static kwsys_stl::string FindLibrary(
const char* name,
const kwsys_stl::vector<kwsys_stl::string>& path);
/**
* Return true if the file is a directory
*/
static bool FileIsDirectory(const char* name);
/**
* Return true if the file is a symlink
*/
static bool FileIsSymlink(const char* name);
/**
* Return true if the file has a given signature (first set of bytes)
*/
static bool FileHasSignature(
const char* filename, const char *signature, long offset = 0);
/**
* Attempt to detect and return the type of a file.
* Up to 'length' bytes are read from the file, if more than 'percent_bin' %
* of the bytes are non-textual elements, the file is considered binary,
* otherwise textual. Textual elements are bytes in the ASCII [0x20, 0x7E]
* range, but also \\n, \\r, \\t.
* The algorithm is simplistic, and should probably check for usual file
* extensions, 'magic' signature, unicode, etc.
*/
enum FileTypeEnum
{
FileTypeUnknown,
FileTypeBinary,
FileTypeText
};
static SystemTools::FileTypeEnum DetectFileType(
const char* filename,
unsigned long length = 256,
double percent_bin = 0.05);
/**
* Create a symbolic link if the platform supports it. Returns whether
* creation succeded.
*/
static bool CreateSymlink(const char* origName, const char* newName);
/**
* Read the contents of a symbolic link. Returns whether reading
* succeded.
*/
static bool ReadSymlink(const char* newName, kwsys_stl::string& origName);
/**
* Try to locate the file 'filename' in the directory 'dir'.
* If 'filename' is a fully qualified filename, the basename of the file is
* used to check for its existence in 'dir'.
* If 'dir' is not a directory, GetFilenamePath() is called on 'dir' to
* get its directory first (thus, you can pass a filename as 'dir', as
* a convenience).
* 'filename_found' is assigned the fully qualified name/path of the file
* if it is found (not touched otherwise).
* If 'try_filename_dirs' is true, try to find the file using the
* components of its path, i.e. if we are looking for c:/foo/bar/bill.txt,
* first look for bill.txt in 'dir', then in 'dir'/bar, then in 'dir'/foo/bar
* etc.
* Return true if the file was found, false otherwise.
*/
static bool LocateFileInDir(const char *filename,
const char *dir,
kwsys_stl::string& filename_found,
int try_filename_dirs = 0);
/** compute the relative path from local to remote. local must
be a directory. remote can be a file or a directory.
Both remote and local must be full paths. Basically, if
you are in directory local and you want to access the file in remote
what is the relative path to do that. For example:
/a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
*/
static kwsys_stl::string RelativePath(const char* local, const char* remote);
/**
* Return file's modified time
*/
static long int ModifiedTime(const char* filename);
/**
* Return file's creation time (Win32: works only for NTFS, not FAT)
*/
static long int CreationTime(const char* filename);
/**
* Get and set permissions of the file.
*/
static bool GetPermissions(const char* file, mode_t& mode);
static bool SetPermissions(const char* file, mode_t mode);
/** -----------------------------------------------------------------
* Time Manipulation Routines
* -----------------------------------------------------------------
*/
/** Get current time in seconds since Posix Epoch (Jan 1, 1970). */
static double GetTime();
/**
* Get current date/time
*/
static kwsys_stl::string GetCurrentDateTime(const char* format);
/** -----------------------------------------------------------------
* Registry Manipulation Routines
* -----------------------------------------------------------------
*/
/**
* Specify access to the 32-bit or 64-bit application view of
* registry values. The default is to match the currently running
* binary type.
*/
enum KeyWOW64 { KeyWOW64_Default, KeyWOW64_32, KeyWOW64_64 };
/**
* Read a registry value
*/
static bool ReadRegistryValue(const char *key, kwsys_stl::string &value,
KeyWOW64 view = KeyWOW64_Default);
/**
* Write a registry value
*/
static bool WriteRegistryValue(const char *key, const char *value,
KeyWOW64 view = KeyWOW64_Default);
/**
* Delete a registry value
*/
static bool DeleteRegistryValue(const char *key,
KeyWOW64 view = KeyWOW64_Default);
/** -----------------------------------------------------------------
* Environment Manipulation Routines
* -----------------------------------------------------------------
*/
/**
* Add the paths from the environment variable PATH to the
* string vector passed in. If env is set then the value
* of env will be used instead of PATH.
*/
static void GetPath(kwsys_stl::vector<kwsys_stl::string>& path,
const char* env=0);
/**
* Read an environment variable
*/
static const char* GetEnv(const char* key);
static bool GetEnv(const char* key, kwsys_stl::string& result);
/** Put a string into the environment
of the form var=value */
static bool PutEnv(const char* env);
/** Remove a string from the environment.
Input is of the form "var" or "var=value" (value is ignored). */
static bool UnPutEnv(const char* env);
/**
* Get current working directory CWD
*/
static kwsys_stl::string GetCurrentWorkingDirectory(bool collapse =true);
/**
* Change directory the the directory specified
*/
static int ChangeDirectory(const char* dir);
/**
* Get the result of strerror(errno)
*/
static kwsys_stl::string GetLastSystemError();
/**
* When building DEBUG with MSVC, this enables a hook that prevents
* error dialogs from popping up if the program is being run from
* DART.
*/
static void EnableMSVCDebugHook();
/**
* Get the width of the terminal window. The code may or may not work, so
* make sure you have some resonable defaults prepared if the code returns
* some bogus size.
*/
static int GetTerminalWidth();
/**
* Add an entry in the path translation table.
*/
static void AddTranslationPath(const char * dir, const char * refdir);
/**
* If dir is different after CollapseFullPath is called,
* Then insert it into the path translation table
*/
static void AddKeepPath(const char* dir);
/**
* Update path by going through the Path Translation table;
*/
static void CheckTranslationPath(kwsys_stl::string & path);
/**
* Delay the execution for a specified amount of time specified
* in miliseconds
*/
static void Delay(unsigned int msec);
/**
* Get the operating system name and version
* This is implemented for Win32 only for the moment
*/
static kwsys_stl::string GetOperatingSystemNameAndVersion();
/**
* Convert windows-style arguments given as a command-line string
* into more traditional argc/argv arguments.
* Note that argv[0] will be assigned the executable name using
* the GetModuleFileName() function.
*/
static void ConvertWindowsCommandLineToUnixArguments(
const char *cmd_line, int *argc, char ***argv);
/** -----------------------------------------------------------------
* URL Manipulation Routines
* -----------------------------------------------------------------
*/
/**
* Parse a character string :
* protocol://dataglom
* and fill protocol as appropriate.
* Return false if the URL does not have the required form, true otherwise.
*/
static bool ParseURLProtocol( const kwsys_stl::string& URL,
kwsys_stl::string& protocol,
kwsys_stl::string& dataglom );
/**
* Parse a string (a URL without protocol prefix) with the form:
* protocol://[[username[':'password]'@']hostname[':'dataport]]'/'[datapath]
* and fill protocol, username, password, hostname, dataport, and datapath
* when values are found.
* Return true if the string matches the format; false otherwise.
*/
static bool ParseURL( const kwsys_stl::string& URL,
kwsys_stl::string& protocol,
kwsys_stl::string& username,
kwsys_stl::string& password,
kwsys_stl::string& hostname,
kwsys_stl::string& dataport,
kwsys_stl::string& datapath );
private:
/**
* Allocate the stl map that serve as the Path Translation table.
*/
static void ClassInitialize();
/**
* Deallocate the stl map that serve as the Path Translation table.
*/
static void ClassFinalize();
/**
* This method prevents warning on SGI
*/
SystemToolsManager* GetSystemToolsManager()
{
return &SystemToolsManagerInstance;
}
/**
* Find a filename (file or directory) in the system PATH, with
* optional extra paths.
*/
static kwsys_stl::string FindName(
const char* name,
const kwsys_stl::vector<kwsys_stl::string>& path =
kwsys_stl::vector<kwsys_stl::string>(),
bool no_system_path = false);
/**
* Path translation table from dir to refdir
* Each time 'dir' will be found it will be replace by 'refdir'
*/
static SystemToolsTranslationMap *TranslationMap;
static SystemToolsTranslationMap *LongPathMap;
#ifdef __CYGWIN__
static SystemToolsTranslationMap *Cyg2Win32Map;
#endif
friend class SystemToolsManager;
};
} // namespace @KWSYS_NAMESPACE@
/* Undefine temporary macros. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsys_stl
# undef kwsys_ios
#endif
#endif

432
Terminal.c Normal file
View File

@ -0,0 +1,432 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Terminal.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "Terminal.h.in"
#endif
/*--------------------------------------------------------------------------*/
/* Configure support for this platform. */
#if defined(_WIN32) || defined(__CYGWIN__)
# define KWSYS_TERMINAL_SUPPORT_CONSOLE
#endif
#if !defined(_WIN32)
# define KWSYS_TERMINAL_ISATTY_WORKS
#endif
/*--------------------------------------------------------------------------*/
/* Include needed system APIs. */
#include <stdlib.h> /* getenv */
#include <string.h> /* strcmp */
#include <stdarg.h> /* va_list */
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
# include <windows.h> /* SetConsoleTextAttribute */
# include <io.h> /* _get_osfhandle */
#endif
#if defined(KWSYS_TERMINAL_ISATTY_WORKS)
# include <unistd.h> /* isatty */
#else
# include <sys/stat.h> /* fstat */
#endif
/*--------------------------------------------------------------------------*/
static int kwsysTerminalStreamIsVT100(FILE* stream, int default_vt100,
int default_tty);
static void kwsysTerminalSetVT100Color(FILE* stream, int color);
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
static HANDLE kwsysTerminalGetStreamHandle(FILE* stream);
static void kwsysTerminalSetConsoleColor(HANDLE hOut,
CONSOLE_SCREEN_BUFFER_INFO* hOutInfo,
FILE* stream,
int color);
#endif
/*--------------------------------------------------------------------------*/
void kwsysTerminal_cfprintf(int color, FILE* stream, const char* format, ...)
{
/* Setup the stream with the given color if possible. */
int pipeIsConsole = 0;
int pipeIsVT100 = 0;
int default_vt100 = color & kwsysTerminal_Color_AssumeVT100;
int default_tty = color & kwsysTerminal_Color_AssumeTTY;
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
CONSOLE_SCREEN_BUFFER_INFO hOutInfo;
HANDLE hOut = kwsysTerminalGetStreamHandle(stream);
if(GetConsoleScreenBufferInfo(hOut, &hOutInfo))
{
pipeIsConsole = 1;
kwsysTerminalSetConsoleColor(hOut, &hOutInfo, stream, color);
}
#endif
if(!pipeIsConsole && kwsysTerminalStreamIsVT100(stream,
default_vt100, default_tty))
{
pipeIsVT100 = 1;
kwsysTerminalSetVT100Color(stream, color);
}
/* Format the text into the stream. */
{
va_list var_args;
va_start(var_args, format);
vfprintf(stream, format, var_args);
va_end(var_args);
}
/* Restore the normal color state for the stream. */
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
if(pipeIsConsole)
{
kwsysTerminalSetConsoleColor(hOut, &hOutInfo, stream,
kwsysTerminal_Color_Normal);
}
#endif
if(pipeIsVT100)
{
kwsysTerminalSetVT100Color(stream, kwsysTerminal_Color_Normal);
}
}
/*--------------------------------------------------------------------------*/
/* Detect cases when a stream is definately not interactive. */
#if !defined(KWSYS_TERMINAL_ISATTY_WORKS)
static int kwsysTerminalStreamIsNotInteractive(FILE* stream)
{
/* The given stream is definately not interactive if it is a regular
file. */
struct stat stream_stat;
if(fstat(fileno(stream), &stream_stat) == 0)
{
if(stream_stat.st_mode & S_IFREG)
{
return 1;
}
}
return 0;
}
#endif
/*--------------------------------------------------------------------------*/
/* List of terminal names known to support VT100 color escape sequences. */
static const char* kwsysTerminalVT100Names[] =
{
"Eterm",
"ansi",
"color-xterm",
"con132x25",
"con132x30",
"con132x43",
"con132x60",
"con80x25",
"con80x28",
"con80x30",
"con80x43",
"con80x50",
"con80x60",
"cons25",
"console",
"cygwin",
"dtterm",
"eterm-color",
"gnome",
"gnome-256color",
"konsole",
"konsole-256color",
"kterm",
"linux",
"msys",
"linux-c",
"mach-color",
"mlterm",
"putty",
"rxvt",
"rxvt-256color",
"rxvt-cygwin",
"rxvt-cygwin-native",
"rxvt-unicode",
"rxvt-unicode-256color",
"screen",
"screen-256color",
"screen-256color-bce",
"screen-bce",
"screen-w",
"screen.linux",
"vt100",
"xterm",
"xterm-16color",
"xterm-256color",
"xterm-88color",
"xterm-color",
"xterm-debian",
0
};
/*--------------------------------------------------------------------------*/
/* Detect whether a stream is displayed in a VT100-compatible terminal. */
static int kwsysTerminalStreamIsVT100(FILE* stream, int default_vt100,
int default_tty)
{
/* If running inside emacs the terminal is not VT100. Some emacs
seem to claim the TERM is xterm even though they do not support
VT100 escapes. */
const char* emacs = getenv("EMACS");
if(emacs && *emacs == 't')
{
return 0;
}
/* Check for a valid terminal. */
if(!default_vt100)
{
const char** t = 0;
const char* term = getenv("TERM");
if(term)
{
for(t = kwsysTerminalVT100Names; *t && strcmp(term, *t) != 0; ++t) {}
}
if(!(t && *t))
{
return 0;
}
}
#if defined(KWSYS_TERMINAL_ISATTY_WORKS)
/* Make sure the stream is a tty. */
(void)default_tty;
return isatty(fileno(stream))? 1:0;
#else
/* Check for cases in which the stream is definately not a tty. */
if(kwsysTerminalStreamIsNotInteractive(stream))
{
return 0;
}
/* Use the provided default for whether this is a tty. */
return default_tty;
#endif
}
/*--------------------------------------------------------------------------*/
/* VT100 escape sequence strings. */
#define KWSYS_TERMINAL_VT100_NORMAL "\33[0m"
#define KWSYS_TERMINAL_VT100_BOLD "\33[1m"
#define KWSYS_TERMINAL_VT100_UNDERLINE "\33[4m"
#define KWSYS_TERMINAL_VT100_BLINK "\33[5m"
#define KWSYS_TERMINAL_VT100_INVERSE "\33[7m"
#define KWSYS_TERMINAL_VT100_FOREGROUND_BLACK "\33[30m"
#define KWSYS_TERMINAL_VT100_FOREGROUND_RED "\33[31m"
#define KWSYS_TERMINAL_VT100_FOREGROUND_GREEN "\33[32m"
#define KWSYS_TERMINAL_VT100_FOREGROUND_YELLOW "\33[33m"
#define KWSYS_TERMINAL_VT100_FOREGROUND_BLUE "\33[34m"
#define KWSYS_TERMINAL_VT100_FOREGROUND_MAGENTA "\33[35m"
#define KWSYS_TERMINAL_VT100_FOREGROUND_CYAN "\33[36m"
#define KWSYS_TERMINAL_VT100_FOREGROUND_WHITE "\33[37m"
#define KWSYS_TERMINAL_VT100_BACKGROUND_BLACK "\33[40m"
#define KWSYS_TERMINAL_VT100_BACKGROUND_RED "\33[41m"
#define KWSYS_TERMINAL_VT100_BACKGROUND_GREEN "\33[42m"
#define KWSYS_TERMINAL_VT100_BACKGROUND_YELLOW "\33[43m"
#define KWSYS_TERMINAL_VT100_BACKGROUND_BLUE "\33[44m"
#define KWSYS_TERMINAL_VT100_BACKGROUND_MAGENTA "\33[45m"
#define KWSYS_TERMINAL_VT100_BACKGROUND_CYAN "\33[46m"
#define KWSYS_TERMINAL_VT100_BACKGROUND_WHITE "\33[47m"
/*--------------------------------------------------------------------------*/
/* Write VT100 escape sequences to the stream for the given color. */
static void kwsysTerminalSetVT100Color(FILE* stream, int color)
{
if(color == kwsysTerminal_Color_Normal)
{
fprintf(stream, KWSYS_TERMINAL_VT100_NORMAL);
return;
}
switch(color & kwsysTerminal_Color_ForegroundMask)
{
case kwsysTerminal_Color_Normal:
fprintf(stream, KWSYS_TERMINAL_VT100_NORMAL);
break;
case kwsysTerminal_Color_ForegroundBlack:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_BLACK);
break;
case kwsysTerminal_Color_ForegroundRed:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_RED);
break;
case kwsysTerminal_Color_ForegroundGreen:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_GREEN);
break;
case kwsysTerminal_Color_ForegroundYellow:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_YELLOW);
break;
case kwsysTerminal_Color_ForegroundBlue:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_BLUE);
break;
case kwsysTerminal_Color_ForegroundMagenta:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_MAGENTA);
break;
case kwsysTerminal_Color_ForegroundCyan:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_CYAN);
break;
case kwsysTerminal_Color_ForegroundWhite:
fprintf(stream, KWSYS_TERMINAL_VT100_FOREGROUND_WHITE);
break;
}
switch(color & kwsysTerminal_Color_BackgroundMask)
{
case kwsysTerminal_Color_BackgroundBlack:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_BLACK);
break;
case kwsysTerminal_Color_BackgroundRed:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_RED);
break;
case kwsysTerminal_Color_BackgroundGreen:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_GREEN);
break;
case kwsysTerminal_Color_BackgroundYellow:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_YELLOW);
break;
case kwsysTerminal_Color_BackgroundBlue:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_BLUE);
break;
case kwsysTerminal_Color_BackgroundMagenta:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_MAGENTA);
break;
case kwsysTerminal_Color_BackgroundCyan:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_CYAN);
break;
case kwsysTerminal_Color_BackgroundWhite:
fprintf(stream, KWSYS_TERMINAL_VT100_BACKGROUND_WHITE);
break;
}
if(color & kwsysTerminal_Color_ForegroundBold)
{
fprintf(stream, KWSYS_TERMINAL_VT100_BOLD);
}
}
/*--------------------------------------------------------------------------*/
#if defined(KWSYS_TERMINAL_SUPPORT_CONSOLE)
# define KWSYS_TERMINAL_MASK_FOREGROUND \
(FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY)
# define KWSYS_TERMINAL_MASK_BACKGROUND \
(BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY)
/* Get the Windows handle for a FILE stream. */
static HANDLE kwsysTerminalGetStreamHandle(FILE* stream)
{
/* Get the C-library file descriptor from the stream. */
int fd = fileno(stream);
# if defined(__CYGWIN__)
/* Cygwin seems to have an extra pipe level. If the file descriptor
corresponds to stdout or stderr then obtain the matching windows
handle directly. */
if(fd == fileno(stdout))
{
return GetStdHandle(STD_OUTPUT_HANDLE);
}
else if(fd == fileno(stderr))
{
return GetStdHandle(STD_ERROR_HANDLE);
}
# endif
/* Get the underlying Windows handle for the descriptor. */
return (HANDLE)_get_osfhandle(fd);
}
/* Set color attributes in a Windows console. */
static void kwsysTerminalSetConsoleColor(HANDLE hOut,
CONSOLE_SCREEN_BUFFER_INFO* hOutInfo,
FILE* stream,
int color)
{
WORD attributes = 0;
switch(color & kwsysTerminal_Color_ForegroundMask)
{
case kwsysTerminal_Color_Normal:
attributes |= hOutInfo->wAttributes & KWSYS_TERMINAL_MASK_FOREGROUND;
break;
case kwsysTerminal_Color_ForegroundBlack:
attributes |= 0;
break;
case kwsysTerminal_Color_ForegroundRed:
attributes |= FOREGROUND_RED;
break;
case kwsysTerminal_Color_ForegroundGreen:
attributes |= FOREGROUND_GREEN;
break;
case kwsysTerminal_Color_ForegroundYellow:
attributes |= FOREGROUND_RED | FOREGROUND_GREEN;
break;
case kwsysTerminal_Color_ForegroundBlue:
attributes |= FOREGROUND_BLUE;
break;
case kwsysTerminal_Color_ForegroundMagenta:
attributes |= FOREGROUND_RED | FOREGROUND_BLUE;
break;
case kwsysTerminal_Color_ForegroundCyan:
attributes |= FOREGROUND_BLUE | FOREGROUND_GREEN;
break;
case kwsysTerminal_Color_ForegroundWhite:
attributes |= FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED;
break;
}
switch(color & kwsysTerminal_Color_BackgroundMask)
{
case kwsysTerminal_Color_Normal:
attributes |= hOutInfo->wAttributes & KWSYS_TERMINAL_MASK_BACKGROUND;
break;
case kwsysTerminal_Color_BackgroundBlack:
attributes |= 0;
break;
case kwsysTerminal_Color_BackgroundRed:
attributes |= BACKGROUND_RED;
break;
case kwsysTerminal_Color_BackgroundGreen:
attributes |= BACKGROUND_GREEN;
break;
case kwsysTerminal_Color_BackgroundYellow:
attributes |= BACKGROUND_RED | BACKGROUND_GREEN;
break;
case kwsysTerminal_Color_BackgroundBlue:
attributes |= BACKGROUND_BLUE;
break;
case kwsysTerminal_Color_BackgroundMagenta:
attributes |= BACKGROUND_RED | BACKGROUND_BLUE;
break;
case kwsysTerminal_Color_BackgroundCyan:
attributes |= BACKGROUND_BLUE | BACKGROUND_GREEN;
break;
case kwsysTerminal_Color_BackgroundWhite:
attributes |= BACKGROUND_BLUE | BACKGROUND_GREEN | BACKGROUND_RED;
break;
}
if(color & kwsysTerminal_Color_ForegroundBold)
{
attributes |= FOREGROUND_INTENSITY;
}
if(color & kwsysTerminal_Color_BackgroundBold)
{
attributes |= BACKGROUND_INTENSITY;
}
fflush(stream);
SetConsoleTextAttribute(hOut, attributes);
}
#endif

159
Terminal.h.in Normal file
View File

@ -0,0 +1,159 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_Terminal_h
#define @KWSYS_NAMESPACE@_Terminal_h
#include <@KWSYS_NAMESPACE@/Configure.h>
#include <stdio.h> /* For file stream type FILE. */
/* Redefine all public interface symbol names to be in the proper
namespace. These macros are used internally to kwsys only, and are
not visible to user code. Use kwsysHeaderDump.pl to reproduce
these macros after making changes to the interface. */
#if !defined(KWSYS_NAMESPACE)
# define kwsys_ns(x) @KWSYS_NAMESPACE@##x
# define kwsysEXPORT @KWSYS_NAMESPACE@_EXPORT
#endif
#if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsysTerminal_cfprintf kwsys_ns(Terminal_cfprintf)
# define kwsysTerminal_Color_e kwsys_ns(Terminal_Color_e)
# define kwsysTerminal_Color_Normal kwsys_ns(Terminal_Color_Normal)
# define kwsysTerminal_Color_ForegroundBlack kwsys_ns(Terminal_Color_ForegroundBlack)
# define kwsysTerminal_Color_ForegroundRed kwsys_ns(Terminal_Color_ForegroundRed)
# define kwsysTerminal_Color_ForegroundGreen kwsys_ns(Terminal_Color_ForegroundGreen)
# define kwsysTerminal_Color_ForegroundYellow kwsys_ns(Terminal_Color_ForegroundYellow)
# define kwsysTerminal_Color_ForegroundBlue kwsys_ns(Terminal_Color_ForegroundBlue)
# define kwsysTerminal_Color_ForegroundMagenta kwsys_ns(Terminal_Color_ForegroundMagenta)
# define kwsysTerminal_Color_ForegroundCyan kwsys_ns(Terminal_Color_ForegroundCyan)
# define kwsysTerminal_Color_ForegroundWhite kwsys_ns(Terminal_Color_ForegroundWhite)
# define kwsysTerminal_Color_ForegroundMask kwsys_ns(Terminal_Color_ForegroundMask)
# define kwsysTerminal_Color_BackgroundBlack kwsys_ns(Terminal_Color_BackgroundBlack)
# define kwsysTerminal_Color_BackgroundRed kwsys_ns(Terminal_Color_BackgroundRed)
# define kwsysTerminal_Color_BackgroundGreen kwsys_ns(Terminal_Color_BackgroundGreen)
# define kwsysTerminal_Color_BackgroundYellow kwsys_ns(Terminal_Color_BackgroundYellow)
# define kwsysTerminal_Color_BackgroundBlue kwsys_ns(Terminal_Color_BackgroundBlue)
# define kwsysTerminal_Color_BackgroundMagenta kwsys_ns(Terminal_Color_BackgroundMagenta)
# define kwsysTerminal_Color_BackgroundCyan kwsys_ns(Terminal_Color_BackgroundCyan)
# define kwsysTerminal_Color_BackgroundWhite kwsys_ns(Terminal_Color_BackgroundWhite)
# define kwsysTerminal_Color_BackgroundMask kwsys_ns(Terminal_Color_BackgroundMask)
# define kwsysTerminal_Color_ForegroundBold kwsys_ns(Terminal_Color_ForegroundBold)
# define kwsysTerminal_Color_BackgroundBold kwsys_ns(Terminal_Color_BackgroundBold)
# define kwsysTerminal_Color_AssumeTTY kwsys_ns(Terminal_Color_AssumeTTY)
# define kwsysTerminal_Color_AssumeVT100 kwsys_ns(Terminal_Color_AssumeVT100)
# define kwsysTerminal_Color_AttributeMask kwsys_ns(Terminal_Color_AttributeMask)
#endif
#if defined(__cplusplus)
extern "C"
{
#endif
/**
* Write colored and formatted text to a stream. Color is used only
* for streams supporting it. The color specification is constructed
* by bitwise-OR-ing enumeration values. At most one foreground and
* one background value may be given.
*
* Whether the a stream supports color is usually automatically
* detected, but with two exceptions:
*
* - When the stream is displayed in a terminal supporting VT100
* color but using an intermediate pipe for communication the
* detection of a tty fails. (This typically occurs for a shell
* running in an rxvt terminal in MSYS.) If the caller knows this
* to be the case, the attribute Color_AssumeTTY may be included in
* the color specification.
*
* - When the stream is displayed in a terminal whose TERM
* environment variable is not set or is set to a value that is not
* known to support VT100 colors. If the caller knows this to be
* the case, the attribute Color_AssumeVT100 may be included in the
* color specification.
*/
kwsysEXPORT void kwsysTerminal_cfprintf(int color, FILE* stream,
const char* format, ...);
enum kwsysTerminal_Color_e
{
/* Normal Text */
kwsysTerminal_Color_Normal = 0,
/* Foreground Color */
kwsysTerminal_Color_ForegroundBlack = 0x1,
kwsysTerminal_Color_ForegroundRed = 0x2,
kwsysTerminal_Color_ForegroundGreen = 0x3,
kwsysTerminal_Color_ForegroundYellow = 0x4,
kwsysTerminal_Color_ForegroundBlue = 0x5,
kwsysTerminal_Color_ForegroundMagenta = 0x6,
kwsysTerminal_Color_ForegroundCyan = 0x7,
kwsysTerminal_Color_ForegroundWhite = 0x8,
kwsysTerminal_Color_ForegroundMask = 0xF,
/* Background Color */
kwsysTerminal_Color_BackgroundBlack = 0x10,
kwsysTerminal_Color_BackgroundRed = 0x20,
kwsysTerminal_Color_BackgroundGreen = 0x30,
kwsysTerminal_Color_BackgroundYellow = 0x40,
kwsysTerminal_Color_BackgroundBlue = 0x50,
kwsysTerminal_Color_BackgroundMagenta = 0x60,
kwsysTerminal_Color_BackgroundCyan = 0x70,
kwsysTerminal_Color_BackgroundWhite = 0x80,
kwsysTerminal_Color_BackgroundMask = 0xF0,
/* Attributes */
kwsysTerminal_Color_ForegroundBold = 0x100,
kwsysTerminal_Color_BackgroundBold = 0x200,
kwsysTerminal_Color_AssumeTTY = 0x400,
kwsysTerminal_Color_AssumeVT100 = 0x800,
kwsysTerminal_Color_AttributeMask = 0xF00
};
#if defined(__cplusplus)
} /* extern "C" */
#endif
/* If we are building a kwsys .c or .cxx file, let it use these macros.
Otherwise, undefine them to keep the namespace clean. */
#if !defined(KWSYS_NAMESPACE)
# undef kwsys_ns
# undef kwsysEXPORT
# if !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsysTerminal_cfprintf
# undef kwsysTerminal_Color_e
# undef kwsysTerminal_Color_Normal
# undef kwsysTerminal_Color_ForegroundBlack
# undef kwsysTerminal_Color_ForegroundRed
# undef kwsysTerminal_Color_ForegroundGreen
# undef kwsysTerminal_Color_ForegroundYellow
# undef kwsysTerminal_Color_ForegroundBlue
# undef kwsysTerminal_Color_ForegroundMagenta
# undef kwsysTerminal_Color_ForegroundCyan
# undef kwsysTerminal_Color_ForegroundWhite
# undef kwsysTerminal_Color_ForegroundMask
# undef kwsysTerminal_Color_BackgroundBlack
# undef kwsysTerminal_Color_BackgroundRed
# undef kwsysTerminal_Color_BackgroundGreen
# undef kwsysTerminal_Color_BackgroundYellow
# undef kwsysTerminal_Color_BackgroundBlue
# undef kwsysTerminal_Color_BackgroundMagenta
# undef kwsysTerminal_Color_BackgroundCyan
# undef kwsysTerminal_Color_BackgroundWhite
# undef kwsysTerminal_Color_BackgroundMask
# undef kwsysTerminal_Color_ForegroundBold
# undef kwsysTerminal_Color_BackgroundBold
# undef kwsysTerminal_Color_AssumeTTY
# undef kwsysTerminal_Color_AssumeVT100
# undef kwsysTerminal_Color_AttributeMask
# endif
#endif
#endif

201
auto_ptr.hxx.in Normal file
View File

@ -0,0 +1,201 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_auto_ptr_hxx
#define @KWSYS_NAMESPACE@_auto_ptr_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
// The HP compiler and VS6 cannot handle the conversions necessary to use
// auto_ptr_ref to pass an auto_ptr returned from one function
// directly to another function as in use_auto_ptr(get_auto_ptr()).
// We instead use const_cast to achieve the syntax on those platforms.
// We do not use const_cast on other platforms to maintain the C++
// standard design and guarantee that if an auto_ptr is bound
// to a reference-to-const then ownership will be maintained.
#if defined(__HP_aCC) || (defined(_MSC_VER) && _MSC_VER <= 1200)
# define @KWSYS_NAMESPACE@_AUTO_PTR_REF 0
# define @KWSYS_NAMESPACE@_AUTO_PTR_CONST const
# define @KWSYS_NAMESPACE@_AUTO_PTR_CAST(a) cast(a)
#else
# define @KWSYS_NAMESPACE@_AUTO_PTR_REF 1
# define @KWSYS_NAMESPACE@_AUTO_PTR_CONST
# define @KWSYS_NAMESPACE@_AUTO_PTR_CAST(a) a
#endif
namespace @KWSYS_NAMESPACE@
{
template <class X> class auto_ptr;
#if @KWSYS_NAMESPACE@_AUTO_PTR_REF
namespace detail
{
// The auto_ptr_ref template is supposed to be a private member of
// auto_ptr but Borland 5.8 cannot handle it. Instead put it in
// a private namespace.
template <class Y> struct auto_ptr_ref
{
Y* p_;
// The extra constructor argument prevents implicit conversion to
// auto_ptr_ref from auto_ptr through the constructor. Normally
// this should be done with the explicit keyword but Borland 5.x
// generates code in the conversion operator to call itself
// infinately.
auto_ptr_ref(Y* p, int): p_(p) {}
};
}
#endif
/** C++98 Standard Section 20.4.5 - Template class auto_ptr. */
template <class X>
class auto_ptr
{
#if !@KWSYS_NAMESPACE@_AUTO_PTR_REF
template <typename Y>
static inline auto_ptr<Y>& cast(auto_ptr<Y> const& a)
{ return const_cast<auto_ptr<Y>&>(a); }
#endif
/** The pointer to the object held. */
X* x_;
public:
/** The type of object held by the auto_ptr. */
typedef X element_type;
/** Construct from an auto_ptr holding a compatible object. This
transfers ownership to the newly constructed auto_ptr. */
template <class Y>
auto_ptr(auto_ptr<Y> @KWSYS_NAMESPACE@_AUTO_PTR_CONST& a) throw():
x_(@KWSYS_NAMESPACE@_AUTO_PTR_CAST(a).release())
{
}
/** Assign from an auto_ptr holding a compatible object. This
transfers ownership to the left-hand-side of the assignment. */
template <class Y>
auto_ptr& operator=(auto_ptr<Y> @KWSYS_NAMESPACE@_AUTO_PTR_CONST& a) throw()
{
this->reset(@KWSYS_NAMESPACE@_AUTO_PTR_CAST(a).release());
return *this;
}
/**
* Explicitly construct from a raw pointer. This is typically
* called with the result of operator new. For example:
*
* auto_ptr<X> ptr(new X());
*/
explicit auto_ptr(X* p=0) throw(): x_(p)
{
}
/** Construct from another auto_ptr holding an object of the same
type. This transfers ownership to the newly constructed
auto_ptr. */
auto_ptr(auto_ptr @KWSYS_NAMESPACE@_AUTO_PTR_CONST& a) throw():
x_(@KWSYS_NAMESPACE@_AUTO_PTR_CAST(a).release())
{
}
/** Assign from another auto_ptr holding an object of the same type.
This transfers ownership to the newly constructed auto_ptr. */
auto_ptr& operator=(auto_ptr @KWSYS_NAMESPACE@_AUTO_PTR_CONST& a) throw()
{
this->reset(@KWSYS_NAMESPACE@_AUTO_PTR_CAST(a).release());
return *this;
}
/** Destruct and delete the object held. */
~auto_ptr() throw()
{
// Assume object destructor is nothrow.
delete this->x_;
}
/** Dereference and return a reference to the object held. */
X& operator*() const throw()
{
return *this->x_;
}
/** Return a pointer to the object held. */
X* operator->() const throw()
{
return this->x_;
}
/** Return a pointer to the object held. */
X* get() const throw()
{
return this->x_;
}
/** Return a pointer to the object held and reset to hold no object.
This transfers ownership to the caller. */
X* release() throw()
{
X* x = this->x_;
this->x_ = 0;
return x;
}
/** Assume ownership of the given object. The object previously
held is deleted. */
void reset(X* p=0) throw()
{
if(this->x_ != p)
{
// Assume object destructor is nothrow.
delete this->x_;
this->x_ = p;
}
}
/** Convert to an auto_ptr holding an object of a compatible type.
This transfers ownership to the returned auto_ptr. */
template <class Y> operator auto_ptr<Y>() throw()
{
return auto_ptr<Y>(this->release());
}
#if @KWSYS_NAMESPACE@_AUTO_PTR_REF
/** Construct from an auto_ptr_ref. This is used when the
constructor argument is a call to a function returning an
auto_ptr. */
auto_ptr(detail::auto_ptr_ref<X> r) throw(): x_(r.p_)
{
}
/** Assign from an auto_ptr_ref. This is used when a function
returning an auto_ptr is passed on the right-hand-side of an
assignment. */
auto_ptr& operator=(detail::auto_ptr_ref<X> r) throw()
{
this->reset(r.p_);
return *this;
}
/** Convert to an auto_ptr_ref. This is used when a function
returning an auto_ptr is the argument to the constructor of
another auto_ptr. */
template <class Y> operator detail::auto_ptr_ref<Y>() throw()
{
return detail::auto_ptr_ref<Y>(this->release(), 1);
}
#endif
};
} // namespace @KWSYS_NAMESPACE@
#endif

149
hash_fun.hxx.in Normal file
View File

@ -0,0 +1,149 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
/*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*/
#ifndef @KWSYS_NAMESPACE@_hash_fun_hxx
#define @KWSYS_NAMESPACE@_hash_fun_hxx
#include <@KWSYS_NAMESPACE@/Configure.hxx>
#include <@KWSYS_NAMESPACE@/cstddef> // size_t
#include <@KWSYS_NAMESPACE@/stl/string> // string
namespace @KWSYS_NAMESPACE@
{
template <class _Key> struct hash { };
inline size_t _stl_hash_string(const char* __s)
{
unsigned long __h = 0;
for ( ; *__s; ++__s)
__h = 5*__h + *__s;
return size_t(__h);
}
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<char*> {
size_t operator()(const char* __s) const { return _stl_hash_string(__s); }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<const char*> {
size_t operator()(const char* __s) const { return _stl_hash_string(__s); }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<@KWSYS_NAMESPACE@_stl::string> {
size_t operator()(const @KWSYS_NAMESPACE@_stl::string & __s) const { return _stl_hash_string(__s.c_str()); }
};
#if !defined(__BORLANDC__)
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<const @KWSYS_NAMESPACE@_stl::string> {
size_t operator()(const @KWSYS_NAMESPACE@_stl::string & __s) const { return _stl_hash_string(__s.c_str()); }
};
#endif
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<char> {
size_t operator()(char __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<unsigned char> {
size_t operator()(unsigned char __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<signed char> {
size_t operator()(unsigned char __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<short> {
size_t operator()(short __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<unsigned short> {
size_t operator()(unsigned short __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<int> {
size_t operator()(int __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<unsigned int> {
size_t operator()(unsigned int __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<long> {
size_t operator()(long __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<unsigned long> {
size_t operator()(unsigned long __x) const { return __x; }
};
// use long long or __int64
#if @KWSYS_USE_LONG_LONG@
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<long long> {
size_t operator()(long long __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<unsigned long long> {
size_t operator()(unsigned long long __x) const { return __x; }
};
#elif @KWSYS_USE___INT64@
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<__int64> {
size_t operator()(__int64 __x) const { return __x; }
};
@KWSYS_NAMESPACE@_CXX_DEFINE_SPECIALIZATION
struct hash<unsigned __int64> {
size_t operator()(unsigned __int64 __x) const { return __x; }
};
#endif // use long long or __int64
} // namespace @KWSYS_NAMESPACE@
#endif

461
hash_map.hxx.in Normal file
View File

@ -0,0 +1,461 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
/*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*/
#ifndef @KWSYS_NAMESPACE@_hash_map_hxx
#define @KWSYS_NAMESPACE@_hash_map_hxx
#include <@KWSYS_NAMESPACE@/hashtable.hxx>
#include <@KWSYS_NAMESPACE@/hash_fun.hxx>
#include <@KWSYS_NAMESPACE@/stl/functional> // equal_to
#if defined(_MSC_VER)
# pragma warning (push)
# pragma warning (disable:4284)
# pragma warning (disable:4786)
#endif
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
# pragma set woff 1174
# pragma set woff 1375
#endif
namespace @KWSYS_NAMESPACE@
{
// select1st is an extension: it is not part of the standard.
template <class T1, class T2>
struct hash_select1st:
public @KWSYS_NAMESPACE@_stl::unary_function<@KWSYS_NAMESPACE@_stl::pair<T1, T2>, T1>
{
const T1& operator()(const @KWSYS_NAMESPACE@_stl::pair<T1, T2>& __x) const
{ return __x.first; }
};
// Forward declaration of equality operator; needed for friend declaration.
template <class _Key, class _Tp,
class _HashFcn = hash<_Key>,
class _EqualKey = @KWSYS_NAMESPACE@_stl::equal_to<_Key>,
class _Alloc = @KWSYS_NAMESPACE@_HASH_DEFAULT_ALLOCATOR(char) >
class hash_map;
template <class _Key, class _Tp, class _HashFn, class _EqKey, class _Alloc>
bool operator==(const hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc>&,
const hash_map<_Key, _Tp, _HashFn, _EqKey, _Alloc>&);
template <class _Key, class _Tp, class _HashFcn, class _EqualKey,
class _Alloc>
class hash_map
{
private:
typedef hashtable<@KWSYS_NAMESPACE@_stl::pair<const _Key,_Tp>,_Key,_HashFcn,
hash_select1st<const _Key,_Tp>,_EqualKey,_Alloc> _Ht;
_Ht _M_ht;
public:
typedef typename _Ht::key_type key_type;
typedef _Tp data_type;
typedef _Tp mapped_type;
typedef typename _Ht::value_type value_type;
typedef typename _Ht::hasher hasher;
typedef typename _Ht::key_equal key_equal;
typedef typename _Ht::size_type size_type;
typedef typename _Ht::difference_type difference_type;
typedef typename _Ht::pointer pointer;
typedef typename _Ht::const_pointer const_pointer;
typedef typename _Ht::reference reference;
typedef typename _Ht::const_reference const_reference;
typedef typename _Ht::iterator iterator;
typedef typename _Ht::const_iterator const_iterator;
typedef typename _Ht::allocator_type allocator_type;
hasher hash_funct() const { return _M_ht.hash_funct(); }
key_equal key_eq() const { return _M_ht.key_eq(); }
allocator_type get_allocator() const { return _M_ht.get_allocator(); }
public:
hash_map() : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
explicit hash_map(size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
hash_map(size_type __n, const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type()) {}
hash_map(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a) {}
#if @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
template <class _InputIterator>
hash_map(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_map(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_map(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_map(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
#else
hash_map(const value_type* __f, const value_type* __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_map(const value_type* __f, const value_type* __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_map(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_map(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
hash_map(const_iterator __f, const_iterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_map(const_iterator __f, const_iterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_map(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_map(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
#endif
public:
size_type size() const { return _M_ht.size(); }
size_type max_size() const { return _M_ht.max_size(); }
bool empty() const { return _M_ht.empty(); }
void swap(hash_map& __hs) { _M_ht.swap(__hs._M_ht); }
friend bool operator==@KWSYS_NAMESPACE@_CXX_NULL_TEMPLATE_ARGS(const hash_map&,
const hash_map&);
iterator begin() { return _M_ht.begin(); }
iterator end() { return _M_ht.end(); }
const_iterator begin() const { return _M_ht.begin(); }
const_iterator end() const { return _M_ht.end(); }
public:
@KWSYS_NAMESPACE@_stl::pair<iterator,bool> insert(const value_type& __obj)
{ return _M_ht.insert_unique(__obj); }
#if @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
{ _M_ht.insert_unique(__f,__l); }
#else
void insert(const value_type* __f, const value_type* __l) {
_M_ht.insert_unique(__f,__l);
}
void insert(const_iterator __f, const_iterator __l)
{ _M_ht.insert_unique(__f, __l); }
#endif
@KWSYS_NAMESPACE@_stl::pair<iterator,bool> insert_noresize(const value_type& __obj)
{ return _M_ht.insert_unique_noresize(__obj); }
iterator find(const key_type& __key) { return _M_ht.find(__key); }
const_iterator find(const key_type& __key) const
{ return _M_ht.find(__key); }
_Tp& operator[](const key_type& __key) {
return _M_ht.find_or_insert(value_type(__key, _Tp())).second;
}
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
@KWSYS_NAMESPACE@_stl::pair<iterator, iterator> equal_range(const key_type& __key)
{ return _M_ht.equal_range(__key); }
@KWSYS_NAMESPACE@_stl::pair<const_iterator, const_iterator>
equal_range(const key_type& __key) const
{ return _M_ht.equal_range(__key); }
size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
void resize(size_type __hint) { _M_ht.resize(__hint); }
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
{ return _M_ht.elems_in_bucket(__n); }
};
template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
bool
operator==(const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
{
return __hm1._M_ht == __hm2._M_ht;
}
template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
inline bool
operator!=(const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
const hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2) {
return !(__hm1 == __hm2);
}
template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
inline void
swap(hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
hash_map<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
{
__hm1.swap(__hm2);
}
// Forward declaration of equality operator; needed for friend declaration.
template <class _Key, class _Tp,
class _HashFcn = hash<_Key>,
class _EqualKey = @KWSYS_NAMESPACE@_stl::equal_to<_Key>,
class _Alloc = @KWSYS_NAMESPACE@_HASH_DEFAULT_ALLOCATOR(char) >
class hash_multimap;
template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
bool
operator==(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2);
template <class _Key, class _Tp, class _HashFcn, class _EqualKey,
class _Alloc>
class hash_multimap
{
private:
typedef hashtable<@KWSYS_NAMESPACE@_stl::pair<const _Key, _Tp>, _Key, _HashFcn,
hash_select1st<const _Key, _Tp>, _EqualKey, _Alloc>
_Ht;
_Ht _M_ht;
public:
typedef typename _Ht::key_type key_type;
typedef _Tp data_type;
typedef _Tp mapped_type;
typedef typename _Ht::value_type value_type;
typedef typename _Ht::hasher hasher;
typedef typename _Ht::key_equal key_equal;
typedef typename _Ht::size_type size_type;
typedef typename _Ht::difference_type difference_type;
typedef typename _Ht::pointer pointer;
typedef typename _Ht::const_pointer const_pointer;
typedef typename _Ht::reference reference;
typedef typename _Ht::const_reference const_reference;
typedef typename _Ht::iterator iterator;
typedef typename _Ht::const_iterator const_iterator;
typedef typename _Ht::allocator_type allocator_type;
hasher hash_funct() const { return _M_ht.hash_funct(); }
key_equal key_eq() const { return _M_ht.key_eq(); }
allocator_type get_allocator() const { return _M_ht.get_allocator(); }
public:
hash_multimap() : _M_ht(100, hasher(), key_equal(), allocator_type()) {}
explicit hash_multimap(size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
hash_multimap(size_type __n, const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type()) {}
hash_multimap(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a) {}
#if @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
template <class _InputIterator>
hash_multimap(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multimap(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
#else
hash_multimap(const value_type* __f, const value_type* __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multimap(const value_type* __f, const value_type* __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multimap(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multimap(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
hash_multimap(const_iterator __f, const_iterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multimap(const_iterator __f, const_iterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multimap(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multimap(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
#endif
public:
size_type size() const { return _M_ht.size(); }
size_type max_size() const { return _M_ht.max_size(); }
bool empty() const { return _M_ht.empty(); }
void swap(hash_multimap& __hs) { _M_ht.swap(__hs._M_ht); }
friend bool operator==@KWSYS_NAMESPACE@_CXX_NULL_TEMPLATE_ARGS(const hash_multimap&,
const hash_multimap&);
iterator begin() { return _M_ht.begin(); }
iterator end() { return _M_ht.end(); }
const_iterator begin() const { return _M_ht.begin(); }
const_iterator end() const { return _M_ht.end(); }
public:
iterator insert(const value_type& __obj)
{ return _M_ht.insert_equal(__obj); }
#if @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
{ _M_ht.insert_equal(__f,__l); }
#else
void insert(const value_type* __f, const value_type* __l) {
_M_ht.insert_equal(__f,__l);
}
void insert(const_iterator __f, const_iterator __l)
{ _M_ht.insert_equal(__f, __l); }
#endif
iterator insert_noresize(const value_type& __obj)
{ return _M_ht.insert_equal_noresize(__obj); }
iterator find(const key_type& __key) { return _M_ht.find(__key); }
const_iterator find(const key_type& __key) const
{ return _M_ht.find(__key); }
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
@KWSYS_NAMESPACE@_stl::pair<iterator, iterator> equal_range(const key_type& __key)
{ return _M_ht.equal_range(__key); }
@KWSYS_NAMESPACE@_stl::pair<const_iterator, const_iterator>
equal_range(const key_type& __key) const
{ return _M_ht.equal_range(__key); }
size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
public:
void resize(size_type __hint) { _M_ht.resize(__hint); }
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
{ return _M_ht.elems_in_bucket(__n); }
};
template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
bool
operator==(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2)
{
return __hm1._M_ht == __hm2._M_ht;
}
template <class _Key, class _Tp, class _HF, class _EqKey, class _Alloc>
inline bool
operator!=(const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm1,
const hash_multimap<_Key,_Tp,_HF,_EqKey,_Alloc>& __hm2) {
return !(__hm1 == __hm2);
}
template <class _Key, class _Tp, class _HashFcn, class _EqlKey, class _Alloc>
inline void
swap(hash_multimap<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm1,
hash_multimap<_Key,_Tp,_HashFcn,_EqlKey,_Alloc>& __hm2)
{
__hm1.swap(__hm2);
}
} // namespace @KWSYS_NAMESPACE@
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
# pragma reset woff 1174
# pragma reset woff 1375
#endif
#if defined(_MSC_VER)
# pragma warning (pop)
#endif
#endif

445
hash_set.hxx.in Normal file
View File

@ -0,0 +1,445 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
/*
* Copyright (c) 1996
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*
* Copyright (c) 1994
* Hewlett-Packard Company
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Hewlett-Packard Company makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*/
#ifndef @KWSYS_NAMESPACE@_hash_set_hxx
#define @KWSYS_NAMESPACE@_hash_set_hxx
#include <@KWSYS_NAMESPACE@/hashtable.hxx>
#include <@KWSYS_NAMESPACE@/hash_fun.hxx>
#include <@KWSYS_NAMESPACE@/stl/functional> // equal_to
#if defined(_MSC_VER)
# pragma warning (push)
# pragma warning (disable:4284)
# pragma warning (disable:4786)
#endif
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
# pragma set woff 1174
# pragma set woff 1375
#endif
namespace @KWSYS_NAMESPACE@
{
// identity is an extension: it is not part of the standard.
template <class _Tp>
struct _Identity : public @KWSYS_NAMESPACE@_stl::unary_function<_Tp,_Tp>
{
const _Tp& operator()(const _Tp& __x) const { return __x; }
};
// Forward declaration of equality operator; needed for friend declaration.
template <class _Value,
class _HashFcn = hash<_Value>,
class _EqualKey = @KWSYS_NAMESPACE@_stl::equal_to<_Value>,
class _Alloc = @KWSYS_NAMESPACE@_HASH_DEFAULT_ALLOCATOR(char) >
class hash_set;
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
bool
operator==(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2);
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
class hash_set
{
private:
typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>,
_EqualKey, _Alloc> _Ht;
_Ht _M_ht;
public:
typedef typename _Ht::key_type key_type;
typedef typename _Ht::value_type value_type;
typedef typename _Ht::hasher hasher;
typedef typename _Ht::key_equal key_equal;
typedef typename _Ht::size_type size_type;
typedef typename _Ht::difference_type difference_type;
typedef typename _Ht::const_pointer pointer;
typedef typename _Ht::const_pointer const_pointer;
typedef typename _Ht::const_reference reference;
typedef typename _Ht::const_reference const_reference;
typedef typename _Ht::const_iterator iterator;
typedef typename _Ht::const_iterator const_iterator;
typedef typename _Ht::allocator_type allocator_type;
hasher hash_funct() const { return _M_ht.hash_funct(); }
key_equal key_eq() const { return _M_ht.key_eq(); }
allocator_type get_allocator() const { return _M_ht.get_allocator(); }
public:
hash_set()
: _M_ht(100, hasher(), key_equal(), allocator_type()) {}
explicit hash_set(size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
hash_set(size_type __n, const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type()) {}
hash_set(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a) {}
#if @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
template <class _InputIterator>
hash_set(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
#else
hash_set(const value_type* __f, const value_type* __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const value_type* __f, const value_type* __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
hash_set(const_iterator __f, const_iterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const_iterator __f, const_iterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_unique(__f, __l); }
hash_set(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_unique(__f, __l); }
#endif
public:
size_type size() const { return _M_ht.size(); }
size_type max_size() const { return _M_ht.max_size(); }
bool empty() const { return _M_ht.empty(); }
void swap(hash_set& __hs) { _M_ht.swap(__hs._M_ht); }
friend bool operator==@KWSYS_NAMESPACE@_CXX_NULL_TEMPLATE_ARGS(const hash_set&,
const hash_set&);
iterator begin() const { return _M_ht.begin(); }
iterator end() const { return _M_ht.end(); }
public:
@KWSYS_NAMESPACE@_stl::pair<iterator, bool> insert(const value_type& __obj)
{
typedef typename _Ht::iterator _Ht_iterator;
@KWSYS_NAMESPACE@_stl::pair<_Ht_iterator, bool> __p = _M_ht.insert_unique(__obj);
return @KWSYS_NAMESPACE@_stl::pair<iterator,bool>(__p.first, __p.second);
}
#if @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
{ _M_ht.insert_unique(__f,__l); }
#else
void insert(const value_type* __f, const value_type* __l) {
_M_ht.insert_unique(__f,__l);
}
void insert(const_iterator __f, const_iterator __l)
{_M_ht.insert_unique(__f, __l); }
#endif
@KWSYS_NAMESPACE@_stl::pair<iterator, bool> insert_noresize(const value_type& __obj)
{
typedef typename _Ht::iterator _Ht_iterator;
@KWSYS_NAMESPACE@_stl::pair<_Ht_iterator, bool> __p =
_M_ht.insert_unique_noresize(__obj);
return @KWSYS_NAMESPACE@_stl::pair<iterator, bool>(__p.first, __p.second);
}
iterator find(const key_type& __key) const { return _M_ht.find(__key); }
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
@KWSYS_NAMESPACE@_stl::pair<iterator, iterator> equal_range(const key_type& __key) const
{ return _M_ht.equal_range(__key); }
size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
public:
void resize(size_type __hint) { _M_ht.resize(__hint); }
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
{ return _M_ht.elems_in_bucket(__n); }
};
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
bool
operator==(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2)
{
return __hs1._M_ht == __hs2._M_ht;
}
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
inline bool
operator!=(const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_set<_Value,_HashFcn,_EqualKey,_Alloc>& __hs2) {
return !(__hs1 == __hs2);
}
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
inline void
swap(hash_set<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
hash_set<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2)
{
__hs1.swap(__hs2);
}
template <class _Value,
class _HashFcn = hash<_Value>,
class _EqualKey = @KWSYS_NAMESPACE@_stl::equal_to<_Value>,
class _Alloc = @KWSYS_NAMESPACE@_HASH_DEFAULT_ALLOCATOR(char) >
class hash_multiset;
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
bool
operator==(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2);
template <class _Value, class _HashFcn, class _EqualKey, class _Alloc>
class hash_multiset
{
private:
typedef hashtable<_Value, _Value, _HashFcn, _Identity<_Value>,
_EqualKey, _Alloc> _Ht;
_Ht _M_ht;
public:
typedef typename _Ht::key_type key_type;
typedef typename _Ht::value_type value_type;
typedef typename _Ht::hasher hasher;
typedef typename _Ht::key_equal key_equal;
typedef typename _Ht::size_type size_type;
typedef typename _Ht::difference_type difference_type;
typedef typename _Ht::const_pointer pointer;
typedef typename _Ht::const_pointer const_pointer;
typedef typename _Ht::const_reference reference;
typedef typename _Ht::const_reference const_reference;
typedef typename _Ht::const_iterator iterator;
typedef typename _Ht::const_iterator const_iterator;
typedef typename _Ht::allocator_type allocator_type;
hasher hash_funct() const { return _M_ht.hash_funct(); }
key_equal key_eq() const { return _M_ht.key_eq(); }
allocator_type get_allocator() const { return _M_ht.get_allocator(); }
public:
hash_multiset()
: _M_ht(100, hasher(), key_equal(), allocator_type()) {}
explicit hash_multiset(size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type()) {}
hash_multiset(size_type __n, const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type()) {}
hash_multiset(size_type __n, const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a) {}
#if @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
template <class _InputIterator>
hash_multiset(_InputIterator __f, _InputIterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
#else
hash_multiset(const value_type* __f, const value_type* __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const value_type* __f, const value_type* __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const value_type* __f, const value_type* __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const_iterator __f, const_iterator __l)
: _M_ht(100, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const_iterator __f, const_iterator __l, size_type __n)
: _M_ht(__n, hasher(), key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf)
: _M_ht(__n, __hf, key_equal(), allocator_type())
{ _M_ht.insert_equal(__f, __l); }
hash_multiset(const_iterator __f, const_iterator __l, size_type __n,
const hasher& __hf, const key_equal& __eql,
const allocator_type& __a = allocator_type())
: _M_ht(__n, __hf, __eql, __a)
{ _M_ht.insert_equal(__f, __l); }
#endif
public:
size_type size() const { return _M_ht.size(); }
size_type max_size() const { return _M_ht.max_size(); }
bool empty() const { return _M_ht.empty(); }
void swap(hash_multiset& hs) { _M_ht.swap(hs._M_ht); }
friend bool operator==@KWSYS_NAMESPACE@_CXX_NULL_TEMPLATE_ARGS(const hash_multiset&,
const hash_multiset&);
iterator begin() const { return _M_ht.begin(); }
iterator end() const { return _M_ht.end(); }
public:
iterator insert(const value_type& __obj)
{ return _M_ht.insert_equal(__obj); }
#if @KWSYS_NAMESPACE@_CXX_HAS_MEMBER_TEMPLATES
template <class _InputIterator>
void insert(_InputIterator __f, _InputIterator __l)
{ _M_ht.insert_equal(__f,__l); }
#else
void insert(const value_type* __f, const value_type* __l) {
_M_ht.insert_equal(__f,__l);
}
void insert(const_iterator __f, const_iterator __l)
{ _M_ht.insert_equal(__f, __l); }
#endif
iterator insert_noresize(const value_type& __obj)
{ return _M_ht.insert_equal_noresize(__obj); }
iterator find(const key_type& __key) const { return _M_ht.find(__key); }
size_type count(const key_type& __key) const { return _M_ht.count(__key); }
@KWSYS_NAMESPACE@_stl::pair<iterator, iterator> equal_range(const key_type& __key) const
{ return _M_ht.equal_range(__key); }
size_type erase(const key_type& __key) {return _M_ht.erase(__key); }
void erase(iterator __it) { _M_ht.erase(__it); }
void erase(iterator __f, iterator __l) { _M_ht.erase(__f, __l); }
void clear() { _M_ht.clear(); }
public:
void resize(size_type __hint) { _M_ht.resize(__hint); }
size_type bucket_count() const { return _M_ht.bucket_count(); }
size_type max_bucket_count() const { return _M_ht.max_bucket_count(); }
size_type elems_in_bucket(size_type __n) const
{ return _M_ht.elems_in_bucket(__n); }
};
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
bool
operator==(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2)
{
return __hs1._M_ht == __hs2._M_ht;
}
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
inline bool
operator!=(const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
const hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2) {
return !(__hs1 == __hs2);
}
template <class _Val, class _HashFcn, class _EqualKey, class _Alloc>
inline void
swap(hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs1,
hash_multiset<_Val,_HashFcn,_EqualKey,_Alloc>& __hs2) {
__hs1.swap(__hs2);
}
} // namespace @KWSYS_NAMESPACE@
#if defined(__sgi) && !defined(__GNUC__) && (_MIPS_SIM != _MIPS_SIM_ABI32)
# pragma reset woff 1174
# pragma reset woff 1375
#endif
#if defined(_MSC_VER)
# pragma warning (pop)
#endif
#endif

1275
hashtable.hxx.in Normal file

File diff suppressed because it is too large Load Diff

50
kwsysHeaderDump.pl Executable file
View File

@ -0,0 +1,50 @@
#!/usr/bin/perl
#=============================================================================
# KWSys - Kitware System Library
# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
if ( $#ARGV+1 < 2 )
{
print "Usage: ./kwsysHeaderDump.pl <name> <header>\n";
exit(1);
}
$name = $ARGV[0];
$max = 0;
open(INFILE, $ARGV[1]);
while (chomp ($line = <INFILE>))
{
if (($line !~ /^\#/) &&
($line =~ s/.*kwsys${name}_([A-Za-z0-9_]*).*/\1/) &&
($i{$line}++ < 1))
{
push(@lines, "$line");
if (length($line) > $max)
{
$max = length($line);
}
}
}
close(INFILE);
$width = $max + 13;
print sprintf("#define %-${width}s kwsys_ns(${name})\n", "kwsys${name}");
foreach $l (@lines)
{
print sprintf("#define %-${width}s kwsys_ns(${name}_$l)\n",
"kwsys${name}_$l");
}
print "\n";
print sprintf("# undef kwsys${name}\n");
foreach $l (@lines)
{
print sprintf("# undef kwsys${name}_$l\n");
}

216
kwsysPlatformTests.cmake Normal file
View File

@ -0,0 +1,216 @@
#=============================================================================
# KWSys - Kitware System Library
# Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
#
# Distributed under the OSI-approved BSD License (the "License");
# see accompanying file Copyright.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even the
# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the License for more information.
#=============================================================================
SET(KWSYS_PLATFORM_TEST_FILE_C kwsysPlatformTestsC.c)
SET(KWSYS_PLATFORM_TEST_FILE_CXX kwsysPlatformTestsCXX.cxx)
MACRO(KWSYS_PLATFORM_TEST lang var description invert)
IF("${var}_COMPILED" MATCHES "^${var}_COMPILED$")
MESSAGE(STATUS "${description}")
TRY_COMPILE(${var}_COMPILED
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/${KWSYS_PLATFORM_TEST_FILE_${lang}}
COMPILE_DEFINITIONS -DTEST_${var} ${KWSYS_PLATFORM_TEST_DEFINES} ${KWSYS_PLATFORM_TEST_EXTRA_FLAGS}
OUTPUT_VARIABLE OUTPUT)
IF(${var}_COMPILED)
FILE(APPEND
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"${description} compiled with the following output:\n${OUTPUT}\n\n")
ELSE(${var}_COMPILED)
FILE(APPEND
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"${description} failed to compile with the following output:\n${OUTPUT}\n\n")
ENDIF(${var}_COMPILED)
IF(${invert} MATCHES INVERT)
IF(${var}_COMPILED)
MESSAGE(STATUS "${description} - no")
ELSE(${var}_COMPILED)
MESSAGE(STATUS "${description} - yes")
ENDIF(${var}_COMPILED)
ELSE(${invert} MATCHES INVERT)
IF(${var}_COMPILED)
MESSAGE(STATUS "${description} - yes")
ELSE(${var}_COMPILED)
MESSAGE(STATUS "${description} - no")
ENDIF(${var}_COMPILED)
ENDIF(${invert} MATCHES INVERT)
ENDIF("${var}_COMPILED" MATCHES "^${var}_COMPILED$")
IF(${invert} MATCHES INVERT)
IF(${var}_COMPILED)
SET(${var} 0)
ELSE(${var}_COMPILED)
SET(${var} 1)
ENDIF(${var}_COMPILED)
ELSE(${invert} MATCHES INVERT)
IF(${var}_COMPILED)
SET(${var} 1)
ELSE(${var}_COMPILED)
SET(${var} 0)
ENDIF(${var}_COMPILED)
ENDIF(${invert} MATCHES INVERT)
ENDMACRO(KWSYS_PLATFORM_TEST)
MACRO(KWSYS_PLATFORM_TEST_RUN lang var description invert)
IF("${var}" MATCHES "^${var}$")
MESSAGE(STATUS "${description}")
TRY_RUN(${var} ${var}_COMPILED
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/${KWSYS_PLATFORM_TEST_FILE_${lang}}
COMPILE_DEFINITIONS -DTEST_${var} ${KWSYS_PLATFORM_TEST_DEFINES} ${KWSYS_PLATFORM_TEST_EXTRA_FLAGS}
OUTPUT_VARIABLE OUTPUT)
# Note that ${var} will be a 0 return value on success.
IF(${var}_COMPILED)
IF(${var})
FILE(APPEND
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"${description} compiled but failed to run with the following output:\n${OUTPUT}\n\n")
ELSE(${var})
FILE(APPEND
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"${description} compiled and ran with the following output:\n${OUTPUT}\n\n")
ENDIF(${var})
ELSE(${var}_COMPILED)
FILE(APPEND
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"${description} failed to compile with the following output:\n${OUTPUT}\n\n")
SET(${var} -1 CACHE INTERNAL "${description} failed to compile.")
ENDIF(${var}_COMPILED)
IF(${invert} MATCHES INVERT)
IF(${var}_COMPILED)
IF(${var})
MESSAGE(STATUS "${description} - yes")
ELSE(${var})
MESSAGE(STATUS "${description} - no")
ENDIF(${var})
ELSE(${var}_COMPILED)
MESSAGE(STATUS "${description} - failed to compile")
ENDIF(${var}_COMPILED)
ELSE(${invert} MATCHES INVERT)
IF(${var}_COMPILED)
IF(${var})
MESSAGE(STATUS "${description} - no")
ELSE(${var})
MESSAGE(STATUS "${description} - yes")
ENDIF(${var})
ELSE(${var}_COMPILED)
MESSAGE(STATUS "${description} - failed to compile")
ENDIF(${var}_COMPILED)
ENDIF(${invert} MATCHES INVERT)
ENDIF("${var}" MATCHES "^${var}$")
IF(${invert} MATCHES INVERT)
IF(${var}_COMPILED)
IF(${var})
SET(${var} 1)
ELSE(${var})
SET(${var} 0)
ENDIF(${var})
ELSE(${var}_COMPILED)
SET(${var} 1)
ENDIF(${var}_COMPILED)
ELSE(${invert} MATCHES INVERT)
IF(${var}_COMPILED)
IF(${var})
SET(${var} 0)
ELSE(${var})
SET(${var} 1)
ENDIF(${var})
ELSE(${var}_COMPILED)
SET(${var} 0)
ENDIF(${var}_COMPILED)
ENDIF(${invert} MATCHES INVERT)
ENDMACRO(KWSYS_PLATFORM_TEST_RUN)
MACRO(KWSYS_PLATFORM_C_TEST var description invert)
SET(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_C_TEST_DEFINES})
SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_C_TEST_EXTRA_FLAGS})
KWSYS_PLATFORM_TEST(C "${var}" "${description}" "${invert}")
SET(KWSYS_PLATFORM_TEST_DEFINES)
SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS)
ENDMACRO(KWSYS_PLATFORM_C_TEST)
MACRO(KWSYS_PLATFORM_C_TEST_RUN var description invert)
SET(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_C_TEST_DEFINES})
SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_C_TEST_EXTRA_FLAGS})
KWSYS_PLATFORM_TEST_RUN(C "${var}" "${description}" "${invert}")
SET(KWSYS_PLATFORM_TEST_DEFINES)
SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS)
ENDMACRO(KWSYS_PLATFORM_C_TEST_RUN)
MACRO(KWSYS_PLATFORM_CXX_TEST var description invert)
SET(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_CXX_TEST_DEFINES})
SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS})
KWSYS_PLATFORM_TEST(CXX "${var}" "${description}" "${invert}")
SET(KWSYS_PLATFORM_TEST_DEFINES)
SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS)
ENDMACRO(KWSYS_PLATFORM_CXX_TEST)
MACRO(KWSYS_PLATFORM_CXX_TEST_RUN var description invert)
SET(KWSYS_PLATFORM_TEST_DEFINES ${KWSYS_PLATFORM_CXX_TEST_DEFINES})
SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS ${KWSYS_PLATFORM_CXX_TEST_EXTRA_FLAGS})
KWSYS_PLATFORM_TEST_RUN(CXX "${var}" "${description}" "${invert}")
SET(KWSYS_PLATFORM_TEST_DEFINES)
SET(KWSYS_PLATFORM_TEST_EXTRA_FLAGS)
ENDMACRO(KWSYS_PLATFORM_CXX_TEST_RUN)
#-----------------------------------------------------------------------------
# KWSYS_PLATFORM_INFO_TEST(lang var description)
#
# Compile test named by ${var} and store INFO strings extracted from binary.
MACRO(KWSYS_PLATFORM_INFO_TEST lang var description)
# We can implement this macro on CMake 2.6 and above.
IF("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.6)
SET(${var} "")
ELSE()
# Choose a location for the result binary.
SET(KWSYS_PLATFORM_INFO_FILE
${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY}/${var}.bin)
# Compile the test binary.
IF(NOT EXISTS ${KWSYS_PLATFORM_INFO_FILE})
MESSAGE(STATUS "${description}")
TRY_COMPILE(${var}_COMPILED
${CMAKE_CURRENT_BINARY_DIR}
${CMAKE_CURRENT_SOURCE_DIR}/${KWSYS_PLATFORM_TEST_FILE_${lang}}
COMPILE_DEFINITIONS -DTEST_${var}
${KWSYS_PLATFORM_${lang}_TEST_DEFINES}
${KWSYS_PLATFORM_${lang}_TEST_EXTRA_FLAGS}
OUTPUT_VARIABLE OUTPUT
COPY_FILE ${KWSYS_PLATFORM_INFO_FILE}
)
IF(${var}_COMPILED)
FILE(APPEND
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeOutput.log
"${description} compiled with the following output:\n${OUTPUT}\n\n")
ELSE()
FILE(APPEND
${CMAKE_BINARY_DIR}${CMAKE_FILES_DIRECTORY}/CMakeError.log
"${description} failed to compile with the following output:\n${OUTPUT}\n\n")
ENDIF()
IF(${var}_COMPILED)
MESSAGE(STATUS "${description} - compiled")
ELSE()
MESSAGE(STATUS "${description} - failed")
ENDIF()
ENDIF()
# Parse info strings out of the compiled binary.
IF(${var}_COMPILED)
FILE(STRINGS ${KWSYS_PLATFORM_INFO_FILE} ${var} REGEX "INFO:[A-Za-z0-9]+\\[[^]]*\\]")
ELSE()
SET(${var} "")
ENDIF()
SET(KWSYS_PLATFORM_INFO_FILE)
ENDIF()
ENDMACRO()

100
kwsysPlatformTestsC.c Normal file
View File

@ -0,0 +1,100 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
/*
Macros to define main() in a cross-platform way.
Usage:
int KWSYS_PLATFORM_TEST_C_MAIN()
{
return 0;
}
int KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv)
{
(void)argc; (void)argv;
return 0;
}
*/
#if defined(__CLASSIC_C__)
# define KWSYS_PLATFORM_TEST_C_MAIN() \
main()
# define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv) \
main(argc,argv) int argc; char* argv[];
#else
# define KWSYS_PLATFORM_TEST_C_MAIN() \
main(void)
# define KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv) \
main(int argc, char* argv[])
#endif
/*--------------------------------------------------------------------------*/
#ifdef TEST_KWSYS_C_HAS_PTRDIFF_T
#include <stddef.h>
int f(ptrdiff_t n) { return n > 0; }
int KWSYS_PLATFORM_TEST_C_MAIN()
{
char* p = 0;
ptrdiff_t d = p - p;
(void)d;
return f(p - p);
}
#endif
/*--------------------------------------------------------------------------*/
#ifdef TEST_KWSYS_C_HAS_SSIZE_T
#include <unistd.h>
int f(ssize_t n) { return (int)n; }
int KWSYS_PLATFORM_TEST_C_MAIN()
{
ssize_t n = 0;
return f(n);
}
#endif
/*--------------------------------------------------------------------------*/
#ifdef TEST_KWSYS_C_TYPE_MACROS
char* info_macros =
#if defined(__SIZEOF_SHORT__)
"INFO:macro[__SIZEOF_SHORT__]\n"
#endif
#if defined(__SIZEOF_INT__)
"INFO:macro[__SIZEOF_INT__]\n"
#endif
#if defined(__SIZEOF_LONG__)
"INFO:macro[__SIZEOF_LONG__]\n"
#endif
#if defined(__SIZEOF_LONG_LONG__)
"INFO:macro[__SIZEOF_LONG_LONG__]\n"
#endif
#if defined(__SHORT_MAX__)
"INFO:macro[__SHORT_MAX__]\n"
#endif
#if defined(__INT_MAX__)
"INFO:macro[__INT_MAX__]\n"
#endif
#if defined(__LONG_MAX__)
"INFO:macro[__LONG_MAX__]\n"
#endif
#if defined(__LONG_LONG_MAX__)
"INFO:macro[__LONG_LONG_MAX__]\n"
#endif
"";
int KWSYS_PLATFORM_TEST_C_MAIN_ARGS(argc, argv)
{
int require = 0;
require += info_macros[argc];
(void)argv;
return require;
}
#endif

516
kwsysPlatformTestsCXX.cxx Normal file
View File

@ -0,0 +1,516 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
// Setup for tests that use result of stl namespace test.
#if defined(KWSYS_STL_HAVE_STD)
# if KWSYS_STL_HAVE_STD
# define kwsys_stl std
# else
# define kwsys_stl
# endif
#endif
// Setup for tests that use iostreams.
#if defined(KWSYS_IOS_USE_ANSI) && defined(KWSYS_IOS_HAVE_STD)
# if defined(_MSC_VER)
# pragma warning (push,1)
# endif
# if KWSYS_IOS_USE_ANSI
# include <iostream>
# else
# include <iostream.h>
# endif
# if defined(_MSC_VER)
# pragma warning (pop)
# endif
# if KWSYS_IOS_HAVE_STD
# define kwsys_ios std
# else
# define kwsys_ios
# endif
#endif
#ifdef TEST_KWSYS_STL_HAVE_STD
#include <list>
void f(std ::list<int>*) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_IOS_USE_ANSI
#include <iosfwd>
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_IOS_HAVE_STD
#include <iosfwd>
void f(std ::ostream*) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_IOS_USE_SSTREAM
#include <sstream>
#if defined(__GNUC__) && __GNUC__ == 2 && __GNUC_MINOR__ == 96
# error "GCC 2.96 stringstream is buggy"
#endif
int main()
{
std ::ostringstream ostr;
ostr << "hello";
if(ostr.str().size() == 5)
{
return 0;
}
return -1;
}
#endif
#ifdef TEST_KWSYS_IOS_USE_STRSTREAM_H
#include <strstream.h>
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_IOS_USE_STRSTREA_H
#include <strstrea.h>
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_STRING_HAVE_OSTREAM
# include <iostream.h>
# include <string>
void f(ostream& os, const kwsys_stl::string& s) { os << s; }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_STRING_HAVE_ISTREAM
# include <iostream.h>
# include <string>
void f(istream& is, kwsys_stl::string& s) { is >> s; }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_STRING_HAVE_NEQ_CHAR
# include <string>
bool f(const kwsys_stl::string& s) { return s != ""; }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_CXX_HAS_CSTDIO
#include <cstdio>
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_CXX_HAS_CSTDDEF
#include <cstddef>
void f(size_t) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_CXX_HAS_LONG_LONG
long long f(long long n) { return n; }
int main()
{
long long n = 0;
return static_cast<int>(f(n));
}
#endif
#ifdef TEST_KWSYS_CXX_HAS___INT64
__int64 f(__int64 n) { return n; }
int main()
{
__int64 n = 0;
return static_cast<int>(f(n));
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_NULL_TEMPLATE_ARGS
template <class T> class A;
template <class T> int f(A<T>&);
template <class T> class A
{
public:
// "friend int f<>(A<T>&)" would conform
friend int f(A<T>&);
private:
int x;
};
template <class T> int f(A<T>& a) { return a.x = 0; }
template int f(A<int>&);
int main()
{
A<int> a;
return f(a);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_MEMBER_TEMPLATES
template <class U>
class A
{
public:
U u;
A(): u(0) {}
template <class V> V m(V* p) { return *p = u; }
};
int main()
{
A<short> a;
int s = 1;
return a.m(&s);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_FULL_SPECIALIZATION
template <class T> struct A {};
template <> struct A<int*>
{
static int f() { return 0; }
};
int main() { return A<int*>::f(); }
#endif
#ifdef TEST_KWSYS_CXX_HAS_ARGUMENT_DEPENDENT_LOOKUP
namespace N
{
class A {};
int f(A*) { return 0; }
}
void f(void*);
int main()
{
N::A* a = 0;
return f(a);
}
#endif
#ifdef TEST_KWSYS_STL_HAS_ITERATOR_TRAITS
#include <iterator>
#include <list>
void f(kwsys_stl::iterator_traits<kwsys_stl::list<int>::iterator>::iterator_category const&) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_HAS_ITERATOR_CATEGORY
#include <iterator>
#include <list>
void f(kwsys_stl::list<int>::iterator x) { kwsys_stl::iterator_category(x); }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_HAS___ITERATOR_CATEGORY
#include <iterator>
#include <list>
void f(kwsys_stl::list<int>::iterator x) { kwsys_stl::__iterator_category(x); }
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_TEMPLATE
#include <memory>
template <class Alloc>
void f(const Alloc&)
{
typedef typename Alloc::size_type alloc_size_type;
}
int main()
{
f(kwsys_stl::allocator<char>());
return 0;
}
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_NONTEMPLATE
#include <memory>
void f(kwsys_stl::allocator::size_type const&) {}
int main() { return 0; }
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_REBIND
#include <memory>
template <class T, class Alloc>
void f(const T&, const Alloc&)
{
typedef typename Alloc::template rebind<T>::other alloc_type;
}
int main()
{
f(0, kwsys_stl::allocator<char>());
return 0;
}
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_MAX_SIZE_ARGUMENT
#include <memory>
void f(kwsys_stl::allocator<char> const& a)
{
a.max_size(sizeof(int));
}
int main()
{
f(kwsys_stl::allocator<char>());
return 0;
}
#endif
#ifdef TEST_KWSYS_STL_HAS_ALLOCATOR_OBJECTS
#include <vector>
void f(kwsys_stl::vector<int> const& v1)
{
kwsys_stl::vector<int>(1, 1, v1.get_allocator());
}
int main()
{
f(kwsys_stl::vector<int>());
return 0;
}
#endif
#ifdef TEST_KWSYS_STAT_HAS_ST_MTIM
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
int main()
{
struct stat stat1;
(void)stat1.st_mtim.tv_sec;
(void)stat1.st_mtim.tv_nsec;
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_SAME_LONG_AND___INT64
void function(long**) {}
int main()
{
__int64** p = 0;
function(p);
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_SAME_LONG_LONG_AND___INT64
void function(long long**) {}
int main()
{
__int64** p = 0;
function(p);
return 0;
}
#endif
#ifdef TEST_KWSYS_CAN_CONVERT_UI64_TO_DOUBLE
void function(double& l, unsigned __int64 const& r)
{
l = static_cast<double>(r);
}
int main()
{
double tTo = 0.0;
unsigned __int64 tFrom = 0;
function(tTo, tFrom);
return 0;
}
#endif
#ifdef TEST_KWSYS_IOS_HAVE_BINARY
int test_binary(int, ...)
{
return 0;
}
int main()
{
return test_binary(1, kwsys_ios::ios::binary);
}
#endif
#ifdef TEST_KWSYS_IOS_HAS_ISTREAM_LONG_LONG
int test_istream(kwsys_ios::istream& is, long long& x)
{
return (is >> x)? 1:0;
}
int main()
{
long long x = 0;
return test_istream(kwsys_ios::cin, x);
}
#endif
#ifdef TEST_KWSYS_IOS_HAS_OSTREAM_LONG_LONG
int test_ostream(kwsys_ios::ostream& os, long long x)
{
return (os << x)? 1:0;
}
int main()
{
long long x = 0;
return test_ostream(kwsys_ios::cout, x);
}
#endif
#ifdef TEST_KWSYS_CHAR_IS_SIGNED
/* Return 0 for char signed and 1 for char unsigned. */
int main()
{
unsigned char uc = 255;
return (*reinterpret_cast<char*>(&uc) < 0)?0:1;
}
#endif
#ifdef TEST_KWSYS_LFS_WORKS
/* Return 0 when LFS is available and 1 otherwise. */
#define _LARGEFILE_SOURCE
#define _LARGEFILE64_SOURCE
#define _LARGE_FILES
#define _FILE_OFFSET_BITS 64
#include <sys/types.h>
#include <sys/stat.h>
#include <assert.h>
#if KWSYS_CXX_HAS_CSTDIO
# include <cstdio>
#endif
#include <stdio.h>
int main(int, char **argv)
{
/* check that off_t can hold 2^63 - 1 and perform basic operations... */
#define OFF_T_64 (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62))
if (OFF_T_64 % 2147483647 != 1)
return 1;
// stat breaks on SCO OpenServer
struct stat buf;
stat( argv[0], &buf );
if (!S_ISREG(buf.st_mode))
return 2;
FILE *file = fopen( argv[0], "r" );
off_t offset = ftello( file );
fseek( file, offset, SEEK_CUR );
fclose( file );
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_SETENV
#include <stdlib.h>
int main()
{
return setenv("A", "B", 1);
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_UNSETENV
#include <stdlib.h>
int main()
{
unsetenv("A");
return 0;
}
#endif
#ifdef TEST_KWSYS_CXX_HAS_ENVIRON_IN_STDLIB_H
#include <stdlib.h>
int main()
{
char* e = environ[0];
return e? 0:1;
}
#endif
#ifdef TEST_KWSYS_CXX_TYPE_INFO
/* Collect fundamental type information and save it to a CMake script. */
/* Include limits.h to get macros indicating long long and __int64.
Note that certain compilers need special macros to define these
macros in limits.h. */
#if defined(_MSC_VER) && !defined(_MSC_EXTENSIONS)
# define _MSC_EXTENSIONS
#endif
#if defined(__GNUC__) && __GNUC__ < 3
# define _GNU_SOURCE
#endif
#include <limits.h>
#include <stdio.h>
#include <string.h>
/* Due to shell differences and limitations of ADD_DEFINITIONS the
KWSYS_CXX_TYPE_INFO_FILE macro will sometimes have double quotes
and sometimes not. This macro will make sure the value is treated
as a double-quoted string. */
#define TO_STRING(x) TO_STRING0(x)
#define TO_STRING0(x) TO_STRING1(x)
#define TO_STRING1(x) #x
void f() {}
int main()
{
/* Construct the output file name. Some preprocessors will add an
extra level of double quotes, so strip them. */
char fbuf[] = TO_STRING(KWSYS_CXX_TYPE_INFO_FILE);
char* fname = fbuf;
if(fname[0] == '"')
{
++fname;
int len = static_cast<int>(strlen(fname));
if(len > 0 && fname[len-1] == '"')
{
fname[len-1] = 0;
}
}
/* Try to open the output file. */
if(FILE* fout = fopen(fname, "w"))
{
/* Set the size of standard types. */
fprintf(fout, "SET(KWSYS_SIZEOF_CHAR %d)\n", static_cast<int>(sizeof(char)));
fprintf(fout, "SET(KWSYS_SIZEOF_SHORT %d)\n", static_cast<int>(sizeof(short)));
fprintf(fout, "SET(KWSYS_SIZEOF_INT %d)\n", static_cast<int>(sizeof(int)));
fprintf(fout, "SET(KWSYS_SIZEOF_LONG %d)\n", static_cast<int>(sizeof(long)));
/* Set the size of some non-standard but common types. */
/* Check for a limits.h macro for long long to see if the type exists. */
#if defined(LLONG_MAX) || defined(LONG_LONG_MAX) || defined(LONGLONG_MAX)
fprintf(fout, "SET(KWSYS_SIZEOF_LONG_LONG %d)\n", static_cast<int>(sizeof(long long)));
#else
fprintf(fout, "SET(KWSYS_SIZEOF_LONG_LONG 0) # No long long available.\n");
#endif
/* Check for a limits.h macro for __int64 to see if the type exists. */
#if defined(_I64_MIN)
fprintf(fout, "SET(KWSYS_SIZEOF___INT64 %d)\n", static_cast<int>(sizeof(__int64)));
#else
fprintf(fout, "SET(KWSYS_SIZEOF___INT64 0) # No __int64 available.\n");
#endif
/* Set the size of some pointer types. */
fprintf(fout, "SET(KWSYS_SIZEOF_PDATA %d)\n", static_cast<int>(sizeof(void*)));
fprintf(fout, "SET(KWSYS_SIZEOF_PFUNC %d)\n", static_cast<int>(sizeof(&f)));
/* Set whether the native type "char" is signed or unsigned. */
unsigned char uc = 255;
fprintf(fout, "SET(KWSYS_CHAR_IS_SIGNED %d)\n",
(*reinterpret_cast<char*>(&uc) < 0)?1:0);
fclose(fout);
return 0;
}
else
{
fprintf(stderr, "Failed to write fundamental type info to \"%s\".\n",
fname);
return 1;
}
}
#endif

41
kwsysPrivate.h Normal file
View File

@ -0,0 +1,41 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef KWSYS_NAMESPACE
# error "Do not include kwsysPrivate.h outside of kwsys c and cxx files."
#endif
#ifndef _kwsysPrivate_h
#define _kwsysPrivate_h
/*
Define KWSYS_HEADER macro to help the c and cxx files include kwsys
headers from the configured namespace directory. The macro can be
used like this:
#include KWSYS_HEADER(Directory.hxx)
#include KWSYS_HEADER(std/vector)
*/
#define KWSYS_HEADER(x) KWSYS_HEADER0(KWSYS_NAMESPACE/x)
#define KWSYS_HEADER0(x) KWSYS_HEADER1(x)
#define KWSYS_HEADER1(x) <x>
/*
Define KWSYS_NAMESPACE_STRING to be a string constant containing the
name configured for this instance of the kwsys library.
*/
#define KWSYS_NAMESPACE_STRING KWSYS_NAMESPACE_STRING0(KWSYS_NAMESPACE)
#define KWSYS_NAMESPACE_STRING0(x) KWSYS_NAMESPACE_STRING1(x)
#define KWSYS_NAMESPACE_STRING1(x) #x
#else
# error "kwsysPrivate.h included multiple times."
#endif

35
kwsys_cstddef.hxx.in Normal file
View File

@ -0,0 +1,35 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_cstddef
#define @KWSYS_NAMESPACE@_cstddef
#include <@KWSYS_NAMESPACE@/Configure.hxx>
/* Avoid warnings in MSVC standard headers. */
#ifdef _MSC_VER
# pragma warning (push, 1)
# pragma warning (disable: 4702)
# pragma warning (disable: 4786)
#endif
/* Include the real header. */
#if @KWSYS_NAMESPACE@_CXX_HAS_CSTDDEF
# include <cstddef>
#else
# include <stddef.h>
#endif
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#endif

46
kwsys_ios_fstream.h.in Normal file
View File

@ -0,0 +1,46 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_ios_fstream
#define @KWSYS_NAMESPACE@_ios_fstream
#include <@KWSYS_NAMESPACE@/Configure.hxx>
#ifdef _MSC_VER
# pragma warning (push, 1)
# pragma warning (disable: 4702)
# pragma warning (disable: 4995) /* Old streams are deprecated. */
#endif
#if @KWSYS_NAMESPACE@_IOS_USE_ANSI
# include <fstream>
#else
# include <fstream.h>
#endif
#if !@KWSYS_NAMESPACE@_IOS_USE_SSTREAM
namespace @KWSYS_NAMESPACE@_ios
{
using @KWSYS_NAMESPACE@_ios_namespace::ostream;
using @KWSYS_NAMESPACE@_ios_namespace::istream;
using @KWSYS_NAMESPACE@_ios_namespace::ofstream;
using @KWSYS_NAMESPACE@_ios_namespace::ifstream;
using @KWSYS_NAMESPACE@_ios_namespace::ios;
using @KWSYS_NAMESPACE@_ios_namespace::endl;
using @KWSYS_NAMESPACE@_ios_namespace::flush;
}
#endif
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#endif

49
kwsys_ios_iosfwd.h.in Normal file
View File

@ -0,0 +1,49 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_ios_iosfwd
#define @KWSYS_NAMESPACE@_ios_iosfwd
#include <@KWSYS_NAMESPACE@/Configure.hxx>
#ifdef _MSC_VER
#pragma warning (push, 1)
#pragma warning (disable: 4702)
#endif
#if @KWSYS_NAMESPACE@_IOS_USE_ANSI
# include <iosfwd>
#else
class fstream;
class ifstream;
class ios;
class istream;
class ofstream;
class ostream;
#endif
#if !@KWSYS_NAMESPACE@_IOS_USE_SSTREAM
namespace @KWSYS_NAMESPACE@_ios
{
using @KWSYS_NAMESPACE@_ios_namespace::fstream;
using @KWSYS_NAMESPACE@_ios_namespace::ifstream;
using @KWSYS_NAMESPACE@_ios_namespace::ios;
using @KWSYS_NAMESPACE@_ios_namespace::istream;
using @KWSYS_NAMESPACE@_ios_namespace::ofstream;
using @KWSYS_NAMESPACE@_ios_namespace::ostream;
}
#endif
#ifdef _MSC_VER
#pragma warning(pop)
#endif
#endif

99
kwsys_ios_iostream.h.in Normal file
View File

@ -0,0 +1,99 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_ios_iostream
#define @KWSYS_NAMESPACE@_ios_iostream
#include <@KWSYS_NAMESPACE@/Configure.hxx>
#ifdef _MSC_VER
# pragma warning (push, 1)
# pragma warning (disable: 4702)
# pragma warning (disable: 4995) /* Old streams are deprecated. */
#endif
#if @KWSYS_NAMESPACE@_IOS_USE_ANSI
# include <iostream>
#else
# include <iostream.h>
#endif
// The HP implementation of iostream defines cin, cout, cerr, and clog
// as macros in order to do thread-private streams.
// See /opt/aCC/include/iostream/iostream.h for details.
// This block redefines the macros in a safe way that is also compatible
// with the HP definitions and the using declarations below.
#if !@KWSYS_NAMESPACE@_IOS_USE_SSTREAM
# if defined(__HP_aCC) && (defined(HP_THREAD_SAFE) || defined(_THREAD_SAFE))
# if defined(cin) && !defined(@KWSYS_NAMESPACE@_IOS_HP_HACK_CIN)
# define @KWSYS_NAMESPACE@_IOS_HP_HACK_CIN
# undef cin
# define cin __tcin.ref()
# endif
# if defined(cout) && !defined(@KWSYS_NAMESPACE@_IOS_HP_HACK_COUT)
# define @KWSYS_NAMESPACE@_IOS_HP_HACK_COUT
# undef cout
# define cout __tcout.ref()
# endif
# if defined(cerr) && !defined(@KWSYS_NAMESPACE@_IOS_HP_HACK_CERR)
# define @KWSYS_NAMESPACE@_IOS_HP_HACK_CERR
# undef cerr
# define cerr __tcerr.ref()
# endif
# if defined(clog) && !defined(@KWSYS_NAMESPACE@_IOS_HP_HACK_CLOG)
# define @KWSYS_NAMESPACE@_IOS_HP_HACK_CLOG
# undef clog
# define clog __tclog.ref()
# endif
# endif
#endif
// If using our own sstream emulation code, put the standard
// streams in the same namespace.
#if !@KWSYS_NAMESPACE@_IOS_USE_SSTREAM
namespace @KWSYS_NAMESPACE@_ios
{
typedef int streamsize;
typedef int streamoff;
using @KWSYS_NAMESPACE@_ios_namespace::ostream;
using @KWSYS_NAMESPACE@_ios_namespace::istream;
using @KWSYS_NAMESPACE@_ios_namespace::ios;
using @KWSYS_NAMESPACE@_ios_namespace::endl;
using @KWSYS_NAMESPACE@_ios_namespace::flush;
# if defined(@KWSYS_NAMESPACE@_IOS_HP_HACK_CIN)
using @KWSYS_NAMESPACE@_ios_namespace::__tcin;
# else
using @KWSYS_NAMESPACE@_ios_namespace::cin;
# endif
# if defined(@KWSYS_NAMESPACE@_IOS_HP_HACK_COUT)
using @KWSYS_NAMESPACE@_ios_namespace::__tcout;
# else
using @KWSYS_NAMESPACE@_ios_namespace::cout;
# endif
# if defined(@KWSYS_NAMESPACE@_IOS_HP_HACK_CERR)
using @KWSYS_NAMESPACE@_ios_namespace::__tcerr;
# else
using @KWSYS_NAMESPACE@_ios_namespace::cerr;
# endif
# if defined(@KWSYS_NAMESPACE@_IOS_HP_HACK_CLOG)
using @KWSYS_NAMESPACE@_ios_namespace::__tclog;
# else
using @KWSYS_NAMESPACE@_ios_namespace::clog;
# endif
}
#endif
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#endif

199
kwsys_ios_sstream.h.in Normal file
View File

@ -0,0 +1,199 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_ios_sstream
#define @KWSYS_NAMESPACE@_ios_sstream
#include <@KWSYS_NAMESPACE@/Configure.hxx>
/* Define this macro temporarily to keep the code readable. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# define kwsys_stl @KWSYS_NAMESPACE@_stl
#endif
#if @KWSYS_NAMESPACE@_IOS_USE_SSTREAM
# ifdef _MSC_VER
# pragma warning (push, 1)
# pragma warning (disable: 4702)
# endif
# include <sstream>
# ifdef _MSC_VER
# pragma warning(pop)
# endif
#else
# ifdef _MSC_VER
# pragma warning (push, 1)
# pragma warning (disable: 4702)
# pragma warning (disable: 4995) /* Old streams are deprecated. */
# endif
# if @KWSYS_NAMESPACE@_IOS_USE_ANSI
# include <strstream>
# elif @KWSYS_NAMESPACE@_IOS_USE_STRSTREAM_H
# include <strstream.h>
# elif @KWSYS_NAMESPACE@_IOS_USE_STRSTREA_H
# include <strstrea.h>
# endif
# if @KWSYS_NAMESPACE@_IOS_USE_ANSI
# include <new> // Need placement operator new.
# else
# include <new.h> // Need placement operator new.
# endif
# ifdef _MSC_VER
# pragma warning(pop)
# endif
// Only have old std strstream classes. Wrap them to look like new
// ostringstream and istringstream classes.
# include <@KWSYS_NAMESPACE@/stl/string>
namespace @KWSYS_NAMESPACE@_ios
{
using @KWSYS_NAMESPACE@_ios_namespace::streambuf;
using @KWSYS_NAMESPACE@_ios_namespace::ostream;
using @KWSYS_NAMESPACE@_ios_namespace::istream;
using @KWSYS_NAMESPACE@_ios_namespace::strstream;
using @KWSYS_NAMESPACE@_ios_namespace::istrstream;
using @KWSYS_NAMESPACE@_ios_namespace::ostrstream;
using @KWSYS_NAMESPACE@_ios_namespace::ios;
using @KWSYS_NAMESPACE@_ios_namespace::endl;
using @KWSYS_NAMESPACE@_ios_namespace::ends;
using @KWSYS_NAMESPACE@_ios_namespace::flush;
class stringstream_cleanup
{
public:
stringstream_cleanup(strstream& str): m_StrStream(str) {}
~stringstream_cleanup() { m_StrStream.rdbuf()->freeze(0); }
static void IgnoreUnusedVariable(const stringstream_cleanup&) {}
protected:
strstream& m_StrStream;
private:
void operator=(stringstream_cleanup const&);
};
class stringstream: public strstream
{
public:
typedef strstream Superclass;
stringstream() {}
stringstream(const kwsys_stl::string& s) { *this << s.c_str(); }
kwsys_stl::string str()
{
stringstream_cleanup cleanup(*this);
stringstream_cleanup::IgnoreUnusedVariable(cleanup);
// Visual Studio 6 has a strstream::pcount, but this is not rdbuf()->pcount()
#if (@KWSYS_NAMESPACE@_IOS_USE_STRSTREA_H) && defined(_MSC_VER) && (_MSC_VER == 1200)
int count = this->pcount();
#elif defined(__WATCOMC__)
int count = this->rdbuf()->out_waiting();
#else
int count = this->rdbuf()->pcount();
#endif
const char* ptr = this->Superclass::str();
return kwsys_stl::string(ptr?ptr:"", count);
}
void str(const kwsys_stl::string& s)
{
this->~stringstream();
new (this) stringstream(s);
}
private:
stringstream(const stringstream&);
void operator=(const stringstream&);
};
class ostringstream_cleanup
{
public:
ostringstream_cleanup(ostrstream& ostr): m_OStrStream(ostr) {}
~ostringstream_cleanup() { m_OStrStream.rdbuf()->freeze(0); }
static void IgnoreUnusedVariable(const ostringstream_cleanup&) {}
protected:
ostrstream& m_OStrStream;
private:
void operator=(ostringstream_cleanup const&);
};
class ostringstream: public ostrstream
{
public:
typedef ostrstream Superclass;
ostringstream() {}
ostringstream(const kwsys_stl::string& s) { *this << s.c_str(); }
kwsys_stl::string str()
{
ostringstream_cleanup cleanup(*this);
ostringstream_cleanup::IgnoreUnusedVariable(cleanup);
int count = this->pcount();
const char* ptr = this->Superclass::str();
return kwsys_stl::string(ptr?ptr:"", count);
}
void str(const kwsys_stl::string& s)
{
this->~ostringstream();
new (this) ostringstream(s);
}
private:
ostringstream(const ostringstream&);
void operator=(const ostringstream&);
};
#if defined(_MSC_VER)
# pragma warning (push)
# pragma warning (disable: 4097) /* typedef-name used as synonym for class */
#endif
#if defined(__WATCOMC__)
// W728: class modifiers for 'A' conflict with class modifiers for 'B'
# pragma warning 728 10
#endif
class istringstream: private kwsys_stl::string, public istrstream
{
public:
typedef kwsys_stl::string StdString;
typedef istrstream IStrStream;
istringstream(): StdString(),
IStrStream(const_cast<char*>(StdString::c_str())) {}
istringstream(const kwsys_stl::string& s):
StdString(s), IStrStream(const_cast<char*>(StdString::c_str())) {}
kwsys_stl::string str() const { return *this; }
void str(const kwsys_stl::string& s)
{
this->~istringstream();
new (this) istringstream(s);
}
void clear(int flags)
{
this->IStrStream::clear(flags);
}
private:
istringstream(const istringstream&);
void operator=(const istringstream&);
};
#if defined(__WATCOMC__)
# pragma warning 728 9
#endif
#if defined(_MSC_VER)
# pragma warning (pop)
#endif
} // namespace @KWSYS_NAMESPACE@_ios
#endif
/* Undefine temporary macro. */
#if !defined (KWSYS_NAMESPACE) && !@KWSYS_NAMESPACE@_NAME_IS_KWSYS
# undef kwsys_stl
#endif
#endif

49
kwsys_stl.hxx.in Normal file
View File

@ -0,0 +1,49 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_stl_@KWSYS_STL_HEADER@
#define @KWSYS_NAMESPACE@_stl_@KWSYS_STL_HEADER@
#include <@KWSYS_NAMESPACE@/Configure.hxx>
/* Avoid warnings in MSVC standard headers. */
#ifdef _MSC_VER
# pragma warning (push, 1)
# pragma warning (disable: 4702)
# pragma warning (disable: 4786)
#endif
/* The HP standard library defines the functor "times" instead of
"multiplies" as specified by C++98 20.3.2 for backward
compatibility with earlier specifications. Defining this macro
fixes this behavior. The name "times" also conflicts with the
function declared in sys/times.h on that platform, so we must do
this as a work-around anyway. */
#if defined(__HP_aCC) && !defined(__HPACC_USING_MULTIPLIES_IN_FUNCTIONAL)
# define __HPACC_USING_MULTIPLIES_IN_FUNCTIONAL
# define @KWSYS_NAMESPACE@_DEFINED___HPACC_USING_MULTIPLIES_IN_FUNCTIONAL
#endif
/* Include the real header. */
#include <@KWSYS_STL_HEADER@>
/* Cleanup. */
#if defined(@KWSYS_NAMESPACE@_DEFINED___HPACC_USING_MULTIPLIES_IN_FUNCTIONAL)
# undef @KWSYS_NAMESPACE@_DEFINED___HPACC_USING_MULTIPLIES_IN_FUNCTIONAL
# undef __HPACC_USING_MULTIPLIES_IN_FUNCTIONAL
#endif
#ifdef _MSC_VER
# pragma warning(pop)
#endif
@KWSYS_STL_HEADER_EXTRA@
#endif

123
kwsys_stl_string.hxx.in Normal file
View File

@ -0,0 +1,123 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
// This header is extra code for <@KWSYS_NAMESPACE@/stl/string>.
#if !defined(@KWSYS_NAMESPACE@_stl_string_including_hxx)
# error "The header <@KWSYS_NAMESPACE@/stl/string.hxx> may be included only by <@KWSYS_NAMESPACE@/stl/string>."
#endif
// Provide the istream operator for the stl string if it is not
// provided by the system or another copy of kwsys. Allow user code
// to block this definition by defining the macro
// @KWSYS_NAMESPACE@_STL_STRING_NO_ISTREAM
// to avoid conflicts with other libraries. User code can test for
// this definition by checking the macro
// @KWSYS_NAMESPACE@_STL_STRING_ISTREAM_DEFINED
#if !@KWSYS_NAMESPACE@_STL_STRING_HAVE_ISTREAM && !defined(@KWSYS_NAMESPACE@_STL_STRING_NO_ISTREAM) && !defined(KWSYS_STL_STRING_ISTREAM_DEFINED)
# define KWSYS_STL_STRING_ISTREAM_DEFINED
# define @KWSYS_NAMESPACE@_STL_STRING_ISTREAM_DEFINED
# include <ctype.h> // isspace
# include <@KWSYS_NAMESPACE@/ios/iostream>
# if defined(__WATCOMC__)
namespace @KWSYS_NAMESPACE@
{
struct ios_istream_hack: public kwsys_ios::istream
{ void eatwhite() { this->@KWSYS_NAMESPACE@_ios::istream::eatwhite(); } };
}
# endif
inline @KWSYS_NAMESPACE@_ios::istream&
operator>>(@KWSYS_NAMESPACE@_ios::istream& is,
@KWSYS_NAMESPACE@_stl::string& s)
{
// Keep track of the resulting state.
int state = @KWSYS_NAMESPACE@_ios::ios::goodbit;
// Save the width setting and set it back to zero.
size_t n = static_cast<size_t>(is.width(0));
// Clear any old contents of the output string.
s.erase();
// Skip leading whitespace.
#if defined(__WATCOMC__)
static_cast<@KWSYS_NAMESPACE@::ios_istream_hack&>(is).eatwhite();
#else
is.eatwhite();
#endif
@KWSYS_NAMESPACE@_ios::istream& okay = is;
if(okay)
{
// Select a maximum possible length.
if(n == 0 || n >= s.max_size())
{
n = s.max_size();
}
// Read until a space is found or the maximum length is reached.
bool success = false;
for(int c = is.peek(); (--n > 0 && c != EOF && !isspace(c)); c = is.peek())
{
s += static_cast<char>(c);
success = true;
is.ignore();
}
// Set flags for resulting state.
if(is.peek() == EOF) { state |= @KWSYS_NAMESPACE@_ios::ios::eofbit; }
if(!success) { state |= @KWSYS_NAMESPACE@_ios::ios::failbit; }
}
// Set the final result state.
is.clear(state);
return is;
}
#endif
// Provide the ostream operator for the stl string if it is not
// provided by the system or another copy of kwsys. Allow user code
// to block this definition by defining the macro
// @KWSYS_NAMESPACE@_STL_STRING_NO_OSTREAM
// to avoid conflicts with other libraries. User code can test for
// this definition by checking the macro
// @KWSYS_NAMESPACE@_STL_STRING_OSTREAM_DEFINED
#if !@KWSYS_NAMESPACE@_STL_STRING_HAVE_OSTREAM && !defined(@KWSYS_NAMESPACE@_STL_STRING_NO_OSTREAM) && !defined(KWSYS_STL_STRING_OSTREAM_DEFINED)
# define KWSYS_STL_STRING_OSTREAM_DEFINED
# define @KWSYS_NAMESPACE@_STL_STRING_OSTREAM_DEFINED
# include <@KWSYS_NAMESPACE@/ios/iostream>
inline @KWSYS_NAMESPACE@_ios::ostream&
operator<<(@KWSYS_NAMESPACE@_ios::ostream& os,
@KWSYS_NAMESPACE@_stl::string const& s)
{
return os << s.c_str();
}
#endif
// Provide the operator!= for the stl string and char* if it is not
// provided by the system or another copy of kwsys. Allow user code
// to block this definition by defining the macro
// @KWSYS_NAMESPACE@_STL_STRING_NO_NEQ_CHAR
// to avoid conflicts with other libraries. User code can test for
// this definition by checking the macro
// @KWSYS_NAMESPACE@_STL_STRING_NEQ_CHAR_DEFINED
#if !@KWSYS_NAMESPACE@_STL_STRING_HAVE_NEQ_CHAR && !defined(@KWSYS_NAMESPACE@_STL_STRING_NO_NEQ_CHAR) && !defined(KWSYS_STL_STRING_NEQ_CHAR_DEFINED)
# define KWSYS_STL_STRING_NEQ_CHAR_DEFINED
# define @KWSYS_NAMESPACE@_STL_STRING_NEQ_CHAR_DEFINED
inline bool operator!=(@KWSYS_NAMESPACE@_stl::string const& s, const char* c)
{
return !(s == c);
}
inline bool operator!=(const char* c, @KWSYS_NAMESPACE@_stl::string const& s)
{
return !(s == c);
}
#endif

166
testAutoPtr.cxx Normal file
View File

@ -0,0 +1,166 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifdef __BORLANDC__
# pragma warn -8027 /* 'for' not inlined. */
# pragma warn -8026 /* exception not inlined. */
#endif
#include "kwsysPrivate.h"
#include KWSYS_HEADER(auto_ptr.hxx)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "auto_ptr.hxx.in"
#endif
#include <stdio.h>
#define ASSERT(x,y) if (!(x)) { printf("FAIL: " y "\n"); status = 1; }
int instances = 0; // don't declare as static
struct A
{
A() { ++instances; }
~A() { --instances; }
A* self() {return this; }
};
struct B: public A {};
static int function_call(kwsys::auto_ptr<A> a)
{
return a.get()? 1:0;
}
static A* get_A(A& a) { return &a; }
static kwsys::auto_ptr<A> generate_auto_ptr_A()
{
return kwsys::auto_ptr<A>(new A);
}
static kwsys::auto_ptr<B> generate_auto_ptr_B()
{
return kwsys::auto_ptr<B>(new B);
}
int testAutoPtr(int, char*[])
{
int status = 0;
// Keep everything in a subscope so we can detect leaks.
{
kwsys::auto_ptr<A> pa0;
kwsys::auto_ptr<A> pa1(new A());
kwsys::auto_ptr<B> pb1(new B());
kwsys::auto_ptr<B> pb2(new B());
kwsys::auto_ptr<A> pa2(new B());
A* ptr = get_A(*pa1);
ASSERT(ptr == pa1.get(),
"auto_ptr does not return correct object when dereferenced");
ptr = pa1->self();
ASSERT(ptr == pa1.get(),
"auto_ptr does not return correct pointer from operator->");
A* before = pa0.get();
pa0.reset(new A());
ASSERT(pa0.get() && pa0.get() != before,
"auto_ptr empty after reset(new A())");
before = pa0.get();
pa0.reset(new B());
ASSERT(pa0.get() && pa0.get() != before,
"auto_ptr empty after reset(new B())");
delete pa0.release();
ASSERT(!pa0.get(), "auto_ptr holds an object after release()");
kwsys::auto_ptr<A> pa3(pb1);
ASSERT(!pb1.get(),
"auto_ptr full after being used to construct another");
ASSERT(pa3.get(),
"auto_ptr empty after construction from another");
{
kwsys::auto_ptr<A> pa;
pa = pa3;
ASSERT(!pa3.get(),
"auto_ptr full after assignment to another");
ASSERT(pa.get(),
"auto_ptr empty after assignment from another");
}
{
kwsys::auto_ptr<A> pa;
pa = pb2;
ASSERT(!pb2.get(),
"auto_ptr full after assignment to compatible");
ASSERT(pa.get(),
"auto_ptr empty after assignment from compatible");
}
{
int receive = function_call(pa2);
ASSERT(receive,
"auto_ptr did not receive ownership in called function");
ASSERT(!pa2.get(),
"auto_ptr did not release ownership to called function");
}
{
int received = function_call(generate_auto_ptr_A());
ASSERT(received,
"auto_ptr in called function did not take ownership "
"from factory function");
}
#if 0
// Is this allowed by the standard?
{
int received = function_call(generate_auto_ptr_B());
ASSERT(received,
"auto_ptr in called function did not take ownership "
"from factory function with conversion");
}
#endif
{
kwsys::auto_ptr<A> pa(generate_auto_ptr_A());
ASSERT(pa.get(),
"auto_ptr empty after construction from factory function");
}
{
kwsys::auto_ptr<A> pa;
pa = generate_auto_ptr_A();
ASSERT(pa.get(),
"auto_ptr empty after assignment from factory function");
}
{
kwsys::auto_ptr<A> pa(generate_auto_ptr_B());
ASSERT(pa.get(),
"auto_ptr empty after construction from compatible factory function");
}
{
kwsys::auto_ptr<A> pa;
pa = generate_auto_ptr_B();
ASSERT(pa.get(),
"auto_ptr empty after assignment from compatible factory function");
}
}
ASSERT(instances == 0, "auto_ptr leaked an object");
return status;
}

View File

@ -0,0 +1,187 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(CommandLineArguments.hxx)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(stl/vector)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "CommandLineArguments.hxx.in"
# include "kwsys_ios_iostream.h.in"
#endif
#include <stddef.h> /* size_t */
#include <string.h> /* strcmp */
void* random_ptr = reinterpret_cast<void*>(0x123);
int argument(const char* arg, const char* value, void* call_data)
{
kwsys_ios::cout << "Got argument: \"" << arg << "\" value: \"" << (value?value:"(null)") << "\"" << kwsys_ios::endl;
if ( call_data != random_ptr )
{
kwsys_ios::cerr << "Problem processing call_data" << kwsys_ios::endl;
return 0;
}
return 1;
}
int unknown_argument(const char* argument, void* call_data)
{
kwsys_ios::cout << "Got unknown argument: \"" << argument << "\"" << kwsys_ios::endl;
if ( call_data != random_ptr )
{
kwsys_ios::cerr << "Problem processing call_data" << kwsys_ios::endl;
return 0;
}
return 1;
}
bool CompareTwoItemsOnList(bool i1, bool i2) { return i1 == i2; }
bool CompareTwoItemsOnList(int i1, int i2) { return i1 == i2; }
bool CompareTwoItemsOnList(double i1, double i2) { return i1 == i2; }
bool CompareTwoItemsOnList(const char* i1,
const char* i2) { return strcmp(i1, i2) == 0; }
bool CompareTwoItemsOnList(const kwsys_stl::string& i1,
const kwsys_stl::string& i2) { return i1 == i2; }
int testCommandLineArguments(int argc, char* argv[])
{
// Example run: ./testCommandLineArguments --some-int-variable 4
// --another-bool-variable --some-bool-variable=yes
// --some-stl-string-variable=foobar --set-bool-arg1 --set-bool-arg2
// --some-string-variable=hello
int res = 0;
kwsys::CommandLineArguments arg;
arg.Initialize(argc, argv);
// For error handling
arg.SetClientData(random_ptr);
arg.SetUnknownArgumentCallback(unknown_argument);
int some_int_variable = 10;
double some_double_variable = 10.10;
char* some_string_variable = 0;
kwsys_stl::string some_stl_string_variable = "";
bool some_bool_variable = false;
bool some_bool_variable1 = false;
bool bool_arg1 = false;
int bool_arg2 = 0;
kwsys_stl::vector<int> numbers_argument;
int valid_numbers[] = { 5, 1, 8, 3, 7, 1, 3, 9, 7, 1 };
kwsys_stl::vector<double> doubles_argument;
double valid_doubles[] = { 12.5, 1.31, 22 };
kwsys_stl::vector<bool> bools_argument;
bool valid_bools[] = { true, true, false };
kwsys_stl::vector<char*> strings_argument;
const char* valid_strings[] = { "andy", "bill", "brad", "ken" };
kwsys_stl::vector<kwsys_stl::string> stl_strings_argument;
kwsys_stl::string valid_stl_strings[] = { "ken", "brad", "bill", "andy" };
typedef kwsys::CommandLineArguments argT;
arg.AddArgument("--some-int-variable", argT::SPACE_ARGUMENT, &some_int_variable, "Set some random int variable");
arg.AddArgument("--some-double-variable", argT::CONCAT_ARGUMENT, &some_double_variable, "Set some random double variable");
arg.AddArgument("--some-string-variable", argT::EQUAL_ARGUMENT, &some_string_variable, "Set some random string variable");
arg.AddArgument("--some-stl-string-variable", argT::EQUAL_ARGUMENT, &some_stl_string_variable, "Set some random stl string variable");
arg.AddArgument("--some-bool-variable", argT::EQUAL_ARGUMENT, &some_bool_variable, "Set some random bool variable");
arg.AddArgument("--another-bool-variable", argT::NO_ARGUMENT, &some_bool_variable1, "Set some random bool variable 1");
arg.AddBooleanArgument("--set-bool-arg1", &bool_arg1, "Test AddBooleanArgument 1");
arg.AddBooleanArgument("--set-bool-arg2", &bool_arg2, "Test AddBooleanArgument 2");
arg.AddArgument("--some-multi-argument", argT::MULTI_ARGUMENT, &numbers_argument, "Some multiple values variable");
arg.AddArgument("-N", argT::SPACE_ARGUMENT, &doubles_argument, "Some explicit multiple values variable");
arg.AddArgument("-BB", argT::CONCAT_ARGUMENT, &bools_argument, "Some explicit multiple values variable");
arg.AddArgument("-SS", argT::EQUAL_ARGUMENT, &strings_argument, "Some explicit multiple values variable");
arg.AddArgument("-SSS", argT::MULTI_ARGUMENT, &stl_strings_argument, "Some explicit multiple values variable");
arg.AddCallback("-A", argT::NO_ARGUMENT, argument, random_ptr, "Some option -A. This option has a multiline comment. It should demonstrate how the code splits lines.");
arg.AddCallback("-B", argT::SPACE_ARGUMENT, argument, random_ptr, "Option -B takes argument with space");
arg.AddCallback("-C", argT::EQUAL_ARGUMENT, argument, random_ptr, "Option -C takes argument after =");
arg.AddCallback("-D", argT::CONCAT_ARGUMENT, argument, random_ptr, "This option takes concatinated argument");
arg.AddCallback("--long1", argT::NO_ARGUMENT, argument, random_ptr, "-A");
arg.AddCallback("--long2", argT::SPACE_ARGUMENT, argument, random_ptr, "-B");
arg.AddCallback("--long3", argT::EQUAL_ARGUMENT, argument, random_ptr, "Same as -C but a bit different");
arg.AddCallback("--long4", argT::CONCAT_ARGUMENT, argument, random_ptr, "-C");
if ( !arg.Parse() )
{
kwsys_ios::cerr << "Problem parsing arguments" << kwsys_ios::endl;
res = 1;
}
kwsys_ios::cout << "Help: " << arg.GetHelp() << kwsys_ios::endl;
kwsys_ios::cout << "Some int variable was set to: " << some_int_variable << kwsys_ios::endl;
kwsys_ios::cout << "Some double variable was set to: " << some_double_variable << kwsys_ios::endl;
if ( some_string_variable && strcmp(some_string_variable, "test string with space") == 0)
{
kwsys_ios::cout << "Some string variable was set to: " << some_string_variable << kwsys_ios::endl;
delete [] some_string_variable;
}
else
{
kwsys_ios::cerr << "Problem setting string variable" << kwsys_ios::endl;
res = 1;
}
size_t cc;
#define CompareTwoLists(list1, list_valid, lsize) \
if ( list1.size() != lsize ) \
{ \
kwsys_ios::cerr << "Problem setting " #list1 ". Size is: " << list1.size() \
<< " should be: " << lsize << kwsys_ios::endl; \
res = 1; \
} \
else \
{ \
kwsys_ios::cout << #list1 " argument set:"; \
for ( cc =0; cc < lsize; ++ cc ) \
{ \
kwsys_ios::cout << " " << list1[cc]; \
if ( !CompareTwoItemsOnList(list1[cc], list_valid[cc]) ) \
{ \
kwsys_ios::cerr << "Problem setting " #list1 ". Value of " \
<< cc << " is: [" << list1[cc] << "] <> [" \
<< list_valid[cc] << "]" << kwsys_ios::endl; \
res = 1; \
break; \
} \
} \
kwsys_ios::cout << kwsys_ios::endl; \
}
CompareTwoLists(numbers_argument, valid_numbers, 10);
CompareTwoLists(doubles_argument, valid_doubles, 3);
CompareTwoLists(bools_argument, valid_bools, 3);
CompareTwoLists(strings_argument, valid_strings, 4);
CompareTwoLists(stl_strings_argument, valid_stl_strings, 4);
kwsys_ios::cout << "Some STL String variable was set to: " << some_stl_string_variable.c_str() << kwsys_ios::endl;
kwsys_ios::cout << "Some bool variable was set to: " << some_bool_variable << kwsys_ios::endl;
kwsys_ios::cout << "Some bool variable was set to: " << some_bool_variable1 << kwsys_ios::endl;
kwsys_ios::cout << "bool_arg1 variable was set to: " << bool_arg1 << kwsys_ios::endl;
kwsys_ios::cout << "bool_arg2 variable was set to: " << bool_arg2 << kwsys_ios::endl;
kwsys_ios::cout << kwsys_ios::endl;
for ( cc = 0; cc < strings_argument.size(); ++ cc )
{
delete [] strings_argument[cc];
strings_argument[cc] = 0;
}
return res;
}

View File

@ -0,0 +1,106 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(CommandLineArguments.hxx)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(stl/vector)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "CommandLineArguments.hxx.in"
# include "kwsys_ios_iostream.h.in"
#endif
#include <string.h> /* strcmp */
int testCommandLineArguments1(int argc, char* argv[])
{
kwsys::CommandLineArguments arg;
arg.Initialize(argc, argv);
int n = 0;
char* m = 0;
kwsys_stl::string p;
int res = 0;
typedef kwsys::CommandLineArguments argT;
arg.AddArgument("-n", argT::SPACE_ARGUMENT, &n, "Argument N");
arg.AddArgument("-m", argT::EQUAL_ARGUMENT, &m, "Argument M");
arg.AddBooleanArgument("-p", &p, "Argument P");
arg.StoreUnusedArguments(true);
if ( !arg.Parse() )
{
kwsys_ios::cerr << "Problem parsing arguments" << kwsys_ios::endl;
res = 1;
}
if ( n != 24 )
{
kwsys_ios::cout << "Problem setting N. Value of N: " << n << kwsys_ios::endl;
res = 1;
}
if ( !m || strcmp(m, "test value") != 0 )
{
kwsys_ios::cout << "Problem setting M. Value of M: " << m << kwsys_ios::endl;
res = 1;
}
if ( p != "1" )
{
kwsys_ios::cout << "Problem setting P. Value of P: " << p.c_str() << kwsys_ios::endl;
res = 1;
}
kwsys_ios::cout << "Value of N: " << n << kwsys_ios::endl;
kwsys_ios::cout << "Value of M: " << m << kwsys_ios::endl;
kwsys_ios::cout << "Value of P: " << p.c_str() << kwsys_ios::endl;
if ( m )
{
delete [] m;
}
char** newArgv = 0;
int newArgc = 0;
arg.GetUnusedArguments(&newArgc, &newArgv);
int cc;
const char* valid_unused_args[9] = {
0, "--ignored", "--second-ignored", "third-ignored",
"some", "junk", "at", "the", "end"
};
if ( newArgc != 9 )
{
kwsys_ios::cerr << "Bad number of unused arguments: " << newArgc << kwsys_ios::endl;
res = 1;
}
for ( cc = 0; cc < newArgc; ++ cc )
{
kwsys_ios::cout << "Unused argument[" << cc << "] = [" << newArgv[cc] << "]"
<< kwsys_ios::endl;
if ( cc >= 9 )
{
kwsys_ios::cerr << "Too many unused arguments: " << cc << kwsys_ios::endl;
res = 1;
}
else if ( valid_unused_args[cc] &&
strcmp(valid_unused_args[cc], newArgv[cc]) != 0 )
{
kwsys_ios::cerr << "Bad unused argument [" << cc << "] \""
<< newArgv[cc] << "\" should be: \"" << valid_unused_args[cc] << "\""
<< kwsys_ios::endl;
res = 1;
}
}
arg.DeleteRemainingArguments(newArgc, &newArgv);
return res;
}

133
testDynamicLoader.cxx Normal file
View File

@ -0,0 +1,133 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(DynamicLoader.hxx)
#include KWSYS_HEADER(ios/iostream)
#include KWSYS_HEADER(stl/string)
#if defined(__BEOS__) && !defined(__HAIKU__)
#include <be/kernel/OS.h> /* disable_debugger() API. */
#endif
#if defined(__HAIKU__)
#include <os/kernel/OS.h> /* disable_debugger() API. */
#endif
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "DynamicLoader.hxx.in"
# include "kwsys_ios_iostream.h.in"
# include "kwsys_stl_string.hxx.in"
#endif
// Include with <> instead of "" to avoid getting any in-source copy
// left on disk.
#include <testSystemTools.h>
kwsys_stl::string GetLibName(const char* lname)
{
// Construct proper name of lib
kwsys_stl::string slname;
slname = EXECUTABLE_OUTPUT_PATH;
#ifdef CMAKE_INTDIR
slname += "/";
slname += CMAKE_INTDIR;
#endif
slname += "/";
slname += kwsys::DynamicLoader::LibPrefix();
slname += lname;
slname += kwsys::DynamicLoader::LibExtension();
return slname;
}
/* libname = Library name (proper prefix, proper extension)
* System = symbol to lookup in libname
* r1: should OpenLibrary succeed ?
* r2: should GetSymbolAddress succeed ?
* r3: should CloseLibrary succeed ?
*/
int TestDynamicLoader(const char* libname, const char* symbol, int r1, int r2, int r3)
{
kwsys_ios::cerr << "Testing: " << libname << kwsys_ios::endl;
kwsys::DynamicLoader::LibraryHandle l
= kwsys::DynamicLoader::OpenLibrary(libname);
// If result is incompatible with expectation just fails (xor):
if( (r1 && !l) || (!r1 && l) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
kwsys::DynamicLoader::SymbolPointer f
= kwsys::DynamicLoader::GetSymbolAddress(l, symbol);
if( (r2 && !f) || (!r2 && f) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
#ifndef __APPLE__
int s = kwsys::DynamicLoader::CloseLibrary(l);
if( (r3 && !s) || (!r3 && s) )
{
kwsys_ios::cerr
<< kwsys::DynamicLoader::LastError() << kwsys_ios::endl;
return 1;
}
#else
(void)r3;
#endif
return 0;
}
int testDynamicLoader(int argc, char *argv[])
{
#if defined(_WIN32)
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#elif defined(__BEOS__) || defined(__HAIKU__)
disable_debugger(1);
#endif
int res = 0;
if( argc == 3 )
{
// User specify a libname and symbol to check.
res = TestDynamicLoader(argv[1], argv[2],1,1,1);
return res;
}
// dlopen() on Syllable before 11/22/2007 doesn't return 0 on error
#ifndef __SYLLABLE__
// Make sure that inexistant lib is giving correct result
res += TestDynamicLoader("azerty_", "foo_bar",0,0,0);
// Make sure that random binary file cannnot be assimilated as dylib
res += TestDynamicLoader(TEST_SYSTEMTOOLS_BIN_FILE, "wp",0,0,0);
#endif
#ifdef __linux__
// This one is actually fun to test, since dlopen is by default loaded...wonder why :)
res += TestDynamicLoader("foobar.lib", "dlopen",0,1,0);
res += TestDynamicLoader("libdl.so", "dlopen",1,1,1);
res += TestDynamicLoader("libdl.so", "TestDynamicLoader",1,0,1);
#endif
// Now try on the generated library
kwsys_stl::string libname = GetLibName(KWSYS_NAMESPACE_STRING "TestDynload");
res += TestDynamicLoader(libname.c_str(), "dummy",1,0,1);
res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderSymbolPointer",1,1,1);
res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderSymbolPointer",1,0,1);
res += TestDynamicLoader(libname.c_str(), "TestDynamicLoaderData",1,1,1);
res += TestDynamicLoader(libname.c_str(), "_TestDynamicLoaderData",1,0,1);
return res;
}

22
testDynload.c Normal file
View File

@ -0,0 +1,22 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifdef _WIN32
#define DL_EXPORT __declspec( dllexport )
#else
#define DL_EXPORT
#endif
DL_EXPORT int TestDynamicLoaderData = 0;
DL_EXPORT void TestDynamicLoaderSymbolPointer()
{
}

76
testEncode.c Normal file
View File

@ -0,0 +1,76 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(MD5.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "MD5.h.in"
#endif
#include <stdio.h>
#include <string.h>
static const unsigned char testMD5input1[] =
" A quick brown fox jumps over the lazy dog.\n"
" This is sample text for MD5 sum input.\n";
static const char testMD5output1[] = "8f146af46ed4f267921bb937d4d3500c";
static const int testMD5input2len = 28;
static const unsigned char testMD5input2[] = "the cow jumped over the moon";
static const char testMD5output2[] = "a2ad137b746138fae4e5adca9c85d3ae";
static int testMD5_1(kwsysMD5* md5)
{
char md5out[33];
kwsysMD5_Initialize(md5);
kwsysMD5_Append(md5, testMD5input1, -1);
kwsysMD5_FinalizeHex(md5, md5out);
md5out[32] = 0;
printf("md5sum 1: expected [%s]\n"
" got [%s]\n",
testMD5output1, md5out);
return (strcmp(md5out, testMD5output1) != 0)? 1:0;
}
static int testMD5_2(kwsysMD5* md5)
{
unsigned char digest[16];
char md5out[33];
kwsysMD5_Initialize(md5);
kwsysMD5_Append(md5, testMD5input2, testMD5input2len);
kwsysMD5_Finalize(md5, digest);
kwsysMD5_DigestToHex(digest, md5out);
md5out[32] = 0;
printf("md5sum 2: expected [%s]\n"
" got [%s]\n",
testMD5output2, md5out);
return (strcmp(md5out, testMD5output2) != 0)? 1:0;
}
int testEncode(int argc, char* argv[])
{
int result = 0;
(void)argc;
(void)argv;
/* Test MD5 digest. */
{
kwsysMD5* md5 = kwsysMD5_New();
result |= testMD5_1(md5);
result |= testMD5_2(md5);
kwsysMD5_Delete(md5);
}
return result;
}

35
testFail.c Normal file
View File

@ -0,0 +1,35 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int testFail(int argc, char* argv[])
{
char* env = getenv("DASHBOARD_TEST_FROM_CTEST");
int oldCtest = 0;
if(env)
{
if(strcmp(env, "1") == 0)
{
oldCtest = 1;
}
printf("DASHBOARD_TEST_FROM_CTEST = %s\n", env);
}
printf("%s: This test intentionally fails\n", argv[0]);
if(oldCtest)
{
printf("The version of ctest is not able to handle intentionally failing tests, so pass.\n");
return 0;
}
return argc;
}

75
testHashSTL.cxx Normal file
View File

@ -0,0 +1,75 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(hash_map.hxx)
#include KWSYS_HEADER(hash_set.hxx)
#include KWSYS_HEADER(ios/iostream)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "hash_map.hxx.in"
# include "hash_set.hxx.in"
# include "hashtable.hxx.in"
# include "kwsys_ios_iostream.h.in"
#endif
#if defined(_MSC_VER)
# pragma warning (disable:4786)
#endif
#if defined(__sgi) && !defined(__GNUC__)
# pragma set woff 1468 /* inline function cannot be explicitly instantiated */
#endif
template class kwsys::hash_map<const char*, int>;
template class kwsys::hash_set<int>;
bool test_hash_map()
{
typedef kwsys::hash_map<const char*, int> mtype;
mtype m;
const char* keys[] = {"hello", "world"};
m[keys[0]] = 1;
m.insert(mtype::value_type(keys[1], 2));
int sum = 0;
for(mtype::iterator mi = m.begin(); mi != m.end(); ++mi)
{
kwsys_ios::cout << "Found entry [" << mi->first << "," << mi->second << "]"
<< kwsys_ios::endl;
sum += mi->second;
}
return sum == 3;
}
bool test_hash_set()
{
typedef kwsys::hash_set<int> stype;
stype s;
s.insert(1);
s.insert(2);
int sum = 0;
for(stype::iterator si = s.begin(); si != s.end(); ++si)
{
kwsys_ios::cout << "Found entry [" << *si << "]" << kwsys_ios::endl;
sum += *si;
}
return sum == 3;
}
int testHashSTL(int, char*[])
{
bool result = true;
result = test_hash_map() && result;
result = test_hash_set() && result;
return result? 0:1;
}

167
testIOS.cxx Normal file
View File

@ -0,0 +1,167 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(stl/vector)
#include KWSYS_HEADER(ios/sstream)
#include KWSYS_HEADER(ios/fstream)
#include KWSYS_HEADER(ios/iostream)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "kwsys_stl_string.hxx.in"
# include "kwsys_stl_vector.h.in"
# include "kwsys_ios_sstream.h.in"
# include "kwsys_ios_fstream.h.in"
# include "kwsys_ios_iostream.h.in"
#endif
#include <string.h> /* strlen */
int testIOS(int, char*[])
{
kwsys_ios::ostringstream ostr;
const char hello[] = "hello";
ostr << hello;
if(ostr.str() != hello)
{
kwsys_ios::cerr << "failed to write hello to ostr" << kwsys_ios::endl;
return 1;
}
const char world[] = "world";
kwsys_ios::ostringstream ostr2;
ostr2.write( hello, strlen(hello) ); /* I could do sizeof */
ostr2.put( '\0' );
ostr2.write( world, strlen(world) );
if(ostr2.str().size() != strlen(hello) + 1 + strlen(world) )
{
kwsys_ios::cerr << "failed to write hello to ostr2" << kwsys_ios::endl;
return 1;
}
static const unsigned char array[] = { 0xff,0x4f,0xff,0x51,0x00,0x29,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x3e,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x07,0x01,0x01,0xff,0x52,0x00,0x0c,0x00,0x00,0x00,0x01,0x00,0x05,0x04,0x04,0x00,0x01,0xff,0x5c,0x00,0x13,0x40,0x40,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0x48,0x48,0x50,0xff,0x64,0x00,0x2c,0x00,0x00,0x43,0x72,0x65,0x61,0x74,0x65,0x64,0x20,0x62,0x79,0x20,0x49,0x54,0x4b,0x2f,0x47,0x44,0x43,0x4d,0x2f,0x4f,0x70,0x65,0x6e,0x4a,0x50,0x45,0x47,0x20,0x76,0x65,0x72,0x73,0x69,0x6f,0x6e,0x20,0x31,0x2e,0x30,0xff,0x90,0x00,0x0a,0x00,0x00,0x00,0x00,0x06,0x2c,0x00,0x01,0xff,0x93,0xcf,0xb0,0x18,0x08,0x7f,0xc6,0x99,0xbf,0xff,0xc0,0xf8,0xc1,0xc1,0xf3,0x05,0x81,0xf2,0x83,0x0a,0xa5,0xff,0x10,0x90,0xbf,0x2f,0xff,0x04,0xa8,0x7f,0xc0,0xf8,0xc4,0xc1,0xf3,0x09,0x81,0xf3,0x0c,0x19,0x34 };
const unsigned int narray = sizeof(array); // 180
kwsys_ios::stringstream strstr;
strstr.write( (char*)array, narray );
//strstr.seekp( narray / 2 ); // set position of put pointer in mid string
if(strstr.str().size() != narray )
{
kwsys_ios::cerr << "failed to write array to strstr" << kwsys_ios::endl;
return 1;
}
kwsys_ios::istringstream istr(" 10 20 str ");
kwsys_stl::string s;
int x;
if(istr >> x)
{
if(x != 10)
{
kwsys_ios::cerr << "x != 10" << kwsys_ios::endl;
return 1;
}
}
else
{
kwsys_ios::cerr << "Failed to read 10 from istr" << kwsys_ios::endl;
return 1;
}
if(istr >> x)
{
if(x != 20)
{
kwsys_ios::cerr << "x != 20" << kwsys_ios::endl;
return 1;
}
}
else
{
kwsys_ios::cerr << "Failed to read 20 from istr" << kwsys_ios::endl;
return 1;
}
if(istr >> s)
{
if(s != "str")
{
kwsys_ios::cerr << "s != \"str\"" << kwsys_ios::endl;
return 1;
}
}
else
{
kwsys_ios::cerr << "Failed to read str from istr" << kwsys_ios::endl;
return 1;
}
if(istr >> s)
{
kwsys_ios::cerr << "Able to read past end of stream" << kwsys_ios::endl;
return 1;
}
else
{
// Clear the failure.
istr.clear(istr.rdstate() & ~kwsys_ios::ios::eofbit);
istr.clear(istr.rdstate() & ~kwsys_ios::ios::failbit);
}
istr.str("30");
if(istr >> x)
{
if(x != 30)
{
kwsys_ios::cerr << "x != 30" << kwsys_ios::endl;
return 1;
}
}
else
{
kwsys_ios::cerr << "Failed to read 30 from istr" << kwsys_ios::endl;
return 1;
}
kwsys_ios::stringstream sstr;
sstr << "40 str2";
if(sstr >> x)
{
if(x != 40)
{
kwsys_ios::cerr << "x != 40" << kwsys_ios::endl;
return 1;
}
}
else
{
kwsys_ios::cerr << "Failed to read 40 from sstr" << kwsys_ios::endl;
return 1;
}
if(sstr >> s)
{
if(s != "str2")
{
kwsys_ios::cerr << "s != \"str2\"" << kwsys_ios::endl;
return 1;
}
}
else
{
kwsys_ios::cerr << "Failed to read str2 from sstr" << kwsys_ios::endl;
return 1;
}
// Just try to compile this.
if(x == 12345)
{
kwsys_ios::ifstream fin("/does_not_exist",
kwsys_ios::ios::in | kwsys_ios_binary);
}
kwsys_ios::cout << "IOS tests passed" << kwsys_ios::endl;
return 0;
}

526
testProcess.c Normal file
View File

@ -0,0 +1,526 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Process.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "Process.h.in"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#if defined(_WIN32)
# include <windows.h>
#else
# include <unistd.h>
#endif
#if defined(__BORLANDC__)
# pragma warn -8060 /* possibly incorrect assignment */
#endif
#if defined(__BEOS__) && !defined(__ZETA__) && !defined(__HAIKU__)
/* BeOS 5 doesn't have usleep(), but it has snooze(), which is identical. */
# include <be/kernel/OS.h>
static inline void testProcess_usleep(unsigned int msec)
{
snooze(msec);
}
#else
# define testProcess_usleep usleep
#endif
int runChild(const char* cmd[], int state, int exception, int value,
int share, int output, int delay, double timeout, int poll,
int repeat, int disown);
int test1(int argc, const char* argv[])
{
(void)argc; (void)argv;
fprintf(stdout, "Output on stdout from test returning 0.\n");
fprintf(stderr, "Output on stderr from test returning 0.\n");
return 0;
}
int test2(int argc, const char* argv[])
{
(void)argc; (void)argv;
fprintf(stdout, "Output on stdout from test returning 123.\n");
fprintf(stderr, "Output on stderr from test returning 123.\n");
return 123;
}
int test3(int argc, const char* argv[])
{
(void)argc; (void)argv;
fprintf(stdout, "Output before sleep on stdout from timeout test.\n");
fprintf(stderr, "Output before sleep on stderr from timeout test.\n");
fflush(stdout);
fflush(stderr);
#if defined(_WIN32)
Sleep(15000);
#else
sleep(15);
#endif
fprintf(stdout, "Output after sleep on stdout from timeout test.\n");
fprintf(stderr, "Output after sleep on stderr from timeout test.\n");
return 0;
}
int test4(int argc, const char* argv[])
{
#if defined(_WIN32)
/* Avoid error diagnostic popups since we are crashing on purpose. */
SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX);
#elif defined(__BEOS__) || defined(__HAIKU__)
/* Avoid error diagnostic popups since we are crashing on purpose. */
disable_debugger(1);
#endif
(void)argc; (void)argv;
fprintf(stdout, "Output before crash on stdout from crash test.\n");
fprintf(stderr, "Output before crash on stderr from crash test.\n");
fflush(stdout);
fflush(stderr);
#if defined(__clang__)
*(int*)1 = 0; /* Clang warns about 0-ptr; undefined behavior. */
#else
*(int*)0 = 0;
#endif
fprintf(stdout, "Output after crash on stdout from crash test.\n");
fprintf(stderr, "Output after crash on stderr from crash test.\n");
return 0;
}
int test5(int argc, const char* argv[])
{
int r;
const char* cmd[4];
(void)argc;
cmd[0] = argv[0];
cmd[1] = "run";
cmd[2] = "4";
cmd[3] = 0;
fprintf(stdout, "Output on stdout before recursive test.\n");
fprintf(stderr, "Output on stderr before recursive test.\n");
fflush(stdout);
fflush(stderr);
r = runChild(cmd, kwsysProcess_State_Exception,
kwsysProcess_Exception_Fault, 1, 1, 1, 0, 15, 0, 1, 0);
fprintf(stdout, "Output on stdout after recursive test.\n");
fprintf(stderr, "Output on stderr after recursive test.\n");
fflush(stdout);
fflush(stderr);
return r;
}
#define TEST6_SIZE (4096*2)
void test6(int argc, const char* argv[])
{
int i;
char runaway[TEST6_SIZE+1];
(void)argc; (void)argv;
for(i=0;i < TEST6_SIZE;++i)
{
runaway[i] = '.';
}
runaway[TEST6_SIZE] = '\n';
/* Generate huge amounts of output to test killing. */
for(;;)
{
fwrite(runaway, 1, TEST6_SIZE+1, stdout);
fflush(stdout);
}
}
/* Define MINPOLL to be one more than the number of times output is
written. Define MAXPOLL to be the largest number of times a loop
delaying 1/10th of a second should ever have to poll. */
#define MINPOLL 5
#define MAXPOLL 20
int test7(int argc, const char* argv[])
{
(void)argc; (void)argv;
fprintf(stdout, "Output on stdout before sleep.\n");
fprintf(stderr, "Output on stderr before sleep.\n");
fflush(stdout);
fflush(stderr);
/* Sleep for 1 second. */
#if defined(_WIN32)
Sleep(1000);
#else
sleep(1);
#endif
fprintf(stdout, "Output on stdout after sleep.\n");
fprintf(stderr, "Output on stderr after sleep.\n");
fflush(stdout);
fflush(stderr);
return 0;
}
int test8(int argc, const char* argv[])
{
/* Create a disowned grandchild to test handling of processes
that exit before their children. */
int r;
const char* cmd[4];
(void)argc;
cmd[0] = argv[0];
cmd[1] = "run";
cmd[2] = "108";
cmd[3] = 0;
fprintf(stdout, "Output on stdout before grandchild test.\n");
fprintf(stderr, "Output on stderr before grandchild test.\n");
fflush(stdout);
fflush(stderr);
r = runChild(cmd, kwsysProcess_State_Disowned, kwsysProcess_Exception_None,
1, 1, 1, 0, 10, 0, 1, 1);
fprintf(stdout, "Output on stdout after grandchild test.\n");
fprintf(stderr, "Output on stderr after grandchild test.\n");
fflush(stdout);
fflush(stderr);
return r;
}
int test8_grandchild(int argc, const char* argv[])
{
(void)argc; (void)argv;
fprintf(stdout, "Output on stdout from grandchild before sleep.\n");
fprintf(stderr, "Output on stderr from grandchild before sleep.\n");
fflush(stdout);
fflush(stderr);
/* TODO: Instead of closing pipes here leave them open to make sure
the grandparent can stop listening when the parent exits. This
part of the test cannot be enabled until the feature is
implemented. */
fclose(stdout);
fclose(stderr);
#if defined(_WIN32)
Sleep(15000);
#else
sleep(15);
#endif
return 0;
}
int runChild2(kwsysProcess* kp,
const char* cmd[], int state, int exception, int value,
int share, int output, int delay, double timeout,
int poll, int disown)
{
int result = 0;
char* data = 0;
int length = 0;
double userTimeout = 0;
double* pUserTimeout = 0;
kwsysProcess_SetCommand(kp, cmd);
if(timeout >= 0)
{
kwsysProcess_SetTimeout(kp, timeout);
}
if(share)
{
kwsysProcess_SetPipeShared(kp, kwsysProcess_Pipe_STDOUT, 1);
kwsysProcess_SetPipeShared(kp, kwsysProcess_Pipe_STDERR, 1);
}
if(disown)
{
kwsysProcess_SetOption(kp, kwsysProcess_Option_Detach, 1);
}
kwsysProcess_Execute(kp);
if(poll)
{
pUserTimeout = &userTimeout;
}
if(!share && !disown)
{
int p;
while((p = kwsysProcess_WaitForData(kp, &data, &length, pUserTimeout)))
{
if(output)
{
if(poll && p == kwsysProcess_Pipe_Timeout)
{
fprintf(stdout, "WaitForData timeout reached.\n");
fflush(stdout);
/* Count the number of times we polled without getting data.
If it is excessive then kill the child and fail. */
if(++poll >= MAXPOLL)
{
fprintf(stdout, "Poll count reached limit %d.\n",
MAXPOLL);
kwsysProcess_Kill(kp);
}
}
else
{
fwrite(data, 1, (size_t) length, stdout);
fflush(stdout);
}
}
if(poll)
{
/* Delay to avoid busy loop during polling. */
#if defined(_WIN32)
Sleep(100);
#else
testProcess_usleep(100000);
#endif
}
if(delay)
{
/* Purposely sleeping only on Win32 to let pipe fill up. */
#if defined(_WIN32)
Sleep(100);
#endif
}
}
}
if(disown)
{
kwsysProcess_Disown(kp);
}
else
{
kwsysProcess_WaitForExit(kp, 0);
}
switch (kwsysProcess_GetState(kp))
{
case kwsysProcess_State_Starting:
printf("No process has been executed.\n"); break;
case kwsysProcess_State_Executing:
printf("The process is still executing.\n"); break;
case kwsysProcess_State_Expired:
printf("Child was killed when timeout expired.\n"); break;
case kwsysProcess_State_Exited:
printf("Child exited with value = %d\n",
kwsysProcess_GetExitValue(kp));
result = ((exception != kwsysProcess_GetExitException(kp)) ||
(value != kwsysProcess_GetExitValue(kp))); break;
case kwsysProcess_State_Killed:
printf("Child was killed by parent.\n"); break;
case kwsysProcess_State_Exception:
printf("Child terminated abnormally: %s\n",
kwsysProcess_GetExceptionString(kp));
result = ((exception != kwsysProcess_GetExitException(kp)) ||
(value != kwsysProcess_GetExitValue(kp))); break;
case kwsysProcess_State_Disowned:
printf("Child was disowned.\n"); break;
case kwsysProcess_State_Error:
printf("Error in administrating child process: [%s]\n",
kwsysProcess_GetErrorString(kp)); break;
};
if(result)
{
if(exception != kwsysProcess_GetExitException(kp))
{
fprintf(stderr, "Mismatch in exit exception. "
"Should have been %d, was %d.\n",
exception, kwsysProcess_GetExitException(kp));
}
if(value != kwsysProcess_GetExitValue(kp))
{
fprintf(stderr, "Mismatch in exit value. "
"Should have been %d, was %d.\n",
value, kwsysProcess_GetExitValue(kp));
}
}
if(kwsysProcess_GetState(kp) != state)
{
fprintf(stderr, "Mismatch in state. "
"Should have been %d, was %d.\n",
state, kwsysProcess_GetState(kp));
result = 1;
}
/* We should have polled more times than there were data if polling
was enabled. */
if(poll && poll < MINPOLL)
{
fprintf(stderr, "Poll count is %d, which is less than %d.\n",
poll, MINPOLL);
result = 1;
}
return result;
}
int runChild(const char* cmd[], int state, int exception, int value,
int share, int output, int delay, double timeout,
int poll, int repeat, int disown)
{
int result = 1;
kwsysProcess* kp = kwsysProcess_New();
if(!kp)
{
fprintf(stderr, "kwsysProcess_New returned NULL!\n");
return 1;
}
while(repeat-- > 0)
{
result = runChild2(kp, cmd, state, exception, value, share,
output, delay, timeout, poll, disown);
}
kwsysProcess_Delete(kp);
return result;
}
int main(int argc, const char* argv[])
{
int n = 0;
#if 0
{
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
DuplicateHandle(GetCurrentProcess(), out,
GetCurrentProcess(), &out, 0, FALSE,
DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
SetStdHandle(STD_OUTPUT_HANDLE, out);
}
{
HANDLE out = GetStdHandle(STD_ERROR_HANDLE);
DuplicateHandle(GetCurrentProcess(), out,
GetCurrentProcess(), &out, 0, FALSE,
DUPLICATE_SAME_ACCESS | DUPLICATE_CLOSE_SOURCE);
SetStdHandle(STD_ERROR_HANDLE, out);
}
#endif
if(argc == 2)
{
n = atoi(argv[1]);
}
else if(argc == 3 && strcmp(argv[1], "run") == 0)
{
n = atoi(argv[2]);
}
/* Check arguments. */
if(((n >= 1 && n <= 8) || n == 108) && argc == 3)
{
/* This is the child process for a requested test number. */
switch (n)
{
case 1: return test1(argc, argv);
case 2: return test2(argc, argv);
case 3: return test3(argc, argv);
case 4: return test4(argc, argv);
case 5: return test5(argc, argv);
case 6: test6(argc, argv); return 0;
case 7: return test7(argc, argv);
case 8: return test8(argc, argv);
case 108: return test8_grandchild(argc, argv);
}
fprintf(stderr, "Invalid test number %d.\n", n);
return 1;
}
else if(n >= 1 && n <= 8)
{
/* This is the parent process for a requested test number. */
int states[8] =
{
kwsysProcess_State_Exited,
kwsysProcess_State_Exited,
kwsysProcess_State_Expired,
kwsysProcess_State_Exception,
kwsysProcess_State_Exited,
kwsysProcess_State_Expired,
kwsysProcess_State_Exited,
kwsysProcess_State_Exited
};
int exceptions[8] =
{
kwsysProcess_Exception_None,
kwsysProcess_Exception_None,
kwsysProcess_Exception_None,
kwsysProcess_Exception_Fault,
kwsysProcess_Exception_None,
kwsysProcess_Exception_None,
kwsysProcess_Exception_None,
kwsysProcess_Exception_None
};
int values[8] = {0, 123, 1, 1, 0, 0, 0, 0};
int outputs[8] = {1, 1, 1, 1, 1, 0, 1, 1};
int delays[8] = {0, 0, 0, 0, 0, 1, 0, 0};
double timeouts[8] = {10, 10, 10, 30, 30, 10, -1, 10};
int polls[8] = {0, 0, 0, 0, 0, 0, 1, 0};
int repeat[8] = {2, 1, 1, 1, 1, 1, 1, 1};
int r;
const char* cmd[4];
#ifdef _WIN32
char* argv0 = 0;
if(n == 0 && (argv0 = strdup(argv[0])))
{
/* Try converting to forward slashes to see if it works. */
char* c;
for(c=argv0; *c; ++c)
{
if(*c == '\\')
{
*c = '/';
}
}
cmd[0] = argv0;
}
else
{
cmd[0] = argv[0];
}
#else
cmd[0] = argv[0];
#endif
cmd[1] = "run";
cmd[2] = argv[1];
cmd[3] = 0;
fprintf(stdout, "Output on stdout before test %d.\n", n);
fprintf(stderr, "Output on stderr before test %d.\n", n);
fflush(stdout);
fflush(stderr);
r = runChild(cmd, states[n-1], exceptions[n-1], values[n-1], 0,
outputs[n-1], delays[n-1], timeouts[n-1],
polls[n-1], repeat[n-1], 0);
fprintf(stdout, "Output on stdout after test %d.\n", n);
fprintf(stderr, "Output on stderr after test %d.\n", n);
fflush(stdout);
fflush(stderr);
#if _WIN32
if(argv0) { free(argv0); }
#endif
return r;
}
else if(argc > 2 && strcmp(argv[1], "0") == 0)
{
/* This is the special debugging test to run a given command
line. */
const char** cmd = argv+2;
int state = kwsysProcess_State_Exited;
int exception = kwsysProcess_Exception_None;
int value = 0;
double timeout = 0;
int r = runChild(cmd, state, exception, value, 0, 1, 0, timeout, 0, 1, 0);
return r;
}
else
{
/* Improper usage. */
fprintf(stdout, "Usage: %s <test number>\n", argv[0]);
return 1;
}
}

109
testRegistry.cxx Normal file
View File

@ -0,0 +1,109 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Registry.hxx)
#include KWSYS_HEADER(ios/iostream)
#include <string.h>
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "Registry.hxx.in"
# include "kwsys_ios_iostream.h.in"
#endif
#define IFT(x,res) if ( !x ) \
{ \
res = 1; \
kwsys_ios::cout << "Error in: " << #x << kwsys_ios::endl; \
}
#define IFNT(x,res) if ( x ) \
{ \
res = 1; \
kwsys_ios::cout << "Error in: " << #x << kwsys_ios::endl; \
}
#define CHE(x,y,res) if ( x && strcmp(x,y) ) \
{ \
res = 1; \
kwsys_ios::cout << "Error, " << x << " != " << y << kwsys_ios::endl; \
}
int testRegistry(int, char*[])
{
int res = 0;
kwsys::Registry reg;
reg.SetTopLevel("TestRegistry");
IFT(reg.SetValue("TestSubkey", "TestKey1", "Test Value 1"), res);
IFT(reg.SetValue("TestSubkey1", "TestKey2", "Test Value 2"), res);
IFT(reg.SetValue("TestSubkey", "TestKey3", "Test Value 3"), res);
IFT(reg.SetValue("TestSubkey2", "TestKey4", "Test Value 4"), res);
const char *buffer;
IFT(reg.ReadValue("TestSubkey", "TestKey1", &buffer), res);
CHE(buffer, "Test Value 1", res);
IFT(reg.ReadValue("TestSubkey1", "TestKey2", &buffer), res);
CHE(buffer, "Test Value 2", res);
IFT(reg.ReadValue("TestSubkey", "TestKey3", &buffer), res);
CHE(buffer, "Test Value 3", res);
IFT(reg.ReadValue("TestSubkey2", "TestKey4", &buffer), res);
CHE(buffer, "Test Value 4", res);
IFT(reg.SetValue("TestSubkey", "TestKey1", "New Test Value 1"), res);
IFT(reg.SetValue("TestSubkey1", "TestKey2", "New Test Value 2"), res);
IFT(reg.SetValue("TestSubkey", "TestKey3", "New Test Value 3"), res);
IFT(reg.SetValue("TestSubkey2", "TestKey4", "New Test Value 4"), res);
IFT(reg.ReadValue("TestSubkey", "TestKey1", &buffer), res);
CHE(buffer, "New Test Value 1", res);
IFT(reg.ReadValue("TestSubkey1", "TestKey2", &buffer), res);
CHE(buffer, "New Test Value 2", res);
IFT(reg.ReadValue("TestSubkey", "TestKey3", &buffer), res);
CHE(buffer, "New Test Value 3", res);
IFT(reg.ReadValue("TestSubkey2", "TestKey4", &buffer), res);
CHE(buffer, "New Test Value 4", res);
IFT( reg.DeleteValue("TestSubkey", "TestKey1"), res);
IFNT(reg.ReadValue( "TestSubkey", "TestKey1", &buffer), res);
IFT( reg.DeleteValue("TestSubkey1", "TestKey2"), res);
IFNT(reg.ReadValue( "TestSubkey1", "TestKey2", &buffer), res);
IFT( reg.DeleteValue("TestSubkey", "TestKey3"), res);
IFNT(reg.ReadValue( "TestSubkey", "TestKey3", &buffer), res);
IFT( reg.DeleteValue("TestSubkey2", "TestKey4"), res);
IFNT(reg.ReadValue( "TestSubkey2", "TestKey5", &buffer), res);
const char* longStringWithNewLines = "Value with embedded CR and LF characters CR='\015' LF='\012' CRLF='\015\012'";
IFT(reg.SetValue("TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName", "TestKey1", longStringWithNewLines), res);
IFT(reg.ReadValue("TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName", "TestKey1", &buffer), res);
CHE(buffer, longStringWithNewLines, res);
IFT(reg.DeleteValue("TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName", "TestKey1"), res);
IFNT(reg.ReadValue("TestSubkeyWithVeryLongInFactSoLongItsHardToImagineAnybodyWouldReallyDoItLongName", "TestKey1", &buffer), res);
IFT(reg.SetValue("TestSubkeyWith = EqualSignChar", "TestKey = 1", "Some value"), res);
IFT(reg.ReadValue("TestSubkeyWith = EqualSignChar", "TestKey = 1", &buffer), res);
CHE(buffer, "Some value", res);
IFT(reg.DeleteValue("TestSubkeyWith = EqualSignChar", "TestKey = 1"), res);
IFNT(reg.ReadValue("TestSubkeyWith = EqualSignChar", "TestKey = 1", &buffer), res);
if ( res )
{
kwsys_ios::cout << "Test failed" << kwsys_ios::endl;
}
else
{
kwsys_ios::cout << "Test passed" << kwsys_ios::endl;
}
return res;
}

36
testSharedForward.c.in Normal file
View File

@ -0,0 +1,36 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#if defined(CMAKE_INTDIR)
# define CONFIG_DIR_PRE CMAKE_INTDIR "/"
# define CONFIG_DIR_POST "/" CMAKE_INTDIR
#else
# define CONFIG_DIR_PRE ""
# define CONFIG_DIR_POST ""
#endif
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_DIR_BUILD "@EXEC_DIR@"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_BUILD "." CONFIG_DIR_POST
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_PATH_INSTALL 0
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_BUILD \
CONFIG_DIR_PRE "@KWSYS_NAMESPACE@TestProcess"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_EXE_INSTALL \
"@KWSYS_NAMESPACE@TestProcess"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_COMMAND "--command"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_PRINT "--print"
#define @KWSYS_NAMESPACE@_SHARED_FORWARD_OPTION_LDD "--ldd"
#if defined(CMAKE_INTDIR)
# define @KWSYS_NAMESPACE@_SHARED_FORWARD_CONFIG_NAME CMAKE_INTDIR
#endif
#include <@KWSYS_NAMESPACE@/SharedForward.h>
int main(int argc, char** argv)
{
return @KWSYS_NAMESPACE@_shared_forward_to_real(argc, argv);
}

65
testSystemInformation.cxx Normal file
View File

@ -0,0 +1,65 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(SystemInformation.hxx)
#include KWSYS_HEADER(ios/iostream)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "SystemInformation.hxx.in"
# include "kwsys_ios_iostream.h.in"
#endif
#define printMethod(inof, m) kwsys_ios::cout << #m << ": " \
<< info.m() << "\n"
#define printMethod2(inof, m, unit) kwsys_ios::cout << #m << ": " \
<< info.m() << " " << unit << "\n"
int testSystemInformation(int, char*[])
{
kwsys::SystemInformation info;
info.RunCPUCheck();
info.RunOSCheck();
info.RunMemoryCheck();
printMethod(info, GetOSName);
printMethod(info, GetHostname);
printMethod(info, GetOSRelease);
printMethod(info, GetOSVersion);
printMethod(info, GetOSPlatform);
printMethod(info, GetVendorString);
printMethod(info, GetVendorID);
printMethod(info, GetTypeID);
printMethod(info, GetFamilyID);
printMethod(info, GetModelID);
printMethod(info, GetExtendedProcessorName);
printMethod(info, GetProcessorSerialNumber);
printMethod2(info, GetProcessorCacheSize, "KB");
printMethod(info, GetLogicalProcessorsPerPhysical);
printMethod2(info, GetProcessorClockFrequency, "MHz");
printMethod(info, Is64Bits);
printMethod(info, GetNumberOfLogicalCPU);
printMethod(info, GetNumberOfPhysicalCPU);
printMethod(info, DoesCPUSupportCPUID);
printMethod(info, GetProcessorAPICID);
printMethod2(info, GetTotalVirtualMemory, "MB");
printMethod2(info, GetAvailableVirtualMemory, "MB");
printMethod2(info, GetTotalPhysicalMemory, "MB");
printMethod2(info, GetAvailablePhysicalMemory, "MB");
//int GetProcessorCacheXSize(long int);
// bool DoesCPUSupportFeature(long int);
return 0;
}

BIN
testSystemTools.bin Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 766 B

414
testSystemTools.cxx Normal file
View File

@ -0,0 +1,414 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#if defined(_MSC_VER)
# pragma warning (disable:4786)
#endif
#include KWSYS_HEADER(SystemTools.hxx)
#include KWSYS_HEADER(ios/iostream)
// Work-around CMake dependency scanning limitation. This must
// duplicate the above list of headers.
#if 0
# include "SystemTools.hxx.in"
# include "kwsys_ios_iostream.h.in"
#endif
// Include with <> instead of "" to avoid getting any in-source copy
// left on disk.
#include <testSystemTools.h>
#include <string.h> /* strcmp */
//----------------------------------------------------------------------------
const char* toUnixPaths[][2] =
{
{ "/usr/local/bin/passwd", "/usr/local/bin/passwd" },
{ "/usr/lo cal/bin/pa sswd", "/usr/lo cal/bin/pa sswd" },
{ "/usr/lo\\ cal/bin/pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
{ "c:/usr/local/bin/passwd", "c:/usr/local/bin/passwd" },
{ "c:/usr/lo cal/bin/pa sswd", "c:/usr/lo cal/bin/pa sswd" },
{ "c:/usr/lo\\ cal/bin/pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
{ "\\usr\\local\\bin\\passwd", "/usr/local/bin/passwd" },
{ "\\usr\\lo cal\\bin\\pa sswd", "/usr/lo cal/bin/pa sswd" },
{ "\\usr\\lo\\ cal\\bin\\pa\\ sswd", "/usr/lo\\ cal/bin/pa\\ sswd" },
{ "c:\\usr\\local\\bin\\passwd", "c:/usr/local/bin/passwd" },
{ "c:\\usr\\lo cal\\bin\\pa sswd", "c:/usr/lo cal/bin/pa sswd" },
{ "c:\\usr\\lo\\ cal\\bin\\pa\\ sswd", "c:/usr/lo\\ cal/bin/pa\\ sswd" },
{ "\\\\usr\\local\\bin\\passwd", "//usr/local/bin/passwd" },
{ "\\\\usr\\lo cal\\bin\\pa sswd", "//usr/lo cal/bin/pa sswd" },
{ "\\\\usr\\lo\\ cal\\bin\\pa\\ sswd", "//usr/lo\\ cal/bin/pa\\ sswd" },
{0, 0}
};
bool CheckConvertToUnixSlashes(kwsys_stl::string input,
kwsys_stl::string output)
{
kwsys_stl::string result = input;
kwsys::SystemTools::ConvertToUnixSlashes(result);
if ( result != output )
{
kwsys_ios::cerr
<< "Problem with ConvertToUnixSlashes - input: " << input.c_str()
<< " output: " << result.c_str() << " expected: " << output.c_str()
<< kwsys_ios::endl;
return false;
}
return true;
}
//----------------------------------------------------------------------------
const char* checkEscapeChars[][4] =
{
{ "1 foo 2 bar 2", "12", "\\", "\\1 foo \\2 bar \\2"},
{ " {} ", "{}", "#", " #{#} "},
{0, 0, 0, 0}
};
bool CheckEscapeChars(kwsys_stl::string input,
const char *chars_to_escape,
char escape_char,
kwsys_stl::string output)
{
kwsys_stl::string result = kwsys::SystemTools::EscapeChars(
input.c_str(), chars_to_escape, escape_char);
if (result != output)
{
kwsys_ios::cerr
<< "Problem with CheckEscapeChars - input: " << input.c_str()
<< " output: " << result.c_str() << " expected: " << output.c_str()
<< kwsys_ios::endl;
return false;
}
return true;
}
//----------------------------------------------------------------------------
bool CheckFileOperations()
{
bool res = true;
if (kwsys::SystemTools::DetectFileType(TEST_SYSTEMTOOLS_BIN_FILE) !=
kwsys::SystemTools::FileTypeBinary)
{
kwsys_ios::cerr
<< "Problem with DetectFileType - failed to detect type of: "
<< TEST_SYSTEMTOOLS_BIN_FILE << kwsys_ios::endl;
res = false;
}
if (kwsys::SystemTools::DetectFileType(TEST_SYSTEMTOOLS_SRC_FILE) !=
kwsys::SystemTools::FileTypeText)
{
kwsys_ios::cerr
<< "Problem with DetectFileType - failed to detect type of: "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
if (kwsys::SystemTools::FileLength(TEST_SYSTEMTOOLS_BIN_FILE) != 766)
{
kwsys_ios::cerr
<< "Problem with FileLength - incorrect length for: "
<< TEST_SYSTEMTOOLS_BIN_FILE << kwsys_ios::endl;
res = false;
}
return res;
}
//----------------------------------------------------------------------------
bool CheckStringOperations()
{
bool res = true;
kwsys_stl::string test = "mary had a little lamb.";
if (kwsys::SystemTools::CapitalizedWords(test) != "Mary Had A Little Lamb.")
{
kwsys_ios::cerr
<< "Problem with CapitalizedWords "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
test = "Mary Had A Little Lamb.";
if (kwsys::SystemTools::UnCapitalizedWords(test) !=
"mary had a little lamb.")
{
kwsys_ios::cerr
<< "Problem with UnCapitalizedWords "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
test = "MaryHadTheLittleLamb.";
if (kwsys::SystemTools::AddSpaceBetweenCapitalizedWords(test) !=
"Mary Had The Little Lamb.")
{
kwsys_ios::cerr
<< "Problem with AddSpaceBetweenCapitalizedWords "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
char * cres =
kwsys::SystemTools::AppendStrings("Mary Had A"," Little Lamb.");
if (strcmp(cres,"Mary Had A Little Lamb."))
{
kwsys_ios::cerr
<< "Problem with AppendStrings "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
delete [] cres;
cres =
kwsys::SystemTools::AppendStrings("Mary Had"," A ","Little Lamb.");
if (strcmp(cres,"Mary Had A Little Lamb."))
{
kwsys_ios::cerr
<< "Problem with AppendStrings "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
delete [] cres;
if (kwsys::SystemTools::CountChar("Mary Had A Little Lamb.",'a') != 3)
{
kwsys_ios::cerr
<< "Problem with CountChar "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
cres =
kwsys::SystemTools::RemoveChars("Mary Had A Little Lamb.","aeiou");
if (strcmp(cres,"Mry Hd A Lttl Lmb."))
{
kwsys_ios::cerr
<< "Problem with RemoveChars "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
delete [] cres;
cres =
kwsys::SystemTools::RemoveCharsButUpperHex("Mary Had A Little Lamb.");
if (strcmp(cres,"A"))
{
kwsys_ios::cerr
<< "Problem with RemoveCharsButUpperHex "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
delete [] cres;
char *cres2 = new char [strlen("Mary Had A Little Lamb.")+1];
strcpy(cres2,"Mary Had A Little Lamb.");
kwsys::SystemTools::ReplaceChars(cres2,"aeiou",'X');
if (strcmp(cres2,"MXry HXd A LXttlX LXmb."))
{
kwsys_ios::cerr
<< "Problem with ReplaceChars "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
delete [] cres2;
if (!kwsys::SystemTools::StringStartsWith("Mary Had A Little Lamb.",
"Mary "))
{
kwsys_ios::cerr
<< "Problem with StringStartsWith "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
if (!kwsys::SystemTools::StringEndsWith("Mary Had A Little Lamb.",
" Lamb."))
{
kwsys_ios::cerr
<< "Problem with StringEndsWith "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
cres = kwsys::SystemTools::DuplicateString("Mary Had A Little Lamb.");
if (strcmp(cres,"Mary Had A Little Lamb."))
{
kwsys_ios::cerr
<< "Problem with DuplicateString "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
delete [] cres;
test = "Mary Had A Little Lamb.";
if (kwsys::SystemTools::CropString(test,13) !=
"Mary ...Lamb.")
{
kwsys_ios::cerr
<< "Problem with CropString "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
kwsys_stl::vector<kwsys_stl::string> lines;
kwsys::SystemTools::Split("Mary Had A Little Lamb.",lines,' ');
if (lines[0] != "Mary" || lines[1] != "Had" ||
lines[2] != "A" || lines[3] != "Little" || lines[4] != "Lamb.")
{
kwsys_ios::cerr
<< "Problem with Split "
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
if (kwsys::SystemTools::ConvertToWindowsOutputPath
("L://Local Mojo/Hex Power Pack/Iffy Voodoo") !=
"\"L:\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"")
{
kwsys_ios::cerr
<< "Problem with ConvertToWindowsOutputPath "
<< kwsys_ios::endl;
res = false;
}
if (kwsys::SystemTools::ConvertToWindowsOutputPath
("//grayson/Local Mojo/Hex Power Pack/Iffy Voodoo") !=
"\"\\\\grayson\\Local Mojo\\Hex Power Pack\\Iffy Voodoo\"")
{
kwsys_ios::cerr
<< "Problem with ConvertToWindowsOutputPath "
<< kwsys_ios::endl;
res = false;
}
if (kwsys::SystemTools::ConvertToUnixOutputPath
("//Local Mojo/Hex Power Pack/Iffy Voodoo") !=
"//Local\\ Mojo/Hex\\ Power\\ Pack/Iffy\\ Voodoo")
{
kwsys_ios::cerr
<< "Problem with ConvertToUnixOutputPath "
<< kwsys_ios::endl;
res = false;
}
int targc;
char **targv;
kwsys::SystemTools::ConvertWindowsCommandLineToUnixArguments
("\"Local Mojo\\Voodoo.asp\" -CastHex \"D:\\My Secret Mojo\\Voodoo.mp3\"", &targc, &targv);
if (targc != 4 || strcmp(targv[1],"Local Mojo\\Voodoo.asp") ||
strcmp(targv[2],"-CastHex") ||
strcmp(targv[3],"D:\\My Secret Mojo\\Voodoo.mp3"))
{
kwsys_ios::cerr
<< "Problem with ConvertWindowsCommandLineToUnixArguments"
<< TEST_SYSTEMTOOLS_SRC_FILE << kwsys_ios::endl;
res = false;
}
for (;targc >=0; --targc)
{
delete [] targv[targc];
}
delete [] targv;
return res;
}
//----------------------------------------------------------------------------
bool CheckPutEnv(const char* env, const char* name, const char* value)
{
if(!kwsys::SystemTools::PutEnv(env))
{
kwsys_ios::cerr << "PutEnv(\"" << env
<< "\") failed!" << kwsys_ios::endl;
return false;
}
const char* v = kwsys::SystemTools::GetEnv(name);
v = v? v : "(null)";
if(strcmp(v, value) != 0)
{
kwsys_ios::cerr << "GetEnv(\"" << name << "\") returned \""
<< v << "\", not \"" << value << "\"!" << kwsys_ios::endl;
return false;
}
return true;
}
bool CheckUnPutEnv(const char* env, const char* name)
{
if(!kwsys::SystemTools::UnPutEnv(env))
{
kwsys_ios::cerr << "UnPutEnv(\"" << env << "\") failed!"
<< kwsys_ios::endl;
return false;
}
if(const char* v = kwsys::SystemTools::GetEnv(name))
{
kwsys_ios::cerr << "GetEnv(\"" << name << "\") returned \""
<< v << "\", not (null)!" << kwsys_ios::endl;
return false;
}
return true;
}
bool CheckEnvironmentOperations()
{
bool res = true;
res &= CheckPutEnv("A=B", "A", "B");
res &= CheckPutEnv("B=C", "B", "C");
res &= CheckPutEnv("C=D", "C", "D");
res &= CheckPutEnv("D=E", "D", "E");
res &= CheckUnPutEnv("A", "A");
res &= CheckUnPutEnv("B=", "B");
res &= CheckUnPutEnv("C=D", "C");
/* Leave "D=E" in environment so a memory checker can test for leaks. */
return res;
}
//----------------------------------------------------------------------------
int testSystemTools(int, char*[])
{
bool res = true;
int cc;
for ( cc = 0; toUnixPaths[cc][0]; cc ++ )
{
res &= CheckConvertToUnixSlashes(toUnixPaths[cc][0], toUnixPaths[cc][1]);
}
// Special check for ~
kwsys_stl::string output;
if(kwsys::SystemTools::GetEnv("HOME", output))
{
output += "/foo bar/lala";
res &= CheckConvertToUnixSlashes("~/foo bar/lala", output);
}
for (cc = 0; checkEscapeChars[cc][0]; cc ++ )
{
res &= CheckEscapeChars(checkEscapeChars[cc][0], checkEscapeChars[cc][1],
*checkEscapeChars[cc][2], checkEscapeChars[cc][3]);
}
res &= CheckFileOperations();
res &= CheckStringOperations();
res &= CheckEnvironmentOperations();
return res ? 0 : 1;
}

20
testSystemTools.h.in Normal file
View File

@ -0,0 +1,20 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#ifndef @KWSYS_NAMESPACE@_testSystemtools_h
#define @KWSYS_NAMESPACE@_testSystemtools_h
#define EXECUTABLE_OUTPUT_PATH "@CMAKE_CURRENT_BINARY_DIR@"
#define TEST_SYSTEMTOOLS_BIN_FILE "@TEST_SYSTEMTOOLS_BIN_FILE@"
#define TEST_SYSTEMTOOLS_SRC_FILE "@TEST_SYSTEMTOOLS_SRC_FILE@"
#endif

31
testTerminal.c Normal file
View File

@ -0,0 +1,31 @@
/*============================================================================
KWSys - Kitware System Library
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "kwsysPrivate.h"
#include KWSYS_HEADER(Terminal.h)
/* Work-around CMake dependency scanning limitation. This must
duplicate the above list of headers. */
#if 0
# include "Terminal.h.in"
#endif
int testTerminal(int argc, char* argv[])
{
(void)argc;
(void)argv;
kwsysTerminal_cfprintf(kwsysTerminal_Color_ForegroundYellow |
kwsysTerminal_Color_BackgroundBlue |
kwsysTerminal_Color_AssumeTTY,
stdout, "Hello %s!", "World");
fprintf(stdout, "\n");
return 0;
}