lh | 9ed821d | 2023-04-07 01:36:19 -0700 | [diff] [blame] | 1 | /* Test assert_perror(). |
| 2 | * |
| 3 | * This is hairier than you'd think, involving games with |
| 4 | * stdio and signals. |
| 5 | * |
| 6 | */ |
| 7 | |
| 8 | #include <signal.h> |
| 9 | #include <stdlib.h> |
| 10 | #include <stdio.h> |
| 11 | #include <string.h> |
| 12 | #include <setjmp.h> |
| 13 | |
| 14 | jmp_buf rec; |
| 15 | char buf[160]; |
| 16 | |
| 17 | static void |
| 18 | sigabrt (int unused) |
| 19 | { |
| 20 | longjmp (rec, 1); /* recover control */ |
| 21 | } |
| 22 | |
| 23 | #undef NDEBUG |
| 24 | #include <assert.h> |
| 25 | static void |
| 26 | assert1 (void) |
| 27 | { |
| 28 | assert_perror (1); |
| 29 | } |
| 30 | |
| 31 | static void |
| 32 | assert2 (void) |
| 33 | { |
| 34 | assert_perror (0); |
| 35 | } |
| 36 | |
| 37 | #define NDEBUG |
| 38 | #include <assert.h> |
| 39 | static void |
| 40 | assert3 (void) |
| 41 | { |
| 42 | assert_perror (2); |
| 43 | } |
| 44 | |
| 45 | int |
| 46 | main(void) |
| 47 | { |
| 48 | volatile int failed = 1; /* safety in presence of longjmp() */ |
| 49 | |
| 50 | fclose (stderr); |
| 51 | stderr = tmpfile (); |
| 52 | if (!stderr) |
| 53 | abort (); |
| 54 | |
| 55 | signal (SIGABRT, sigabrt); |
| 56 | |
| 57 | if (!setjmp (rec)) |
| 58 | assert1 (); |
| 59 | else |
| 60 | failed = 0; /* should happen */ |
| 61 | |
| 62 | if (!setjmp (rec)) |
| 63 | assert2 (); |
| 64 | else |
| 65 | failed = 1; /* should not happen */ |
| 66 | |
| 67 | if (!setjmp (rec)) |
| 68 | assert3 (); |
| 69 | else |
| 70 | failed = 1; /* should not happen */ |
| 71 | |
| 72 | rewind (stderr); |
| 73 | fgets (buf, 160, stderr); |
| 74 | if (!strstr(buf, strerror (1))) |
| 75 | failed = 1; |
| 76 | |
| 77 | fgets (buf, 160, stderr); |
| 78 | if (strstr (buf, strerror (0))) |
| 79 | failed = 1; |
| 80 | |
| 81 | fgets (buf, 160, stderr); |
| 82 | if (strstr (buf, strerror (2))) |
| 83 | failed = 1; |
| 84 | |
| 85 | return failed; |
| 86 | } |