| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319 | /*=========================================================================  Program:   CMake - Cross-Platform Makefile Generator  Module:    $RCSfile$  Language:  C++  Date:      $Date$  Version:   $Revision$  Copyright (c) 2002 Kitware, Inc., Insight Consortium.  All rights reserved.  See Copyright.txt or http://www.cmake.org/HTML/Copyright.html for details.     This software is distributed WITHOUT ANY WARRANTY; without even      the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR      PURPOSE.  See the above copyright notices for more information.=========================================================================*/#include "cmSystemTools.h"   #include <ctype.h>#include <errno.h>#include <time.h>#include <cmsys/RegularExpression.hxx>#include <cmsys/Directory.hxx>#include <cmsys/Process.h>// support for realpath call#ifndef _WIN32#include <limits.h>#include <stdlib.h>#include <sys/param.h>#include <sys/wait.h>#endif#if defined(_WIN32) && (defined(_MSC_VER) || defined(__BORLANDC__))#include <string.h>#include <windows.h>#include <direct.h>#include <io.h>#define _unlink unlink#else#include <sys/types.h>#include <fcntl.h>#include <unistd.h>#endif#include <sys/stat.h>bool cmSystemTools::s_RunCommandHideConsole = false;bool cmSystemTools::s_DisableRunCommandOutput = false;bool cmSystemTools::s_ErrorOccured = false;bool cmSystemTools::s_FatalErrorOccured = false;bool cmSystemTools::s_DisableMessages = false;bool cmSystemTools::s_ForceUnixPaths = false;std::string cmSystemTools::s_Windows9xComspecSubstitute = "command.com";void cmSystemTools::SetWindows9xComspecSubstitute(const char* str){  if ( str )    {    cmSystemTools::s_Windows9xComspecSubstitute = str;    }}const char* cmSystemTools::GetWindows9xComspecSubstitute(){  return cmSystemTools::s_Windows9xComspecSubstitute.c_str();}void (*cmSystemTools::s_ErrorCallback)(const char*, const char*, bool&, void*);void (*cmSystemTools::s_StdoutCallback)(const char*, int len, void*);void* cmSystemTools::s_ErrorCallbackClientData = 0;void* cmSystemTools::s_StdoutCallbackClientData = 0;// replace replace with with as many times as it shows up in source.// write the result into source.#if defined(_WIN32) && !defined(__CYGWIN__)void cmSystemTools::ExpandRegistryValues(std::string& source){  // Regular expression to match anything inside [...] that begins in HKEY.  // Note that there is a special rule for regular expressions to match a  // close square-bracket inside a list delimited by square brackets.  // The "[^]]" part of this expression will match any character except  // a close square-bracket.  The ']' character must be the first in the  // list of characters inside the [^...] block of the expression.  cmsys::RegularExpression regEntry("\\[(HKEY[^]]*)\\]");    // check for black line or comment  while (regEntry.find(source))    {    // the arguments are the second match    std::string key = regEntry.match(1);    std::string val;    if (ReadRegistryValue(key.c_str(), val))      {      std::string reg = "[";      reg += key + "]";      cmSystemTools::ReplaceString(source, reg.c_str(), val.c_str());      }    else      {      std::string reg = "[";      reg += key + "]";      cmSystemTools::ReplaceString(source, reg.c_str(), "/registry");      }    }}#elsevoid cmSystemTools::ExpandRegistryValues(std::string&){}#endifstd::string cmSystemTools::EscapeQuotes(const char* str){  std::string result = "";  for(const char* ch = str; *ch != '\0'; ++ch)    {    if(*ch == '"')      {      result += '\\';      }    result += *ch;    }  return result;}std::string cmSystemTools::EscapeSpaces(const char* str){#if defined(_WIN32) && !defined(__CYGWIN__)  bool useDoubleQ = true;#else  bool useDoubleQ = false;#endif  if(cmSystemTools::s_ForceUnixPaths)    {    useDoubleQ = false;    }    if(useDoubleQ)    {    std::string result;        // if there are spaces    std::string temp = str;    if (temp.find(" ") != std::string::npos &&         temp.find("\"")==std::string::npos)      {      result = "\"";      result += str;      result += "\"";      return result;      }    return str;    }  else    {    std::string result = "";    for(const char* ch = str; *ch != '\0'; ++ch)      {      if(*ch == ' ')        {        result += '\\';        }      result += *ch;      }    return result;    }}std::string cmSystemTools::RemoveEscapes(const char* s){  std::string result = "";  for(const char* ch = s; *ch; ++ch)    {    if(*ch == '\\' && *(ch+1) != ';')      {      ++ch;      switch (*ch)        {        case '\\': result.insert(result.end(), '\\'); break;        case '"': result.insert(result.end(), '"'); break;        case ' ': result.insert(result.end(), ' '); break;        case 't': result.insert(result.end(), '\t'); break;        case 'n': result.insert(result.end(), '\n'); break;        case 'r': result.insert(result.end(), '\r'); break;        case '#': result.insert(result.end(), '#'); break;        case '(': result.insert(result.end(), '('); break;        case ')': result.insert(result.end(), ')'); break;        case '0': result.insert(result.end(), '\0'); break;        case '\0':          {          cmSystemTools::Error("Trailing backslash in argument:\n", s);          return result;          }        default:          {          std::string chStr(1, *ch);          cmSystemTools::Error("Invalid escape sequence \\", chStr.c_str(),                               "\nin argument ", s);          }        }      }    else      {      result.insert(result.end(), *ch);      }    }  return result;}void cmSystemTools::Error(const char* m1, const char* m2,                          const char* m3, const char* m4){  std::string message = "CMake Error: ";  if(m1)    {    message += m1;    }  if(m2)    {    message += m2;    }  if(m3)    {    message += m3;    }  if(m4)    {    message += m4;    }  cmSystemTools::s_ErrorOccured = true;  cmSystemTools::Message(message.c_str(),"Error");}void cmSystemTools::SetErrorCallback(ErrorCallback f, void* clientData){  s_ErrorCallback = f;  s_ErrorCallbackClientData = clientData;}void cmSystemTools::SetStdoutCallback(StdoutCallback f, void* clientData){  s_StdoutCallback = f;  s_StdoutCallbackClientData = clientData;}void cmSystemTools::Stdout(const char* s){  if(s_StdoutCallback)    {    (*s_StdoutCallback)(s, strlen(s), s_StdoutCallbackClientData);    }  else    {    std::cout << s;    std::cout.flush();    }}void cmSystemTools::Stdout(const char* s, int length){  if(s_StdoutCallback)    {    (*s_StdoutCallback)(s, length, s_StdoutCallbackClientData);    }  else    {    std::cout.write(s, length);    std::cout.flush();    }}void cmSystemTools::Message(const char* m1, const char *title){  if(s_DisableMessages)    {    return;    }  if(s_ErrorCallback)    {    (*s_ErrorCallback)(m1, title, s_DisableMessages, s_ErrorCallbackClientData);    return;    }  else    {    std::cerr << m1 << std::endl << std::flush;    }  }void cmSystemTools::ReportLastSystemError(const char* msg){  std::string m = msg;  m += ": System Error: ";  m += Superclass::GetLastSystemError();  cmSystemTools::Error(m.c_str());} bool cmSystemTools::IsOn(const char* val){  if (!val)    {    return false;    }  std::basic_string<char> v = val;    for(std::basic_string<char>::iterator c = v.begin();      c != v.end(); c++)    {    *c = toupper(*c);    }  return (v == "ON" || v == "1" || v == "YES" || v == "TRUE" || v == "Y");}bool cmSystemTools::IsNOTFOUND(const char* val){  int len = strlen(val);  const char* notfound = "-NOTFOUND";  const int lenNotFound = 9;  if(len < lenNotFound-1)    {    return false;    }  if(len == lenNotFound-1)    {    return ( strcmp(val, "NOTFOUND") == 0);    }  return ((strncmp((val + (len - lenNotFound)), notfound, lenNotFound) == 0));}bool cmSystemTools::IsOff(const char* val){  if (!val || strlen(val) == 0)    {    return true;    }  std::basic_string<char> v = val;    for(std::basic_string<char>::iterator c = v.begin();      c != v.end(); c++)    {    *c = toupper(*c);    }  return (v == "OFF" || v == "0" || v == "NO" || v == "FALSE" ||           v == "N" || cmSystemTools::IsNOTFOUND(v.c_str()) || v == "IGNORE");}std::vector<cmStdString> cmSystemTools::ParseArguments(const char* command){  std::vector<cmStdString> args;  std::string arg;  bool win_path = false;  if ( command[0] != '/' && command[1] == ':' && command[2] == '\\' ||       command[0] == '\"' && command[1] != '/' && command[2] == ':' && command[3] == '\\' ||        command[0] == '\\' && command[1] == '\\')    {    win_path = true;    }  // Split the command into an argv array.  for(const char* c = command; *c;)    {    // Skip over whitespace.    while(*c == ' ' || *c == '\t')      {      ++c;      }    arg = "";    if(*c == '"')      {      // Parse a quoted argument.      ++c;      while(*c && *c != '"')        {        arg.append(1, *c);        ++c;        }      if(*c)        {        ++c;        }      args.push_back(arg);      }    else if(*c)      {      // Parse an unquoted argument.      while(*c && *c != ' ' && *c != '\t')        {        if(*c == '\\' && !win_path)          {          ++c;          if(*c)            {            arg.append(1, *c);            ++c;            }          }        else          {          arg.append(1, *c);          ++c;          }        }      args.push_back(arg);      }    }    return args;}bool cmSystemTools::RunSingleCommand(  const char* command,   std::string* output,  int *retVal,   const char* dir,  bool verbose,  double timeout){  if(s_DisableRunCommandOutput)    {    verbose = false;    }  std::vector<cmStdString> args = cmSystemTools::ParseArguments(command);  if(args.size() < 1)    {    return false;    }    std::vector<const char*> argv;  for(std::vector<cmStdString>::const_iterator a = args.begin();      a != args.end(); ++a)    {    argv.push_back(a->c_str());    }  argv.push_back(0);  if ( output )    {    *output = "";    }  cmsysProcess* cp = cmsysProcess_New();  cmsysProcess_SetCommand(cp, &*argv.begin());  cmsysProcess_SetWorkingDirectory(cp, dir);  if(cmSystemTools::GetRunCommandHideConsole())    {    cmsysProcess_SetOption(cp, cmsysProcess_Option_HideWindow, 1);    }  cmsysProcess_SetTimeout(cp, timeout);  cmsysProcess_Execute(cp);    std::vector<char> tempOutput;  char* data;  int length;  if ( output || verbose )    {  while(cmsysProcess_WaitForData(cp, &data, &length, 0))    {    if ( output )      {      tempOutput.insert(tempOutput.end(), data, data+length);      }    if(verbose)      {      cmSystemTools::Stdout(data, length);      }    }    }    cmsysProcess_WaitForExit(cp, 0);  if ( output )    {    output->append(&*tempOutput.begin(), tempOutput.size());    }    bool result = true;  if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exited)    {    if ( retVal )      {      *retVal = cmsysProcess_GetExitValue(cp);      }    else      {      if ( cmsysProcess_GetExitValue(cp) !=  0 )        {        result = false;        }      }    }  else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Exception)    {    const char* exception_str = cmsysProcess_GetExceptionString(cp);    if ( verbose )      {      std::cerr << exception_str << std::endl;      }    if ( output )      {      output->append(exception_str, strlen(exception_str));      }    result = false;    }  else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Error)    {    const char* error_str = cmsysProcess_GetErrorString(cp);    if ( verbose )      {      std::cerr << error_str << std::endl;      }    if ( output )      {      output->append(error_str, strlen(error_str));      }    result = false;    }  else if(cmsysProcess_GetState(cp) == cmsysProcess_State_Expired)    {    const char* error_str = "Process terminated due to timeout\n";    if ( verbose )      {      std::cerr << error_str << std::endl;      }    if ( output )      {      output->append(error_str, strlen(error_str));      }    result = false;    }    cmsysProcess_Delete(cp);    return result;}bool cmSystemTools::RunCommand(const char* command,                                std::string& output,                               const char* dir,                               bool verbose,                               int timeout){  int dummy;  return cmSystemTools::RunCommand(command, output, dummy,                                    dir, verbose, timeout);}#if defined(WIN32) && !defined(__CYGWIN__)#include "cmWin32ProcessExecution.h"// use this for shell commands like echo and dirbool RunCommandViaWin32(const char* command,                        const char* dir,                        std::string& output,                        int& retVal,                        bool verbose,                        int timeout){#if defined(__BORLANDC__)  return cmWin32ProcessExecution::BorlandRunCommand(command, dir, output,                                                     retVal,                                                     verbose, timeout,                                                     cmSystemTools::GetRunCommandHideConsole());#else // Visual studio  ::SetLastError(ERROR_SUCCESS);  if ( ! command )    {    cmSystemTools::Error("No command specified");    return false;    }  cmWin32ProcessExecution resProc;  if(cmSystemTools::GetRunCommandHideConsole())    {    resProc.SetHideWindows(true);    }    if ( cmSystemTools::GetWindows9xComspecSubstitute() )    {    resProc.SetConsoleSpawn(cmSystemTools::GetWindows9xComspecSubstitute() );    }  if ( !resProc.StartProcess(command, dir, verbose) )    {    output = resProc.GetOutput();    if(verbose)      {      cmSystemTools::Stdout(output.c_str());      }    return false;    }  resProc.Wait(timeout);  output = resProc.GetOutput();  retVal = resProc.GetExitValue();  return true;#endif}// use this for shell commands like echo and dirbool RunCommandViaSystem(const char* command,                         const char* dir,                         std::string& output,                         int& retVal,                         bool verbose){    std::cout << "@@ " << command << std::endl;  std::string commandInDir;  if(dir)    {    commandInDir = "cd ";    commandInDir += cmSystemTools::ConvertToOutputPath(dir);    commandInDir += " && ";    commandInDir += command;    }  else    {    commandInDir = command;    }  command = commandInDir.c_str();  std::string commandToFile = command;  commandToFile += " > ";  std::string tempFile;  tempFile += _tempnam(0, "cmake");  commandToFile += tempFile;  retVal = system(commandToFile.c_str());  std::ifstream fin(tempFile.c_str());  if(!fin)    {    if(verbose)      {      std::string errormsg = "RunCommand produced no output: command: \"";      errormsg += command;      errormsg += "\"";      errormsg += "\nOutput file: ";      errormsg += tempFile;      cmSystemTools::Error(errormsg.c_str());      }    fin.close();    cmSystemTools::RemoveFile(tempFile.c_str());    return false;    }  bool multiLine = false;  std::string line;  while(cmSystemTools::GetLineFromStream(fin, line))    {    output += line;    if(multiLine)      {      output += "\n";      }    multiLine = true;    }  fin.close();  cmSystemTools::RemoveFile(tempFile.c_str());  return true;}#else // We have popenbool RunCommandViaPopen(const char* command,                        const char* dir,                        std::string& output,                        int& retVal,                        bool verbose,                        int /*timeout*/){  // if only popen worked on windows.....  std::string commandInDir;  if(dir)    {    commandInDir = "cd \"";    commandInDir += dir;    commandInDir += "\" && ";    commandInDir += command;    }  else    {    commandInDir = command;    }  commandInDir += " 2>&1";  command = commandInDir.c_str();  const int BUFFER_SIZE = 4096;  char buffer[BUFFER_SIZE];  if(verbose)    {    cmSystemTools::Stdout("running ");    cmSystemTools::Stdout(command);    cmSystemTools::Stdout("\n");    }  fflush(stdout);  fflush(stderr);  FILE* cpipe = popen(command, "r");  if(!cpipe)    {    return false;    }  fgets(buffer, BUFFER_SIZE, cpipe);  while(!feof(cpipe))    {    if(verbose)      {      cmSystemTools::Stdout(buffer);      }    output += buffer;    fgets(buffer, BUFFER_SIZE, cpipe);    }  retVal = pclose(cpipe);  if (WIFEXITED(retVal))    {    retVal = WEXITSTATUS(retVal);    return true;    }  if (WIFSIGNALED(retVal))    {    retVal = WTERMSIG(retVal);    cmOStringStream error;    error << "\nProcess terminated due to ";    switch (retVal)      {#ifdef SIGKILL      case SIGKILL:        error << "SIGKILL";        break;#endif#ifdef SIGFPE      case SIGFPE:        error << "SIGFPE";        break;#endif#ifdef SIGBUS      case SIGBUS:        error << "SIGBUS";        break;#endif#ifdef SIGSEGV      case SIGSEGV:        error << "SIGSEGV";        break;#endif      default:        error << "signal " << retVal;        break;      }    output += error.str();    }  return false;}#endif  // endif WIN32 not CYGWIN// run a command unix uses popen (easy)// windows uses system and ShortPathbool cmSystemTools::RunCommand(const char* command,                                std::string& output,                               int &retVal,                                const char* dir,                               bool verbose,                               int timeout){  if(s_DisableRunCommandOutput)    {    verbose = false;    }  #if defined(WIN32) && !defined(__CYGWIN__)  // if the command does not start with a quote, then  // try to find the program, and if the program can not be  // found use system to run the command as it must be a built in  // shell command like echo or dir  int count = 0;  if(command[0] == '\"')    {    // count the number of quotes    for(const char* s = command; *s != 0; ++s)      {      if(*s == '\"')        {        count++;        if(count > 2)          {          break;          }        }            }    // if there are more than two double quotes use     // GetShortPathName, the cmd.exe program in windows which    // is used by system fails to execute if there are more than    // one set of quotes in the arguments    if(count > 2)      {      cmsys::RegularExpression quoted("^\"([^\"]*)\"[ \t](.*)");      if(quoted.find(command))        {        std::string shortCmd;        std::string cmd = quoted.match(1);        std::string args = quoted.match(2);        if(! cmSystemTools::FileExists(cmd.c_str()) )          {          shortCmd = cmd;          }        else if(!cmSystemTools::GetShortPath(cmd.c_str(), shortCmd))          {         cmSystemTools::Error("GetShortPath failed for " , cmd.c_str());          return false;          }        shortCmd += " ";        shortCmd += args;        //return RunCommandViaSystem(shortCmd.c_str(), dir,         //                           output, retVal, verbose);        //return WindowsRunCommand(shortCmd.c_str(), dir,         //output, retVal, verbose);        return RunCommandViaWin32(shortCmd.c_str(), dir,                                   output, retVal, verbose, timeout);        }      else        {        cmSystemTools::Error("Could not parse command line with quotes ",                              command);        }      }    }  // if there is only one set of quotes or no quotes then just run the command  //return RunCommandViaSystem(command, dir, output, retVal, verbose);  //return WindowsRunCommand(command, dir, output, retVal, verbose);  return ::RunCommandViaWin32(command, dir, output, retVal, verbose, timeout);#else  return ::RunCommandViaPopen(command, dir, output, retVal, verbose, timeout);#endif}bool cmSystemTools::DoesFileExistWithExtensions(  const char* name,  const std::vector<std::string>& headerExts){  std::string hname;  for( std::vector<std::string>::const_iterator ext = headerExts.begin();       ext != headerExts.end(); ++ext )    {    hname = name;    hname += ".";    hname += *ext;    if(cmSystemTools::FileExists(hname.c_str()))      {      return true;      }    }  return false;}bool cmSystemTools::cmCopyFile(const char* source, const char* destination){  return Superclass::CopyFileAlways(source, destination);}bool cmSystemTools::CopyFileIfDifferent(const char* source,   const char* destination){  return Superclass::CopyFileIfDifferent(source, destination);}void cmSystemTools::Glob(const char *directory, const char *regexp,                         std::vector<std::string>& files){  cmsys::Directory d;  cmsys::RegularExpression reg(regexp);    if (d.Load(directory))    {    size_t numf;        unsigned int i;    numf = d.GetNumberOfFiles();    for (i = 0; i < numf; i++)      {      std::string fname = d.GetFile(i);      if (reg.find(fname))        {        files.push_back(fname);        }      }    }}void cmSystemTools::GlobDirs(const char *fullPath,                             std::vector<std::string>& files){  std::string path = fullPath;  std::string::size_type pos = path.find("/*");  if(pos == std::string::npos)    {    files.push_back(fullPath);    return;    }  std::string startPath = path.substr(0, pos);  std::string finishPath = path.substr(pos+2);  cmsys::Directory d;  if (d.Load(startPath.c_str()))    {    for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)      {      if((std::string(d.GetFile(i)) != ".")         && (std::string(d.GetFile(i)) != ".."))        {        std::string fname = startPath;        fname +="/";        fname += d.GetFile(i);        if(cmSystemTools::FileIsDirectory(fname.c_str()))          {          fname += finishPath;          cmSystemTools::GlobDirs(fname.c_str(), files);          }        }      }    }}void cmSystemTools::ExpandList(std::vector<std::string> const& arguments,                                std::vector<std::string>& newargs){  std::vector<std::string>::const_iterator i;  for(i = arguments.begin();i != arguments.end(); ++i)    {    cmSystemTools::ExpandListArgument(*i, newargs);    }}void cmSystemTools::ExpandListArgument(const std::string& arg,                                       std::vector<std::string>& newargs){  std::string newarg;  // If argument is empty, it is an empty list.  if(arg.length() == 0)    {    return;    }  // if there are no ; in the name then just copy the current string  if(arg.find(';') == std::string::npos)    {    newargs.push_back(arg);    return;    }  // Break the string at non-escaped semicolons not nested in [].  int squareNesting = 0;  for(const char* c = arg.c_str(); *c; ++c)    {    switch(*c)      {      case '\\':        {        // We only want to allow escaping of semicolons.  Other        // escapes should not be processed here.        ++c;        if(*c == ';')          {          newarg += ';';          }        else          {          newarg += '\\';          if(*c)            {            newarg += *c;            }          }        } break;      case '[':        {        ++squareNesting;        newarg += '[';        } break;      case ']':        {        --squareNesting;        newarg += ']';        } break;      case ';':        {        // Break the string here if we are not nested inside square        // brackets.        if(squareNesting == 0)          {          if(newarg.length())            {            // Add an argument if the string is not empty.            newargs.push_back(newarg);            newarg = "";            }          }        else          {          newarg += ';';          }        } break;      default:        {        // Just append this character.        newarg += *c;        } break;      }    }  if(newarg.length())    {    // Add the last argument if the string is not empty.    newargs.push_back(newarg);    }}bool cmSystemTools::SimpleGlob(const cmStdString& glob,                                std::vector<cmStdString>& files,                                int type /* = 0 */){  files.clear();  if ( glob[glob.size()-1] != '*' )    {    return false;    }  std::string path = cmSystemTools::GetFilenamePath(glob);  std::string ppath = cmSystemTools::GetFilenameName(glob);  ppath = ppath.substr(0, ppath.size()-1);  if ( path.size() == 0 )    {    path = "/";    }  bool res = false;  cmsys::Directory d;  if (d.Load(path.c_str()))    {    for (unsigned int i = 0; i < d.GetNumberOfFiles(); ++i)      {      if((std::string(d.GetFile(i)) != ".")         && (std::string(d.GetFile(i)) != ".."))        {        std::string fname = path;        if ( path[path.size()-1] != '/' )          {          fname +="/";          }        fname += d.GetFile(i);        std::string sfname = d.GetFile(i);        if ( type > 0 && cmSystemTools::FileIsDirectory(fname.c_str()) )          {          continue;          }        if ( type < 0 && !cmSystemTools::FileIsDirectory(fname.c_str()) )          {          continue;          }        if ( sfname.size() >= ppath.size() &&              sfname.substr(0, ppath.size()) ==              ppath )          {          files.push_back(fname);          res = true;          }        }      }    }  return res;}cmSystemTools::FileFormat cmSystemTools::GetFileFormat(const char* cext){  if ( ! cext || *cext == 0 )    {    return cmSystemTools::NO_FILE_FORMAT;    }  //std::string ext = cmSystemTools::LowerCase(cext);  std::string ext = cext;  if ( ext == "c" || ext == ".c" ) { return cmSystemTools::C_FILE_FORMAT; }  if (     ext == "C" || ext == ".C" ||    ext == "M" || ext == ".M" ||    ext == "c++" || ext == ".c++" ||    ext == "cc" || ext == ".cc" ||    ext == "cpp" || ext == ".cpp" ||    ext == "cxx" || ext == ".cxx" ||    ext == "m" || ext == ".m" ||    ext == "mm" || ext == ".mm"    ) { return cmSystemTools::CXX_FILE_FORMAT; }  if (     ext == "f" || ext == ".f" ||    ext == "F" || ext == ".F" ||    ext == "f77" || ext == ".f77" ||    ext == "f90" || ext == ".f90" ||    ext == "for" || ext == ".for" ||    ext == "f95" || ext == ".f95"     ) { return cmSystemTools::FORTRAN_FILE_FORMAT; }  if ( ext == "java" || ext == ".java" ) { return cmSystemTools::JAVA_FILE_FORMAT; }  if (     ext == "H" || ext == ".H" ||     ext == "h" || ext == ".h" ||     ext == "h++" || ext == ".h++" ||    ext == "hm" || ext == ".hm" ||     ext == "hpp" || ext == ".hpp" ||     ext == "hxx" || ext == ".hxx" ||    ext == "in" || ext == ".in" ||    ext == "txx" || ext == ".txx"    ) { return cmSystemTools::HEADER_FILE_FORMAT; }  if ( ext == "rc" || ext == ".rc" ) { return cmSystemTools::RESOURCE_FILE_FORMAT; }  if ( ext == "def" || ext == ".def" ) { return cmSystemTools::DEFINITION_FILE_FORMAT; }  if ( ext == "lib" || ext == ".lib" ||       ext == "a" || ext == ".a") { return cmSystemTools::STATIC_LIBRARY_FILE_FORMAT; }  if ( ext == "o" || ext == ".o" ||       ext == "obj" || ext == ".obj") { return cmSystemTools::OBJECT_FILE_FORMAT; }#ifdef __APPLE__  if ( ext == "dylib" || ext == ".dylib" )     { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }  if ( ext == "so" || ext == ".so" ||        ext == "bundle" || ext == ".bundle" )     { return cmSystemTools::MODULE_FILE_FORMAT; } #else // __APPLE__  if ( ext == "so" || ext == ".so" ||        ext == "sl" || ext == ".sl" ||        ext == "dll" || ext == ".dll" )     { return cmSystemTools::SHARED_LIBRARY_FILE_FORMAT; }#endif // __APPLE__  return cmSystemTools::UNKNOWN_FILE_FORMAT;}bool cmSystemTools::Split(const char* s, std::vector<cmStdString>& l){  std::vector<std::string> temp;  bool res = Superclass::Split(s, temp);  for(std::vector<std::string>::const_iterator i = temp.begin();      i != temp.end(); ++i)    {    l.push_back(*i);    }  return res;}std::string cmSystemTools::ConvertToOutputPath(const char* path){#if defined(_WIN32) && !defined(__CYGWIN__)  if(s_ForceUnixPaths)    {    return cmSystemTools::ConvertToUnixOutputPath(path);    }  return cmSystemTools::ConvertToWindowsOutputPath(path);#else  return cmSystemTools::ConvertToUnixOutputPath(path);#endif}std::string cmSystemTools::ConvertToRunCommandPath(const char* path){#if defined(_WIN32) && !defined(__CYGWIN__)  return cmSystemTools::ConvertToWindowsOutputPath(path);#else  return cmSystemTools::ConvertToUnixOutputPath(path);#endif}bool cmSystemTools::StringEndsWith(const char* str1, const char* str2){  if ( !str1 || !str2 || strlen(str1) < strlen(str2) )    {    return 0;    }  return !strncmp(str1 + (strlen(str1)-strlen(str2)), str2, strlen(str2));}#if defined(_WIN32) && !defined(__CYGWIN__)bool cmSystemTools::CreateSymlink(const char*, const char*){  // Should we create a copy here?  return false;}#elsebool cmSystemTools::CreateSymlink(const char* origName, const char* newName){  return (symlink(origName, newName) >= 0);}#endifstd::vector<cmStdString> cmSystemTools::SplitString(const char* p, char sep, bool isPath){  std::string path = p;  std::vector<cmStdString> paths;  if(isPath && path[0] == '/')    {    path.erase(path.begin());    paths.push_back("/");     }  std::string::size_type pos1 = 0;  std::string::size_type pos2 = path.find(sep, pos1+1);  while(pos2 != std::string::npos)    {    paths.push_back(path.substr(pos1, pos2-pos1));    pos1 = pos2+1;    pos2 = path.find(sep, pos1+1);    }   paths.push_back(path.substr(pos1, pos2-pos1));    return paths;}// compute the relative path from here to therestd::string cmSystemTools::RelativePath(const char* local, const char* remote){  if(!cmSystemTools::FileIsFullPath(local))    {    cmSystemTools::Error("RelativePath must be passed a full path to local: ", local);    }  if(!cmSystemTools::FileIsFullPath(remote))    {    cmSystemTools::Error("RelativePath must be passed a full path to local: ", remote);    }    // check for driveletter: as the start of the path  // if not on the same drive then full path to local must be used.  if(local[0] && local[0] != '/')    {    if(remote[0] && local[0] != remote[0])      {      return remote;      }    }  std::string relativePath;     // result string  // split up both paths into arrays of strings using / as a separator  std::string localString = local;  std::vector<cmStdString> fileSplit = cmSystemTools::SplitString(local, '/', true);   std::vector<cmStdString> relativeSplit = cmSystemTools::SplitString(remote, '/', true);  std::vector<cmStdString> commonPath;  std::vector<cmStdString> finalPath;  // count up how many matching directory names there are from the start  unsigned int sameCount = 0;  while(    ((sameCount <= (fileSplit.size()-1)) && (sameCount <= (relativeSplit.size()-1)))    && // for windows and apple do a case insensitive string compare    #if defined(_WIN32) || defined(__APPLE__)    cmSystemTools::Strucmp(fileSplit[sameCount].c_str(),                              relativeSplit[sameCount].c_str()) == 0#else    fileSplit[sameCount] == relativeSplit[sameCount]#endif    )    {    // put the common parts of the path into the commonPath array    commonPath.push_back(fileSplit[sameCount]);    // erase the common parts of the path from the original path arrays    fileSplit[sameCount] = "";    relativeSplit[sameCount] = "";    sameCount++;    }  // for each entry that is not common in the local or file path   // add a ../ to the finalpath array  for(unsigned int i = 0; i < fileSplit.size(); ++i)    {    if(fileSplit[i].size())      {      finalPath.push_back("../");      }    }  // for each entry that is not common in the remote path add it  // to the final path  for(std::vector<cmStdString>::iterator i = relativeSplit.begin();      i != relativeSplit.end(); ++i)    {    if(i->size())      {      finalPath.push_back(*i);      }    }  // now turn the array of directories into a unix path by puttint /   // between each entry that does not already have one  for(std::vector<cmStdString>::iterator i = finalPath.begin();      i != finalPath.end(); ++i)    {    if(relativePath.size() && relativePath[relativePath.size()-1] != '/')      {      relativePath += "/";      }    relativePath += *i;    }  return relativePath;}class cmDeletingCharVector : public std::vector<char*>{public:  ~cmDeletingCharVector()    {      for(std::vector<char*>::iterator i = this->begin();          i != this->end(); ++i)        {        delete []*i;        }    }};        bool cmSystemTools::PutEnv(const char* value){   static cmDeletingCharVector localEnvironment;  char* envVar = new char[strlen(value)+1];  strcpy(envVar, value);  int ret = putenv(envVar);  // save the pointer in the static vector so that it can  // be deleted on exit  localEnvironment.push_back(envVar);  return ret == 0;}
 |