1 /*
2  * Copyright (c) 2022, Commonwealth Scientific and Industrial Research
3  * Organisation (CSIRO) ABN 41 687 119 230.
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <zephyr/ztest.h>
9 #include <zephyr/arch/common/semihost.h>
10 
ZTEST(semihost,test_file_ops)11 ZTEST(semihost, test_file_ops)
12 {
13 	const char *test_file = "./test.bin";
14 	uint8_t w_buffer[16] = { 1, 2, 3, 4, 5 };
15 	uint8_t r_buffer[16];
16 	long read, fd;
17 
18 	/* Open in write mode */
19 	fd = semihost_open(test_file, SEMIHOST_OPEN_WB);
20 	zassert_true(fd > 0, "Bad handle (%d)", fd);
21 	zassert_equal(semihost_flen(fd), 0, "File not empty");
22 
23 	/* Write some data */
24 	zassert_equal(semihost_write(fd, w_buffer, sizeof(w_buffer)), 0, "Write failed");
25 	zassert_equal(semihost_flen(fd), sizeof(w_buffer), "Size not updated");
26 	zassert_equal(semihost_write(fd, w_buffer, sizeof(w_buffer)), 0, "Write failed");
27 	zassert_equal(semihost_flen(fd), 2 * sizeof(w_buffer), "Size not updated");
28 
29 	/* Reading should fail in this mode */
30 	read = semihost_read(fd, r_buffer, sizeof(r_buffer));
31 	zassert_equal(read, -EIO, "Read from write-only file");
32 
33 	/* Close the file */
34 	zassert_equal(semihost_close(fd), 0, "Close failed");
35 
36 	/* Open the same file again for reading */
37 	fd = semihost_open(test_file, SEMIHOST_OPEN_RB);
38 	zassert_true(fd > 0, "Bad handle (%d)", fd);
39 	zassert_equal(semihost_flen(fd), 2 * sizeof(w_buffer), "Data not preserved");
40 
41 	/* Check reading data */
42 	read = semihost_read(fd, r_buffer, sizeof(r_buffer));
43 	zassert_equal(read, sizeof(r_buffer), "Read failed %d", read);
44 	zassert_mem_equal(r_buffer, w_buffer, sizeof(r_buffer), "Data not read");
45 	read = semihost_read(fd, r_buffer, sizeof(r_buffer));
46 	zassert_equal(read, sizeof(r_buffer), "Read failed");
47 	zassert_mem_equal(r_buffer, w_buffer, sizeof(r_buffer), "Data not read");
48 
49 	/* Read past end of file */
50 	read = semihost_read(fd, r_buffer, sizeof(r_buffer));
51 	zassert_equal(read, -EIO, "Read past end of file");
52 
53 	/* Seek to file offset */
54 	zassert_equal(semihost_seek(fd, 1), 0, "Seek failed");
55 
56 	/* Read from offset */
57 	read = semihost_read(fd, r_buffer, sizeof(r_buffer) - 1);
58 	zassert_equal(read, sizeof(r_buffer) - 1, "Read failed");
59 	zassert_mem_equal(r_buffer, w_buffer + 1, sizeof(r_buffer) - 1, "Data not read");
60 
61 	/* Close the file */
62 	zassert_equal(semihost_close(fd), 0, "Close failed");
63 
64 	/* Opening again in write mode should erase the file */
65 	fd = semihost_open(test_file, SEMIHOST_OPEN_WB);
66 	zassert_true(fd > 0, "Bad handle (%d)", fd);
67 	zassert_equal(semihost_flen(fd), 0, "File not empty");
68 	zassert_equal(semihost_close(fd), 0, "Close failed");
69 }
70 
71 ZTEST_SUITE(semihost, NULL, NULL, NULL, NULL, NULL);
72