]> wimlib.net Git - wimlib/blob - tools/libFuzzer/encoding/fuzz.c
mount_image.c: add fallback definitions of RENAME_* constants
[wimlib] / tools / libFuzzer / encoding / fuzz.c
1 #include "../fuzzer.h"
2
3 /*
4  * "UTF-8" (actually "WTF-8") to UTF-16LE (actually "arbitrary sequence of
5  * 16-bit wchars") and back again should be lossless, unless the initial string
6  * isn't valid WTF-8, in which case WIMLIB_ERR_INVALID_UTF8_STRING is expected.
7  */
8 static void
9 fuzz_utf8_roundtrip(const u8 *in, size_t insize)
10 {
11         utf16lechar *utf16;
12         size_t utf16_size;
13         int ret;
14         char *result;
15         size_t result_size;
16
17         ret = wimlib_utf8_to_utf16le((const char *)in, insize,
18                                      &utf16, &utf16_size);
19         if (ret) {
20                 assert(ret == WIMLIB_ERR_INVALID_UTF8_STRING);
21                 return;
22         }
23         assert(ret == 0);
24         ret = wimlib_utf16le_to_utf8(utf16, utf16_size, &result, &result_size);
25         assert(ret == 0);
26         assert(result_size == insize);
27         assert(memcmp(result, in, insize) == 0);
28         free(result);
29         free(utf16);
30 }
31
32 /*
33  * "UTF-16LE" (actually "arbitrary sequence of 16-bit wchars") to UTF-8
34  * (actually "WTF-8") and back again should be lossless, unless the initial
35  * length isn't a multiple of 2 bytes, in which case
36  * WIMLIB_ERR_INVALID_UTF16_STRING is expected.
37  */
38 static void
39 fuzz_utf16_roundtrip(const u8 *in, size_t insize)
40 {
41         utf16lechar *in_aligned = malloc(insize);
42         char *utf8;
43         size_t utf8_size;
44         int ret;
45         utf16lechar *result;
46         size_t result_size;
47
48         memcpy(in_aligned, in, insize);
49         ret = wimlib_utf16le_to_utf8(in_aligned, insize, &utf8, &utf8_size);
50         if (insize % 2) {
51                 assert(ret == WIMLIB_ERR_INVALID_UTF16_STRING);
52                 free(in_aligned);
53                 return;
54         }
55         assert(ret == 0);
56         ret = wimlib_utf8_to_utf16le(utf8, utf8_size, &result, &result_size);
57         assert(ret == 0);
58         assert(result_size == insize);
59         assert(memcmp(result, in, insize) == 0);
60         free(result);
61         free(utf8);
62         free(in_aligned);
63 }
64
65 /* Fuzz character encoding conversion. */
66 int LLVMFuzzerTestOneInput(const u8 *in, size_t insize)
67 {
68         int which;
69
70         if (insize < 1)
71                 return 0;
72         which = *in++;
73         insize--;
74         switch (which) {
75         case 0:
76                 fuzz_utf8_roundtrip(in, insize);
77                 break;
78         case 1:
79                 fuzz_utf16_roundtrip(in, insize);
80                 break;
81         }
82         return 0;
83 }