1 /*
2  * Copyright (c) 2011-2018 Scott Vokes <vokes.s@gmail.com>
3  *
4  * Permission to use, copy, modify, and/or distribute this software for any
5  * purpose with or without fee is hereby granted, provided that the above
6  * copyright notice and this permission notice appear in all copies.
7  *
8  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
9  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
10  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
11  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
12  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
13  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
14  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
15  */
16 
17 #ifndef GREATEST_H
18 #define GREATEST_H
19 
20 #if defined(__cplusplus) && !defined(GREATEST_NO_EXTERN_CPLUSPLUS)
21 extern "C" {
22 #endif
23 
main(int,char **)24 /* 1.4.0 */
25 #define GREATEST_VERSION_MAJOR 1
26 #define GREATEST_VERSION_MINOR 4
27 #define GREATEST_VERSION_PATCH 0
28 
29 /* A unit testing system for C, contained in 1 file.
30  * It doesn't use dynamic allocation or depend on anything
31  * beyond ANSI C89.
32  *
33  * An up-to-date version can be found at:
34  *     https://github.com/silentbicycle/greatest/
35  */
36 
37 
38 /*********************************************************************
39  * Minimal test runner template
40  *********************************************************************/
41 #if 0
42 
43 #include "greatest.h"
44 
45 TEST foo_should_foo(void) {
46     PASS();
47 }
48 
49 static void setup_cb(void *data) {
50     printf("setup callback for each test case\n");
51 }
52 
53 static void teardown_cb(void *data) {
54     printf("teardown callback for each test case\n");
55 }
56 
57 SUITE(suite) {
58     /* Optional setup/teardown callbacks which will be run before/after
59      * every test case. If using a test suite, they will be cleared when
60      * the suite finishes. */
61     SET_SETUP(setup_cb, voidp_to_callback_data);
62     SET_TEARDOWN(teardown_cb, voidp_to_callback_data);
63 
64     RUN_TEST(foo_should_foo);
65 }
66 
67 /* Add definitions that need to be in the test runner's main file. */
68 GREATEST_MAIN_DEFS();
69 
70 /* Set up, run suite(s) of tests, report pass/fail/skip stats. */
71 int run_tests(void) {
72     GREATEST_INIT();            /* init. greatest internals */
73     /* List of suites to run (if any). */
74     RUN_SUITE(suite);
75 
76     /* Tests can also be run directly, without using test suites. */
77     RUN_TEST(foo_should_foo);
78 
79     GREATEST_PRINT_REPORT();          /* display results */
80     return greatest_all_passed();
81 }
82 
83 /* main(), for a standalone command-line test runner.
84  * This replaces run_tests above, and adds command line option
85  * handling and exiting with a pass/fail status. */
86 int main(int argc, char **argv) {
87     GREATEST_MAIN_BEGIN();      /* init & parse command-line args */
88     RUN_SUITE(suite);
89     GREATEST_MAIN_END();        /* display results */
90 }
91 
92 #endif
93 /*********************************************************************/
94 
95 
96 #include <stdlib.h>
97 #include <stdio.h>
98 #include <string.h>
99 #include <ctype.h>
100 
101 /***********
102  * Options *
103  ***********/
104 
105 /* Default column width for non-verbose output. */
106 #ifndef GREATEST_DEFAULT_WIDTH
107 #define GREATEST_DEFAULT_WIDTH 72
108 #endif
109 
110 /* FILE *, for test logging. */
111 #ifndef GREATEST_STDOUT
112 #define GREATEST_STDOUT stdout
113 #endif
114 
115 /* Remove GREATEST_ prefix from most commonly used symbols? */
116 #ifndef GREATEST_USE_ABBREVS
117 #define GREATEST_USE_ABBREVS 1
118 #endif
119 
120 /* Set to 0 to disable all use of setjmp/longjmp. */
121 #ifndef GREATEST_USE_LONGJMP
122 #define GREATEST_USE_LONGJMP 1
123 #endif
124 
125 /* Make it possible to replace fprintf with another
126  * function with the same interface. */
127 #ifndef GREATEST_FPRINTF
128 #define GREATEST_FPRINTF fprintf
129 #endif
130 
131 #if GREATEST_USE_LONGJMP
132 #include <setjmp.h>
133 #endif
134 
135 /* Set to 0 to disable all use of time.h / clock(). */
136 #ifndef GREATEST_USE_TIME
137 #define GREATEST_USE_TIME 1
138 #endif
139 
140 #if GREATEST_USE_TIME
141 #include <time.h>
142 #endif
143 
144 /* Floating point type, for ASSERT_IN_RANGE. */
145 #ifndef GREATEST_FLOAT
146 #define GREATEST_FLOAT double
147 #define GREATEST_FLOAT_FMT "%g"
148 #endif
149 
150 /* Size of buffer for test name + optional '_' separator and suffix */
151 #ifndef GREATEST_TESTNAME_BUF_SIZE
152 #define GREATEST_TESTNAME_BUF_SIZE 128
153 #endif
154 
155 
156 /*********
157  * Types *
158  *********/
159 
160 /* Info for the current running suite. */
161 typedef struct greatest_suite_info {
162     unsigned int tests_run;
163     unsigned int passed;
164     unsigned int failed;
165     unsigned int skipped;
166 
167 #if GREATEST_USE_TIME
168     /* timers, pre/post running suite and individual tests */
169     clock_t pre_suite;
170     clock_t post_suite;
171     clock_t pre_test;
172     clock_t post_test;
173 #endif
174 } greatest_suite_info;
175 
176 /* Type for a suite function. */
177 typedef void greatest_suite_cb(void);
178 
179 /* Types for setup/teardown callbacks. If non-NULL, these will be run
180  * and passed the pointer to their additional data. */
181 typedef void greatest_setup_cb(void *udata);
182 typedef void greatest_teardown_cb(void *udata);
183 
184 /* Type for an equality comparison between two pointers of the same type.
185  * Should return non-0 if equal, otherwise 0.
186  * UDATA is a closure value, passed through from ASSERT_EQUAL_T[m]. */
187 typedef int greatest_equal_cb(const void *exp, const void *got, void *udata);
188 
189 /* Type for a callback that prints a value pointed to by T.
190  * Return value has the same meaning as printf's.
191  * UDATA is a closure value, passed through from ASSERT_EQUAL_T[m]. */
192 typedef int greatest_printf_cb(const void *t, void *udata);
193 
194 /* Callbacks for an arbitrary type; needed for type-specific
195  * comparisons via GREATEST_ASSERT_EQUAL_T[m].*/
196 typedef struct greatest_type_info {
197     greatest_equal_cb *equal;
198     greatest_printf_cb *print;
199 } greatest_type_info;
200 
201 typedef struct greatest_memory_cmp_env {
202     const unsigned char *exp;
203     const unsigned char *got;
204     size_t size;
205 } greatest_memory_cmp_env;
206 
207 /* Callbacks for string and raw memory types. */
208 extern greatest_type_info greatest_type_info_string;
209 extern greatest_type_info greatest_type_info_memory;
210 
211 typedef enum {
212     GREATEST_FLAG_FIRST_FAIL = 0x01,
213     GREATEST_FLAG_LIST_ONLY = 0x02,
214     GREATEST_FLAG_ABORT_ON_FAIL = 0x04
215 } greatest_flag_t;
216 
217 /* Internal state for a PRNG, used to shuffle test order. */
218 struct greatest_prng {
219     unsigned char random_order; /* use random ordering? */
220     unsigned char initialized;  /* is random ordering initialized? */
221     unsigned char pad_0[6];
222     unsigned long state;        /* PRNG state */
223     unsigned long count;        /* how many tests, this pass */
224     unsigned long count_ceil;   /* total number of tests */
225     unsigned long count_run;    /* total tests run */
226     unsigned long mod;          /* power-of-2 ceiling of count_ceil */
227     unsigned long a;            /* LCG multiplier */
228     unsigned long c;            /* LCG increment */
229 };
230 
231 /* Struct containing all test runner state. */
232 typedef struct greatest_run_info {
233     unsigned char flags;
234     unsigned char verbosity;
235     unsigned char pad_0[2];
236 
237     unsigned int tests_run;     /* total test count */
238 
239     /* currently running test suite */
240     greatest_suite_info suite;
241 
242     /* overall pass/fail/skip counts */
243     unsigned int passed;
244     unsigned int failed;
245     unsigned int skipped;
246     unsigned int assertions;
247 
248     /* info to print about the most recent failure */
249     unsigned int fail_line;
250     unsigned int pad_1;
251     const char *fail_file;
252     const char *msg;
253 
254     /* current setup/teardown hooks and userdata */
255     greatest_setup_cb *setup;
256     void *setup_udata;
257     greatest_teardown_cb *teardown;
258     void *teardown_udata;
259 
260     /* formatting info for ".....s...F"-style output */
261     unsigned int col;
262     unsigned int width;
263 
264     /* only run a specific suite or test */
265     const char *suite_filter;
266     const char *test_filter;
267     const char *test_exclude;
268     const char *name_suffix;    /* print suffix with test name */
269     char name_buf[GREATEST_TESTNAME_BUF_SIZE];
270 
271     struct greatest_prng prng[2]; /* 0: suites, 1: tests */
272 
273 #if GREATEST_USE_TIME
274     /* overall timers */
275     clock_t begin;
276     clock_t end;
277 #endif
278 
279 #if GREATEST_USE_LONGJMP
280     int pad_jmp_buf;
281     unsigned char pad_2[4];
282     jmp_buf jump_dest;
283 #endif
284 } greatest_run_info;
285 
286 struct greatest_report_t {
287     /* overall pass/fail/skip counts */
288     unsigned int passed;
289     unsigned int failed;
290     unsigned int skipped;
291     unsigned int assertions;
292 };
293 
294 /* Global var for the current testing context.
295  * Initialized by GREATEST_MAIN_DEFS(). */
296 extern greatest_run_info greatest_info;
297 
298 /* Type for ASSERT_ENUM_EQ's ENUM_STR argument. */
299 typedef const char *greatest_enum_str_fun(int value);
300 
301 
302 /**********************
303  * Exported functions *
304  **********************/
305 
306 /* These are used internally by greatest macros. */
307 int greatest_test_pre(const char *name);
308 void greatest_test_post(int res);
309 int greatest_do_assert_equal_t(const void *exp, const void *got,
310     greatest_type_info *type_info, void *udata);
311 void greatest_prng_init_first_pass(int id);
312 int greatest_prng_init_second_pass(int id, unsigned long seed);
313 void greatest_prng_step(int id);
314 
315 /* These are part of the public greatest API. */
316 void GREATEST_SET_SETUP_CB(greatest_setup_cb *cb, void *udata);
317 void GREATEST_SET_TEARDOWN_CB(greatest_teardown_cb *cb, void *udata);
318 void GREATEST_INIT(void);
319 void GREATEST_PRINT_REPORT(void);
320 int greatest_all_passed(void);
321 void greatest_set_suite_filter(const char *filter);
322 void greatest_set_test_filter(const char *filter);
323 void greatest_set_test_exclude(const char *filter);
324 void greatest_stop_at_first_fail(void);
325 void greatest_abort_on_fail(void);
326 void greatest_list_only(void);
327 void greatest_get_report(struct greatest_report_t *report);
328 unsigned int greatest_get_verbosity(void);
329 void greatest_set_verbosity(unsigned int verbosity);
330 void greatest_set_flag(greatest_flag_t flag);
331 void greatest_set_test_suffix(const char *suffix);
332 
333 
334 /********************
335 * Language Support *
336 ********************/
337 
338 /* If __VA_ARGS__ (C99) is supported, allow parametric testing
339 * without needing to manually manage the argument struct. */
340 #if (defined(__STDC_VERSION__) && __STDC_VERSION__ >= 19901L) ||        \
341     (defined(_MSC_VER) && _MSC_VER >= 1800)
342 #define GREATEST_VA_ARGS
343 #endif
344 
345 
346 /**********
347  * Macros *
348  **********/
349 
350 /* Define a suite. */
351 #define GREATEST_SUITE(NAME) void NAME(void); void NAME(void)
352 
353 /* Declare a suite, provided by another compilation unit. */
354 #define GREATEST_SUITE_EXTERN(NAME) void NAME(void)
355 
356 /* Start defining a test function.
357  * The arguments are not included, to allow parametric testing. */
358 #define GREATEST_TEST static enum greatest_test_res
359 
360 /* PASS/FAIL/SKIP result from a test. Used internally. */
361 typedef enum greatest_test_res {
362     GREATEST_TEST_RES_PASS = 0,
363     GREATEST_TEST_RES_FAIL = -1,
364     GREATEST_TEST_RES_SKIP = 1
365 } greatest_test_res;
366 
367 /* Run a suite. */
368 #define GREATEST_RUN_SUITE(S_NAME) greatest_run_suite(S_NAME, #S_NAME)
369 
370 /* Run a test in the current suite. */
371 #define GREATEST_RUN_TEST(TEST)                                         \
372     do {                                                                \
373         if (greatest_test_pre(#TEST) == 1) {                            \
374             enum greatest_test_res res = GREATEST_SAVE_CONTEXT();       \
375             if (res == GREATEST_TEST_RES_PASS) {                        \
376                 res = TEST();                                           \
377             }                                                           \
378             greatest_test_post(res);                                    \
379         }                                                               \
380     } while (0)
381 
382 /* Ignore a test, don't warn about it being unused. */
383 #define GREATEST_IGNORE_TEST(TEST) (void)TEST
384 
385 /* Run a test in the current suite with one void * argument,
386  * which can be a pointer to a struct with multiple arguments. */
387 #define GREATEST_RUN_TEST1(TEST, ENV)                                   \
388     do {                                                                \
389         if (greatest_test_pre(#TEST) == 1) {                            \
390             enum greatest_test_res res = GREATEST_SAVE_CONTEXT();       \
391             if (res == GREATEST_TEST_RES_PASS) {                        \
392                 res = TEST(ENV);                                        \
393             }                                                           \
394             greatest_test_post(res);                                    \
395         }                                                               \
396     } while (0)
397 
398 #ifdef GREATEST_VA_ARGS
399 #define GREATEST_RUN_TESTp(TEST, ...)                                   \
400     do {                                                                \
401         if (greatest_test_pre(#TEST) == 1) {                            \
402             enum greatest_test_res res = GREATEST_SAVE_CONTEXT();       \
403             if (res == GREATEST_TEST_RES_PASS) {                        \
404                 res = TEST(__VA_ARGS__);                                \
405             }                                                           \
406             greatest_test_post(res);                                    \
407         }                                                               \
408     } while (0)
409 #endif
410 
411 
412 /* Check if the test runner is in verbose mode. */
413 #define GREATEST_IS_VERBOSE() ((greatest_info.verbosity) > 0)
414 #define GREATEST_LIST_ONLY()                                            \
415     (greatest_info.flags & GREATEST_FLAG_LIST_ONLY)
416 #define GREATEST_FIRST_FAIL()                                           \
417     (greatest_info.flags & GREATEST_FLAG_FIRST_FAIL)
418 #define GREATEST_ABORT_ON_FAIL()                                        \
419     (greatest_info.flags & GREATEST_FLAG_ABORT_ON_FAIL)
420 #define GREATEST_FAILURE_ABORT()                                        \
421     (GREATEST_FIRST_FAIL() &&                                           \
422         (greatest_info.suite.failed > 0 || greatest_info.failed > 0))
423 
424 /* Message-less forms of tests defined below. */
425 #define GREATEST_PASS() GREATEST_PASSm(NULL)
426 #define GREATEST_FAIL() GREATEST_FAILm(NULL)
427 #define GREATEST_SKIP() GREATEST_SKIPm(NULL)
428 #define GREATEST_ASSERT(COND)                                           \
429     GREATEST_ASSERTm(#COND, COND)
430 #define GREATEST_ASSERT_OR_LONGJMP(COND)                                \
431     GREATEST_ASSERT_OR_LONGJMPm(#COND, COND)
432 #define GREATEST_ASSERT_FALSE(COND)                                     \
433     GREATEST_ASSERT_FALSEm(#COND, COND)
434 #define GREATEST_ASSERT_EQ(EXP, GOT)                                    \
435     GREATEST_ASSERT_EQm(#EXP " != " #GOT, EXP, GOT)
436 #define GREATEST_ASSERT_EQ_FMT(EXP, GOT, FMT)                           \
437     GREATEST_ASSERT_EQ_FMTm(#EXP " != " #GOT, EXP, GOT, FMT)
438 #define GREATEST_ASSERT_IN_RANGE(EXP, GOT, TOL)                         \
439     GREATEST_ASSERT_IN_RANGEm(#EXP " != " #GOT " +/- " #TOL, EXP, GOT, TOL)
440 #define GREATEST_ASSERT_EQUAL_T(EXP, GOT, TYPE_INFO, UDATA)             \
441     GREATEST_ASSERT_EQUAL_Tm(#EXP " != " #GOT, EXP, GOT, TYPE_INFO, UDATA)
442 #define GREATEST_ASSERT_STR_EQ(EXP, GOT)                                \
443     GREATEST_ASSERT_STR_EQm(#EXP " != " #GOT, EXP, GOT)
444 #define GREATEST_ASSERT_STRN_EQ(EXP, GOT, SIZE)                         \
445     GREATEST_ASSERT_STRN_EQm(#EXP " != " #GOT, EXP, GOT, SIZE)
446 #define GREATEST_ASSERT_MEM_EQ(EXP, GOT, SIZE)                          \
447     GREATEST_ASSERT_MEM_EQm(#EXP " != " #GOT, EXP, GOT, SIZE)
448 #define GREATEST_ASSERT_ENUM_EQ(EXP, GOT, ENUM_STR)                     \
449     GREATEST_ASSERT_ENUM_EQm(#EXP " != " #GOT, EXP, GOT, ENUM_STR)
450 
451 /* The following forms take an additional message argument first,
452  * to be displayed by the test runner. */
453 
454 /* Fail if a condition is not true, with message. */
455 #define GREATEST_ASSERTm(MSG, COND)                                     \
456     do {                                                                \
457         greatest_info.assertions++;                                     \
458         if (!(COND)) { GREATEST_FAILm(MSG); }                           \
459     } while (0)
460 
461 /* Fail if a condition is not true, longjmping out of test. */
462 #define GREATEST_ASSERT_OR_LONGJMPm(MSG, COND)                          \
463     do {                                                                \
464         greatest_info.assertions++;                                     \
465         if (!(COND)) { GREATEST_FAIL_WITH_LONGJMPm(MSG); }              \
466     } while (0)
467 
468 /* Fail if a condition is not false, with message. */
469 #define GREATEST_ASSERT_FALSEm(MSG, COND)                               \
470     do {                                                                \
471         greatest_info.assertions++;                                     \
472         if ((COND)) { GREATEST_FAILm(MSG); }                            \
473     } while (0)
474 
475 /* Fail if EXP != GOT (equality comparison by ==). */
476 #define GREATEST_ASSERT_EQm(MSG, EXP, GOT)                              \
477     do {                                                                \
478         greatest_info.assertions++;                                     \
479         if ((EXP) != (GOT)) { GREATEST_FAILm(MSG); }                    \
480     } while (0)
481 
482 /* Fail if EXP != GOT (equality comparison by ==).
483  * Warning: FMT, EXP, and GOT will be evaluated more
484  * than once on failure. */
485 #define GREATEST_ASSERT_EQ_FMTm(MSG, EXP, GOT, FMT)                     \
486     do {                                                                \
487         greatest_info.assertions++;                                     \
488         if ((EXP) != (GOT)) {                                           \
489             GREATEST_FPRINTF(GREATEST_STDOUT, "\nExpected: ");          \
490             GREATEST_FPRINTF(GREATEST_STDOUT, FMT, EXP);                \
491             GREATEST_FPRINTF(GREATEST_STDOUT, "\n     Got: ");          \
492             GREATEST_FPRINTF(GREATEST_STDOUT, FMT, GOT);                \
493             GREATEST_FPRINTF(GREATEST_STDOUT, "\n");                    \
494             GREATEST_FAILm(MSG);                                        \
495         }                                                               \
496     } while (0)
497 
498 /* Fail if EXP is not equal to GOT, printing enum IDs. */
499 #define GREATEST_ASSERT_ENUM_EQm(MSG, EXP, GOT, ENUM_STR)               \
500     do {                                                                \
501         int greatest_EXP = (int)(EXP);                                  \
502         int greatest_GOT = (int)(GOT);                                  \
503         greatest_enum_str_fun *greatest_ENUM_STR = ENUM_STR;            \
504         if (greatest_EXP != greatest_GOT) {                             \
505             GREATEST_FPRINTF(GREATEST_STDOUT, "\nExpected: %s",         \
506                 greatest_ENUM_STR(greatest_EXP));                       \
507             GREATEST_FPRINTF(GREATEST_STDOUT, "\n     Got: %s\n",       \
508                 greatest_ENUM_STR(greatest_GOT));                       \
509             GREATEST_FAILm(MSG);                                        \
510         }                                                               \
511     } while (0)                                                         \
512 
513 /* Fail if GOT not in range of EXP +|- TOL. */
514 #define GREATEST_ASSERT_IN_RANGEm(MSG, EXP, GOT, TOL)                   \
515     do {                                                                \
516         GREATEST_FLOAT greatest_EXP = (EXP);                            \
517         GREATEST_FLOAT greatest_GOT = (GOT);                            \
518         GREATEST_FLOAT greatest_TOL = (TOL);                            \
519         greatest_info.assertions++;                                     \
520         if ((greatest_EXP > greatest_GOT &&                             \
521                 greatest_EXP - greatest_GOT > greatest_TOL) ||          \
522             (greatest_EXP < greatest_GOT &&                             \
523                 greatest_GOT - greatest_EXP > greatest_TOL)) {          \
524             GREATEST_FPRINTF(GREATEST_STDOUT,                           \
525                 "\nExpected: " GREATEST_FLOAT_FMT                       \
526                 " +/- " GREATEST_FLOAT_FMT                              \
527                 "\n     Got: " GREATEST_FLOAT_FMT                       \
528                 "\n",                                                   \
529                 greatest_EXP, greatest_TOL, greatest_GOT);              \
530             GREATEST_FAILm(MSG);                                        \
531         }                                                               \
532     } while (0)
533 
534 /* Fail if EXP is not equal to GOT, according to strcmp. */
535 #define GREATEST_ASSERT_STR_EQm(MSG, EXP, GOT)                          \
536     do {                                                                \
537         GREATEST_ASSERT_EQUAL_Tm(MSG, EXP, GOT,                         \
538             &greatest_type_info_string, NULL);                          \
539     } while (0)                                                         \
540 
541 /* Fail if EXP is not equal to GOT, according to strcmp. */
542 #define GREATEST_ASSERT_STRN_EQm(MSG, EXP, GOT, SIZE)                   \
543     do {                                                                \
544         size_t size = SIZE;                                             \
545         GREATEST_ASSERT_EQUAL_Tm(MSG, EXP, GOT,                         \
546             &greatest_type_info_string, &size);                         \
547     } while (0)                                                         \
548 
549 /* Fail if EXP is not equal to GOT, according to memcmp. */
550 #define GREATEST_ASSERT_MEM_EQm(MSG, EXP, GOT, SIZE)                    \
551     do {                                                                \
552         greatest_memory_cmp_env env;                                    \
553         env.exp = (const unsigned char *)EXP;                           \
554         env.got = (const unsigned char *)GOT;                           \
555         env.size = SIZE;                                                \
556         GREATEST_ASSERT_EQUAL_Tm(MSG, env.exp, env.got,                 \
557             &greatest_type_info_memory, &env);                          \
558     } while (0)                                                         \
559 
560 /* Fail if EXP is not equal to GOT, according to a comparison
561  * callback in TYPE_INFO. If they are not equal, optionally use a
562  * print callback in TYPE_INFO to print them. */
563 #define GREATEST_ASSERT_EQUAL_Tm(MSG, EXP, GOT, TYPE_INFO, UDATA)       \
564     do {                                                                \
565         greatest_type_info *type_info = (TYPE_INFO);                    \
566         greatest_info.assertions++;                                     \
567         if (!greatest_do_assert_equal_t(EXP, GOT,                       \
568                 type_info, UDATA)) {                                    \
569             if (type_info == NULL || type_info->equal == NULL) {        \
570                 GREATEST_FAILm("type_info->equal callback missing!");   \
571             } else {                                                    \
572                 GREATEST_FAILm(MSG);                                    \
573             }                                                           \
574         }                                                               \
575     } while (0)                                                         \
576 
577 /* Pass. */
578 #define GREATEST_PASSm(MSG)                                             \
579     do {                                                                \
580         greatest_info.msg = MSG;                                        \
581         return GREATEST_TEST_RES_PASS;                                  \
582     } while (0)
583 
584 /* Fail. */
585 #define GREATEST_FAILm(MSG)                                             \
586     do {                                                                \
587         greatest_info.fail_file = __FILE__;                             \
588         greatest_info.fail_line = __LINE__;                             \
589         greatest_info.msg = MSG;                                        \
590         if (GREATEST_ABORT_ON_FAIL()) { abort(); }                      \
591         return GREATEST_TEST_RES_FAIL;                                  \
592     } while (0)
593 
594 /* Optional GREATEST_FAILm variant that longjmps. */
595 #if GREATEST_USE_LONGJMP
596 #define GREATEST_FAIL_WITH_LONGJMP() GREATEST_FAIL_WITH_LONGJMPm(NULL)
597 #define GREATEST_FAIL_WITH_LONGJMPm(MSG)                                \
598     do {                                                                \
599         greatest_info.fail_file = __FILE__;                             \
600         greatest_info.fail_line = __LINE__;                             \
601         greatest_info.msg = MSG;                                        \
602         longjmp(greatest_info.jump_dest, GREATEST_TEST_RES_FAIL);       \
603     } while (0)
604 #endif
605 
606 /* Skip the current test. */
607 #define GREATEST_SKIPm(MSG)                                             \
608     do {                                                                \
609         greatest_info.msg = MSG;                                        \
610         return GREATEST_TEST_RES_SKIP;                                  \
611     } while (0)
612 
613 /* Check the result of a subfunction using ASSERT, etc. */
614 #define GREATEST_CHECK_CALL(RES)                                        \
615     do {                                                                \
616         enum greatest_test_res greatest_RES = RES;                      \
617         if (greatest_RES != GREATEST_TEST_RES_PASS) {                   \
618             return greatest_RES;                                        \
619         }                                                               \
620     } while (0)                                                         \
621 
622 #if GREATEST_USE_TIME
623 #define GREATEST_SET_TIME(NAME)                                         \
624     NAME = clock();                                                     \
625     if (NAME == (clock_t) -1) {                                         \
626         GREATEST_FPRINTF(GREATEST_STDOUT,                               \
627             "clock error: %s\n", #NAME);                                \
628         exit(EXIT_FAILURE);                                             \
629     }
630 
631 #define GREATEST_CLOCK_DIFF(C1, C2)                                     \
632     GREATEST_FPRINTF(GREATEST_STDOUT, " (%lu ticks, %.3f sec)",         \
633         (long unsigned int) (C2) - (long unsigned int)(C1),             \
634         (double)((C2) - (C1)) / (1.0 * (double)CLOCKS_PER_SEC))
635 #else
636 #define GREATEST_SET_TIME(UNUSED)
637 #define GREATEST_CLOCK_DIFF(UNUSED1, UNUSED2)
638 #endif
639 
640 #if GREATEST_USE_LONGJMP
641 #define GREATEST_SAVE_CONTEXT()                                         \
642         /* setjmp returns 0 (GREATEST_TEST_RES_PASS) on first call *    \
643          * so the test runs, then RES_FAIL from FAIL_WITH_LONGJMP. */   \
644         ((enum greatest_test_res)(setjmp(greatest_info.jump_dest)))
645 #else
646 #define GREATEST_SAVE_CONTEXT()                                         \
647     /*a no-op, since setjmp/longjmp aren't being used */                \
648     GREATEST_TEST_RES_PASS
649 #endif
650 
651 /* Run every suite / test function run within BODY in pseudo-random
652  * order, seeded by SEED. (The top 3 bits of the seed are ignored.)
653  *
654  * This should be called like:
655  *     GREATEST_SHUFFLE_TESTS(seed, {
656  *         GREATEST_RUN_TEST(some_test);
657  *         GREATEST_RUN_TEST(some_other_test);
658  *         GREATEST_RUN_TEST(yet_another_test);
659  *     });
660  *
661  * Note that the body of the second argument will be evaluated
662  * multiple times. */
663 #define GREATEST_SHUFFLE_SUITES(SD, BODY) GREATEST_SHUFFLE(0, SD, BODY)
664 #define GREATEST_SHUFFLE_TESTS(SD, BODY) GREATEST_SHUFFLE(1, SD, BODY)
665 #define GREATEST_SHUFFLE(ID, SD, BODY)                                  \
666     do {                                                                \
667         struct greatest_prng *prng = &greatest_info.prng[ID];           \
668         greatest_prng_init_first_pass(ID);                              \
669         do {                                                            \
670             prng->count = 0;                                            \
671             if (prng->initialized) { greatest_prng_step(ID); }          \
672             BODY;                                                       \
673             if (!prng->initialized) {                                   \
674                 if (!greatest_prng_init_second_pass(ID, SD)) { break; } \
675             } else if (prng->count_run == prng->count_ceil) {           \
676                 break;                                                  \
677             }                                                           \
678         } while (!GREATEST_FAILURE_ABORT());                            \
679         prng->count_run = prng->random_order = prng->initialized = 0;   \
680     } while(0)
681 
682 /* Include several function definitions in the main test file. */
683 #define GREATEST_MAIN_DEFS()                                            \
684                                                                         \
685 /* Is FILTER a subset of NAME? */                                       \
686 static int greatest_name_match(const char *name, const char *filter,    \
687         int res_if_none) {                                              \
688     size_t offset = 0;                                                  \
689     size_t filter_len = filter ? strlen(filter) : 0;                    \
690     if (filter_len == 0) { return res_if_none; } /* no filter */        \
691     while (name[offset] != '\0') {                                      \
692         if (name[offset] == filter[0]) {                                \
693             if (0 == strncmp(&name[offset], filter, filter_len)) {      \
694                 return 1;                                               \
695             }                                                           \
696         }                                                               \
697         offset++;                                                       \
698     }                                                                   \
699                                                                         \
700     return 0;                                                           \
701 }                                                                       \
702                                                                         \
703 static void greatest_buffer_test_name(const char *name) {               \
704     struct greatest_run_info *g = &greatest_info;                       \
705     size_t len = strlen(name), size = sizeof(g->name_buf);              \
706     memset(g->name_buf, 0x00, size);                                    \
707     (void)strncat(g->name_buf, name, size - 1);                         \
708     if (g->name_suffix && (len + 1 < size)) {                           \
709         g->name_buf[len] = '_';                                         \
710         strncat(&g->name_buf[len+1], g->name_suffix, size-(len+2));     \
711     }                                                                   \
712 }                                                                       \
713                                                                         \
714 /* Before running a test, check the name filtering and                  \
715  * test shuffling state, if applicable, and then call setup hooks. */   \
716 int greatest_test_pre(const char *name) {                               \
717     struct greatest_run_info *g = &greatest_info;                       \
718     int match;                                                          \
719     greatest_buffer_test_name(name);                                    \
720     match = greatest_name_match(g->name_buf, g->test_filter, 1) &&      \
721       !greatest_name_match(g->name_buf, g->test_exclude, 0);            \
722     if (GREATEST_LIST_ONLY()) {   /* just listing test names */         \
723         if (match) {                                                    \
724             fprintf(GREATEST_STDOUT, "  %s\n", g->name_buf);            \
725         }                                                               \
726         goto clear;                                                     \
727     }                                                                   \
728     if (match && (!GREATEST_FIRST_FAIL() || g->suite.failed == 0)) {    \
729             struct greatest_prng *p = &g->prng[1];                      \
730         if (p->random_order) {                                          \
731             p->count++;                                                 \
732             if (!p->initialized || ((p->count - 1) != p->state)) {      \
733                 goto clear;       /* don't run this test yet */         \
734             }                                                           \
735         }                                                               \
736         GREATEST_SET_TIME(g->suite.pre_test);                           \
737         if (g->setup) { g->setup(g->setup_udata); }                     \
738         p->count_run++;                                                 \
739         return 1;                 /* test should be run */              \
740     } else {                                                            \
741         goto clear;               /* skipped */                         \
742     }                                                                   \
743 clear:                                                                  \
744     g->name_suffix = NULL;                                              \
745     return 0;                                                           \
746 }                                                                       \
747                                                                         \
748 static void greatest_do_pass(void) {                                    \
749     struct greatest_run_info *g = &greatest_info;                       \
750     if (GREATEST_IS_VERBOSE()) {                                        \
751         GREATEST_FPRINTF(GREATEST_STDOUT, "PASS %s: %s",                \
752             g->name_buf, g->msg ? g->msg : "");                         \
753     } else {                                                            \
754         GREATEST_FPRINTF(GREATEST_STDOUT, ".");                         \
755     }                                                                   \
756     g->suite.passed++;                                                  \
757 }                                                                       \
758                                                                         \
759 static void greatest_do_fail(void) {                                    \
760     struct greatest_run_info *g = &greatest_info;                       \
761     if (GREATEST_IS_VERBOSE()) {                                        \
762         GREATEST_FPRINTF(GREATEST_STDOUT,                               \
763             "FAIL %s: %s (%s:%u)", g->name_buf,                         \
764             g->msg ? g->msg : "", g->fail_file, g->fail_line);          \
765     } else {                                                            \
766         GREATEST_FPRINTF(GREATEST_STDOUT, "F");                         \
767         g->col++;  /* add linebreak if in line of '.'s */               \
768         if (g->col != 0) {                                              \
769             GREATEST_FPRINTF(GREATEST_STDOUT, "\n");                    \
770             g->col = 0;                                                 \
771         }                                                               \
772         GREATEST_FPRINTF(GREATEST_STDOUT, "FAIL %s: %s (%s:%u)\n",      \
773             g->name_buf, g->msg ? g->msg : "",                          \
774             g->fail_file, g->fail_line);                                \
775     }                                                                   \
776     g->suite.failed++;                                                  \
777 }                                                                       \
778                                                                         \
779 static void greatest_do_skip(void) {                                    \
780     struct greatest_run_info *g = &greatest_info;                       \
781     if (GREATEST_IS_VERBOSE()) {                                        \
782         GREATEST_FPRINTF(GREATEST_STDOUT, "SKIP %s: %s",                \
783             g->name_buf, g->msg ? g->msg : "");                         \
784     } else {                                                            \
785         GREATEST_FPRINTF(GREATEST_STDOUT, "s");                         \
786     }                                                                   \
787     g->suite.skipped++;                                                 \
788 }                                                                       \
789                                                                         \
790 void greatest_test_post(int res) {                                      \
791     GREATEST_SET_TIME(greatest_info.suite.post_test);                   \
792     if (greatest_info.teardown) {                                       \
793         void *udata = greatest_info.teardown_udata;                     \
794         greatest_info.teardown(udata);                                  \
795     }                                                                   \
796                                                                         \
797     if (res <= GREATEST_TEST_RES_FAIL) {                                \
798         greatest_do_fail();                                             \
799     } else if (res >= GREATEST_TEST_RES_SKIP) {                         \
800         greatest_do_skip();                                             \
801     } else if (res == GREATEST_TEST_RES_PASS) {                         \
802         greatest_do_pass();                                             \
803     }                                                                   \
804     greatest_info.name_suffix = NULL;                                   \
805     greatest_info.suite.tests_run++;                                    \
806     greatest_info.col++;                                                \
807     if (GREATEST_IS_VERBOSE()) {                                        \
808         GREATEST_CLOCK_DIFF(greatest_info.suite.pre_test,               \
809             greatest_info.suite.post_test);                             \
810         GREATEST_FPRINTF(GREATEST_STDOUT, "\n");                        \
811     } else if (greatest_info.col % greatest_info.width == 0) {          \
812         GREATEST_FPRINTF(GREATEST_STDOUT, "\n");                        \
813         greatest_info.col = 0;                                          \
814     }                                                                   \
815     fflush(GREATEST_STDOUT);                                            \
816 }                                                                       \
817                                                                         \
818 static void report_suite(void) {                                        \
819     if (greatest_info.suite.tests_run > 0) {                            \
820         GREATEST_FPRINTF(GREATEST_STDOUT,                               \
821             "\n%u test%s - %u passed, %u failed, %u skipped",           \
822             greatest_info.suite.tests_run,                              \
823             greatest_info.suite.tests_run == 1 ? "" : "s",              \
824             greatest_info.suite.passed,                                 \
825             greatest_info.suite.failed,                                 \
826             greatest_info.suite.skipped);                               \
827         GREATEST_CLOCK_DIFF(greatest_info.suite.pre_suite,              \
828             greatest_info.suite.post_suite);                            \
829         GREATEST_FPRINTF(GREATEST_STDOUT, "\n");                        \
830     }                                                                   \
831 }                                                                       \
832                                                                         \
833 static void update_counts_and_reset_suite(void) {                       \
834     greatest_info.setup = NULL;                                         \
835     greatest_info.setup_udata = NULL;                                   \
836     greatest_info.teardown = NULL;                                      \
837     greatest_info.teardown_udata = NULL;                                \
838     greatest_info.passed += greatest_info.suite.passed;                 \
839     greatest_info.failed += greatest_info.suite.failed;                 \
840     greatest_info.skipped += greatest_info.suite.skipped;               \
841     greatest_info.tests_run += greatest_info.suite.tests_run;           \
842     memset(&greatest_info.suite, 0, sizeof(greatest_info.suite));       \
843     greatest_info.col = 0;                                              \
844 }                                                                       \
845                                                                         \
846 static int greatest_suite_pre(const char *suite_name) {                 \
847     struct greatest_prng *p = &greatest_info.prng[0];                   \
848     if (!greatest_name_match(suite_name, greatest_info.suite_filter, 1) \
849         || (GREATEST_FIRST_FAIL() && greatest_info.failed > 0)) {       \
850         return 0;                                                       \
851     }                                                                   \
852     if (p->random_order) {                                              \
853         p->count++;                                                     \
854         if (!p->initialized || ((p->count - 1) != p->state)) {          \
855             return 0; /* don't run this suite yet */                    \
856         }                                                               \
857     }                                                                   \
858     p->count_run++;                                                     \
859     update_counts_and_reset_suite();                                    \
860     GREATEST_FPRINTF(GREATEST_STDOUT, "\n* Suite %s:\n", suite_name);   \
861     GREATEST_SET_TIME(greatest_info.suite.pre_suite);                   \
862     return 1;                                                           \
863 }                                                                       \
864                                                                         \
865 static void greatest_suite_post(void) {                                 \
866     GREATEST_SET_TIME(greatest_info.suite.post_suite);                  \
867     report_suite();                                                     \
868 }                                                                       \
869                                                                         \
870 static void greatest_run_suite(greatest_suite_cb *suite_cb,             \
871                                const char *suite_name) {                \
872     if (greatest_suite_pre(suite_name)) {                               \
873         suite_cb();                                                     \
874         greatest_suite_post();                                          \
875     }                                                                   \
876 }                                                                       \
877                                                                         \
878 int greatest_do_assert_equal_t(const void *exp, const void *got,        \
879         greatest_type_info *type_info, void *udata) {                   \
880     int eq = 0;                                                         \
881     if (type_info == NULL || type_info->equal == NULL) {                \
882         return 0;                                                       \
883     }                                                                   \
884     eq = type_info->equal(exp, got, udata);                             \
885     if (!eq) {                                                          \
886         if (type_info->print != NULL) {                                 \
887             GREATEST_FPRINTF(GREATEST_STDOUT, "\nExpected: ");          \
888             (void)type_info->print(exp, udata);                         \
889             GREATEST_FPRINTF(GREATEST_STDOUT, "\n     Got: ");          \
890             (void)type_info->print(got, udata);                         \
891             GREATEST_FPRINTF(GREATEST_STDOUT, "\n");                    \
892         }                                                               \
893     }                                                                   \
894     return eq;                                                          \
895 }                                                                       \
896                                                                         \
897 static void greatest_usage(const char *name) {                          \
898     GREATEST_FPRINTF(GREATEST_STDOUT,                                   \
899         "Usage: %s [--help] [-hlfav] [-s SUITE] [-t TEST]\n"            \
900         "  -h, --help  print this Help\n"                               \
901         "  -l          List suites and tests, then exit (dry run)\n"    \
902         "  -f          Stop runner after first failure\n"               \
903         "  -a          Abort on first failure (implies -f)\n"           \
904         "  -v          Verbose output\n"                                \
905         "  -s SUITE    only run suites containing string SUITE\n"       \
906         "  -t TEST     only run tests containing string TEST\n"         \
907         "  -x EXCLUDE  exclude tests containing string EXCLUDE\n",      \
908         name);                                                          \
909 }                                                                       \
910                                                                         \
911 static void greatest_parse_options(int argc, char **argv) {             \
912     int i = 0;                                                          \
913     for (i = 1; i < argc; i++) {                                        \
914         if (argv[i][0] == '-') {                                        \
915             char f = argv[i][1];                                        \
916             if ((f == 's' || f == 't' || f == 'x') && argc <= i + 1) {  \
917                 greatest_usage(argv[0]); exit(EXIT_FAILURE);            \
918             }                                                           \
919             switch (f) {                                                \
920             case 's': /* suite name filter */                           \
921                 greatest_set_suite_filter(argv[i + 1]); i++; break;     \
922             case 't': /* test name filter */                            \
923                 greatest_set_test_filter(argv[i + 1]); i++; break;      \
924             case 'x': /* test name exclusion */                         \
925                 greatest_set_test_exclude(argv[i + 1]); i++; break;     \
926             case 'f': /* first fail flag */                             \
927                 greatest_stop_at_first_fail(); break;                   \
928             case 'a': /* abort() on fail flag */                        \
929                 greatest_abort_on_fail(); break;                        \
930             case 'l': /* list only (dry run) */                         \
931                 greatest_list_only(); break;                            \
932             case 'v': /* first fail flag */                             \
933                 greatest_info.verbosity++; break;                       \
934             case 'h': /* help */                                        \
935                 greatest_usage(argv[0]); exit(EXIT_SUCCESS);            \
936             case '-':                                                   \
937                 if (0 == strncmp("--help", argv[i], 6)) {               \
938                     greatest_usage(argv[0]); exit(EXIT_SUCCESS);        \
939                 } else if (0 == strncmp("--", argv[i], 2)) {            \
940                     return; /* ignore following arguments */            \
941                 }  /* fall through */                                   \
942             default:                                                    \
943                 GREATEST_FPRINTF(GREATEST_STDOUT,                       \
944                     "Unknown argument '%s'\n", argv[i]);                \
945                 greatest_usage(argv[0]);                                \
946                 exit(EXIT_FAILURE);                                     \
947             }                                                           \
948         }                                                               \
949     }                                                                   \
950 }                                                                       \
951                                                                         \
952 int greatest_all_passed(void) { return (greatest_info.failed == 0); }   \
953                                                                         \
954 void greatest_set_test_filter(const char *filter) {                     \
955     greatest_info.test_filter = filter;                                 \
956 }                                                                       \
957                                                                         \
958 void greatest_set_test_exclude(const char *filter) {                    \
959     greatest_info.test_exclude = filter;                                \
960 }                                                                       \
961                                                                         \
962 void greatest_set_suite_filter(const char *filter) {                    \
963     greatest_info.suite_filter = filter;                                \
964 }                                                                       \
965                                                                         \
966 void greatest_stop_at_first_fail(void) {                                \
967     greatest_set_flag(GREATEST_FLAG_FIRST_FAIL);                        \
968 }                                                                       \
969                                                                         \
970 void greatest_abort_on_fail(void) {                                     \
971     greatest_set_flag(GREATEST_FLAG_ABORT_ON_FAIL);                     \
972 }                                                                       \
973                                                                         \
974 void greatest_list_only(void) {                                         \
975     greatest_set_flag(GREATEST_FLAG_LIST_ONLY);                         \
976 }                                                                       \
977                                                                         \
978 void greatest_get_report(struct greatest_report_t *report) {            \
979     if (report) {                                                       \
980         report->passed = greatest_info.passed;                          \
981         report->failed = greatest_info.failed;                          \
982         report->skipped = greatest_info.skipped;                        \
983         report->assertions = greatest_info.assertions;                  \
984     }                                                                   \
985 }                                                                       \
986                                                                         \
987 unsigned int greatest_get_verbosity(void) {                             \
988     return greatest_info.verbosity;                                     \
989 }                                                                       \
990                                                                         \
991 void greatest_set_verbosity(unsigned int verbosity) {                   \
992     greatest_info.verbosity = (unsigned char)verbosity;                 \
993 }                                                                       \
994                                                                         \
995 void greatest_set_flag(greatest_flag_t flag) {                          \
996     greatest_info.flags |= flag;                                        \
997 }                                                                       \
998                                                                         \
999 void greatest_set_test_suffix(const char *suffix) {                     \
1000     greatest_info.name_suffix = suffix;                                 \
1001 }                                                                       \
1002                                                                         \
1003 void GREATEST_SET_SETUP_CB(greatest_setup_cb *cb, void *udata) {        \
1004     greatest_info.setup = cb;                                           \
1005     greatest_info.setup_udata = udata;                                  \
1006 }                                                                       \
1007                                                                         \
1008 void GREATEST_SET_TEARDOWN_CB(greatest_teardown_cb *cb,                 \
1009                                     void *udata) {                      \
1010     greatest_info.teardown = cb;                                        \
1011     greatest_info.teardown_udata = udata;                               \
1012 }                                                                       \
1013                                                                         \
1014 static int greatest_string_equal_cb(const void *exp, const void *got,   \
1015     void *udata) {                                                      \
1016     size_t *size = (size_t *)udata;                                     \
1017     return (size != NULL                                                \
1018         ? (0 == strncmp((const char *)exp, (const char *)got, *size))   \
1019         : (0 == strcmp((const char *)exp, (const char *)got)));         \
1020 }                                                                       \
1021                                                                         \
1022 static int greatest_string_printf_cb(const void *t, void *udata) {      \
1023     (void)udata; /* note: does not check \0 termination. */             \
1024     return GREATEST_FPRINTF(GREATEST_STDOUT, "%s", (const char *)t);    \
1025 }                                                                       \
1026                                                                         \
1027 greatest_type_info greatest_type_info_string = {                        \
1028     greatest_string_equal_cb,                                           \
1029     greatest_string_printf_cb,                                          \
1030 };                                                                      \
1031                                                                         \
1032 static int greatest_memory_equal_cb(const void *exp, const void *got,   \
1033     void *udata) {                                                      \
1034     greatest_memory_cmp_env *env = (greatest_memory_cmp_env *)udata;    \
1035     return (0 == memcmp(exp, got, env->size));                          \
1036 }                                                                       \
1037                                                                         \
1038 /* Hexdump raw memory, with differences highlighted */                  \
1039 static int greatest_memory_printf_cb(const void *t, void *udata) {      \
1040     greatest_memory_cmp_env *env = (greatest_memory_cmp_env *)udata;    \
1041     const unsigned char *buf = (const unsigned char *)t;                \
1042     unsigned char diff_mark = ' ';                                      \
1043     FILE *out = GREATEST_STDOUT;                                        \
1044     size_t i, line_i, line_len = 0;                                     \
1045     int len = 0;   /* format hexdump with differences highlighted */    \
1046     for (i = 0; i < env->size; i+= line_len) {                          \
1047         diff_mark = ' ';                                                \
1048         line_len = env->size - i;                                       \
1049         if (line_len > 16) { line_len = 16; }                           \
1050         for (line_i = i; line_i < i + line_len; line_i++) {             \
1051             if (env->exp[line_i] != env->got[line_i]) diff_mark = 'X';  \
1052         }                                                               \
1053         len += GREATEST_FPRINTF(out, "\n%04x %c ",                      \
1054             (unsigned int)i, diff_mark);                                \
1055         for (line_i = i; line_i < i + line_len; line_i++) {             \
1056             int m = env->exp[line_i] == env->got[line_i]; /* match? */  \
1057             len += GREATEST_FPRINTF(out, "%02x%c",                      \
1058                 buf[line_i], m ? ' ' : '<');                            \
1059         }                                                               \
1060         for (line_i = 0; line_i < 16 - line_len; line_i++) {            \
1061             len += GREATEST_FPRINTF(out, "   ");                        \
1062         }                                                               \
1063         GREATEST_FPRINTF(out, " ");                                     \
1064         for (line_i = i; line_i < i + line_len; line_i++) {             \
1065             unsigned char c = buf[line_i];                              \
1066             len += GREATEST_FPRINTF(out, "%c", isprint(c) ? c : '.');   \
1067         }                                                               \
1068     }                                                                   \
1069     len += GREATEST_FPRINTF(out, "\n");                                 \
1070     return len;                                                         \
1071 }                                                                       \
1072                                                                         \
1073 void greatest_prng_init_first_pass(int id) {                            \
1074     greatest_info.prng[id].random_order = 1;                            \
1075     greatest_info.prng[id].count_run = 0;                               \
1076 }                                                                       \
1077                                                                         \
1078 int greatest_prng_init_second_pass(int id, unsigned long seed) {        \
1079     static unsigned long primes[] = { 11, 101, 1009, 10007,             \
1080         100003, 1000003, 10000019, 100000007, 1000000007,               \
1081         1538461, 1865471, 17471, 2147483647 /* 2**32 - 1 */, };         \
1082     struct greatest_prng *prng = &greatest_info.prng[id];               \
1083     if (prng->count == 0) { return 0; }                                 \
1084     prng->mod = 1;                                                      \
1085     prng->count_ceil = prng->count;                                     \
1086     while (prng->mod < prng->count) { prng->mod <<= 1; }                \
1087     prng->state = seed & 0x1fffffff;    /* only use lower 29 bits... */ \
1088     prng->a = (4LU * prng->state) + 1;  /* to avoid overflow */         \
1089     prng->c = primes[(seed * 16451) % sizeof(primes)/sizeof(primes[0])];\
1090     prng->initialized = 1;                                              \
1091     return 1;                                                           \
1092 }                                                                       \
1093                                                                         \
1094 /* Step the pseudorandom number generator until its state reaches       \
1095  * another test ID between 0 and the test count.                        \
1096  * This use a linear congruential pseudorandom number generator,        \
1097  * with the power-of-two ceiling of the test count as the modulus, the  \
1098  * masked seed as the multiplier, and a prime as the increment. For     \
1099  * each generated value < the test count, run the corresponding test.   \
1100  * This will visit all IDs 0 <= X < mod once before repeating,          \
1101  * with a starting position chosen based on the initial seed.           \
1102  * For details, see: Knuth, The Art of Computer Programming             \
1103  * Volume. 2, section 3.2.1. */                                         \
1104 void greatest_prng_step(int id) {                                       \
1105     struct greatest_prng *p = &greatest_info.prng[id];                  \
1106     do {                                                                \
1107         p->state = ((p->a * p->state) + p->c) & (p->mod - 1);           \
1108     } while (p->state >= p->count_ceil);                                \
1109 }                                                                       \
1110                                                                         \
1111 void GREATEST_INIT(void) {                                              \
1112     /* Suppress unused function warning if features aren't used */      \
1113     (void)greatest_run_suite;                                           \
1114     (void)greatest_parse_options;                                       \
1115     (void)greatest_prng_step;                                           \
1116     (void)greatest_prng_init_first_pass;                                \
1117     (void)greatest_prng_init_second_pass;                               \
1118     (void)greatest_set_test_suffix;                                     \
1119                                                                         \
1120     memset(&greatest_info, 0, sizeof(greatest_info));                   \
1121     greatest_info.width = GREATEST_DEFAULT_WIDTH;                       \
1122     GREATEST_SET_TIME(greatest_info.begin);                             \
1123 }                                                                       \
1124                                                                         \
1125 /* Report passes, failures, skipped tests, the number of                \
1126  * assertions, and the overall run time. */                             \
1127 void GREATEST_PRINT_REPORT(void) {                                      \
1128     if (!GREATEST_LIST_ONLY()) {                                        \
1129         update_counts_and_reset_suite();                                \
1130         GREATEST_SET_TIME(greatest_info.end);                           \
1131         GREATEST_FPRINTF(GREATEST_STDOUT,                               \
1132             "\nTotal: %u test%s",                                       \
1133             greatest_info.tests_run,                                    \
1134             greatest_info.tests_run == 1 ? "" : "s");                   \
1135         GREATEST_CLOCK_DIFF(greatest_info.begin,                        \
1136             greatest_info.end);                                         \
1137         GREATEST_FPRINTF(GREATEST_STDOUT, ", %u assertion%s\n",         \
1138             greatest_info.assertions,                                   \
1139             greatest_info.assertions == 1 ? "" : "s");                  \
1140         GREATEST_FPRINTF(GREATEST_STDOUT,                               \
1141             "Pass: %u, fail: %u, skip: %u.\n",                          \
1142             greatest_info.passed,                                       \
1143             greatest_info.failed, greatest_info.skipped);               \
1144     }                                                                   \
1145 }                                                                       \
1146                                                                         \
1147 greatest_type_info greatest_type_info_memory = {                        \
1148     greatest_memory_equal_cb,                                           \
1149     greatest_memory_printf_cb,                                          \
1150 };                                                                      \
1151                                                                         \
1152 greatest_run_info greatest_info
1153 
1154 /* Handle command-line arguments, etc. */
1155 #define GREATEST_MAIN_BEGIN()                                           \
1156     do {                                                                \
1157         GREATEST_INIT();                                                \
1158         greatest_parse_options(argc, argv);                             \
1159     } while (0)
1160 
1161 /* Report results, exit with exit status based on results. */
1162 #define GREATEST_MAIN_END()                                             \
1163     do {                                                                \
1164         GREATEST_PRINT_REPORT();                                        \
1165         return (greatest_all_passed() ? EXIT_SUCCESS : EXIT_FAILURE);   \
1166     } while (0)
1167 
1168 /* Make abbreviations without the GREATEST_ prefix for the
1169  * most commonly used symbols. */
1170 #if GREATEST_USE_ABBREVS
1171 #define TEST           GREATEST_TEST
1172 #define SUITE          GREATEST_SUITE
1173 #define SUITE_EXTERN   GREATEST_SUITE_EXTERN
1174 #define RUN_TEST       GREATEST_RUN_TEST
1175 #define RUN_TEST1      GREATEST_RUN_TEST1
1176 #define RUN_SUITE      GREATEST_RUN_SUITE
1177 #define IGNORE_TEST    GREATEST_IGNORE_TEST
1178 #define ASSERT         GREATEST_ASSERT
1179 #define ASSERTm        GREATEST_ASSERTm
1180 #define ASSERT_FALSE   GREATEST_ASSERT_FALSE
1181 #define ASSERT_EQ      GREATEST_ASSERT_EQ
1182 #define ASSERT_EQ_FMT  GREATEST_ASSERT_EQ_FMT
1183 #define ASSERT_IN_RANGE GREATEST_ASSERT_IN_RANGE
1184 #define ASSERT_EQUAL_T GREATEST_ASSERT_EQUAL_T
1185 #define ASSERT_STR_EQ  GREATEST_ASSERT_STR_EQ
1186 #define ASSERT_STRN_EQ GREATEST_ASSERT_STRN_EQ
1187 #define ASSERT_MEM_EQ  GREATEST_ASSERT_MEM_EQ
1188 #define ASSERT_ENUM_EQ GREATEST_ASSERT_ENUM_EQ
1189 #define ASSERT_FALSEm  GREATEST_ASSERT_FALSEm
1190 #define ASSERT_EQm     GREATEST_ASSERT_EQm
1191 #define ASSERT_EQ_FMTm GREATEST_ASSERT_EQ_FMTm
1192 #define ASSERT_IN_RANGEm GREATEST_ASSERT_IN_RANGEm
1193 #define ASSERT_EQUAL_Tm GREATEST_ASSERT_EQUAL_Tm
1194 #define ASSERT_STR_EQm GREATEST_ASSERT_STR_EQm
1195 #define ASSERT_STRN_EQm GREATEST_ASSERT_STRN_EQm
1196 #define ASSERT_MEM_EQm GREATEST_ASSERT_MEM_EQm
1197 #define ASSERT_ENUM_EQm GREATEST_ASSERT_ENUM_EQm
1198 #define PASS           GREATEST_PASS
1199 #define FAIL           GREATEST_FAIL
1200 #define SKIP           GREATEST_SKIP
1201 #define PASSm          GREATEST_PASSm
1202 #define FAILm          GREATEST_FAILm
1203 #define SKIPm          GREATEST_SKIPm
1204 #define SET_SETUP      GREATEST_SET_SETUP_CB
1205 #define SET_TEARDOWN   GREATEST_SET_TEARDOWN_CB
1206 #define CHECK_CALL     GREATEST_CHECK_CALL
1207 #define SHUFFLE_TESTS  GREATEST_SHUFFLE_TESTS
1208 #define SHUFFLE_SUITES GREATEST_SHUFFLE_SUITES
1209 
1210 #ifdef GREATEST_VA_ARGS
1211 #define RUN_TESTp      GREATEST_RUN_TESTp
1212 #endif
1213 
1214 #if GREATEST_USE_LONGJMP
1215 #define ASSERT_OR_LONGJMP  GREATEST_ASSERT_OR_LONGJMP
1216 #define ASSERT_OR_LONGJMPm GREATEST_ASSERT_OR_LONGJMPm
1217 #define FAIL_WITH_LONGJMP  GREATEST_FAIL_WITH_LONGJMP
1218 #define FAIL_WITH_LONGJMPm GREATEST_FAIL_WITH_LONGJMPm
1219 #endif
1220 
1221 #endif /* USE_ABBREVS */
1222 
1223 #if defined(__cplusplus) && !defined(GREATEST_NO_EXTERN_CPLUSPLUS)
1224 }
1225 #endif
1226 
1227 #endif
1228