1 /*============================================================================
2 CMake - Cross Platform Makefile Generator
3 Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
5 Distributed under the OSI-approved BSD License (the "License");
6 see accompanying file Copyright.txt for details.
8 This software is distributed WITHOUT ANY WARRANTY; without even the
9 implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
10 See the License for more information.
11 ============================================================================*/
12 #ifndef cmSystemTools_h
13 #define cmSystemTools_h
15 #include "cmStandardIncludes.h"
17 #include <cmsys/SystemTools.hxx>
18 #include <cmsys/Process.h>
20 class cmSystemToolsFileTime;
22 /** \class cmSystemTools
23 * \brief A collection of useful functions for CMake.
25 * cmSystemTools is a class that provides helper functions
26 * for the CMake build system.
28 class cmSystemTools: public cmsys::SystemTools
31 typedef cmsys::SystemTools Superclass;
33 /** Expand out any arguments in the vector that have ; separated
34 * strings into multiple arguments. A new vector is created
35 * containing the expanded versions of all arguments in argsIn.
37 static void ExpandList(std::vector<std::string> const& argsIn,
38 std::vector<std::string>& argsOut);
39 static void ExpandListArgument(const std::string& arg,
40 std::vector<std::string>& argsOut,
41 bool emptyArgs=false);
44 * Look for and replace registry values in a string
46 static void ExpandRegistryValues(std::string& source,
47 KeyWOW64 view = KeyWOW64_Default);
49 ///! Escape quotes in a string.
50 static std::string EscapeQuotes(const char* str);
53 * Returns a string that has whitespace removed from the start and the end.
55 static std::string TrimWhitespace(const std::string& s);
57 typedef void (*ErrorCallback)(const char*, const char*, bool&, void*);
59 * Set the function used by GUI's to display error messages
60 * Function gets passed: message as a const char*,
61 * title as a const char*, and a reference to bool that when
62 * set to false, will disable furthur messages (cancel).
64 static void SetErrorCallback(ErrorCallback f, void* clientData=0);
67 * Display an error message.
69 static void Error(const char* m, const char* m2=0,
70 const char* m3=0, const char* m4=0);
75 static void Message(const char* m, const char* title=0);
77 ///! Send a string to stdout
78 static void Stdout(const char* s);
79 static void Stdout(const char* s, int length);
80 typedef void (*StdoutCallback)(const char*, int length, void*);
81 static void SetStdoutCallback(StdoutCallback, void* clientData=0);
83 ///! Send a string to stderr. Stdout callbacks will not be invoced.
84 static void Stderr(const char* s, int length);
87 typedef bool (*InterruptCallback)(void*);
88 static void SetInterruptCallback(InterruptCallback f, void* clientData=0);
89 static bool GetInterruptFlag();
91 ///! Return true if there was an error at any point.
92 static bool GetErrorOccuredFlag()
94 return cmSystemTools::s_ErrorOccured ||
95 cmSystemTools::s_FatalErrorOccured;
97 ///! If this is set to true, cmake stops processing commands.
98 static void SetFatalErrorOccured()
100 cmSystemTools::s_FatalErrorOccured = true;
102 static void SetErrorOccured()
104 cmSystemTools::s_ErrorOccured = true;
106 ///! Return true if there was an error at any point.
107 static bool GetFatalErrorOccured()
109 return cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
112 ///! Set the error occured flag and fatal error back to false
113 static void ResetErrorOccuredFlag()
115 cmSystemTools::s_FatalErrorOccured = false;
116 cmSystemTools::s_ErrorOccured = false;
120 * Does a string indicates that CMake/CPack/CTest internally
121 * forced this value. This is not the same as On, but this
122 * may be considered as "internally switched on".
124 static bool IsInternallyOn(const char* val);
126 * does a string indicate a true or on value ? This is not the same
129 static bool IsOn(const char* val);
132 * does a string indicate a false or off value ? Note that this is
133 * not the same as !IsOn(...) because there are a number of
134 * ambiguous values such as "/usr/local/bin" a path will result in
135 * IsON and IsOff both returning false. Note that the special path
136 * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
138 static bool IsOff(const char* val);
140 ///! Return true if value is NOTFOUND or ends in -NOTFOUND.
141 static bool IsNOTFOUND(const char* value);
142 ///! Return true if the path is a framework
143 static bool IsPathToFramework(const char* value);
145 static bool DoesFileExistWithExtensions(
147 const std::vector<std::string>& sourceExts);
150 * Check if the given file exists in one of the parent directory of the
151 * given file or directory and if it does, return the name of the file.
152 * Toplevel specifies the top-most directory to where it will look.
154 static std::string FileExistsInParentDirectories(const char* fname,
155 const char* directory, const char* toplevel);
157 static void Glob(const char *directory, const char *regexp,
158 std::vector<std::string>& files);
159 static void GlobDirs(const char *fullPath, std::vector<std::string>& files);
162 * Try to find a list of files that match the "simple" globbing
163 * expression. At this point in time the globbing expressions have
164 * to be in form: /directory/partial_file_name*. The * character has
165 * to be at the end of the string and it does not support ?
166 * []... The optional argument type specifies what kind of files you
167 * want to find. 0 means all files, -1 means directories, 1 means
168 * files only. This method returns true if search was succesfull.
170 static bool SimpleGlob(const cmStdString& glob,
171 std::vector<cmStdString>& files,
175 static bool cmCopyFile(const char* source, const char* destination);
176 static bool CopyFileIfDifferent(const char* source,
177 const char* destination);
179 /** Rename a file or directory within a single disk volume (atomic
181 static bool RenameFile(const char* oldname, const char* newname);
183 ///! Compute the md5sum of a file
184 static bool ComputeFileMD5(const char* source, char* md5out);
186 /** Compute the md5sum of a string. */
187 static std::string ComputeStringMD5(const char* input);
190 * Run an executable command and put the stdout in output.
191 * A temporary file is created in the binaryDir for storing the
192 * output because windows does not have popen.
194 * If verbose is false, no user-viewable output from the program
195 * being run will be generated.
197 * If timeout is specified, the command will be terminated after
200 static bool RunCommand(const char* command, std::string& output,
201 const char* directory = 0,
202 bool verbose = true, int timeout = 0);
203 static bool RunCommand(const char* command, std::string& output,
204 int &retVal, const char* directory = 0,
205 bool verbose = true, int timeout = 0);
207 * Run a single executable command
209 * Output is controlled with outputflag. If outputflag is OUTPUT_NONE, no
210 * user-viewable output from the program being run will be generated.
211 * OUTPUT_MERGE is the legacy behaviour where stdout and stderr are merged
212 * into stdout. OUTPUT_NORMAL passes through the output to stdout/stderr as
215 * If timeout is specified, the command will be terminated after
216 * timeout expires. Timeout is specified in seconds.
218 * Argument retVal should be a pointer to the location where the
219 * exit code will be stored. If the retVal is not specified and
220 * the program exits with a code other than 0, then the this
221 * function will return false.
223 * If the command has spaces in the path the caller MUST call
224 * cmSystemTools::ConvertToRunCommandPath on the command before passing
225 * it into this function or it will not work. The command must be correctly
226 * escaped for this to with spaces.
234 static bool RunSingleCommand(const char* command, std::string* output = 0,
235 int* retVal = 0, const char* dir = 0,
236 OutputOption outputflag = OUTPUT_MERGE,
237 double timeout = 0.0);
239 * In this version of RunSingleCommand, command[0] should be
240 * the command to run, and each argument to the command should
241 * be in comand[1]...command[command.size()]
243 static bool RunSingleCommand(std::vector<cmStdString> const& command,
244 std::string* output = 0,
245 int* retVal = 0, const char* dir = 0,
246 OutputOption outputflag = OUTPUT_MERGE,
247 double timeout = 0.0);
250 * Parse arguments out of a single string command
252 static std::vector<cmStdString> ParseArguments(const char* command);
254 /** Parse arguments out of a windows command line string. */
255 static void ParseWindowsCommandLine(const char* command,
256 std::vector<std::string>& args);
258 /** Parse arguments out of a unix command line string. */
259 static void ParseUnixCommandLine(const char* command,
260 std::vector<std::string>& args);
261 static void ParseUnixCommandLine(const char* command,
262 std::vector<cmStdString>& args);
264 /** Compute an escaped version of the given argument for use in a
265 windows shell. See kwsys/System.h.in for details. */
266 static std::string EscapeWindowsShellArgument(const char* arg,
269 static void EnableMessages() { s_DisableMessages = false; }
270 static void DisableMessages() { s_DisableMessages = true; }
271 static void DisableRunCommandOutput() {s_DisableRunCommandOutput = true; }
272 static void EnableRunCommandOutput() {s_DisableRunCommandOutput = false; }
273 static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; }
276 * Come constants for different file formats.
285 RESOURCE_FILE_FORMAT,
286 DEFINITION_FILE_FORMAT,
287 STATIC_LIBRARY_FILE_FORMAT,
288 SHARED_LIBRARY_FILE_FORMAT,
303 static bool VersionCompare(CompareOp op, const char* lhs, const char* rhs);
306 * Determine the file type based on the extension
308 static FileFormat GetFileFormat(const char* ext);
311 * On Windows 9x we need a comspec (command.com) substitute to run
312 * programs correctly. This string has to be constant available
313 * through the running of program. This method does not create a copy.
315 static void SetWindows9xComspecSubstitute(const char*);
316 static const char* GetWindows9xComspecSubstitute();
318 /** Windows if this is true, the CreateProcess in RunCommand will
319 * not show new consol windows when running programs.
321 static void SetRunCommandHideConsole(bool v){s_RunCommandHideConsole = v;}
322 static bool GetRunCommandHideConsole(){ return s_RunCommandHideConsole;}
323 /** Call cmSystemTools::Error with the message m, plus the
324 * result of strerror(errno)
326 static void ReportLastSystemError(const char* m);
328 /** a general output handler for cmsysProcess */
329 static int WaitForLine(cmsysProcess* process, std::string& line,
331 std::vector<char>& out,
332 std::vector<char>& err);
334 /** Split a string on its newlines into multiple lines. Returns
335 false only if the last line stored had no newline. */
336 static bool Split(const char* s, std::vector<cmStdString>& l);
337 static void SetForceUnixPaths(bool v)
339 s_ForceUnixPaths = v;
341 static bool GetForceUnixPaths()
343 return s_ForceUnixPaths;
346 // ConvertToOutputPath use s_ForceUnixPaths
347 static std::string ConvertToOutputPath(const char* path);
348 static void ConvertToOutputSlashes(std::string& path);
350 // ConvertToRunCommandPath does not use s_ForceUnixPaths and should
351 // be used when RunCommand is called from cmake, because the
352 // running cmake needs paths to be in its format
353 static std::string ConvertToRunCommandPath(const char* path);
354 //! Check if the first string ends with the second one.
355 static bool StringEndsWith(const char* str1, const char* str2);
357 /** compute the relative path from local to remote. local must
358 be a directory. remote can be a file or a directory.
359 Both remote and local must be full paths. Basically, if
360 you are in directory local and you want to access the file in remote
361 what is the relative path to do that. For example:
362 /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
363 from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
365 static std::string RelativePath(const char* local, const char* remote);
367 #ifdef CMAKE_BUILD_WITH_CMAKE
368 /** Remove an environment variable */
369 static bool UnsetEnv(const char* value);
371 /** Get the list of all environment variables */
372 static std::vector<std::string> GetEnvironmentVariables();
374 /** Append multiple variables to the current environment. */
375 static void AppendEnv(std::vector<std::string> const& env);
377 /** Helper class to save and restore the environment.
378 Instantiate this class as an automatic variable on
379 the stack. Its constructor saves a copy of the current
380 environment and then its destructor restores the
381 original environment. */
382 class SaveRestoreEnvironment
385 SaveRestoreEnvironment();
386 virtual ~SaveRestoreEnvironment();
388 std::vector<std::string> Env;
392 /** Setup the environment to enable VS 8 IDE output. */
393 static void EnableVSConsoleOutput();
396 static bool ListTar(const char* outFileName,
397 bool gzip, bool verbose);
398 static bool CreateTar(const char* outFileName,
399 const std::vector<cmStdString>& files, bool gzip,
400 bool bzip2, bool verbose);
401 static bool ExtractTar(const char* inFileName, bool gzip,
403 // This should be called first thing in main
404 // it will keep child processes from inheriting the
405 // stdin and stdout of this process. This is important
406 // if you want to be able to kill child processes and
407 // not get stuck waiting for all the output on the pipes.
408 static void DoNotInheritStdPipes();
410 /** Copy the file create/access/modify times from the file named by
411 the first argument to that named by the second. */
412 static bool CopyFileTime(const char* fromFile, const char* toFile);
414 /** Save and restore file times. */
415 static cmSystemToolsFileTime* FileTimeNew();
416 static void FileTimeDelete(cmSystemToolsFileTime*);
417 static bool FileTimeGet(const char* fname, cmSystemToolsFileTime* t);
418 static bool FileTimeSet(const char* fname, cmSystemToolsFileTime* t);
420 /** Random seed generation. */
421 static unsigned int RandomSeed();
423 /** Find the directory containing the running executable. Save it
424 in a global location to be queried by GetExecutableDirectory
426 static void FindExecutableDirectory(const char* argv0);
428 /** Get the directory containing the currently running executable. */
429 static const char* GetExecutableDirectory();
431 #if defined(CMAKE_BUILD_WITH_CMAKE)
432 /** Echo a message in color using KWSys's Terminal cprintf. */
433 static void MakefileColorEcho(int color, const char* message,
434 bool newLine, bool enabled);
437 /** Try to guess the soname of a shared library. */
438 static bool GuessLibrarySOName(std::string const& fullPath,
439 std::string& soname);
441 /** Try to set the RPATH in an ELF binary. */
442 static bool ChangeRPath(std::string const& file,
443 std::string const& oldRPath,
444 std::string const& newRPath,
445 std::string* emsg = 0,
448 /** Try to remove the RPATH from an ELF binary. */
449 static bool RemoveRPath(std::string const& file, std::string* emsg = 0,
452 /** Check whether the RPATH in an ELF binary contains the path
454 static bool CheckRPath(std::string const& file,
455 std::string const& newRPath);
457 /** Remove a directory; repeat a few times in case of locked files. */
458 static bool RepeatedRemoveDirectory(const char* dir);
460 /** Tokenize a string */
461 static std::vector<std::string> tokenize(const std::string& str,
462 const std::string& sep);
464 static bool s_ForceUnixPaths;
465 static bool s_RunCommandHideConsole;
466 static bool s_ErrorOccured;
467 static bool s_FatalErrorOccured;
468 static bool s_DisableMessages;
469 static bool s_DisableRunCommandOutput;
470 static ErrorCallback s_ErrorCallback;
471 static StdoutCallback s_StdoutCallback;
472 static InterruptCallback s_InterruptCallback;
473 static void* s_ErrorCallbackClientData;
474 static void* s_StdoutCallbackClientData;
475 static void* s_InterruptCallbackClientData;
477 static std::string s_Windows9xComspecSubstitute;