Coverage Report

Created: 2026-12-04 07:08

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/yara/libyara/re.c
Line
Count
Source
1
/*
2
Copyright (c) 2013. The YARA Authors. All Rights Reserved.
3
4
Redistribution and use in source and binary forms, with or without modification,
5
are permitted provided that the following conditions are met:
6
7
1. Redistributions of source code must retain the above copyright notice, this
8
list of conditions and the following disclaimer.
9
10
2. Redistributions in binary form must reproduce the above copyright notice,
11
this list of conditions and the following disclaimer in the documentation and/or
12
other materials provided with the distribution.
13
14
3. Neither the name of the copyright holder nor the names of its contributors
15
may be used to endorse or promote products derived from this software without
16
specific prior written permission.
17
18
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
22
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
25
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
*/
29
30
/*
31
32
This module implements a regular expressions engine based on Thompson's
33
algorithm as described by Russ Cox in http://swtch.com/~rsc/regexp/regexp2.html.
34
35
What the article names a "thread" has been named a "fiber" in this code, in
36
order to avoid confusion with operating system threads.
37
38
*/
39
40
#include <assert.h>
41
#include <string.h>
42
#include <yara/arena.h>
43
#include <yara/compiler.h>
44
#include <yara/error.h>
45
#include <yara/globals.h>
46
#include <yara/hex_lexer.h>
47
#include <yara/libyara.h>
48
#include <yara/limits.h>
49
#include <yara/mem.h>
50
#include <yara/re.h>
51
#include <yara/re_lexer.h>
52
#include <yara/strutils.h>
53
#include <yara/threading.h>
54
#include <yara/unaligned.h>
55
#include <yara/utils.h>
56
57
0
#define EMIT_BACKWARDS               0x01
58
0
#define EMIT_DONT_SET_FORWARDS_CODE  0x02
59
0
#define EMIT_DONT_SET_BACKWARDS_CODE 0x04
60
61
#ifndef INT16_MAX
62
#define INT16_MAX (32767)
63
#endif
64
65
typedef uint8_t RE_SPLIT_ID_TYPE;
66
67
// RE_REPEAT_ARGS and RE_REPEAT_ANY_ARGS are structures that are embedded in
68
// the regexp's instruction stream. As such, they are not always aligned to
69
// 8-byte boundaries, so they need to be "packed" structures in order to prevent
70
// issues due to unaligned memory accesses.
71
#pragma pack(push)
72
#pragma pack(1)
73
74
typedef struct _RE_REPEAT_ARGS
75
{
76
  uint16_t min;
77
  uint16_t max;
78
  int32_t offset;
79
80
} RE_REPEAT_ARGS;
81
82
typedef struct _RE_REPEAT_ANY_ARGS
83
{
84
  uint16_t min;
85
  uint16_t max;
86
87
} RE_REPEAT_ANY_ARGS;
88
89
#pragma pack(pop)
90
91
typedef struct _RE_EMIT_CONTEXT
92
{
93
  YR_ARENA* arena;
94
  RE_SPLIT_ID_TYPE next_split_id;
95
  yr_arena_off_t start_offset;
96
97
} RE_EMIT_CONTEXT;
98
99
0
#define CHAR_IN_CLASS(cls, chr) ((cls)[(chr) / 8] & 1 << ((chr) % 8))
100
101
static bool _yr_re_is_char_in_class(
102
    RE_CLASS* re_class,
103
    uint8_t chr,
104
    int case_insensitive)
105
0
{
106
0
  int result = CHAR_IN_CLASS(re_class->bitmap, chr);
107
108
0
  if (case_insensitive)
109
0
    result |= CHAR_IN_CLASS(re_class->bitmap, yr_altercase[chr]);
110
111
0
  if (re_class->negated)
112
0
    result = !result;
113
114
0
  return result;
115
0
}
116
117
static bool _yr_re_is_word_char(const uint8_t* input, uint8_t character_size)
118
0
{
119
0
  int result = ((yr_isalnum(input) || (*input) == '_'));
120
121
0
  if (character_size == 2)
122
0
    result = result && (*(input + 1) == 0);
123
124
0
  return result;
125
0
}
126
127
RE_NODE* yr_re_node_create(int type)
128
0
{
129
0
  RE_NODE* result = (RE_NODE*) yr_malloc(sizeof(RE_NODE));
130
131
0
  if (result != NULL)
132
0
  {
133
0
    result->type = type;
134
0
    result->children_head = NULL;
135
0
    result->children_tail = NULL;
136
0
    result->prev_sibling = NULL;
137
0
    result->next_sibling = NULL;
138
0
    result->greedy = true;
139
0
    result->forward_code_ref = YR_ARENA_NULL_REF;
140
0
    result->backward_code_ref = YR_ARENA_NULL_REF;
141
0
  }
142
143
0
  return result;
144
0
}
145
146
////////////////////////////////////////////////////////////////////////////////
147
// Destroys a regular expression AST node and all its descendants iteratively.
148
//
149
// Instead of recursing (which can overflow the C call stack on deeply nested
150
// ASTs), this flattens the subtree in-place into a FIFO queue linked through
151
// `next_sibling`, where `current` is the queue head and `tail` is the queue
152
// tail.
153
//
154
void yr_re_node_destroy(RE_NODE* node)
155
0
{
156
0
  RE_NODE* current = node;
157
0
  RE_NODE* tail = node;
158
0
  RE_NODE* next;
159
160
0
  if (node == NULL)
161
0
    return;
162
163
  // Initialize the queue with `node` as its only element. Clearing
164
  // `node->next_sibling` ensures we only destroy the subtree rooted at `node`
165
  // (and not any siblings `node` might have). If `node` has children, the
166
  // first iteration below will overwrite `node->next_sibling` (via `tail`) to
167
  // point to `node->children_head` before `current->next_sibling` is read.
168
0
  node->next_sibling = NULL;
169
170
0
  while (current != NULL)
171
0
  {
172
    // If the current node has children, append its entire child list
173
    // (`children_head` .. `children_tail`) to the end of the queue.
174
0
    if (current->children_head != NULL)
175
0
    {
176
0
      tail->next_sibling = current->children_head;
177
0
      tail = current->children_tail;
178
0
    }
179
180
0
    next = current->next_sibling;
181
182
0
    if (current->type == RE_NODE_CLASS)
183
0
      yr_free(current->re_class);
184
185
0
    yr_free(current);
186
0
    current = next;
187
0
  }
188
0
}
189
190
////////////////////////////////////////////////////////////////////////////////
191
// Appends a node to the end of the children list.
192
//
193
void yr_re_node_append_child(RE_NODE* node, RE_NODE* child)
194
0
{
195
0
  if (node->children_head == NULL)
196
0
    node->children_head = child;
197
198
0
  if (node->children_tail != NULL)
199
0
    node->children_tail->next_sibling = child;
200
201
0
  child->prev_sibling = node->children_tail;
202
0
  node->children_tail = child;
203
0
}
204
205
////////////////////////////////////////////////////////////////////////////////
206
// Appends a node to the beginning of the children list.
207
//
208
void yr_re_node_prepend_child(RE_NODE* node, RE_NODE* child)
209
0
{
210
0
  child->next_sibling = node->children_head;
211
212
0
  if (node->children_head != NULL)
213
0
    node->children_head->prev_sibling = child;
214
215
0
  node->children_head = child;
216
217
0
  if (node->children_tail == NULL)
218
0
    node->children_tail = child;
219
0
}
220
221
int yr_re_ast_create(RE_AST** re_ast)
222
0
{
223
0
  *re_ast = (RE_AST*) yr_malloc(sizeof(RE_AST));
224
225
0
  if (*re_ast == NULL)
226
0
    return ERROR_INSUFFICIENT_MEMORY;
227
228
0
  (*re_ast)->flags = 0;
229
0
  (*re_ast)->levels = 0;
230
0
  (*re_ast)->root_node = NULL;
231
232
0
  return ERROR_SUCCESS;
233
0
}
234
235
void yr_re_ast_destroy(RE_AST* re_ast)
236
0
{
237
0
  if (re_ast->root_node != NULL)
238
0
    yr_re_node_destroy(re_ast->root_node);
239
240
0
  yr_free(re_ast);
241
0
}
242
243
////////////////////////////////////////////////////////////////////////////////
244
// Parses a regexp but don't emit its code. A further call to
245
// yr_re_ast_emit_code is required to get the code.
246
//
247
int yr_re_parse(
248
    const char* re_string,
249
    RE_AST** re_ast,
250
    RE_ERROR* error,
251
    int flags)
252
0
{
253
0
  return yr_parse_re_string(re_string, re_ast, error, flags);
254
0
}
255
256
////////////////////////////////////////////////////////////////////////////////
257
// Parses a hex string but don't emit its code. A further call to
258
// yr_re_ast_emit_code is required to get the code.
259
//
260
int yr_re_parse_hex(const char* hex_string, RE_AST** re_ast, RE_ERROR* error)
261
0
{
262
0
  return yr_parse_hex_string(hex_string, re_ast, error);
263
0
}
264
265
////////////////////////////////////////////////////////////////////////////////
266
// Parses the regexp and emit its code to the provided to the
267
// YR_RE_CODE_SECTION in the specified arena.
268
//
269
int yr_re_compile(
270
    const char* re_string,
271
    int flags,
272
    int parser_flags,
273
    YR_ARENA* arena,
274
    YR_ARENA_REF* ref,
275
    RE_ERROR* error)
276
0
{
277
0
  RE_AST* re_ast;
278
0
  RE _re;
279
0
  int result;
280
281
0
  result = yr_re_parse(re_string, &re_ast, error, parser_flags);
282
0
  if (result != ERROR_UNKNOWN_ESCAPE_SEQUENCE)
283
0
    FAIL_ON_ERROR(result);
284
285
0
  _re.flags = flags;
286
287
0
  FAIL_ON_ERROR_WITH_CLEANUP(
288
0
      yr_arena_write_data(arena, YR_RE_CODE_SECTION, &_re, sizeof(_re), ref),
289
0
      yr_re_ast_destroy(re_ast));
290
291
0
  FAIL_ON_ERROR_WITH_CLEANUP(
292
0
      yr_re_ast_emit_code(re_ast, arena, false), yr_re_ast_destroy(re_ast));
293
294
0
  yr_re_ast_destroy(re_ast);
295
296
0
  return result;
297
0
}
298
299
////////////////////////////////////////////////////////////////////////////////
300
// Verifies if the target string matches the pattern
301
//
302
// Args:
303
//    context: Scan context
304
//    re: A pointer to a compiled regexp
305
//    target: Target string
306
//
307
// Returns:
308
//    See return codes for yr_re_exec
309
//
310
int yr_re_match(YR_SCAN_CONTEXT* context, RE* re, const char* target)
311
0
{
312
0
  int result;
313
314
0
  yr_re_exec(
315
0
      context,
316
0
      re->code,
317
0
      (uint8_t*) target,
318
0
      strlen(target),
319
0
      0,
320
0
      re->flags | RE_FLAGS_SCAN,
321
0
      NULL,
322
0
      NULL,
323
0
      &result);
324
325
0
  return result;
326
0
}
327
328
////////////////////////////////////////////////////////////////////////////////
329
// Verifies if the provided regular expression is just a literal string
330
// like "abc", "12345", without any wildcard, operator, etc. In that case
331
// returns the string as a SIZED_STRING, or returns NULL if otherwise.
332
//
333
// The caller is responsible for deallocating the returned SIZED_STRING by
334
// calling yr_free.
335
//
336
SIZED_STRING* yr_re_ast_extract_literal(RE_AST* re_ast)
337
0
{
338
0
  SIZED_STRING* string;
339
0
  RE_NODE* child;
340
341
0
  int length = 0;
342
343
0
  if (re_ast->root_node->type == RE_NODE_LITERAL)
344
0
  {
345
0
    length = 1;
346
0
  }
347
0
  else if (re_ast->root_node->type == RE_NODE_CONCAT)
348
0
  {
349
0
    child = re_ast->root_node->children_tail;
350
351
0
    while (child != NULL && child->type == RE_NODE_LITERAL)
352
0
    {
353
0
      length++;
354
0
      child = child->prev_sibling;
355
0
    }
356
357
0
    if (child != NULL)
358
0
      return NULL;
359
0
  }
360
0
  else
361
0
  {
362
0
    return NULL;
363
0
  }
364
365
0
  string = (SIZED_STRING*) yr_malloc(sizeof(SIZED_STRING) + length);
366
367
0
  if (string == NULL)
368
0
    return NULL;
369
370
0
  string->length = length;
371
0
  string->flags = 0;
372
373
0
  if (re_ast->root_node->type == RE_NODE_LITERAL)
374
0
  {
375
0
    string->c_string[0] = re_ast->root_node->value;
376
0
  }
377
0
  else
378
0
  {
379
0
    child = re_ast->root_node->children_tail;
380
381
0
    while (child != NULL)
382
0
    {
383
0
      string->c_string[--length] = child->value;
384
0
      child = child->prev_sibling;
385
0
    }
386
0
  }
387
388
0
  string->c_string[string->length] = '\0';
389
390
0
  return string;
391
0
}
392
393
int _yr_re_node_has_unbounded_quantifier_for_dot(RE_NODE* re_node)
394
0
{
395
0
  RE_NODE* child;
396
397
0
  if ((re_node->type == RE_NODE_STAR || re_node->type == RE_NODE_PLUS) &&
398
0
      re_node->children_head->type == RE_NODE_ANY)
399
0
    return true;
400
401
0
  if (re_node->type == RE_NODE_RANGE_ANY && re_node->end == RE_MAX_RANGE)
402
0
    return true;
403
404
0
  if (re_node->type == RE_NODE_CONCAT)
405
0
  {
406
0
    child = re_node->children_tail;
407
408
0
    while (child != NULL)
409
0
    {
410
0
      if (_yr_re_node_has_unbounded_quantifier_for_dot(child))
411
0
        return true;
412
413
0
      child = child->prev_sibling;
414
0
    }
415
0
  }
416
417
0
  return false;
418
0
}
419
420
////////////////////////////////////////////////////////////////////////////////
421
// Detects the use of .*, .+ or .{x,} in a regexp. The use of wildcards with
422
// quantifiers that don't have a reasonably small upper bound causes a
423
// performance penalty. This function detects such cases in order to warn the
424
// user about this.
425
//
426
int yr_re_ast_has_unbounded_quantifier_for_dot(RE_AST* re_ast)
427
0
{
428
0
  return _yr_re_node_has_unbounded_quantifier_for_dot(re_ast->root_node);
429
0
}
430
431
////////////////////////////////////////////////////////////////////////////////
432
// In some cases splitting a regular expression (or hex string) in two parts is
433
// convenient for increasing performance. This happens when the pattern contains
434
// a large gap (a.k.a jump), for example: { 01 02 03 [0-999] 04 05 06 }
435
// In this case the string is splitted in { 01 02 03 } and { 04 05 06 } where
436
// the latter is chained to the former. This means that { 01 02 03 } and
437
// { 04 05 06 } are handled as individual strings, and when both of them are
438
// found, YARA verifies if the distance between the matches complies with the
439
// [0-999] restriction.
440
//
441
// This function traverses a regexp's AST looking for nodes where it should be
442
// splitted. It must be noticed that this only applies to two-level ASTs (i.e.
443
// an AST consisting in a RE_NODE_CONCAT at the root where all the children are
444
// leaves).
445
//
446
// For example, { 01 02 03 [0-1000] 04 05 06 [500-2000] 07 08 09 } has the
447
// following AST:
448
//
449
// RE_NODE_CONCAT
450
// |
451
// |- RE_NODE_LITERAL (01)
452
// |- RE_NODE_LITERAL (02)
453
// |- RE_NODE_LITERAL (03)
454
// |- RE_NODE_RANGE_ANY (start=0, end=1000)
455
// |- RE_NODE_LITERAL (04)
456
// |- RE_NODE_LITERAL (05)
457
// |- RE_NODE_LITERAL (06)
458
// |- RE_NODE_RANGE_ANY (start=500, end=2000)
459
// |- RE_NODE_LITERAL (07)
460
// |- RE_NODE_LITERAL (08)
461
// |- RE_NODE_LITERAL (09)
462
//
463
// If the AST above is passed in the re_ast argument, it will be trimmed to:
464
//
465
// RE_NODE_CONCAT
466
// |
467
// |- RE_NODE_LITERAL (01)
468
// |- RE_NODE_LITERAL (02)
469
// |- RE_NODE_LITERAL (03)
470
//
471
// While remainder_re_ast will be:
472
//
473
// RE_NODE_CONCAT
474
// |
475
// |- RE_NODE_LITERAL (04)
476
// |- RE_NODE_LITERAL (05)
477
// |- RE_NODE_LITERAL (06)
478
// |- RE_NODE_RANGE_ANY (start=500, end=2000)
479
// |- RE_NODE_LITERAL (07)
480
// |- RE_NODE_LITERAL (08)
481
// |- RE_NODE_LITERAL (09)
482
//
483
// The caller is responsible for freeing the new AST in remainder_re_ast by
484
// calling yr_re_ast_destroy.
485
//
486
// The integers pointed to by min_gap and max_gap will be filled with the
487
// minimum and maximum gap size between the sub-strings represented by the
488
// two ASTs.
489
//
490
int yr_re_ast_split_at_chaining_point(
491
    RE_AST* re_ast,
492
    RE_AST** remainder_re_ast,
493
    int32_t* min_gap,
494
    int32_t* max_gap)
