File: stress.c

package info (click to toggle)
libchewing 0.10.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 8,040 kB
  • sloc: ansic: 7,031; python: 190; sh: 127; makefile: 44
file content (266 lines) | stat: -rw-r--r-- 9,098 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/**
 * stress.c
 *
 * Copyright (c) 2015
 *      libchewing Core Team.
 *
 * See the file "COPYING" for information on usage and redistribution
 * of this file.
 */

#include "chewing.h"
#include "testhelper.h"

#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <assert.h>
#include <fcntl.h>

#ifndef _MSC_VER
#include <unistd.h>
#else
#include <io.h>
#endif

static int selKey_define[11] = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 0 }; /* Default */

static int normal_keys[] = {
    // all isprint()
    '~', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+',
    '`', '1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '-', '=',
    'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', '{', '}', '|',
    'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\\',
    'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', ':', '"',
    'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', '\'',
    'Z', 'X', 'C', 'V', 'B', 'N', 'M', '<', '>', '?',
    'z', 'x', 'c', 'v', 'b', 'n', 'm', ',', '.', '/',
};

static int input_fd = -1;

static int random256()
{
    return rand() % 256;
}

void commit_string(ChewingContext *ctx)
{
    char *s;

    if (chewing_commit_Check(ctx)) {
        s = chewing_commit_String(ctx);
        free(s);
    }
}

int read_from_fd()
{
    unsigned char c;
    int len = read(input_fd, &c, 1);
    if (len <= 0)
        return EOF;
    return c;
}

static void verbose_logger(void *data, int level, const char *fmt, ...)
{
    va_list ap;

    va_start(ap, fmt);
    vprintf(fmt, ap);
    va_end(ap);
    printf("\r");
    fflush(stdout);
}

