Remove all unnecessary HAVE_CONFIG_H
[alexxy/gromacs.git] / src / gromacs / commandline / cmdlineprogramcontext.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2012,2013,2014, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements gmx::CommandLineProgramContext.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_commandline
41  */
42 #include "cmdlineprogramcontext.h"
43
44 #include "config.h"
45
46 #include <cstdlib>
47 #include <cstring>
48
49 #include <string>
50 #include <vector>
51
52 #include <boost/scoped_ptr.hpp>
53
54 #include "thread_mpi/mutex.h"
55
56 #include "gromacs/utility/exceptions.h"
57 #include "gromacs/utility/file.h"
58 #include "gromacs/utility/gmxassert.h"
59 #include "gromacs/utility/path.h"
60 #include "gromacs/utility/stringutil.h"
61
62 namespace gmx
63 {
64
65 namespace
66 {
67
68 //! \addtogroup module_commandline
69 //! \{
70
71 /*! \brief
72  * Quotes a string if it contains spaces.
73  */
74 std::string quoteIfNecessary(const char *str)
75 {
76     const bool bSpaces = (std::strchr(str, ' ') != NULL);
77     if (bSpaces)
78     {
79         return formatString("'%s'", str);
80     }
81     return str;
82 }
83
84 /*! \brief
85  * Default implementation for ExecutableEnvironmentInterface.
86  *
87  * Used if ExecutableEnvironmentInterface is not explicitly provided when
88  * constructing CommandLineProgramContext.
89  */
90 class DefaultExecutableEnvironment : public ExecutableEnvironmentInterface
91 {
92     public:
93         //! Allocates a default environment.
94         static ExecutableEnvironmentPointer create()
95         {
96             return ExecutableEnvironmentPointer(new DefaultExecutableEnvironment());
97         }
98
99         DefaultExecutableEnvironment()
100             : initialWorkingDirectory_(Path::getWorkingDirectory())
101         {
102         }
103
104         virtual std::string getWorkingDirectory() const
105         {
106             return initialWorkingDirectory_;
107         }
108         virtual std::vector<std::string> getExecutablePaths() const
109         {
110             return Path::getExecutablePaths();
111         }
112
113     private:
114         std::string   initialWorkingDirectory_;
115 };
116
117 /*! \brief
118  * Finds the absolute path of the binary from \c argv[0].
119  *
120  * \param[in] invokedName \c argv[0] the binary was invoked with.
121  * \param[in] env         Executable environment.
122  * \returns   The full path of the binary.
123  *
124  * If a binary with the given name cannot be located, \p invokedName is
125  * returned.
126  */
127 std::string findFullBinaryPath(const std::string                    &invokedName,
128                                const ExecutableEnvironmentInterface &env)
129 {
130     std::string searchName = invokedName;
131     // On Windows & Cygwin we need to add the .exe extension,
132     // or we wont be able to detect that the file exists.
133 #if (defined GMX_NATIVE_WINDOWS || defined GMX_CYGWIN)
134     if (!endsWith(searchName, ".exe"))
135     {
136         searchName.append(".exe");
137     }
138 #endif
139     if (!Path::containsDirectory(searchName))
140     {
141         // No directory in name means it must be in the path - search it!
142         std::vector<std::string>                 pathEntries = env.getExecutablePaths();
143         std::vector<std::string>::const_iterator i;
144         for (i = pathEntries.begin(); i != pathEntries.end(); ++i)
145         {
146             const std::string &dir      = i->empty() ? env.getWorkingDirectory() : *i;
147             std::string        testPath = Path::join(dir, searchName);
148             if (File::exists(testPath))
149             {
150                 return testPath;
151             }
152         }
153     }
154     else if (!Path::isAbsolute(searchName))
155     {
156         // Name contains directories, but is not absolute, i.e.,
157         // it is relative to the current directory.
158         std::string cwd      = env.getWorkingDirectory();
159         std::string testPath = Path::join(cwd, searchName);
160         return testPath;
161     }
162     return searchName;
163 }
164
165 /*! \brief
166  * Returns whether given path contains files from `share/top/`.
167  *
168  * Only checks for a single file that has an uncommon enough name.
169  */
170 bool isAcceptableLibraryPath(const std::string &path)
171 {
172     return Path::exists(Path::join(path, "gurgle.dat"));
173 }
174
175 /*! \brief
176  * Returns whether given path prefix contains files from `share/top/`.
177  *
178  * \param[in]  path   Path prefix to check.
179  * \param[out] result If return value is `true`, the pointee is set to the
180  *     actual data directory. Otherwise, the pointee is not modified.
181  * \returns  `true` if \p path contains the data files.
182  *
183  * Checks whether \p path could be the installation prefix where `share/top/`
184  * files have been installed:  appends the relative installation path of the
185  * data files and calls isAcceptableLibraryPath().
186  */
187 bool isAcceptableLibraryPathPrefix(const std::string &path, std::string *result)
188 {
189     std::string testPath = Path::join(path, GMXLIB_SEARCH_DIR);
190     if (isAcceptableLibraryPath(testPath))
191     {
192         *result = testPath;
193         return true;
194     }
195     return false;
196 }
197
198 /*! \brief
199  * Returns a fallback data path.
200  *
201  * Checks a few standard locations for the data files before returning a
202  * configure-time hard-coded path.  The hard-coded path is preferred if it
203  * actually contains the data files, though.
204  */
205 std::string findFallbackLibraryDataPath()
206 {
207 #ifndef GMX_NATIVE_WINDOWS
208     if (!isAcceptableLibraryPath(GMXLIB_FALLBACK))
209     {
210         std::string foundPath;
211         if (isAcceptableLibraryPathPrefix("/usr/local", &foundPath))
212         {
213             return foundPath;
214         }
215         if (isAcceptableLibraryPathPrefix("/usr", &foundPath))
216         {
217             return foundPath;
218         }
219         if (isAcceptableLibraryPathPrefix("/opt", &foundPath))
220         {
221             return foundPath;
222         }
223     }
224 #endif
225     return GMXLIB_FALLBACK;
226 }
227
228 /*! \brief
229  * Finds the library data files based on path of the binary.
230  *
231  * \param[in] binaryPath  Absolute path to the binary.
232  * \returns  Path to the `share/top/` data files.
233  *
234  * The search based on the path only works if the binary is in the same
235  * relative path as the installed \Gromacs binaries.  If the binary is
236  * somewhere else, a hard-coded fallback is used.  This doesn't work if the
237  * binaries are somewhere else than the path given during configure time...
238  *
239  * Extra logic is present to allow running binaries from the build tree such
240  * that they use up-to-date data files from the source tree.
241  */
242 std::string findDefaultLibraryDataPath(const std::string &binaryPath)
243 {
244     // If the input path is not absolute, the binary could not be found.
245     // Don't search anything.
246     if (Path::isAbsolute(binaryPath))
247     {
248         // Remove the executable name.
249         std::string searchPath = Path::getParentPath(binaryPath);
250         // If running directly from the build tree, try to use the source
251         // directory.
252 #if (defined CMAKE_SOURCE_DIR && defined CMAKE_BINARY_DIR)
253         if (Path::startsWith(searchPath, CMAKE_BINARY_DIR))
254         {
255             std::string testPath = Path::join(CMAKE_SOURCE_DIR, "share/top");
256             if (isAcceptableLibraryPath(testPath))
257             {
258                 return testPath;
259             }
260         }
261 #endif
262
263         // Use the executable path to (try to) find the library dir.
264         while (!searchPath.empty())
265         {
266             std::string testPath = Path::join(searchPath, GMXLIB_SEARCH_DIR);
267             if (isAcceptableLibraryPath(testPath))
268             {
269                 return testPath;
270             }
271             searchPath = Path::getParentPath(searchPath);
272         }
273     }
274
275     // End of smart searching. If we didn't find it in our parent tree,
276     // or if the program name wasn't set, return a fallback.
277     return findFallbackLibraryDataPath();
278 }
279
280 //! \}
281
282 }   // namespace
283
284 /********************************************************************
285  * CommandLineProgramContext::Impl
286  */
287
288 class CommandLineProgramContext::Impl
289 {
290     public:
291         Impl();
292         Impl(int argc, const char *const argv[],
293              ExecutableEnvironmentPointer env);
294
295         /*! \brief
296          * Finds the full binary path if it isn't searched yet.
297          *
298          * Sets \a fullBinaryPath_ if it isn't set yet.
299          *
300          * The \a binaryPathMutex_ should be locked by the caller before
301          * calling this function.
302          */
303         void findBinaryPath() const;
304
305         ExecutableEnvironmentPointer  executableEnv_;
306         std::string                   invokedName_;
307         std::string                   programName_;
308         std::string                   displayName_;
309         std::string                   commandLine_;
310         mutable std::string           fullBinaryPath_;
311         mutable std::string           defaultLibraryDataPath_;
312         mutable tMPI::mutex           binaryPathMutex_;
313 };
314
315 CommandLineProgramContext::Impl::Impl()
316     : programName_("GROMACS")
317 {
318 }
319
320 CommandLineProgramContext::Impl::Impl(int argc, const char *const argv[],
321                                       ExecutableEnvironmentPointer env)
322     : executableEnv_(env)
323 {
324     invokedName_ = (argc != 0 ? argv[0] : "");
325     programName_ = Path::getFilename(invokedName_);
326     programName_ = stripSuffixIfPresent(programName_, ".exe");
327
328     commandLine_ = quoteIfNecessary(programName_.c_str());
329     for (int i = 1; i < argc; ++i)
330     {
331         commandLine_.append(" ");
332         commandLine_.append(quoteIfNecessary(argv[i]));
333     }
334 }
335
336 void CommandLineProgramContext::Impl::findBinaryPath() const
337 {
338     if (fullBinaryPath_.empty())
339     {
340         fullBinaryPath_ = findFullBinaryPath(invokedName_, *executableEnv_);
341         fullBinaryPath_ = Path::normalize(Path::resolveSymlinks(fullBinaryPath_));
342         // TODO: Investigate/Consider using a dladdr()-based solution.
343         // Potentially less portable, but significantly simpler, and also works
344         // with user binaries even if they are located in some arbitrary location,
345         // as long as shared libraries are used.
346     }
347 }
348
349 /********************************************************************
350  * CommandLineProgramContext
351  */
352
353 CommandLineProgramContext::CommandLineProgramContext()
354     : impl_(new Impl)
355 {
356 }
357
358 CommandLineProgramContext::CommandLineProgramContext(const char *binaryName)
359     : impl_(new Impl(1, &binaryName, DefaultExecutableEnvironment::create()))
360 {
361 }
362
363 CommandLineProgramContext::CommandLineProgramContext(
364         int argc, const char *const argv[])
365     : impl_(new Impl(argc, argv, DefaultExecutableEnvironment::create()))
366 {
367 }
368
369 CommandLineProgramContext::CommandLineProgramContext(
370         int argc, const char *const argv[], ExecutableEnvironmentPointer env)
371     : impl_(new Impl(argc, argv, env))
372 {
373 }
374
375 CommandLineProgramContext::~CommandLineProgramContext()
376 {
377 }
378
379 void CommandLineProgramContext::setDisplayName(const std::string &name)
380 {
381     GMX_RELEASE_ASSERT(impl_->displayName_.empty(),
382                        "Can only set display name once");
383     impl_->displayName_ = name;
384 }
385
386 const char *CommandLineProgramContext::programName() const
387 {
388     return impl_->programName_.c_str();
389 }
390
391 const char *CommandLineProgramContext::displayName() const
392 {
393     return impl_->displayName_.empty()
394            ? impl_->programName_.c_str()
395            : impl_->displayName_.c_str();
396 }
397
398 const char *CommandLineProgramContext::commandLine() const
399 {
400     return impl_->commandLine_.c_str();
401 }
402
403 const char *CommandLineProgramContext::fullBinaryPath() const
404 {
405     tMPI::lock_guard<tMPI::mutex> lock(impl_->binaryPathMutex_);
406     impl_->findBinaryPath();
407     return impl_->fullBinaryPath_.c_str();
408 }
409
410 const char *CommandLineProgramContext::defaultLibraryDataPath() const
411 {
412     tMPI::lock_guard<tMPI::mutex> lock(impl_->binaryPathMutex_);
413     if (impl_->defaultLibraryDataPath_.empty())
414     {
415         impl_->findBinaryPath();
416         impl_->defaultLibraryDataPath_ =
417             Path::normalize(findDefaultLibraryDataPath(impl_->fullBinaryPath_));
418     }
419     return impl_->defaultLibraryDataPath_.c_str();
420 }
421
422 } // namespace gmx