test_suite_platform_printf.function (2404B)
1 /* BEGIN_HEADER */ 2 3 /* The printf test functions take a format argument from the test data 4 * for several reasons: 5 * - For some tests, it makes sense to vary the format. 6 * - For all tests, it means we're testing the actual printf function 7 * that parses the format at runtime, and not a compiler optimization. 8 * (It may be useful to add tests that allow compiler optimizations. 9 * There aren't any yet at the time of writing.) 10 */ 11 12 #include "mbedtls/platform.h" 13 14 #include <stdio.h> 15 #include <stdlib.h> 16 #include <string.h> 17 18 #define NEWLINE_CHAR '\n' 19 #define SPACE_CHAR ' ' 20 #define DOUBLE_QUOTE_CHAR '"' 21 #define COLON_CHAR ':' 22 #define QUESTION_CHAR '?' 23 #define BACKSLASH_CHAR '\\' 24 #define LOWERCASE_N_CHAR 'n' 25 /* END_HEADER */ 26 27 /* BEGIN_CASE */ 28 void printf_int(char *format, /* any format expecting one int argument, e.g. "%d" */ 29 int x, char *result) 30 { 31 char *output = NULL; 32 const size_t n = strlen(result); 33 34 /* Nominal case: buffer just large enough */ 35 TEST_CALLOC(output, n + 1); 36 TEST_EQUAL(n, mbedtls_snprintf(output, n + 1, format, x)); 37 TEST_MEMORY_COMPARE(result, n + 1, output, n + 1); 38 mbedtls_free(output); 39 output = NULL; 40 41 exit: 42 mbedtls_free(output); 43 } 44 /* END_CASE */ 45 46 /* BEGIN_CASE */ 47 void printf_long_max(const char *format, /* "%lx" or longer type */ 48 long value) 49 { 50 char *expected = NULL; 51 char *output = NULL; 52 /* 2 hex digits per byte */ 53 const size_t n = sizeof(value) * 2; 54 55 /* We assume that long has no padding bits! */ 56 TEST_CALLOC(expected, n + 1); 57 expected[0] = '7'; 58 memset(expected + 1, 'f', sizeof(value) * 2 - 1); 59 60 TEST_CALLOC(output, n + 1); 61 TEST_EQUAL(n, mbedtls_snprintf(output, n + 1, format, value)); 62 TEST_MEMORY_COMPARE(expected, n + 1, output, n + 1); 63 mbedtls_free(output); 64 output = NULL; 65 66 exit: 67 mbedtls_free(output); 68 mbedtls_free(expected); 69 } 70 /* END_CASE */ 71 72 /* BEGIN_CASE */ 73 void printf_char2(char *format, /* "%c%c" */ 74 int arg1, int arg2, char *result) 75 { 76 char *output = NULL; 77 const size_t n = strlen(result); 78 79 /* Nominal case: buffer just large enough */ 80 TEST_CALLOC(output, n + 1); 81 TEST_EQUAL(n, mbedtls_snprintf(output, n + 1, format, arg1, arg2)); 82 TEST_MEMORY_COMPARE(result, n + 1, output, n + 1); 83 mbedtls_free(output); 84 output = NULL; 85 86 exit: 87 mbedtls_free(output); 88 } 89 /* END_CASE */