495
0
{
496
0
  RE_NODE* child;
497
0
  RE_NODE* concat;
498
499
0
  int result;
500
501
0
  *remainder_re_ast = NULL;
502
0
  *min_gap = 0;
503
0
  *max_gap = 0;
504
505
0
  if (re_ast->root_node->type != RE_NODE_CONCAT)
506
0
    return ERROR_SUCCESS;
507
508
0
  child = re_ast->root_node->children_head;
509
510
0
  while (child != NULL)
511
0
  {
512
0
    if (!child->greedy && child->type == RE_NODE_RANGE_ANY &&
513
0
        child->prev_sibling != NULL && child->next_sibling != NULL &&
514
0
        (child->start > YR_STRING_CHAINING_THRESHOLD ||
515
0
         child->end > YR_STRING_CHAINING_THRESHOLD))
516
0
    {
517
0
      result = yr_re_ast_create(remainder_re_ast);
518
519
0
      if (result != ERROR_SUCCESS)
520
0
        return result;
521
522
0
      concat = yr_re_node_create(RE_NODE_CONCAT);
523
524
0
      if (concat == NULL)
525
0
        return ERROR_INSUFFICIENT_MEMORY;
526
527
0
      concat->children_head = child->next_sibling;
528
0
      concat->children_tail = re_ast->root_node->children_tail;
529
530
0
      re_ast->root_node->children_tail = child->prev_sibling;
531
532
0
      child->prev_sibling->next_sibling = NULL;
533
0
      child->next_sibling->prev_sibling = NULL;
534
535
0
      *min_gap = child->start;
536
0
      *max_gap = child->end;
537
538
0
      (*remainder_re_ast)->root_node = concat;
539
0
      (*remainder_re_ast)->flags = re_ast->flags;
540
541
0
      yr_re_node_destroy(child);
542
543
0
      return ERROR_SUCCESS;
544
0
    }
545
546
0
    child = child->next_sibling;
547
0
  }
548
549
0
  return ERROR_SUCCESS;
550
0
}
551
552
int _yr_emit_inst(
553
    RE_EMIT_CONTEXT* emit_context,
554
    uint8_t opcode,
555
    YR_ARENA_REF* instruction_ref)
556
0
{
557
0
  FAIL_ON_ERROR(yr_arena_write_data(
558
0
      emit_context->arena,
559
0
      YR_RE_CODE_SECTION,
560
0
      &opcode,
561
0
      sizeof(uint8_t),
562
0
      instruction_ref));
563
564
0
  return ERROR_SUCCESS;
565
0
}
566
567
int _yr_emit_inst_arg_uint8(
568
    RE_EMIT_CONTEXT* emit_context,
569
    uint8_t opcode,
570
    uint8_t argument,
571
    YR_ARENA_REF* instruction_ref,
572
    YR_ARENA_REF* argument_ref)
573
0
{
574
0
  FAIL_ON_ERROR(yr_arena_write_data(
575
0
      emit_context->arena,
576
0
      YR_RE_CODE_SECTION,
577
0
      &opcode,
578
0
      sizeof(uint8_t),
579
0
      instruction_ref));
580
581
0
  FAIL_ON_ERROR(yr_arena_write_data(
582
0
      emit_context->arena,
583
0
      YR_RE_CODE_SECTION,
584
0
      &argument,
585
0
      sizeof(uint8_t),
586
0
      argument_ref));
587
588
0
  return ERROR_SUCCESS;
589
0
}
590
591
int _yr_emit_inst_arg_uint16(
592
    RE_EMIT_CONTEXT* emit_context,
593
    uint8_t opcode,
594
    uint16_t argument,
595
    YR_ARENA_REF* instruction_ref,
596
    YR_ARENA_REF* argument_ref)
597
0
{
598
0
  FAIL_ON_ERROR(yr_arena_write_data(
599
0
      emit_context->arena,
600
0
      YR_RE_CODE_SECTION,
601
0
      &opcode,
602
0
      sizeof(uint8_t),
603
0
      instruction_ref));
604
605
0
  FAIL_ON_ERROR(yr_arena_write_data(
606
0
      emit_context->arena,
607
0
      YR_RE_CODE_SECTION,
608
0
      &argument,
609
0
      sizeof(uint16_t),
610
0
      argument_ref));
611
612
0
  return ERROR_SUCCESS;
613
0
}
614
615
int _yr_emit_inst_arg_uint32(
616
    RE_EMIT_CONTEXT* emit_context,
617
    uint8_t opcode,
618
    uint32_t argument,
619
    YR_ARENA_REF* instruction_ref,
620
    YR_ARENA_REF* argument_ref)
621
0
{
622
0
  FAIL_ON_ERROR(yr_arena_write_data(
623
0
      emit_context->arena,
624
0
      YR_RE_CODE_SECTION,
625
0
      &opcode,
626
0
      sizeof(uint8_t),
627
0
      instruction_ref));
628
629
0
  FAIL_ON_ERROR(yr_arena_write_data(
630
0
      emit_context->arena,
631
0
      YR_RE_CODE_SECTION,
632
0
      &argument,
633
0
      sizeof(uint32_t),
634
0
      argument_ref));
635
636
0
  return ERROR_SUCCESS;
637
0
}
638
639
int _yr_emit_inst_arg_int16(
640
    RE_EMIT_CONTEXT* emit_context,
641
    uint8_t opcode,
642
    int16_t argument,
643
    YR_ARENA_REF* instruction_ref,
644
    YR_ARENA_REF* argument_ref)
645
0
{
646
0
  FAIL_ON_ERROR(yr_arena_write_data(
647
0
      emit_context->arena,
648
0
      YR_RE_CODE_SECTION,
649
0
      &opcode,
650
0
      sizeof(uint8_t),
651
0
      instruction_ref));
652
653
0
  FAIL_ON_ERROR(yr_arena_write_data(
654
0
      emit_context->arena,
655
0
      YR_RE_CODE_SECTION,
656
0
      &argument,
657
0
      sizeof(int16_t),
658
0
      argument_ref));
659
660
0
  return ERROR_SUCCESS;
661
0
}
662
663
int _yr_emit_inst_arg_struct(
664
    RE_EMIT_CONTEXT* emit_context,
665
    uint8_t opcode,
666
    void* structure,
667
    size_t structure_size,
668
    YR_ARENA_REF* instruction_ref,
669
    YR_ARENA_REF* argument_ref)
670
0
{
671
0
  FAIL_ON_ERROR(yr_arena_write_data(
672
0
      emit_context->arena,
673
0
      YR_RE_CODE_SECTION,
674
0
      &opcode,
675
0
      sizeof(uint8_t),
676
0
      instruction_ref));
677
678
0
  FAIL_ON_ERROR(yr_arena_write_data(
679
0
      emit_context->arena,
680
0
      YR_RE_CODE_SECTION,
681
0
      structure,
682
0
      structure_size,
683
0
      argument_ref));
684
685
0
  return ERROR_SUCCESS;
686
0
}
687
688
int _yr_emit_split(
689
    RE_EMIT_CONTEXT* emit_context,
690
    uint8_t opcode,
691
    int16_t argument,
692
    YR_ARENA_REF* instruction_ref,
693
    YR_ARENA_REF* argument_ref)
694
0
{
695
0
  assert(opcode == RE_OPCODE_SPLIT_A || opcode == RE_OPCODE_SPLIT_B);
696
697
0
  if (emit_context->next_split_id == RE_MAX_SPLIT_ID)
698
0
    return ERROR_REGULAR_EXPRESSION_TOO_COMPLEX;
699
700
0
  FAIL_ON_ERROR(yr_arena_write_data(
701
0
      emit_context->arena,
702
0
      YR_RE_CODE_SECTION,
703
0
      &opcode,
704
0
      sizeof(uint8_t),
705
0
      instruction_ref));
706
707
0
  FAIL_ON_ERROR(yr_arena_write_data(
708
0
      emit_context->arena,
709
0
      YR_RE_CODE_SECTION,
710
0
      &emit_context->next_split_id,
711
0
      sizeof(RE_SPLIT_ID_TYPE),
712
0
      NULL));
713
714
0
  emit_context->next_split_id++;
715
716
0
  FAIL_ON_ERROR(yr_arena_write_data(
717
0
      emit_context->arena,
718
0
      YR_RE_CODE_SECTION,
719
0
      &argument,
720
0
      sizeof(int16_t),
721
0
      argument_ref));
722
723
0
  return ERROR_SUCCESS;
724
0
}
725
726
static int _yr_re_emit(
727
    RE_EMIT_CONTEXT* emit_context,
728
    RE_NODE* re_node,
729
    int flags,
730
    YR_ARENA_REF* code_ref)
