summaryrefslogtreecommitdiffstats
path: root/modules/policy/lua-aho-corasick/ac_slow.cxx
blob: cb3957a04b0a1594ffbe33866b262840e48adb05 (plain)
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
#include <ctype.h>
#include <strings.h> // for bzero
#include <algorithm>
#include "ac_slow.hpp"
#include "ac.h"

//////////////////////////////////////////////////////////////////////////
//
//      Implementation of AhoCorasick_Slow
//
//////////////////////////////////////////////////////////////////////////
//
ACS_Constructor::ACS_Constructor() : _next_node_id(1) {
    _root = new_state();
    _root_char = new InputTy[256];
    bzero((void*)_root_char, 256);

#ifdef VERIFY
    _pattern_buf = 0;
#endif
}

ACS_Constructor::~ACS_Constructor() {
    for (std::vector<ACS_State* >::iterator i =  _all_states.begin(),
            e = _all_states.end(); i != e; i++) {
        delete *i;
    }
    _all_states.clear();
    delete[] _root_char;

#ifdef VERIFY
    delete[] _pattern_buf;
#endif
}

ACS_State*
ACS_Constructor::new_state() {
    ACS_State* t = new ACS_State(_next_node_id++);
    _all_states.push_back(t);
    return t;
}

void
ACS_Constructor::Add_Pattern(const char* str, unsigned int str_len,
                             int pattern_idx) {
    ACS_State* state = _root;
    for (unsigned int i = 0; i < str_len; i++) {
        const char c = str[i];
        ACS_State* new_s = state->Get_Goto(c);
        if (!new_s) {
            new_s = new_state();
            new_s->_depth = state->_depth + 1;
            state->Set_Goto(c, new_s);
        }
        state = new_s;
    }
    state->_is_terminal = true;
    state->set_Pattern_Idx(pattern_idx);
}

void
ACS_Constructor::Propagate_faillink() {
    ACS_State* r = _root;
    std::vector<ACS_State*> wl;

    const ACS_Goto_Map& m = r->Get_Goto_Map();
    for (ACS_Goto_Map::const_iterator i = m.begin(), e = m.end(); i != e; i++) {
        ACS_State* s = i->second;
        s->_fail_link = r;
        wl.push_back(s);
    }

    // For any input c, make sure "goto(root, c)" is valid, which make the
    // fail-link propagation lot easier.
    ACS_Goto_Map goto_save = r->_goto_map;
    for (uint32 i = 0; i <= 255; i++) {
        ACS_State* s = r->Get_Goto(i);
        if (!s) r->Set_Goto(i, r);
    }

    for (uint32 i = 0; i < wl.size(); i++) {
        ACS_State* s = wl[i];
        ACS_State* fl = s->_fail_link;

        const ACS_Goto_Map& tran_map = s->Get_Goto_Map();

        for (ACS_Goto_Map::const_iterator ii = tran_map.begin(),
                ee = tran_map.end(); ii != ee; ii++) {
            InputTy c = ii->first;
            ACS_State *tran = ii->second;

            ACS_State* tran_fl = 0;
            for (ACS_State* fl_walk = fl; ;) {
                if (ACS_State* t = fl_walk->Get_Goto(c)) {
                    tran_fl = t;
                    break;
                } else {
                    fl_walk = fl_walk->Get_FailLink();
                }
            }

            tran->_fail_link = tran_fl;
            wl.push_back(tran);
        }
    }

    // Remove "goto(root, c) == root" transitions
    r->_goto_map = goto_save;
}

void
ACS_Constructor::Construct(const char** strv, unsigned int* strlenv,
                           uint32 strnum) {
    Save_Patterns(strv, strlenv, strnum);

    for (uint32 i = 0; i < strnum; i++) {
        Add_Pattern(strv[i], strlenv[i], i);
    }

    Propagate_faillink();
    unsigned char* p = _root_char;

    const ACS_Goto_Map& m = _root->Get_Goto_Map();
    for (ACS_Goto_Map::const_iterator i = m.begin(), e = m.end();
            i != e; i++) {
        p[i->first] = 1;
    }
}

Match_Result
ACS_Constructor::MatchHelper(const char *str, uint32 len) const {
    const ACS_State* root = _root;
    const ACS_State* state = root;

    uint32 idx = 0;
    while (idx < len) {
        InputTy c = str[idx];
        idx++;
        if (_root_char[c]) {
            state = root->Get_Goto(c);
            break;
        }
    }

    if (unlikely(state->is_Terminal())) {
        // This could happen if the one of the pattern has only one char!
        uint32 pos = idx - 1;
        Match_Result r(pos - state->Get_Depth() + 1, pos,
                       state->get_Pattern_Idx());
        return r;
    }

    while (idx < len) {
        InputTy c = str[idx];
        ACS_State* gs = state->Get_Goto(c);

        if (!gs) {
            ACS_State* fl = state->Get_FailLink();
            if (fl == root) {
                while (idx < len) {
                    InputTy c = str[idx];
                    idx++;
                    if (_root_char[c]) {
                        state = root->Get_Goto(c);
                        break;
                    }
                }
            } else {
                state = fl;
            }
        } else {
            idx ++;
            state = gs;
        }

        if (state->is_Terminal()) {
            uint32 pos = idx - 1;
            Match_Result r = Match_Result(pos - state->Get_Depth() + 1, pos,
                                          state->get_Pattern_Idx());
            return r;
        }
    }

    return Match_Result(-1, -1, -1);
}

