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