731
0
{
732
0
  int16_t jmp_offset;
733
734
0
  yr_arena_off_t bookmark_1 = 0;
735
0
  yr_arena_off_t bookmark_2 = 0;
736
0
  yr_arena_off_t bookmark_3 = 0;
737
0
  yr_arena_off_t bookmark_4 = 0;
738
739
0
  bool emit_split;
740
0
  bool emit_repeat;
741
0
  bool emit_prolog;
742
0
  bool emit_epilog;
743
744
0
  RE_REPEAT_ARGS repeat_args;
745
0
  RE_REPEAT_ARGS* repeat_start_args_addr;
746
0
  RE_REPEAT_ANY_ARGS repeat_any_args;
747
748
0
  RE_NODE* child;
749
750
0
  void* split_offset_addr = NULL;
751
0
  void* jmp_offset_addr = NULL;
752
753
0
  YR_ARENA_REF instruction_ref = YR_ARENA_NULL_REF;
754
0
  YR_ARENA_REF split_offset_ref;
755
0
  YR_ARENA_REF jmp_instruction_ref;
756
0
  YR_ARENA_REF jmp_offset_ref;
757
0
  YR_ARENA_REF repeat_start_args_ref;
758
759
0
  if (yr_arena_get_current_offset(
760
0
          emit_context->arena, YR_RE_CODE_SECTION) -
761
0
          emit_context->start_offset >
762
0
      RE_MAX_CODE_SIZE)
763
0
  {
764
0
    return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
765
0
  }
766
767
0
  switch (re_node->type)
768
0
  {
769
0
  case RE_NODE_LITERAL:
770
0
    FAIL_ON_ERROR(_yr_emit_inst_arg_uint8(
771
0
        emit_context,
772
0
        RE_OPCODE_LITERAL,
773
0
        re_node->value,
774
0
        &instruction_ref,
775
0
        NULL));
776
0
    break;
777
778
0
  case RE_NODE_NOT_LITERAL:
779
0
    FAIL_ON_ERROR(_yr_emit_inst_arg_uint8(
780
0
        emit_context,
781
0
        RE_OPCODE_NOT_LITERAL,
782
0
        re_node->value,
783
0
        &instruction_ref,
784
0
        NULL));
785
0
    break;
786
787
0
  case RE_NODE_MASKED_LITERAL:
788
0
    FAIL_ON_ERROR(_yr_emit_inst_arg_uint16(
789
0
        emit_context,
790
0
        RE_OPCODE_MASKED_LITERAL,
791
0
        re_node->mask << 8 | re_node->value,
792
0
        &instruction_ref,
793
0
        NULL));
794
0
    break;
795
796
0
  case RE_NODE_MASKED_NOT_LITERAL:
797
0
    FAIL_ON_ERROR(_yr_emit_inst_arg_uint16(
798
0
        emit_context,
799
0
        RE_OPCODE_MASKED_NOT_LITERAL,
800
0
        re_node->mask << 8 | re_node->value,
801
0
        &instruction_ref,
802
0
        NULL));
803
0
    break;
804
805
0
  case RE_NODE_WORD_CHAR:
806
0
    FAIL_ON_ERROR(
807
0
        _yr_emit_inst(emit_context, RE_OPCODE_WORD_CHAR, &instruction_ref));
808
0
    break;
809
810
0
  case RE_NODE_NON_WORD_CHAR:
811
0
    FAIL_ON_ERROR(
812
0
        _yr_emit_inst(emit_context, RE_OPCODE_NON_WORD_CHAR, &instruction_ref));
813
0
    break;
814
815
0
  case RE_NODE_WORD_BOUNDARY:
816
0
    FAIL_ON_ERROR(
817
0
        _yr_emit_inst(emit_context, RE_OPCODE_WORD_BOUNDARY, &instruction_ref));
818
0
    break;
819
820
0
  case RE_NODE_NON_WORD_BOUNDARY:
821
0
    FAIL_ON_ERROR(_yr_emit_inst(
822
0
        emit_context, RE_OPCODE_NON_WORD_BOUNDARY, &instruction_ref));
823
0
    break;
824
825
0
  case RE_NODE_SPACE:
826
0
    FAIL_ON_ERROR(
827
0
        _yr_emit_inst(emit_context, RE_OPCODE_SPACE, &instruction_ref));
828
0
    break;
829
830
0
  case RE_NODE_NON_SPACE:
831
0
    FAIL_ON_ERROR(
832
0
        _yr_emit_inst(emit_context, RE_OPCODE_NON_SPACE, &instruction_ref));
833
0
    break;
834
835
0
  case RE_NODE_DIGIT:
836
0
    FAIL_ON_ERROR(
837
0
        _yr_emit_inst(emit_context, RE_OPCODE_DIGIT, &instruction_ref));
838
0
    break;
839
840
0
  case RE_NODE_NON_DIGIT:
841
0
    FAIL_ON_ERROR(
842
0
        _yr_emit_inst(emit_context, RE_OPCODE_NON_DIGIT, &instruction_ref));
843
0
    break;
844
845
0
  case RE_NODE_ANY:
846
0
    FAIL_ON_ERROR(_yr_emit_inst(emit_context, RE_OPCODE_ANY, &instruction_ref));
847
0
    break;
848
849
0
  case RE_NODE_CLASS:
850
0
    FAIL_ON_ERROR(
851
0
        _yr_emit_inst(emit_context, RE_OPCODE_CLASS, &instruction_ref));
852
853
0
    FAIL_ON_ERROR(yr_arena_write_data(
854
0
        emit_context->arena,
855
0
        YR_RE_CODE_SECTION,
856
0
        re_node->re_class,
857
0
        sizeof(*re_node->re_class),
858
0
        NULL));
859
0
    break;
860
861
0
  case RE_NODE_ANCHOR_START:
862
0
    FAIL_ON_ERROR(_yr_emit_inst(
863
0
        emit_context, RE_OPCODE_MATCH_AT_START, &instruction_ref));
864
0
    break;
865
866
0
  case RE_NODE_ANCHOR_END:
867
0
    FAIL_ON_ERROR(
868
0
        _yr_emit_inst(emit_context, RE_OPCODE_MATCH_AT_END, &instruction_ref));
869
0
    break;
870
871
0
  case RE_NODE_CONCAT:
872
0
    child = (flags & EMIT_BACKWARDS) ? re_node->children_tail
873
0
                                     : re_node->children_head;
874
875
0
    while (child != NULL)
876
0
    {
877
0
      FAIL_ON_ERROR(_yr_re_emit(
878
0
          emit_context,
879
0
          child,
880
0
          flags,
881
0
          YR_ARENA_IS_NULL_REF(instruction_ref) ? &instruction_ref : NULL));
882
883
0
      child = (flags & EMIT_BACKWARDS) ? child->prev_sibling
884
0
                                       : child->next_sibling;
885
0
    }
886
0
    break;
887
888
0
  case RE_NODE_PLUS:
889
    // Code for e+ looks like:
890
    //
891
    //          L1: code for e
892
    //              split L1, L2
893
    //          L2:
894
    //
895
0
    FAIL_ON_ERROR(_yr_re_emit(
896
0
        emit_context, re_node->children_head, flags, &instruction_ref));
897
898
    // If the child node emitted no code at all (e.g. "(k{0})+"), there is
899
    // nothing to loop over, so don't emit the split instruction.
900
0
    if (YR_ARENA_IS_NULL_REF(instruction_ref))
901
0
      break;
902
903
0
    bookmark_1 = yr_arena_get_current_offset(
904
0
        emit_context->arena, YR_RE_CODE_SECTION);
905
906
0
    if (instruction_ref.offset - bookmark_1 < INT16_MIN)
907
0
      return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
908
909
0
    jmp_offset = (int16_t) (instruction_ref.offset - bookmark_1);
910
911
0
    FAIL_ON_ERROR(_yr_emit_split(
912
0
        emit_context,
913
0
        re_node->greedy ? RE_OPCODE_SPLIT_B : RE_OPCODE_SPLIT_A,
914
0
        jmp_offset,
915
0
        NULL,
916
0
        NULL));
917
918
0
    break;
919
920
0
  case RE_NODE_STAR:
921
    // Code for e* looks like:
922
    //
923
    //          L1: split L1, L2
924
    //              code for e
925
    //              jmp L1
926
    //          L2:
927
0
    FAIL_ON_ERROR(_yr_emit_split(
928
0
        emit_context,
929
0
        re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B,
930
0
        0,
931
0
        &instruction_ref,
932
0
        &split_offset_ref));
933
934
0
    FAIL_ON_ERROR(
935
0
        _yr_re_emit(emit_context, re_node->children_head, flags, NULL));
936
937
0
    bookmark_1 = yr_arena_get_current_offset(
938
0
        emit_context->arena, YR_RE_CODE_SECTION);
939
940
0
    if (instruction_ref.offset - bookmark_1 < INT16_MIN)
941
0
      return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
942
943
0
    jmp_offset = (int16_t) (instruction_ref.offset - bookmark_1);
944
945
    // Emit jump with offset set to 0.
946
947
0
    FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
948
0
        emit_context, RE_OPCODE_JUMP, jmp_offset, NULL, NULL));
949
950
0
    bookmark_1 = yr_arena_get_current_offset(
951
0
        emit_context->arena, YR_RE_CODE_SECTION);
952
953
0
    if (bookmark_1 - instruction_ref.offset > INT16_MAX)
954
0
      return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
955
956
0
    jmp_offset = (int16_t) (bookmark_1 - instruction_ref.offset);
957
958
    // Update split offset.
959
0
    split_offset_addr =
960
0
        yr_arena_ref_to_ptr(emit_context->arena, &split_offset_ref);
961
962
0
    memcpy(split_offset_addr, &jmp_offset, sizeof(jmp_offset));
963
0
    break;
964
965
0
  case RE_NODE_ALT:
966
    // Code for e1|e2 looks like:
967
    //
968
    //              split L1, L2
969
    //          L1: code for e1
970
    //              jmp L3
971
    //          L2: code for e2
972
    //          L3:
973
974
    // Emit a split instruction with offset set to 0 temporarily. Offset
975
    // will be updated after we know the size of the code generated for
976
    // the left node (e1).
977
978
0
    FAIL_ON_ERROR(_yr_emit_split(
979
0
        emit_context,
980
0
        RE_OPCODE_SPLIT_A,
981
0
        0,
982
0
        &instruction_ref,
983
0
        &split_offset_ref));
984
985
0
    FAIL_ON_ERROR(
986
0
        _yr_re_emit(emit_context, re_node->children_head, flags, NULL));
987
988
    // Emit jump with offset set to 0.
989
990
0
    FAIL_ON_ERROR(_yr_emit_inst_arg_int16(
991
0
        emit_context,
992
0
        RE_OPCODE_JUMP,
993
0
        0,
994
0
        &jmp_instruction_ref,
995
0
        &jmp_offset_ref));
996
997
0
    bookmark_1 = yr_arena_get_current_offset(
998
0
        emit_context->arena, YR_RE_CODE_SECTION);
999
1000
0
    if (bookmark_1 - instruction_ref.offset > INT16_MAX)
1001
0
      return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
1002
1003
0
    jmp_offset = (int16_t) (bookmark_1 - instruction_ref.offset);
1004
1005
    // Update split offset.
1006
0
    split_offset_addr =
1007
0
        yr_arena_ref_to_ptr(emit_context->arena, &split_offset_ref);
1008
1009
0
    memcpy(split_offset_addr, &jmp_offset, sizeof(jmp_offset));
1010
1011
0
    FAIL_ON_ERROR(
1012
0
        _yr_re_emit(emit_context, re_node->children_tail, flags, NULL));
1013
1014
0
    bookmark_1 = yr_arena_get_current_offset(
1015
0
        emit_context->arena, YR_RE_CODE_SECTION);
1016
1017
0
    if (bookmark_1 - jmp_instruction_ref.offset > INT16_MAX)
1018
0
      return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
1019
1020
0
    jmp_offset = (int16_t) (bookmark_1 - jmp_instruction_ref.offset);
1021
1022
    // Update offset for jmp instruction.
1023
0
    jmp_offset_addr = yr_arena_ref_to_ptr(emit_context->arena, &jmp_offset_ref);
1024
1025
0
    memcpy(jmp_offset_addr, &jmp_offset, sizeof(jmp_offset));
1026
0
    break;
1027
1028
0
  case RE_NODE_RANGE_ANY:
1029
0
    repeat_any_args.min = re_node->start;
1030
0
    repeat_any_args.max = re_node->end;
1031
1032
0
    FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
1033
0
        emit_context,
1034
0
        re_node->greedy ? RE_OPCODE_REPEAT_ANY_GREEDY
1035
0
                        : RE_OPCODE_REPEAT_ANY_UNGREEDY,
1036
0
        &repeat_any_args,
1037
0
        sizeof(repeat_any_args),
1038
0
        &instruction_ref,
1039
0
        NULL));
1040
1041
0
    break;
1042
1043
0
  case RE_NODE_RANGE:
1044
    // Code for e{n,m} looks like:
1045
    //
1046
    //            code for e              ---   prolog
1047
    //            repeat_start n, m, L1   --+
1048
    //        L0: code for e                |   repeat
1049
    //            repeat_end n, m, L0     --+
1050
    //        L1: split L2, L3            ---   split
1051
    //        L2: code for e              ---   epilog
1052
    //        L3:
1053
    //
1054
    // Not all sections (prolog, repeat, split and epilog) are generated in all
1055
    // cases, it depends on the values of n and m. The following table shows
1056
    // which sections are generated for the first few values of n and m.
1057
    //
1058
    //        n,m   prolog  repeat      split  epilog
1059
    //                      (min,max)
1060
    //        ---------------------------------------
1061
    //        0,0     -       -           -      -
1062
    //        0,1     -       -           X      X
1063
    //        0,2     -       0,1         X      X
1064
    //        0,3     -       0,2         X      X
1065
    //        0,M     -       0,M-1       X      X
1066
    //
1067
    //        1,1     X       -           -      -
1068
    //        1,2     X       -           X      X
1069
    //        1,3     X       0,1         X      X
1070
    //        1,4     X       1,2         X      X
1071
    //        1,M     X       1,M-2       X      X
1072
    //
1073
    //        2,2     X       -           -      X
1074
    //        2,3     X       1,1         X      X
1075
    //        2,4     X       1,2         X      X
1076
    //        2,M     X       1,M-2       X      X
1077
    //
1078
    //        3,3     X       1,1         -      X
1079
    //        3,4     X       2,2         X      X
1080
    //        3,M     X       2,M-2       X      X
1081
    //
1082
    //        4,4     X       2,2         -      X
1083
    //        4,5     X       3,3         X      X
1084
    //        4,M     X       3,M-2       X      X
1085
    //
1086
    // The code can't consists simply in the repeat section, the prolog and