#ifdef DEBUG
void
ACS_Constructor::dump_text(const char* txtfile) const {
    FILE* f = fopen(txtfile, "w+");
    for (std::vector<ACS_State*>::const_iterator i = _all_states.begin(),
            e = _all_states.end(); i != e; i++) {
        ACS_State* s = *i;

        fprintf(f, "S%d goto:{", s->Get_ID());
        const ACS_Goto_Map& goto_func = s->Get_Goto_Map();

        for (ACS_Goto_Map::const_iterator i = goto_func.begin(), e = goto_func.end();
              i != e; i++) {
            InputTy input = i->first;
            ACS_State* tran = i->second;
            if (isprint(input))
                fprintf(f, "'%c' -> S:%d,", input, tran->Get_ID());
            else
                fprintf(f, "%#x -> S:%d,", input, tran->Get_ID());
        }
        fprintf(f, "} ");

        if (s->_fail_link) {
            fprintf(f, ", fail=S:%d", s->_fail_link->Get_ID());
        }

        if (s->_is_terminal) {
            fprintf(f, ", terminal");
        }

        fprintf(f, "\n");
    }
    fclose(f);
}

void
ACS_Constructor::dump_dot(const char *dotfile) const {
    FILE* f = fopen(dotfile, "w+");
    const char* indent = "  ";

    fprintf(f, "digraph G {\n");

    // Emit node information
    fprintf(f, "%s%d [style=filled];\n", indent, _root->Get_ID());
    for (std::vector<ACS_State*>::const_iterator i = _all_states.begin(),
            e = _all_states.end(); i != e; i++) {
        ACS_State *s = *i;
        if (s->_is_terminal) {
            fprintf(f, "%s%d [shape=doublecircle];\n", indent, s->Get_ID());
        }
    }
    fprintf(f, "\n");

    // Emit edge information
    for (std::vector<ACS_State*>::const_iterator i = _all_states.begin(),
            e = _all_states.end(); i != e; i++) {
        ACS_State* s = *i;
        uint32 id = s->Get_ID();

        const ACS_Goto_Map& m = s->Get_Goto_Map();
        for (ACS_Goto_Map::const_iterator ii = m.begin(), ee = m.end();
             ii != ee; ii++) {
            InputTy input = ii->first;
            ACS_State* tran = ii->second;
            if (isalnum(input))
                fprintf(f, "%s%d -> %d [label=%c];\n",
                        indent, id, tran->Get_ID(), input);
            else
                fprintf(f, "%s%d -> %d [label=\"%#x\"];\n",
                        indent, id, tran->Get_ID(), input);

        }

        // Emit fail-link
        ACS_State* fl = s->Get_FailLink();
        if (fl && fl != _root) {
            fprintf(f, "%s%d -> %d [style=dotted, color=red]; \n",
                    indent, id, fl->Get_ID());
        }
    }
    fprintf(f, "}\n");
    fclose(f);
}
#endif

#ifdef VERIFY
void
ACS_Constructor::Verify_Result(const char* subject, const Match_Result* r)
    const {
    if (r->begin >= 0) {
        unsigned len = r->end - r->begin + 1;
        int ptn_idx = r->pattern_idx;

        ASSERT(ptn_idx >= 0 &&
               len == get_ith_Pattern_Len(ptn_idx) &&
               memcmp(subject + r->begin, get_ith_Pattern(ptn_idx), len) == 0);
    }
}

void
ACS_Constructor::Save_Patterns(const char** strv, unsigned int* strlenv,
                               int pattern_num) {
    // calculate the total size needed to save all patterns.
    //
    int buf_size = 0;
    for (int i = 0; i < pattern_num; i++) { buf_size += strlenv[i]; }

    // HINT: patterns are delimited by '\0' in order to ease debugging.
    buf_size += pattern_num;
    ASSERT(_pattern_buf == 0);
    _pattern_buf = new char[buf_size + 1];
    #define MAGIC_NUM 0x5a
    _pattern_buf[buf_size] = MAGIC_NUM;

    int ofst = 0;
    _pattern_lens.resize(pattern_num);
    _pattern_vect.resize(pattern_num);
    for (int i = 0; i < pattern_num; i++) {
        int l = strlenv[i];
        _pattern_lens[i] = l;
        _pattern_vect[i] = _pattern_buf + ofst;

        memcpy(_pattern_buf + ofst, strv[i], l);
        ofst += l;
        _pattern_buf[ofst++] = '\0';
    }

    ASSERT(_pattern_buf[buf_size] == MAGIC_NUM);
    #undef MAGIC_NUM
}

#endif