Fix test/recipes/95-test_external_krb5.t
[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     fflush(stdout);
118
119     for (i = 0; i != num_tests; ++i) {
120         if (all_tests[i].num == -1) {
121             int ret = all_tests[i].test_fn();
122
123             if (!ret) {
124                 printf("** %s failed **\n--------\n",
125                        all_tests[i].test_case_name);
126                 fflush(stdout);
127                 ++num_failed;
128             }
129             finalize(ret);
130         } else {
131             for (j = 0; j < all_tests[i].num; j++) {
132                 int ret = all_tests[i].param_test_fn(j);
133
134                 if (!ret) {
135                     printf("** %s failed test %d\n--------\n",
136                            all_tests[i].test_case_name, j);
137                     fflush(stdout);
138                     ++num_failed;
139                 }
140                 finalize(ret);
141             }
142         }
143     }
144
145     if (num_failed != 0) {
146         printf("%s: %d test%s failed (out of %d)\n", test_prog_name,
147                num_failed, num_failed != 1 ? "s" : "", num_test_cases);
148         fflush(stdout);
149         return EXIT_FAILURE;
150     }
151     printf("  All tests passed.\n");
152     fflush(stdout);
153     return EXIT_SUCCESS;
154 }
155
156 /*
157  * A common routine to output test failure messages.  Generally this should not
158  * be called directly, rather it should be called by the following functions.
159  *
160  * |desc| is a printf formatted description with arguments |args| that is
161  * supplied by the user and |desc| can be NULL.  |type| is the data type
162  * that was tested (int, char, ptr, ...).  |fmt| is a system provided
163  * printf format with following arguments that spell out the failure
164  * details i.e. the actual values compared and the operator used.
165  *
166  * The typical use for this is from an utility test function:
167  *
168  * int test6(const char *file, int line, int n) {
169  *     if (n != 6) {
170  *         test_fail_message(1, file, line, "int", "value %d is not %d", n, 6);
171  *         return 0;
172  *     }
173  *     return 1;
174  * }
175  *
176  * calling test6(3, "oops") will return 0 and produce out along the lines of:
177  *      FAIL oops: (int) value 3 is not 6\n
178  *
179  * It general, test_fail_message should not be called directly.
180  */
181 static void test_fail_message(const char *prefix, const char *file, int line,
182                               const char *type, const char *fmt, ...)
183             PRINTF_FORMAT(5, 6);
184
185 static void test_fail_message_va(const char *prefix, const char *file, int line,
186                                  const char *type, const char *fmt, va_list ap)
187 {
188     fputs(prefix != NULL ? prefix : "ERROR", stderr);
189     fputs(":", stderr);
190     if (type)
191         fprintf(stderr, " (%s)", type);
192     if (fmt != NULL) {
193         fputc(' ', stderr);
194         vfprintf(stderr, fmt, ap);
195     }
196     if (file != NULL) {
197         fprintf(stderr, " @ %s:%d", file, line);
198     }
199     fputc('\n', stderr);
200 }
201
202 static void test_fail_message(const char *prefix, const char *file, int line,
203                               const char *type, const char *fmt, ...)
204 {
205     va_list ap;
206     va_start(ap, fmt);
207     test_fail_message_va(prefix, file, line, type, fmt, ap);
208     va_end(ap);
209 }
210
211 void test_info_c90(const char *desc, ...)
212 {
213     va_list ap;
214
215     va_start(ap, desc);
216     test_fail_message_va("INFO", NULL, -1, NULL, desc, ap);
217     va_end(ap);
218 }
219
220 void test_info(const char *file, int line, const char *desc, ...)
221 {
222     va_list ap;
223
224     va_start(ap, desc);
225     test_fail_message_va("INFO", file, line, NULL, desc, ap);
226     va_end(ap);
227 }
228
229 void test_error_c90(const char *desc, ...)
230 {
231     va_list ap;
232
233     va_start(ap, desc);
234     test_fail_message(NULL, NULL, -1, NULL, desc, ap);
235     va_end(ap);
236 }
237
238 void test_error(const char *file, int line, const char *desc, ...)
239 {
240     va_list ap;
241
242     va_start(ap, desc);
243     test_fail_message_va(NULL, file, line, NULL, desc, ap);
244     va_end(ap);
245 }
246
247 /*
248  * Define some comparisons between pairs of various types.
249  * These functions return 1 if the test is true.
250  * Otherwise, they return 0 and pretty-print diagnostics.
251  *
252  * In each case the functions produced are:
253  *  int test_name_eq(const type t1, const type t2, const char *desc, ...);
254  *  int test_name_ne(const type t1, const type t2, const char *desc, ...);
255  *  int test_name_lt(const type t1, const type t2, const char *desc, ...);
256  *  int test_name_le(const type t1, const type t2, const char *desc, ...);
257  *  int test_name_gt(const type t1, const type t2, const char *desc, ...);
258  *  int test_name_ge(const type t1, const type t2, const char *desc, ...);
259  *
260  * The t1 and t2 arguments are to be compared for equality, inequality,
261  * less than, less than or equal to, greater than and greater than or
262  * equal to respectively.  If the specified condition holds, the functions
263  * return 1.  If the condition does not hold, the functions print a diagnostic
264  * message and return 0.
265  *
266  * The desc argument is a printf format string followed by its arguments and
267  * this is included in the output if the condition being tested for is false.
268  */
269 #define DEFINE_COMPARISON(type, name, opname, op, fmt)                  \
270     int test_ ## name ## _ ## opname(const char *file, int line,        \
271                                      const char *s1, const char *s2,    \
272                                      const type t1, const type t2)      \
273     {                                                                   \
274         if (t1 op t2)                                                   \
275             return 1;                                                   \
276         test_fail_message(NULL, file, line, #type,                      \
277                           "%s [" fmt "] " #op " %s [" fmt "]",          \
278                           s1, t1, s2, t2);                              \
279         return 0;                                                       \
280     }
281
282 #define DEFINE_COMPARISONS(type, name, fmt)                             \
283     DEFINE_COMPARISON(type, name, eq, ==, fmt)                          \
284     DEFINE_COMPARISON(type, name, ne, !=, fmt)                          \
285     DEFINE_COMPARISON(type, name, lt, <, fmt)                           \
286     DEFINE_COMPARISON(type, name, le, <=, fmt)                          \
287     DEFINE_COMPARISON(type, name, gt, >, fmt)                           \
288     DEFINE_COMPARISON(type, name, ge, >=, fmt)
289
290 DEFINE_COMPARISONS(int, int, "%d")
291 DEFINE_COMPARISONS(unsigned int, uint, "%u")
292 DEFINE_COMPARISONS(char, char, "%c")
293 DEFINE_COMPARISONS(unsigned char, uchar, "%u")
294 DEFINE_COMPARISONS(long, long, "%ld")
295 DEFINE_COMPARISONS(unsigned long, ulong, "%lu")
296 DEFINE_COMPARISONS(size_t, size_t, "%" OSSLzu)
297
298 DEFINE_COMPARISON(void *, ptr, eq, ==, "%p")
299 DEFINE_COMPARISON(void *, ptr, ne, !=, "%p")
300
301 int test_ptr_null(const char *file, int line, const char *s, const void *p)
302 {
303     if (p == NULL)
304         return 1;
305     test_fail_message(NULL, file, line, "ptr", "%s [%p] == NULL", s, p);
306     return 0;
307 }
308
309 int test_ptr(const char *file, int line, const char *s, const void *p)
310 {
311     if (p != NULL)
312         return 1;
313     test_fail_message(NULL, file, line, "ptr", "%s [%p] != NULL", s, p);
314     return 0;
315 }
316
317 int test_true(const char *file, int line, const char *s, int b)
318 {
319     if (b)
320         return 1;
321     test_fail_message(NULL, file, line, "bool", "%s [false] == true", s);
322     return 0;
323 }
324
325 int test_false(const char *file, int line, const char *s, int b)
326 {
327     if (!b)
328         return 1;
329     test_fail_message(NULL, file, line, "bool", "%s [true] == false", s);
330     return 0;
331 }
332
333 static const char *print_string_maybe_null(const char *s)
334 {
335     return s == NULL ? "(NULL)" : s;
336 }
337
338 int test_str_eq(const char *file, int line, const char *st1, const char *st2,
339                 const char *s1, const char *s2)
340 {
341     if (s1 == NULL && s2 == NULL)
342       return 1;
343     if (s1 == NULL || s2 == NULL || strcmp(s1, s2) != 0) {
344         test_fail_message(NULL, file, line, "string", "%s [%s] == %s [%s]",
345                           st1, print_string_maybe_null(s1),
346                           st2, print_string_maybe_null(s2));
347         return 0;
348     }
349     return 1;
350 }
351
352 int test_str_ne(const char *file, int line, const char *st1, const char *st2,
353                 const char *s1, const char *s2)
354 {
355     if ((s1 == NULL) ^ (s2 == NULL))
356       return 1;
357     if (s1 == NULL || strcmp(s1, s2) == 0) {
358         test_fail_message(NULL, file, line, "string", "%s [%s] != %s [%s]",
359                           st1, print_string_maybe_null(s1),
360                           st2, print_string_maybe_null(s2));
361         return 0;
362     }
363     return 1;
364 }
365
366 int test_strn_eq(const char *file, int line, const char *st1, const char *st2,
367                  const char *s1, const char *s2, size_t len)
368 {
369     int prec = (int)len;
370
371     if (s1 == NULL && s2 == NULL)
372       return 1;
373     if (s1 == NULL || s2 == NULL || strncmp(s1, s2, len) != 0) {
374         test_fail_message(NULL, file, line, "string", "%.s [%.*s] == %s [%.*s]",
375                           st1, prec, print_string_maybe_null(s1),
376                           st2, prec, print_string_maybe_null(s2));
377         return 0;
378     }
379     return 1;
380 }
381
382 int test_strn_ne(const char *file, int line, const char *st1, const char *st2,
383                  const char *s1, const char *s2, size_t len)
384 {
385     int prec = (int)len;
386
387     if ((s1 == NULL) ^ (s2 == NULL))
388       return 1;
389     if (s1 == NULL || strncmp(s1, s2, len) == 0) {
390         test_fail_message(NULL, file, line, "string", "%s [%.*s] != %s [%.*s]",
391                           st1, prec, print_string_maybe_null(s1),
392                           st2, prec, print_string_maybe_null(s2));
393         return 0;
394     }
395     return 1;
396 }
397
398 /*
399  * We could use OPENSSL_buf2hexstr() to do this but trying to allocate memory
400  * in a failure state isn't generally a great idea.
401  */
402 static const char *print_mem_maybe_null(const void *s, size_t n,
403                                         char out[MEM_BUFFER_SIZE])
404 {
405     size_t i;
406     const unsigned char *p = (const unsigned char *)s;
407     int pad = 2*n >= MEM_BUFFER_SIZE;
408
409     if (s == NULL)
410         return "(NULL)";
411     if (pad)
412         n = MEM_BUFFER_SIZE-4;
413     
414     for (i=0; i<2*n; i++) {
415         unsigned char c = (i & 1) != 0 ? p[i / 2] & 15 : p[i / 2] >> 4;
416         out[i] = "0123456789abcdef"[c];
417     }
418     if (pad) {
419         out[i++] = '.';
420         out[i++] = '.';
421         out[i++] = '.';
422     }
423     out[i] = '\0';
424         
425     return out;
426 }
427
428 int test_mem_eq(const char *file, int line, const char *st1, const char *st2,
429                 const void *s1, size_t n1, const void *s2, size_t n2)
430 {
431     char b1[MEM_BUFFER_SIZE], b2[MEM_BUFFER_SIZE];
432
433     if (s1 == NULL && s2 == NULL)
434         return 1;
435     if (n1 != n2) {
436         test_fail_message(NULL, file, line, "memory",
437                           "size mismatch %s %s [%"OSSLzu"] != %s %s [%"OSSLzu"]",
438                           st1, print_mem_maybe_null(s1, n1, b1), n1,
439                           st2, print_mem_maybe_null(s2, n2, b2), n2);
440         return 0;
441     }
442     if (s1 == NULL || s2 == NULL || memcmp(s1, s2, n1) != 0) {
443         test_fail_message(NULL, file, line, "memory",
444                           "%s %s [%"OSSLzu"] != %s %s [%"OSSLzu"]",
445                           st1, print_mem_maybe_null(s1, n1, b1), n1,
446                           st2, print_mem_maybe_null(s2, n2, b2), n2);
447         return 0;
448     }
449     return 1;
450 }
451
452 int test_mem_ne(const char *file, int line, const char *st1, const char *st2,
453                 const void *s1, size_t n1, const void *s2, size_t n2)
454 {
455     char b1[MEM_BUFFER_SIZE], b2[MEM_BUFFER_SIZE];
456
457     if ((s1 == NULL) ^ (s2 == NULL))
458       return 1;
459     if (n1 != n2)
460         return 1;
461     if (s1 == NULL || memcmp(s1, s2, n1) == 0) {
462         test_fail_message(NULL, file, line, "memory",
463                           "%s %s [%"OSSLzu"] != %s %s [%"OSSLzu"]",
464                           st1, print_mem_maybe_null(s1, n1, b1), n1,
465                           st2, print_mem_maybe_null(s2, n2, b2), n2);
466         return 0;
467     }
468     return 1;
469 }