1087
    // epilog are required because we can't have atoms pointing to code inside
1088
    // the repeat loop. Atoms' forwards_code will point to code in the prolog
1089
    // and backwards_code will point to code in the epilog (or in prolog if
1090
    // epilog wasn't generated, like in n=1,m=1)
1091
1092
0
    emit_prolog = re_node->start > 0;
1093
0
    emit_repeat = re_node->end > re_node->start + 1 || re_node->end > 2;
1094
0
    emit_split = re_node->end > re_node->start;
1095
0
    emit_epilog = re_node->end > re_node->start || re_node->end > 1;
1096
1097
0
    if (emit_prolog)
1098
0
    {
1099
0
      FAIL_ON_ERROR(_yr_re_emit(
1100
0
          emit_context, re_node->children_head, flags, &instruction_ref));
1101
1102
      // If the child node emitted no code at all (e.g. "(k{0}){2}"), there is
1103
      // nothing to repeat, so don't emit the repeat, split or epilog sections.
1104
0
      if (YR_ARENA_IS_NULL_REF(instruction_ref))
1105
0
        break;
1106
0
    }
1107
1108
0
    if (emit_repeat)
1109
0
    {
1110
0
      repeat_args.min = re_node->start;
1111
0
      repeat_args.max = re_node->end;
1112
1113
0
      if (emit_prolog)
1114
0
      {
1115
0
        repeat_args.max--;
1116
0
        repeat_args.min--;
1117
0
      }
1118
1119
0
      if (emit_split)
1120
0
      {
1121
0
        repeat_args.max--;
1122
0
      }
1123
0
      else
1124
0
      {
1125
0
        repeat_args.min--;
1126
0
        repeat_args.max--;
1127
0
      }
1128
1129
0
      repeat_args.offset = 0;
1130
1131
0
      bookmark_1 = yr_arena_get_current_offset(
1132
0
          emit_context->arena, YR_RE_CODE_SECTION);
1133
1134
0
      FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
1135
0
          emit_context,
1136
0
          re_node->greedy ? RE_OPCODE_REPEAT_START_GREEDY
1137
0
                          : RE_OPCODE_REPEAT_START_UNGREEDY,
1138
0
          &repeat_args,
1139
0
          sizeof(repeat_args),
1140
0
          YR_ARENA_IS_NULL_REF(instruction_ref) ? &instruction_ref : NULL,
1141
0
          &repeat_start_args_ref));
1142
1143
0
      bookmark_2 = yr_arena_get_current_offset(
1144
0
          emit_context->arena, YR_RE_CODE_SECTION);
1145
1146
0
      FAIL_ON_ERROR(_yr_re_emit(
1147
0
          emit_context,
1148
0
          re_node->children_head,
1149
0
          flags | EMIT_DONT_SET_FORWARDS_CODE | EMIT_DONT_SET_BACKWARDS_CODE,
1150
0
          NULL));
1151
1152
0
      bookmark_3 = yr_arena_get_current_offset(
1153
0
          emit_context->arena, YR_RE_CODE_SECTION);
1154
1155
0
      if (bookmark_2 - bookmark_3 < INT32_MIN)
1156
0
        return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
1157
1158
0
      repeat_args.offset = (int32_t) (bookmark_2 - bookmark_3);
1159
1160
0
      FAIL_ON_ERROR(_yr_emit_inst_arg_struct(
1161
0
          emit_context,
1162
0
          re_node->greedy ? RE_OPCODE_REPEAT_END_GREEDY
1163
0
                          : RE_OPCODE_REPEAT_END_UNGREEDY,
1164
0
          &repeat_args,
1165
0
          sizeof(repeat_args),
1166
0
          NULL,
1167
0
          NULL));
1168
1169
0
      bookmark_4 = yr_arena_get_current_offset(
1170
0
          emit_context->arena, YR_RE_CODE_SECTION);
1171
1172
0
      repeat_start_args_addr = (RE_REPEAT_ARGS*) yr_arena_ref_to_ptr(
1173
0
          emit_context->arena, &repeat_start_args_ref);
1174
1175
0
      if (bookmark_4 - bookmark_1 > INT32_MAX)
1176
0
        return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
1177
1178
0
      repeat_start_args_addr->offset = (int32_t) (bookmark_4 - bookmark_1);
1179
0
    }
1180
1181
0
    if (emit_split)
1182
0
    {
1183
0
      bookmark_1 = yr_arena_get_current_offset(
1184
0
          emit_context->arena, YR_RE_CODE_SECTION);
1185
1186
0
      FAIL_ON_ERROR(_yr_emit_split(
1187
0
          emit_context,
1188
0
          re_node->greedy ? RE_OPCODE_SPLIT_A : RE_OPCODE_SPLIT_B,
1189
0
          0,
1190
0
          YR_ARENA_IS_NULL_REF(instruction_ref) ? &instruction_ref : NULL,
1191
0
          &split_offset_ref));
1192
0
    }
1193
1194
0
    if (emit_epilog)
1195
0
    {
1196
0
      FAIL_ON_ERROR(_yr_re_emit(
1197
0
          emit_context,
1198
0
          re_node->children_head,
1199
0
          emit_prolog ? flags | EMIT_DONT_SET_FORWARDS_CODE : flags,
1200
0
          YR_ARENA_IS_NULL_REF(instruction_ref) ? &instruction_ref : NULL));
1201
0
    }
1202
1203
0
    if (emit_split)
1204
0
    {
1205
0
      bookmark_2 = yr_arena_get_current_offset(
1206
0
          emit_context->arena, YR_RE_CODE_SECTION);
1207
1208
0
      if (bookmark_2 - bookmark_1 > INT16_MAX)
1209
0
        return ERROR_REGULAR_EXPRESSION_TOO_LARGE;
1210
1211
0
      split_offset_addr =
1212
0
          yr_arena_ref_to_ptr(emit_context->arena, &split_offset_ref);
1213
1214
0
      jmp_offset = (int16_t) (bookmark_2 - bookmark_1);
1215
1216
0
      memcpy(split_offset_addr, &jmp_offset, sizeof(jmp_offset));
1217
0
    }
1218
1219
0
    break;
1220
0
  }
1221
1222
0
  if (flags & EMIT_BACKWARDS)
1223
0
  {
1224
0
    if (!(flags & EMIT_DONT_SET_BACKWARDS_CODE))
1225
0
    {
1226
0
      re_node->backward_code_ref.buffer_id = YR_RE_CODE_SECTION;
1227
0
      re_node->backward_code_ref.offset = yr_arena_get_current_offset(
1228
0
          emit_context->arena, YR_RE_CODE_SECTION);
1229
0
    }
1230
0
  }
1231
0
  else
1232
0
  {
1233
0
    if (!(flags & EMIT_DONT_SET_FORWARDS_CODE))
1234
0
    {
1235
0
      re_node->forward_code_ref = instruction_ref;
1236
0
    }
1237
0
  }
1238
1239
0
  if (code_ref != NULL)
1240
0
    *code_ref = instruction_ref;
1241
1242
0
  return ERROR_SUCCESS;
1243
0
}
1244
1245
int yr_re_ast_emit_code(RE_AST* re_ast, YR_ARENA* arena, int backwards_code)
1246
0
{
1247
0
  RE_EMIT_CONTEXT emit_context;
1248
1249
  // Emit code for matching the regular expressions forwards.
1250
0
  emit_context.arena = arena;
1251
0
  emit_context.next_split_id = 0;
1252
0
  emit_context.start_offset = yr_arena_get_current_offset(
1253
0
      arena, YR_RE_CODE_SECTION);
1254
1255
0
  FAIL_ON_ERROR(_yr_re_emit(
1256
0
      &emit_context,
1257
0
      re_ast->root_node,
1258
0
      backwards_code ? EMIT_BACKWARDS : 0,
1259
0
      NULL));
1260
1261
0
  FAIL_ON_ERROR(_yr_emit_inst(&emit_context, RE_OPCODE_MATCH, NULL));
1262
1263
0
  return ERROR_SUCCESS;
1264
0
}
1265
1266
static int _yr_re_fiber_create(RE_FIBER_POOL* fiber_pool, RE_FIBER** new_fiber)
1267
0
{
1268
0
  RE_FIBER* fiber;
1269
1270
0
  if (fiber_pool->fibers.head != NULL)
1271
0
  {
1272
0
    fiber = fiber_pool->fibers.head;
1273
0
    fiber_pool->fibers.head = fiber->next;
1274
1275
0
    if (fiber_pool->fibers.tail == fiber)
1276
0
      fiber_pool->fibers.tail = NULL;
1277
0
  }
1278
0
  else
1279
0
  {
1280
0
    if (fiber_pool->fiber_count == RE_MAX_FIBERS)
1281
0
      return ERROR_TOO_MANY_RE_FIBERS;
1282
1283
0
    fiber = (RE_FIBER*) yr_malloc(sizeof(RE_FIBER));
1284
1285
0
    if (fiber == NULL)
1286
0
      return ERROR_INSUFFICIENT_MEMORY;
1287
1288
0
    fiber_pool->fiber_count++;
1289
0
  }
1290
1291
0
  fiber->ip = NULL;
1292
0
  fiber->sp = -1;
1293
0
  fiber->rc = -1;
1294
0
  fiber->next = NULL;
1295
0
  fiber->prev = NULL;
1296
1297
0
  *new_fiber = fiber;
1298
1299
0
  return ERROR_SUCCESS;
1300
0
}
1301
1302
////////////////////////////////////////////////////////////////////////////////
1303
// Appends 'fiber' to 'fiber_list'
1304
//
1305
static void _yr_re_fiber_append(RE_FIBER_LIST* fiber_list, RE_FIBER* fiber)
1306
0
{
1307
0
  assert(fiber->prev == NULL);
1308
0
  assert(fiber->next == NULL);
1309
1310
0
  fiber->prev = fiber_list->tail;
1311
1312
0
  if (fiber_list->tail != NULL)
1313
0
    fiber_list->tail->next = fiber;
1314
1315
0
  fiber_list->tail = fiber;
1316
1317
0
  if (fiber_list->head == NULL)
1318
0
    fiber_list->head = fiber;
1319
1320
0
  assert(fiber_list->tail->next == NULL);
1321
0
  assert(fiber_list->head->prev == NULL);
1322
0
}
1323
1324
////////////////////////////////////////////////////////////////////////////////
1325
// Verifies if a fiber with the same properties (ip, rc, sp, and stack values)
1326
// than 'target_fiber' exists in 'fiber_list'. The list is iterated from
1327
// the start until 'last_fiber' (inclusive). Fibers past 'last_fiber' are not
1328
// taken into account.
1329
//
1330
static int _yr_re_fiber_exists(
1331
    RE_FIBER_LIST* fiber_list,
1332
    RE_FIBER* target_fiber,
1333
    RE_FIBER* last_fiber)
1334
0
{
1335
0
  RE_FIBER* fiber = fiber_list->head;
1336
1337
0
  int equal_stacks;
1338
0
  int i;
1339
1340
0
  if (last_fiber == NULL)
1341
0
    return false;
1342
1343
0
  while (fiber != last_fiber->next)
1344
0
  {
1345
0
    if (fiber->ip == target_fiber->ip && fiber->sp == target_fiber->sp &&
1346
0
        fiber->rc == target_fiber->rc)
1347
0
    {
1348
0
      equal_stacks = true;
1349
1350
0
      for (i = 0; i <= fiber->sp; i++)
1351
0
      {
1352
0
        if (fiber->stack[i] != target_fiber->stack[i])
1353
0
        {
1354
0
          equal_stacks = false;
1355
0
          break;
1356
0
        }
1357
0
      }
1358
1359
0
      if (equal_stacks)
1360
0
        return true;
1361
0
    }
1362
1363
0
    fiber = fiber->next;
1364
0
  }
1365
1366
0
  return false;
1367
0
}
1368
1369
////////////////////////////////////////////////////////////////////////////////
1370
// Clones a fiber in fiber_list and inserts the cloned fiber just after.
1371
// the original one. If fiber_list is:
1372
//
1373
//   f1 -> f2 -> f3 -> f4
1374
//
1375
// Splitting f2 will result in:
1376
//
1377
//   f1 -> f2 -> cloned f2 -> f3 -> f4
1378
//
1379
static int _yr_re_fiber_split(
1380
    RE_FIBER_LIST* fiber_list,
1381
    RE_FIBER_POOL* fiber_pool,
1382
    RE_FIBER* fiber,
1383
    RE_FIBER** new_fiber)
1384
0
{
1385
0
  int32_t i;
1386
1387
0
  FAIL_ON_ERROR(_yr_re_fiber_create(fiber_pool, new_fiber));
1388
1389
0
  (*new_fiber)->sp = fiber->sp;
1390
0
  (*new_fiber)->ip = fiber->ip;
1391
0
  (*new_fiber)->rc = fiber->rc;
1392
1393
0
  for (i = 0; i <= fiber->sp; i++) (*new_fiber)->stack[i] = fiber->stack[i];
1394
1395
0
  (*new_fiber)->next = fiber->next;
1396
0
  (*new_fiber)->prev = fiber;
1397
1398
0
  if (fiber->next != NULL)
1399
0
    fiber->next->prev = *new_fiber;
1400
1401
0
  fiber->next = *new_fiber;
1402
1403
0
  if (fiber_list->tail == fiber)
1404
0
    fiber_list->tail = *new_fiber;
1405
1406
0
  assert(fiber_list->tail->next == NULL);
1407
0
  assert(fiber_list->head->prev == NULL);
1408
1409
0
  return ERROR_SUCCESS;
1410
0
}
1411
1412
////////////////////////////////////////////////////////////////////////////////
1413
// Kills a given fiber by removing it from the fiber list and putting it in the
1414
// fiber pool.
1415
//
1416
static RE_FIBER* _yr_re_fiber_kill(
1417
    RE_FIBER_LIST* fiber_list,
1418
    RE_FIBER_POOL* fiber_pool,
1419
    RE_FIBER* fiber)
