cmocka: Print skipped tests in group summary
[platform/upstream/cmocka.git] / src / cmocka.c
1 /*
2  * Copyright 2008 Google Inc.
3  * Copyright 2014-2015 Andreas Schneider <asn@cryptomilk.org>
4  * Copyright 2015      Jakub Hrozek <jakub.hrozek@posteo.se>
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  * http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  */
18 #ifdef HAVE_CONFIG_H
19 #include "config.h"
20 #endif
21
22 #ifdef HAVE_MALLOC_H
23 #include <malloc.h>
24 #endif
25
26 #ifdef HAVE_INTTYPES_H
27 #include <inttypes.h>
28 #endif
29
30 #ifdef HAVE_SIGNAL_H
31 #include <signal.h>
32 #endif
33
34 #include <stdint.h>
35 #include <setjmp.h>
36 #include <stdarg.h>
37 #include <stddef.h>
38 #include <stdio.h>
39 #include <stdlib.h>
40 #include <string.h>
41 #include <time.h>
42
43 /*
44  * This allows to add a platform specific header file. Some embedded platforms
45  * sometimes miss certain types and definitions.
46  *
47  * Example:
48  *
49  * typedef unsigned long int uintptr_t
50  * #define _UINTPTR_T 1
51  * #define _UINTPTR_T_DEFINED 1
52  */
53 #ifdef CMOCKA_PLATFORM_INCLUDE
54 # include "cmocka_platform.h"
55 #endif /* CMOCKA_PLATFORM_INCLUDE */
56
57 #include <cmocka.h>
58 #include <cmocka_private.h>
59
60 /* Size of guard bytes around dynamically allocated blocks. */
61 #define MALLOC_GUARD_SIZE 16
62 /* Pattern used to initialize guard blocks. */
63 #define MALLOC_GUARD_PATTERN 0xEF
64 /* Pattern used to initialize memory allocated with test_malloc(). */
65 #define MALLOC_ALLOC_PATTERN 0xBA
66 #define MALLOC_FREE_PATTERN 0xCD
67 /* Alignment of allocated blocks.  NOTE: This must be base2. */
68 #define MALLOC_ALIGNMENT sizeof(size_t)
69
70 /* Printf formatting for source code locations. */
71 #define SOURCE_LOCATION_FORMAT "%s:%u"
72
73 #if defined(HAVE_GCC_THREAD_LOCAL_STORAGE)
74 # define CMOCKA_THREAD __thread
75 #elif defined(HAVE_MSVC_THREAD_LOCAL_STORAGE)
76 # define CMOCKA_THREAD __declspec(thread)
77 #else
78 # define CMOCKA_THREAD
79 #endif
80
81 #ifdef HAVE_CLOCK_GETTIME_REALTIME
82 #define CMOCKA_CLOCK_GETTIME(clock_id, ts) clock_gettime((clock_id), (ts))
83 #else
84 #define CMOCKA_CLOCK_GETTIME(clock_id, ts)
85 #endif
86
87 /*
88  * Declare and initialize the pointer member of ValuePointer variable name
89  * with ptr.
90  */
91 #define declare_initialize_value_pointer_pointer(name, ptr) \
92     ValuePointer name ; \
93     name.value = 0; \
94     name.x.pointer = (void*)(ptr)
95
96 /*
97  * Declare and initialize the value member of ValuePointer variable name
98  * with val.
99  */
100 #define declare_initialize_value_pointer_value(name, val) \
101     ValuePointer name ; \
102     name.value = val
103
104 /* Cast a LargestIntegralType to pointer_type via a ValuePointer. */
105 #define cast_largest_integral_type_to_pointer( \
106     pointer_type, largest_integral_type) \
107     ((pointer_type)((ValuePointer*)&(largest_integral_type))->x.pointer)
108
109 /* Used to cast LargetIntegralType to void* and vice versa. */
110 typedef union ValuePointer {
111     LargestIntegralType value;
112     struct {
113 #if defined(WORDS_BIGENDIAN) && (WORDS_SIZEOF_VOID_P == 4)
114         unsigned int padding;
115 #endif
116         void *pointer;
117     } x;
118 } ValuePointer;
119
120 /* Doubly linked list node. */
121 typedef struct ListNode {
122     const void *value;
123     int refcount;
124     struct ListNode *next;
125     struct ListNode *prev;
126 } ListNode;
127
128 /* Debug information for malloc(). */
129 typedef struct MallocBlockInfo {
130     void* block;              /* Address of the block returned by malloc(). */
131     size_t allocated_size;    /* Total size of the allocated block. */
132     size_t size;              /* Request block size. */
133     SourceLocation location;  /* Where the block was allocated. */
134     ListNode node;            /* Node within list of all allocated blocks. */
135 } MallocBlockInfo;
136
137 /* State of each test. */
138 typedef struct TestState {
139     const ListNode *check_point; /* Check point of the test if there's a */
140                                  /* setup function. */
141     void *state;                 /* State associated with the test. */
142 } TestState;
143
144 /* Determines whether two values are the same. */
145 typedef int (*EqualityFunction)(const void *left, const void *right);
146
147 /* Value of a symbol and the place it was declared. */
148 typedef struct SymbolValue {
149     SourceLocation location;
150     LargestIntegralType value;
151 } SymbolValue;
152
153 /*
154  * Contains a list of values for a symbol.
155  * NOTE: Each structure referenced by symbol_values_list_head must have a
156  * SourceLocation as its' first member.
157  */
158 typedef struct SymbolMapValue {
159     const char *symbol_name;
160     ListNode symbol_values_list_head;
161 } SymbolMapValue;
162
163 /* Used by list_free() to deallocate values referenced by list nodes. */
164 typedef void (*CleanupListValue)(const void *value, void *cleanup_value_data);
165
166 /* Structure used to check the range of integer types.a */
167 typedef struct CheckIntegerRange {
168     CheckParameterEvent event;
169     LargestIntegralType minimum;
170     LargestIntegralType maximum;
171 } CheckIntegerRange;
172
173 /* Structure used to check whether an integer value is in a set. */
174 typedef struct CheckIntegerSet {
175     CheckParameterEvent event;
176     const LargestIntegralType *set;
177     size_t size_of_set;
178 } CheckIntegerSet;
179
180 /* Used to check whether a parameter matches the area of memory referenced by
181  * this structure.  */
182 typedef struct CheckMemoryData {
183     CheckParameterEvent event;
184     const void *memory;
185     size_t size;
186 } CheckMemoryData;
187
188 static ListNode* list_initialize(ListNode * const node);
189 static ListNode* list_add(ListNode * const head, ListNode *new_node);
190 static ListNode* list_add_value(ListNode * const head, const void *value,
191                                      const int count);
192 static ListNode* list_remove(
193     ListNode * const node, const CleanupListValue cleanup_value,
194     void * const cleanup_value_data);
195 static void list_remove_free(
196     ListNode * const node, const CleanupListValue cleanup_value,
197     void * const cleanup_value_data);
198 static int list_empty(const ListNode * const head);
199 static int list_find(
200     ListNode * const head, const void *value,
201     const EqualityFunction equal_func, ListNode **output);
202 static int list_first(ListNode * const head, ListNode **output);
203 static ListNode* list_free(
204     ListNode * const head, const CleanupListValue cleanup_value,
205     void * const cleanup_value_data);
206
207 static void add_symbol_value(
208     ListNode * const symbol_map_head, const char * const symbol_names[],
209     const size_t number_of_symbol_names, const void* value, const int count);
210 static int get_symbol_value(
211     ListNode * const symbol_map_head, const char * const symbol_names[],
212     const size_t number_of_symbol_names, void **output);
213 static void free_value(const void *value, void *cleanup_value_data);
214 static void free_symbol_map_value(
215     const void *value, void *cleanup_value_data);
216 static void remove_always_return_values(ListNode * const map_head,
217                                         const size_t number_of_symbol_names);
218 static int check_for_leftover_values(
219     const ListNode * const map_head, const char * const error_message,
220     const size_t number_of_symbol_names);
221 /*
222  * This must be called at the beginning of a test to initialize some data
223  * structures.
224  */
225 static void initialize_testing(const char *test_name);
226
227 /* This must be called at the end of a test to free() allocated structures. */
228 static void teardown_testing(const char *test_name);
229
230 static int cm_error_message_enabled = 1;
231 static CMOCKA_THREAD char *cm_error_message;
232
233 void cm_print_error(const char * const format, ...) CMOCKA_PRINTF_ATTRIBUTE(1, 2);
234
235 /*
236  * Keeps track of the calling context returned by setenv() so that the fail()
237  * method can jump out of a test.
238  */
239 static CMOCKA_THREAD jmp_buf global_run_test_env;
240 static CMOCKA_THREAD int global_running_test = 0;
241
242 /* Keeps track of the calling context returned by setenv() so that */
243 /* mock_assert() can optionally jump back to expect_assert_failure(). */
244 jmp_buf global_expect_assert_env;
245 int global_expecting_assert = 0;
246 const char *global_last_failed_assert = NULL;
247 static int global_skip_test;
248
249 /* Keeps a map of the values that functions will have to return to provide */
250 /* mocked interfaces. */
251 static CMOCKA_THREAD ListNode global_function_result_map_head;
252 /* Location of the last mock value returned was declared. */
253 static CMOCKA_THREAD SourceLocation global_last_mock_value_location;
254
255 /* Keeps a map of the values that functions expect as parameters to their
256  * mocked interfaces. */
257 static CMOCKA_THREAD ListNode global_function_parameter_map_head;
258 /* Location of last parameter value checked was declared. */
259 static CMOCKA_THREAD SourceLocation global_last_parameter_location;
260
261 /* List of all currently allocated blocks. */
262 static CMOCKA_THREAD ListNode global_allocated_blocks;
263
264 static enum cm_message_output global_msg_output = CM_OUTPUT_STDOUT;
265
266 #ifndef _WIN32
267 /* Signals caught by exception_handler(). */
268 static const int exception_signals[] = {
269     SIGFPE,
270     SIGILL,
271     SIGSEGV,
272 #ifdef SIGBUS
273     SIGBUS,
274 #endif
275 #ifdef SIGSYS
276     SIGSYS,
277 #endif
278 };
279
280 /* Default signal functions that should be restored after a test is complete. */
281 typedef void (*SignalFunction)(int signal);
282 static SignalFunction default_signal_functions[
283     ARRAY_SIZE(exception_signals)];
284
285 #else /* _WIN32 */
286
287 /* The default exception filter. */
288 static LPTOP_LEVEL_EXCEPTION_FILTER previous_exception_filter;
289
290 /* Fatal exceptions. */
291 typedef struct ExceptionCodeInfo {
292     DWORD code;
293     const char* description;
294 } ExceptionCodeInfo;
295
296 #define EXCEPTION_CODE_INFO(exception_code) {exception_code, #exception_code}
297
298 static const ExceptionCodeInfo exception_codes[] = {
299     EXCEPTION_CODE_INFO(EXCEPTION_ACCESS_VIOLATION),
300     EXCEPTION_CODE_INFO(EXCEPTION_ARRAY_BOUNDS_EXCEEDED),
301     EXCEPTION_CODE_INFO(EXCEPTION_DATATYPE_MISALIGNMENT),
302     EXCEPTION_CODE_INFO(EXCEPTION_FLT_DENORMAL_OPERAND),
303     EXCEPTION_CODE_INFO(EXCEPTION_FLT_DIVIDE_BY_ZERO),
304     EXCEPTION_CODE_INFO(EXCEPTION_FLT_INEXACT_RESULT),
305     EXCEPTION_CODE_INFO(EXCEPTION_FLT_INVALID_OPERATION),
306     EXCEPTION_CODE_INFO(EXCEPTION_FLT_OVERFLOW),
307     EXCEPTION_CODE_INFO(EXCEPTION_FLT_STACK_CHECK),
308     EXCEPTION_CODE_INFO(EXCEPTION_FLT_UNDERFLOW),
309     EXCEPTION_CODE_INFO(EXCEPTION_GUARD_PAGE),
310     EXCEPTION_CODE_INFO(EXCEPTION_ILLEGAL_INSTRUCTION),
311     EXCEPTION_CODE_INFO(EXCEPTION_INT_DIVIDE_BY_ZERO),
312     EXCEPTION_CODE_INFO(EXCEPTION_INT_OVERFLOW),
313     EXCEPTION_CODE_INFO(EXCEPTION_INVALID_DISPOSITION),
314     EXCEPTION_CODE_INFO(EXCEPTION_INVALID_HANDLE),
315     EXCEPTION_CODE_INFO(EXCEPTION_IN_PAGE_ERROR),
316     EXCEPTION_CODE_INFO(EXCEPTION_NONCONTINUABLE_EXCEPTION),
317     EXCEPTION_CODE_INFO(EXCEPTION_PRIV_INSTRUCTION),
318     EXCEPTION_CODE_INFO(EXCEPTION_STACK_OVERFLOW),
319 };
320 #endif /* !_WIN32 */
321
322 enum CMUnitTestStatus {
323     CM_TEST_NOT_STARTED,
324     CM_TEST_PASSED,
325     CM_TEST_FAILED,
326     CM_TEST_ERROR,
327     CM_TEST_SKIPPED,
328 };
329
330 struct CMUnitTestState {
331     const ListNode *check_point; /* Check point of the test if there's a setup function. */
332     const struct CMUnitTest *test; /* Point to array element in the tests we get passed */
333     void *state; /* State associated with the test */
334     const char *error_message; /* The error messages by the test */
335     enum CMUnitTestStatus status; /* PASSED, FAILED, ABORT ... */
336     double runtime; /* Time calculations */
337 };
338
339 /* Exit the currently executing test. */
340 static void exit_test(const int quit_application)
341 {
342     const char *abort_test = getenv("CMOCKA_TEST_ABORT");
343
344     if (abort_test != NULL && abort_test[0] == '1') {
345         print_error("%s", cm_error_message);
346         abort();
347     } else if (global_running_test) {
348         longjmp(global_run_test_env, 1);
349     } else if (quit_application) {
350         exit(-1);
351     }
352 }
353
354 void _skip(const char * const file, const int line)
355 {
356     cm_print_error(SOURCE_LOCATION_FORMAT ": Skipped!\n", file, line);
357     global_skip_test = 1;
358     exit_test(1);
359 }
360
361 /* Initialize a SourceLocation structure. */
362 static void initialize_source_location(SourceLocation * const location) {
363     assert_non_null(location);
364     location->file = NULL;
365     location->line = 0;
366 }
367
368
369 /* Determine whether a source location is currently set. */
370 static int source_location_is_set(const SourceLocation * const location) {
371     assert_non_null(location);
372     return location->file && location->line;
373 }
374
375
376 /* Set a source location. */
377 static void set_source_location(
378     SourceLocation * const location, const char * const file,
379     const int line) {
380     assert_non_null(location);
381     location->file = file;
382     location->line = line;
383 }
384
385
386 /* Create function results and expected parameter lists. */
387 void initialize_testing(const char *test_name) {
388         (void)test_name;
389     list_initialize(&global_function_result_map_head);
390     initialize_source_location(&global_last_mock_value_location);
391     list_initialize(&global_function_parameter_map_head);
392     initialize_source_location(&global_last_parameter_location);
393 }
394
395
396 static void fail_if_leftover_values(const char *test_name) {
397     int error_occurred = 0;
398         (void)test_name;
399     remove_always_return_values(&global_function_result_map_head, 1);
400     if (check_for_leftover_values(
401             &global_function_result_map_head,
402             "%s() has remaining non-returned values.\n", 1)) {
403         error_occurred = 1;
404     }
405
406     remove_always_return_values(&global_function_parameter_map_head, 2);
407     if (check_for_leftover_values(
408             &global_function_parameter_map_head,
409             "%s parameter still has values that haven't been checked.\n", 2)) {
410         error_occurred = 1;
411     }
412     if (error_occurred) {
413         exit_test(1);
414     }
415 }
416
417
418 static void teardown_testing(const char *test_name) {
419         (void)test_name;
420     list_free(&global_function_result_map_head, free_symbol_map_value,
421               (void*)0);
422     initialize_source_location(&global_last_mock_value_location);
423     list_free(&global_function_parameter_map_head, free_symbol_map_value,
424               (void*)1);
425     initialize_source_location(&global_last_parameter_location);
426 }
427
428 /* Initialize a list node. */
429 static ListNode* list_initialize(ListNode * const node) {
430     node->value = NULL;
431     node->next = node;
432     node->prev = node;
433     node->refcount = 1;
434     return node;
435 }
436
437
438 /*
439  * Adds a value at the tail of a given list.
440  * The node referencing the value is allocated from the heap.
441  */
442 static ListNode* list_add_value(ListNode * const head, const void *value,
443                                      const int refcount) {
444     ListNode * const new_node = (ListNode*)malloc(sizeof(ListNode));
445     assert_non_null(head);
446     assert_non_null(value);
447     new_node->value = value;
448     new_node->refcount = refcount;
449     return list_add(head, new_node);
450 }
451
452
453 /* Add new_node to the end of the list. */
454 static ListNode* list_add(ListNode * const head, ListNode *new_node) {
455     assert_non_null(head);
456     assert_non_null(new_node);
457     new_node->next = head;
458     new_node->prev = head->prev;
459     head->prev->next = new_node;
460     head->prev = new_node;
461     return new_node;
462 }
463
464
465 /* Remove a node from a list. */
466 static ListNode* list_remove(
467         ListNode * const node, const CleanupListValue cleanup_value,
468         void * const cleanup_value_data) {
469     assert_non_null(node);
470     node->prev->next = node->next;
471     node->next->prev = node->prev;
472     if (cleanup_value) {
473         cleanup_value(node->value, cleanup_value_data);
474     }
475     return node;
476 }
477
478
479 /* Remove a list node from a list and free the node. */
480 static void list_remove_free(
481         ListNode * const node, const CleanupListValue cleanup_value,
482         void * const cleanup_value_data) {
483     assert_non_null(node);
484     free(list_remove(node, cleanup_value, cleanup_value_data));
485 }
486
487
488 /*
489  * Frees memory kept by a linked list The cleanup_value function is called for
490  * every "value" field of nodes in the list, except for the head.  In addition
491  * to each list value, cleanup_value_data is passed to each call to
492  * cleanup_value.  The head of the list is not deallocated.
493  */
494 static ListNode* list_free(
495         ListNode * const head, const CleanupListValue cleanup_value,
496         void * const cleanup_value_data) {
497     assert_non_null(head);
498     while (!list_empty(head)) {
499         list_remove_free(head->next, cleanup_value, cleanup_value_data);
500     }
501     return head;
502 }
503
504
505 /* Determine whether a list is empty. */
506 static int list_empty(const ListNode * const head) {
507     assert_non_null(head);
508     return head->next == head;
509 }
510
511
512 /*
513  * Find a value in the list using the equal_func to compare each node with the
514  * value.
515  */
516 static int list_find(ListNode * const head, const void *value,
517                      const EqualityFunction equal_func, ListNode **output) {
518     ListNode *current;
519     assert_non_null(head);
520     for (current = head->next; current != head; current = current->next) {
521         if (equal_func(current->value, value)) {
522             *output = current;
523             return 1;
524         }
525     }
526     return 0;
527 }
528
529 /* Returns the first node of a list */
530 static int list_first(ListNode * const head, ListNode **output) {
531     ListNode *target_node;
532     assert_non_null(head);
533     if (list_empty(head)) {
534         return 0;
535     }
536     target_node = head->next;
537     *output = target_node;
538     return 1;
539 }
540
541
542 /* Deallocate a value referenced by a list. */
543 static void free_value(const void *value, void *cleanup_value_data) {
544         (void)cleanup_value_data;
545     assert_non_null(value);
546     free((void*)value);
547 }
548
549
550 /* Releases memory associated to a symbol_map_value. */
551 static void free_symbol_map_value(const void *value,
552                                   void *cleanup_value_data) {
553     SymbolMapValue * const map_value = (SymbolMapValue*)value;
554     const LargestIntegralType children = cast_ptr_to_largest_integral_type(cleanup_value_data);
555     assert_non_null(value);
556     list_free(&map_value->symbol_values_list_head,
557               children ? free_symbol_map_value : free_value,
558               (void *) ((uintptr_t)children - 1));
559     free(map_value);
560 }
561
562
563 /*
564  * Determine whether a symbol name referenced by a symbol_map_value matches the
565  * specified function name.
566  */
567 static int symbol_names_match(const void *map_value, const void *symbol) {
568     return !strcmp(((SymbolMapValue*)map_value)->symbol_name,
569                    (const char*)symbol);
570 }
571
572
573 /*
574  * Adds a value to the queue of values associated with the given hierarchy of
575  * symbols.  It's assumed value is allocated from the heap.
576  */
577 static void add_symbol_value(ListNode * const symbol_map_head,
578                              const char * const symbol_names[],
579                              const size_t number_of_symbol_names,
580                              const void* value, const int refcount) {
581     const char* symbol_name;
582     ListNode *target_node;
583     SymbolMapValue *target_map_value;
584     assert_non_null(symbol_map_head);
585     assert_non_null(symbol_names);
586     assert_true(number_of_symbol_names);
587     symbol_name = symbol_names[0];
588
589     if (!list_find(symbol_map_head, symbol_name, symbol_names_match,
590                    &target_node)) {
591         SymbolMapValue * const new_symbol_map_value =
592             (SymbolMapValue*)malloc(sizeof(*new_symbol_map_value));
593         new_symbol_map_value->symbol_name = symbol_name;
594         list_initialize(&new_symbol_map_value->symbol_values_list_head);
595         target_node = list_add_value(symbol_map_head, new_symbol_map_value,
596                                           1);
597     }
598
599     target_map_value = (SymbolMapValue*)target_node->value;
600     if (number_of_symbol_names == 1) {
601             list_add_value(&target_map_value->symbol_values_list_head,
602                                 value, refcount);
603     } else {
604         add_symbol_value(&target_map_value->symbol_values_list_head,
605                          &symbol_names[1], number_of_symbol_names - 1, value,
606                          refcount);
607     }
608 }
609
610
611 /*
612  * Gets the next value associated with the given hierarchy of symbols.
613  * The value is returned as an output parameter with the function returning the
614  * node's old refcount value if a value is found, 0 otherwise.  This means that
615  * a return value of 1 indicates the node was just removed from the list.
616  */
617 static int get_symbol_value(
618         ListNode * const head, const char * const symbol_names[],
619         const size_t number_of_symbol_names, void **output) {
620     const char* symbol_name;
621     ListNode *target_node;
622     assert_non_null(head);
623     assert_non_null(symbol_names);
624     assert_true(number_of_symbol_names);
625     assert_non_null(output);
626     symbol_name = symbol_names[0];
627
628     if (list_find(head, symbol_name, symbol_names_match, &target_node)) {
629         SymbolMapValue *map_value;
630         ListNode *child_list;
631         int return_value = 0;
632         assert_non_null(target_node);
633         assert_non_null(target_node->value);
634
635         map_value = (SymbolMapValue*)target_node->value;
636         child_list = &map_value->symbol_values_list_head;
637
638         if (number_of_symbol_names == 1) {
639             ListNode *value_node = NULL;
640             return_value = list_first(child_list, &value_node);
641             assert_true(return_value);
642             *output = (void*) value_node->value;
643             return_value = value_node->refcount;
644             if (--value_node->refcount == 0) {
645                 list_remove_free(value_node, NULL, NULL);
646             }
647         } else {
648             return_value = get_symbol_value(
649                 child_list, &symbol_names[1], number_of_symbol_names - 1,
650                 output);
651         }
652         if (list_empty(child_list)) {
653             list_remove_free(target_node, free_symbol_map_value, (void*)0);
654         }
655         return return_value;
656     } else {
657         cm_print_error("No entries for symbol %s.\n", symbol_name);
658     }
659     return 0;
660 }
661
662
663 /*
664  * Traverse down a tree of symbol values and remove the first symbol value
665  * in each branch that has a refcount < -1 (i.e should always be returned
666  * and has been returned at least once).
667  */
668 static void remove_always_return_values(ListNode * const map_head,
669                                         const size_t number_of_symbol_names) {
670     ListNode *current;
671     assert_non_null(map_head);
672     assert_true(number_of_symbol_names);
673     current = map_head->next;
674     while (current != map_head) {
675         SymbolMapValue * const value = (SymbolMapValue*)current->value;
676         ListNode * const next = current->next;
677         ListNode *child_list;
678         assert_non_null(value);
679         child_list = &value->symbol_values_list_head;
680
681         if (!list_empty(child_list)) {
682             if (number_of_symbol_names == 1) {
683                 ListNode * const child_node = child_list->next;
684                 /* If this item has been returned more than once, free it. */
685                 if (child_node->refcount < -1) {
686                     list_remove_free(child_node, free_value, NULL);
687                 }
688             } else {
689                 remove_always_return_values(child_list,
690                                             number_of_symbol_names - 1);
691             }
692         }
693
694         if (list_empty(child_list)) {
695             list_remove_free(current, free_value, NULL);
696         }
697         current = next;
698     }
699 }
700
701 /*
702  * Checks if there are any leftover values set up by the test that were never
703  * retrieved through execution, and fail the test if that is the case.
704  */
705 static int check_for_leftover_values(
706         const ListNode * const map_head, const char * const error_message,
707         const size_t number_of_symbol_names) {
708     const ListNode *current;
709     int symbols_with_leftover_values = 0;
710     assert_non_null(map_head);
711     assert_true(number_of_symbol_names);
712
713     for (current = map_head->next; current != map_head;
714          current = current->next) {
715         const SymbolMapValue * const value =
716             (SymbolMapValue*)current->value;
717         const ListNode *child_list;
718         assert_non_null(value);
719         child_list = &value->symbol_values_list_head;
720
721         if (!list_empty(child_list)) {
722             if (number_of_symbol_names == 1) {
723                 const ListNode *child_node;
724                 cm_print_error(error_message, value->symbol_name);
725
726                 for (child_node = child_list->next; child_node != child_list;
727                      child_node = child_node->next) {
728                     const SourceLocation * const location =
729                         (const SourceLocation*)child_node->value;
730                     cm_print_error(SOURCE_LOCATION_FORMAT
731                                    ": note: remaining item was declared here\n",
732                                    location->file, location->line);
733                 }
734             } else {
735                 cm_print_error("%s.", value->symbol_name);
736                 check_for_leftover_values(child_list, error_message,
737                                           number_of_symbol_names - 1);
738             }
739             symbols_with_leftover_values ++;
740         }
741     }
742     return symbols_with_leftover_values;
743 }
744
745
746 /* Get the next return value for the specified mock function. */
747 LargestIntegralType _mock(const char * const function, const char* const file,
748                           const int line) {
749     void *result;
750     const int rc = get_symbol_value(&global_function_result_map_head,
751                                     &function, 1, &result);
752     if (rc) {
753         SymbolValue * const symbol = (SymbolValue*)result;
754         const LargestIntegralType value = symbol->value;
755         global_last_mock_value_location = symbol->location;
756         if (rc == 1) {
757             free(symbol);
758         }
759         return value;
760     } else {
761         cm_print_error(SOURCE_LOCATION_FORMAT ": error: Could not get value "
762                        "to mock function %s\n", file, line, function);
763         if (source_location_is_set(&global_last_mock_value_location)) {
764             cm_print_error(SOURCE_LOCATION_FORMAT
765                            ": note: Previously returned mock value was declared here\n",
766                            global_last_mock_value_location.file,
767                            global_last_mock_value_location.line);
768         } else {
769             cm_print_error("There were no previously returned mock values for "
770                            "this test.\n");
771         }
772         exit_test(1);
773     }
774     return 0;
775 }
776
777
778 /* Add a return value for the specified mock function name. */
779 void _will_return(const char * const function_name, const char * const file,
780                   const int line, const LargestIntegralType value,
781                   const int count) {
782     SymbolValue * const return_value =
783             (SymbolValue*)malloc(sizeof(*return_value));
784     assert_true(count > 0 || count == -1);
785     return_value->value = value;
786     set_source_location(&return_value->location, file, line);
787     add_symbol_value(&global_function_result_map_head, &function_name, 1,
788                      return_value, count);
789 }
790
791
792 /*
793  * Add a custom parameter checking function.  If the event parameter is NULL
794  * the event structure is allocated internally by this function.  If event
795  * parameter is provided it must be allocated on the heap and doesn't need to
796  * be deallocated by the caller.
797  */
798 void _expect_check(
799         const char* const function, const char* const parameter,
800         const char* const file, const int line,
801         const CheckParameterValue check_function,
802         const LargestIntegralType check_data,
803         CheckParameterEvent * const event, const int count) {
804     CheckParameterEvent * const check =
805         event ? event : (CheckParameterEvent*)malloc(sizeof(*check));
806     const char* symbols[] = {function, parameter};
807     check->parameter_name = parameter;
808     check->check_value = check_function;
809     check->check_value_data = check_data;
810     set_source_location(&check->location, file, line);
811     add_symbol_value(&global_function_parameter_map_head, symbols, 2, check,
812                      count);
813 }
814
815
816 /* Returns 1 if the specified values are equal.  If the values are not equal
817  * an error is displayed and 0 is returned. */
818 static int values_equal_display_error(const LargestIntegralType left,
819                                       const LargestIntegralType right) {
820     const int equal = left == right;
821     if (!equal) {
822         cm_print_error(LargestIntegralTypePrintfFormat " != "
823                        LargestIntegralTypePrintfFormat "\n", left, right);
824     }
825     return equal;
826 }
827
828 /*
829  * Returns 1 if the specified values are not equal.  If the values are equal
830  * an error is displayed and 0 is returned. */
831 static int values_not_equal_display_error(const LargestIntegralType left,
832                                           const LargestIntegralType right) {
833     const int not_equal = left != right;
834     if (!not_equal) {
835         cm_print_error(LargestIntegralTypePrintfFormat " == "
836                        LargestIntegralTypePrintfFormat "\n", left, right);
837     }
838     return not_equal;
839 }
840
841
842 /*
843  * Determine whether value is contained within check_integer_set.
844  * If invert is 0 and the value is in the set 1 is returned, otherwise 0 is
845  * returned and an error is displayed.  If invert is 1 and the value is not
846  * in the set 1 is returned, otherwise 0 is returned and an error is
847  * displayed.
848  */
849 static int value_in_set_display_error(
850         const LargestIntegralType value,
851         const CheckIntegerSet * const check_integer_set, const int invert) {
852     int succeeded = invert;
853     assert_non_null(check_integer_set);
854     {
855         const LargestIntegralType * const set = check_integer_set->set;
856         const size_t size_of_set = check_integer_set->size_of_set;
857         size_t i;
858         for (i = 0; i < size_of_set; i++) {
859             if (set[i] == value) {
860                 /* If invert = 0 and item is found, succeeded = 1. */
861                 /* If invert = 1 and item is found, succeeded = 0. */
862                 succeeded = !succeeded;
863                 break;
864             }
865         }
866         if (succeeded) {
867             return 1;
868         }
869         cm_print_error("%" PRIu64 " is %sin the set (", value,
870                        invert ? "" : "not ");
871         for (i = 0; i < size_of_set; i++) {
872             cm_print_error("%" PRIu64 ", ", set[i]);
873         }
874         cm_print_error(")\n");
875     }
876     return 0;
877 }
878
879
880 /*
881  * Determine whether a value is within the specified range.  If the value is
882  * within the specified range 1 is returned.  If the value isn't within the
883  * specified range an error is displayed and 0 is returned.
884  */
885 static int integer_in_range_display_error(
886         const LargestIntegralType value, const LargestIntegralType range_min,
887         const LargestIntegralType range_max) {
888     if (value >= range_min && value <= range_max) {
889         return 1;
890     }
891     cm_print_error("%" PRIu64 " is not within the range %" PRIu64 "-%" PRIu64 "\n",
892                    value, range_min, range_max);
893     return 0;
894 }
895
896
897 /*
898  * Determine whether a value is within the specified range.  If the value
899  * is not within the range 1 is returned.  If the value is within the
900  * specified range an error is displayed and zero is returned.
901  */
902 static int integer_not_in_range_display_error(
903         const LargestIntegralType value, const LargestIntegralType range_min,
904         const LargestIntegralType range_max) {
905     if (value < range_min || value > range_max) {
906         return 1;
907     }
908     cm_print_error("%" PRIu64 " is within the range %" PRIu64 "-%" PRIu64 "\n",
909                    value, range_min, range_max);
910     return 0;
911 }
912
913
914 /*
915  * Determine whether the specified strings are equal.  If the strings are equal
916  * 1 is returned.  If they're not equal an error is displayed and 0 is
917  * returned.
918  */
919 static int string_equal_display_error(
920         const char * const left, const char * const right) {
921     if (strcmp(left, right) == 0) {
922         return 1;
923     }
924     cm_print_error("\"%s\" != \"%s\"\n", left, right);
925     return 0;
926 }
927
928
929 /*
930  * Determine whether the specified strings are equal.  If the strings are not
931  * equal 1 is returned.  If they're not equal an error is displayed and 0 is
932  * returned
933  */
934 static int string_not_equal_display_error(
935         const char * const left, const char * const right) {
936     if (strcmp(left, right) != 0) {
937         return 1;
938     }
939     cm_print_error("\"%s\" == \"%s\"\n", left, right);
940     return 0;
941 }
942
943
944 /*
945  * Determine whether the specified areas of memory are equal.  If they're equal
946  * 1 is returned otherwise an error is displayed and 0 is returned.
947  */
948 static int memory_equal_display_error(const char* const a, const char* const b,
949                                       const size_t size) {
950     int differences = 0;
951     size_t i;
952     for (i = 0; i < size; i++) {
953         const char l = a[i];
954         const char r = b[i];
955         if (l != r) {
956             cm_print_error("difference at offset %" PRIdS " 0x%02x 0x%02x\n",
957                            i, l, r);
958             differences ++;
959         }
960     }
961     if (differences) {
962         cm_print_error("%d bytes of %p and %p differ\n", differences,
963                     a, b);
964         return 0;
965     }
966     return 1;
967 }
968
969
970 /*
971  * Determine whether the specified areas of memory are not equal.  If they're
972  * not equal 1 is returned otherwise an error is displayed and 0 is
973  * returned.
974  */
975 static int memory_not_equal_display_error(
976         const char* const a, const char* const b, const size_t size) {
977     size_t same = 0;
978     size_t i;
979     for (i = 0; i < size; i++) {
980         const char l = a[i];
981         const char r = b[i];
982         if (l == r) {
983             same ++;
984         }
985     }
986     if (same == size) {
987         cm_print_error("%"PRIdS "bytes of %p and %p the same\n", same,
988                     a, b);
989         return 0;
990     }
991     return 1;
992 }
993
994
995 /* CheckParameterValue callback to check whether a value is within a set. */
996 static int check_in_set(const LargestIntegralType value,
997                         const LargestIntegralType check_value_data) {
998     return value_in_set_display_error(value,
999         cast_largest_integral_type_to_pointer(CheckIntegerSet*,
1000                                               check_value_data), 0);
1001 }
1002
1003
1004 /* CheckParameterValue callback to check whether a value isn't within a set. */
1005 static int check_not_in_set(const LargestIntegralType value,
1006                             const LargestIntegralType check_value_data) {
1007     return value_in_set_display_error(value,
1008         cast_largest_integral_type_to_pointer(CheckIntegerSet*,
1009                                               check_value_data), 1);
1010 }
1011
1012
1013 /* Create the callback data for check_in_set() or check_not_in_set() and
1014  * register a check event. */
1015 static void expect_set(
1016         const char* const function, const char* const parameter,
1017         const char* const file, const int line,
1018         const LargestIntegralType values[], const size_t number_of_values,
1019         const CheckParameterValue check_function, const int count) {
1020     CheckIntegerSet * const check_integer_set =
1021         (CheckIntegerSet*)malloc(sizeof(*check_integer_set) +
1022                (sizeof(values[0]) * number_of_values));
1023     LargestIntegralType * const set = (LargestIntegralType*)(
1024         check_integer_set + 1);
1025     declare_initialize_value_pointer_pointer(check_data, check_integer_set);
1026     assert_non_null(values);
1027     assert_true(number_of_values);
1028     memcpy(set, values, number_of_values * sizeof(values[0]));
1029     check_integer_set->set = set;
1030     check_integer_set->size_of_set = number_of_values;
1031     _expect_check(
1032         function, parameter, file, line, check_function,
1033         check_data.value, &check_integer_set->event, count);
1034 }
1035
1036
1037 /* Add an event to check whether a value is in a set. */
1038 void _expect_in_set(
1039         const char* const function, const char* const parameter,
1040         const char* const file, const int line,
1041         const LargestIntegralType values[], const size_t number_of_values,
1042         const int count) {
1043     expect_set(function, parameter, file, line, values, number_of_values,
1044                check_in_set, count);
1045 }
1046
1047
1048 /* Add an event to check whether a value isn't in a set. */
1049 void _expect_not_in_set(
1050         const char* const function, const char* const parameter,
1051         const char* const file, const int line,
1052         const LargestIntegralType values[], const size_t number_of_values,
1053         const int count) {
1054     expect_set(function, parameter, file, line, values, number_of_values,
1055                check_not_in_set, count);
1056 }
1057
1058
1059 /* CheckParameterValue callback to check whether a value is within a range. */
1060 static int check_in_range(const LargestIntegralType value,
1061                           const LargestIntegralType check_value_data) {
1062     CheckIntegerRange * const check_integer_range =
1063         cast_largest_integral_type_to_pointer(CheckIntegerRange*,
1064                                               check_value_data);
1065     assert_non_null(check_integer_range);
1066     return integer_in_range_display_error(value, check_integer_range->minimum,
1067                                           check_integer_range->maximum);
1068 }
1069
1070
1071 /* CheckParameterValue callback to check whether a value is not within a range. */
1072 static int check_not_in_range(const LargestIntegralType value,
1073                               const LargestIntegralType check_value_data) {
1074     CheckIntegerRange * const check_integer_range =
1075         cast_largest_integral_type_to_pointer(CheckIntegerRange*,
1076                                               check_value_data);
1077     assert_non_null(check_integer_range);
1078     return integer_not_in_range_display_error(
1079         value, check_integer_range->minimum, check_integer_range->maximum);
1080 }
1081
1082
1083 /* Create the callback data for check_in_range() or check_not_in_range() and
1084  * register a check event. */
1085 static void expect_range(
1086         const char* const function, const char* const parameter,
1087         const char* const file, const int line,
1088         const LargestIntegralType minimum, const LargestIntegralType maximum,
1089         const CheckParameterValue check_function, const int count) {
1090     CheckIntegerRange * const check_integer_range =
1091         (CheckIntegerRange*)malloc(sizeof(*check_integer_range));
1092     declare_initialize_value_pointer_pointer(check_data, check_integer_range);
1093     check_integer_range->minimum = minimum;
1094     check_integer_range->maximum = maximum;
1095     _expect_check(function, parameter, file, line, check_function,
1096                   check_data.value, &check_integer_range->event, count);
1097 }
1098
1099
1100 /* Add an event to determine whether a parameter is within a range. */
1101 void _expect_in_range(
1102         const char* const function, const char* const parameter,
1103         const char* const file, const int line,
1104         const LargestIntegralType minimum, const LargestIntegralType maximum,
1105         const int count) {
1106     expect_range(function, parameter, file, line, minimum, maximum,
1107                  check_in_range, count);
1108 }
1109
1110
1111 /* Add an event to determine whether a parameter is not within a range. */
1112 void _expect_not_in_range(
1113         const char* const function, const char* const parameter,
1114         const char* const file, const int line,
1115         const LargestIntegralType minimum, const LargestIntegralType maximum,
1116         const int count) {
1117     expect_range(function, parameter, file, line, minimum, maximum,
1118                  check_not_in_range, count);
1119 }
1120
1121
1122 /* CheckParameterValue callback to check whether a value is equal to an
1123  * expected value. */
1124 static int check_value(const LargestIntegralType value,
1125                        const LargestIntegralType check_value_data) {
1126     return values_equal_display_error(value, check_value_data);
1127 }
1128
1129
1130 /* Add an event to check a parameter equals an expected value. */
1131 void _expect_value(
1132         const char* const function, const char* const parameter,
1133         const char* const file, const int line,
1134         const LargestIntegralType value, const int count) {
1135     _expect_check(function, parameter, file, line, check_value, value, NULL,
1136                   count);
1137 }
1138
1139
1140 /* CheckParameterValue callback to check whether a value is not equal to an
1141  * expected value. */
1142 static int check_not_value(const LargestIntegralType value,
1143                            const LargestIntegralType check_value_data) {
1144     return values_not_equal_display_error(value, check_value_data);
1145 }
1146
1147
1148 /* Add an event to check a parameter is not equal to an expected value. */
1149 void _expect_not_value(
1150         const char* const function, const char* const parameter,
1151         const char* const file, const int line,
1152         const LargestIntegralType value, const int count) {
1153     _expect_check(function, parameter, file, line, check_not_value, value,
1154                   NULL, count);
1155 }
1156
1157
1158 /* CheckParameterValue callback to check whether a parameter equals a string. */
1159 static int check_string(const LargestIntegralType value,
1160                         const LargestIntegralType check_value_data) {
1161     return string_equal_display_error(
1162         cast_largest_integral_type_to_pointer(char*, value),
1163         cast_largest_integral_type_to_pointer(char*, check_value_data));
1164 }
1165
1166
1167 /* Add an event to check whether a parameter is equal to a string. */
1168 void _expect_string(
1169         const char* const function, const char* const parameter,
1170         const char* const file, const int line, const char* string,
1171         const int count) {
1172     declare_initialize_value_pointer_pointer(string_pointer,
1173                                              discard_const(string));
1174     _expect_check(function, parameter, file, line, check_string,
1175                   string_pointer.value, NULL, count);
1176 }
1177
1178
1179 /* CheckParameterValue callback to check whether a parameter is not equals to
1180  * a string. */
1181 static int check_not_string(const LargestIntegralType value,
1182                             const LargestIntegralType check_value_data) {
1183     return string_not_equal_display_error(
1184         cast_largest_integral_type_to_pointer(char*, value),
1185         cast_largest_integral_type_to_pointer(char*, check_value_data));
1186 }
1187
1188
1189 /* Add an event to check whether a parameter is not equal to a string. */
1190 void _expect_not_string(
1191         const char* const function, const char* const parameter,
1192         const char* const file, const int line, const char* string,
1193         const int count) {
1194     declare_initialize_value_pointer_pointer(string_pointer,
1195                                              discard_const(string));
1196     _expect_check(function, parameter, file, line, check_not_string,
1197                   string_pointer.value, NULL, count);
1198 }
1199
1200 /* CheckParameterValue callback to check whether a parameter equals an area of
1201  * memory. */
1202 static int check_memory(const LargestIntegralType value,
1203                         const LargestIntegralType check_value_data) {
1204     CheckMemoryData * const check = cast_largest_integral_type_to_pointer(
1205         CheckMemoryData*, check_value_data);
1206     assert_non_null(check);
1207     return memory_equal_display_error(
1208         cast_largest_integral_type_to_pointer(const char*, value),
1209         (const char*)check->memory, check->size);
1210 }
1211
1212
1213 /* Create the callback data for check_memory() or check_not_memory() and
1214  * register a check event. */
1215 static void expect_memory_setup(
1216         const char* const function, const char* const parameter,
1217         const char* const file, const int line,
1218         const void * const memory, const size_t size,
1219         const CheckParameterValue check_function, const int count) {
1220     CheckMemoryData * const check_data =
1221             (CheckMemoryData*)malloc(sizeof(*check_data) + size);
1222     void * const mem = (void*)(check_data + 1);
1223     declare_initialize_value_pointer_pointer(check_data_pointer, check_data);
1224     assert_non_null(memory);
1225     assert_true(size);
1226     memcpy(mem, memory, size);
1227     check_data->memory = mem;
1228     check_data->size = size;
1229     _expect_check(function, parameter, file, line, check_function,
1230                   check_data_pointer.value, &check_data->event, count);
1231 }
1232
1233
1234 /* Add an event to check whether a parameter matches an area of memory. */
1235 void _expect_memory(
1236         const char* const function, const char* const parameter,
1237         const char* const file, const int line, const void* const memory,
1238         const size_t size, const int count) {
1239     expect_memory_setup(function, parameter, file, line, memory, size,
1240                         check_memory, count);
1241 }
1242
1243
1244 /* CheckParameterValue callback to check whether a parameter is not equal to
1245  * an area of memory. */
1246 static int check_not_memory(const LargestIntegralType value,
1247                             const LargestIntegralType check_value_data) {
1248     CheckMemoryData * const check = cast_largest_integral_type_to_pointer(
1249         CheckMemoryData*, check_value_data);
1250     assert_non_null(check);
1251     return memory_not_equal_display_error(
1252         cast_largest_integral_type_to_pointer(const char*, value),
1253         (const char*)check->memory,
1254         check->size);
1255 }
1256
1257
1258 /* Add an event to check whether a parameter doesn't match an area of memory. */
1259 void _expect_not_memory(
1260         const char* const function, const char* const parameter,
1261         const char* const file, const int line, const void* const memory,
1262         const size_t size, const int count) {
1263     expect_memory_setup(function, parameter, file, line, memory, size,
1264                         check_not_memory, count);
1265 }
1266
1267
1268 /* CheckParameterValue callback that always returns 1. */
1269 static int check_any(const LargestIntegralType value,
1270                      const LargestIntegralType check_value_data) {
1271         (void)value;
1272         (void)check_value_data;
1273     return 1;
1274 }
1275
1276
1277 /* Add an event to allow any value for a parameter. */
1278 void _expect_any(
1279         const char* const function, const char* const parameter,
1280         const char* const file, const int line, const int count) {
1281     _expect_check(function, parameter, file, line, check_any, 0, NULL,
1282                   count);
1283 }
1284
1285
1286 void _check_expected(
1287         const char * const function_name, const char * const parameter_name,
1288         const char* file, const int line, const LargestIntegralType value) {
1289     void *result;
1290     const char* symbols[] = {function_name, parameter_name};
1291     const int rc = get_symbol_value(&global_function_parameter_map_head,
1292                                     symbols, 2, &result);
1293     if (rc) {
1294         CheckParameterEvent * const check = (CheckParameterEvent*)result;
1295         int check_succeeded;
1296         global_last_parameter_location = check->location;
1297         check_succeeded = check->check_value(value, check->check_value_data);
1298         if (rc == 1) {
1299             free(check);
1300         }
1301         if (!check_succeeded) {
1302             cm_print_error(SOURCE_LOCATION_FORMAT
1303                            ": error: Check of parameter %s, function %s failed\n"
1304                            SOURCE_LOCATION_FORMAT
1305                            ": note: Expected parameter declared here\n",
1306                            file, line,
1307                            parameter_name, function_name,
1308                            global_last_parameter_location.file,
1309                            global_last_parameter_location.line);
1310             _fail(file, line);
1311         }
1312     } else {
1313         cm_print_error(SOURCE_LOCATION_FORMAT ": error: Could not get value "
1314                     "to check parameter %s of function %s\n", file, line,
1315                     parameter_name, function_name);
1316         if (source_location_is_set(&global_last_parameter_location)) {
1317             cm_print_error(SOURCE_LOCATION_FORMAT
1318                         ": note: Previously declared parameter value was declared here\n",
1319                         global_last_parameter_location.file,
1320                         global_last_parameter_location.line);
1321         } else {
1322             cm_print_error("There were no previously declared parameter values "
1323                         "for this test.\n");
1324         }
1325         exit_test(1);
1326     }
1327 }
1328
1329
1330 /* Replacement for assert. */
1331 void mock_assert(const int result, const char* const expression,
1332                  const char* const file, const int line) {
1333     if (!result) {
1334         if (global_expecting_assert) {
1335             global_last_failed_assert = expression;
1336             longjmp(global_expect_assert_env, result);
1337         } else {
1338             cm_print_error("ASSERT: %s\n", expression);
1339             _fail(file, line);
1340         }
1341     }
1342 }
1343
1344
1345 void _assert_true(const LargestIntegralType result,
1346                   const char * const expression,
1347                   const char * const file, const int line) {
1348     if (!result) {
1349         cm_print_error("%s\n", expression);
1350         _fail(file, line);
1351     }
1352 }
1353
1354 void _assert_return_code(const LargestIntegralType result,
1355                          size_t rlen,
1356                          const LargestIntegralType error,
1357                          const char * const expression,
1358                          const char * const file,
1359                          const int line)
1360 {
1361     LargestIntegralType valmax;
1362
1363
1364     switch (rlen) {
1365     case 1:
1366         valmax = 255;
1367         break;
1368     case 2:
1369         valmax = 32767;
1370         break;
1371     case 4:
1372         valmax = 2147483647;
1373         break;
1374     case 8:
1375     default:
1376         if (rlen > sizeof(valmax)) {
1377             valmax = 2147483647;
1378         } else {
1379             valmax = 9223372036854775807L;
1380         }
1381         break;
1382     }
1383
1384     if (result > valmax - 1) {
1385         if (error > 0) {
1386             cm_print_error("%s < 0, errno(%" PRIu64 "): %s\n",
1387                            expression, error, strerror((int)error));
1388         } else {
1389             cm_print_error("%s < 0\n", expression);
1390         }
1391         _fail(file, line);
1392     }
1393 }
1394
1395 void _assert_int_equal(
1396         const LargestIntegralType a, const LargestIntegralType b,
1397         const char * const file, const int line) {
1398     if (!values_equal_display_error(a, b)) {
1399         _fail(file, line);
1400     }
1401 }
1402
1403
1404 void _assert_int_not_equal(
1405         const LargestIntegralType a, const LargestIntegralType b,
1406         const char * const file, const int line) {
1407     if (!values_not_equal_display_error(a, b)) {
1408         _fail(file, line);
1409     }
1410 }
1411
1412
1413 void _assert_string_equal(const char * const a, const char * const b,
1414                           const char * const file, const int line) {
1415     if (!string_equal_display_error(a, b)) {
1416         _fail(file, line);
1417     }
1418 }
1419
1420
1421 void _assert_string_not_equal(const char * const a, const char * const b,
1422                               const char *file, const int line) {
1423     if (!string_not_equal_display_error(a, b)) {
1424         _fail(file, line);
1425     }
1426 }
1427
1428
1429 void _assert_memory_equal(const void * const a, const void * const b,
1430                           const size_t size, const char* const file,
1431                           const int line) {
1432     if (!memory_equal_display_error((const char*)a, (const char*)b, size)) {
1433         _fail(file, line);
1434     }
1435 }
1436
1437
1438 void _assert_memory_not_equal(const void * const a, const void * const b,
1439                               const size_t size, const char* const file,
1440                               const int line) {
1441     if (!memory_not_equal_display_error((const char*)a, (const char*)b,
1442                                         size)) {
1443         _fail(file, line);
1444     }
1445 }
1446
1447
1448 void _assert_in_range(
1449         const LargestIntegralType value, const LargestIntegralType minimum,
1450         const LargestIntegralType maximum, const char* const file,
1451         const int line) {
1452     if (!integer_in_range_display_error(value, minimum, maximum)) {
1453         _fail(file, line);
1454     }
1455 }
1456
1457 void _assert_not_in_range(
1458         const LargestIntegralType value, const LargestIntegralType minimum,
1459         const LargestIntegralType maximum, const char* const file,
1460         const int line) {
1461     if (!integer_not_in_range_display_error(value, minimum, maximum)) {
1462         _fail(file, line);
1463     }
1464 }
1465
1466 void _assert_in_set(const LargestIntegralType value,
1467                     const LargestIntegralType values[],
1468                     const size_t number_of_values, const char* const file,
1469                     const int line) {
1470     CheckIntegerSet check_integer_set;
1471     check_integer_set.set = values;
1472     check_integer_set.size_of_set = number_of_values;
1473     if (!value_in_set_display_error(value, &check_integer_set, 0)) {
1474         _fail(file, line);
1475     }
1476 }
1477
1478 void _assert_not_in_set(const LargestIntegralType value,
1479                         const LargestIntegralType values[],
1480                         const size_t number_of_values, const char* const file,
1481                         const int line) {
1482     CheckIntegerSet check_integer_set;
1483     check_integer_set.set = values;
1484     check_integer_set.size_of_set = number_of_values;
1485     if (!value_in_set_display_error(value, &check_integer_set, 1)) {
1486         _fail(file, line);
1487     }
1488 }
1489
1490
1491 /* Get the list of allocated blocks. */
1492 static ListNode* get_allocated_blocks_list() {
1493     /* If it initialized, initialize the list of allocated blocks. */
1494     if (!global_allocated_blocks.value) {
1495         list_initialize(&global_allocated_blocks);
1496         global_allocated_blocks.value = (void*)1;
1497     }
1498     return &global_allocated_blocks;
1499 }
1500
1501 static void *libc_malloc(size_t size)
1502 {
1503 #undef malloc
1504     return malloc(size);
1505 #define malloc test_malloc
1506 }
1507
1508 static void libc_free(void *ptr)
1509 {
1510 #undef free
1511     free(ptr);
1512 #define free test_free
1513 }
1514
1515 static void *libc_realloc(void *ptr, size_t size)
1516 {
1517 #undef realloc
1518     return realloc(ptr, size);
1519 #define realloc test_realloc
1520 }
1521
1522 static void vcm_print_error(const char* const format,
1523                             va_list args) CMOCKA_PRINTF_ATTRIBUTE(1, 0);
1524
1525 /* It's important to use the libc malloc and free here otherwise
1526  * the automatic free of leaked blocks can reap the error messages
1527  */
1528 static void vcm_print_error(const char* const format, va_list args)
1529 {
1530     char buffer[1024];
1531     size_t msg_len = 0;
1532     va_list ap;
1533     int len;
1534
1535     len = vsnprintf(buffer, sizeof(buffer), format, args);
1536     if (len < 0) {
1537         /* TODO */
1538         return;
1539     }
1540
1541     if (cm_error_message == NULL) {
1542         /* CREATE MESSAGE */
1543
1544         cm_error_message = libc_malloc(len + 1);
1545         if (cm_error_message == NULL) {
1546             /* TODO */
1547             return;
1548         }
1549     } else {
1550         /* APPEND MESSAGE */
1551         char *tmp;
1552
1553         msg_len = strlen(cm_error_message);
1554         tmp = libc_realloc(cm_error_message, msg_len + len + 1);
1555         if (tmp == NULL) {
1556             return;
1557         }
1558         cm_error_message = tmp;
1559     }
1560
1561     if (((size_t)len) < sizeof(buffer)) {
1562         /* Use len + 1 to also copy '\0' */
1563         memcpy(cm_error_message + msg_len, buffer, len + 1);
1564     } else {
1565         va_copy(ap, args);
1566         vsnprintf(cm_error_message + msg_len, len, format, ap);
1567         va_end(ap);
1568     }
1569 }
1570
1571 static void vcm_free_error(char *err_msg)
1572 {
1573     libc_free(err_msg);
1574 }
1575
1576 /* Use the real malloc in this function. */
1577 #undef malloc
1578 void* _test_malloc(const size_t size, const char* file, const int line) {
1579     char* ptr;
1580     MallocBlockInfo *block_info;
1581     ListNode * const block_list = get_allocated_blocks_list();
1582     const size_t allocate_size = size + (MALLOC_GUARD_SIZE * 2) +
1583         sizeof(*block_info) + MALLOC_ALIGNMENT;
1584     char* const block = (char*)malloc(allocate_size);
1585     assert_non_null(block);
1586
1587     /* Calculate the returned address. */
1588     ptr = (char*)(((size_t)block + MALLOC_GUARD_SIZE + sizeof(*block_info) +
1589                   MALLOC_ALIGNMENT) & ~(MALLOC_ALIGNMENT - 1));
1590
1591     /* Initialize the guard blocks. */
1592     memset(ptr - MALLOC_GUARD_SIZE, MALLOC_GUARD_PATTERN, MALLOC_GUARD_SIZE);
1593     memset(ptr + size, MALLOC_GUARD_PATTERN, MALLOC_GUARD_SIZE);
1594     memset(ptr, MALLOC_ALLOC_PATTERN, size);
1595
1596     block_info = (MallocBlockInfo*)(ptr - (MALLOC_GUARD_SIZE +
1597                                              sizeof(*block_info)));
1598     set_source_location(&block_info->location, file, line);
1599     block_info->allocated_size = allocate_size;
1600     block_info->size = size;
1601     block_info->block = block;
1602     block_info->node.value = block_info;
1603     list_add(block_list, &block_info->node);
1604     return ptr;
1605 }
1606 #define malloc test_malloc
1607
1608
1609 void* _test_calloc(const size_t number_of_elements, const size_t size,
1610                    const char* file, const int line) {
1611     void* const ptr = _test_malloc(number_of_elements * size, file, line);
1612     if (ptr) {
1613         memset(ptr, 0, number_of_elements * size);
1614     }
1615     return ptr;
1616 }
1617
1618
1619 /* Use the real free in this function. */
1620 #undef free
1621 void _test_free(void* const ptr, const char* file, const int line) {
1622     unsigned int i;
1623     char *block = discard_const_p(char, ptr);
1624     MallocBlockInfo *block_info;
1625
1626     if (ptr == NULL) {
1627         return;
1628     }
1629
1630     _assert_true(cast_ptr_to_largest_integral_type(ptr), "ptr", file, line);
1631     block_info = (MallocBlockInfo*)(block - (MALLOC_GUARD_SIZE +
1632                                                sizeof(*block_info)));
1633     /* Check the guard blocks. */
1634     {
1635         char *guards[2] = {block - MALLOC_GUARD_SIZE,
1636                            block + block_info->size};
1637         for (i = 0; i < ARRAY_SIZE(guards); i++) {
1638             unsigned int j;
1639             char * const guard = guards[i];
1640             for (j = 0; j < MALLOC_GUARD_SIZE; j++) {
1641                 const char diff = guard[j] - MALLOC_GUARD_PATTERN;
1642                 if (diff) {
1643                     cm_print_error(SOURCE_LOCATION_FORMAT
1644                                    ": error: Guard block of %p size=%lu is corrupt\n"
1645                                    SOURCE_LOCATION_FORMAT ": note: allocated here at %p\n",
1646                                    file, line,
1647                                    ptr, (unsigned long)block_info->size,
1648                                    block_info->location.file, block_info->location.line,
1649                                    &guard[j]);
1650                     _fail(file, line);
1651                 }
1652             }
1653         }
1654     }
1655     list_remove(&block_info->node, NULL, NULL);
1656
1657     block = discard_const_p(char, block_info->block);
1658     memset(block, MALLOC_FREE_PATTERN, block_info->allocated_size);
1659     free(block);
1660 }
1661 #define free test_free
1662
1663 #undef realloc
1664 void *_test_realloc(void *ptr,
1665                    const size_t size,
1666                    const char *file,
1667                    const int line)
1668 {
1669     MallocBlockInfo *block_info;
1670     char *block = ptr;
1671     size_t block_size = size;
1672     void *new;
1673
1674     if (ptr == NULL) {
1675         return _test_malloc(size, file, line);
1676     }
1677
1678     if (size == 0) {
1679         _test_free(ptr, file, line);
1680         return NULL;
1681     }
1682
1683     block_info = (MallocBlockInfo*)(block - (MALLOC_GUARD_SIZE +
1684                                              sizeof(*block_info)));
1685
1686     new = _test_malloc(size, file, line);
1687     if (new == NULL) {
1688         return NULL;
1689     }
1690
1691     if (block_info->size < size) {
1692         block_size = block_info->size;
1693     }
1694
1695     memcpy(new, ptr, block_size);
1696
1697     /* Free previous memory */
1698     _test_free(ptr, file, line);
1699
1700     return new;
1701 }
1702 #define realloc test_realloc
1703
1704 /* Crudely checkpoint the current heap state. */
1705 static const ListNode* check_point_allocated_blocks() {
1706     return get_allocated_blocks_list()->prev;
1707 }
1708
1709
1710 /* Display the blocks allocated after the specified check point.  This
1711  * function returns the number of blocks displayed. */
1712 static int display_allocated_blocks(const ListNode * const check_point) {
1713     const ListNode * const head = get_allocated_blocks_list();
1714     const ListNode *node;
1715     int allocated_blocks = 0;
1716     assert_non_null(check_point);
1717     assert_non_null(check_point->next);
1718
1719     for (node = check_point->next; node != head; node = node->next) {
1720         const MallocBlockInfo * const block_info =
1721                 (const MallocBlockInfo*)node->value;
1722         assert_non_null(block_info);
1723
1724         if (!allocated_blocks) {
1725             cm_print_error("Blocks allocated...\n");
1726         }
1727         cm_print_error(SOURCE_LOCATION_FORMAT ": note: block %p allocated here\n",
1728                        block_info->location.file,
1729                        block_info->location.line,
1730                        block_info->block);
1731         allocated_blocks ++;
1732     }
1733     return allocated_blocks;
1734 }
1735
1736
1737 /* Free all blocks allocated after the specified check point. */
1738 static void free_allocated_blocks(const ListNode * const check_point) {
1739     const ListNode * const head = get_allocated_blocks_list();
1740     const ListNode *node;
1741     assert_non_null(check_point);
1742
1743     node = check_point->next;
1744     assert_non_null(node);
1745
1746     while (node != head) {
1747         MallocBlockInfo * const block_info = (MallocBlockInfo*)node->value;
1748         node = node->next;
1749         free(discard_const_p(char, block_info) + sizeof(*block_info) + MALLOC_GUARD_SIZE);
1750     }
1751 }
1752
1753
1754 /* Fail if any any blocks are allocated after the specified check point. */
1755 static void fail_if_blocks_allocated(const ListNode * const check_point,
1756                                      const char * const test_name) {
1757     const int allocated_blocks = display_allocated_blocks(check_point);
1758     if (allocated_blocks) {
1759         free_allocated_blocks(check_point);
1760         cm_print_error("ERROR: %s leaked %d block(s)\n", test_name,
1761                        allocated_blocks);
1762         exit_test(1);
1763     }
1764 }
1765
1766
1767 void _fail(const char * const file, const int line) {
1768     cm_print_error(SOURCE_LOCATION_FORMAT ": error: Failure!\n", file, line);
1769     exit_test(1);
1770 }
1771
1772
1773 #ifndef _WIN32
1774 static void exception_handler(int sig) {
1775 #ifdef HAVE_STRSIGNAL
1776     cm_print_error("Test failed with exception: %s\n", strsignal(sig));
1777 #else
1778     cm_print_error("Test failed with exception: %d\n", sig);
1779 #endif
1780     exit_test(1);
1781 }
1782
1783 #else /* _WIN32 */
1784
1785 static LONG WINAPI exception_filter(EXCEPTION_POINTERS *exception_pointers) {
1786     EXCEPTION_RECORD * const exception_record =
1787         exception_pointers->ExceptionRecord;
1788     const DWORD code = exception_record->ExceptionCode;
1789     unsigned int i;
1790     for (i = 0; i < ARRAY_SIZE(exception_codes); i++) {
1791         const ExceptionCodeInfo * const code_info = &exception_codes[i];
1792         if (code == code_info->code) {
1793             static int shown_debug_message = 0;
1794             fflush(stdout);
1795             cm_print_error("%s occurred at %p.\n", code_info->description,
1796                         exception_record->ExceptionAddress);
1797             if (!shown_debug_message) {
1798                 cm_print_error(
1799                     "\n"
1800                     "To debug in Visual Studio...\n"
1801                     "1. Select menu item File->Open Project\n"
1802                     "2. Change 'Files of type' to 'Executable Files'\n"
1803                     "3. Open this executable.\n"
1804                     "4. Select menu item Debug->Start\n"
1805                     "\n"
1806                     "Alternatively, set the environment variable \n"
1807                     "UNIT_TESTING_DEBUG to 1 and rebuild this executable, \n"
1808                     "then click 'Debug' in the popup dialog box.\n"
1809                     "\n");
1810                 shown_debug_message = 1;
1811             }
1812             exit_test(0);
1813             return EXCEPTION_EXECUTE_HANDLER;
1814         }
1815     }
1816     return EXCEPTION_CONTINUE_SEARCH;
1817 }
1818 #endif /* !_WIN32 */
1819
1820 void cm_print_error(const char * const format, ...)
1821 {
1822     va_list args;
1823     va_start(args, format);
1824     if (cm_error_message_enabled) {
1825         vcm_print_error(format, args);
1826     } else {
1827         vprint_error(format, args);
1828     }
1829     va_end(args);
1830 }
1831
1832 /* Standard output and error print methods. */
1833 void vprint_message(const char* const format, va_list args) {
1834     char buffer[1024];
1835     vsnprintf(buffer, sizeof(buffer), format, args);
1836     printf("%s", buffer);
1837     fflush(stdout);
1838 #ifdef _WIN32
1839     OutputDebugString(buffer);
1840 #endif /* _WIN32 */
1841 }
1842
1843
1844 void vprint_error(const char* const format, va_list args) {
1845     char buffer[1024];
1846     vsnprintf(buffer, sizeof(buffer), format, args);
1847     fprintf(stderr, "%s", buffer);
1848     fflush(stderr);
1849 #ifdef _WIN32
1850     OutputDebugString(buffer);
1851 #endif /* _WIN32 */
1852 }
1853
1854
1855 void print_message(const char* const format, ...) {
1856     va_list args;
1857     va_start(args, format);
1858     vprint_message(format, args);
1859     va_end(args);
1860 }
1861
1862
1863 void print_error(const char* const format, ...) {
1864     va_list args;
1865     va_start(args, format);
1866     vprint_error(format, args);
1867     va_end(args);
1868 }
1869
1870 /* New formatter */
1871 static enum cm_message_output cm_get_output(void)
1872 {
1873     enum cm_message_output output = global_msg_output;
1874     char *env;
1875
1876     env = getenv("CMOCKA_MESSAGE_OUTPUT");
1877     if (env != NULL) {
1878         if (strcasecmp(env, "STDOUT") == 0) {
1879             output = CM_OUTPUT_STDOUT;
1880         } else if (strcasecmp(env, "SUBUNIT") == 0) {
1881             output = CM_OUTPUT_SUBUNIT;
1882         } else if (strcasecmp(env, "TAP") == 0) {
1883             output = CM_OUTPUT_TAP;
1884         } else if (strcasecmp(env, "XML") == 0) {
1885             output = CM_OUTPUT_XML;
1886         }
1887     }
1888
1889     return output;
1890 }
1891
1892 enum cm_printf_type {
1893     PRINTF_TEST_START,
1894     PRINTF_TEST_SUCCESS,
1895     PRINTF_TEST_FAILURE,
1896     PRINTF_TEST_ERROR,
1897     PRINTF_TEST_SKIPPED,
1898 };
1899
1900 static void cmprintf_group_finish_xml(const char *group_name,
1901                                       size_t total_executed,
1902                                       size_t total_failed,
1903                                       size_t total_errors,
1904                                       size_t total_skipped,
1905                                       double total_runtime,
1906                                       struct CMUnitTestState *cm_tests)
1907 {
1908     FILE *fp = stdout;
1909     int file_opened = 0;
1910     char *env;
1911     size_t i;
1912
1913     env = getenv("CMOCKA_XML_FILE");
1914     if (env != NULL) {
1915         char buf[1024];
1916         snprintf(buf, sizeof(buf), "%s", env);
1917
1918         fp = fopen(buf, "r");
1919         if (fp == NULL) {
1920             fp = fopen(buf, "w");
1921             if (fp != NULL) {
1922                 file_opened = 1;
1923             } else {
1924                 fp = stderr;
1925             }
1926         } else {
1927             fclose(fp);
1928             fp = stderr;
1929         }
1930     }
1931
1932     fprintf(fp, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
1933     fprintf(fp, "<testsuites>\n");
1934     fprintf(fp, "  <testsuite name=\"%s\" time=\"%.3f\" "
1935                 "tests=\"%u\" failures=\"%u\" errors=\"%u\" skipped=\"%u\" >\n",
1936                 group_name,
1937                 total_runtime * 1000, /* miliseconds */
1938                 (unsigned)total_executed,
1939                 (unsigned)total_failed,
1940                 (unsigned)total_errors,
1941                 (unsigned)total_skipped);
1942
1943     for (i = 0; i < total_executed; i++) {
1944         struct CMUnitTestState *cmtest = &cm_tests[i];
1945
1946         fprintf(fp, "    <testcase name=\"%s\" time=\"%.3f\" >\n",
1947                 cmtest->test->name, cmtest->runtime * 1000);
1948
1949         switch (cmtest->status) {
1950         case CM_TEST_ERROR:
1951         case CM_TEST_FAILED:
1952             if (cmtest->error_message != NULL) {
1953                 fprintf(fp, "      <failure><![CDATA[%s]]></failure>\n",
1954                         cmtest->error_message);
1955             } else {
1956                 fprintf(fp, "      <failure message=\"Unknown error\" />\n");
1957             }
1958             break;
1959         case CM_TEST_SKIPPED:
1960             fprintf(fp, "      <skipped/>\n");
1961             break;
1962
1963         case CM_TEST_PASSED:
1964         case CM_TEST_NOT_STARTED:
1965             break;
1966         }
1967
1968         fprintf(fp, "    </testcase>\n");
1969     }
1970
1971     fprintf(fp, "  </testsuite>\n");
1972     fprintf(fp, "</testsuites>\n");
1973
1974     if (file_opened) {
1975         fclose(fp);
1976     }
1977 }
1978
1979 static void cmprintf_group_start_standard(const size_t num_tests)
1980 {
1981     print_message("[==========] Running %u test(s).\n",
1982                   (unsigned)num_tests);
1983 }
1984
1985 static void cmprintf_group_finish_standard(size_t total_executed,
1986                                            size_t total_passed,
1987                                            size_t total_failed,
1988                                            size_t total_errors,
1989                                            size_t total_skipped,
1990                                            struct CMUnitTestState *cm_tests)
1991 {
1992     size_t i;
1993
1994     print_message("[==========] %u test(s) run.\n", (unsigned)total_executed);
1995     print_error("[  PASSED  ] %u test(s).\n",
1996                 (unsigned)(total_passed));
1997
1998     if (total_skipped) {
1999         print_error("[  SKIPPED ] %"PRIdS " test(s), listed below:\n", total_skipped);
2000         for (i = 0; i < total_executed; i++) {
2001             struct CMUnitTestState *cmtest = &cm_tests[i];
2002
2003             if (cmtest->status == CM_TEST_SKIPPED) {
2004                 print_error("[  SKIPPED ] %s\n", cmtest->test->name);
2005             }
2006         }
2007         print_error("\n %u SKIPPED TEST(S)\n", (unsigned)(total_skipped));
2008     }
2009
2010     if (total_failed) {
2011         print_error("[  FAILED  ] %"PRIdS " test(s), listed below:\n", total_failed);
2012         for (i = 0; i < total_executed; i++) {
2013             struct CMUnitTestState *cmtest = &cm_tests[i];
2014
2015             if (cmtest->status == CM_TEST_FAILED) {
2016                 print_error("[  FAILED  ] %s\n", cmtest->test->name);
2017             }
2018         }
2019         print_error("\n %u FAILED TEST(S)\n",
2020                     (unsigned)(total_failed + total_errors));
2021     }
2022 }
2023
2024 static void cmprintf_standard(enum cm_printf_type type,
2025                               const char *test_name,
2026                               const char *error_message)
2027 {
2028     switch (type) {
2029     case PRINTF_TEST_START:
2030         print_message("[ RUN      ] %s\n", test_name);
2031         break;
2032     case PRINTF_TEST_SUCCESS:
2033         print_message("[       OK ] %s\n", test_name);
2034         break;
2035     case PRINTF_TEST_FAILURE:
2036         if (error_message != NULL) {
2037             print_error("%s\n", error_message);
2038         }
2039         print_message("[  FAILED  ] %s\n", test_name);
2040         break;
2041     case PRINTF_TEST_SKIPPED:
2042         print_message("[  SKIPPED ] %s\n", test_name);
2043         break;
2044     case PRINTF_TEST_ERROR:
2045         if (error_message != NULL) {
2046             print_error("%s\n", error_message);
2047         }
2048         print_error("[  ERROR   ] %s\n", test_name);
2049         break;
2050     }
2051 }
2052
2053 static void cmprintf_group_start_tap(const size_t num_tests)
2054 {
2055     print_message("\t1..%u\n", (unsigned)num_tests);
2056 }
2057
2058 static void cmprintf_group_finish_tap(const char *group_name,
2059                                       size_t total_executed,
2060                                       size_t total_passed,
2061                                       size_t total_skipped)
2062 {
2063     const char *status = "not ok";
2064     if (total_passed + total_skipped == total_executed) {
2065         status = "ok";
2066     }
2067     print_message("%s - %s\n", status, group_name);
2068 }
2069
2070 static void cmprintf_tap(enum cm_printf_type type,
2071                          uint32_t test_number,
2072                          const char *test_name,
2073                          const char *error_message)
2074 {
2075     switch (type) {
2076     case PRINTF_TEST_START:
2077         break;
2078     case PRINTF_TEST_SUCCESS:
2079         print_message("\tok %u - %s\n", (unsigned)test_number, test_name);
2080         break;
2081     case PRINTF_TEST_FAILURE:
2082         print_message("\tnot ok %u - %s\n", (unsigned)test_number, test_name);
2083         if (error_message != NULL) {
2084             char *msg;
2085             char *p;
2086
2087             msg = strdup(error_message);
2088             if (msg == NULL) {
2089                 return;
2090             }
2091             p = msg;
2092
2093             while (p[0] != '\0') {
2094                 char *q = p;
2095
2096                 p = strchr(q, '\n');
2097                 if (p != NULL) {
2098                     p[0] = '\0';
2099                 }
2100
2101                 print_message("\t# %s\n", q);
2102
2103                 if (p == NULL) {
2104                     break;
2105                 }
2106                 p++;
2107             }
2108             libc_free(msg);
2109         }
2110         break;
2111     case PRINTF_TEST_SKIPPED:
2112         print_message("\tnot ok %u # SKIP %s\n", (unsigned)test_number, test_name);
2113         break;
2114     case PRINTF_TEST_ERROR:
2115         print_message("\tnot ok %u - %s %s\n",
2116                       (unsigned)test_number, test_name, error_message);
2117         break;
2118     }
2119 }
2120
2121 static void cmprintf_subunit(enum cm_printf_type type,
2122                              const char *test_name,
2123                              const char *error_message)
2124 {
2125     switch (type) {
2126     case PRINTF_TEST_START:
2127         print_message("test: %s\n", test_name);
2128         break;
2129     case PRINTF_TEST_SUCCESS:
2130         print_message("success: %s\n", test_name);
2131         break;
2132     case PRINTF_TEST_FAILURE:
2133         print_message("failure: %s", test_name);
2134         if (error_message != NULL) {
2135             print_message(" [\n%s]\n", error_message);
2136         }
2137         break;
2138     case PRINTF_TEST_SKIPPED:
2139         print_message("skip: %s\n", test_name);
2140         break;
2141     case PRINTF_TEST_ERROR:
2142         print_message("error: %s [ %s ]\n", test_name, error_message);
2143         break;
2144     }
2145 }
2146
2147 static void cmprintf_group_start(const size_t num_tests)
2148 {
2149     enum cm_message_output output;
2150
2151     output = cm_get_output();
2152
2153     switch (output) {
2154     case CM_OUTPUT_STDOUT:
2155         cmprintf_group_start_standard(num_tests);
2156         break;
2157     case CM_OUTPUT_SUBUNIT:
2158         break;
2159     case CM_OUTPUT_TAP:
2160         cmprintf_group_start_tap(num_tests);
2161         break;
2162     case CM_OUTPUT_XML:
2163         break;
2164     }
2165 }
2166
2167 static void cmprintf_group_finish(const char *group_name,
2168                                   size_t total_executed,
2169                                   size_t total_passed,
2170                                   size_t total_failed,
2171                                   size_t total_errors,
2172                                   size_t total_skipped,
2173                                   double total_runtime,
2174                                   struct CMUnitTestState *cm_tests)
2175 {
2176     enum cm_message_output output;
2177
2178     output = cm_get_output();
2179
2180     switch (output) {
2181     case CM_OUTPUT_STDOUT:
2182         cmprintf_group_finish_standard(total_executed,
2183                                     total_passed,
2184                                     total_failed,
2185                                     total_errors,
2186                                     total_skipped,
2187                                     cm_tests);
2188         break;
2189     case CM_OUTPUT_SUBUNIT:
2190         break;
2191     case CM_OUTPUT_TAP:
2192         cmprintf_group_finish_tap(group_name, total_executed, total_passed, total_skipped);
2193         break;
2194     case CM_OUTPUT_XML:
2195         cmprintf_group_finish_xml(group_name,
2196                                   total_executed,
2197                                   total_failed,
2198                                   total_errors,
2199                                   total_skipped,
2200                                   total_runtime,
2201                                   cm_tests);
2202         break;
2203     }
2204 }
2205
2206 static void cmprintf(enum cm_printf_type type,
2207                      size_t test_number,
2208                      const char *test_name,
2209                      const char *error_message)
2210 {
2211     enum cm_message_output output;
2212
2213     output = cm_get_output();
2214
2215     switch (output) {
2216     case CM_OUTPUT_STDOUT:
2217         cmprintf_standard(type, test_name, error_message);
2218         break;
2219     case CM_OUTPUT_SUBUNIT:
2220         cmprintf_subunit(type, test_name, error_message);
2221         break;
2222     case CM_OUTPUT_TAP:
2223         cmprintf_tap(type, test_number, test_name, error_message);
2224         break;
2225     case CM_OUTPUT_XML:
2226         break;
2227     }
2228 }
2229
2230 void cmocka_set_message_output(enum cm_message_output output)
2231 {
2232     global_msg_output = output;
2233 }
2234
2235 /****************************************************************************
2236  * TIME CALCULATIONS
2237  ****************************************************************************/
2238
2239 #ifdef HAVE_STRUCT_TIMESPEC
2240 static struct timespec cm_tspecdiff(struct timespec time1,
2241                                     struct timespec time0)
2242 {
2243     struct timespec ret;
2244     int xsec = 0;
2245     int sign = 1;
2246
2247     if (time0.tv_nsec > time1.tv_nsec) {
2248         xsec = (int) ((time0.tv_nsec - time1.tv_nsec) / (1E9 + 1));
2249         time0.tv_nsec -= (long int) (1E9 * xsec);
2250         time0.tv_sec += xsec;
2251     }
2252
2253     if ((time1.tv_nsec - time0.tv_nsec) > 1E9) {
2254         xsec = (int) ((time1.tv_nsec - time0.tv_nsec) / 1E9);
2255         time0.tv_nsec += (long int) (1E9 * xsec);
2256         time0.tv_sec -= xsec;
2257     }
2258
2259     ret.tv_sec = time1.tv_sec - time0.tv_sec;
2260     ret.tv_nsec = time1.tv_nsec - time0.tv_nsec;
2261
2262     if (time1.tv_sec < time0.tv_sec) {
2263         sign = -1;
2264     }
2265
2266     ret.tv_sec = ret.tv_sec * sign;
2267
2268     return ret;
2269 }
2270
2271 static double cm_secdiff(struct timespec clock1, struct timespec clock0)
2272 {
2273     double ret;
2274     struct timespec diff;
2275
2276     diff = cm_tspecdiff(clock1, clock0);
2277
2278     ret = diff.tv_sec;
2279     ret += (double) diff.tv_nsec / (double) 1E9;
2280
2281     return ret;
2282 }
2283 #endif /* HAVE_STRUCT_TIMESPEC */
2284
2285 /****************************************************************************
2286  * CMOCKA TEST RUNNER
2287  ****************************************************************************/
2288 static int cmocka_run_one_test_or_fixture(const char *function_name,
2289                                           CMUnitTestFunction test_func,
2290                                           CMFixtureFunction setup_func,
2291                                           CMFixtureFunction teardown_func,
2292                                           void ** const volatile state,
2293                                           const void *const heap_check_point)
2294 {
2295     const ListNode * const volatile check_point = (const ListNode*)
2296         (heap_check_point != NULL ?
2297          heap_check_point : check_point_allocated_blocks());
2298     int handle_exceptions = 1;
2299     void *current_state = NULL;
2300     int rc = 0;
2301
2302     /* FIXME check only one test or fixture is set */
2303
2304     /* Detect if we should handle exceptions */
2305 #ifdef _WIN32
2306     handle_exceptions = !IsDebuggerPresent();
2307 #endif /* _WIN32 */
2308 #ifdef UNIT_TESTING_DEBUG
2309     handle_exceptions = 0;
2310 #endif /* UNIT_TESTING_DEBUG */
2311
2312
2313     if (handle_exceptions) {
2314 #ifndef _WIN32
2315         unsigned int i;
2316         for (i = 0; i < ARRAY_SIZE(exception_signals); i++) {
2317             default_signal_functions[i] = signal(
2318                     exception_signals[i], exception_handler);
2319         }
2320 #else /* _WIN32 */
2321         previous_exception_filter = SetUnhandledExceptionFilter(
2322                 exception_filter);
2323 #endif /* !_WIN32 */
2324     }
2325
2326     /* Init the test structure */
2327     initialize_testing(function_name);
2328
2329     global_running_test = 1;
2330
2331     if (setjmp(global_run_test_env) == 0) {
2332         if (test_func != NULL) {
2333             test_func(state != NULL ? state : &current_state);
2334
2335             fail_if_blocks_allocated(check_point, function_name);
2336             rc = 0;
2337         } else if (setup_func != NULL) {
2338             rc = setup_func(state != NULL ? state : &current_state);
2339
2340             /*
2341              * For setup we can ignore any allocated blocks. We just need to
2342              * ensure they're deallocated on tear down.
2343              */
2344         } else if (teardown_func != NULL) {
2345             rc = teardown_func(state != NULL ? state : &current_state);
2346
2347             fail_if_blocks_allocated(check_point, function_name);
2348         } else {
2349             /* ERROR */
2350         }
2351         fail_if_leftover_values(function_name);
2352         global_running_test = 0;
2353     } else {
2354         /* TEST FAILED */
2355         global_running_test = 0;
2356         rc = -1;
2357     }
2358     teardown_testing(function_name);
2359
2360     if (handle_exceptions) {
2361 #ifndef _WIN32
2362         unsigned int i;
2363         for (i = 0; i < ARRAY_SIZE(exception_signals); i++) {
2364             signal(exception_signals[i], default_signal_functions[i]);
2365         }
2366 #else /* _WIN32 */
2367         if (previous_exception_filter) {
2368             SetUnhandledExceptionFilter(previous_exception_filter);
2369             previous_exception_filter = NULL;
2370         }
2371 #endif /* !_WIN32 */
2372     }
2373
2374     return rc;
2375 }
2376
2377 static int cmocka_run_group_fixture(const char *function_name,
2378                                     CMFixtureFunction setup_func,
2379                                     CMFixtureFunction teardown_func,
2380                                     void **state,
2381                                     const void *const heap_check_point)
2382 {
2383     int rc;
2384
2385     if (setup_func != NULL) {
2386         rc = cmocka_run_one_test_or_fixture(function_name,
2387                                         NULL,
2388                                         setup_func,
2389                                         NULL,
2390                                         state,
2391                                         heap_check_point);
2392     } else {
2393         rc = cmocka_run_one_test_or_fixture(function_name,
2394                                         NULL,
2395                                         NULL,
2396                                         teardown_func,
2397                                         state,
2398                                         heap_check_point);
2399     }
2400
2401     return rc;
2402 }
2403
2404 static int cmocka_run_one_tests(struct CMUnitTestState *test_state)
2405 {
2406 #ifdef HAVE_STRUCT_TIMESPEC
2407     struct timespec start = {
2408         .tv_sec = 0,
2409         .tv_nsec = 0,
2410     };
2411     struct timespec finish = {
2412         .tv_sec = 0,
2413         .tv_nsec = 0,
2414     };
2415 #endif
2416     int rc = 0;
2417
2418     /* Run setup */
2419     if (test_state->test->setup_func != NULL) {
2420         /* Setup the memory check point, it will be evaluated on teardown */
2421         test_state->check_point = check_point_allocated_blocks();
2422
2423         rc = cmocka_run_one_test_or_fixture(test_state->test->name,
2424                                             NULL,
2425                                             test_state->test->setup_func,
2426                                             NULL,
2427                                             &test_state->state,
2428                                             test_state->check_point);
2429         if (rc != 0) {
2430             test_state->status = CM_TEST_ERROR;
2431             cm_print_error("Test setup failed");
2432         }
2433     }
2434
2435     /* Run test */
2436 #ifdef HAVE_STRUCT_TIMESPEC
2437     CMOCKA_CLOCK_GETTIME(CLOCK_REALTIME, &start);
2438 #endif
2439
2440     if (rc == 0) {
2441         rc = cmocka_run_one_test_or_fixture(test_state->test->name,
2442                                             test_state->test->test_func,
2443                                             NULL,
2444                                             NULL,
2445                                             &test_state->state,
2446                                             NULL);
2447         if (rc == 0) {
2448             test_state->status = CM_TEST_PASSED;
2449         } else {
2450             if (global_skip_test) {
2451                 test_state->status = CM_TEST_SKIPPED;
2452                 global_skip_test = 0; /* Do not skip the next test */
2453             } else {
2454                 test_state->status = CM_TEST_FAILED;
2455             }
2456         }
2457         rc = 0;
2458     }
2459
2460     test_state->runtime = 0.0;
2461
2462 #ifdef HAVE_STRUCT_TIMESPEC
2463     CMOCKA_CLOCK_GETTIME(CLOCK_REALTIME, &finish);
2464     test_state->runtime = cm_secdiff(finish, start);
2465 #endif
2466
2467     /* Run teardown */
2468     if (rc == 0 && test_state->test->teardown_func != NULL) {
2469         rc = cmocka_run_one_test_or_fixture(test_state->test->name,
2470                                             NULL,
2471                                             NULL,
2472                                             test_state->test->teardown_func,
2473                                             &test_state->state,
2474                                             test_state->check_point);
2475         if (rc != 0) {
2476             test_state->status = CM_TEST_ERROR;
2477             cm_print_error("Test teardown failed");
2478         }
2479     }
2480
2481     test_state->error_message = cm_error_message;
2482     cm_error_message = NULL;
2483
2484     return rc;
2485 }
2486
2487 int _cmocka_run_group_tests(const char *group_name,
2488                             const struct CMUnitTest * const tests,
2489                             const size_t num_tests,
2490                             CMFixtureFunction group_setup,
2491                             CMFixtureFunction group_teardown)
2492 {
2493     struct CMUnitTestState *cm_tests;
2494     const ListNode *group_check_point = check_point_allocated_blocks();
2495     void *group_state = NULL;
2496     size_t total_failed = 0;
2497     size_t total_passed = 0;
2498     size_t total_executed = 0;
2499     size_t total_errors = 0;
2500     size_t total_skipped = 0;
2501     double total_runtime = 0;
2502     size_t i;
2503     int rc;
2504
2505     /* Make sure LargestIntegralType is at least the size of a pointer. */
2506     assert_true(sizeof(LargestIntegralType) >= sizeof(void*));
2507
2508     cm_tests = (struct CMUnitTestState *)libc_malloc(sizeof(struct CMUnitTestState) * num_tests);
2509     if (cm_tests == NULL) {
2510         return -1;
2511     }
2512
2513     cmprintf_group_start(num_tests);
2514
2515     /* Setup cmocka test array */
2516     for (i = 0; i < num_tests; i++) {
2517         cm_tests[i] = (struct CMUnitTestState) {
2518             .test = &tests[i],
2519             .status = CM_TEST_NOT_STARTED,
2520             .state = NULL,
2521         };
2522     }
2523
2524     rc = 0;
2525
2526     /* Run group setup */
2527     if (group_setup != NULL) {
2528         rc = cmocka_run_group_fixture("cmocka_group_setup",
2529                                       group_setup,
2530                                       NULL,
2531                                       &group_state,
2532                                       group_check_point);
2533     }
2534
2535     if (rc == 0) {
2536         /* Execute tests */
2537         for (i = 0; i < num_tests; i++) {
2538             struct CMUnitTestState *cmtest = &cm_tests[i];
2539             size_t test_number = i + 1;
2540
2541             cmprintf(PRINTF_TEST_START, test_number, cmtest->test->name, NULL);
2542
2543             if (group_state != NULL) {
2544                 cm_tests[i].state = group_state;
2545             }
2546             rc = cmocka_run_one_tests(cmtest);
2547             total_executed++;
2548             total_runtime += cmtest->runtime;
2549             if (rc == 0) {
2550                 switch (cmtest->status) {
2551                     case CM_TEST_PASSED:
2552                         cmprintf(PRINTF_TEST_SUCCESS,
2553                                  test_number,
2554                                  cmtest->test->name,
2555                                  cmtest->error_message);
2556                         total_passed++;
2557                         break;
2558                     case CM_TEST_SKIPPED:
2559                         cmprintf(PRINTF_TEST_SKIPPED,
2560                                  test_number,
2561                                  cmtest->test->name,
2562                                  cmtest->error_message);
2563                         total_skipped++;
2564                         break;
2565                     case CM_TEST_FAILED:
2566                         cmprintf(PRINTF_TEST_FAILURE,
2567                                  test_number,
2568                                  cmtest->test->name,
2569                                  cmtest->error_message);
2570                         total_failed++;
2571                         break;
2572                     default:
2573                         cmprintf(PRINTF_TEST_ERROR,
2574                                  test_number,
2575                                  cmtest->test->name,
2576                                  "Internal cmocka error");
2577                         total_errors++;
2578                         break;
2579                 }
2580             } else {
2581                 cmprintf(PRINTF_TEST_ERROR,
2582                          test_number,
2583                          cmtest->test->name,
2584                          "Could not run the test - check test fixtures");
2585                 total_errors++;
2586             }
2587         }
2588     } else {
2589         cmprintf(PRINTF_TEST_ERROR, 0,
2590                  group_name, "Group setup failed");
2591         total_errors++;
2592     }
2593
2594     /* Run group teardown */
2595     if (group_teardown != NULL) {
2596         rc = cmocka_run_group_fixture("cmocka_group_teardown",
2597                                       NULL,
2598                                       group_teardown,
2599                                       &group_state,
2600                                       group_check_point);
2601     }
2602
2603     cmprintf_group_finish(group_name,
2604                           total_executed,
2605                           total_passed,
2606                           total_failed,
2607                           total_errors,
2608                           total_skipped,
2609                           total_runtime,
2610                           cm_tests);
2611
2612     for (i = 0; i < num_tests; i++) {
2613         vcm_free_error(discard_const_p(char, cm_tests[i].error_message));
2614     }
2615     libc_free(cm_tests);
2616     fail_if_blocks_allocated(group_check_point, "cmocka_group_tests");
2617
2618     return total_failed + total_errors;
2619 }
2620
2621 /****************************************************************************
2622  * DEPRECATED TEST RUNNER
2623  ****************************************************************************/
2624
2625 int _run_test(
2626         const char * const function_name,  const UnitTestFunction Function,
2627         void ** const volatile state, const UnitTestFunctionType function_type,
2628         const void* const heap_check_point) {
2629     const ListNode * const volatile check_point = (const ListNode*)
2630         (heap_check_point ?
2631          heap_check_point : check_point_allocated_blocks());
2632     void *current_state = NULL;
2633     volatile int rc = 1;
2634     int handle_exceptions = 1;
2635 #ifdef _WIN32
2636     handle_exceptions = !IsDebuggerPresent();
2637 #endif /* _WIN32 */
2638 #ifdef UNIT_TESTING_DEBUG
2639     handle_exceptions = 0;
2640 #endif /* UNIT_TESTING_DEBUG */
2641
2642     cm_error_message_enabled = 0;
2643
2644     if (handle_exceptions) {
2645 #ifndef _WIN32
2646         unsigned int i;
2647         for (i = 0; i < ARRAY_SIZE(exception_signals); i++) {
2648             default_signal_functions[i] = signal(
2649                 exception_signals[i], exception_handler);
2650         }
2651 #else /* _WIN32 */
2652         previous_exception_filter = SetUnhandledExceptionFilter(
2653             exception_filter);
2654 #endif /* !_WIN32 */
2655     }
2656
2657     if (function_type == UNIT_TEST_FUNCTION_TYPE_TEST) {
2658         print_message("[ RUN      ] %s\n", function_name);
2659     }
2660     initialize_testing(function_name);
2661     global_running_test = 1;
2662     if (setjmp(global_run_test_env) == 0) {
2663         Function(state ? state : &current_state);
2664         fail_if_leftover_values(function_name);
2665
2666         /* If this is a setup function then ignore any allocated blocks
2667          * only ensure they're deallocated on tear down. */
2668         if (function_type != UNIT_TEST_FUNCTION_TYPE_SETUP) {
2669             fail_if_blocks_allocated(check_point, function_name);
2670         }
2671
2672         global_running_test = 0;
2673
2674         if (function_type == UNIT_TEST_FUNCTION_TYPE_TEST) {
2675             print_message("[       OK ] %s\n", function_name);
2676         }
2677         rc = 0;
2678     } else {
2679         global_running_test = 0;
2680         print_message("[  FAILED  ] %s\n", function_name);
2681     }
2682     teardown_testing(function_name);
2683
2684     if (handle_exceptions) {
2685 #ifndef _WIN32
2686         unsigned int i;
2687         for (i = 0; i < ARRAY_SIZE(exception_signals); i++) {
2688             signal(exception_signals[i], default_signal_functions[i]);
2689         }
2690 #else /* _WIN32 */
2691         if (previous_exception_filter) {
2692             SetUnhandledExceptionFilter(previous_exception_filter);
2693             previous_exception_filter = NULL;
2694         }
2695 #endif /* !_WIN32 */
2696     }
2697
2698     return rc;
2699 }
2700
2701
2702 int _run_tests(const UnitTest * const tests, const size_t number_of_tests) {
2703     /* Whether to execute the next test. */
2704     int run_next_test = 1;
2705     /* Whether the previous test failed. */
2706     int previous_test_failed = 0;
2707     /* Whether the previous setup failed. */
2708     int previous_setup_failed = 0;
2709     /* Check point of the heap state. */
2710     const ListNode * const check_point = check_point_allocated_blocks();
2711     /* Current test being executed. */
2712     size_t current_test = 0;
2713     /* Number of tests executed. */
2714     size_t tests_executed = 0;
2715     /* Number of failed tests. */
2716     size_t total_failed = 0;
2717     /* Number of setup functions. */
2718     size_t setups = 0;
2719     /* Number of teardown functions. */
2720     size_t teardowns = 0;
2721     size_t i;
2722     /*
2723      * A stack of test states.  A state is pushed on the stack
2724      * when a test setup occurs and popped on tear down.
2725      */
2726     TestState* test_states =
2727             (TestState*)malloc(number_of_tests * sizeof(*test_states));
2728     /* The number of test states which should be 0 at the end */
2729     long number_of_test_states = 0;
2730     /* Names of the tests that failed. */
2731     const char** failed_names = (const char**)malloc(number_of_tests *
2732                                        sizeof(*failed_names));
2733     void **current_state = NULL;
2734
2735     /* Count setup and teardown functions */
2736     for (i = 0; i < number_of_tests; i++) {
2737         const UnitTest * const test = &tests[i];
2738
2739         if (test->function_type == UNIT_TEST_FUNCTION_TYPE_SETUP) {
2740             setups++;
2741         }
2742
2743         if (test->function_type == UNIT_TEST_FUNCTION_TYPE_TEARDOWN) {
2744             teardowns++;
2745         }
2746     }
2747
2748     print_message("[==========] Running %"PRIdS " test(s).\n",
2749                   number_of_tests - setups - teardowns);
2750
2751     /* Make sure LargestIntegralType is at least the size of a pointer. */
2752     assert_true(sizeof(LargestIntegralType) >= sizeof(void*));
2753
2754     while (current_test < number_of_tests) {
2755         const ListNode *test_check_point = NULL;
2756         TestState *current_TestState;
2757         const UnitTest * const test = &tests[current_test++];
2758         if (!test->function) {
2759             continue;
2760         }
2761
2762         switch (test->function_type) {
2763         case UNIT_TEST_FUNCTION_TYPE_TEST:
2764             if (! previous_setup_failed) {
2765                 run_next_test = 1;
2766             }
2767             break;
2768         case UNIT_TEST_FUNCTION_TYPE_SETUP: {
2769             /* Checkpoint the heap before the setup. */
2770             current_TestState = &test_states[number_of_test_states++];
2771             current_TestState->check_point = check_point_allocated_blocks();
2772             test_check_point = current_TestState->check_point;
2773             current_state = &current_TestState->state;
2774             *current_state = NULL;
2775             run_next_test = 1;
2776             break;
2777         }
2778         case UNIT_TEST_FUNCTION_TYPE_TEARDOWN:
2779             /* Check the heap based on the last setup checkpoint. */
2780             assert_true(number_of_test_states);
2781             current_TestState = &test_states[--number_of_test_states];
2782             test_check_point = current_TestState->check_point;
2783             current_state = &current_TestState->state;
2784             break;
2785         default:
2786             print_error("Invalid unit test function type %d\n",
2787                         test->function_type);
2788             exit_test(1);
2789             break;
2790         }
2791
2792         if (run_next_test) {
2793             int failed = _run_test(test->name, test->function, current_state,
2794                                    test->function_type, test_check_point);
2795             if (failed) {
2796                 failed_names[total_failed] = test->name;
2797             }
2798
2799             switch (test->function_type) {
2800             case UNIT_TEST_FUNCTION_TYPE_TEST:
2801                 previous_test_failed = failed;
2802                 total_failed += failed;
2803                 tests_executed ++;
2804                 break;
2805
2806             case UNIT_TEST_FUNCTION_TYPE_SETUP:
2807                 if (failed) {
2808                     total_failed ++;
2809                     tests_executed ++;
2810                     /* Skip forward until the next test or setup function. */
2811                     run_next_test = 0;
2812                     previous_setup_failed = 1;
2813                 }
2814                 previous_test_failed = 0;
2815                 break;
2816
2817             case UNIT_TEST_FUNCTION_TYPE_TEARDOWN:
2818                 /* If this test failed. */
2819                 if (failed && !previous_test_failed) {
2820                     total_failed ++;
2821                 }
2822                 break;
2823             default:
2824 #ifndef _HPUX
2825                 assert_null("BUG: shouldn't be here!");
2826 #endif
2827                 break;
2828             }
2829         }
2830     }
2831
2832     print_message("[==========] %"PRIdS " test(s) run.\n", tests_executed);
2833     print_error("[  PASSED  ] %"PRIdS " test(s).\n", tests_executed - total_failed);
2834
2835     if (total_failed > 0) {
2836         print_error("[  FAILED  ] %"PRIdS " test(s), listed below:\n", total_failed);
2837         for (i = 0; i < total_failed; i++) {
2838             print_error("[  FAILED  ] %s\n", failed_names[i]);
2839         }
2840     } else {
2841         print_error("\n %"PRIdS " FAILED TEST(S)\n", total_failed);
2842     }
2843
2844     if (number_of_test_states != 0) {
2845         print_error("[  ERROR   ] Mismatched number of setup %"PRIdS " and "
2846                     "teardown %"PRIdS " functions\n", setups, teardowns);
2847         total_failed = (size_t)-1;
2848     }
2849
2850     free(test_states);
2851     free((void*)failed_names);
2852
2853     fail_if_blocks_allocated(check_point, "run_tests");
2854     return (int)total_failed;
2855 }
2856
2857 int _run_group_tests(const UnitTest * const tests, const size_t number_of_tests)
2858 {
2859     UnitTestFunction setup = NULL;
2860     const char *setup_name;
2861     size_t num_setups = 0;
2862     UnitTestFunction teardown = NULL;
2863     const char *teardown_name;
2864     size_t num_teardowns = 0;
2865     size_t current_test = 0;
2866     size_t i;
2867
2868     /* Number of tests executed. */
2869     size_t tests_executed = 0;
2870     /* Number of failed tests. */
2871     size_t total_failed = 0;
2872     /* Check point of the heap state. */
2873     const ListNode * const check_point = check_point_allocated_blocks();
2874     const char** failed_names = (const char**)malloc(number_of_tests *
2875                                        sizeof(*failed_names));
2876     void **current_state = NULL;
2877     TestState group_state;
2878
2879     /* Find setup and teardown function */
2880     for (i = 0; i < number_of_tests; i++) {
2881         const UnitTest * const test = &tests[i];
2882
2883         if (test->function_type == UNIT_TEST_FUNCTION_TYPE_GROUP_SETUP) {
2884             if (setup == NULL) {
2885                 setup = test->function;
2886                 setup_name = test->name;
2887                 num_setups = 1;
2888             } else {
2889                 print_error("[  ERROR   ] More than one group setup function detected\n");
2890                 exit_test(1);
2891             }
2892         }
2893
2894         if (test->function_type == UNIT_TEST_FUNCTION_TYPE_GROUP_TEARDOWN) {
2895             if (teardown == NULL) {
2896                 teardown = test->function;
2897                 teardown_name = test->name;
2898                 num_teardowns = 1;
2899             } else {
2900                 print_error("[  ERROR   ] More than one group teardown function detected\n");
2901                 exit_test(1);
2902             }
2903         }
2904     }
2905
2906     print_message("[==========] Running %"PRIdS " test(s).\n",
2907                   number_of_tests - num_setups - num_teardowns);
2908
2909     if (setup != NULL) {
2910         int failed;
2911
2912         group_state.check_point = check_point_allocated_blocks();
2913         current_state = &group_state.state;
2914         *current_state = NULL;
2915         failed = _run_test(setup_name,
2916                            setup,
2917                            current_state,
2918                            UNIT_TEST_FUNCTION_TYPE_SETUP,
2919                            group_state.check_point);
2920         if (failed) {
2921             failed_names[total_failed] = setup_name;
2922         }
2923
2924         total_failed += failed;
2925         tests_executed++;
2926     }
2927
2928     while (current_test < number_of_tests) {
2929         int run_test = 0;
2930         const UnitTest * const test = &tests[current_test++];
2931         if (test->function == NULL) {
2932             continue;
2933         }
2934
2935         switch (test->function_type) {
2936         case UNIT_TEST_FUNCTION_TYPE_TEST:
2937             run_test = 1;
2938             break;
2939         case UNIT_TEST_FUNCTION_TYPE_SETUP:
2940         case UNIT_TEST_FUNCTION_TYPE_TEARDOWN:
2941         case UNIT_TEST_FUNCTION_TYPE_GROUP_SETUP:
2942         case UNIT_TEST_FUNCTION_TYPE_GROUP_TEARDOWN:
2943             break;
2944         default:
2945             print_error("Invalid unit test function type %d\n",
2946                         test->function_type);
2947             break;
2948         }
2949
2950         if (run_test) {
2951             int failed;
2952
2953             failed = _run_test(test->name,
2954                                test->function,
2955                                current_state,
2956                                test->function_type,
2957                                NULL);
2958             if (failed) {
2959                 failed_names[total_failed] = test->name;
2960             }
2961
2962             total_failed += failed;
2963             tests_executed++;
2964         }
2965     }
2966
2967     if (teardown != NULL) {
2968         int failed;
2969
2970         failed = _run_test(teardown_name,
2971                            teardown,
2972                            current_state,
2973                            UNIT_TEST_FUNCTION_TYPE_GROUP_TEARDOWN,
2974                            group_state.check_point);
2975         if (failed) {
2976             failed_names[total_failed] = teardown_name;
2977         }
2978
2979         total_failed += failed;
2980         tests_executed++;
2981     }
2982
2983     print_message("[==========] %"PRIdS " test(s) run.\n", tests_executed);
2984     print_error("[  PASSED  ] %"PRIdS " test(s).\n", tests_executed - total_failed);
2985
2986     if (total_failed) {
2987         print_error("[  FAILED  ] %"PRIdS " test(s), listed below:\n", total_failed);
2988         for (i = 0; i < total_failed; i++) {
2989             print_error("[  FAILED  ] %s\n", failed_names[i]);
2990         }
2991     } else {
2992         print_error("\n %"PRIdS " FAILED TEST(S)\n", total_failed);
2993     }
2994
2995     free((void*)failed_names);
2996     fail_if_blocks_allocated(check_point, "run_group_tests");
2997
2998     return (int)total_failed;
2999 }
3000