2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2012,2013,2014,2015,2016,2017, 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.
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.
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.
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.
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.
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.
37 * Implements gmx::CommandLineProgramContext.
39 * See \linktodevmanual{relocatable-binaries,developer guide section on
40 * relocatable binaries} for explanation of the searching logic.
42 * \author Teemu Murtola <teemu.murtola@gmail.com>
43 * \ingroup module_commandline
47 #include "cmdlineprogramcontext.h"
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"
70 //! \addtogroup module_commandline
74 * Quotes a string if it contains spaces.
76 std::string quoteIfNecessary(const char *str)
78 const bool bSpaces = (std::strchr(str, ' ') != nullptr);
81 return formatString("'%s'", str);
87 * Default implementation for IExecutableEnvironment.
89 * Used if IExecutableEnvironment is not explicitly provided when
90 * constructing CommandLineProgramContext.
92 class DefaultExecutableEnvironment : public IExecutableEnvironment
95 //! Allocates a default environment.
96 static ExecutableEnvironmentPointer create()
98 return ExecutableEnvironmentPointer(new DefaultExecutableEnvironment());
101 DefaultExecutableEnvironment()
102 : initialWorkingDirectory_(Path::getWorkingDirectory())
106 virtual std::string getWorkingDirectory() const
108 return initialWorkingDirectory_;
110 virtual std::vector<std::string> getExecutablePaths() const
112 return Path::getExecutablePaths();
116 std::string initialWorkingDirectory_;
120 * Finds the absolute path of the binary from \c argv[0].
122 * \param[in] invokedName \c argv[0] the binary was invoked with.
123 * \param[in] env Executable environment.
124 * \returns The full path of the binary.
126 * If a binary with the given name cannot be located, \p invokedName is
129 std::string findFullBinaryPath(const std::string &invokedName,
130 const IExecutableEnvironment &env)
132 std::string searchName = invokedName;
133 // On Windows & Cygwin we need to add the .exe extension,
134 // or we wont be able to detect that the file exists.
135 #if GMX_NATIVE_WINDOWS || GMX_CYGWIN
136 if (!endsWith(searchName, ".exe"))
138 searchName.append(".exe");
141 if (!Path::containsDirectory(searchName))
143 // No directory in name means it must be in the path - search it!
144 std::vector<std::string> pathEntries = env.getExecutablePaths();
145 std::vector<std::string>::const_iterator i;
146 for (i = pathEntries.begin(); i != pathEntries.end(); ++i)
148 const std::string &dir = i->empty() ? env.getWorkingDirectory() : *i;
149 std::string testPath = Path::join(dir, searchName);
150 if (File::exists(testPath, File::returnFalseOnError))
156 else if (!Path::isAbsolute(searchName))
158 // Name contains directories, but is not absolute, i.e.,
159 // it is relative to the current directory.
160 std::string cwd = env.getWorkingDirectory();
161 std::string testPath = Path::join(cwd, searchName);
168 * Returns whether given path contains files from `share/top/`.
170 * Only checks for a single file that has an uncommon enough name.
172 bool isAcceptableLibraryPath(const std::string &path)
174 return Path::exists(Path::join(path, "residuetypes.dat"));
178 * Returns whether given path prefix contains files from `share/top/`.
180 * \param[in] path Path prefix to check.
181 * \returns `true` if \p path contains the data files.
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().
187 bool isAcceptableLibraryPathPrefix(const std::string &path)
189 std::string testPath = Path::join(path, DATA_INSTALL_DIR, "top");
190 if (isAcceptableLibraryPath(testPath))
198 * Returns a fallback installation prefix path.
200 * Checks a few standard locations for the data files before returning a
201 * configure-time hard-coded path. The hard-coded path is preferred if it
202 * actually contains the data files, though.
204 std::string findFallbackInstallationPrefixPath()
206 #if !GMX_NATIVE_WINDOWS
207 if (!isAcceptableLibraryPathPrefix(CMAKE_INSTALL_PREFIX))
209 if (isAcceptableLibraryPathPrefix("/usr/local"))
213 if (isAcceptableLibraryPathPrefix("/usr"))
217 if (isAcceptableLibraryPathPrefix("/opt"))
223 return CMAKE_INSTALL_PREFIX;
227 * Generic function to find data files based on path of the binary.
229 * \param[in] binaryPath Absolute path to the binary.
230 * \param[out] bSourceLayout Set to `true` if the binary is run from
231 * the build tree and the original source directory can be found.
232 * \returns Path to the `share/top/` data files.
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...
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.
242 std::string findInstallationPrefixPath(const std::string &binaryPath,
245 *bSourceLayout = false;
246 // Don't search anything if binary cannot be found.
247 if (Path::exists(binaryPath))
249 // Remove the executable name.
250 std::string searchPath = Path::getParentPath(binaryPath);
251 // If running directly from the build tree, try to use the source
253 #if (defined CMAKE_SOURCE_DIR && defined CMAKE_BINARY_DIR)
254 std::string buildBinPath;
255 #ifdef CMAKE_INTDIR /*In multi-configuration build systems the output subdirectory*/
256 buildBinPath = Path::join(CMAKE_BINARY_DIR, "bin", CMAKE_INTDIR);
258 buildBinPath = Path::join(CMAKE_BINARY_DIR, "bin");
260 if (Path::isEquivalent(searchPath, buildBinPath))
262 std::string testPath = Path::join(CMAKE_SOURCE_DIR, "share/top");
263 if (isAcceptableLibraryPath(testPath))
265 *bSourceLayout = true;
266 return CMAKE_SOURCE_DIR;
271 // Use the executable path to (try to) find the library dir.
272 // TODO: Consider only going up exactly the required number of levels.
273 while (!searchPath.empty())
275 if (isAcceptableLibraryPathPrefix(searchPath))
279 searchPath = Path::getParentPath(searchPath);
283 // End of smart searching. If we didn't find it in our parent tree,
284 // or if the program name wasn't set, return a fallback.
285 return findFallbackInstallationPrefixPath();
292 /********************************************************************
293 * CommandLineProgramContext::Impl
296 class CommandLineProgramContext::Impl
300 Impl(int argc, const char *const argv[],
301 ExecutableEnvironmentPointer env);
304 * Finds the full binary path if it isn't searched yet.
306 * Sets \a fullBinaryPath_ if it isn't set yet.
308 * The \a binaryPathMutex_ should be locked by the caller before
309 * calling this function.
311 void findBinaryPath() const;
313 ExecutableEnvironmentPointer executableEnv_;
314 std::string invokedName_;
315 std::string programName_;
316 std::string displayName_;
317 std::string commandLine_;
318 mutable std::string fullBinaryPath_;
319 mutable std::string installationPrefix_;
320 mutable bool bSourceLayout_;
321 mutable Mutex binaryPathMutex_;
324 CommandLineProgramContext::Impl::Impl()
325 : programName_("GROMACS"), bSourceLayout_(false)
329 CommandLineProgramContext::Impl::Impl(int argc, const char *const argv[],
330 ExecutableEnvironmentPointer env)
331 : executableEnv_(std::move(env)), invokedName_(argc != 0 ? argv[0] : ""), bSourceLayout_(false)
333 programName_ = Path::getFilename(invokedName_);
334 programName_ = stripSuffixIfPresent(programName_, ".exe");
336 commandLine_ = quoteIfNecessary(programName_.c_str());
337 for (int i = 1; i < argc; ++i)
339 commandLine_.append(" ");
340 commandLine_.append(quoteIfNecessary(argv[i]));
344 void CommandLineProgramContext::Impl::findBinaryPath() const
346 if (fullBinaryPath_.empty())
348 fullBinaryPath_ = findFullBinaryPath(invokedName_, *executableEnv_);
349 fullBinaryPath_ = Path::normalize(Path::resolveSymlinks(fullBinaryPath_));
350 // TODO: Investigate/Consider using a dladdr()-based solution.
351 // Potentially less portable, but significantly simpler, and also works
352 // with user binaries even if they are located in some arbitrary location,
353 // as long as shared libraries are used.
357 /********************************************************************
358 * CommandLineProgramContext
361 CommandLineProgramContext::CommandLineProgramContext()
366 CommandLineProgramContext::CommandLineProgramContext(const char *binaryName)
367 : impl_(new Impl(1, &binaryName, DefaultExecutableEnvironment::create()))
371 CommandLineProgramContext::CommandLineProgramContext(
372 int argc, const char *const argv[])
373 : impl_(new Impl(argc, argv, DefaultExecutableEnvironment::create()))
377 CommandLineProgramContext::CommandLineProgramContext(
378 int argc, const char *const argv[], ExecutableEnvironmentPointer env)
379 : impl_(new Impl(argc, argv, move(env)))
383 CommandLineProgramContext::~CommandLineProgramContext()
387 void CommandLineProgramContext::setDisplayName(const std::string &name)
389 GMX_RELEASE_ASSERT(impl_->displayName_.empty(),
390 "Can only set display name once");
391 impl_->displayName_ = name;
394 const char *CommandLineProgramContext::programName() const
396 return impl_->programName_.c_str();
399 const char *CommandLineProgramContext::displayName() const
401 return impl_->displayName_.empty()
402 ? impl_->programName_.c_str()
403 : impl_->displayName_.c_str();
406 const char *CommandLineProgramContext::commandLine() const
408 return impl_->commandLine_.c_str();
411 const char *CommandLineProgramContext::fullBinaryPath() const
413 lock_guard<Mutex> lock(impl_->binaryPathMutex_);
414 impl_->findBinaryPath();
415 return impl_->fullBinaryPath_.c_str();
418 InstallationPrefixInfo CommandLineProgramContext::installationPrefix() const
420 lock_guard<Mutex> lock(impl_->binaryPathMutex_);
421 if (impl_->installationPrefix_.empty())
423 impl_->findBinaryPath();
424 impl_->installationPrefix_ =
425 Path::normalize(findInstallationPrefixPath(impl_->fullBinaryPath_,
426 &impl_->bSourceLayout_));
428 return InstallationPrefixInfo(
429 impl_->installationPrefix_.c_str(),
430 impl_->bSourceLayout_);