1420
0
{
1421
0
  RE_FIBER* next_fiber = fiber->next;
1422
1423
0
  if (fiber->prev != NULL)
1424
0
    fiber->prev->next = next_fiber;
1425
1426
0
  if (next_fiber != NULL)
1427
0
    next_fiber->prev = fiber->prev;
1428
1429
0
  if (fiber_pool->fibers.tail != NULL)
1430
0
    fiber_pool->fibers.tail->next = fiber;
1431
1432
0
  if (fiber_list->tail == fiber)
1433
0
    fiber_list->tail = fiber->prev;
1434
1435
0
  if (fiber_list->head == fiber)
1436
0
    fiber_list->head = next_fiber;
1437
1438
0
  fiber->next = NULL;
1439
0
  fiber->prev = fiber_pool->fibers.tail;
1440
0
  fiber_pool->fibers.tail = fiber;
1441
1442
0
  if (fiber_pool->fibers.head == NULL)
1443
0
    fiber_pool->fibers.head = fiber;
1444
1445
0
  return next_fiber;
1446
0
}
1447
1448
////////////////////////////////////////////////////////////////////////////////
1449
// Kills all fibers from the given one up to the end of the fiber list.
1450
//
1451
static void _yr_re_fiber_kill_tail(
1452
    RE_FIBER_LIST* fiber_list,
1453
    RE_FIBER_POOL* fiber_pool,
1454
    RE_FIBER* fiber)
1455
0
{
1456
0
  RE_FIBER* prev_fiber = fiber->prev;
1457
1458
0
  if (prev_fiber != NULL)
1459
0
    prev_fiber->next = NULL;
1460
1461
0
  fiber->prev = fiber_pool->fibers.tail;
1462
1463
0
  if (fiber_pool->fibers.tail != NULL)
1464
0
    fiber_pool->fibers.tail->next = fiber;
1465
1466
0
  fiber_pool->fibers.tail = fiber_list->tail;
1467
0
  fiber_list->tail = prev_fiber;
1468
1469
0
  if (fiber_list->head == fiber)
1470
0
    fiber_list->head = NULL;
1471
1472
0
  if (fiber_pool->fibers.head == NULL)
1473
0
    fiber_pool->fibers.head = fiber;
1474
0
}
1475
1476
////////////////////////////////////////////////////////////////////////////////
1477
// Kills all fibers in the fiber list.
1478
//
1479
static void _yr_re_fiber_kill_all(
1480
    RE_FIBER_LIST* fiber_list,
1481
    RE_FIBER_POOL* fiber_pool)
1482
0
{
1483
0
  if (fiber_list->head != NULL)
1484
0
    _yr_re_fiber_kill_tail(fiber_list, fiber_pool, fiber_list->head);
1485
0
}
1486
1487
////////////////////////////////////////////////////////////////////////////////
1488
// Executes a fiber until reaching an "matching" instruction. A "matching"
1489
// instruction is one that actually reads a byte from the input and performs
1490
// some matching. If the fiber reaches a split instruction, the new fiber is
1491
// also synced.
1492
//
1493
static int _yr_re_fiber_sync(
1494
    RE_FIBER_LIST* fiber_list,
1495
    RE_FIBER_POOL* fiber_pool,
1496
    RE_FIBER* fiber_to_sync,
1497
    const uint8_t* input_data,
1498
    size_t input_forwards_size,
1499
    size_t input_backwards_size,
1500
    int bytes_matched,
1501
    int flags)
1502
0
{
1503
  // A array for keeping track of which split instructions has been already
1504
  // executed. Each split instruction within a regexp has an associated ID
1505
  // between 0 and RE_MAX_SPLIT_ID-1. Keeping track of executed splits is
1506
  // required to avoid infinite loops in regexps like (a*)* or (a|)*
1507
1508
0
  RE_SPLIT_ID_TYPE splits_executed[RE_MAX_SPLIT_ID];
1509
0
  const uint8_t* splits_executed_ip[RE_MAX_SPLIT_ID];
1510
0
  RE_SPLIT_ID_TYPE splits_executed_count = 0;
1511
0
  RE_SPLIT_ID_TYPE split_id, splits_executed_idx;
1512
1513
0
  int split_already_executed;
1514
0
  int repeat_jumps = 0;
1515
0
  int match;
1516
0
  int kill;
1517
0
  int input_incr;
1518
1519
0
  uint8_t character_size;
1520
0
  const uint8_t* input;
1521
1522
0
  bool prev_is_word_char = false;
1523
0
  bool input_is_word_char = false;
1524
1525
0
  RE_REPEAT_ARGS* repeat_args;
1526
0
  RE_REPEAT_ANY_ARGS* repeat_any_args;
1527
1528
0
  RE_FIBER* fiber;
1529
0
  RE_FIBER* last;
1530
0
  RE_FIBER* next;
1531
0
  RE_FIBER* branch_a;
1532
0
  RE_FIBER* branch_b;
1533
1534
0
  if (flags & RE_FLAGS_WIDE)
1535
0
    character_size = 2;
1536
0
  else
1537
0
    character_size = 1;
1538
1539
0
  input = input_data;
1540
0
  input_incr = character_size;
1541
1542
0
  if (flags & RE_FLAGS_BACKWARDS)
1543
0
  {
1544
0
    input -= character_size + bytes_matched;
1545
0
    input_incr = -input_incr;
1546
0
  }
1547
0
  else
1548
0
  {
1549
0
    input += bytes_matched;
1550
0
  }
1551
1552
0
  fiber = fiber_to_sync;
1553
0
  last = fiber_to_sync->next;
1554
1555
0
  while (fiber != last)
1556
0
  {
1557
0
    int16_t jmp_len;
1558
0
    uint8_t opcode = *fiber->ip;
1559
1560
0
    switch (opcode)
1561
0
    {
1562
0
    case RE_OPCODE_SPLIT_A:
1563
0
    case RE_OPCODE_SPLIT_B:
1564
1565
0
      split_id = *(RE_SPLIT_ID_TYPE*) (fiber->ip + 1);
1566
0
      split_already_executed = false;
1567
1568
0
      for (splits_executed_idx = 0; splits_executed_idx < splits_executed_count;
1569
0
           splits_executed_idx++)
1570
0
      {
1571
0
        if (split_id == splits_executed[splits_executed_idx])
1572
0
        {
1573
0
          split_already_executed = true;
1574
0
          break;
1575
0
        }
1576
0
      }
1577
1578
0
      if (split_already_executed)
1579
0
      {
1580
0
        fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
1581
0
      }
1582
0
      else
1583
0
      {
1584
0
        const uint8_t* split_ip = fiber->ip;
1585
0
        branch_a = fiber;
1586
1587
0
        FAIL_ON_ERROR(
1588
0
            _yr_re_fiber_split(fiber_list, fiber_pool, branch_a, &branch_b));
1589
1590
        // With RE_OPCODE_SPLIT_A the current fiber continues at the next
1591
        // instruction in the stream (branch A), while the newly created
1592
        // fiber starts at the address indicated by the instruction (branch B)
1593
        // RE_OPCODE_SPLIT_B has the opposite behavior.
1594
1595
0
        if (opcode == RE_OPCODE_SPLIT_B)
1596
0
          yr_swap(branch_a, branch_b, RE_FIBER*);
1597
1598
        // Branch A continues at the next instruction
1599
0
        branch_a->ip += (sizeof(RE_SPLIT_ID_TYPE) + 3);
1600
1601
        // Branch B adds the offset indicated by the split instruction.
1602
0
        jmp_len = yr_unaligned_i16(branch_b->ip + 1 + sizeof(RE_SPLIT_ID_TYPE));
1603
1604
0
        branch_b->ip += jmp_len;
1605
1606
0
#if YR_PARANOID_EXEC
1607
        // In normal conditions this should never happen. But with compiled
1608
        // rules that has been hand-crafted by a malicious actor this could
1609
        // happen.
1610
0
        if (splits_executed_count >= RE_MAX_SPLIT_ID)
1611
0
          return ERROR_INTERNAL_FATAL_ERROR;
1612
0
#endif
1613
1614
0
        splits_executed[splits_executed_count] = split_id;
1615
0
        splits_executed_ip[splits_executed_count] = split_ip;
1616
0
        splits_executed_count++;
1617
0
      }
1618
1619
0
      break;
1620
1621
0
    case RE_OPCODE_REPEAT_START_GREEDY:
1622
0
    case RE_OPCODE_REPEAT_START_UNGREEDY:
1623
1624
0
      repeat_args = (RE_REPEAT_ARGS*) (fiber->ip + 1);
1625
0
      assert(repeat_args->max > 0);
1626
0
      branch_a = fiber;
1627
1628
0
      if (repeat_args->min == 0)
1629
0
      {
1630
0
        FAIL_ON_ERROR(
1631
0
            _yr_re_fiber_split(fiber_list, fiber_pool, branch_a, &branch_b));
1632
1633
0
        if (opcode == RE_OPCODE_REPEAT_START_UNGREEDY)
1634
0
          yr_swap(branch_a, branch_b, RE_FIBER*);
1635
1636
0
        branch_b->ip += repeat_args->offset;
1637
0
      }
1638
1639
0
#if YR_PARANOID_EXEC
1640
      // In normal conditions this should never happen. But with compiled
1641
      // rules that has been hand-crafted by a malicious actor this could
1642
      // happen.
1643
0
      if (branch_a->sp >= RE_MAX_STACK - 1)
1644
0
        return ERROR_INTERNAL_FATAL_ERROR;
1645
0
#endif
1646
1647
0
      branch_a->stack[++branch_a->sp] = 0;
1648
0
      branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
1649
0
      break;
1650
1651
0
    case RE_OPCODE_REPEAT_END_GREEDY:
1652
0
    case RE_OPCODE_REPEAT_END_UNGREEDY:
1653
1654
0
      repeat_args = (RE_REPEAT_ARGS*) (fiber->ip + 1);
1655
1656
0
#if YR_PARANOID_EXEC
1657
      // A REPEAT_END with no matching REPEAT_START leaves sp at -1 and the
1658
      // access below would read and write before the stack. In normal
1659
      // conditions this never happens, but it can with compiled rules that
1660
      // have been hand-crafted by a malicious actor.
1661
0
      if (fiber->sp < 0)
1662
0
        return ERROR_INTERNAL_FATAL_ERROR;
1663
0
#endif
1664
1665
0
      fiber->stack[fiber->sp]++;
1666
1667
0
      if (fiber->stack[fiber->sp] < repeat_args->min)
1668
0
      {
1669
0
        if (++repeat_jumps <= RE_MAX_FIBERS)
1670
0
        {
1671
0
          const uint8_t* next_ip = fiber->ip + repeat_args->offset;
1672
0
          RE_SPLIT_ID_TYPE write_idx = 0;
1673
1674
0
          for (splits_executed_idx = 0;
1675
0
               splits_executed_idx < splits_executed_count;
1676
0
               splits_executed_idx++)
1677
0
          {
1678
0
            if (splits_executed_ip[splits_executed_idx] < next_ip ||
1679
0
                splits_executed_ip[splits_executed_idx] >= fiber->ip)
1680
0
            {
1681
0
              splits_executed[write_idx] = splits_executed[splits_executed_idx];
1682
0
              splits_executed_ip[write_idx] =
1683
0
                  splits_executed_ip[splits_executed_idx];
1684
0
              write_idx++;
1685
0
            }
1686
0
          }
1687
1688
0
          splits_executed_count = write_idx;
1689
0
          fiber->ip = next_ip;
1690
0
          break;
1691
0
        }
1692
1693
0
        fiber->stack[fiber->sp] = repeat_args->min;
1694
0
      }
1695
1696
0
      branch_a = fiber;
1697
1698
0
      if (fiber->stack[fiber->sp] < repeat_args->max)
1699
0
      {
1700
0
        FAIL_ON_ERROR(
1701
0
            _yr_re_fiber_split(fiber_list, fiber_pool, branch_a, &branch_b));
1702
1703
0
        if (opcode == RE_OPCODE_REPEAT_END_GREEDY)
1704
0
          yr_swap(branch_a, branch_b, RE_FIBER*);
1705
1706
0
        branch_b->ip += repeat_args->offset;
1707
0
      }
1708
1709
0
      branch_a->sp--;
1710
0
      branch_a->ip += (1 + sizeof(RE_REPEAT_ARGS));
1711
0
      break;
1712
1713
0
    case RE_OPCODE_REPEAT_ANY_GREEDY:
1714
0
    case RE_OPCODE_REPEAT_ANY_UNGREEDY:
1715
1716
0
      repeat_any_args = (RE_REPEAT_ANY_ARGS*) (fiber->ip + 1);
1717
1718
      // If repetition counter (rc) is -1 it means that we are reaching this
1719
      // instruction from the previous one in the instructions stream. In
1720
      // this case let's initialize the counter to 0 and start looping.
1721
1722
0
      if (fiber->rc == -1)
1723
0
        fiber->rc = 0;
1724
1725
0
      if (fiber->rc < repeat_any_args->min)
1726
0
      {
1727
        // Increase repetition counter and continue with next fiber. The
1728
        // instruction pointer for this fiber is not incremented yet, this
1729
        // fiber spins in this same instruction until reaching the minimum
1730
        // number of repetitions.
1731
1732
0
        fiber->rc++;
1733
0
        fiber = fiber->next;
1734
0
      }
1735
0
      else if (fiber->rc < repeat_any_args->max)
1736
0
      {
1737
        // Once the minimum number of repetitions are matched one fiber
1738
        // remains spinning in this instruction until reaching the maximum
1739
        // number of repetitions while new fibers are created. New fibers
1740
        // start executing at the next instruction.
1741
1742
0
        next = fiber->next;
1743
0
        branch_a = fiber;
1744
1745
0
        FAIL_ON_ERROR(
1746
0
            _yr_re_fiber_split(fiber_list, fiber_pool, branch_a, &branch_b));
1747
1748
0
        if (opcode == RE_OPCODE_REPEAT_ANY_UNGREEDY)
1749
0
          yr_swap(branch_a, branch_b, RE_FIBER*);
1750
1751
0
        branch_a->rc++;
1752
0
        branch_b->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
1753
0
        branch_b->rc = -1;
1754
1755
0
        FAIL_ON_ERROR(_yr_re_fiber_sync(
1756
0
            fiber_list,
1757
0
            fiber_pool,
1758
0
            branch_b,
1759
0
            input_data,
1760
0
            input_forwards_size,
1761
0
            input_backwards_size,
1762
0
            bytes_matched,
1763
0
            flags));
1764
1765
0
        fiber = next;
1766
0
      }
1767
0
      else
1768
0
      {
1769
        // When the maximum number of repetitions is reached the fiber keeps
1770
        // executing at the next instruction. The repetition counter is set
1771
        // to -1 indicating that we are not spinning in a repeat instruction
1772
        // anymore.
1773
1774
0
        fiber->ip += (1 + sizeof(RE_REPEAT_ANY_ARGS));
1775
0
        fiber->rc = -1;
1776
0
      }
1777
1778
0
      break;
1779
1780
0
    case RE_OPCODE_JUMP:
1781
0
      jmp_len = yr_unaligned_i16(fiber->ip + 1);
1782
0
      fiber->ip += jmp_len;
1783
0
      break;
1784
1785
0
    case RE_OPCODE_WORD_BOUNDARY:
1786
0
    case RE_OPCODE_NON_WORD_BOUNDARY:
1787
1788
0
      if (input - input_incr + character_size <=
1789
0
              input_data + input_forwards_size &&
1790
0
          input - input_incr >= input_data - input_backwards_size)
1791
0
      {
1792
0
        prev_is_word_char = _yr_re_is_word_char(
1793
0
            input - input_incr, character_size);
1794
0
      }
1795
0
      else
1796
0
      {
1797
0
        prev_is_word_char = false;
1798
0
      }
1799
1800
0
      if (input + character_size <= input_data + input_forwards_size &&
1801
0
          input >= input_data - input_backwards_size)
1802
0
      {
1803
0
        input_is_word_char = _yr_re_is_word_char(input, character_size);
1804
0
      }
1805
0
      else
1806
0
      {
1807
0
        input_is_word_char = false;
1808
0
      }
1809
1810
0
      match = (prev_is_word_char && !input_is_word_char) ||
1811
0
              (!prev_is_word_char && input_is_word_char);
1812
1813
0
      if (opcode == RE_OPCODE_NON_WORD_BOUNDARY)
1814
0
        match = !match;
1815
1816
0
      if (match)
1817
0
        fiber->ip += 1;
1818
0
      else
1819
0
        fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
1820
1821
0
      break;
1822
1823
0
    case RE_OPCODE_MATCH_AT_START:
1824
0
      if (flags & RE_FLAGS_BACKWARDS)
1825
0
        kill = input_backwards_size != (size_t) bytes_matched;
1826
0
      else
1827
0
        kill = input_backwards_size > 0 || (bytes_matched != 0);
1828
1829
0
      if (kill)
1830
0
        fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
1831
0
      else
1832
0
        fiber->ip += 1;
1833
1834
0
      break;
1835
1836
0
    case RE_OPCODE_MATCH_AT_END:
1837
0
      kill = flags & RE_FLAGS_BACKWARDS ||
1838
0
             input_forwards_size != (size_t) bytes_matched;
1839
1840
0
      if (kill)
1841
0
        fiber = _yr_re_fiber_kill(fiber_list, fiber_pool, fiber);
1842
0
      else
1843
0
        fiber->ip += 1;
1844
1845
0
      break;
1846
1847
0
    default:
1848
0
      fiber = fiber->next;
1849
0
    }
1850
0
  }
1851
1852
0
  return ERROR_SUCCESS;
1853
0
}
1854
1855
////////////////////////////////////////////////////////////////////////////////
1856
// Executes a regular expression. The specified regular expression will try to
1857
// match the data starting at the address specified by "input". The "input"
1858
// pointer can point to any address inside a memory buffer. Arguments
1859
// "input_forwards_size" and "input_backwards_size" indicate how many bytes
1860
// can be accessible starting at "input" and going forwards and backwards
1861
// respectively.
1862
//
1863
//   <--- input_backwards_size -->|<----------- input_forwards_size -------->
1864
//  |--------  memory buffer  -----------------------------------------------|
1865
//                                ^
1866
//                              input
1867
//
1868
// Args:
1869
//   YR_SCAN_CONTEXT *context         - Scan context.
1870
//   const uint8_t* code              - Regexp code be executed
1871
//   const uint8_t* input             - Pointer to input data
1872
//   size_t input_forwards_size       - Number of accessible bytes starting at
1873
//                                      "input" and going forwards.
1874
//   size_t input_backwards_size      - Number of accessible bytes starting at
1875
//                                      "input" and going backwards
1876
//   int flags                        - Flags:
1877
//      RE_FLAGS_SCAN
1878
//      RE_FLAGS_BACKWARDS
1879
//      RE_FLAGS_EXHAUSTIVE
1880
//      RE_FLAGS_WIDE
1881
//      RE_FLAGS_NO_CASE
1882
//      RE_FLAGS_DOT_ALL
1883
//   RE_MATCH_CALLBACK_FUNC callback  - Callback function
1884
//   void* callback_args              - Callback argument
1885
//   int*  matches                    - Pointer to an integer receiving the
1886
//                                      number of matching bytes. Notice that
1887
//                                      0 means a zero-length match, while no
1888
//                                      matches is -1.
1889
// Returns:
1890
//    ERROR_SUCCESS or any other error code.
1891
1892
int yr_re_exec(
1893
    YR_SCAN_CONTEXT* context,
1894
    const uint8_t* code,
1895
    const uint8_t* input_data,
1896
    size_t input_forwards_size,
1897
    size_t input_backwards_size,
1898
    int flags,
1899
    RE_MATCH_CALLBACK_FUNC callback,
1900
    void* callback_args,
1901
    int* matches)
