xref: /aosp_15_r20/external/vboot_reference/tests/vb21_host_misc_tests.c (revision 8617a60d3594060b7ecbd21bc622a7c14f3cf2bc)
1 /* Copyright 2014 The ChromiumOS Authors
2  * Use of this source code is governed by a BSD-style license that can be
3  * found in the LICENSE file.
4  *
5  * Tests for host misc library vboot2 functions
6  */
7 
8 #include <stdio.h>
9 #include <unistd.h>
10 
11 #include "2common.h"
12 #include "2sysincludes.h"
13 #include "common/tests.h"
14 #include "host_common.h"
15 #include "host_common21.h"
16 #include "host_misc.h"
17 
misc_tests(void)18 static void misc_tests(void)
19 {
20 	TEST_EQ(roundup32(0), 0, "roundup32(0)");
21 	TEST_EQ(roundup32(15), 16, "roundup32(15)");
22 	TEST_EQ(roundup32(16), 16, "roundup32(16)");
23 
24 	TEST_EQ(vb2_desc_size(NULL), 0, "desc size null");
25 	TEST_EQ(vb2_desc_size(""), 0, "desc size empty");
26 	TEST_EQ(vb2_desc_size("foo"), 4, "desc size 'foo'");
27 	TEST_EQ(vb2_desc_size("foob"), 8, "desc size 'foob'");
28 }
29 
file_tests(const char * temp_dir)30 static void file_tests(const char *temp_dir)
31 {
32 	char *testfile;
33 	const uint8_t test_data[] = "Some test data";
34 	uint8_t *read_data;
35 	uint32_t read_size;
36 
37 	uint8_t cbuf[sizeof(struct vb21_struct_common) + 12];
38 	struct vb21_struct_common *c = (struct vb21_struct_common *)cbuf;
39 
40 	xasprintf(&testfile, "%s/file_tests.dat", temp_dir);
41 
42 	unlink(testfile);
43 
44 	TEST_EQ(vb2_read_file(testfile, &read_data, &read_size),
45 		VB2_ERROR_READ_FILE_OPEN, "vb2_read_file() missing");
46 	TEST_EQ(vb2_write_file("no/such/dir", test_data, sizeof(test_data)),
47 		VB2_ERROR_WRITE_FILE_OPEN, "vb2_write_file() open");
48 
49 	TEST_SUCC(vb2_write_file(testfile, test_data, sizeof(test_data)),
50 		  "vb2_write_file() good");
51 	TEST_SUCC(vb2_read_file(testfile, &read_data, &read_size),
52 		  "vb2_read_file() good");
53 	TEST_EQ(read_size, sizeof(test_data), "  data size");
54 	TEST_EQ(memcmp(read_data, test_data, read_size), 0, "  data");
55 	free(read_data);
56 	unlink(testfile);
57 
58 	memset(cbuf, 0, sizeof(cbuf));
59 	c->fixed_size = sizeof(*c);
60 	c->total_size = sizeof(cbuf);
61 	c->magic = 0x1234;
62 	cbuf[sizeof(cbuf) - 1] = 0xed;  /* Some non-zero data at the end */
63 	TEST_SUCC(vb21_write_object(testfile, c), "vb2_write_object() good");
64 	TEST_SUCC(vb2_read_file(testfile, &read_data, &read_size),
65 		  "vb2_read_file() object");
66 	TEST_EQ(read_size, c->total_size, "  data size");
67 	/* Compare the entire buffer, including the non-zero data at the end */
68 	TEST_EQ(memcmp(read_data, c, read_size), 0, "  data");
69 	free(read_data);
70 	unlink(testfile);
71 }
72 
main(int argc,char * argv[])73 int main(int argc, char* argv[])
74 {
75 	if (argc != 2) {
76 		fprintf(stderr, "Usage: %s <temp_dir>\n", argv[0]);
77 		return -1;
78 	}
79 	const char *temp_dir = argv[1];
80 
81 	misc_tests();
82 	file_tests(temp_dir);
83 
84 	return gTestSuccess ? 0 : 255;
85 }
86