2 * This file is part of the GROMACS molecular simulation package.
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.
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 <boost/scoped_ptr.hpp>
59 #include "thread_mpi/mutex.h"
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"
74 //! \addtogroup module_commandline
78 * Quotes a string if it contains spaces.
80 std::string quoteIfNecessary(const char *str)
82 const bool bSpaces = (std::strchr(str, ' ') != NULL);
85 return formatString("'%s'", str);
91 * Default implementation for ExecutableEnvironmentInterface.
93 * Used if ExecutableEnvironmentInterface is not explicitly provided when
94 * constructing CommandLineProgramContext.
96 class DefaultExecutableEnvironment : public ExecutableEnvironmentInterface
99 //! Allocates a default environment.
100 static ExecutableEnvironmentPointer create()
102 return ExecutableEnvironmentPointer(new DefaultExecutableEnvironment());
105 DefaultExecutableEnvironment()
106 : initialWorkingDirectory_(Path::getWorkingDirectory())
110 virtual std::string getWorkingDirectory() const
112 return initialWorkingDirectory_;
114 virtual std::vector<std::string> getExecutablePaths() const
116 return Path::getExecutablePaths();
120 std::string initialWorkingDirectory_;
124 * Finds the absolute path of the binary from \c argv[0].
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.
130 * If a binary with the given name cannot be located, \p invokedName is
133 std::string findFullBinaryPath(const std::string &invokedName,
134 const ExecutableEnvironmentInterface &env)
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"))
142 searchName.append(".exe");
145 if (!Path::containsDirectory(searchName))
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)
152 const std::string &dir = i->empty() ? env.getWorkingDirectory() : *i;
153 std::string testPath = Path::join(dir, searchName);
154 if (File::exists(testPath))
160 else if (!Path::isAbsolute(searchName))
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);
172 * Returns whether given path contains files from `share/top/`.
174 * Only checks for a single file that has an uncommon enough name.
176 bool isAcceptableLibraryPath(const std::string &path)
178 return Path::exists(Path::join(path, "gurgle.dat"));
182 * Returns whether given path prefix contains files from `share/top/`.
184 * \param[in] path Path prefix to check.
185 * \returns `true` if \p path contains the data files.
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().
191 bool isAcceptableLibraryPathPrefix(const std::string &path)
193 std::string testPath = Path::join(path, DATA_INSTALL_DIR, "top");
194 if (isAcceptableLibraryPath(testPath))
202 * Returns a fallback installation prefix path.
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.
208 std::string findFallbackInstallationPrefixPath()
210 #ifndef GMX_NATIVE_WINDOWS
211 if (!isAcceptableLibraryPathPrefix(CMAKE_INSTALL_PREFIX))
213 if (isAcceptableLibraryPathPrefix("/usr/local"))
217 if (isAcceptableLibraryPathPrefix("/usr"))
221 if (isAcceptableLibraryPathPrefix("/opt"))
227 return CMAKE_INSTALL_PREFIX;
231 * Generic function to find data files based on path of the binary.
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.
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...
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.
246 std::string findInstallationPrefixPath(const std::string &binaryPath,
249 *bSourceLayout = false;
250 // Don't search anything if binary cannot be found.
251 if (Path::exists(binaryPath))
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
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);
262 buildBinPath = Path::join(CMAKE_BINARY_DIR, "bin");
264 if (Path::isEquivalent(searchPath, buildBinPath))
266 std::string testPath = Path::join(CMAKE_SOURCE_DIR, "share/top");
267 if (isAcceptableLibraryPath(testPath))
269 *bSourceLayout = true;
270 return CMAKE_SOURCE_DIR;
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())
279 if (isAcceptableLibraryPathPrefix(searchPath))
283 searchPath = Path::getParentPath(searchPath);
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();
296 /********************************************************************
297 * CommandLineProgramContext::Impl
300 class CommandLineProgramContext::Impl
304 Impl(int argc, const char *const argv[],
305 ExecutableEnvironmentPointer env);
308 * Finds the full binary path if it isn't searched yet.
310 * Sets \a fullBinaryPath_ if it isn't set yet.
312 * The \a binaryPathMutex_ should be locked by the caller before
313 * calling this function.
315 void findBinaryPath() const;
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_;
328 CommandLineProgramContext::Impl::Impl()
329 : programName_("GROMACS"), bSourceLayout_(false)
333 CommandLineProgramContext::Impl::Impl(int argc, const char *const argv[],
334 ExecutableEnvironmentPointer env)
335 : executableEnv_(env), bSourceLayout_(false)
337 invokedName_ = (argc != 0 ? argv[0] : "");
338 programName_ = Path::getFilename(invokedName_);
339 programName_ = stripSuffixIfPresent(programName_, ".exe");
341 commandLine_ = quoteIfNecessary(programName_.c_str());
342 for (int i = 1; i < argc; ++i)
344 commandLine_.append(" ");
345 commandLine_.append(quoteIfNecessary(argv[i]));
349 void CommandLineProgramContext::Impl::findBinaryPath() const
351 if (fullBinaryPath_.empty())
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.
362 /********************************************************************
363 * CommandLineProgramContext
366 CommandLineProgramContext::CommandLineProgramContext()
371 CommandLineProgramContext::CommandLineProgramContext(const char *binaryName)
372 : impl_(new Impl(1, &binaryName, DefaultExecutableEnvironment::create()))
376 CommandLineProgramContext::CommandLineProgramContext(
377 int argc, const char *const argv[])
378 : impl_(new Impl(argc, argv, DefaultExecutableEnvironment::create()))
382 CommandLineProgramContext::CommandLineProgramContext(
383 int argc, const char *const argv[], ExecutableEnvironmentPointer env)
384 : impl_(new Impl(argc, argv, env))
388 CommandLineProgramContext::~CommandLineProgramContext()
392 void CommandLineProgramContext::setDisplayName(const std::string &name)
394 GMX_RELEASE_ASSERT(impl_->displayName_.empty(),
395 "Can only set display name once");
396 impl_->displayName_ = name;
399 const char *CommandLineProgramContext::programName() const
401 return impl_->programName_.c_str();
404 const char *CommandLineProgramContext::displayName() const
406 return impl_->displayName_.empty()
407 ? impl_->programName_.c_str()
408 : impl_->displayName_.c_str();
411 const char *CommandLineProgramContext::commandLine() const
413 return impl_->commandLine_.c_str();
416 const char *CommandLineProgramContext::fullBinaryPath() const
418 tMPI::lock_guard<tMPI::mutex> lock(impl_->binaryPathMutex_);
419 impl_->findBinaryPath();
420 return impl_->fullBinaryPath_.c_str();
423 InstallationPrefixInfo CommandLineProgramContext::installationPrefix() const
425 tMPI::lock_guard<tMPI::mutex> lock(impl_->binaryPathMutex_);
426 if (impl_->installationPrefix_.empty())
428 impl_->findBinaryPath();
429 impl_->installationPrefix_ =
430 Path::normalize(findInstallationPrefixPath(impl_->fullBinaryPath_,
431 &impl_->bSourceLayout_));
433 return InstallationPrefixInfo(
434 impl_->installationPrefix_.c_str(),
435 impl_->bSourceLayout_);