1902
0
{
1903
0
  const uint8_t* input;
1904
0
  const uint8_t* ip;
1905
1906
0
  uint16_t opcode_args;
1907
0
  uint8_t mask;
1908
0
  uint8_t value;
1909
0
  uint8_t character_size;
1910
1911
0
  RE_FIBER_LIST fibers;
1912
0
  RE_FIBER* fiber;
1913
0
  RE_FIBER* next_fiber;
1914
1915
0
  int bytes_matched;
1916
0
  int max_bytes_matched;
1917
1918
0
  int match;
1919
0
  int input_incr;
1920
0
  int action;
1921
0
  int cycle = 0;
1922
1923
0
#define ACTION_NONE      0
1924
0
#define ACTION_KILL      1
1925
0
#define ACTION_KILL_TAIL 2
1926
1927
0
#define prolog                                      \
1928
0
  {                                                 \
1929
0
    if ((bytes_matched >= max_bytes_matched) ||     \
1930
0
        (character_size == 2 && *(input + 1) != 0)) \
1931
0
    {                                               \
1932
0
      action = ACTION_KILL;                         \
1933
0
      break;                                        \
1934
0
    }                                               \
1935
0
  }
1936
1937
0
  if (matches != NULL)
1938
0
    *matches = -1;
1939
1940
0
  if (flags & RE_FLAGS_WIDE)
1941
0
    character_size = 2;
1942
0
  else
1943
0
    character_size = 1;
1944
1945
0
  input = input_data;
1946
0
  input_incr = character_size;
1947
1948
0
  if (flags & RE_FLAGS_BACKWARDS)
1949
0
  {
1950
    // Signedness conversion is sound as long as YR_RE_SCAN_LIMIT <= INT_MAX
1951
0
    max_bytes_matched = (int) yr_min(input_backwards_size, YR_RE_SCAN_LIMIT);
1952
0
    input -= character_size;
1953
0
    input_incr = -input_incr;
1954
0
  }
1955
0
  else
1956
0
  {
1957
    // Signedness conversion is sound as long as YR_RE_SCAN_LIMIT <= INT_MAX
1958
0
    max_bytes_matched = (int) yr_min(input_forwards_size, YR_RE_SCAN_LIMIT);
1959
0
  }
1960
1961
  // Round down max_bytes_matched to a multiple of character_size, this way if
1962
  // character_size is 2 and max_bytes_matched is odd we are ignoring the
1963
  // extra byte which can't match anyways.
1964
1965
0
  max_bytes_matched = max_bytes_matched - max_bytes_matched % character_size;
1966
0
  bytes_matched = 0;
1967
1968
0
  FAIL_ON_ERROR(_yr_re_fiber_create(&context->re_fiber_pool, &fiber));
1969
1970
0
  fiber->ip = code;
1971
0
  fibers.head = fiber;
1972
0
  fibers.tail = fiber;
1973
1974
0
  FAIL_ON_ERROR_WITH_CLEANUP(
1975
0
      _yr_re_fiber_sync(
1976
0
          &fibers,
1977
0
          &context->re_fiber_pool,
1978
0
          fiber,
1979
0
          input_data,
1980
0
          input_forwards_size,
1981
0
          input_backwards_size,
1982
0
          bytes_matched,
1983
0
          flags),
1984
0
      _yr_re_fiber_kill_all(&fibers, &context->re_fiber_pool));
1985
1986
0
  while (fibers.head != NULL ||
1987
0
         (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched))
1988
0
  {
1989
0
    fiber = fibers.head;
1990
1991
0
    while (fiber != NULL)
1992
0
    {
1993
0
      next_fiber = fiber->next;
1994
1995
0
      if (_yr_re_fiber_exists(&fibers, fiber, fiber->prev))
1996
0
        _yr_re_fiber_kill(&fibers, &context->re_fiber_pool, fiber);
1997
1998
0
      fiber = next_fiber;
1999
0
    }
2000
2001
0
    fiber = fibers.head;
2002
2003
0
    while (fiber != NULL)
2004
0
    {
2005
0
      ip = fiber->ip;
2006
0
      action = ACTION_NONE;
2007
2008
0
      switch (*ip)
2009
0
      {
2010
0
      case RE_OPCODE_ANY:
2011
0
        prolog;
2012
0
        match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
2013
0
        action = match ? ACTION_NONE : ACTION_KILL;
2014
0
        fiber->ip += 1;
2015
0
        break;
2016
2017
0
      case RE_OPCODE_REPEAT_ANY_GREEDY:
2018
0
      case RE_OPCODE_REPEAT_ANY_UNGREEDY:
2019
0
        prolog;
2020
0
        match = (flags & RE_FLAGS_DOT_ALL) || (*input != 0x0A);
2021
0
        action = match ? ACTION_NONE : ACTION_KILL;
2022
2023
        // The instruction pointer is not incremented here. The current fiber
2024
        // spins in this instruction until reaching the required number of
2025
        // repetitions. The code controlling the number of repetitions is in
2026
        // _yr_re_fiber_sync.
2027
2028
0
        break;
2029
2030
0
      case RE_OPCODE_LITERAL:
2031
0
        prolog;
2032
0
        if (flags & RE_FLAGS_NO_CASE)
2033
0
          match = yr_lowercase[*input] == yr_lowercase[*(ip + 1)];
2034
0
        else
2035
0
          match = (*input == *(ip + 1));
2036
0
        action = match ? ACTION_NONE : ACTION_KILL;
2037
0
        fiber->ip += 2;
2038
0
        break;
2039
2040
0
      case RE_OPCODE_NOT_LITERAL:
2041
0
        prolog;
2042
2043
        // We don't need to take into account the case-insensitive
2044
        // case because this opcode is only used with hex strings,
2045
        // which can't be case-insensitive.
2046
2047
0
        match = (*input != *(ip + 1));
2048
0
        action = match ? ACTION_NONE : ACTION_KILL;
2049
0
        fiber->ip += 2;
2050
0
        break;
2051
2052
0
      case RE_OPCODE_MASKED_LITERAL:
2053
0
        prolog;
2054
0
        opcode_args = yr_unaligned_u16(ip + 1);
2055
0
        mask = opcode_args >> 8;
2056
0
        value = opcode_args & 0xFF;
2057
2058
        // We don't need to take into account the case-insensitive
2059
        // case because this opcode is only used with hex strings,
2060
        // which can't be case-insensitive.
2061
2062
0
        match = ((*input & mask) == value);
2063
0
        action = match ? ACTION_NONE : ACTION_KILL;
2064
0
        fiber->ip += 3;
2065
0
        break;
2066
2067
0
      case RE_OPCODE_MASKED_NOT_LITERAL:
2068
0
        prolog;
2069
0
        opcode_args = yr_unaligned_u16(ip + 1);
2070
0
        mask = opcode_args >> 8;
2071
0
        value = opcode_args & 0xFF;
2072
2073
        // We don't need to take into account the case-insensitive
2074
        // case because this opcode is only used with hex strings,
2075
        // which can't be case-insensitive.
2076
2077
0
        match = ((*input & mask) != value);
2078
0
        action = match ? ACTION_NONE : ACTION_KILL;
2079
0
        fiber->ip += 3;
2080
0
        break;
2081
2082
0
      case RE_OPCODE_CLASS:
2083
0
        prolog;
2084
0
        match = _yr_re_is_char_in_class(
2085
0
            (RE_CLASS*) (ip + 1), *input, flags & RE_FLAGS_NO_CASE);
2086
0
        action = match ? ACTION_NONE : ACTION_KILL;
2087
0
        fiber->ip += (sizeof(RE_CLASS) + 1);
2088
0
        break;
2089
2090
0
      case RE_OPCODE_WORD_CHAR:
2091
0
        prolog;
2092
0
        match = _yr_re_is_word_char(input, character_size);
2093
0
        action = match ? ACTION_NONE : ACTION_KILL;
2094
0
        fiber->ip += 1;
2095
0
        break;
2096
2097
0
      case RE_OPCODE_NON_WORD_CHAR:
2098
0
        prolog;
2099
0
        match = !_yr_re_is_word_char(input, character_size);
2100
0
        action = match ? ACTION_NONE : ACTION_KILL;
2101
0
        fiber->ip += 1;
2102
0
        break;
2103
2104
0
      case RE_OPCODE_SPACE:
2105
0
      case RE_OPCODE_NON_SPACE:
2106
2107
0
        prolog;
2108
2109
0
        switch (*input)
2110
0
        {
2111
0
        case ' ':
2112
0
        case '\t':
2113
0
        case '\r':
2114
0
        case '\n':
2115
0
        case '\v':
2116
0
        case '\f':
2117
0
          match = true;
2118
0
          break;
2119
0
        default:
2120
0
          match = false;
2121
0
        }
2122
2123
0
        if (*ip == RE_OPCODE_NON_SPACE)
2124
0
          match = !match;
2125
2126
0
        action = match ? ACTION_NONE : ACTION_KILL;
2127
0
        fiber->ip += 1;
2128
0
        break;
2129
2130
0
      case RE_OPCODE_DIGIT:
2131
0
        prolog;
2132
0
        match = isdigit(*input);
2133
0
        action = match ? ACTION_NONE : ACTION_KILL;
2134
0
        fiber->ip += 1;
2135
0
        break;
2136
2137
0
      case RE_OPCODE_NON_DIGIT:
2138
0
        prolog;
2139
0
        match = !isdigit(*input);
2140
0
        action = match ? ACTION_NONE : ACTION_KILL;
2141
0
        fiber->ip += 1;
2142
0
        break;
2143
2144
0
      case RE_OPCODE_MATCH:
2145
2146
0
        if (matches != NULL)
2147
0
          *matches = bytes_matched;
2148
2149
0
        if (flags & RE_FLAGS_EXHAUSTIVE)
2150
0
        {
2151
0
          if (callback != NULL)
2152
0
          {
2153
0
            if (flags & RE_FLAGS_BACKWARDS)
2154
0
            {
2155
0
              FAIL_ON_ERROR_WITH_CLEANUP(
2156
0
                  callback(
2157
0
                      input + character_size,
2158
0
                      bytes_matched,
2159
0
                      flags,
2160
0
                      callback_args),
2161
0
                  _yr_re_fiber_kill_all(&fibers, &context->re_fiber_pool));
2162
0
            }
2163
0
            else
2164
0
            {
2165
0
              FAIL_ON_ERROR_WITH_CLEANUP(
2166
0
                  callback(input_data, bytes_matched, flags, callback_args),
2167
0
                  _yr_re_fiber_kill_all(&fibers, &context->re_fiber_pool));
2168
0
            }
2169
0
          }
2170
2171
0
          action = ACTION_KILL;
2172
0
        }
2173
0
        else
2174
0
        {
2175
0
          action = ACTION_KILL_TAIL;
2176
0
        }
2177
2178
0
        break;
2179
2180
0
      default:
2181
0
        assert(false);
2182
0
        action = ACTION_KILL;
2183
0
      }
2184
2185
0
      switch (action)
2186
0
      {
2187
0
      case ACTION_KILL:
2188
0
        fiber = _yr_re_fiber_kill(&fibers, &context->re_fiber_pool, fiber);
2189
0
        break;
2190
2191
0
      case ACTION_KILL_TAIL:
2192
0
        _yr_re_fiber_kill_tail(&fibers, &context->re_fiber_pool, fiber);
2193
0
        fiber = NULL;
2194
0
        break;
2195
2196
0
      default:
2197
0
        next_fiber = fiber->next;
2198
0
        FAIL_ON_ERROR_WITH_CLEANUP(
2199
0
            _yr_re_fiber_sync(
2200
0
                &fibers,
2201
0
                &context->re_fiber_pool,
2202
0
                fiber,
2203
0
                input_data,
2204
0
                input_forwards_size,
2205
0
                input_backwards_size,
2206
0
                bytes_matched + character_size,
2207
0
                flags),
2208
0
            _yr_re_fiber_kill_all(&fibers, &context->re_fiber_pool));
2209
0
        fiber = next_fiber;
2210
0
      }
2211
2212
0
      if (context->timeout > 0ULL && ++cycle == 100)
2213
0
      {
2214
0
        if (yr_stopwatch_elapsed_ns(&context->stopwatch) > context->timeout)
2215
0
        {
2216
0
          _yr_re_fiber_kill_all(&fibers, &context->re_fiber_pool);
2217
0
          return ERROR_SCAN_TIMEOUT;
2218
0
        }
2219
2220
0
        cycle = 0;
2221
0
      }
2222
0
    }
2223
2224
0
    input += input_incr;
2225
0
    bytes_matched += character_size;
2226
2227
0
    if (flags & RE_FLAGS_SCAN && bytes_matched < max_bytes_matched)
2228
0
    {
2229
0
      FAIL_ON_ERROR_WITH_CLEANUP(
2230
0
          _yr_re_fiber_create(&context->re_fiber_pool, &fiber),
2231
0
          _yr_re_fiber_kill_all(&fibers, &context->re_fiber_pool));
2232
2233
0
      fiber->ip = code;
2234
0
      _yr_re_fiber_append(&fibers, fiber);
2235
2236
0
      FAIL_ON_ERROR_WITH_CLEANUP(
2237
0
          _yr_re_fiber_sync(
2238
0
              &fibers,
2239
0
              &context->re_fiber_pool,
2240
0
              fiber,
2241
0
              input_data,
2242
0
              input_forwards_size,
2243
0
              input_backwards_size,
2244
0
              bytes_matched,
2245
0
              flags),
2246
0
          _yr_re_fiber_kill_all(&fibers, &context->re_fiber_pool));
2247
0
    }
2248
0
  }
2249
2250
0
  return ERROR_SUCCESS;
2251
0
}
2252
2253
////////////////////////////////////////////////////////////////////////////////
2254
// Helper function that creates a RE_FAST_EXEC_POSITION by either allocating it
2255
// or reusing a previously allocated one from a pool.
2256
//
2257
static int _yr_re_fast_exec_position_create(
2258
    RE_FAST_EXEC_POSITION_POOL* pool,
2259
    RE_FAST_EXEC_POSITION** new_position)
