1 #include <stdint.h>
2 #include <string.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <gc.h>
6 #include "wc.h"
7 #include "wtf.h"
8
get_null_terminated(const uint8_t * data,size_t size)9 char *get_null_terminated(const uint8_t *data, size_t size) {
10 char *new_str = (char *)malloc(size+1);
11 if (new_str == NULL){
12 exit(1);
13 }
14 memcpy(new_str, data, size);
15 new_str[size] = '\0';
16 return new_str;
17 }
18
die_oom(size_t bytes)19 static void *die_oom(size_t bytes) {
20 fprintf(stderr, "Out of memory: %lu bytes unavailable!\n", (unsigned long)bytes);
21 exit(1);
22 }
23
LLVMFuzzerTestOneInput(const uint8_t * data,size_t size)24 int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size){
25 static int init_done = 0;
26
27 if (!init_done) {
28 setenv("GC_LARGE_ALLOC_WARN_INTERVAL", "30000", 1);
29 GC_INIT();
30 #if (GC_VERSION_MAJOR>7) || ((GC_VERSION_MAJOR==7) && (GC_VERSION_MINOR>=2))
31 GC_set_oom_fn(die_oom);
32 #else
33 GC_oom_fn = die_oom;
34 #endif
35 #ifdef USE_M17N
36 #ifdef USE_UNICODE
37 wtf_init(WC_CES_UTF_8, WC_CES_UTF_8);
38 #else
39 wtf_init(WC_CES_EUC_JP, WC_CES_EUC_JP);
40 #endif
41 #endif
42 init_done = 1;
43 }
44
45 if (size < 30) {
46 return 0;
47 }
48
49 GC_disable();
50
51 char *new_str1 = get_null_terminated(data, 20);
52 data += 20; size -= 20;
53 char *new_str2 = get_null_terminated(data, size);
54
55 wc_ces old, from, to;
56 from = wc_guess_charset_short(new_str1,0);
57 to = wc_guess_charset_short(new_str2, 0);
58
59 char filename[256];
60 sprintf(filename, "/tmp/libfuzzer.%d", getpid());
61
62 FILE *fp = fopen(filename, "wb");
63 if (fp) {
64 fwrite(data, size, 1, fp);
65 fclose(fp);
66 }
67
68 FILE *f = fopen(filename, "r");
69 if (f) {
70 Str s = Strfgetall(f);
71 wc_Str_conv_with_detect(s, &from, from, to);
72 if (s != NULL) {
73 Strfree(s);
74 }
75 fclose(f);
76 }
77
78 unlink(filename);
79
80 free(new_str1);
81 free(new_str2);
82
83 GC_enable();
84 GC_gcollect();
85
86 return 0;
87 }
88