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