2260
0
{
2261
0
  RE_FAST_EXEC_POSITION* position;
2262
2263
0
  if (pool->head != NULL)
2264
0
  {
2265
0
    position = pool->head;
2266
0
    pool->head = position->next;
2267
0
  }
2268
0
  else
2269
0
  {
2270
0
    position = (RE_FAST_EXEC_POSITION*) yr_malloc(
2271
0
        sizeof(RE_FAST_EXEC_POSITION));
2272
2273
0
    if (position == NULL)
2274
0
      return ERROR_INSUFFICIENT_MEMORY;
2275
0
  }
2276
2277
0
  position->input = NULL;
2278
0
  position->round = 0;
2279
0
  position->next = NULL;
2280
0
  position->prev = NULL;
2281
2282
0
  *new_position = position;
2283
2284
0
  return ERROR_SUCCESS;
2285
0
}
2286
2287
////////////////////////////////////////////////////////////////////////////////
2288
// Helper function that moves a list of RE_FAST_EXEC_POSITION structures to a
2289
// pool represented by a RE_FAST_EXEC_POSITION_POOL. Receives pointers to the
2290
// pool, the first item, and last item in the list.
2291
//
2292
static void _yr_re_fast_exec_destroy_position_list(
2293
    RE_FAST_EXEC_POSITION_POOL* pool,
2294
    RE_FAST_EXEC_POSITION* first,
2295
    RE_FAST_EXEC_POSITION* last)
2296
0
{
2297
0
  last->next = pool->head;
2298
2299
0
  if (pool->head != NULL)
2300
0
    pool->head->prev = last;
2301
2302
0
  pool->head = first;
2303
0
}
2304
2305
////////////////////////////////////////////////////////////////////////////////
2306
// This function replaces yr_re_exec for regular expressions marked with flag
2307
// RE_FLAGS_FAST_REGEXP. These regular expressions are derived from hex strings
2308
// that don't contain alternatives, like for example:
2309
//
2310
//   { 01 02 03 04 [0-2] 04 05 06 07 }
2311
//
2312
// The regexp's code produced by such strings can be matched by a faster, less
2313
// general algorithm, and it contains only the following opcodes:
2314
//
2315
//   * RE_OPCODE_LITERAL
2316
//   * RE_OPCODE_MASKED_LITERAL,
2317
//   * RE_OPCODE_NOT_LITERAL
2318
//   * RE_OPCODE_MASKED_NOT_LITERAL
2319
//   * RE_OPCODE_ANY
2320
//   * RE_OPCODE_REPEAT_ANY_UNGREEDY
2321
//   * RE_OPCODE_MATCH.
2322
//
2323
// The regexp's code is executed one instruction at time, and the function
2324
// maintains a list of positions within the input for tracking different
2325
// matching alternatives, these positions are described by an instance of
2326
// RE_FAST_EXEC_POSITION. With each instruction the list of positions is
2327
// updated, removing those where the input data doesn't match the current
2328
// instruction, or adding new positions if the instruction is
2329
// RE_OPCODE_REPEAT_ANY_UNGREEDY. The list of positions is maintained sorted
2330
// by the value of the pointer they hold to the input, and it doesn't contain
2331
// duplicated pointer values.
2332
//
2333
int yr_re_fast_exec(
2334
    YR_SCAN_CONTEXT* context,
2335
    const uint8_t* code,
2336
    const uint8_t* input_data,
2337
    size_t input_forwards_size,
2338
    size_t input_backwards_size,
2339
    int flags,
2340
    RE_MATCH_CALLBACK_FUNC callback,
2341
    void* callback_args,
2342
    int* matches)
