64308a1a4cf64137efd204d0461f5df06d52b3da
[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,2015, 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  * See \linktodevmanual{relocatable-binaries,developer guide section on
40  * relocatable binaries} for explanation of the searching logic.
41  *
42  * \author Teemu Murtola <teemu.murtola@gmail.com>
43  * \ingroup module_commandline
44  */
45 #include "gmxpre.h"
46
47 #include "cmdlineprogramcontext.h"
48
49 #include "config.h"
50
51 #include <cstdlib>
52 #include <cstring>
53
54 #include <string>
55 #include <vector>
56
57 #include <boost/scoped_ptr.hpp>
58
59 #include "buildinfo.h"
60 #include "gromacs/utility/exceptions.h"
61 #include "gromacs/utility/gmxassert.h"
62 #include "gromacs/utility/mutex.h"
63 #include "gromacs/utility/path.h"
64 #include "gromacs/utility/stringutil.h"
65
66 namespace gmx
67 {
68
69 namespace
70 {
71
72 //! \addtogroup module_commandline
73 //! \{
74
75 /*! \brief
76  * Quotes a string if it contains spaces.
77  */
78 std::string quoteIfNecessary(const char *str)
79 {
80     const bool bSpaces = (std::strchr(str, ' ') != NULL);
81     if (bSpaces)
82     {
83         return formatString("'%s'", str);
84     }
85     return str;
86 }
87
88 /*! \brief
89  * Default implementation for ExecutableEnvironmentInterface.
90  *
91  * Used if ExecutableEnvironmentInterface is not explicitly provided when
92  * constructing CommandLineProgramContext.
93  */
94 class DefaultExecutableEnvironment : public ExecutableEnvironmentInterface
95 {
96     public:
97         //! Allocates a default environment.
98         static ExecutableEnvironmentPointer create()
99         {
100             return ExecutableEnvironmentPointer(new DefaultExecutableEnvironment());
101         }
102
103         DefaultExecutableEnvironment()
104             : initialWorkingDirectory_(Path::getWorkingDirectory())
105         {
106         }
107
108         virtual std::string getWorkingDirectory() const
109         {
110             return initialWorkingDirectory_;
111         }
112         virtual std::vector<std::string> getExecutablePaths() const
113         {
114             return Path::getExecutablePaths();
115         }
116
117     private:
118         std::string   initialWorkingDirectory_;
119 };
120
121 /*! \brief
122  * Finds the absolute path of the binary from \c argv[0].
123  *
124  * \param[in] invokedName \c argv[0] the binary was invoked with.
125  * \param[in] env         Executable environment.
126  * \returns   The full path of the binary.
127  *
128  * If a binary with the given name cannot be located, \p invokedName is
129  * returned.
130  */
131 std::string findFullBinaryPath(const std::string                    &invokedName,
132                                const ExecutableEnvironmentInterface &env)
133 {
134     std::string searchName = invokedName;
135     // On Windows & Cygwin we need to add the .exe extension,
136     // or we wont be able to detect that the file exists.
137 #if (defined GMX_NATIVE_WINDOWS || defined GMX_CYGWIN)
138     if (!endsWith(searchName, ".exe"))
139     {
140         searchName.append(".exe");
141     }
142 #endif
143     if (!Path::containsDirectory(searchName))
144     {
145         // No directory in name means it must be in the path - search it!
146         std::vector<std::string>                 pathEntries = env.getExecutablePaths();
147         std::vector<std::string>::const_iterator i;
148         for (i = pathEntries.begin(); i != pathEntries.end(); ++i)
149         {
150             const std::string &dir      = i->empty() ? env.getWorkingDirectory() : *i;
151             std::string        testPath = Path::join(dir, searchName);
152             if (File::exists(testPath))
153             {
154                 return testPath;
155             }
156         }
157     }
158     else if (!Path::isAbsolute(searchName))
159     {
160         // Name contains directories, but is not absolute, i.e.,
161         // it is relative to the current directory.
162         std::string cwd      = env.getWorkingDirectory();
163         std::string testPath = Path::join(cwd, searchName);
164         return testPath;
165     }
166     return searchName;
167 }
168
169 /*! \brief
170  * Returns whether given path contains files from `share/top/`.
171  *
172  * Only checks for a single file that has an uncommon enough name.
173  */
174 bool isAcceptableLibraryPath(const std::string &path)
175 {
176     return Path::exists(Path::join(path, "gurgle.dat"));
177 }
178
179 /*! \brief
180  * Returns whether given path prefix contains files from `share/top/`.
181  *
182  * \param[in]  path   Path prefix to check.
183  * \returns  `true` if \p path contains the data files.
184  *
185  * Checks whether \p path could be the installation prefix where `share/top/`
186  * files have been installed:  appends the relative installation path of the
187  * data files and calls isAcceptableLibraryPath().
188  */
189 bool isAcceptableLibraryPathPrefix(const std::string &path)
190 {
191     std::string testPath = Path::join(path, DATA_INSTALL_DIR, "top");
192     if (isAcceptableLibraryPath(testPath))
193     {
194         return true;
195     }
196     return false;
197 }
198
199 /*! \brief
200  * Returns a fallback installation prefix path.
201  *
202  * Checks a few standard locations for the data files before returning a
203  * configure-time hard-coded path.  The hard-coded path is preferred if it
204  * actually contains the data files, though.
205  */
206 std::string findFallbackInstallationPrefixPath()
207 {
208 #ifndef GMX_NATIVE_WINDOWS
209     if (!isAcceptableLibraryPathPrefix(CMAKE_INSTALL_PREFIX))
210     {
211         if (isAcceptableLibraryPathPrefix("/usr/local"))
212         {
213             return "/usr/local";
214         }
215         if (isAcceptableLibraryPathPrefix("/usr"))
216         {
217             return "/usr";
218         }
219         if (isAcceptableLibraryPathPrefix("/opt"))
220         {
221             return "/opt";
222         }
223     }
224 #endif
225     return CMAKE_INSTALL_PREFIX;
226 }
227
228 /*! \brief
229  * Generic function to find data files based on path of the binary.
230  *
231  * \param[in]  binaryPath     Absolute path to the binary.
232  * \param[out] bSourceLayout  Set to `true` if the binary is run from
233  *     the build tree and the original source directory can be found.
234  * \returns  Path to the `share/top/` data files.
235  *
236  * The search based on the path only works if the binary is in the same
237  * relative path as the installed \Gromacs binaries.  If the binary is
238  * somewhere else, a hard-coded fallback is used.  This doesn't work if the
239  * binaries are somewhere else than the path given during configure time...
240  *
241  * Extra logic is present to allow running binaries from the build tree such
242  * that they use up-to-date data files from the source tree.
243  */
244 std::string findInstallationPrefixPath(const std::string &binaryPath,
245                                        bool              *bSourceLayout)
246 {
247     *bSourceLayout = false;
248     // Don't search anything if binary cannot be found.
249     if (Path::exists(binaryPath))
250     {
251         // Remove the executable name.
252         std::string searchPath = Path::getParentPath(binaryPath);
253         // If running directly from the build tree, try to use the source
254         // directory.
255 #if (defined CMAKE_SOURCE_DIR && defined CMAKE_BINARY_DIR)
256         std::string buildBinPath;
257 #ifdef CMAKE_INTDIR /*In multi-configuration build systems the output subdirectory*/
258         buildBinPath = Path::join(CMAKE_BINARY_DIR, "bin", CMAKE_INTDIR);
259 #else
260         buildBinPath = Path::join(CMAKE_BINARY_DIR, "bin");
261 #endif
262         if (Path::isEquivalent(searchPath, buildBinPath))
263         {
264             std::string testPath = Path::join(CMAKE_SOURCE_DIR, "share/top");
265             if (isAcceptableLibraryPath(testPath))
266             {
267                 *bSourceLayout = true;
268                 return CMAKE_SOURCE_DIR;
269             }
270         }
271 #endif
272
273         // Use the executable path to (try to) find the library dir.
274         // TODO: Consider only going up exactly the required number of levels.
275         while (!searchPath.empty())
276         {
277             if (isAcceptableLibraryPathPrefix(searchPath))
278             {
279                 return searchPath;
280             }
281             searchPath = Path::getParentPath(searchPath);
282         }
283     }
284
285     // End of smart searching. If we didn't find it in our parent tree,
286     // or if the program name wasn't set, return a fallback.
287     return findFallbackInstallationPrefixPath();
288 }
289
290 //! \}
291
292 }   // namespace
293
294 /********************************************************************
295  * CommandLineProgramContext::Impl
296  */
297
298 class CommandLineProgramContext::Impl
299 {
300     public:
301         Impl();
302         Impl(int argc, const char *const argv[],
303              ExecutableEnvironmentPointer env);
304
305         /*! \brief
306          * Finds the full binary path if it isn't searched yet.
307          *
308          * Sets \a fullBinaryPath_ if it isn't set yet.
309          *
310          * The \a binaryPathMutex_ should be locked by the caller before
311          * calling this function.
312          */
313         void findBinaryPath() const;
314
315         ExecutableEnvironmentPointer  executableEnv_;
316         std::string                   invokedName_;
317         std::string                   programName_;
318         std::string                   displayName_;
319         std::string                   commandLine_;
320         mutable std::string           fullBinaryPath_;
321         mutable std::string           installationPrefix_;
322         mutable bool                  bSourceLayout_;
323         mutable Mutex                 binaryPathMutex_;
324 };
325
326 CommandLineProgramContext::Impl::Impl()
327     : programName_("GROMACS"), bSourceLayout_(false)
328 {
329 }
330
331 CommandLineProgramContext::Impl::Impl(int argc, const char *const argv[],
332                                       ExecutableEnvironmentPointer env)
333     : executableEnv_(env), bSourceLayout_(false)
334 {
335     invokedName_ = (argc != 0 ? argv[0] : "");
336     programName_ = Path::getFilename(invokedName_);
337     programName_ = stripSuffixIfPresent(programName_, ".exe");
338
339     commandLine_ = quoteIfNecessary(programName_.c_str());
340     for (int i = 1; i < argc; ++i)
341     {
342         commandLine_.append(" ");
343         commandLine_.append(quoteIfNecessary(argv[i]));
344     }
345 }
346
347 void CommandLineProgramContext::Impl::findBinaryPath() const
348 {
349     if (fullBinaryPath_.empty())
350     {
351         fullBinaryPath_ = findFullBinaryPath(invokedName_, *executableEnv_);
352         fullBinaryPath_ = Path::normalize(Path::resolveSymlinks(fullBinaryPath_));
353         // TODO: Investigate/Consider using a dladdr()-based solution.
354         // Potentially less portable, but significantly simpler, and also works
355         // with user binaries even if they are located in some arbitrary location,
356         // as long as shared libraries are used.
357     }
358 }
359
360 /********************************************************************
361  * CommandLineProgramContext
362  */
363
364 CommandLineProgramContext::CommandLineProgramContext()
365     : impl_(new Impl)
366 {
367 }
368
369 CommandLineProgramContext::CommandLineProgramContext(const char *binaryName)
370     : impl_(new Impl(1, &binaryName, DefaultExecutableEnvironment::create()))
371 {
372 }
373
374 CommandLineProgramContext::CommandLineProgramContext(
375         int argc, const char *const argv[])
376     : impl_(new Impl(argc, argv, DefaultExecutableEnvironment::create()))
377 {
378 }
379
380 CommandLineProgramContext::CommandLineProgramContext(
381         int argc, const char *const argv[], ExecutableEnvironmentPointer env)
382     : impl_(new Impl(argc, argv, env))
383 {
384 }
385
386 CommandLineProgramContext::~CommandLineProgramContext()
387 {
388 }
389
390 void CommandLineProgramContext::setDisplayName(const std::string &name)
391 {
392     GMX_RELEASE_ASSERT(impl_->displayName_.empty(),
393                        "Can only set display name once");
394     impl_->displayName_ = name;
395 }
396
397 const char *CommandLineProgramContext::programName() const
398 {
399     return impl_->programName_.c_str();
400 }
401
402 const char *CommandLineProgramContext::displayName() const
403 {
404     return impl_->displayName_.empty()
405            ? impl_->programName_.c_str()
406            : impl_->displayName_.c_str();
407 }
408
409 const char *CommandLineProgramContext::commandLine() const
410 {
411     return impl_->commandLine_.c_str();
412 }
413
414 const char *CommandLineProgramContext::fullBinaryPath() const
415 {
416     lock_guard<Mutex> lock(impl_->binaryPathMutex_);
417     impl_->findBinaryPath();
418     return impl_->fullBinaryPath_.c_str();
419 }
420
421 InstallationPrefixInfo CommandLineProgramContext::installationPrefix() const
422 {
423     lock_guard<Mutex> lock(impl_->binaryPathMutex_);
424     if (impl_->installationPrefix_.empty())
425     {
426         impl_->findBinaryPath();
427         impl_->installationPrefix_ =
428             Path::normalize(findInstallationPrefixPath(impl_->fullBinaryPath_,
429                                                        &impl_->bSourceLayout_));
430     }
431     return InstallationPrefixInfo(
432             impl_->installationPrefix_.c_str(),
433             impl_->bSourceLayout_);
434 }
435
436 } // namespace gmx