1 /* $NetBSD: safe_test.c,v 1.3 2025/01/26 16:25:50 christos Exp $ */ 2 3 /* 4 * Copyright (C) Internet Systems Consortium, Inc. ("ISC") 5 * 6 * SPDX-License-Identifier: MPL-2.0 7 * 8 * This Source Code Form is subject to the terms of the Mozilla Public 9 * License, v. 2.0. If a copy of the MPL was not distributed with this 10 * file, you can obtain one at https://mozilla.org/MPL/2.0/. 11 * 12 * See the COPYRIGHT file distributed with this work for additional 13 * information regarding copyright ownership. 14 */ 15 16 /* ! \file */ 17 18 #include <inttypes.h> 19 #include <sched.h> /* IWYU pragma: keep */ 20 #include <setjmp.h> 21 #include <stdarg.h> 22 #include <stddef.h> 23 #include <stdlib.h> 24 #include <string.h> 25 26 #define UNIT_TESTING 27 #include <cmocka.h> 28 29 #include <isc/safe.h> 30 #include <isc/util.h> 31 32 #include <tests/isc.h> 33 34 /* test isc_safe_memequal() */ 35 ISC_RUN_TEST_IMPL(isc_safe_memequal) { 36 UNUSED(state); 37 38 assert_true(isc_safe_memequal("test", "test", 4)); 39 assert_true(!isc_safe_memequal("test", "tesc", 4)); 40 assert_true( 41 isc_safe_memequal("\x00\x00\x00\x00", "\x00\x00\x00\x00", 4)); 42 assert_true( 43 !isc_safe_memequal("\x00\x00\x00\x00", "\x00\x00\x00\x01", 4)); 44 assert_true( 45 !isc_safe_memequal("\x00\x00\x00\x02", "\x00\x00\x00\x00", 4)); 46 } 47 48 /* test isc_safe_memwipe() */ 49 ISC_RUN_TEST_IMPL(isc_safe_memwipe) { 50 UNUSED(state); 51 52 /* These should pass. */ 53 isc_safe_memwipe(NULL, 0); 54 isc_safe_memwipe((void *)-1, 0); 55 56 /* 57 * isc_safe_memwipe(ptr, size) should function same as 58 * memset(ptr, 0, size); 59 */ 60 { 61 char buf1[4] = { 1, 2, 3, 4 }; 62 char buf2[4] = { 1, 2, 3, 4 }; 63 64 isc_safe_memwipe(buf1, sizeof(buf1)); 65 memset(buf2, 0, sizeof(buf2)); 66 67 assert_int_equal(memcmp(buf1, buf2, sizeof(buf1)), 0); 68 } 69 70 /* 71 * Boundary test. 72 */ 73 { 74 char buf1[4] = { 1, 2, 3, 4 }; 75 char buf2[4] = { 1, 2, 3, 4 }; 76 77 /* 78 * We wipe 3 elements on purpose, keeping the 4th in 79 * place. 80 */ 81 isc_safe_memwipe(buf1, 3); 82 memset(buf2, 0, 3); 83 84 assert_int_equal(memcmp(buf1, buf2, sizeof(buf1)), 0); 85 } 86 } 87 88 ISC_TEST_LIST_START 89 ISC_TEST_ENTRY(isc_safe_memequal) 90 ISC_TEST_ENTRY(isc_safe_memwipe) 91 92 ISC_TEST_LIST_END 93 94 ISC_TEST_MAIN 95