cmockery.c 62 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803
  1. /*
  2. * Copyright 2008 Google Inc.
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #ifdef HAVE_CONFIG_H
  17. #include "config.h"
  18. #endif
  19. #ifdef HAVE_MALLOC_H
  20. #include <malloc.h>
  21. #endif
  22. #include <setjmp.h>
  23. #ifndef _WIN32
  24. #include <signal.h>
  25. #endif // !_WIN32
  26. #include <stdarg.h>
  27. #include <stddef.h>
  28. #include <stdio.h>
  29. #include <stdlib.h>
  30. #include <string.h>
  31. #ifdef HAVE_INTTYPES_H
  32. #include <inttypes.h>
  33. #endif /* HAVE_INTTYPES_H */
  34. #ifdef _WIN32
  35. #include <windows.h>
  36. #endif // _WIN32
  37. #include <cmockery.h>
  38. #ifdef _WIN32
  39. #define vsnprintf _vsnprintf
  40. #endif // _WIN32
  41. /* Backwards compatibility with headers shipped with Visual Studio 2005 and
  42. * earlier. */
  43. #ifdef _WIN32
  44. WINBASEAPI BOOL WINAPI IsDebuggerPresent(VOID);
  45. #endif // _WIN32
  46. // Size of guard bytes around dynamically allocated blocks.
  47. #define MALLOC_GUARD_SIZE 16
  48. // Pattern used to initialize guard blocks.
  49. #define MALLOC_GUARD_PATTERN 0xEF
  50. // Pattern used to initialize memory allocated with test_malloc().
  51. #define MALLOC_ALLOC_PATTERN 0xBA
  52. #define MALLOC_FREE_PATTERN 0xCD
  53. // Alignment of allocated blocks. NOTE: This must be base2.
  54. #define MALLOC_ALIGNMENT sizeof(size_t)
  55. // Printf formatting for source code locations.
  56. #define SOURCE_LOCATION_FORMAT "%s:%d"
  57. // Calculates the number of elements in an array.
  58. #define ARRAY_LENGTH(x) (sizeof(x) / sizeof((x)[0]))
  59. // Declare and initialize the pointer member of ValuePointer variable name
  60. // with ptr.
  61. #define declare_initialize_value_pointer_pointer(name, ptr) \
  62. ValuePointer name ; \
  63. name.value = 0; \
  64. name.pointer = (void*)(ptr)
  65. // Declare and initialize the value member of ValuePointer variable name
  66. // with val.
  67. #define declare_initialize_value_pointer_value(name, val) \
  68. ValuePointer name ; \
  69. name.value = val
  70. // Cast a uintmax_t to pointer_type via a ValuePointer.
  71. #define cast_largest_integral_type_to_pointer( \
  72. pointer_type, largest_integral_type) \
  73. ((pointer_type)((ValuePointer*)&(largest_integral_type))->pointer)
  74. // Used to cast uintmax_t to void* and vice versa.
  75. typedef union ValuePointer {
  76. uintmax_t value;
  77. void *pointer;
  78. } ValuePointer;
  79. // Doubly linked list node.
  80. typedef struct ListNode {
  81. const void *value;
  82. int refcount;
  83. struct ListNode *next;
  84. struct ListNode *prev;
  85. } ListNode;
  86. // Debug information for malloc().
  87. typedef struct MallocBlockInfo {
  88. void* block; // Address of the block returned by malloc().
  89. size_t allocated_size; // Total size of the allocated block.
  90. size_t size; // Request block size.
  91. SourceLocation location; // Where the block was allocated.
  92. ListNode node; // Node within list of all allocated blocks.
  93. } MallocBlockInfo;
  94. // State of each test.
  95. typedef struct TestState {
  96. const ListNode *check_point; // Check point of the test if there's a
  97. // setup function.
  98. void *state; // State associated with the test.
  99. } TestState;
  100. // Determines whether two values are the same.
  101. typedef int (*EqualityFunction)(const void *left, const void *right);
  102. // Value of a symbol and the place it was declared.
  103. typedef struct SymbolValue {
  104. SourceLocation location;
  105. uintmax_t value;
  106. } SymbolValue;
  107. /* Contains a list of values for a symbol.
  108. * NOTE: Each structure referenced by symbol_values_list_head must have a
  109. * SourceLocation as its' first member.
  110. */
  111. typedef struct SymbolMapValue {
  112. const char *symbol_name;
  113. ListNode symbol_values_list_head;
  114. } SymbolMapValue;
  115. // Used by list_free() to deallocate values referenced by list nodes.
  116. typedef void (*CleanupListValue)(const void *value, void *cleanup_value_data);
  117. // Structure used to check the range of integer types.
  118. typedef struct CheckIntegerRange {
  119. CheckParameterEvent event;
  120. uintmax_t minimum;
  121. uintmax_t maximum;
  122. } CheckIntegerRange;
  123. // Structure used to check whether an integer value is in a set.
  124. typedef struct CheckIntegerSet {
  125. CheckParameterEvent event;
  126. const uintmax_t *set;
  127. size_t size_of_set;
  128. } CheckIntegerSet;
  129. /* Used to check whether a parameter matches the area of memory referenced by
  130. * this structure. */
  131. typedef struct CheckMemoryData {
  132. CheckParameterEvent event;
  133. const void *memory;
  134. size_t size;
  135. } CheckMemoryData;
  136. static ListNode* list_initialize(ListNode * const node);
  137. static ListNode* list_add(ListNode * const head, ListNode *new_node);
  138. static ListNode* list_add_value(ListNode * const head, const void *value,
  139. const int count);
  140. static ListNode* list_remove(
  141. ListNode * const node, const CleanupListValue cleanup_value,
  142. void * const cleanup_value_data);
  143. static void list_remove_free(
  144. ListNode * const node, const CleanupListValue cleanup_value,
  145. void * const cleanup_value_data);
  146. static int list_empty(const ListNode * const head);
  147. static int list_find(
  148. ListNode * const head, const void *value,
  149. const EqualityFunction equal_func, ListNode **output);
  150. static int list_first(ListNode * const head, ListNode **output);
  151. static ListNode* list_free(
  152. ListNode * const head, const CleanupListValue cleanup_value,
  153. void * const cleanup_value_data);
  154. static void add_symbol_value(
  155. ListNode * const symbol_map_head, const char * const symbol_names[],
  156. const size_t number_of_symbol_names, const void* value, const int count);
  157. static int get_symbol_value(
  158. ListNode * const symbol_map_head, const char * const symbol_names[],
  159. const size_t number_of_symbol_names, void **output);
  160. static void free_value(const void *value, void *cleanup_value_data);
  161. static void free_symbol_map_value(
  162. const void *value, void *cleanup_value_data);
  163. static void remove_always_return_values(ListNode * const map_head,
  164. const size_t number_of_symbol_names);
  165. static int check_for_leftover_values(
  166. const ListNode * const map_head, const char * const error_message,
  167. const size_t number_of_symbol_names);
  168. // This must be called at the beginning of a test to initialize some data
  169. // structures.
  170. static void initialize_testing(const char *test_name);
  171. // This must be called at the end of a test to free() allocated structures.
  172. static void teardown_testing(const char *test_name);
  173. // Keeps track of the calling context returned by setenv() so that the fail()
  174. // method can jump out of a test.
  175. static jmp_buf global_run_test_env;
  176. static int global_running_test = 0;
  177. // Keeps track of the calling context returned by setenv() so that
  178. // mock_assert() can optionally jump back to expect_assert_failure().
  179. jmp_buf global_expect_assert_env;
  180. int global_expecting_assert = 0;
  181. // Keeps a map of the values that functions will have to return to provide
  182. // mocked interfaces.
  183. static ListNode global_function_result_map_head;
  184. // Location of the last mock value returned was declared.
  185. static SourceLocation global_last_mock_value_location;
  186. /* Keeps a map of the values that functions expect as parameters to their
  187. * mocked interfaces. */
  188. static ListNode global_function_parameter_map_head;
  189. // Location of last parameter value checked was declared.
  190. static SourceLocation global_last_parameter_location;
  191. // List of all currently allocated blocks.
  192. static ListNode global_allocated_blocks;
  193. #ifndef _WIN32
  194. // Signals caught by exception_handler().
  195. static const int exception_signals[] = {
  196. SIGFPE,
  197. SIGILL,
  198. SIGSEGV,
  199. SIGBUS,
  200. SIGSYS,
  201. };
  202. // Default signal functions that should be restored after a test is complete.
  203. typedef void (*SignalFunction)(int signal);
  204. static SignalFunction default_signal_functions[
  205. ARRAY_LENGTH(exception_signals)];
  206. #else // _WIN32
  207. // The default exception filter.
  208. static LPTOP_LEVEL_EXCEPTION_FILTER previous_exception_filter;
  209. // Fatal exceptions.
  210. typedef struct ExceptionCodeInfo {
  211. DWORD code;
  212. const char* description;
  213. } ExceptionCodeInfo;
  214. #define EXCEPTION_CODE_INFO(exception_code) {exception_code, #exception_code}
  215. static const ExceptionCodeInfo exception_codes[] = {
  216. EXCEPTION_CODE_INFO(EXCEPTION_ACCESS_VIOLATION),
  217. EXCEPTION_CODE_INFO(EXCEPTION_ARRAY_BOUNDS_EXCEEDED),
  218. EXCEPTION_CODE_INFO(EXCEPTION_DATATYPE_MISALIGNMENT),
  219. EXCEPTION_CODE_INFO(EXCEPTION_FLT_DENORMAL_OPERAND),
  220. EXCEPTION_CODE_INFO(EXCEPTION_FLT_DIVIDE_BY_ZERO),
  221. EXCEPTION_CODE_INFO(EXCEPTION_FLT_INEXACT_RESULT),
  222. EXCEPTION_CODE_INFO(EXCEPTION_FLT_INVALID_OPERATION),
  223. EXCEPTION_CODE_INFO(EXCEPTION_FLT_OVERFLOW),
  224. EXCEPTION_CODE_INFO(EXCEPTION_FLT_STACK_CHECK),
  225. EXCEPTION_CODE_INFO(EXCEPTION_FLT_UNDERFLOW),
  226. EXCEPTION_CODE_INFO(EXCEPTION_GUARD_PAGE),
  227. EXCEPTION_CODE_INFO(EXCEPTION_ILLEGAL_INSTRUCTION),
  228. EXCEPTION_CODE_INFO(EXCEPTION_INT_DIVIDE_BY_ZERO),
  229. EXCEPTION_CODE_INFO(EXCEPTION_INT_OVERFLOW),
  230. EXCEPTION_CODE_INFO(EXCEPTION_INVALID_DISPOSITION),
  231. EXCEPTION_CODE_INFO(EXCEPTION_INVALID_HANDLE),
  232. EXCEPTION_CODE_INFO(EXCEPTION_IN_PAGE_ERROR),
  233. EXCEPTION_CODE_INFO(EXCEPTION_NONCONTINUABLE_EXCEPTION),
  234. EXCEPTION_CODE_INFO(EXCEPTION_PRIV_INSTRUCTION),
  235. EXCEPTION_CODE_INFO(EXCEPTION_STACK_OVERFLOW),
  236. };
  237. #endif // !_WIN32
  238. // Exit the currently executing test.
  239. static void exit_test(const int quit_application) {
  240. if (global_running_test) {
  241. longjmp(global_run_test_env, 1);
  242. } else if (quit_application) {
  243. exit(-1);
  244. }
  245. }
  246. // Initialize a SourceLocation structure.
  247. static void initialize_source_location(SourceLocation * const location) {
  248. assert_non_null(location);
  249. location->file = NULL;
  250. location->line = 0;
  251. }
  252. // Determine whether a source location is currently set.
  253. static int source_location_is_set(const SourceLocation * const location) {
  254. assert_non_null(location);
  255. return location->file && location->line;
  256. }
  257. // Set a source location.
  258. static void set_source_location(
  259. SourceLocation * const location, const char * const file,
  260. const int line) {
  261. assert_non_null(location);
  262. location->file = file;
  263. location->line = line;
  264. }
  265. // Create function results and expected parameter lists.
  266. void initialize_testing(const char *test_name) {
  267. (void)test_name;
  268. list_initialize(&global_function_result_map_head);
  269. initialize_source_location(&global_last_mock_value_location);
  270. list_initialize(&global_function_parameter_map_head);
  271. initialize_source_location(&global_last_parameter_location);
  272. }
  273. void fail_if_leftover_values(const char *test_name) {
  274. int error_occurred = 0;
  275. (void)test_name;
  276. remove_always_return_values(&global_function_result_map_head, 1);
  277. if (check_for_leftover_values(
  278. &global_function_result_map_head,
  279. "%s() has remaining non-returned values.\n", 1)) {
  280. error_occurred = 1;
  281. }
  282. remove_always_return_values(&global_function_parameter_map_head, 2);
  283. if (check_for_leftover_values(
  284. &global_function_parameter_map_head,
  285. "%s parameter still has values that haven't been checked.\n", 2)) {
  286. error_occurred = 1;
  287. }
  288. if (error_occurred) {
  289. exit_test(1);
  290. }
  291. }
  292. void teardown_testing(const char *test_name) {
  293. (void)test_name;
  294. list_free(&global_function_result_map_head, free_symbol_map_value,
  295. (void*)0);
  296. initialize_source_location(&global_last_mock_value_location);
  297. list_free(&global_function_parameter_map_head, free_symbol_map_value,
  298. (void*)1);
  299. initialize_source_location(&global_last_parameter_location);
  300. }
  301. // Initialize a list node.
  302. static ListNode* list_initialize(ListNode * const node) {
  303. node->value = NULL;
  304. node->next = node;
  305. node->prev = node;
  306. node->refcount = 1;
  307. return node;
  308. }
  309. /* Adds a value at the tail of a given list.
  310. * The node referencing the value is allocated from the heap. */
  311. static ListNode* list_add_value(ListNode * const head, const void *value,
  312. const int refcount) {
  313. ListNode * const new_node = (ListNode*)malloc(sizeof(ListNode));
  314. assert_non_null(head);
  315. assert_non_null(value);
  316. new_node->value = value;
  317. new_node->refcount = refcount;
  318. return list_add(head, new_node);
  319. }
  320. // Add new_node to the end of the list.
  321. static ListNode* list_add(ListNode * const head, ListNode *new_node) {
  322. assert_non_null(head);
  323. assert_non_null(new_node);
  324. new_node->next = head;
  325. new_node->prev = head->prev;
  326. head->prev->next = new_node;
  327. head->prev = new_node;
  328. return new_node;
  329. }
  330. // Remove a node from a list.
  331. static ListNode* list_remove(
  332. ListNode * const node, const CleanupListValue cleanup_value,
  333. void * const cleanup_value_data) {
  334. assert_non_null(node);
  335. node->prev->next = node->next;
  336. node->next->prev = node->prev;
  337. if (cleanup_value) {
  338. cleanup_value(node->value, cleanup_value_data);
  339. }
  340. return node;
  341. }
  342. /* Remove a list node from a list and free the node. */
  343. static void list_remove_free(
  344. ListNode * const node, const CleanupListValue cleanup_value,
  345. void * const cleanup_value_data) {
  346. assert_non_null(node);
  347. free(list_remove(node, cleanup_value, cleanup_value_data));
  348. }
  349. /* Frees memory kept by a linked list
  350. * The cleanup_value function is called for every "value" field of nodes in the
  351. * list, except for the head. In addition to each list value,
  352. * cleanup_value_data is passed to each call to cleanup_value. The head
  353. * of the list is not deallocated.
  354. */
  355. static ListNode* list_free(
  356. ListNode * const head, const CleanupListValue cleanup_value,
  357. void * const cleanup_value_data) {
  358. assert_non_null(head);
  359. while (!list_empty(head)) {
  360. list_remove_free(head->next, cleanup_value, cleanup_value_data);
  361. }
  362. return head;
  363. }
  364. // Determine whether a list is empty.
  365. static int list_empty(const ListNode * const head) {
  366. assert_non_null(head);
  367. return head->next == head;
  368. }
  369. /* Find a value in the list using the equal_func to compare each node with the
  370. * value.
  371. */
  372. static int list_find(ListNode * const head, const void *value,
  373. const EqualityFunction equal_func, ListNode **output) {
  374. ListNode *current;
  375. assert_non_null(head);
  376. for (current = head->next; current != head; current = current->next) {
  377. if (equal_func(current->value, value)) {
  378. *output = current;
  379. return 1;
  380. }
  381. }
  382. return 0;
  383. }
  384. // Returns the first node of a list
  385. static int list_first(ListNode * const head, ListNode **output) {
  386. ListNode *target_node;
  387. assert_non_null(head);
  388. if (list_empty(head)) {
  389. return 0;
  390. }
  391. target_node = head->next;
  392. *output = target_node;
  393. return 1;
  394. }
  395. // Deallocate a value referenced by a list.
  396. static void free_value(const void *value, void *cleanup_value_data) {
  397. (void)cleanup_value_data;
  398. assert_non_null(value);
  399. free((void*)value);
  400. }
  401. // Releases memory associated to a symbol_map_value.
  402. static void free_symbol_map_value(const void *value,
  403. void *cleanup_value_data) {
  404. SymbolMapValue * const map_value = (SymbolMapValue*)value;
  405. const uintmax_t children = cast_ptr_to_largest_integral_type(cleanup_value_data);
  406. assert_non_null(value);
  407. list_free(&map_value->symbol_values_list_head,
  408. children ? free_symbol_map_value : free_value,
  409. (void *) ((uintptr_t)children - 1));
  410. free(map_value);
  411. }
  412. /* Determine whether a symbol name referenced by a symbol_map_value
  413. * matches the specified function name. */
  414. static int symbol_names_match(const void *map_value, const void *symbol) {
  415. return !strcmp(((SymbolMapValue*)map_value)->symbol_name,
  416. (const char*)symbol);
  417. }
  418. /* Adds a value to the queue of values associated with the given
  419. * hierarchy of symbols. It's assumed value is allocated from the heap.
  420. */
  421. static void add_symbol_value(ListNode * const symbol_map_head,
  422. const char * const symbol_names[],
  423. const size_t number_of_symbol_names,
  424. const void* value, const int refcount) {
  425. const char* symbol_name;
  426. ListNode *target_node;
  427. SymbolMapValue *target_map_value;
  428. assert_non_null(symbol_map_head);
  429. assert_non_null(symbol_names);
  430. assert_true(number_of_symbol_names);
  431. symbol_name = symbol_names[0];
  432. if (!list_find(symbol_map_head, symbol_name, symbol_names_match,
  433. &target_node)) {
  434. SymbolMapValue * const new_symbol_map_value =
  435. (SymbolMapValue*)malloc(sizeof(*new_symbol_map_value));
  436. new_symbol_map_value->symbol_name = symbol_name;
  437. list_initialize(&new_symbol_map_value->symbol_values_list_head);
  438. target_node = list_add_value(symbol_map_head, new_symbol_map_value,
  439. 1);
  440. }
  441. target_map_value = (SymbolMapValue*)target_node->value;
  442. if (number_of_symbol_names == 1) {
  443. list_add_value(&target_map_value->symbol_values_list_head,
  444. value, refcount);
  445. } else {
  446. add_symbol_value(&target_map_value->symbol_values_list_head,
  447. &symbol_names[1], number_of_symbol_names - 1, value,
  448. refcount);
  449. }
  450. }
  451. /* Gets the next value associated with the given hierarchy of symbols.
  452. * The value is returned as an output parameter with the function returning the
  453. * node's old refcount value if a value is found, 0 otherwise.
  454. * This means that a return value of 1 indicates the node was just removed from
  455. * the list.
  456. */
  457. static int get_symbol_value(
  458. ListNode * const head, const char * const symbol_names[],
  459. const size_t number_of_symbol_names, void **output) {
  460. const char* symbol_name;
  461. ListNode *target_node;
  462. assert_non_null(head);
  463. assert_non_null(symbol_names);
  464. assert_true(number_of_symbol_names);
  465. assert_non_null(output);
  466. symbol_name = symbol_names[0];
  467. if (list_find(head, symbol_name, symbol_names_match, &target_node)) {
  468. SymbolMapValue *map_value;
  469. ListNode *child_list;
  470. int return_value = 0;
  471. assert_non_null(target_node);
  472. assert_non_null(target_node->value);
  473. map_value = (SymbolMapValue*)target_node->value;
  474. child_list = &map_value->symbol_values_list_head;
  475. if (number_of_symbol_names == 1) {
  476. ListNode *value_node = NULL;
  477. return_value = list_first(child_list, &value_node);
  478. assert_true(return_value);
  479. *output = (void*) value_node->value;
  480. return_value = value_node->refcount;
  481. if (--value_node->refcount == 0) {
  482. list_remove_free(value_node, NULL, NULL);
  483. }
  484. } else {
  485. return_value = get_symbol_value(
  486. child_list, &symbol_names[1], number_of_symbol_names - 1,
  487. output);
  488. }
  489. if (list_empty(child_list)) {
  490. list_remove_free(target_node, free_symbol_map_value, (void*)0);
  491. }
  492. return return_value;
  493. } else {
  494. print_error("No entries for symbol %s.\n", symbol_name);
  495. }
  496. return 0;
  497. }
  498. /* Traverse down a tree of symbol values and remove the first symbol value
  499. * in each branch that has a refcount < -1 (i.e should always be returned
  500. * and has been returned at least once).
  501. */
  502. static void remove_always_return_values(ListNode * const map_head,
  503. const size_t number_of_symbol_names) {
  504. ListNode *current;
  505. assert_non_null(map_head);
  506. assert_true(number_of_symbol_names);
  507. current = map_head->next;
  508. while (current != map_head) {
  509. SymbolMapValue * const value = (SymbolMapValue*)current->value;
  510. ListNode * const next = current->next;
  511. ListNode *child_list;
  512. assert_non_null(value);
  513. child_list = &value->symbol_values_list_head;
  514. if (!list_empty(child_list)) {
  515. if (number_of_symbol_names == 1) {
  516. ListNode * const child_node = child_list->next;
  517. // If this item has been returned more than once, free it.
  518. if (child_node->refcount < -1) {
  519. list_remove_free(child_node, free_value, NULL);
  520. }
  521. } else {
  522. remove_always_return_values(child_list,
  523. number_of_symbol_names - 1);
  524. }
  525. }
  526. if (list_empty(child_list)) {
  527. list_remove_free(current, free_value, NULL);
  528. }
  529. current = next;
  530. }
  531. }
  532. /* Checks if there are any leftover values set up by the test that were never
  533. * retrieved through execution, and fail the test if that is the case.
  534. */
  535. static int check_for_leftover_values(
  536. const ListNode * const map_head, const char * const error_message,
  537. const size_t number_of_symbol_names) {
  538. const ListNode *current;
  539. int symbols_with_leftover_values = 0;
  540. assert_non_null(map_head);
  541. assert_true(number_of_symbol_names);
  542. for (current = map_head->next; current != map_head;
  543. current = current->next) {
  544. const SymbolMapValue * const value =
  545. (SymbolMapValue*)current->value;
  546. const ListNode *child_list;
  547. assert_non_null(value);
  548. child_list = &value->symbol_values_list_head;
  549. if (!list_empty(child_list)) {
  550. if (number_of_symbol_names == 1) {
  551. const ListNode *child_node;
  552. print_error(error_message, value->symbol_name);
  553. print_error(" Remaining item(s) declared at...\n");
  554. for (child_node = child_list->next; child_node != child_list;
  555. child_node = child_node->next) {
  556. const SourceLocation * const location =
  557. (const SourceLocation*)child_node->value;
  558. print_error(" " SOURCE_LOCATION_FORMAT "\n",
  559. location->file, location->line);
  560. }
  561. } else {
  562. print_error("%s.", value->symbol_name);
  563. check_for_leftover_values(child_list, error_message,
  564. number_of_symbol_names - 1);
  565. }
  566. symbols_with_leftover_values ++;
  567. }
  568. }
  569. return symbols_with_leftover_values;
  570. }
  571. // Get the next return value for the specified mock function.
  572. uintmax_t _mock(const char * const function, const char* const file,
  573. const int line) {
  574. void *result;
  575. const int rc = get_symbol_value(&global_function_result_map_head,
  576. &function, 1, &result);
  577. if (rc) {
  578. SymbolValue * const symbol = (SymbolValue*)result;
  579. const uintmax_t value = symbol->value;
  580. global_last_mock_value_location = symbol->location;
  581. if (rc == 1) {
  582. free(symbol);
  583. }
  584. return value;
  585. } else {
  586. print_error("ERROR: " SOURCE_LOCATION_FORMAT " - Could not get value "
  587. "to mock function %s\n", file, line, function);
  588. if (source_location_is_set(&global_last_mock_value_location)) {
  589. print_error("Previously returned mock value was declared at "
  590. SOURCE_LOCATION_FORMAT "\n",
  591. global_last_mock_value_location.file,
  592. global_last_mock_value_location.line);
  593. } else {
  594. print_error("There were no previously returned mock values for "
  595. "this test.\n");
  596. }
  597. exit_test(1);
  598. }
  599. return 0;
  600. }
  601. // Add a return value for the specified mock function name.
  602. void _will_return(const char * const function_name, const char * const file,
  603. const int line, const uintmax_t value,
  604. const int count) {
  605. SymbolValue * const return_value =
  606. (SymbolValue*)malloc(sizeof(*return_value));
  607. assert_true(count > 0 || count == -1);
  608. return_value->value = value;
  609. set_source_location(&return_value->location, file, line);
  610. add_symbol_value(&global_function_result_map_head, &function_name, 1,
  611. return_value, count);
  612. }
  613. /* Add a custom parameter checking function. If the event parameter is NULL
  614. * the event structure is allocated internally by this function. If event
  615. * parameter is provided it must be allocated on the heap and doesn't need to
  616. * be deallocated by the caller.
  617. */
  618. void _expect_check(
  619. const char* const function, const char* const parameter,
  620. const char* const file, const int line,
  621. const CheckParameterValue check_function,
  622. const uintmax_t check_data,
  623. CheckParameterEvent * const event, const int count) {
  624. CheckParameterEvent * const check =
  625. event ? event : (CheckParameterEvent*)malloc(sizeof(*check));
  626. const char* symbols[] = {function, parameter};
  627. check->parameter_name = parameter;
  628. check->check_value = check_function;
  629. check->check_value_data = check_data;
  630. set_source_location(&check->location, file, line);
  631. add_symbol_value(&global_function_parameter_map_head, symbols, 2, check,
  632. count);
  633. }
  634. /* Returns 1 if the specified values are equal. If the values are not equal
  635. * an error is displayed and 0 is returned. */
  636. static int values_equal_display_error(const uintmax_t left,
  637. const uintmax_t right) {
  638. const int equal = left == right;
  639. if (!equal) {
  640. print_error("%" PRIxMAX " != "
  641. "%" PRIxMAX "\n", left, right);
  642. }
  643. return equal;
  644. }
  645. /* Returns 1 if the specified values are not equal. If the values are equal
  646. * an error is displayed and 0 is returned. */
  647. static int values_not_equal_display_error(const uintmax_t left,
  648. const uintmax_t right) {
  649. const int not_equal = left != right;
  650. if (!not_equal) {
  651. print_error("%" PRIxMAX " == "
  652. "%" PRIxMAX "\n", left, right);
  653. }
  654. return not_equal;
  655. }
  656. /* Determine whether value is contained within check_integer_set.
  657. * If invert is 0 and the value is in the set 1 is returned, otherwise 0 is
  658. * returned and an error is displayed. If invert is 1 and the value is not
  659. * in the set 1 is returned, otherwise 0 is returned and an error is
  660. * displayed. */
  661. static int value_in_set_display_error(
  662. const uintmax_t value,
  663. const CheckIntegerSet * const check_integer_set, const int invert) {
  664. int succeeded = invert;
  665. assert_non_null(check_integer_set);
  666. {
  667. const uintmax_t * const set = check_integer_set->set;
  668. const size_t size_of_set = check_integer_set->size_of_set;
  669. size_t i;
  670. for (i = 0; i < size_of_set; i++) {
  671. if (set[i] == value) {
  672. // If invert = 0 and item is found, succeeded = 1.
  673. // If invert = 1 and item is found, succeeded = 0.
  674. succeeded = !succeeded;
  675. break;
  676. }
  677. }
  678. if (succeeded) {
  679. return 1;
  680. }
  681. print_error("%" PRIuMAX " is %sin the set (", value, invert ? "" : "not ");
  682. for (i = 0; i < size_of_set; i++) {
  683. print_error("%" PRIuMAX ", ", set[i]);
  684. }
  685. print_error(")\n");
  686. }
  687. return 0;
  688. }
  689. /* Determine whether a value is within the specified range. If the value is
  690. * within the specified range 1 is returned. If the value isn't within the
  691. * specified range an error is displayed and 0 is returned. */
  692. static int integer_in_range_display_error(
  693. const uintmax_t value, const uintmax_t range_min,
  694. const uintmax_t range_max) {
  695. if (value >= range_min && value <= range_max) {
  696. return 1;
  697. }
  698. print_error("%" PRIuMAX " is not within the range %" PRIuMAX "-%" PRIuMAX "\n",
  699. value, range_min, range_max);
  700. return 0;
  701. }
  702. /* Determine whether a value is within the specified range. If the value
  703. * is not within the range 1 is returned. If the value is within the
  704. * specified range an error is displayed and zero is returned. */
  705. static int integer_not_in_range_display_error(
  706. const uintmax_t value, const uintmax_t range_min,
  707. const uintmax_t range_max) {
  708. if (value < range_min || value > range_max) {
  709. return 1;
  710. }
  711. print_error("%" PRIuMAX " is within the range %" PRIuMAX "-%" PRIuMAX "\n",
  712. value, range_min, range_max);
  713. return 0;
  714. }
  715. /* Determine whether the specified strings are equal. If the strings are equal
  716. * 1 is returned. If they're not equal an error is displayed and 0 is
  717. * returned. */
  718. static int string_equal_display_error(
  719. const char * const left, const char * const right) {
  720. if (strcmp(left, right) == 0) {
  721. return 1;
  722. }
  723. print_error("\"%s\" != \"%s\"\n", left, right);
  724. return 0;
  725. }
  726. /* Determine whether the specified strings are equal. If the strings are not
  727. * equal 1 is returned. If they're not equal an error is displayed and 0 is
  728. * returned */
  729. static int string_not_equal_display_error(
  730. const char * const left, const char * const right) {
  731. if (strcmp(left, right) != 0) {
  732. return 1;
  733. }
  734. print_error("\"%s\" == \"%s\"\n", left, right);
  735. return 0;
  736. }
  737. /* Determine whether the specified areas of memory are equal. If they're equal
  738. * 1 is returned otherwise an error is displayed and 0 is returned. */
  739. static int memory_equal_display_error(const char* const a, const char* const b,
  740. const size_t size) {
  741. int differences = 0;
  742. size_t i;
  743. for (i = 0; i < size; i++) {
  744. const char l = a[i];
  745. const char r = b[i];
  746. if (l != r) {
  747. print_error("difference at offset %" PRIuMAX " 0x%02x 0x%02x\n",
  748. cast_to_largest_integral_type(i), l, r);
  749. differences ++;
  750. }
  751. }
  752. if (differences) {
  753. print_error("%d bytes of 0x%08" PRIxMAX " and 0x%08" PRIxMAX " differ\n",
  754. differences,
  755. cast_ptr_to_largest_integral_type(a),
  756. cast_ptr_to_largest_integral_type(b));
  757. return 0;
  758. }
  759. return 1;
  760. }
  761. /* Determine whether the specified areas of memory are not equal. If they're
  762. * not equal 1 is returned otherwise an error is displayed and 0 is
  763. * returned. */
  764. static int memory_not_equal_display_error(
  765. const char* const a, const char* const b, const size_t size) {
  766. size_t same = 0;
  767. size_t i;
  768. for (i = 0; i < size; i++) {
  769. const char l = a[i];
  770. const char r = b[i];
  771. if (l == r) {
  772. same ++;
  773. }
  774. }
  775. if (same == size) {
  776. print_error("%" PRIuMAX " bytes of 0x%08" PRIxMAX " and 0x%08" PRIxMAX" the same\n",
  777. cast_to_largest_integral_type(same),
  778. cast_ptr_to_largest_integral_type(a),
  779. cast_ptr_to_largest_integral_type(b));
  780. return 0;
  781. }
  782. return 1;
  783. }
  784. // CheckParameterValue callback to check whether a value is within a set.
  785. static int check_in_set(const uintmax_t value,
  786. const uintmax_t check_value_data) {
  787. return value_in_set_display_error(value,
  788. cast_largest_integral_type_to_pointer(CheckIntegerSet*,
  789. check_value_data), 0);
  790. }
  791. // CheckParameterValue callback to check whether a value isn't within a set.
  792. static int check_not_in_set(const uintmax_t value,
  793. const uintmax_t check_value_data) {
  794. return value_in_set_display_error(value,
  795. cast_largest_integral_type_to_pointer(CheckIntegerSet*,
  796. check_value_data), 1);
  797. }
  798. /* Create the callback data for check_in_set() or check_not_in_set() and
  799. * register a check event. */
  800. static void expect_set(
  801. const char* const function, const char* const parameter,
  802. const char* const file, const int line,
  803. const uintmax_t values[], const size_t number_of_values,
  804. const CheckParameterValue check_function, const int count) {
  805. CheckIntegerSet * const check_integer_set =
  806. (CheckIntegerSet*)malloc(sizeof(*check_integer_set) +
  807. (sizeof(values[0]) * number_of_values));
  808. uintmax_t * const set = (uintmax_t*)(
  809. check_integer_set + 1);
  810. declare_initialize_value_pointer_pointer(check_data, check_integer_set);
  811. assert_non_null(values);
  812. assert_true(number_of_values);
  813. memcpy(set, values, number_of_values * sizeof(values[0]));
  814. check_integer_set->set = set;
  815. _expect_check(
  816. function, parameter, file, line, check_function,
  817. check_data.value, &check_integer_set->event, count);
  818. }
  819. // Add an event to check whether a value is in a set.
  820. void _expect_in_set(
  821. const char* const function, const char* const parameter,
  822. const char* const file, const int line,
  823. const uintmax_t values[], const size_t number_of_values,
  824. const int count) {
  825. expect_set(function, parameter, file, line, values, number_of_values,
  826. check_in_set, count);
  827. }
  828. // Add an event to check whether a value isn't in a set.
  829. void _expect_not_in_set(
  830. const char* const function, const char* const parameter,
  831. const char* const file, const int line,
  832. const uintmax_t values[], const size_t number_of_values,
  833. const int count) {
  834. expect_set(function, parameter, file, line, values, number_of_values,
  835. check_not_in_set, count);
  836. }
  837. // CheckParameterValue callback to check whether a value is within a range.
  838. static int check_in_range(const uintmax_t value,
  839. const uintmax_t check_value_data) {
  840. CheckIntegerRange * const check_integer_range =
  841. cast_largest_integral_type_to_pointer(CheckIntegerRange*,
  842. check_value_data);
  843. assert_non_null(check_integer_range);
  844. return integer_in_range_display_error(value, check_integer_range->minimum,
  845. check_integer_range->maximum);
  846. }
  847. // CheckParameterValue callback to check whether a value is not within a range.
  848. static int check_not_in_range(const uintmax_t value,
  849. const uintmax_t check_value_data) {
  850. CheckIntegerRange * const check_integer_range =
  851. cast_largest_integral_type_to_pointer(CheckIntegerRange*,
  852. check_value_data);
  853. assert_non_null(check_integer_range);
  854. return integer_not_in_range_display_error(
  855. value, check_integer_range->minimum, check_integer_range->maximum);
  856. }
  857. /* Create the callback data for check_in_range() or check_not_in_range() and
  858. * register a check event. */
  859. static void expect_range(
  860. const char* const function, const char* const parameter,
  861. const char* const file, const int line,
  862. const uintmax_t minimum, const uintmax_t maximum,
  863. const CheckParameterValue check_function, const int count) {
  864. CheckIntegerRange * const check_integer_range =
  865. (CheckIntegerRange*)malloc(sizeof(*check_integer_range));
  866. declare_initialize_value_pointer_pointer(check_data, check_integer_range);
  867. check_integer_range->minimum = minimum;
  868. check_integer_range->maximum = maximum;
  869. _expect_check(function, parameter, file, line, check_function,
  870. check_data.value, &check_integer_range->event, count);
  871. }
  872. // Add an event to determine whether a parameter is within a range.
  873. void _expect_in_range(
  874. const char* const function, const char* const parameter,
  875. const char* const file, const int line,
  876. const uintmax_t minimum, const uintmax_t maximum,
  877. const int count) {
  878. expect_range(function, parameter, file, line, minimum, maximum,
  879. check_in_range, count);
  880. }
  881. // Add an event to determine whether a parameter is not within a range.
  882. void _expect_not_in_range(
  883. const char* const function, const char* const parameter,
  884. const char* const file, const int line,
  885. const uintmax_t minimum, const uintmax_t maximum,
  886. const int count) {
  887. expect_range(function, parameter, file, line, minimum, maximum,
  888. check_not_in_range, count);
  889. }
  890. /* CheckParameterValue callback to check whether a value is equal to an
  891. * expected value. */
  892. static int check_value(const uintmax_t value,
  893. const uintmax_t check_value_data) {
  894. return values_equal_display_error(value, check_value_data);
  895. }
  896. // Add an event to check a parameter equals an expected value.
  897. void _expect_value(
  898. const char* const function, const char* const parameter,
  899. const char* const file, const int line,
  900. const uintmax_t value, const int count) {
  901. _expect_check(function, parameter, file, line, check_value, value, NULL,
  902. count);
  903. }
  904. /* CheckParameterValue callback to check whether a value is not equal to an
  905. * expected value. */
  906. static int check_not_value(const uintmax_t value,
  907. const uintmax_t check_value_data) {
  908. return values_not_equal_display_error(value, check_value_data);
  909. }
  910. // Add an event to check a parameter is not equal to an expected value.
  911. void _expect_not_value(
  912. const char* const function, const char* const parameter,
  913. const char* const file, const int line,
  914. const uintmax_t value, const int count) {
  915. _expect_check(function, parameter, file, line, check_not_value, value,
  916. NULL, count);
  917. }
  918. // CheckParameterValue callback to check whether a parameter equals a string.
  919. static int check_string(const uintmax_t value,
  920. const uintmax_t check_value_data) {
  921. return string_equal_display_error(
  922. cast_largest_integral_type_to_pointer(char*, value),
  923. cast_largest_integral_type_to_pointer(char*, check_value_data));
  924. }
  925. // Add an event to check whether a parameter is equal to a string.
  926. void _expect_string(
  927. const char* const function, const char* const parameter,
  928. const char* const file, const int line, const char* string,
  929. const int count) {
  930. declare_initialize_value_pointer_pointer(string_pointer, (char*)string);
  931. _expect_check(function, parameter, file, line, check_string,
  932. string_pointer.value, NULL, count);
  933. }
  934. /* CheckParameterValue callback to check whether a parameter is not equals to
  935. * a string. */
  936. static int check_not_string(const uintmax_t value,
  937. const uintmax_t check_value_data) {
  938. return string_not_equal_display_error(
  939. cast_largest_integral_type_to_pointer(char*, value),
  940. cast_largest_integral_type_to_pointer(char*, check_value_data));
  941. }
  942. // Add an event to check whether a parameter is not equal to a string.
  943. void _expect_not_string(
  944. const char* const function, const char* const parameter,
  945. const char* const file, const int line, const char* string,
  946. const int count) {
  947. declare_initialize_value_pointer_pointer(string_pointer, (char*)string);
  948. _expect_check(function, parameter, file, line, check_not_string,
  949. string_pointer.value, NULL, count);
  950. }
  951. /* CheckParameterValue callback to check whether a parameter equals an area of
  952. * memory. */
  953. static int check_memory(const uintmax_t value,
  954. const uintmax_t check_value_data) {
  955. CheckMemoryData * const check = cast_largest_integral_type_to_pointer(
  956. CheckMemoryData*, check_value_data);
  957. assert_non_null(check);
  958. return memory_equal_display_error(
  959. cast_largest_integral_type_to_pointer(const char*, value),
  960. (const char*)check->memory, check->size);
  961. }
  962. /* Create the callback data for check_memory() or check_not_memory() and
  963. * register a check event. */
  964. static void expect_memory_setup(
  965. const char* const function, const char* const parameter,
  966. const char* const file, const int line,
  967. const void * const memory, const size_t size,
  968. const CheckParameterValue check_function, const int count) {
  969. CheckMemoryData * const check_data =
  970. (CheckMemoryData*)malloc(sizeof(*check_data) + size);
  971. void * const mem = (void*)(check_data + 1);
  972. declare_initialize_value_pointer_pointer(check_data_pointer, check_data);
  973. assert_non_null(memory);
  974. assert_true(size);
  975. memcpy(mem, memory, size);
  976. check_data->memory = mem;
  977. check_data->size = size;
  978. _expect_check(function, parameter, file, line, check_function,
  979. check_data_pointer.value, &check_data->event, count);
  980. }
  981. // Add an event to check whether a parameter matches an area of memory.
  982. void _expect_memory(
  983. const char* const function, const char* const parameter,
  984. const char* const file, const int line, const void* const memory,
  985. const size_t size, const int count) {
  986. expect_memory_setup(function, parameter, file, line, memory, size,
  987. check_memory, count);
  988. }
  989. /* CheckParameterValue callback to check whether a parameter is not equal to
  990. * an area of memory. */
  991. static int check_not_memory(const uintmax_t value,
  992. const uintmax_t check_value_data) {
  993. CheckMemoryData * const check = cast_largest_integral_type_to_pointer(
  994. CheckMemoryData*, check_value_data);
  995. assert_non_null(check);
  996. return memory_not_equal_display_error(
  997. cast_largest_integral_type_to_pointer(const char*, value),
  998. (const char*)check->memory,
  999. check->size);
  1000. }
  1001. // Add an event to check whether a parameter doesn't match an area of memory.
  1002. void _expect_not_memory(
  1003. const char* const function, const char* const parameter,
  1004. const char* const file, const int line, const void* const memory,
  1005. const size_t size, const int count) {
  1006. expect_memory_setup(function, parameter, file, line, memory, size,
  1007. check_not_memory, count);
  1008. }
  1009. // CheckParameterValue callback that always returns 1.
  1010. static int check_any(const uintmax_t value,
  1011. const uintmax_t check_value_data) {
  1012. (void)value;
  1013. (void)check_value_data;
  1014. return 1;
  1015. }
  1016. // Add an event to allow any value for a parameter.
  1017. void _expect_any(
  1018. const char* const function, const char* const parameter,
  1019. const char* const file, const int line, const int count) {
  1020. _expect_check(function, parameter, file, line, check_any, 0, NULL,
  1021. count);
  1022. }
  1023. void _check_expected(
  1024. const char * const function_name, const char * const parameter_name,
  1025. const char* file, const int line, const uintmax_t value) {
  1026. void *result;
  1027. const char* symbols[] = {function_name, parameter_name};
  1028. const int rc = get_symbol_value(&global_function_parameter_map_head,
  1029. symbols, 2, &result);
  1030. if (rc) {
  1031. CheckParameterEvent * const check = (CheckParameterEvent*)result;
  1032. int check_succeeded;
  1033. global_last_parameter_location = check->location;
  1034. check_succeeded = check->check_value(value, check->check_value_data);
  1035. if (rc == 1) {
  1036. free(check);
  1037. }
  1038. if (!check_succeeded) {
  1039. print_error("ERROR: Check of parameter %s, function %s failed\n"
  1040. "Expected parameter declared at "
  1041. SOURCE_LOCATION_FORMAT "\n",
  1042. parameter_name, function_name,
  1043. global_last_parameter_location.file,
  1044. global_last_parameter_location.line);
  1045. _fail(file, line);
  1046. }
  1047. } else {
  1048. print_error("ERROR: " SOURCE_LOCATION_FORMAT " - Could not get value "
  1049. "to check parameter %s of function %s\n", file, line,
  1050. parameter_name, function_name);
  1051. if (source_location_is_set(&global_last_parameter_location)) {
  1052. print_error("Previously declared parameter value was declared at "
  1053. SOURCE_LOCATION_FORMAT "\n",
  1054. global_last_parameter_location.file,
  1055. global_last_parameter_location.line);
  1056. } else {
  1057. print_error("There were no previously declared parameter values "
  1058. "for this test.\n");
  1059. }
  1060. exit_test(1);
  1061. }
  1062. }
  1063. // Replacement for assert.
  1064. void mock_assert(const int result, const char* const expression,
  1065. const char* const file, const int line) {
  1066. if (!result) {
  1067. if (global_expecting_assert) {
  1068. longjmp(global_expect_assert_env, (int)expression);
  1069. } else {
  1070. print_error("ASSERT: %s\n", expression);
  1071. _fail(file, line);
  1072. }
  1073. }
  1074. }
  1075. void _assert_true(const uintmax_t result,
  1076. const char * const expression,
  1077. const char * const file, const int line) {
  1078. if (!result) {
  1079. print_error("%s\n", expression);
  1080. _fail(file, line);
  1081. }
  1082. }
  1083. void _assert_int_equal(
  1084. const uintmax_t a, const uintmax_t b,
  1085. const char * const file, const int line) {
  1086. if (!values_equal_display_error(a, b)) {
  1087. _fail(file, line);
  1088. }
  1089. }
  1090. void _assert_int_not_equal(
  1091. const uintmax_t a, const uintmax_t b,
  1092. const char * const file, const int line) {
  1093. if (!values_not_equal_display_error(a, b)) {
  1094. _fail(file, line);
  1095. }
  1096. }
  1097. void _assert_string_equal(const char * const a, const char * const b,
  1098. const char * const file, const int line) {
  1099. if (!string_equal_display_error(a, b)) {
  1100. _fail(file, line);
  1101. }
  1102. }
  1103. void _assert_string_not_equal(const char * const a, const char * const b,
  1104. const char *file, const int line) {
  1105. if (!string_not_equal_display_error(a, b)) {
  1106. _fail(file, line);
  1107. }
  1108. }
  1109. void _assert_memory_equal(const void * const a, const void * const b,
  1110. const size_t size, const char* const file,
  1111. const int line) {
  1112. if (!memory_equal_display_error((const char*)a, (const char*)b, size)) {
  1113. _fail(file, line);
  1114. }
  1115. }
  1116. void _assert_memory_not_equal(const void * const a, const void * const b,
  1117. const size_t size, const char* const file,
  1118. const int line) {
  1119. if (!memory_not_equal_display_error((const char*)a, (const char*)b,
  1120. size)) {
  1121. _fail(file, line);
  1122. }
  1123. }
  1124. void _assert_in_range(
  1125. const uintmax_t value, const uintmax_t minimum,
  1126. const uintmax_t maximum, const char* const file,
  1127. const int line) {
  1128. if (!integer_in_range_display_error(value, minimum, maximum)) {
  1129. _fail(file, line);
  1130. }
  1131. }
  1132. void _assert_not_in_range(
  1133. const uintmax_t value, const uintmax_t minimum,
  1134. const uintmax_t maximum, const char* const file,
  1135. const int line) {
  1136. if (!integer_not_in_range_display_error(value, minimum, maximum)) {
  1137. _fail(file, line);
  1138. }
  1139. }
  1140. void _assert_in_set(const uintmax_t value,
  1141. const uintmax_t values[],
  1142. const size_t number_of_values, const char* const file,
  1143. const int line) {
  1144. CheckIntegerSet check_integer_set;
  1145. check_integer_set.set = values;
  1146. check_integer_set.size_of_set = number_of_values;
  1147. if (!value_in_set_display_error(value, &check_integer_set, 0)) {
  1148. _fail(file, line);
  1149. }
  1150. }
  1151. void _assert_not_in_set(const uintmax_t value,
  1152. const uintmax_t values[],
  1153. const size_t number_of_values, const char* const file,
  1154. const int line) {
  1155. CheckIntegerSet check_integer_set;
  1156. check_integer_set.set = values;
  1157. check_integer_set.size_of_set = number_of_values;
  1158. if (!value_in_set_display_error(value, &check_integer_set, 1)) {
  1159. _fail(file, line);
  1160. }
  1161. }
  1162. // Get the list of allocated blocks.
  1163. static ListNode* get_allocated_blocks_list() {
  1164. // If it initialized, initialize the list of allocated blocks.
  1165. if (!global_allocated_blocks.value) {
  1166. list_initialize(&global_allocated_blocks);
  1167. global_allocated_blocks.value = (void*)1;
  1168. }
  1169. return &global_allocated_blocks;
  1170. }
  1171. // Use the real malloc in this function.
  1172. #undef malloc
  1173. void* _test_malloc(const size_t size, const char* file, const int line) {
  1174. char* ptr;
  1175. MallocBlockInfo *block_info;
  1176. ListNode * const block_list = get_allocated_blocks_list();
  1177. const size_t allocate_size = size + (MALLOC_GUARD_SIZE * 2) +
  1178. sizeof(*block_info) + MALLOC_ALIGNMENT;
  1179. char* const block = (char*)malloc(allocate_size);
  1180. assert_non_null(block);
  1181. // Calculate the returned address.
  1182. ptr = (char*)(((size_t)block + MALLOC_GUARD_SIZE + sizeof(*block_info) +
  1183. MALLOC_ALIGNMENT) & ~(MALLOC_ALIGNMENT - 1));
  1184. // Initialize the guard blocks.
  1185. memset(ptr - MALLOC_GUARD_SIZE, MALLOC_GUARD_PATTERN, MALLOC_GUARD_SIZE);
  1186. memset(ptr + size, MALLOC_GUARD_PATTERN, MALLOC_GUARD_SIZE);
  1187. memset(ptr, MALLOC_ALLOC_PATTERN, size);
  1188. block_info = (MallocBlockInfo*)(ptr - (MALLOC_GUARD_SIZE +
  1189. sizeof(*block_info)));
  1190. set_source_location(&block_info->location, file, line);
  1191. block_info->allocated_size = allocate_size;
  1192. block_info->size = size;
  1193. block_info->block = block;
  1194. block_info->node.value = block_info;
  1195. list_add(block_list, &block_info->node);
  1196. return ptr;
  1197. }
  1198. #define malloc test_malloc
  1199. void* _test_calloc(const size_t number_of_elements, const size_t size,
  1200. const char* file, const int line) {
  1201. void* const ptr = _test_malloc(number_of_elements * size, file, line);
  1202. if (ptr) {
  1203. memset(ptr, 0, number_of_elements * size);
  1204. }
  1205. return ptr;
  1206. }
  1207. // Use the real free in this function.
  1208. #undef free
  1209. void _test_free(void* const ptr, const char* file, const int line) {
  1210. unsigned int i;
  1211. char *block = (char*)ptr;
  1212. MallocBlockInfo *block_info;
  1213. _assert_true(cast_ptr_to_largest_integral_type(ptr), "ptr", file, line);
  1214. block_info = (MallocBlockInfo*)(block - (MALLOC_GUARD_SIZE +
  1215. sizeof(*block_info)));
  1216. // Check the guard blocks.
  1217. {
  1218. char *guards[2] = {block - MALLOC_GUARD_SIZE,
  1219. block + block_info->size};
  1220. for (i = 0; i < ARRAY_LENGTH(guards); i++) {
  1221. unsigned int j;
  1222. char * const guard = guards[i];
  1223. for (j = 0; j < MALLOC_GUARD_SIZE; j++) {
  1224. const char diff = guard[j] - MALLOC_GUARD_PATTERN;
  1225. if (diff) {
  1226. print_error(
  1227. "Guard block of 0x%08" PRIxMAX " size=%" PRIuMAX " allocated by "
  1228. SOURCE_LOCATION_FORMAT " at 0x%08" PRIxMAX " is corrupt\n",
  1229. cast_ptr_to_largest_integral_type(ptr),
  1230. cast_to_largest_integral_type(block_info->size),
  1231. block_info->location.file, block_info->location.line,
  1232. cast_ptr_to_largest_integral_type(&guard[j]));
  1233. _fail(file, line);
  1234. }
  1235. }
  1236. }
  1237. }
  1238. list_remove(&block_info->node, NULL, NULL);
  1239. block = (char*)block_info->block;
  1240. memset(block, MALLOC_FREE_PATTERN, block_info->allocated_size);
  1241. free(block);
  1242. }
  1243. #define free test_free
  1244. // Crudely checkpoint the current heap state.
  1245. static const ListNode* check_point_allocated_blocks() {
  1246. return get_allocated_blocks_list()->prev;
  1247. }
  1248. /* Display the blocks allocated after the specified check point. This
  1249. * function returns the number of blocks displayed. */
  1250. static int display_allocated_blocks(const ListNode * const check_point) {
  1251. const ListNode * const head = get_allocated_blocks_list();
  1252. const ListNode *node;
  1253. int allocated_blocks = 0;
  1254. assert_non_null(check_point);
  1255. assert_non_null(check_point->next);
  1256. for (node = check_point->next; node != head; node = node->next) {
  1257. const MallocBlockInfo * const block_info =
  1258. (const MallocBlockInfo*)node->value;
  1259. assert_non_null(block_info);
  1260. if (!allocated_blocks) {
  1261. print_error("Blocks allocated...\n");
  1262. }
  1263. print_error(" 0x%08" PRIxMAX " : " SOURCE_LOCATION_FORMAT "\n",
  1264. cast_ptr_to_largest_integral_type(block_info->block),
  1265. block_info->location.file,
  1266. block_info->location.line);
  1267. allocated_blocks ++;
  1268. }
  1269. return allocated_blocks;
  1270. }
  1271. // Free all blocks allocated after the specified check point.
  1272. static void free_allocated_blocks(const ListNode * const check_point) {
  1273. const ListNode * const head = get_allocated_blocks_list();
  1274. const ListNode *node;
  1275. assert_non_null(check_point);
  1276. node = check_point->next;
  1277. assert_non_null(node);
  1278. while (node != head) {
  1279. MallocBlockInfo * const block_info = (MallocBlockInfo*)node->value;
  1280. node = node->next;
  1281. free((char*)block_info + sizeof(*block_info) + MALLOC_GUARD_SIZE);
  1282. }
  1283. }
  1284. // Fail if any any blocks are allocated after the specified check point.
  1285. static void fail_if_blocks_allocated(const ListNode * const check_point,
  1286. const char * const test_name) {
  1287. const int allocated_blocks = display_allocated_blocks(check_point);
  1288. if (allocated_blocks) {
  1289. free_allocated_blocks(check_point);
  1290. print_error("ERROR: %s leaked %d block(s)\n", test_name,
  1291. allocated_blocks);
  1292. exit_test(1);
  1293. }
  1294. }
  1295. void _fail(const char * const file, const int line) {
  1296. print_error("ERROR: " SOURCE_LOCATION_FORMAT " Failure!\n", file, line);
  1297. exit_test(1);
  1298. }
  1299. #ifndef _WIN32
  1300. static void exception_handler(int sig) {
  1301. #ifdef _HPUX
  1302. print_error("%d\n", sig);
  1303. #else
  1304. print_error("%s\n", strsignal(sig));
  1305. #endif
  1306. exit_test(1);
  1307. }
  1308. #else // _WIN32
  1309. static LONG WINAPI exception_filter(EXCEPTION_POINTERS *exception_pointers) {
  1310. EXCEPTION_RECORD * const exception_record =
  1311. exception_pointers->ExceptionRecord;
  1312. const DWORD code = exception_record->ExceptionCode;
  1313. unsigned int i;
  1314. for (i = 0; i < ARRAY_LENGTH(exception_codes); i++) {
  1315. const ExceptionCodeInfo * const code_info = &exception_codes[i];
  1316. if (code == code_info->code) {
  1317. static int shown_debug_message = 0;
  1318. fflush(stdout);
  1319. print_error("%s occurred at 0x%08" PRIxMAX ".\n", code_info->description,
  1320. cast_to_largest_integral_type(exception_record->ExceptionAddress));
  1321. if (!shown_debug_message) {
  1322. print_error(
  1323. "\n"
  1324. "To debug in Visual Studio...\n"
  1325. "1. Select menu item File->Open Project\n"
  1326. "2. Change 'Files of type' to 'Executable Files'\n"
  1327. "3. Open this executable.\n"
  1328. "4. Select menu item Debug->Start\n"
  1329. "\n"
  1330. "Alternatively, set the environment variable \n"
  1331. "UNIT_TESTING_DEBUG to 1 and rebuild this executable, \n"
  1332. "then click 'Debug' in the popup dialog box.\n"
  1333. "\n");
  1334. shown_debug_message = 1;
  1335. }
  1336. exit_test(0);
  1337. return EXCEPTION_EXECUTE_HANDLER;
  1338. }
  1339. }
  1340. return EXCEPTION_CONTINUE_SEARCH;
  1341. }
  1342. #endif // !_WIN32
  1343. // Standard output and error print methods.
  1344. void vprint_message(const char* const format, va_list args) {
  1345. char buffer[1024];
  1346. vsnprintf(buffer, sizeof(buffer), format, args);
  1347. printf("%s", buffer);
  1348. fflush(stdout);
  1349. #ifdef _WIN32
  1350. OutputDebugString(buffer);
  1351. #endif // _WIN32
  1352. }
  1353. void vprint_error(const char* const format, va_list args) {
  1354. char buffer[1024];
  1355. vsnprintf(buffer, sizeof(buffer), format, args);
  1356. fprintf(stderr, "%s", buffer);
  1357. fflush(stderr);
  1358. #ifdef _WIN32
  1359. OutputDebugString(buffer);
  1360. #endif // _WIN32
  1361. }
  1362. void print_message(const char* const format, ...) {
  1363. va_list args;
  1364. va_start(args, format);
  1365. vprint_message(format, args);
  1366. va_end(args);
  1367. }
  1368. void print_error(const char* const format, ...) {
  1369. va_list args;
  1370. va_start(args, format);
  1371. vprint_error(format, args);
  1372. va_end(args);
  1373. }
  1374. int _run_test(
  1375. const char * const function_name, const UnitTestFunction Function,
  1376. void ** const volatile state, const UnitTestFunctionType function_type,
  1377. const void* const heap_check_point) {
  1378. const ListNode * const volatile check_point = (const ListNode*)
  1379. (heap_check_point ?
  1380. heap_check_point : check_point_allocated_blocks());
  1381. void *current_state = NULL;
  1382. volatile int rc = 1;
  1383. int handle_exceptions = 1;
  1384. #ifdef _WIN32
  1385. handle_exceptions = !IsDebuggerPresent();
  1386. #endif // _WIN32
  1387. #if UNIT_TESTING_DEBUG
  1388. handle_exceptions = 0;
  1389. #endif // UNIT_TESTING_DEBUG
  1390. if (handle_exceptions) {
  1391. #ifndef _WIN32
  1392. unsigned int i;
  1393. for (i = 0; i < ARRAY_LENGTH(exception_signals); i++) {
  1394. default_signal_functions[i] = signal(
  1395. exception_signals[i], exception_handler);
  1396. }
  1397. #else // _WIN32
  1398. previous_exception_filter = SetUnhandledExceptionFilter(
  1399. exception_filter);
  1400. #endif // !_WIN32
  1401. }
  1402. if (function_type == UNIT_TEST_FUNCTION_TYPE_TEST) {
  1403. print_message("[ RUN ] %s\n", function_name);
  1404. }
  1405. initialize_testing(function_name);
  1406. global_running_test = 1;
  1407. if (setjmp(global_run_test_env) == 0) {
  1408. Function(state ? state : &current_state);
  1409. fail_if_leftover_values(function_name);
  1410. /* If this is a setup function then ignore any allocated blocks
  1411. * only ensure they're deallocated on tear down. */
  1412. if (function_type != UNIT_TEST_FUNCTION_TYPE_SETUP) {
  1413. fail_if_blocks_allocated(check_point, function_name);
  1414. }
  1415. global_running_test = 0;
  1416. if (function_type == UNIT_TEST_FUNCTION_TYPE_TEST) {
  1417. print_message("[ OK ] %s\n", function_name);
  1418. }
  1419. rc = 0;
  1420. } else {
  1421. global_running_test = 0;
  1422. print_message("[ FAILED ] %s\n", function_name);
  1423. }
  1424. teardown_testing(function_name);
  1425. if (handle_exceptions) {
  1426. #ifndef _WIN32
  1427. unsigned int i;
  1428. for (i = 0; i < ARRAY_LENGTH(exception_signals); i++) {
  1429. signal(exception_signals[i], default_signal_functions[i]);
  1430. }
  1431. #else // _WIN32
  1432. if (previous_exception_filter) {
  1433. SetUnhandledExceptionFilter(previous_exception_filter);
  1434. previous_exception_filter = NULL;
  1435. }
  1436. #endif // !_WIN32
  1437. }
  1438. return rc;
  1439. }
  1440. int _run_tests(const UnitTest * const tests, const size_t number_of_tests) {
  1441. // Whether to execute the next test.
  1442. int run_next_test = 1;
  1443. // Whether the previous test failed.
  1444. int previous_test_failed = 0;
  1445. // Check point of the heap state.
  1446. const ListNode * const check_point = check_point_allocated_blocks();
  1447. // Current test being executed.
  1448. size_t current_test = 0;
  1449. // Number of tests executed.
  1450. size_t tests_executed = 0;
  1451. // Number of failed tests.
  1452. size_t total_failed = 0;
  1453. // Number of setup functions.
  1454. size_t setups = 0;
  1455. // Number of teardown functions.
  1456. size_t teardowns = 0;
  1457. /* A stack of test states. A state is pushed on the stack
  1458. * when a test setup occurs and popped on tear down. */
  1459. TestState* test_states =
  1460. (TestState*)malloc(number_of_tests * sizeof(*test_states));
  1461. size_t number_of_test_states = 0;
  1462. // Names of the tests that failed.
  1463. const char** failed_names = (const char**)malloc(number_of_tests *
  1464. sizeof(*failed_names));
  1465. void **current_state = NULL;
  1466. print_message("[==========] Running %d test(s).\n", number_of_tests);
  1467. // Make sure uintmax_t is at least the size of a pointer.
  1468. assert_true(sizeof(uintmax_t) >= sizeof(void*));
  1469. while (current_test < number_of_tests) {
  1470. const ListNode *test_check_point = NULL;
  1471. TestState *current_TestState;
  1472. const UnitTest * const test = &tests[current_test++];
  1473. if (!test->function) {
  1474. continue;
  1475. }
  1476. switch (test->function_type) {
  1477. case UNIT_TEST_FUNCTION_TYPE_TEST:
  1478. run_next_test = 1;
  1479. break;
  1480. case UNIT_TEST_FUNCTION_TYPE_SETUP: {
  1481. // Checkpoint the heap before the setup.
  1482. current_TestState = &test_states[number_of_test_states++];
  1483. current_TestState->check_point = check_point_allocated_blocks();
  1484. test_check_point = current_TestState->check_point;
  1485. current_state = &current_TestState->state;
  1486. *current_state = NULL;
  1487. run_next_test = 1;
  1488. setups ++;
  1489. break;
  1490. }
  1491. case UNIT_TEST_FUNCTION_TYPE_TEARDOWN:
  1492. // Check the heap based on the last setup checkpoint.
  1493. assert_true(number_of_test_states);
  1494. current_TestState = &test_states[--number_of_test_states];
  1495. test_check_point = current_TestState->check_point;
  1496. current_state = &current_TestState->state;
  1497. teardowns ++;
  1498. break;
  1499. default:
  1500. print_error("Invalid unit test function type %d\n",
  1501. test->function_type);
  1502. exit_test(1);
  1503. break;
  1504. }
  1505. if (run_next_test) {
  1506. int failed = _run_test(test->name, test->function, current_state,
  1507. test->function_type, test_check_point);
  1508. if (failed) {
  1509. failed_names[total_failed] = test->name;
  1510. }
  1511. switch (test->function_type) {
  1512. case UNIT_TEST_FUNCTION_TYPE_TEST:
  1513. previous_test_failed = failed;
  1514. total_failed += failed;
  1515. tests_executed ++;
  1516. break;
  1517. case UNIT_TEST_FUNCTION_TYPE_SETUP:
  1518. if (failed) {
  1519. total_failed ++;
  1520. tests_executed ++;
  1521. // Skip forward until the next test or setup function.
  1522. run_next_test = 0;
  1523. }
  1524. previous_test_failed = 0;
  1525. break;
  1526. case UNIT_TEST_FUNCTION_TYPE_TEARDOWN:
  1527. // If this test failed.
  1528. if (failed && !previous_test_failed) {
  1529. total_failed ++;
  1530. }
  1531. break;
  1532. default:
  1533. #ifndef _HPUX
  1534. assert_null("BUG: shouldn't be here!");
  1535. #endif
  1536. break;
  1537. }
  1538. }
  1539. }
  1540. print_message("[==========] %d test(s) run.\n", tests_executed);
  1541. print_error("[ PASSED ] %d test(s).\n", tests_executed - total_failed);
  1542. if (total_failed) {
  1543. size_t i;
  1544. print_error("[ FAILED ] %d test(s), listed below:\n", total_failed);
  1545. for (i = 0; i < total_failed; i++) {
  1546. print_error("[ FAILED ] %s\n", failed_names[i]);
  1547. }
  1548. } else {
  1549. print_error("\n %d FAILED TEST(S)\n", total_failed);
  1550. }
  1551. if (number_of_test_states) {
  1552. print_error("[ ERROR ] Mismatched number of setup %d and "
  1553. "teardown %d functions\n", setups, teardowns);
  1554. total_failed = (size_t)-1;
  1555. }
  1556. free(test_states);
  1557. free((void*)failed_names);
  1558. fail_if_blocks_allocated(check_point, "run_tests");
  1559. return (int)total_failed;
  1560. }