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