Update rc2test to use the test infrastructure
[openssl.git] / test / testutil.c
1 /*
2  * Copyright 2014-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include "testutil.h"
11
12 #include <assert.h>
13 #include <stdlib.h>
14 #include <stdio.h>
15 #include <string.h>
16 #include "e_os.h"
17
18 #include <openssl/opensslconf.h>
19 #include <openssl/crypto.h>
20 #include <openssl/err.h>
21
22 /* The size of memory buffers to display on failure */
23 #define MEM_BUFFER_SIZE     (21)
24
25 /*
26  * Declares the structures needed to register each test case function.
27  */
28 typedef struct test_info {
29     const char *test_case_name;
30     int (*test_fn) ();
31     int (*param_test_fn)(int idx);
32     int num;
33 } TEST_INFO;
34
35 static TEST_INFO all_tests[1024];
36 static int num_tests = 0;
37 /*
38  * A parameterised tests runs a loop of test cases.
39  * |num_test_cases| counts the total number of test cases
40  * across all tests.
41  */
42 static int num_test_cases = 0;
43
44 void add_test(const char *test_case_name, int (*test_fn) ())
45 {
46     assert(num_tests != OSSL_NELEM(all_tests));
47     all_tests[num_tests].test_case_name = test_case_name;
48     all_tests[num_tests].test_fn = test_fn;
49     all_tests[num_tests].num = -1;
50     ++num_test_cases;
51     ++num_tests;
52 }
53
54 void add_all_tests(const char *test_case_name, int(*test_fn)(int idx),
55                    int num)
56 {
57     assert(num_tests != OSSL_NELEM(all_tests));
58     all_tests[num_tests].test_case_name = test_case_name;
59     all_tests[num_tests].param_test_fn = test_fn;
60     all_tests[num_tests].num = num;
61     ++num_tests;
62     num_test_cases += num;
63 }
64
65 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
66 static int should_report_leaks()
67 {
68     /*
69      * When compiled with enable-crypto-mdebug, OPENSSL_DEBUG_MEMORY=0
70      * can be used to disable leak checking at runtime.
71      * Note this only works when running the test binary manually;
72      * the test harness always enables OPENSSL_DEBUG_MEMORY.
73      */
74     char *mem_debug_env = getenv("OPENSSL_DEBUG_MEMORY");
75
76     return mem_debug_env == NULL
77         || (strcmp(mem_debug_env, "0") && strcmp(mem_debug_env, ""));
78 }
79 #endif
80
81
82 void setup_test()
83 {
84 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
85     if (should_report_leaks()) {
86         CRYPTO_set_mem_debug(1);
87         CRYPTO_mem_ctrl(CRYPTO_MEM_CHECK_ON);
88     }
89 #endif
90 }
91
92 int finish_test(int ret)
93 {
94 #ifndef OPENSSL_NO_CRYPTO_MDEBUG
95     if (should_report_leaks() && CRYPTO_mem_leaks_fp(stderr) <= 0)
96         return EXIT_FAILURE;
97 #endif
98     return ret;
99 }
100
101 static void finalize(int success)
102 {
103     if (success)
104         ERR_clear_error();
105     else
106         ERR_print_errors_fp(stderr);
107 }
108
109 int run_tests(const char *test_prog_name)
110 {
111     int num_failed = 0;
112
113     int i, j;
114
115     printf("%s: %d test case%s\n", test_prog_name, num_test_cases,
116            num_test_cases == 1 ? "" : "s");
117
118     for (i = 0; i != num_tests; ++i) {
119         if (all_tests[i].num == -1) {
120             int ret = all_tests[i].test_fn();
121
122             if (!ret) {
123                 printf("** %s failed **\n--------\n",
124                        all_tests[i].test_case_name);
125                 ++num_failed;
126             }
127             finalize(ret);
128         } else {
129             for (j = 0; j < all_tests[i].num; j++) {
130                 int ret = all_tests[i].param_test_fn(j);
131
132                 if (!ret) {
133                     printf("** %s failed test %d\n--------\n",
134                            all_tests[i].test_case_name, j);
135                     ++num_failed;
136                 }
137                 finalize(ret);
138             }
139         }
140     }
141
142     if (num_failed != 0) {
143         printf("%s: %d test%s failed (out of %d)\n", test_prog_name,
144                num_failed, num_failed != 1 ? "s" : "", num_test_cases);
145         return EXIT_FAILURE;
146     }
147     printf("  All tests passed.\n");
148     return EXIT_SUCCESS;
149 }
150
151 /*
152  * A common routine to output test failure messages.  Generally this should not
153  * be called directly, rather it should be called by the following functions.
154  *
155  * |desc| is a printf formatted description with arguments |args| that is
156  * supplied by the user and |desc| can be NULL.  |type| is the data type
157  * that was tested (int, char, ptr, ...).  |fmt| is a system provided
158  * printf format with following arguments that spell out the failure
159  * details i.e. the actual values compared and the operator used.
160  *
161  * The typical use for this is from an utility test function:
162  *
163  * int test6(const char *file, int line, int n) {
164  *     if (n != 6) {
165  *         test_fail_message(1, file, line, "int", "value %d is not %d", n, 6);
166  *         return 0;
167  *     }
168  *     return 1;
169  * }
170  *
171  * calling test6(3, "oops") will return 0 and produce out along the lines of:
172  *      FAIL oops: (int) value 3 is not 6\n
173  *
174  * It general, test_fail_message should not be called directly.
175  */
176 static void test_fail_message(const char *prefix, const char *file, int line,
177                               const char *type, const char *fmt, ...)
178             PRINTF_FORMAT(5, 6);
179
180 static void test_fail_message_va(const char *prefix, const char *file, int line,
181                                  const char *type, const char *fmt, va_list ap)
182 {
183     fputs(prefix != NULL ? prefix : "ERROR", stderr);
184     fputs(":", stderr);
185     if (type)
186         fprintf(stderr, " (%s)", type);
187     if (fmt != NULL) {
188         fputc(' ', stderr);
189         vfprintf(stderr, fmt, ap);
190     }
191     if (file != NULL) {
192         fprintf(stderr, " @ %s:%d", file, line);
193     }
194     fputc('\n', stderr);
195 }
196
197 static void test_fail_message(const char *prefix, const char *file, int line,
198                               const char *type, const char *fmt, ...)
199 {
200     va_list ap;
201     va_start(ap, fmt);
202     test_fail_message_va(prefix, file, line, type, fmt, ap);
203     va_end(ap);
204 }
205
206 void test_info_c90(const char *desc, ...)
207 {
208     va_list ap;
209
210     va_start(ap, desc);
211     test_fail_message_va("INFO", NULL, -1, NULL, desc, ap);
212     va_end(ap);
213 }
214
215 void test_info(const char *file, int line, const char *desc, ...)
216 {
217     va_list ap;
218
219     va_start(ap, desc);
220     test_fail_message_va("INFO", file, line, NULL, desc, ap);
221     va_end(ap);
222 }
223
224 void test_error_c90(const char *desc, ...)
225 {
226     va_list ap;
227
228     va_start(ap, desc);
229     test_fail_message(NULL, NULL, -1, NULL, desc, ap);
230     va_end(ap);
231 }
232
233 void test_error(const char *file, int line, const char *desc, ...)
234 {
235     va_list ap;
236
237     va_start(ap, desc);
238     test_fail_message_va(NULL, file, line, NULL, desc, ap);
239     va_end(ap);
240 }
241
242 /*
243  * Define some comparisons between pairs of various types.
244  * These functions return 1 if the test is true.
245  * Otherwise, they return 0 and pretty-print diagnostics.
246  *
247  * In each case the functions produced are:
248  *  int test_name_eq(const type t1, const type t2, const char *desc, ...);
249  *  int test_name_ne(const type t1, const type t2, const char *desc, ...);
250  *  int test_name_lt(const type t1, const type t2, const char *desc, ...);
251  *  int test_name_le(const type t1, const type t2, const char *desc, ...);
252  *  int test_name_gt(const type t1, const type t2, const char *desc, ...);
253  *  int test_name_ge(const type t1, const type t2, const char *desc, ...);
254  *
255  * The t1 and t2 arguments are to be compared for equality, inequality,
256  * less than, less than or equal to, greater than and greater than or
257  * equal to respectively.  If the specified condition holds, the functions
258  * return 1.  If the condition does not hold, the functions print a diagnostic
259  * message and return 0.
260  *
261  * The desc argument is a printf format string followed by its arguments and
262  * this is included in the output if the condition being tested for is false.
263  */
264 #define DEFINE_COMPARISON(type, name, opname, op, fmt)                  \
265     int test_ ## name ## _ ## opname(const char *file, int line,        \
266                                      const char *s1, const char *s2,    \
267                                      const type t1, const type t2)      \
268     {                                                                   \
269         if (t1 op t2)                                                   \
270             return 1;                                                   \
271         test_fail_message(NULL, file, line, #type,                      \
272                           "%s [" fmt "] " #op " %s [" fmt "]",          \
273                           s1, t1, s2, t2);                              \
274         return 0;                                                       \
275     }
276
277 #define DEFINE_COMPARISONS(type, name, fmt)                             \
278     DEFINE_COMPARISON(type, name, eq, ==, fmt)                          \
279     DEFINE_COMPARISON(type, name, ne, !=, fmt)                          \
280     DEFINE_COMPARISON(type, name, lt, <, fmt)                           \
281     DEFINE_COMPARISON(type, name, le, <=, fmt)                          \
282     DEFINE_COMPARISON(type, name, gt, >, fmt)                           \
283     DEFINE_COMPARISON(type, name, ge, >=, fmt)
284
285 DEFINE_COMPARISONS(int, int, "%d")
286 DEFINE_COMPARISONS(unsigned int, uint, "%u")
287 DEFINE_COMPARISONS(char, char, "%c")
288 DEFINE_COMPARISONS(unsigned char, uchar, "%u")
289 DEFINE_COMPARISONS(long, long, "%ld")
290 DEFINE_COMPARISONS(unsigned long, ulong, "%lu")
291 DEFINE_COMPARISONS(size_t, size_t, "%" OSSLzu)
292
293 DEFINE_COMPARISON(void *, ptr, eq, ==, "%p")
294 DEFINE_COMPARISON(void *, ptr, ne, !=, "%p")
295
296 int test_ptr_null(const char *file, int line, const char *s, const void *p)
297 {
298     if (p == NULL)
299         return 1;
300     test_fail_message(NULL, file, line, "ptr", "%s [%p] == NULL", s, p);
301     return 0;
302 }
303
304 int test_ptr(const char *file, int line, const char *s, const void *p)
305 {
306     if (p != NULL)
307         return 1;
308     test_fail_message(NULL, file, line, "ptr", "%s [%p] != NULL", s, p);
309     return 0;
310 }
311
312 int test_true(const char *file, int line, const char *s, int b)
313 {
314     if (b)
315         return 1;
316     test_fail_message(NULL, file, line, "bool", "%s [false] == true", s);
317     return 0;
318 }
319
320 int test_false(const char *file, int line, const char *s, int b)
321 {
322     if (!b)
323         return 1;
324     test_fail_message(NULL, file, line, "bool", "%s [true] == false", s);
325     return 0;
326 }
327
328 static const char *print_string_maybe_null(const char *s)
329 {
330     return s == NULL ? "(NULL)" : s;
331 }
332
333 int test_str_eq(const char *file, int line, const char *st1, const char *st2,
334                 const char *s1, const char *s2)
335 {
336     if (s1 == NULL && s2 == NULL)
337       return 1;
338     if (s1 == NULL || s2 == NULL || strcmp(s1, s2) != 0) {
339         test_fail_message(NULL, file, line, "string", "%s [%s] == %s [%s]",
340                           st1, print_string_maybe_null(s1),
341                           st2, print_string_maybe_null(s2));
342         return 0;
343     }
344     return 1;
345 }
346
347 int test_str_ne(const char *file, int line, const char *st1, const char *st2,
348                 const char *s1, const char *s2)
349 {
350     if ((s1 == NULL) ^ (s2 == NULL))
351       return 1;
352     if (s1 == NULL || strcmp(s1, s2) == 0) {
353         test_fail_message(NULL, file, line, "string", "%s [%s] != %s [%s]",
354                           st1, print_string_maybe_null(s1),
355                           st2, print_string_maybe_null(s2));
356         return 0;
357     }
358     return 1;
359 }
360
361 /*
362  * We could use OPENSSL_buf2hexstr() to do this but trying to allocate memory
363  * in a failure state isn't generally a great idea.
364  */
365 static const char *print_mem_maybe_null(const void *s, size_t n,
366                                         char out[MEM_BUFFER_SIZE])
367 {
368     size_t i;
369     const unsigned char *p = (const unsigned char *)s;
370     int pad = 2*n >= MEM_BUFFER_SIZE;
371
372     if (s == NULL)
373         return "(NULL)";
374     if (pad)
375         n = MEM_BUFFER_SIZE-4;
376     
377     for (i=0; i<2*n; i++) {
378         unsigned char c = (i & 1) != 0 ? p[i / 2] & 15 : p[i / 2] >> 4;
379         out[i] = "0123456789abcdef"[c];
380     }
381     if (pad) {
382         out[i++] = '.';
383         out[i++] = '.';
384         out[i++] = '.';
385     }
386     out[i] = '\0';
387         
388     return out;
389 }
390
391 int test_mem_eq(const char *file, int line, const char *st1, const char *st2,
392                 const void *s1, size_t n1, const void *s2, size_t n2)
393 {
394     char b1[MEM_BUFFER_SIZE], b2[MEM_BUFFER_SIZE];
395
396     if (s1 == NULL && s2 == NULL)
397         return 1;
398     if (n1 != n2) {
399         test_fail_message(NULL, file, line, "memory",
400                           "size mismatch %s %s [%"OSSLzu"] != %s %s [%"OSSLzu"]",
401                           st1, print_mem_maybe_null(s1, n1, b1), n1,
402                           st2, print_mem_maybe_null(s2, n2, b2), n2);
403         return 0;
404     }
405     if (s1 == NULL || s2 == NULL || memcmp(s1, s2, n1) != 0) {
406         test_fail_message(NULL, file, line, "memory",
407                           "%s %s [%"OSSLzu"] != %s %s [%"OSSLzu"]",
408                           st1, print_mem_maybe_null(s1, n1, b1), n1,
409                           st2, print_mem_maybe_null(s2, n2, b2), n2);
410         return 0;
411     }
412     return 1;
413 }
414
415 int test_mem_ne(const char *file, int line, const char *st1, const char *st2,
416                 const void *s1, size_t n1, const void *s2, size_t n2)
417 {
418     char b1[MEM_BUFFER_SIZE], b2[MEM_BUFFER_SIZE];
419
420     if ((s1 == NULL) ^ (s2 == NULL))
421       return 1;
422     if (n1 != n2)
423         return 1;
424     if (s1 == NULL || memcmp(s1, s2, n1) == 0) {
425         test_fail_message(NULL, file, line, "memory",
426                           "%s %s [%"OSSLzu"] != %s %s [%"OSSLzu"]",
427                           st1, print_mem_maybe_null(s1, n1, b1), n1,
428                           st2, print_mem_maybe_null(s2, n2, b2), n2);
429         return 0;
430     }
431     return 1;
432 }