int main(int argc, char *argv[])
{
    int i;
    int flag_random_init = 0;
    int flag_random_extra = 0;
    int flag_loop = -1;
    int flag_verbose = 0;
    int (*get_input)() = &random256;
    void (*logger) (void *data, int level, const char *fmt, ...) = NULL;
    char *chewing_sys_path;
    char *userphrase_path;
    int num_special_key = 0;
    int num_normal_key = sizeof(normal_keys) / sizeof(normal_keys[0]);
    TestKeyEntry *key_entry;

    for (i = 1; i < argc; i++) {
        if (strcmp(argv[i], "-init") == 0)
            flag_random_init = 1;
        else if (strcmp(argv[i], "-extra") == 0)
            flag_random_extra = 1;
        else if (strcmp(argv[i], "-verbose") == 0) {
            flag_verbose = 1;
            logger = verbose_logger;
        } else if (strcmp(argv[i], "-loop") == 0 && argv[i + 1])
            flag_loop = atoi(argv[++i]);
        else if (strcmp(argv[i], "-stdin") == 0) {
            input_fd = 0;
            get_input = &read_from_fd;
        } else if (strcmp(argv[i], "-file") == 0 && argv[i + 1]) {
            input_fd = open(argv[i + 1], O_RDONLY);
            if (input_fd < 0) {
                fprintf(stderr, "failed to open '%s'\n", argv[i + 1]);
                exit(1);
            }
            get_input = &read_from_fd;
            i++;
        } else {
            printf("Usage: %s [-init] [-extra] [-loop N] [-stdin]\n", argv[0]);
            printf("\t-init           Random initial configuration\n");
            printf("\t-extra          Random change all configurations during input.\n");
            printf("\t                This is usually unexpected.\n");
            printf("\t-stdin          Get random input from stdin\n");
            printf("\t-loop N         How many iterations to test (default infinite=-1)\n");
            printf("\t-verbose        Verbose\n");
            exit(1);
        }
    }

    /* Initialize for testing */
    for (key_entry = chewing_test_special_keys; key_entry->key; key_entry++)
        num_special_key++;

    /* Initialize libchewing */
    chewing_sys_path = getenv("CHEWING_PATH");
    if (!chewing_sys_path)
        chewing_sys_path = CHEWING_DATA_PREFIX;

    /* for the sake of testing, we should not change existing hash data */
    userphrase_path = get_test_userphrase_path();

    for (i = 0; i != flag_loop; i++) {
        ChewingContext *ctx;
        clean_userphrase();
        ctx = chewing_new2(chewing_sys_path, userphrase_path, logger, NULL);

        /* typical configuration */
        chewing_set_KBType(ctx, chewing_KBStr2Num("KB_DEFAULT"));
        chewing_set_candPerPage(ctx, 9);
        chewing_set_maxChiSymbolLen(ctx, 16);
        chewing_set_addPhraseDirection(ctx, 1);
        chewing_set_selKey(ctx, selKey_define, 10);
        chewing_set_spaceAsSelection(ctx, 1);

        if (flag_random_init) {
            chewing_set_KBType(ctx, get_input());
            chewing_set_candPerPage(ctx, get_input());
            chewing_set_maxChiSymbolLen(ctx, get_input());
            chewing_set_addPhraseDirection(ctx, get_input());
            chewing_set_selKey(ctx, selKey_define, get_input() % 11);
            chewing_set_spaceAsSelection(ctx, get_input());
            chewing_set_escCleanAllBuf(ctx, get_input());
            chewing_set_autoShiftCur(ctx, get_input());
            chewing_set_easySymbolInput(ctx, get_input());
            chewing_set_phraseChoiceRearward(ctx, get_input());
        }

        while (1) {
            /* Random value: [0, max_key) for keys, [max_key, 0xff] for
             * configurations. Use a fixed range here because I don't want the
             * meaning of input changed a lot frequently if we add more keys in
             * the future. */
            const int max_key = 192;  /* arbitrary number */
            int v = get_input();
            if (v == EOF)
                break;
            assert(max_key >= (num_special_key + num_normal_key));
            if (v >= max_key) {
                const int typical = 2;
                int handled = 1;
                v = v - max_key;
                if (flag_random_extra || v < typical) {
                    switch (v) {
                    /* typical configurations may be changed during input */
                    case 0:
                        chewing_set_ChiEngMode(ctx, get_input());
                        break;
                    case 1:
                        chewing_set_ShapeMode(ctx, get_input());
                        break;
                    /* usually not changed during input */
                    case 2:
                        chewing_set_KBType(ctx, get_input());
                        break;
                    case 3:
                        chewing_set_candPerPage(ctx, get_input());
                        break;
                    case 4:
                        chewing_set_maxChiSymbolLen(ctx, get_input());
                        break;
                    case 5:
                        chewing_set_addPhraseDirection(ctx, get_input());
                        break;
                    case 6:
                        chewing_set_selKey(ctx, selKey_define, get_input() % 11);
                        break;
                    case 7:
                        chewing_set_spaceAsSelection(ctx, get_input());
                        break;
                    case 8:
                        chewing_set_escCleanAllBuf(ctx, get_input());
                        break;
                    case 9:
                        chewing_set_autoShiftCur(ctx, get_input());
                        break;
                    case 10:
                        chewing_set_easySymbolInput(ctx, get_input());
                        break;
                    case 11:
                        chewing_set_phraseChoiceRearward(ctx, get_input());
                        break;
                    default:
                        handled = 0;
                        break;
                    }
                } else {
                    handled = 0;
                }
                if (!handled)
                    break;
            } else {
                if (0 <= v && v < num_special_key) {
                    int key = chewing_test_special_keys[v].key;
                    if (flag_verbose) {
                        printf("\r\n------------------------------\r\n");
                        printf("keystroke: %s\r\n", chewing_test_special_keys[v].str);
                        fflush(stdout);
                    }
                    type_single_keystroke(ctx, key);
                } else if (num_special_key <= v && v < num_special_key + num_normal_key) {
                    int key = normal_keys[v - num_special_key];
                    if (flag_verbose) {
                        printf("\r\n------------------------------\r\n");
                        printf("keystroke: [%c]\r\n", key);
                        fflush(stdout);
                    }
                    type_single_keystroke(ctx, key);
                } else {
                    break;
                }
            }
            commit_string(ctx);
        }
        if (flag_verbose)
            printf("\r\n");
        chewing_delete(ctx);

#if !defined(_WIN32) && !defined(_WIN64) && !defined(_WIN32_WCE)
        if (getenv("AFL_PERSISTENT"))
            raise(SIGSTOP);
#endif
    }
    clean_userphrase();

    if (input_fd > 0)
        close(input_fd);

    return 0;
}