xref: /freebsd/lib/libdiff/tests/libdiff_test.c (revision 7affbeeab1c99685012df0d72df2d7a87e09e472)
1  /*-
2   * Copyright (c) 2024 Klara, Inc.
3   *
4   * SPDX-License-Identifier: BSD-2-Clause
5   */
6  
7  #include <sys/types.h>
8  #include <sys/mman.h>
9  
10  #include <assert.h>
11  #include <errno.h>
12  #include <stdint.h>
13  #include <stdio.h>
14  #include <string.h>
15  #include <unistd.h>
16  
17  #include <arraylist.h>
18  #include <diff_main.h>
19  
20  #include <atf-c.h>
21  
22  ATF_TC_WITH_CLEANUP(diff_atomize_truncated);
23  ATF_TC_HEAD(diff_atomize_truncated, tc)
24  {
25  	atf_tc_set_md_var(tc, "descr", "Verify that the atomizer "
26  	    "does not crash when an input file is truncated");
27  }
28  ATF_TC_BODY(diff_atomize_truncated, tc)
29  {
30  	char line[128];
31  	struct diff_config cfg = { .atomize_func = diff_atomize_text_by_line };
32  	struct diff_data d = { };
33  	const char *fn = atf_tc_get_ident(tc);
34  	FILE *f;
35  	unsigned char *p;
36  	size_t size = 65536;
37  
38  	ATF_REQUIRE((f = fopen(fn, "w+")) != NULL);
39  	line[sizeof(line) - 1] = '\n';
40  	for (unsigned int i = 0; i <= size / sizeof(line); i++) {
41  		memset(line, 'a' + i % 26, sizeof(line) - 1);
42  		ATF_REQUIRE(fwrite(line, sizeof(line), 1, f) == 1);
43  	}
44  	ATF_REQUIRE(fsync(fileno(f)) == 0);
45  	rewind(f);
46  	ATF_REQUIRE(truncate(fn, size / 2) == 0);
47  	ATF_REQUIRE((p = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fileno(f), 0)) != MAP_FAILED);
48  	ATF_REQUIRE(diff_atomize_file(&d, &cfg, f, p, size, 0) == 0);
49  	ATF_REQUIRE((size_t)d.len <= size / 2);
50  	ATF_REQUIRE((size_t)d.len >= size / 2 - sizeof(line));
51  	ATF_REQUIRE(d.atomizer_flags & DIFF_ATOMIZER_FILE_TRUNCATED);
52  }
53  ATF_TC_CLEANUP(diff_atomize_truncated, tc)
54  {
55  	unlink(atf_tc_get_ident(tc));
56  }
57  
58  ATF_TP_ADD_TCS(tp)
59  {
60  	ATF_TP_ADD_TC(tp, diff_atomize_truncated);
61  	return atf_no_error();
62  }
63