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