xref: /petsc/src/sys/error/err.c (revision 811af0c4b09a35de4306c442f88bd09fdc09897d)
1 
2 /*
3       Code that allows one to set the error handlers
4 */
5 #include <petsc/private/petscimpl.h> /*I "petscsys.h" I*/
6 #include <petscviewer.h>
7 
8 typedef struct _EH *EH;
9 struct _EH {
10   PetscErrorCode (*handler)(MPI_Comm, int, const char *, const char *, PetscErrorCode, PetscErrorType, const char *, void *);
11   void *ctx;
12   EH    previous;
13 };
14 
15 static EH eh = NULL;
16 
17 /*@C
18    PetscEmacsClientErrorHandler - Error handler that uses the emacsclient program to
19     load the file where the error occurred. Then calls the "previous" error handler.
20 
21    Not Collective
22 
23    Input Parameters:
24 +  comm - communicator over which error occurred
25 .  line - the line number of the error (indicated by __LINE__)
26 .  file - the file in which the error was detected (indicated by __FILE__)
27 .  mess - an error text string, usually just printed to the screen
28 .  n - the generic error number
29 .  p - specific error number
30 -  ctx - error handler context
31 
32    Options Database Key:
33 .   -on_error_emacs <machinename> - will contact machinename to open the Emacs client there
34 
35    Level: developer
36 
37    Note:
38    You must put (server-start) in your .emacs file for the emacsclient software to work
39 
40    Developer Note:
41    Since this is an error handler it cannot call `PetscCall()`; thus we just return if an error is detected.
42    But some of the functions it calls do perform error checking that may not be appropriate in a error handler call.
43 
44 .seealso: `PetscError()`, `PetscPushErrorHandler()`, `PetscPopErrorHandler()`, `PetscAttachDebuggerErrorHandler()`,
45           `PetscAbortErrorHandler()`, `PetscMPIAbortErrorHandler()`, `PetscTraceBackErrorHandler()`, `PetscReturnErrorHandler()`
46  @*/
47 PetscErrorCode PetscEmacsClientErrorHandler(MPI_Comm comm, int line, const char *fun, const char *file, PetscErrorCode n, PetscErrorType p, const char *mess, void *ctx) {
48   PetscErrorCode ierr;
49   char           command[PETSC_MAX_PATH_LEN];
50   const char    *pdir;
51   FILE          *fp;
52 
53   ierr = PetscGetPetscDir(&pdir);
54   if (ierr) return ierr;
55   sprintf(command, "cd %s; emacsclient --no-wait +%d %s\n", pdir, line, file);
56 #if defined(PETSC_HAVE_POPEN)
57   ierr = PetscPOpen(MPI_COMM_WORLD, (char *)ctx, command, "r", &fp);
58   if (ierr) return ierr;
59   ierr = PetscPClose(MPI_COMM_WORLD, fp);
60   if (ierr) return ierr;
61 #else
62   SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP_SYS, "Cannot run external programs on this machine");
63 #endif
64   ierr = PetscPopErrorHandler();
65   if (ierr) return ierr; /* remove this handler from the stack of handlers */
66   if (!eh) {
67     ierr = PetscTraceBackErrorHandler(comm, line, fun, file, n, p, mess, NULL);
68     if (ierr) return ierr;
69   } else {
70     ierr = (*eh->handler)(comm, line, fun, file, n, p, mess, eh->ctx);
71     if (ierr) return ierr;
72   }
73   return 0;
74 }
75 
76 /*@C
77    PetscPushErrorHandler - Sets a routine to be called on detection of errors.
78 
79    Not Collective
80 
81    Input Parameters:
82 +  handler - error handler routine
83 -  ctx - optional handler context that contains information needed by the handler (for
84          example file pointers for error messages etc.)
85 
86    Calling sequence of handler:
87 $    int handler(MPI_Comm comm,int line,char *func,char *file,PetscErrorCode n,int p,char *mess,void *ctx);
88 
89 +  comm - communicator over which error occurred
90 .  line - the line number of the error (indicated by __LINE__)
91 .  file - the file in which the error was detected (indicated by __FILE__)
92 .  n - the generic error number (see list defined in include/petscerror.h)
93 .  p - PETSC_ERROR_INITIAL if error just detected, otherwise PETSC_ERROR_REPEAT
94 .  mess - an error text string, usually just printed to the screen
95 -  ctx - the error handler context
96 
97    Options Database Keys:
98 +   -on_error_attach_debugger <noxterm,gdb or dbx> - starts up the debugger if an error occurs
99 -   -on_error_abort - aborts the program if an error occurs
100 
101    Level: intermediate
102 
103    Note:
104    The currently available PETSc error handlers include `PetscTraceBackErrorHandler()`,
105    `PetscAttachDebuggerErrorHandler()`, `PetscAbortErrorHandler()`, and `PetscMPIAbortErrorHandler()`, `PetscReturnErrorHandler()`.
106 
107    Fortran Note:
108     You can only push one error handler from Fortran before poping it.
109 
110 .seealso: `PetscPopErrorHandler()`, `PetscAttachDebuggerErrorHandler()`, `PetscAbortErrorHandler()`, `PetscTraceBackErrorHandler()`, `PetscPushSignalHandler()`
111 @*/
112 PetscErrorCode PetscPushErrorHandler(PetscErrorCode (*handler)(MPI_Comm comm, int, const char *, const char *, PetscErrorCode, PetscErrorType, const char *, void *), void *ctx) {
113   EH neweh;
114 
115   PetscFunctionBegin;
116   PetscCall(PetscNew(&neweh));
117   if (eh) neweh->previous = eh;
118   else neweh->previous = NULL;
119   neweh->handler = handler;
120   neweh->ctx     = ctx;
121   eh             = neweh;
122   PetscFunctionReturn(0);
123 }
124 
125 /*@
126    PetscPopErrorHandler - Removes the latest error handler that was
127    pushed with `PetscPushErrorHandler()`.
128 
129    Not Collective
130 
131    Level: intermediate
132 
133 .seealso: `PetscPushErrorHandler()`
134 @*/
135 PetscErrorCode PetscPopErrorHandler(void) {
136   EH tmp;
137 
138   PetscFunctionBegin;
139   if (!eh) PetscFunctionReturn(0);
140   tmp = eh;
141   eh  = eh->previous;
142   PetscCall(PetscFree(tmp));
143   PetscFunctionReturn(0);
144 }
145 
146 /*@C
147   PetscReturnErrorHandler - Error handler that causes a return without printing an error message.
148 
149    Not Collective
150 
151    Input Parameters:
152 +  comm - communicator over which error occurred
153 .  line - the line number of the error (indicated by __LINE__)
154 .  file - the file in which the error was detected (indicated by __FILE__)
155 .  mess - an error text string, usually just printed to the screen
156 .  n - the generic error number
157 .  p - specific error number
158 -  ctx - error handler context
159 
160    Level: developer
161 
162    Notes:
163    Most users need not directly employ this routine and the other error
164    handlers, but can instead use the simplified interface `SETERRQ()`, which has
165    the calling sequence
166 $     SETERRQ(comm,number,mess)
167 
168    `PetscIgnoreErrorHandler()` does the same thing as this function, but is deprecated, you should use this function.
169 
170    Use `PetscPushErrorHandler()` to set the desired error handler.
171 
172 .seealso: `PetscPushErrorHandler()`, `PetscPopErrorHandler()`, `PetscError()`, `PetscAbortErrorHandler()`, `PetscMPIAbortErrorHandler()`, `PetscTraceBackErrorHandler()`,
173           `PetscAttachDebuggerErrorHandler()`, `PetscEmacsClientErrorHandler()`
174  @*/
175 PetscErrorCode PetscReturnErrorHandler(MPI_Comm comm, int line, const char *fun, const char *file, PetscErrorCode n, PetscErrorType p, const char *mess, void *ctx) {
176   return n;
177 }
178 
179 static char        PetscErrorBaseMessage[1024];
180 /*
181        The numerical values for these are defined in include/petscerror.h; any changes
182    there must also be made here
183 */
184 static const char *PetscErrorStrings[] = {
185   /*55 */ "Out of memory",
186   "No support for this operation for this object type",
187   "No support for this operation on this system",
188   /*58 */ "Operation done in wrong order",
189   /*59 */ "Signal received",
190   /*60 */ "Nonconforming object sizes",
191   "Argument aliasing not permitted",
192   "Invalid argument",
193   /*63 */ "Argument out of range",
194   "Corrupt argument: https://petsc.org/release/faq/#valgrind",
195   "Unable to open file",
196   "Read from file failed",
197   "Write to file failed",
198   "Invalid pointer",
199   /*69 */ "Arguments must have same type",
200   /*70 */ "Attempt to use a pointer that does not point to a valid accessible location",
201   /*71 */ "Zero pivot in LU factorization: https://petsc.org/release/faq/#zeropivot",
202   /*72 */ "Floating point exception",
203   /*73 */ "Object is in wrong state",
204   "Corrupted Petsc object",
205   "Arguments are incompatible",
206   "Error in external library",
207   /*77 */ "Petsc has generated inconsistent data",
208   "Memory corruption: https://petsc.org/release/faq/#valgrind",
209   "Unexpected data in file",
210   /*80 */ "Arguments must have same communicators",
211   /*81 */ "Zero pivot in Cholesky factorization: https://petsc.org/release/faq/#zeropivot",
212   "",
213   "",
214   "Overflow in integer operation: https://petsc.org/release/faq/#64-bit-indices",
215   /*85 */ "Null argument, when expecting valid pointer",
216   /*86 */ "Unknown type. Check for miss-spelling or missing package: https://petsc.org/release/install/install/#external-packages",
217   /*87 */ "MPI library at runtime is not compatible with MPI used at compile time",
218   /*88 */ "Error in system call",
219   /*89 */ "Object Type not set: https://petsc.org/release/faq/#object-type-not-set",
220   /*90 */ "",
221   /*   */ "",
222   /*92 */ "See https://petsc.org/release/overview/linear_solve_table/ for possible LU and Cholesky solvers",
223   /*93 */ "You cannot overwrite this option since that will conflict with other previously set options",
224   /*94 */ "Example/application run with number of MPI ranks it does not support",
225   /*95 */ "Missing or incorrect user input",
226   /*96 */ "GPU resources unavailable",
227   /*97 */ "GPU error",
228   /*98 */ "General MPI error"};
229 
230 /*@C
231    PetscErrorMessage - returns the text string associated with a PETSc error code.
232 
233    Not Collective
234 
235    Input Parameter:
236 .   errnum - the error code
237 
238    Output Parameters:
239 +  text - the error message (NULL if not desired)
240 -  specific - the specific error message that was set with `SETERRQ()` or `PetscError()`.  (NULL if not desired)
241 
242    Level: developer
243 
244 .seealso: `PetscPushErrorHandler()`, `PetscAttachDebuggerErrorHandler()`, `PetscError()`, `SETERRQ()`, `PetscCall()`
245           `PetscAbortErrorHandler()`, `PetscTraceBackErrorHandler()`
246  @*/
247 PetscErrorCode PetscErrorMessage(int errnum, const char *text[], char **specific) {
248   size_t len;
249 
250   PetscFunctionBegin;
251   if (text && errnum > PETSC_ERR_MIN_VALUE && errnum < PETSC_ERR_MAX_VALUE) {
252     *text = PetscErrorStrings[errnum - PETSC_ERR_MIN_VALUE - 1];
253     PetscCall(PetscStrlen(*text, &len));
254     if (!len) *text = NULL;
255   } else if (text) *text = NULL;
256 
257   if (specific) *specific = PetscErrorBaseMessage;
258   PetscFunctionReturn(0);
259 }
260 
261 #if defined(PETSC_CLANGUAGE_CXX)
262 /* C++ exceptions are formally not allowed to propagate through extern "C" code. In practice, far too much software
263  * would be broken if implementations did not handle it it some common cases. However, keep in mind
264  *
265  *   Rule 62. Don't allow exceptions to propagate across module boundaries
266  *
267  * in "C++ Coding Standards" by Sutter and Alexandrescu. (This accounts for part of the ongoing C++ binary interface
268  * instability.) Having PETSc raise errors as C++ exceptions was probably misguided and should eventually be removed.
269  *
270  * Here is the problem: You have a C++ function call a PETSc function, and you would like to maintain the error message
271  * and stack information from the PETSc error. You could make everyone write exactly this code in their C++, but that
272  * seems crazy to me.
273  */
274 #include <sstream>
275 #include <stdexcept>
276 static void PetscCxxErrorThrow() {
277   const char *str;
278   if (eh && eh->ctx) {
279     std::ostringstream *msg;
280     msg = (std::ostringstream *)eh->ctx;
281     str = msg->str().c_str();
282   } else str = "Error detected in C PETSc";
283 
284   throw std::runtime_error(str);
285 }
286 #endif
287 
288 /*@C
289    PetscError - Routine that is called when an error has been detected, usually called through the macro SETERRQ(PETSC_COMM_SELF,).
290 
291   Collective
292 
293    Input Parameters:
294 +  comm - communicator over which error occurred.  ALL ranks of this communicator MUST call this routine
295 .  line - the line number of the error (indicated by __LINE__)
296 .  func - the function name in which the error was detected
297 .  file - the file in which the error was detected (indicated by __FILE__)
298 .  n - the generic error number
299 .  p - `PETSC_ERROR_INITIAL` indicates the error was initially detected, `PETSC_ERROR_REPEAT` indicates this is a traceback from a previously detected error
300 -  mess - formatted message string - aka printf
301 
302   Options Database Keys:
303 +  -error_output_stdout - output the error messages to stdout instead of the default stderr
304 -  -error_output_none - do not output the error messages
305 
306   Level: intermediate
307 
308    Notes:
309    PETSc error handling is done with error return codes. A non-zero return indicates an error was detected. Errors are generally not something that the code
310    can recover from. Note that numerical errors (potential divide by zero, for example) are not managed by the error return codes; they are managed via, for example,
311    `KSPGetConvergedReason()` that indicates if the solve was successful or not. The option -ksp_error_if_not_converged, for example, turns numerical failures into
312    hard errors managed via `PetscError()`.
313 
314    PETSc provides a rich supply of error handlers, see the list below, and users can also provide their own error handlers.
315 
316    Most users need not directly use this routine and the error handlers, but
317    can instead use the simplified interface `PetscCall()` or `SETERRQ()`
318 
319    Set the error handler with `PetscPushErrorHandler()`.
320 
321    Fortran Note:
322    This routine is used differently from Fortran
323 $    PetscError(MPI_Comm comm,PetscErrorCode n,PetscErrorType p,char *message)
324 
325    Developer Note:
326    Since this is called after an error condition it should not be calling any error handlers (currently it ignores any error codes)
327    BUT this routine does call regular PETSc functions that may call error handlers, this is problematic and could be fixed by never calling other PETSc routines
328    but this annoying.
329 
330 .seealso: `PetscErrorCode`, `PetscPushErrorHandler()`, `PetscPopErrorHandler()`, `PetscTraceBackErrorHandler()`, `PetscAbortErrorHandler()`, `PetscMPIAbortErrorHandler()`,
331           `PetscReturnErrorHandler()`, `PetscAttachDebuggerErrorHandler()`, `PetscEmacsClientErrorHandler()`,
332           `SETERRQ()`, `PetscCall()`, `CHKMEMQ`, `SETERRQ()`, `SETERRQ()`, `PetscErrorMessage()`, `PETSCABORT()`
333 @*/
334 PetscErrorCode PetscError(MPI_Comm comm, int line, const char *func, const char *file, PetscErrorCode n, PetscErrorType p, const char *mess, ...) {
335   va_list        Argp;
336   size_t         fullLength;
337   char           buf[2048], *lbuf = NULL;
338   PetscBool      ismain;
339   PetscErrorCode ierr;
340 
341   if (!PetscErrorHandlingInitialized) return n;
342   if (comm == MPI_COMM_NULL) comm = PETSC_COMM_SELF;
343 
344   /* Compose the message evaluating the print format */
345   if (mess) {
346     va_start(Argp, mess);
347     PetscVSNPrintf(buf, 2048, mess, &fullLength, Argp);
348     va_end(Argp);
349     lbuf = buf;
350     if (p == PETSC_ERROR_INITIAL) PetscStrncpy(PetscErrorBaseMessage, lbuf, 1023);
351   }
352 
353   if (p == PETSC_ERROR_INITIAL && n != PETSC_ERR_MEMC) PetscMallocValidate(__LINE__, PETSC_FUNCTION_NAME, __FILE__);
354 
355   if (!eh) ierr = PetscTraceBackErrorHandler(comm, line, func, file, n, p, lbuf, NULL);
356   else ierr = (*eh->handler)(comm, line, func, file, n, p, lbuf, eh->ctx);
357   PetscStackClearTop;
358 
359   /*
360       If this is called from the main() routine we call MPI_Abort() instead of
361     return to allow the parallel program to be properly shutdown.
362 
363     Does not call PETSCABORT() since that would provide the wrong source file and line number information
364   */
365   if (func) {
366     PetscStrncmp(func, "main", 4, &ismain);
367     if (ismain) {
368       if (petscwaitonerrorflg) PetscSleep(1000);
369       PETSCABORT(comm, ierr);
370     }
371   }
372 #if defined(PETSC_CLANGUAGE_CXX)
373   if (p == PETSC_ERROR_IN_CXX) PetscCxxErrorThrow();
374 #endif
375   return ierr;
376 }
377 
378 /* -------------------------------------------------------------------------*/
379 
380 /*@C
381     PetscIntView - Prints an array of integers; useful for debugging.
382 
383     Collective on viewer
384 
385     Input Parameters:
386 +   N - number of integers in array
387 .   idx - array of integers
388 -   viewer - location to print array,  `PETSC_VIEWER_STDOUT_WORLD`, `PETSC_VIEWER_STDOUT_SELF` or 0
389 
390   Level: intermediate
391 
392     Note:
393     This may be called from within the debugger
394 
395     Developer Note:
396     idx cannot be const because may be passed to binary viewer where temporary byte swapping may be done
397 
398 .seealso: `PetscViewer`, `PetscRealView()`
399 @*/
400 PetscErrorCode PetscIntView(PetscInt N, const PetscInt idx[], PetscViewer viewer) {
401   PetscMPIInt rank, size;
402   PetscInt    j, i, n = N / 20, p = N % 20;
403   PetscBool   iascii, isbinary;
404   MPI_Comm    comm;
405 
406   PetscFunctionBegin;
407   if (!viewer) viewer = PETSC_VIEWER_STDOUT_SELF;
408   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 3);
409   if (N) PetscValidIntPointer(idx, 2);
410   PetscCall(PetscObjectGetComm((PetscObject)viewer, &comm));
411   PetscCallMPI(MPI_Comm_size(comm, &size));
412   PetscCallMPI(MPI_Comm_rank(comm, &rank));
413 
414   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
415   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
416   if (iascii) {
417     PetscCall(PetscViewerASCIIPushSynchronized(viewer));
418     for (i = 0; i < n; i++) {
419       if (size > 1) {
420         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %" PetscInt_FMT ":", rank, 20 * i));
421       } else {
422         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%" PetscInt_FMT ":", 20 * i));
423       }
424       for (j = 0; j < 20; j++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %" PetscInt_FMT, idx[i * 20 + j]));
425       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
426     }
427     if (p) {
428       if (size > 1) {
429         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %" PetscInt_FMT ":", rank, 20 * n));
430       } else {
431         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%" PetscInt_FMT ":", 20 * n));
432       }
433       for (i = 0; i < p; i++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %" PetscInt_FMT, idx[20 * n + i]));
434       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
435     }
436     PetscCall(PetscViewerFlush(viewer));
437     PetscCall(PetscViewerASCIIPopSynchronized(viewer));
438   } else if (isbinary) {
439     PetscMPIInt *sizes, Ntotal, *displs, NN;
440     PetscInt    *array;
441 
442     PetscCall(PetscMPIIntCast(N, &NN));
443 
444     if (size > 1) {
445       if (rank) {
446         PetscCallMPI(MPI_Gather(&NN, 1, MPI_INT, NULL, 0, MPI_INT, 0, comm));
447         PetscCallMPI(MPI_Gatherv((void *)idx, NN, MPIU_INT, NULL, NULL, NULL, MPIU_INT, 0, comm));
448       } else {
449         PetscCall(PetscMalloc1(size, &sizes));
450         PetscCallMPI(MPI_Gather(&NN, 1, MPI_INT, sizes, 1, MPI_INT, 0, comm));
451         Ntotal = sizes[0];
452         PetscCall(PetscMalloc1(size, &displs));
453         displs[0] = 0;
454         for (i = 1; i < size; i++) {
455           Ntotal += sizes[i];
456           displs[i] = displs[i - 1] + sizes[i - 1];
457         }
458         PetscCall(PetscMalloc1(Ntotal, &array));
459         PetscCallMPI(MPI_Gatherv((void *)idx, NN, MPIU_INT, array, sizes, displs, MPIU_INT, 0, comm));
460         PetscCall(PetscViewerBinaryWrite(viewer, array, Ntotal, PETSC_INT));
461         PetscCall(PetscFree(sizes));
462         PetscCall(PetscFree(displs));
463         PetscCall(PetscFree(array));
464       }
465     } else {
466       PetscCall(PetscViewerBinaryWrite(viewer, idx, N, PETSC_INT));
467     }
468   } else {
469     const char *tname;
470     PetscCall(PetscObjectGetName((PetscObject)viewer, &tname));
471     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot handle that PetscViewer of type %s", tname);
472   }
473   PetscFunctionReturn(0);
474 }
475 
476 /*@C
477     PetscRealView - Prints an array of doubles; useful for debugging.
478 
479     Collective on viewer
480 
481     Input Parameters:
482 +   N - number of `PetscReal` in array
483 .   idx - array of `PetscReal`
484 -   viewer - location to print array,  `PETSC_VIEWER_STDOUT_WORLD`, `PETSC_VIEWER_STDOUT_SELF` or 0
485 
486   Level: intermediate
487 
488     Note:
489     This may be called from within the debugger
490 
491     Developer Note:
492     idx cannot be const because may be passed to binary viewer where temporary byte swapping may be done
493 
494 .seealso: `PetscViewer`, `PetscIntView()`
495 @*/
496 PetscErrorCode PetscRealView(PetscInt N, const PetscReal idx[], PetscViewer viewer) {
497   PetscMPIInt rank, size;
498   PetscInt    j, i, n = N / 5, p = N % 5;
499   PetscBool   iascii, isbinary;
500   MPI_Comm    comm;
501 
502   PetscFunctionBegin;
503   if (!viewer) viewer = PETSC_VIEWER_STDOUT_SELF;
504   PetscValidHeaderSpecific(viewer, PETSC_VIEWER_CLASSID, 3);
505   PetscValidRealPointer(idx, 2);
506   PetscCall(PetscObjectGetComm((PetscObject)viewer, &comm));
507   PetscCallMPI(MPI_Comm_size(comm, &size));
508   PetscCallMPI(MPI_Comm_rank(comm, &rank));
509 
510   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
511   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
512   if (iascii) {
513     PetscInt tab;
514 
515     PetscCall(PetscViewerASCIIPushSynchronized(viewer));
516     PetscCall(PetscViewerASCIIGetTab(viewer, &tab));
517     for (i = 0; i < n; i++) {
518       PetscCall(PetscViewerASCIISetTab(viewer, tab));
519       if (size > 1) {
520         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %2" PetscInt_FMT ":", rank, 5 * i));
521       } else {
522         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%2" PetscInt_FMT ":", 5 * i));
523       }
524       PetscCall(PetscViewerASCIISetTab(viewer, 0));
525       for (j = 0; j < 5; j++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %12.4e", (double)idx[i * 5 + j]));
526       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
527     }
528     if (p) {
529       PetscCall(PetscViewerASCIISetTab(viewer, tab));
530       if (size > 1) {
531         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %2" PetscInt_FMT ":", rank, 5 * n));
532       } else {
533         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%2" PetscInt_FMT ":", 5 * n));
534       }
535       PetscCall(PetscViewerASCIISetTab(viewer, 0));
536       for (i = 0; i < p; i++) PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %12.4e", (double)idx[5 * n + i]));
537       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
538     }
539     PetscCall(PetscViewerFlush(viewer));
540     PetscCall(PetscViewerASCIISetTab(viewer, tab));
541     PetscCall(PetscViewerASCIIPopSynchronized(viewer));
542   } else if (isbinary) {
543     PetscMPIInt *sizes, *displs, Ntotal, NN;
544     PetscReal   *array;
545 
546     PetscCall(PetscMPIIntCast(N, &NN));
547 
548     if (size > 1) {
549       if (rank) {
550         PetscCallMPI(MPI_Gather(&NN, 1, MPI_INT, NULL, 0, MPI_INT, 0, comm));
551         PetscCallMPI(MPI_Gatherv((PetscReal *)idx, NN, MPIU_REAL, NULL, NULL, NULL, MPIU_REAL, 0, comm));
552       } else {
553         PetscCall(PetscMalloc1(size, &sizes));
554         PetscCallMPI(MPI_Gather(&NN, 1, MPI_INT, sizes, 1, MPI_INT, 0, comm));
555         Ntotal = sizes[0];
556         PetscCall(PetscMalloc1(size, &displs));
557         displs[0] = 0;
558         for (i = 1; i < size; i++) {
559           Ntotal += sizes[i];
560           displs[i] = displs[i - 1] + sizes[i - 1];
561         }
562         PetscCall(PetscMalloc1(Ntotal, &array));
563         PetscCallMPI(MPI_Gatherv((PetscReal *)idx, NN, MPIU_REAL, array, sizes, displs, MPIU_REAL, 0, comm));
564         PetscCall(PetscViewerBinaryWrite(viewer, array, Ntotal, PETSC_REAL));
565         PetscCall(PetscFree(sizes));
566         PetscCall(PetscFree(displs));
567         PetscCall(PetscFree(array));
568       }
569     } else {
570       PetscCall(PetscViewerBinaryWrite(viewer, (void *)idx, N, PETSC_REAL));
571     }
572   } else {
573     const char *tname;
574     PetscCall(PetscObjectGetName((PetscObject)viewer, &tname));
575     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot handle that PetscViewer of type %s", tname);
576   }
577   PetscFunctionReturn(0);
578 }
579 
580 /*@C
581     PetscScalarView - Prints an array of `PetscScalar`; useful for debugging.
582 
583     Collective on viewer
584 
585     Input Parameters:
586 +   N - number of scalars in array
587 .   idx - array of scalars
588 -   viewer - location to print array,  `PETSC_VIEWER_STDOUT_WORLD`, `PETSC_VIEWER_STDOUT_SELF` or 0
589 
590   Level: intermediate
591 
592     Note:
593     This may be called from within the debugger
594 
595     Developer Note:
596     idx cannot be const because may be passed to binary viewer where byte swapping may be done
597 
598 .seealso: `PetscViewer`, `PetscIntView()`, `PetscRealView()`
599 @*/
600 PetscErrorCode PetscScalarView(PetscInt N, const PetscScalar idx[], PetscViewer viewer) {
601   PetscMPIInt rank, size;
602   PetscInt    j, i, n = N / 3, p = N % 3;
603   PetscBool   iascii, isbinary;
604   MPI_Comm    comm;
605 
606   PetscFunctionBegin;
607   if (!viewer) viewer = PETSC_VIEWER_STDOUT_SELF;
608   PetscValidHeader(viewer, 3);
609   if (N) PetscValidScalarPointer(idx, 2);
610   PetscCall(PetscObjectGetComm((PetscObject)viewer, &comm));
611   PetscCallMPI(MPI_Comm_size(comm, &size));
612   PetscCallMPI(MPI_Comm_rank(comm, &rank));
613 
614   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERASCII, &iascii));
615   PetscCall(PetscObjectTypeCompare((PetscObject)viewer, PETSCVIEWERBINARY, &isbinary));
616   if (iascii) {
617     PetscCall(PetscViewerASCIIPushSynchronized(viewer));
618     for (i = 0; i < n; i++) {
619       if (size > 1) {
620         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %2" PetscInt_FMT ":", rank, 3 * i));
621       } else {
622         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%2" PetscInt_FMT ":", 3 * i));
623       }
624       for (j = 0; j < 3; j++) {
625 #if defined(PETSC_USE_COMPLEX)
626         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " (%12.4e,%12.4e)", (double)PetscRealPart(idx[i * 3 + j]), (double)PetscImaginaryPart(idx[i * 3 + j])));
627 #else
628         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %12.4e", (double)idx[i * 3 + j]));
629 #endif
630       }
631       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
632     }
633     if (p) {
634       if (size > 1) {
635         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "[%d] %2" PetscInt_FMT ":", rank, 3 * n));
636       } else {
637         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "%2" PetscInt_FMT ":", 3 * n));
638       }
639       for (i = 0; i < p; i++) {
640 #if defined(PETSC_USE_COMPLEX)
641         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " (%12.4e,%12.4e)", (double)PetscRealPart(idx[n * 3 + i]), (double)PetscImaginaryPart(idx[n * 3 + i])));
642 #else
643         PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, " %12.4e", (double)idx[3 * n + i]));
644 #endif
645       }
646       PetscCall(PetscViewerASCIISynchronizedPrintf(viewer, "\n"));
647     }
648     PetscCall(PetscViewerFlush(viewer));
649     PetscCall(PetscViewerASCIIPopSynchronized(viewer));
650   } else if (isbinary) {
651     PetscMPIInt *sizes, Ntotal, *displs, NN;
652     PetscScalar *array;
653 
654     PetscCall(PetscMPIIntCast(N, &NN));
655 
656     if (size > 1) {
657       if (rank) {
658         PetscCallMPI(MPI_Gather(&NN, 1, MPI_INT, NULL, 0, MPI_INT, 0, comm));
659         PetscCallMPI(MPI_Gatherv((void *)idx, NN, MPIU_SCALAR, NULL, NULL, NULL, MPIU_SCALAR, 0, comm));
660       } else {
661         PetscCall(PetscMalloc1(size, &sizes));
662         PetscCallMPI(MPI_Gather(&NN, 1, MPI_INT, sizes, 1, MPI_INT, 0, comm));
663         Ntotal = sizes[0];
664         PetscCall(PetscMalloc1(size, &displs));
665         displs[0] = 0;
666         for (i = 1; i < size; i++) {
667           Ntotal += sizes[i];
668           displs[i] = displs[i - 1] + sizes[i - 1];
669         }
670         PetscCall(PetscMalloc1(Ntotal, &array));
671         PetscCallMPI(MPI_Gatherv((void *)idx, NN, MPIU_SCALAR, array, sizes, displs, MPIU_SCALAR, 0, comm));
672         PetscCall(PetscViewerBinaryWrite(viewer, array, Ntotal, PETSC_SCALAR));
673         PetscCall(PetscFree(sizes));
674         PetscCall(PetscFree(displs));
675         PetscCall(PetscFree(array));
676       }
677     } else {
678       PetscCall(PetscViewerBinaryWrite(viewer, (void *)idx, N, PETSC_SCALAR));
679     }
680   } else {
681     const char *tname;
682     PetscCall(PetscObjectGetName((PetscObject)viewer, &tname));
683     SETERRQ(PETSC_COMM_SELF, PETSC_ERR_SUP, "Cannot handle that PetscViewer of type %s", tname);
684   }
685   PetscFunctionReturn(0);
686 }
687 
688 #if defined(PETSC_HAVE_CUDA)
689 #include <petscdevice.h>
690 PETSC_EXTERN const char *PetscCUBLASGetErrorName(cublasStatus_t status) {
691   switch (status) {
692 #if (CUDART_VERSION >= 8000) /* At least CUDA 8.0 of Sep. 2016 had these */
693   case CUBLAS_STATUS_SUCCESS: return "CUBLAS_STATUS_SUCCESS";
694   case CUBLAS_STATUS_NOT_INITIALIZED: return "CUBLAS_STATUS_NOT_INITIALIZED";
695   case CUBLAS_STATUS_ALLOC_FAILED: return "CUBLAS_STATUS_ALLOC_FAILED";
696   case CUBLAS_STATUS_INVALID_VALUE: return "CUBLAS_STATUS_INVALID_VALUE";
697   case CUBLAS_STATUS_ARCH_MISMATCH: return "CUBLAS_STATUS_ARCH_MISMATCH";
698   case CUBLAS_STATUS_MAPPING_ERROR: return "CUBLAS_STATUS_MAPPING_ERROR";
699   case CUBLAS_STATUS_EXECUTION_FAILED: return "CUBLAS_STATUS_EXECUTION_FAILED";
700   case CUBLAS_STATUS_INTERNAL_ERROR: return "CUBLAS_STATUS_INTERNAL_ERROR";
701   case CUBLAS_STATUS_NOT_SUPPORTED: return "CUBLAS_STATUS_NOT_SUPPORTED";
702   case CUBLAS_STATUS_LICENSE_ERROR: return "CUBLAS_STATUS_LICENSE_ERROR";
703 #endif
704   default: return "unknown error";
705   }
706 }
707 PETSC_EXTERN const char *PetscCUSolverGetErrorName(cusolverStatus_t status) {
708   switch (status) {
709 #if (CUDART_VERSION >= 8000) /* At least CUDA 8.0 of Sep. 2016 had these */
710   case CUSOLVER_STATUS_SUCCESS: return "CUSOLVER_STATUS_SUCCESS";
711   case CUSOLVER_STATUS_NOT_INITIALIZED: return "CUSOLVER_STATUS_NOT_INITIALIZED";
712   case CUSOLVER_STATUS_INVALID_VALUE: return "CUSOLVER_STATUS_INVALID_VALUE";
713   case CUSOLVER_STATUS_ARCH_MISMATCH: return "CUSOLVER_STATUS_ARCH_MISMATCH";
714   case CUSOLVER_STATUS_INTERNAL_ERROR: return "CUSOLVER_STATUS_INTERNAL_ERROR";
715 #if (CUDART_VERSION >= 9000) /* CUDA 9.0 had these defined on June 2021 */
716   case CUSOLVER_STATUS_ALLOC_FAILED: return "CUSOLVER_STATUS_ALLOC_FAILED";
717   case CUSOLVER_STATUS_MAPPING_ERROR: return "CUSOLVER_STATUS_MAPPING_ERROR";
718   case CUSOLVER_STATUS_EXECUTION_FAILED: return "CUSOLVER_STATUS_EXECUTION_FAILED";
719   case CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED: return "CUSOLVER_STATUS_MATRIX_TYPE_NOT_SUPPORTED";
720   case CUSOLVER_STATUS_NOT_SUPPORTED: return "CUSOLVER_STATUS_NOT_SUPPORTED ";
721   case CUSOLVER_STATUS_ZERO_PIVOT: return "CUSOLVER_STATUS_ZERO_PIVOT";
722   case CUSOLVER_STATUS_INVALID_LICENSE: return "CUSOLVER_STATUS_INVALID_LICENSE";
723 #endif
724 #endif
725   default: return "unknown error";
726   }
727 }
728 PETSC_EXTERN const char *PetscCUFFTGetErrorName(cufftResult result) {
729   switch (result) {
730   case CUFFT_SUCCESS: return "CUFFT_SUCCESS";
731   case CUFFT_INVALID_PLAN: return "CUFFT_INVALID_PLAN";
732   case CUFFT_ALLOC_FAILED: return "CUFFT_ALLOC_FAILED";
733   case CUFFT_INVALID_TYPE: return "CUFFT_INVALID_TYPE";
734   case CUFFT_INVALID_VALUE: return "CUFFT_INVALID_VALUE";
735   case CUFFT_INTERNAL_ERROR: return "CUFFT_INTERNAL_ERROR";
736   case CUFFT_EXEC_FAILED: return "CUFFT_EXEC_FAILED";
737   case CUFFT_SETUP_FAILED: return "CUFFT_SETUP_FAILED";
738   case CUFFT_INVALID_SIZE: return "CUFFT_INVALID_SIZE";
739   case CUFFT_UNALIGNED_DATA: return "CUFFT_UNALIGNED_DATA";
740   case CUFFT_INCOMPLETE_PARAMETER_LIST: return "CUFFT_INCOMPLETE_PARAMETER_LIST";
741   case CUFFT_INVALID_DEVICE: return "CUFFT_INVALID_DEVICE";
742   case CUFFT_PARSE_ERROR: return "CUFFT_PARSE_ERROR";
743   case CUFFT_NO_WORKSPACE: return "CUFFT_NO_WORKSPACE";
744   case CUFFT_NOT_IMPLEMENTED: return "CUFFT_NOT_IMPLEMENTED";
745   case CUFFT_LICENSE_ERROR: return "CUFFT_LICENSE_ERROR";
746   case CUFFT_NOT_SUPPORTED: return "CUFFT_NOT_SUPPORTED";
747   default: return "unknown error";
748   }
749 }
750 #endif
751 
752 #if defined(PETSC_HAVE_HIP)
753 #include <petscdevice.h>
754 PETSC_EXTERN const char *PetscHIPBLASGetErrorName(hipblasStatus_t status) {
755   switch (status) {
756   case HIPBLAS_STATUS_SUCCESS: return "HIPBLAS_STATUS_SUCCESS";
757   case HIPBLAS_STATUS_NOT_INITIALIZED: return "HIPBLAS_STATUS_NOT_INITIALIZED";
758   case HIPBLAS_STATUS_ALLOC_FAILED: return "HIPBLAS_STATUS_ALLOC_FAILED";
759   case HIPBLAS_STATUS_INVALID_VALUE: return "HIPBLAS_STATUS_INVALID_VALUE";
760   case HIPBLAS_STATUS_ARCH_MISMATCH: return "HIPBLAS_STATUS_ARCH_MISMATCH";
761   case HIPBLAS_STATUS_MAPPING_ERROR: return "HIPBLAS_STATUS_MAPPING_ERROR";
762   case HIPBLAS_STATUS_EXECUTION_FAILED: return "HIPBLAS_STATUS_EXECUTION_FAILED";
763   case HIPBLAS_STATUS_INTERNAL_ERROR: return "HIPBLAS_STATUS_INTERNAL_ERROR";
764   case HIPBLAS_STATUS_NOT_SUPPORTED: return "HIPBLAS_STATUS_NOT_SUPPORTED";
765   default: return "unknown error";
766   }
767 }
768 #endif
769 
770 /*@
771       PetscMPIErrorString - Given an MPI error code returns the `MPI_Error_string()` appropriately
772            formatted for displaying with the PETSc error handlers.
773 
774  Input Parameter:
775 .  err - the MPI error code
776 
777  Output Parameter:
778 .  string - the MPI error message, should declare its length to be larger than `MPI_MAX_ERROR_STRING`
779 
780    Level: developer
781 
782  Note:
783     Does not return an error code or do error handling because it may be called from inside an error handler
784 
785 @*/
786 void PetscMPIErrorString(PetscMPIInt err, char *string) {
787   char        errorstring[MPI_MAX_ERROR_STRING];
788   PetscMPIInt len, j = 0;
789 
790   MPI_Error_string(err, (char *)errorstring, &len);
791   for (PetscMPIInt i = 0; i < len; i++) {
792     string[j++] = errorstring[i];
793     if (errorstring[i] == '\n') {
794       for (PetscMPIInt k = 0; k < 16; k++) string[j++] = ' ';
795     }
796   }
797   string[j] = 0;
798 }
799