784cf34b250af31a72a9f86641773dc011d34cd5
[alexxy/gromacs.git] / src / gromacs / utility / exceptions.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2011-2018, The GROMACS development team.
5  * Copyright (c) 2019,2020, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \internal \file
37  * \brief
38  * Implements classes and functions in exceptions.h.
39  *
40  * \author Teemu Murtola <teemu.murtola@gmail.com>
41  * \ingroup module_utility
42  */
43 #include "gmxpre.h"
44
45 #include "gromacs/utility/exceptions.h"
46
47 #include <cstring>
48
49 #include <map>
50 #include <memory>
51 #include <new>
52 #include <stdexcept>
53 #include <typeinfo>
54
55 #include "thread_mpi/system_error.h"
56
57 #include "gromacs/utility/basenetwork.h"
58 #include "gromacs/utility/fatalerror.h"
59 #include "gromacs/utility/gmxassert.h"
60 #include "gromacs/utility/stringutil.h"
61 #include "gromacs/utility/textwriter.h"
62
63 #include "errorcodes.h"
64 #include "errorformat.h"
65
66 namespace gmx
67 {
68
69 namespace internal
70 {
71
72 IExceptionInfo::~IExceptionInfo() {}
73
74 class ExceptionData
75 {
76 public:
77     std::map<std::type_index, ExceptionInfoPointer> infos_;
78 };
79
80 } // namespace internal
81
82 namespace
83 {
84
85 /********************************************************************
86  * ErrorMessage
87  */
88
89 /*! \brief
90  * Error message or error context text item.
91  *
92  * Error messages for an exception are represented as a chain of ErrorMessage
93  * objects: the elements at the bottom of the chain (with no children) is the
94  * error message, and other elements are the context strings added.
95  *
96  * \ingroup module_utility
97  */
98 class ErrorMessage
99 {
100 public:
101     /*! \brief
102      * Creates an error message object with the specified text.
103      *
104      * \param[in] text  Text for the message.
105      */
106     explicit ErrorMessage(const std::string& text);
107
108     //! Whether this object is a context string.
109     bool isContext() const { return static_cast<bool>(child_); }
110     //! Returns the text for this object.
111     const std::string& text() const { return text_; }
112     /*! \brief
113      * Returns the child object for a context object.
114      *
115      * Must not be called if isContext() returns false.
116      */
117     const ErrorMessage& child() const
118     {
119         GMX_ASSERT(isContext(), "Attempting to access nonexistent message object");
120         return *child_;
121     }
122
123     /*! \brief
124      * Creates a new message object with context prepended.
125      *
126      * \param[in] context  Context string to add.
127      * \returns   New error message object that has \p context as its text
128      *      and \c this as its child.
129      * \throws    std::bad_alloc if out of memory.
130      */
131     ErrorMessage prependContext(const std::string& context) const;
132
133 private:
134     std::string                   text_;
135     std::shared_ptr<ErrorMessage> child_;
136 };
137
138 /*! \internal \brief
139  * Stores a reason or the top-most context string of an exception.
140  *
141  * \ingroup module_utility
142  */
143 typedef ExceptionInfo<struct ExceptionInfoMessage_, ErrorMessage> ExceptionInfoMessage;
144
145 ErrorMessage::ErrorMessage(const std::string& text) : text_(text)
146 {
147     size_t length = text_.find_last_not_of(" \n");
148     if (length == std::string::npos)
149     {
150         length = text_.length() - 1;
151     }
152     text_.resize(length + 1);
153 }
154
155 ErrorMessage ErrorMessage::prependContext(const std::string& context) const
156 {
157     ErrorMessage newMessage(context);
158     newMessage.child_ = std::make_shared<ErrorMessage>(*this);
159     return newMessage;
160 }
161
162 /*! \brief
163  * Stores list of nested exceptions for Gromacs exceptions.
164  *
165  * \ingroup module_utility
166  */
167 typedef ExceptionInfo<struct ExceptionInfoNestedExceptions_, internal::NestedExceptionList> ExceptionInfoNestedExceptions;
168
169 } // namespace
170
171 /********************************************************************
172  * GromacsException
173  */
174
175 GromacsException::GromacsException(const ExceptionInitializer& details) :
176     data_(new internal::ExceptionData)
177 {
178     setInfo(ExceptionInfoMessage(ErrorMessage(details.reason_)));
179     if (details.hasNestedExceptions())
180     {
181         setInfo(ExceptionInfoNestedExceptions(details.nested_));
182     }
183 }
184
185 const char* GromacsException::what() const noexcept
186 {
187     const ErrorMessage* msg = getInfo<ExceptionInfoMessage>();
188     if (msg == nullptr)
189     {
190         return "No reason provided";
191     }
192     while (msg->isContext())
193     {
194         msg = &msg->child();
195     }
196     return msg->text().c_str();
197 }
198
199 void GromacsException::prependContext(const std::string& context)
200 {
201     const ErrorMessage* msg = getInfo<ExceptionInfoMessage>();
202     GMX_RELEASE_ASSERT(msg != nullptr, "Message should always be set");
203     setInfo(ExceptionInfoMessage(msg->prependContext(context)));
204 }
205
206 const internal::IExceptionInfo* GromacsException::getInfo(const std::type_index& index) const
207 {
208     auto iter = data_->infos_.find(index);
209     if (iter != data_->infos_.end())
210     {
211         return iter->second.get();
212     }
213     return nullptr;
214 }
215
216 void GromacsException::setInfo(const std::type_index& index, internal::ExceptionInfoPointer&& item)
217 {
218     data_->infos_[index] = std::move(item);
219 }
220
221 /********************************************************************
222  * Derived exception classes
223  */
224
225 int FileIOError::errorCode() const
226 {
227     return eeFileIO;
228 }
229
230 int InvalidInputError::errorCode() const
231 {
232     return eeInvalidInput;
233 }
234
235 int InconsistentInputError::errorCode() const
236 {
237     return eeInconsistentInput;
238 }
239
240 int ToleranceError::errorCode() const
241 {
242     return eeTolerance;
243 }
244
245 int SimulationInstabilityError::errorCode() const
246 {
247     return eeInstability;
248 }
249
250 int InternalError::errorCode() const
251 {
252     return eeInternalError;
253 }
254
255 int APIError::errorCode() const
256 {
257     return eeAPIError;
258 }
259
260 int RangeError::errorCode() const
261 {
262     return eeRange;
263 }
264
265 int NotImplementedError::errorCode() const
266 {
267     return eeNotImplemented;
268 }
269
270 int ParallelConsistencyError::errorCode() const
271 {
272     return eeParallelConsistency;
273 }
274
275 int ModularSimulatorError::errorCode() const
276 {
277     return eeModularSimulator;
278 }
279
280
281 /********************************************************************
282  * Global functions
283  */
284
285 namespace
286 {
287
288 //! \addtogroup module_utility
289 //! \{
290
291 /*! \brief
292  * Abstracts actual output from the other logic in exception formatting.
293  *
294  * Object that implements this interface is passed to
295  * formatExceptionMessageInternal(), and is responsible for composing the
296  * output.  This allows using the same implementation of interpreting the
297  * exceptions while still supporting output to different formats (e.g., to a
298  * string or to \c stderr).
299  */
300 class IMessageWriter
301 {
302 public:
303     virtual ~IMessageWriter() {}
304
305     /*! \brief
306      * Writes a single line of text into the output.
307      *
308      * \param[in] text    Text to write on the line.
309      * \param[in] indent  Suggested number of spaces to indent the line.
310      */
311     virtual void writeLine(const char* text, int indent) = 0;
312     /*! \brief
313      * Writes information about a system error (errno-based).
314      *
315      * \param[in] errorNumber  errno value
316      * \param[in] funcName     Name of the system call (can be NULL).
317      * \param[in] indent       Suggested number of spaces to indent the output.
318      */
319     virtual void writeErrNoInfo(int errorNumber, const char* funcName, int indent) = 0;
320 };
321
322 /*! \brief
323  * Exception information writer for cases where exceptions should be avoided.
324  *
325  * Formats the messages into the provided FILE handle without checking for
326  * errors in std::fprintf() calls.
327  */
328 class MessageWriterFileNoThrow : public IMessageWriter
329 {
330 public:
331     //! Initializes a writer that writes to the given file handle.
332     explicit MessageWriterFileNoThrow(FILE* fp) : fp_(fp) {}
333
334     void writeLine(const char* text, int indent) override
335     {
336         internal::printFatalErrorMessageLine(fp_, text, indent);
337     }
338     void writeErrNoInfo(int errorNumber, const char* funcName, int indent) override
339     {
340         std::fprintf(fp_, "%*sReason: %s\n", indent, "", std::strerror(errorNumber));
341         if (funcName != nullptr)
342         {
343             std::fprintf(fp_, "%*s(call to %s() returned error code %d)\n", indent, "", funcName,
344                          errorNumber);
345         }
346     }
347
348 private:
349     FILE* fp_;
350 };
351
352 /*! \brief
353  * Exception information writer to format into a TextOutputStream.
354  */
355 class MessageWriterTextWriter : public IMessageWriter
356 {
357 public:
358     //! Initializes a writer that writes to the given stream.
359     explicit MessageWriterTextWriter(TextWriter* writer) : writer_(writer) {}
360
361     void writeLine(const char* text, int indent) override
362     {
363         writer_->wrapperSettings().setIndent(indent);
364         writer_->writeLine(text);
365     }
366     void writeErrNoInfo(int errorNumber, const char* funcName, int indent) override
367     {
368         writer_->wrapperSettings().setIndent(indent);
369         writer_->writeLine(formatString("Reason: %s", std::strerror(errorNumber)));
370         if (funcName != nullptr)
371         {
372             writer_->writeLine(formatString("(call to %s() returned error code %d)", funcName, errorNumber));
373         }
374     }
375
376 private:
377     TextWriter* writer_;
378 };
379
380 /*! \brief
381  * Exception information writer to format into an std::string.
382  */
383 class MessageWriterString : public IMessageWriter
384 {
385 public:
386     //! Post-processes the output string to not end in a line feed.
387     void removeTerminatingLineFeed()
388     {
389         if (!result_.empty())
390         {
391             result_.erase(result_.size() - 1);
392         }
393     }
394     //! Returns the constructed string.
395     const std::string& result() const { return result_; }
396
397     void writeLine(const char* text, int indent) override
398     {
399         result_.append(indent, ' ');
400         result_.append(text);
401         result_.append("\n");
402     }
403     void writeErrNoInfo(int errorNumber, const char* funcName, int indent) override
404     {
405         writeLine(formatString("Reason: %s", std::strerror(errorNumber)).c_str(), indent);
406         if (funcName != nullptr)
407         {
408             writeLine(formatString("(call to %s() returned error code %d)", funcName, errorNumber).c_str(),
409                       indent);
410         }
411     }
412
413 private:
414     std::string result_;
415 };
416
417 /*! \brief
418  * Prints error information for an exception object.
419  *
420  * \param[in] writer  Writer to write out the information.
421  * \param[in] ex      Exception object to print.
422  * \param[in] indent  Indentation for the information.
423  *
424  * If the exception contains nested exceptions, information from them is
425  * recursively printed.
426  *
427  * Does not throw unless the writer throws.
428  */
429 void formatExceptionMessageInternal(IMessageWriter* writer, const std::exception& ex, int indent)
430 {
431     const GromacsException* gmxEx = dynamic_cast<const GromacsException*>(&ex);
432     if (gmxEx != nullptr)
433     {
434         // TODO: Add an option to print location information for the tests
435
436         // std::string        result;
437         // if (filePtr != NULL && linePtr != NULL)
438         // {
439         //     result = formatString("%s:%d: %s\n", *filePtr, *linePtr,
440         //                           funcPtr != NULL ? *funcPtr : "");
441         // }
442
443         bool bAnythingWritten = false;
444         // TODO: Remove duplicate context if present in multiple nested exceptions.
445         const ErrorMessage* msg = gmxEx->getInfo<ExceptionInfoMessage>();
446         if (msg != nullptr)
447         {
448             while (msg != nullptr && msg->isContext())
449             {
450                 writer->writeLine(msg->text().c_str(), indent * 2);
451                 ++indent;
452                 msg = &msg->child();
453             }
454             if (msg != nullptr && !msg->text().empty())
455             {
456                 writer->writeLine(msg->text().c_str(), indent * 2);
457                 bAnythingWritten = true;
458             }
459         }
460         else
461         {
462             writer->writeLine(ex.what(), indent * 2);
463             bAnythingWritten = true;
464         }
465
466         const int* errorNumber = gmxEx->getInfo<ExceptionInfoErrno>();
467         if (errorNumber != nullptr && *errorNumber != 0)
468         {
469             const char* const* funcName = gmxEx->getInfo<ExceptionInfoApiFunction>();
470             writer->writeErrNoInfo(*errorNumber, funcName != nullptr ? *funcName : nullptr,
471                                    (indent + 1) * 2);
472             bAnythingWritten = true;
473         }
474
475         const internal::NestedExceptionList* nested = gmxEx->getInfo<ExceptionInfoNestedExceptions>();
476         if (nested != nullptr)
477         {
478             internal::NestedExceptionList::const_iterator ni;
479             for (ni = nested->begin(); ni != nested->end(); ++ni)
480             {
481                 try
482                 {
483                     std::rethrow_exception(*ni);
484                 }
485                 catch (const std::exception& nestedEx)
486                 {
487                     const int newIndent = indent + (bAnythingWritten ? 1 : 0);
488                     formatExceptionMessageInternal(writer, nestedEx, newIndent);
489                 }
490             }
491         }
492     }
493     else
494     {
495         writer->writeLine(ex.what(), indent * 2);
496     }
497 }
498
499 //! \}
500
501 } // namespace
502
503 void printFatalErrorMessage(FILE* fp, const std::exception& ex)
504 {
505     const char*             title      = "Unknown exception";
506     bool                    bPrintType = false;
507     const GromacsException* gmxEx      = dynamic_cast<const GromacsException*>(&ex);
508     // TODO: Treat more of the standard exceptions
509     if (gmxEx != nullptr)
510     {
511         title = getErrorCodeString(gmxEx->errorCode());
512     }
513     else if (dynamic_cast<const tMPI::system_error*>(&ex) != nullptr)
514     {
515         title = "System error in thread synchronization";
516     }
517     else if (dynamic_cast<const std::bad_alloc*>(&ex) != nullptr)
518     {
519         title = "Memory allocation failed";
520     }
521     else if (dynamic_cast<const std::logic_error*>(&ex) != nullptr)
522     {
523         title      = "Standard library logic error (bug)";
524         bPrintType = true;
525     }
526     else if (dynamic_cast<const std::runtime_error*>(&ex) != nullptr)
527     {
528         title      = "Standard library runtime error (possible bug)";
529         bPrintType = true;
530     }
531     else
532     {
533         bPrintType = true;
534     }
535     const char* func = nullptr;
536     const char* file = nullptr;
537     int         line = 0;
538     if (gmxEx != nullptr)
539     {
540         const ThrowLocation* loc = gmxEx->getInfo<ExceptionInfoLocation>();
541         if (loc != nullptr)
542         {
543             func = loc->func;
544             file = loc->file;
545             line = loc->line;
546         }
547     }
548     internal::printFatalErrorHeader(fp, title, func, file, line);
549     if (bPrintType)
550     {
551         std::fprintf(fp, "(exception type: %s)\n", typeid(ex).name());
552     }
553     MessageWriterFileNoThrow writer(fp);
554     formatExceptionMessageInternal(&writer, ex, 0);
555     internal::printFatalErrorFooter(fp);
556 }
557
558 std::string formatExceptionMessageToString(const std::exception& ex)
559 {
560     MessageWriterString writer;
561     formatExceptionMessageInternal(&writer, ex, 0);
562     writer.removeTerminatingLineFeed();
563     return writer.result();
564 }
565
566 void formatExceptionMessageToFile(FILE* fp, const std::exception& ex)
567 {
568     MessageWriterFileNoThrow writer(fp);
569     formatExceptionMessageInternal(&writer, ex, 0);
570 }
571
572 void formatExceptionMessageToWriter(TextWriter* writer, const std::exception& ex)
573 {
574     MessageWriterTextWriter messageWriter(writer);
575     formatExceptionMessageInternal(&messageWriter, ex, 0);
576 }
577
578 int processExceptionAtExit(const std::exception& /*ex*/)
579 {
580     int returnCode = 1;
581     // If we have more than one rank (whether real MPI or thread-MPI),
582     // we cannot currently know whether just one rank or all ranks
583     // actually threw the error, so we need to exit here.
584     // Returning would mean graceful cleanup, which is not possible if
585     // some code is still executing on other ranks/threads.
586     if (gmx_node_num() > 1)
587     {
588         gmx_exit_on_fatal_error(ExitType_Abort, returnCode);
589     }
590     return returnCode;
591 }
592
593 void processExceptionAsFatalError(const std::exception& ex)
594 {
595     printFatalErrorMessage(stderr, ex);
596     gmx_exit_on_fatal_error(ExitType_Abort, 1);
597 }
598
599 } // namespace gmx