2343
0
{
2344
0
  RE_REPEAT_ANY_ARGS* repeat_any_args;
2345
2346
  // Pointers to the first and last position in the list.
2347
0
  RE_FAST_EXEC_POSITION* first;
2348
0
  RE_FAST_EXEC_POSITION* last;
2349
2350
0
  int input_incr = flags & RE_FLAGS_BACKWARDS ? -1 : 1;
2351
0
  int bytes_matched;
2352
0
  int max_bytes_matched;
2353
2354
0
  if (flags & RE_FLAGS_BACKWARDS)
2355
0
    max_bytes_matched = (int) yr_min(input_backwards_size, YR_RE_SCAN_LIMIT);
2356
0
  else
2357
0
    max_bytes_matched = (int) yr_min(input_forwards_size, YR_RE_SCAN_LIMIT);
2358
2359
0
  const uint8_t* ip = code;
2360
2361
  // Create the first position in the list, which points to the start of the
2362
  // input data. Intially this is the only position, more positions will be
2363
  // created every time RE_OPCODE_REPEAT_ANY_UNGREEDY is executed.
2364
0
  FAIL_ON_ERROR(_yr_re_fast_exec_position_create(
2365
0
      &context->re_fast_exec_position_pool, &first));
2366
2367
0
  first->round = 0;
2368
0
  first->input = input_data;
2369
0
  first->prev = NULL;
2370
0
  first->next = NULL;
2371
2372
0
  if (flags & RE_FLAGS_BACKWARDS)
2373
0
    first->input--;
2374
2375
  // As we are starting with a single position, the last one and the first one
2376
  // are the same.
2377
0
  last = first;
2378
2379
  // Round is incremented with every regxp instruction.
2380
0
  int round = 0;
2381
2382
  // Keep in the loop until the list of positions gets empty. Positions are
2383
  // removed from the list when they don't match the current instruction in
2384
  // the code.
2385
0
  while (first != NULL)
2386
0
  {
2387
0
    RE_FAST_EXEC_POSITION* current = first;
2388
2389
    // Iterate over all the positions, executing the current instruction at
2390
    // all of them.
2391
0
    while (current != NULL)
2392
0
    {
2393
0
      RE_FAST_EXEC_POSITION* next = current->next;
2394
2395
      // Ignore any position in the list whose round number is different from
2396
      // the current round. This prevents new positions added to the list in
2397
      // this round from being taken into account in this same round.
2398
0
      if (current->round != round)
2399
0
      {
2400
0
        current = next;
2401
0
        continue;
2402
0
      }
2403
2404
0
      bytes_matched = flags & RE_FLAGS_BACKWARDS
2405
0
                          ? (int) (input_data - current->input - 1)
2406
0
                          : (int) (current->input - input_data);
2407
2408
0
      uint16_t opcode_args;
2409
0
      uint8_t mask;
2410
0
      uint8_t value;
2411
2412
0
      bool match = false;
2413
2414
0
      switch (*ip)
2415
0
      {
2416
0
      case RE_OPCODE_ANY:
2417
0
        if (bytes_matched >= max_bytes_matched)
2418
0
          break;
2419
2420
0
        match = true;
2421
0
        current->input += input_incr;
2422
0
        break;
2423
2424
0
      case RE_OPCODE_LITERAL:
2425
0
        if (bytes_matched >= max_bytes_matched)
2426
0
          break;
2427
2428
0
        if (*current->input == *(ip + 1))
2429
0
        {
2430
0
          match = true;
2431
0
          current->input += input_incr;
2432
0
        }
2433
0
        break;
2434
2435
0
      case RE_OPCODE_NOT_LITERAL:
2436
0
        if (bytes_matched >= max_bytes_matched)
2437
0
          break;
2438
2439
0
        if (*current->input != *(ip + 1))
2440
0
        {
2441
0
          match = true;
2442
0
          current->input += input_incr;
2443
0
        }
2444
0
        break;
2445
2446
0
      case RE_OPCODE_MASKED_LITERAL:
2447
0
        if (bytes_matched >= max_bytes_matched)
2448
0
          break;
2449
2450
0
        opcode_args = yr_unaligned_u16(ip + 1);
2451
0
        mask = opcode_args >> 8;
2452
0
        value = opcode_args & 0xFF;
2453
2454
0
        if ((*current->input & mask) == value)
2455
0
        {
2456
0
          match = true;
2457
0
          current->input += input_incr;
2458
0
        }
2459
0
        break;
2460
2461
0
      case RE_OPCODE_MASKED_NOT_LITERAL:
2462
0
        if (bytes_matched >= max_bytes_matched)
2463
0
          break;
2464
2465
0
        opcode_args = yr_unaligned_u16(ip + 1);
2466
0
        mask = opcode_args >> 8;
2467
0
        value = opcode_args & 0xFF;
2468
2469
0
        if ((*current->input & mask) != value)
2470
0
        {
2471
0
          match = true;
2472
0
          current->input += input_incr;
2473
0
        }
2474
0
        break;
2475
2476
0
      case RE_OPCODE_REPEAT_ANY_UNGREEDY:
2477
0
        repeat_any_args = (RE_REPEAT_ANY_ARGS*) (ip + 1);
2478
2479
0
        if (bytes_matched + repeat_any_args->min >= max_bytes_matched)
2480
0
          break;
2481
2482
0
        match = true;
2483
2484
0
        const uint8_t* next_opcode = ip + 1 + sizeof(RE_REPEAT_ANY_ARGS);
2485
2486
        // insertion_point indicates the item in the list of inputs after which
2487
        // the newly created inputs will be inserted.
2488
0
        RE_FAST_EXEC_POSITION* insertion_point = current;
2489
2490
0
        for (int j = repeat_any_args->min + 1; j <= repeat_any_args->max; j++)
2491
0
        {
2492
          // bytes_matched is the number of bytes matched so far, and j is the
2493
          // minimum number of bytes that are still pending to match. If these
2494
          // two numbers sum more than the maximum number of bytes that can be
2495
          // matched the loop can be aborted. The position that we were about
2496
          // to create can't lead to a match without exceeding
2497
          // max_bytes_matched.
2498
0
          if (bytes_matched + j >= max_bytes_matched)
2499
0
            break;
2500
2501
0
          const uint8_t* next_input = current->input + j * input_incr;
2502
2503
          // Find the point where next_input should be inserted. The list is
2504
          // kept sorted by pointer in increasing order, the insertion point is
2505
          // an item that has a pointer lower or equal than next_input, but
2506
          // whose next item have a pointer that is larger.
2507
0
          while (insertion_point->next != NULL &&
2508
0
                 insertion_point->next->input <= next_input)
2509
0
          {
2510
0
            insertion_point = insertion_point->next;
2511
0
          }
2512
2513
          // If the input already exists for the next round, we don't need to
2514
          // insert it.
2515
0
          if (insertion_point->round == round + 1 &&
2516
0
              insertion_point->input == next_input)
2517
0
            continue;
2518
2519
          // The next opcode is RE_OPCODE_LITERAL, but the literal doesn't
2520
          // match with the byte at next_input, we don't need to add this
2521
          // input to the list as we already know that it won't match in the
2522
          // next round and will be deleted from the list anyways.
2523
0
          if (*(next_opcode) == RE_OPCODE_LITERAL &&
2524
0
              *(next_opcode + 1) != *next_input)
2525
0
            continue;
2526
2527
0
          RE_FAST_EXEC_POSITION* new_input;
2528
2529
0
          FAIL_ON_ERROR_WITH_CLEANUP(
2530
0
              _yr_re_fast_exec_position_create(
2531
0
                  &context->re_fast_exec_position_pool, &new_input),
2532
              // Cleanup
2533
0
              _yr_re_fast_exec_destroy_position_list(
2534
0
                  &context->re_fast_exec_position_pool, first, last));
2535
2536
0
          new_input->input = next_input;
2537
0
          new_input->round = round + 1;
2538
0
          new_input->prev = insertion_point;
2539
0
          new_input->next = insertion_point->next;
2540
0
          insertion_point->next = new_input;
2541
2542
0
          if (new_input->next != NULL)
2543
0
            new_input->next->prev = new_input;
2544
2545
0
          if (insertion_point == last)
2546
0
            last = new_input;
2547
0
        }
2548
2549
0
        current->input += input_incr * repeat_any_args->min;
2550
0
        break;
2551
2552
0
      case RE_OPCODE_MATCH:
2553
2554
0
        if (flags & RE_FLAGS_EXHAUSTIVE)
2555
0
        {
2556
0
          FAIL_ON_ERROR_WITH_CLEANUP(
2557
0
              callback(
2558
                  // When matching forwards the matching data always starts at
2559
                  // input_data, when matching backwards it starts at input + 1
2560
                  // or input_data - input_backwards_size if input + 1 is
2561
                  // outside the buffer.
2562
0
                  flags & RE_FLAGS_BACKWARDS
2563
0
                      ? yr_max(
2564
0
                            current->input + 1,
2565
0
                            input_data - input_backwards_size)
2566
0
                      : input_data,
2567
                  // The number of matched bytes should not be larger than
2568
                  // max_bytes_matched.
2569
0
                  yr_min(bytes_matched, max_bytes_matched),
2570
0
                  flags,
2571
0
                  callback_args),
2572
              // Cleanup
2573
0
              _yr_re_fast_exec_destroy_position_list(
2574
0
                  &context->re_fast_exec_position_pool, first, last));
2575
0
        }
2576
0
        else
2577
0
        {
2578
0
          if (matches != NULL)
2579
0
            *matches = bytes_matched;
2580
2581
0
          _yr_re_fast_exec_destroy_position_list(
2582
0
              &context->re_fast_exec_position_pool, first, last);
2583
2584
0
          return ERROR_SUCCESS;
2585
0
        }
2586
0
        break;
2587
2588
0
      default:
2589
0
        printf("non-supported opcode: %d\n", *ip);
2590
0
        assert(false);
2591
0
      }
2592
2593
0
      if (match)
2594
0
      {
2595
0
        current->round = round + 1;
2596
0
      }
2597
0
      else
2598
0
      {
2599
        // Remove current from the list. If the item being removed is the first
2600
        // one or the last one, the first and last pointers should be updated.
2601
        // The removed item is put into the pool for later reuse.
2602
2603
0
        if (current == first)
2604
0
          first = current->next;
2605
2606
0
        if (current == last)
2607
0
          last = current->prev;
2608
2609
0
        if (current->prev != NULL)
2610
0
          current->prev->next = current->next;
2611
2612
0
        if (current->next != NULL)
2613
0
          current->next->prev = current->prev;
2614
2615
0
        current->prev = NULL;
2616
0
        current->next = context->re_fast_exec_position_pool.head;
2617
2618
0
        if (current->next != NULL)
2619
0
          current->next->prev = current;
2620
2621
0
        context->re_fast_exec_position_pool.head = current;
2622
0
      }
2623
2624
0
      current = next;
2625
2626
0
    }  // while (current != NULL)
2627
2628
    // Move instruction pointer (ip) to next instruction. Each opcode has
2629
    // a different size.
2630
0
    switch (*ip)
2631
0
    {
2632
0
    case RE_OPCODE_ANY:
2633
0
      ip += 1;
2634
0
      break;
2635
0
    case RE_OPCODE_LITERAL:
2636
0
    case RE_OPCODE_NOT_LITERAL:
2637
0
      ip += 2;
2638
0
      break;
2639
0
    case RE_OPCODE_MASKED_LITERAL:
2640
0
    case RE_OPCODE_MASKED_NOT_LITERAL:
2641
0
      ip += 3;
2642
0
      break;
2643
0
    case RE_OPCODE_REPEAT_ANY_UNGREEDY:
2644
0
      ip += 1 + sizeof(RE_REPEAT_ANY_ARGS);
2645
0
      break;
2646
0
    case RE_OPCODE_MATCH:
2647
0
      break;
2648
0
    default:
2649
0
      assert(false);
2650
0
    }
2651
2652
0
    round++;
2653
0
  }
2654
2655
  // If this point is reached no matches were found.
2656
2657
0
  if (matches != NULL)
2658
0
    *matches = -1;
2659
2660
0
  return ERROR_SUCCESS;
2661
0
}
2662
2663
static void _yr_re_print_node(RE_NODE* re_node, uint32_t indent)
2664
0
{
2665
0
  RE_NODE* child;
2666
0
  int i;
2667
2668
0
  if (re_node == NULL)
2669
0
    return;
2670
2671
0
  if (indent > 0)
2672
0
    printf("\n%*s", indent, " ");
2673
0
  switch (re_node->type)
2674
0
  {
2675
0
  case RE_NODE_ALT:
2676
0
    printf("Alt(");
2677
0
    _yr_re_print_node(re_node->children_head, indent + 4);
2678
0
    printf(",");
2679
0
    _yr_re_print_node(re_node->children_tail, indent + 4);
2680
0
    printf("\n%*s%s", indent, " ", ")");
2681
0
    break;
2682
2683
0
  case RE_NODE_CONCAT:
2684
0
    printf("Cat(");
2685
0
    child = re_node->children_head;
2686
0
    while (child != NULL)
2687
0
    {
2688
0
      _yr_re_print_node(child, indent + 4);
2689
0
      printf(",");
2690
0
      child = child->next_sibling;
2691
0
    }
2692
0
    printf("\n%*s%s", indent, " ", ")");
2693
0
    break;
2694
2695
0
  case RE_NODE_STAR:
2696
0
    printf("Star(");
2697
0
    _yr_re_print_node(re_node->children_head, indent + 4);
2698
0
    printf(")");
2699
0
    break;
2700
2701
0
  case RE_NODE_PLUS:
2702
0
    printf("Plus(");
2703
0
    _yr_re_print_node(re_node->children_head, indent + 4);
2704
0
    printf(")");
2705
0
    break;
2706
2707
0
  case RE_NODE_LITERAL:
2708
0
    printf("Lit(%c)", re_node->value);
2709
0
    break;
2710
2711
0
  case RE_NODE_NOT_LITERAL:
2712
0
    printf("NotLit(%c)", re_node->value);
2713
0
    break;
2714
2715
0
  case RE_NODE_MASKED_LITERAL:
2716
0
    printf("MaskedLit(%02X,%02X)", re_node->value, re_node->mask);
2717
0
    break;
2718
2719
0
  case RE_NODE_WORD_CHAR:
2720
0
    printf("WordChar");
2721
0
    break;
2722
2723
0
  case RE_NODE_NON_WORD_CHAR:
2724
0
    printf("NonWordChar");
2725
0
    break;
2726
2727
0
  case RE_NODE_SPACE:
2728
0
    printf("Space");
2729
0
    break;
2730
2731
0
  case RE_NODE_NON_SPACE:
2732
0
    printf("NonSpace");
2733
0
    break;
2734
2735
0
  case RE_NODE_DIGIT:
2736
0
    printf("Digit");
2737
0
    break;
2738
2739
0
  case RE_NODE_NON_DIGIT:
2740
0
    printf("NonDigit");
2741
0
    break;
2742
2743
0
  case RE_NODE_ANY:
2744
0
    printf("Any");
2745
0
    break;
2746
2747
0
  case RE_NODE_RANGE:
2748
0
    printf("Range(%d-%d, ", re_node->start, re_node->end);
2749
0
    _yr_re_print_node(re_node->children_head, indent + 4);
2750
0
    printf("\n%*s%s", indent, " ", ")");
2751
0
    break;
2752
2753
0
  case RE_NODE_CLASS:
2754
0
    printf("Class(");
2755
0
    for (i = 0; i < 256; i++)
2756
0
      if (_yr_re_is_char_in_class(re_node->re_class, i, false))
2757
0
        printf("%02X,", i);
2758
0
    printf(")");
2759
0
    break;
2760
2761
0
  case RE_NODE_EMPTY:
2762
0
    printf("Empty");
2763
0
    break;
2764
2765
0
  case RE_NODE_ANCHOR_START:
2766
0
    printf("AnchorStart");
2767
0
    break;
2768
2769
0
  case RE_NODE_ANCHOR_END:
2770
0
    printf("AnchorEnd");
2771
0
    break;
2772
2773
0
  case RE_NODE_WORD_BOUNDARY:
2774
0
    printf("WordBoundary");
2775
0
    break;
2776
2777
0
  case RE_NODE_NON_WORD_BOUNDARY:
2778
0
    printf("NonWordBoundary");
2779
0
    break;
2780
2781
0
  case RE_NODE_RANGE_ANY:
2782
0
    printf("RangeAny");
2783
0
    break;
2784
2785
0
  default:
2786
0
    printf("???");
2787
0
    break;
2788
0
  }
2789
0
}
2790
2791
void yr_re_print(RE_AST* re_ast)
2792
0
{
2793
0
  _yr_re_print_node(re_ast->root_node, 0);
2794
0
}