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 GUIs 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 ||
98 ///! If this is set to true, cmake stops processing commands.
99 static void SetFatalErrorOccured()
101 cmSystemTools::s_FatalErrorOccured = true;
103 static void SetErrorOccured()
105 cmSystemTools::s_ErrorOccured = true;
107 ///! Return true if there was an error at any point.
108 static bool GetFatalErrorOccured()
110 return cmSystemTools::s_FatalErrorOccured || GetInterruptFlag();
113 ///! Set the error occured flag and fatal error back to false
114 static void ResetErrorOccuredFlag()
116 cmSystemTools::s_FatalErrorOccured = false;
117 cmSystemTools::s_ErrorOccured = false;
121 * Does a string indicates that CMake/CPack/CTest internally
122 * forced this value. This is not the same as On, but this
123 * may be considered as "internally switched on".
125 static bool IsInternallyOn(const char* val);
127 * does a string indicate a true or on value ? This is not the same
130 static bool IsOn(const char* val);
133 * does a string indicate a false or off value ? Note that this is
134 * not the same as !IsOn(...) because there are a number of
135 * ambiguous values such as "/usr/local/bin" a path will result in
136 * IsON and IsOff both returning false. Note that the special path
137 * NOTFOUND, *-NOTFOUND or IGNORE will cause IsOff to return true.
139 static bool IsOff(const char* val);
141 ///! Return true if value is NOTFOUND or ends in -NOTFOUND.
142 static bool IsNOTFOUND(const char* value);
143 ///! Return true if the path is a framework
144 static bool IsPathToFramework(const char* value);
146 static bool DoesFileExistWithExtensions(
148 const std::vector<std::string>& sourceExts);
151 * Check if the given file exists in one of the parent directory of the
152 * given file or directory and if it does, return the name of the file.
153 * Toplevel specifies the top-most directory to where it will look.
155 static std::string FileExistsInParentDirectories(const char* fname,
156 const char* directory, const char* toplevel);
158 static void Glob(const char *directory, const char *regexp,
159 std::vector<std::string>& files);
160 static void GlobDirs(const char *fullPath, std::vector<std::string>& files);
163 * Try to find a list of files that match the "simple" globbing
164 * expression. At this point in time the globbing expressions have
165 * to be in form: /directory/partial_file_name*. The * character has
166 * to be at the end of the string and it does not support ?
167 * []... The optional argument type specifies what kind of files you
168 * want to find. 0 means all files, -1 means directories, 1 means
169 * files only. This method returns true if search was succesfull.
171 static bool SimpleGlob(const cmStdString& glob,
172 std::vector<cmStdString>& files,
176 static bool cmCopyFile(const char* source, const char* destination);
177 static bool CopyFileIfDifferent(const char* source,
178 const char* destination);
180 /** Rename a file or directory within a single disk volume (atomic
182 static bool RenameFile(const char* oldname, const char* newname);
184 ///! Compute the md5sum of a file
185 static bool ComputeFileMD5(const char* source, char* md5out);
187 /** Compute the md5sum of a string. */
188 static std::string ComputeStringMD5(const char* input);
191 * Run an executable command and put the stdout in output.
192 * A temporary file is created in the binaryDir for storing the
193 * output because windows does not have popen.
195 * If verbose is false, no user-viewable output from the program
196 * being run will be generated.
198 * If timeout is specified, the command will be terminated after
201 static bool RunCommand(const char* command, std::string& output,
202 const char* directory = 0,
203 bool verbose = true, int timeout = 0);
204 static bool RunCommand(const char* command, std::string& output,
205 int &retVal, const char* directory = 0,
206 bool verbose = true, int timeout = 0);
208 * Run a single executable command
210 * Output is controlled with outputflag. If outputflag is OUTPUT_NONE, no
211 * user-viewable output from the program being run will be generated.
212 * OUTPUT_MERGE is the legacy behaviour where stdout and stderr are merged
213 * into stdout. OUTPUT_NORMAL passes through the output to stdout/stderr as
214 * it was received. OUTPUT_PASSTHROUGH passes through the original handles.
216 * If timeout is specified, the command will be terminated after
217 * timeout expires. Timeout is specified in seconds.
219 * Argument retVal should be a pointer to the location where the
220 * exit code will be stored. If the retVal is not specified and
221 * the program exits with a code other than 0, then the this
222 * function will return false.
224 * If the command has spaces in the path the caller MUST call
225 * cmSystemTools::ConvertToRunCommandPath on the command before passing
226 * it into this function or it will not work. The command must be correctly
227 * escaped for this to with spaces.
236 static bool RunSingleCommand(const char* command, std::string* output = 0,
237 int* retVal = 0, const char* dir = 0,
238 OutputOption outputflag = OUTPUT_MERGE,
239 double timeout = 0.0);
241 * In this version of RunSingleCommand, command[0] should be
242 * the command to run, and each argument to the command should
243 * be in comand[1]...command[command.size()]
245 static bool RunSingleCommand(std::vector<cmStdString> const& command,
246 std::string* output = 0,
247 int* retVal = 0, const char* dir = 0,
248 OutputOption outputflag = OUTPUT_MERGE,
249 double timeout = 0.0);
252 * Parse arguments out of a single string command
254 static std::vector<cmStdString> ParseArguments(const char* command);
256 /** Parse arguments out of a windows command line string. */
257 static void ParseWindowsCommandLine(const char* command,
258 std::vector<std::string>& args);
260 /** Parse arguments out of a unix command line string. */
261 static void ParseUnixCommandLine(const char* command,
262 std::vector<std::string>& args);
263 static void ParseUnixCommandLine(const char* command,
264 std::vector<cmStdString>& args);
266 /** Compute an escaped version of the given argument for use in a
267 windows shell. See kwsys/System.h.in for details. */
268 static std::string EscapeWindowsShellArgument(const char* arg,
271 static void EnableMessages() { s_DisableMessages = false; }
272 static void DisableMessages() { s_DisableMessages = true; }
273 static void DisableRunCommandOutput() {s_DisableRunCommandOutput = true; }
274 static void EnableRunCommandOutput() {s_DisableRunCommandOutput = false; }
275 static bool GetRunCommandOutput() { return s_DisableRunCommandOutput; }
278 * Some constants for different file formats.
287 RESOURCE_FILE_FORMAT,
288 DEFINITION_FILE_FORMAT,
289 STATIC_LIBRARY_FILE_FORMAT,
290 SHARED_LIBRARY_FILE_FORMAT,
305 static bool VersionCompare(CompareOp op, const char* lhs, const char* rhs);
308 * Determine the file type based on the extension
310 static FileFormat GetFileFormat(const char* ext);
313 * On Windows 9x we need a comspec (command.com) substitute to run
314 * programs correctly. This string has to be constant available
315 * through the running of program. This method does not create a copy.
317 static void SetWindows9xComspecSubstitute(const char*);
318 static const char* GetWindows9xComspecSubstitute();
320 /** Windows if this is true, the CreateProcess in RunCommand will
321 * not show new consol windows when running programs.
323 static void SetRunCommandHideConsole(bool v){s_RunCommandHideConsole = v;}
324 static bool GetRunCommandHideConsole(){ return s_RunCommandHideConsole;}
325 /** Call cmSystemTools::Error with the message m, plus the
326 * result of strerror(errno)
328 static void ReportLastSystemError(const char* m);
330 /** a general output handler for cmsysProcess */
331 static int WaitForLine(cmsysProcess* process, std::string& line,
333 std::vector<char>& out,
334 std::vector<char>& err);
336 /** Split a string on its newlines into multiple lines. Returns
337 false only if the last line stored had no newline. */
338 static bool Split(const char* s, std::vector<cmStdString>& l);
339 static void SetForceUnixPaths(bool v)
341 s_ForceUnixPaths = v;
343 static bool GetForceUnixPaths()
345 return s_ForceUnixPaths;
348 // ConvertToOutputPath use s_ForceUnixPaths
349 static std::string ConvertToOutputPath(const char* path);
350 static void ConvertToOutputSlashes(std::string& path);
352 // ConvertToRunCommandPath does not use s_ForceUnixPaths and should
353 // be used when RunCommand is called from cmake, because the
354 // running cmake needs paths to be in its format
355 static std::string ConvertToRunCommandPath(const char* path);
356 //! Check if the first string ends with the second one.
357 static bool StringEndsWith(const char* str1, const char* str2);
359 /** compute the relative path from local to remote. local must
360 be a directory. remote can be a file or a directory.
361 Both remote and local must be full paths. Basically, if
362 you are in directory local and you want to access the file in remote
363 what is the relative path to do that. For example:
364 /a/b/c/d to /a/b/c1/d1 -> ../../c1/d1
365 from /usr/src to /usr/src/test/blah/foo.cpp -> test/blah/foo.cpp
367 static std::string RelativePath(const char* local, const char* remote);
369 /** Joins two paths while collapsing x/../ parts
370 * For example CollapseCombinedPath("a/b/c", "../../d") results in "a/d"
372 static std::string CollapseCombinedPath(std::string const& dir,
373 std::string const& file);
375 #ifdef CMAKE_BUILD_WITH_CMAKE
376 /** Remove an environment variable */
377 static bool UnsetEnv(const char* value);
379 /** Get the list of all environment variables */
380 static std::vector<std::string> GetEnvironmentVariables();
382 /** Append multiple variables to the current environment. */
383 static void AppendEnv(std::vector<std::string> const& env);
385 /** Helper class to save and restore the environment.
386 Instantiate this class as an automatic variable on
387 the stack. Its constructor saves a copy of the current
388 environment and then its destructor restores the
389 original environment. */
390 class SaveRestoreEnvironment
393 SaveRestoreEnvironment();
394 virtual ~SaveRestoreEnvironment();
396 std::vector<std::string> Env;
400 /** Setup the environment to enable VS 8 IDE output. */
401 static void EnableVSConsoleOutput();
404 static bool ListTar(const char* outFileName,
405 bool gzip, bool verbose);
406 static bool CreateTar(const char* outFileName,
407 const std::vector<cmStdString>& files, bool gzip,
408 bool bzip2, bool verbose);
409 static bool ExtractTar(const char* inFileName, bool gzip,
411 // This should be called first thing in main
412 // it will keep child processes from inheriting the
413 // stdin and stdout of this process. This is important
414 // if you want to be able to kill child processes and
415 // not get stuck waiting for all the output on the pipes.
416 static void DoNotInheritStdPipes();
418 /** Copy the file create/access/modify times from the file named by
419 the first argument to that named by the second. */
420 static bool CopyFileTime(const char* fromFile, const char* toFile);
422 /** Save and restore file times. */
423 static cmSystemToolsFileTime* FileTimeNew();
424 static void FileTimeDelete(cmSystemToolsFileTime*);
425 static bool FileTimeGet(const char* fname, cmSystemToolsFileTime* t);
426 static bool FileTimeSet(const char* fname, cmSystemToolsFileTime* t);
428 /** Random seed generation. */
429 static unsigned int RandomSeed();
431 /** Find the directory containing the running executable. Save it
432 in a global location to be queried by GetExecutableDirectory
434 static void FindExecutableDirectory(const char* argv0);
436 /** Get the directory containing the currently running executable. */
437 static const char* GetExecutableDirectory();
439 #if defined(CMAKE_BUILD_WITH_CMAKE)
440 /** Echo a message in color using KWSys's Terminal cprintf. */
441 static void MakefileColorEcho(int color, const char* message,
442 bool newLine, bool enabled);
445 /** Try to guess the soname of a shared library. */
446 static bool GuessLibrarySOName(std::string const& fullPath,
447 std::string& soname);
449 /** Try to guess the install name of a shared library. */
450 static bool GuessLibraryInstallName(std::string const& fullPath,
451 std::string& soname);
453 /** Try to set the RPATH in an ELF binary. */
454 static bool ChangeRPath(std::string const& file,
455 std::string const& oldRPath,
456 std::string const& newRPath,
457 std::string* emsg = 0,
460 /** Try to remove the RPATH from an ELF binary. */
461 static bool RemoveRPath(std::string const& file, std::string* emsg = 0,
464 /** Check whether the RPATH in an ELF binary contains the path
466 static bool CheckRPath(std::string const& file,
467 std::string const& newRPath);
469 /** Remove a directory; repeat a few times in case of locked files. */
470 static bool RepeatedRemoveDirectory(const char* dir);
472 /** Tokenize a string */
473 static std::vector<std::string> tokenize(const std::string& str,
474 const std::string& sep);
476 static bool s_ForceUnixPaths;
477 static bool s_RunCommandHideConsole;
478 static bool s_ErrorOccured;
479 static bool s_FatalErrorOccured;
480 static bool s_DisableMessages;
481 static bool s_DisableRunCommandOutput;
482 static ErrorCallback s_ErrorCallback;
483 static StdoutCallback s_StdoutCallback;
484 static InterruptCallback s_InterruptCallback;
485 static void* s_ErrorCallbackClientData;
486 static void* s_StdoutCallbackClientData;
487 static void* s_InterruptCallbackClientData;
489 static std::string s_Windows9xComspecSubstitute;