File: stapregex-parse.cxx

package info (click to toggle)
systemtap 5.1-5
  • links: PTS, VCS
  • area: main
  • in suites: sid, trixie
  • size: 47,964 kB
  • sloc: cpp: 80,838; ansic: 54,757; xml: 49,725; exp: 43,665; sh: 11,527; python: 5,003; perl: 2,252; tcl: 1,312; makefile: 1,006; javascript: 149; lisp: 105; awk: 101; asm: 91; java: 70; sed: 16
file content (623 lines) | stat: -rw-r--r-- 15,709 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
// -*- C++ -*-
// Copyright (C) 2012-2018 Red Hat Inc.
//
// This file is part of systemtap, and is free software.  You can
// redistribute it and/or modify it under the terms of the GNU General
// Public License (GPL); either version 2, or (at your option) any
// later version.
//
// ---
//
// This file incorporates code from the re2c project; please see
// the file README.stapregex for details.

#include "util.h"

#include "stapregex-tree.h"
#include "stapregex-parse.h"

#include <cstdlib>
#include <cstring>
#include <string>

using namespace std;

namespace stapregex {

void print_escaped(std::ostream& o, rchar c)
{
  o << escaped_character((unsigned)c);
}

// ------------------------------------------------------------------------

cursor::cursor() : input(NULL), do_unescape(false), pos(~0),
                   last_pos(~0), finished(false), next_c(0), last_c(0) {}

cursor::cursor(const std::string *input, bool do_unescape)
  : input(input), do_unescape(do_unescape), pos(0), last_pos(0), finished(false)
{
  next_c = 0; last_c = 0;
  finished = ( pos >= input->length() );
}

rchar
cursor::next ()
{
  if (! next_c && finished)
    throw regex_error(_("unexpected end of regex"), pos);
  if (! next_c)
    get_unescaped();

  last_c = next_c;
  // advance by zeroing next_c
  next_c = 0;

  return last_c;
}

rchar
cursor::peek ()
{
  if (! next_c && ! finished)
      get_unescaped();

  // don't advance by zeroing next_c
  last_c = next_c;

  return next_c;
}

bool
cursor::has (unsigned n)
{
  return ( pos <= input->length() - n );
}

/* Systemtap doesn't unescape string literals for us, presuming to
   pass the backslashes intact to a C compiler; hence we need to do
   our own unescaping here.

   This functionality needs to be handled as part of cursor, in order
   to correctly retain the original positions in the string when doing
   error reporting. */
void
cursor::get_unescaped ()
{
  static const char *hex = "0123456789abcdef";
  static const char *oct = "01234567";

  last_pos = pos;
  char c = (*input)[pos];

  if (c != '\\' || !do_unescape)
    {
      next_c = c;
      pos++;
      finished = ( pos >= input->length() );
      return;
    }

  pos++;

  /* Check for improper string end: */
  if (pos >= input->length())
    throw regex_error(_("unexpected end of regex"), pos);

  /* The logic is based on re2c's Scanner::unescape() method;
     the set of accepted escape codes should correspond to
     lexer::scan() in parse.cxx. */
  c = (*input)[pos];
  switch (c)
    {
    case 'a': c = '\a'; break;
    case 'b': c = '\b'; break;
    case 't': c = '\t'; break;
    case 'n': c = '\n'; break;
    case 'v': c = '\v'; break;
    case 'f': c = '\f'; break;
    case 'r': c = '\r'; break;

    case 'x':
      {
      if (pos >= input->length() - 2)
        throw regex_error(_("two hex digits required in escape sequence"), pos);

      const char *d1 = strchr(hex, tolower((*input)[pos+1]));
      const char *d2 = strchr(hex, tolower((*input)[pos+2]));

      if (!d1 || !d2)
        throw regex_error(_("two hex digits required in escape sequence"), pos + (d1 ? 1 : 2));

      c = (char)((d1-hex) << 4) + (char)(d2-hex);
      pos += 2; // skip two chars more than usual
      break;
      }
    case '4' ... '7':
      // XXX: perhaps perform error recovery (slurp 3 octal chars)?
      throw regex_error(_("octal escape sequence out of range"), pos);

    case '0' ... '3':
      {
      if (pos >= input->length() - 2)
        throw regex_error(_("three octal digits required in escape sequence"), pos);

      const char *d0 = strchr(oct, (*input)[pos]);
      const char *d1 = strchr(oct, (*input)[pos+1]);
      const char *d2 = strchr(oct, (*input)[pos+2]);

      if (!d0 || !d1 || !d2)
        throw regex_error(_("three octal digits required in escape sequence"), pos + (d1 ? 1 : 2));
      
      c = (char)((d0-oct) << 6) + (char)((d1-oct) << 3) + (char)(d2-oct);
      pos += 2; // skip two chars more than usual
      break;
      }
    default:
      // do nothing; this removes the backslash from c
      ;
    }

  next_c = c;
  pos++;
  finished = ( pos >= input->length() );
}

// ------------------------------------------------------------------------

regexp *
regex_parser::parse (bool do_tag)
{
  cur = cursor(&input, do_unescape);
  this->do_tag = do_tag;
  num_subexpressions = do_tag ? 1 : 0; // group 0 is guaranteed when using tag

  regexp *result = parse_expr ();

  // PR15065 glom appropriate tag_ops onto the expr (subexpression 0)
  if (do_tag) {
    result = new cat_op(new tag_op(TAG_START(0)), result);
    result = new cat_op(result, new tag_op(TAG_END(0)));
  }

  if (! cur.finished)
    {
      rchar c = cur.peek ();
      if (c == ')')
        parse_error (_("unbalanced ')'"), cur.pos);
      else
        // This should not be possible:
        parse_error ("BUG -- regex parse failed to finish for unknown reasons", cur.pos);
    }

  // PR15065 store num_tags in result
  result->num_tags = 2 * num_subexpressions;
  return result;
}

bool
regex_parser::isspecial (rchar c)
{
  return ( c == '.' || c == '[' || c == '{' || c == '(' || c == ')'
           || c == '\\' || c == '*' || c == '+' || c == '?' || c == '|'
           || c == '^' || c == '$' );
}

void
regex_parser::expect (rchar expected)
{
  rchar c = 0;
  try {
    c = cur.next ();
  } catch (const regex_error &e) {
    parse_error (_F("expected %c, found end of regex", expected));
  }

  if (c != expected)
    parse_error (_F("expected %c, found %c", expected, c));
}

void
regex_parser::parse_error (const string& msg, unsigned pos)
{
  throw regex_error(msg, pos);
}

void
regex_parser::parse_error (const string& msg)
{
  parse_error (msg, cur.last_pos);
}

// ------------------------------------------------------------------------

regexp *
regex_parser::parse_expr ()
{
  regexp *result = parse_term ();

  rchar c = cur.peek ();
  while (c && c == '|')
    {
      cur.next ();
      regexp *alt = parse_term ();
      result = make_alt (result, alt);
      c = cur.peek ();
    }

  return result;
}

regexp *
regex_parser::parse_term ()
{
  regexp *result = parse_factor ();

  rchar c = cur.peek ();
  while (c && c != '|' && c != ')')
    {
      regexp *next = parse_factor ();
      result = new cat_op(result, next);
      c = cur.peek ();
    }

  return result;
}

regexp *
regex_parser::parse_factor ()
{
  regexp *result;
  regexp *old_result = NULL;

  rchar c = cur.peek ();
  if (! c || c == '|' || c == ')')
    {
      result = new null_op;
      return result;
    }
  else if (c == '*' || c == '+' || c == '?' || c == '{')
    {
      parse_error(_F("unexpected '%c'", c));
    }

  if (isspecial (c) && c != '\\')
    cur.next (); // c is guaranteed to be swallowed

  if (c == '.')
    {
      result = make_dot ();
    }
  else if (c == '[')
    {
      result = parse_char_range ();
      expect (']');
    }
  else if (c == '(')
    {
      // Allow non-capturing group (?:...)
      bool do_tag_now = do_tag;
      rchar c2 = cur.peek();
      if (c2 == '?')
        {
          cur.next();
          rchar c3 = cur.peek();
          if (c3 != ':')
            parse_error(_F("unexpected '(?%c'", c3));
          do_tag_now = false;
        }

      // To number tags correctly, reserve a subexpression number here:
      unsigned curr_subexpression = 0;
      if (do_tag_now)
        curr_subexpression = num_subexpressions++;

      result = parse_expr ();

      // PR15065 glom appropriate tag_ops onto the expr
      if (do_tag_now) {
        result = new cat_op(new tag_op(TAG_START(curr_subexpression)), result);
        result = new cat_op(result, new tag_op(TAG_END(curr_subexpression)));
      } else {
        // XXX: workaround for certain error checking test cases which
        // would otherwise produce divergent behaviour without tag_ops
        // (e.g. "^*" vs "(^)*").
        result = new cat_op(result, new null_op);
      }

      expect (')');
    }
  else if (c == '^' || c == '$')
    {
      result = new anchor_op(c);
    }
  else // escaped or ordinary character -- not yet swallowed
    {
      string accumulate;
      rchar d = 0;

      while (c && ( ! isspecial (c) || c == '\\' ))
        {
          if (c == '\\')
            {
              cur.next ();
              c = cur.peek ();
            }

          cur.next ();
          d = cur.peek ();

          /* if we end in a closure, it should only govern the last character */
          if (d == '*' || d == '+' || d == '?' || d == '{')
            {
              /* save the last character */
              d = c; break;
            }

          accumulate.push_back (c);
          c = d; d = 0;
        }

      result = str_to_re (accumulate);

      /* separately deal with the last character before a closure */
      if (d != 0) {
        old_result = result; /* will add it back outside closure at the end */
        result = str_to_re (string(1,d));
      }
    }

  /* parse closures or other postfix operators */
  c = cur.peek ();
  while (c == '*' || c == '+' || c == '?' || c == '{')
    {
      cur.next ();

      /* closure-type operators applied to $^ are definitely not kosher */
      if (result->type_of() == "anchor_op")
        {
          parse_error(_F("postfix closure '%c' applied to anchoring operator", c));
        }

      if (c == '*')
        {
          result = make_alt (new close_op(result), new null_op);
        }
      else if (c == '+')
        {
          result = new close_op(result);
        }
      else if (c == '?')
        {
          result = make_alt (result, new null_op);
        }
      else if (c == '{')
        {
          int minsize = parse_number ();
          int maxsize = -1;

          c = cur.next ();
          if (c == ',')
            {
              c = cur.peek ();
              if (c == '}')
                {
                  cur.next ();
                  maxsize = -1;
                }
              else if (isdigit (c))
                {
                  maxsize = parse_number ();
                  expect ('}');
                }
              else
                parse_error(_("expected '}' or number"), cur.pos);
            }
          else if (c == '}')
            {
              maxsize = minsize;
            }
          else
            parse_error(_("expected ',' or '}'"));

          /* optimize {0,0}, {0,} and {1,} */
          if (!do_tag && minsize == 0 && maxsize == 0)
            {
              // XXX: this optimization is only used when
              // subexpression-extraction is disabled
              delete result;
              result = new null_op;
            }
          else if (minsize == 0 && maxsize == -1)
            {
              result = make_alt (new close_op(result), new null_op);
            }
          else if (minsize == 1 && maxsize == -1)
            {
              result = new close_op(result);
            }
          else
            {
              result = new closev_op(result, minsize, maxsize);
            }
        }
      
      c = cur.peek ();
    }

  if (old_result)
    result = new cat_op(old_result, result);

  return result;
}

regexp *
regex_parser::parse_char_range ()
{
  range *ran = NULL;

  // check for inversion
  bool inv = false;
  rchar c = cur.peek ();
  if (c == '^')
    {
      inv = true;
      cur.next ();
    }

  for (;;)
    {
      // break on string end whenever we encounter it
      if (cur.finished) parse_error(_("unclosed character class"));

      range *add = stapregex_getrange (cur);
      range *new_ran = ( ran != NULL ? range_union(ran, add) : add );
      delete ran; if (new_ran != add) delete add;
      ran = new_ran;

      // break on ']' (except at the start of the class)
      c = cur.peek ();
      if (c == ']')
        break;
    }

  if (inv)
    {
      range *new_ran = range_invert(ran);
      delete ran;
      ran = new_ran;
    }

  if (ran == NULL)
    return new null_op;

  return new match_op(ran);
}

unsigned
regex_parser::parse_number ()
{
  string digits;

  rchar c = cur.peek ();
  while (c && isdigit (c))
    {
      cur.next ();
      digits.push_back (c);
      c = cur.peek ();
    }

  if (digits == "") parse_error(_("expected number"), cur.pos);

  char *endptr = NULL;
  int val = strtol (digits.c_str (), &endptr, 10);

  if (*endptr != '\0' || errno == ERANGE) // paranoid error checking
    parse_error(_F("could not parse number %s", digits.c_str()), cur.pos);
#define MAX_DFA_REPETITIONS 12345
  if (val >= MAX_DFA_REPETITIONS) // XXX: is there a more sensible max size?
    parse_error(_F("%s is too large", digits.c_str()), cur.pos);

  return atoi (digits.c_str ());
}

// ------------------------------------------------------------------------

std::map<std::string, range *> named_char_classes;

range *
named_char_class (const string& name)
{
  // static initialization of table
  if (named_char_classes.empty())
    {
      // original source for these is http://www.regular-expressions.info/posixbrackets.html
      // also checked against (intended to match) the c stdlib isFOO() chr class functions
      named_char_classes["alpha"] = new range("A-Za-z");
      named_char_classes["alnum"] = new range("A-Za-z0-9");
      named_char_classes["blank"] = new range(" \t");
      named_char_classes["cntrl"] = new range("\x01-\x1F\x7F"); // XXX: include \x00 in range? -- probably not!
      named_char_classes["d"] = named_char_classes["digit"] = new range("0-9");
      named_char_classes["xdigit"] = new range("0-9a-fA-F");
      named_char_classes["graph"] = new range("\x21-\x7E");
      named_char_classes["l"] = named_char_classes["lower"] = new range("a-z");
      named_char_classes["print"] = new range("\x20-\x7E");
      named_char_classes["punct"] = new range("!\"#$%&'()*+,./:;<=>?@[\\]^_`{|}~-");
      named_char_classes["s"] = named_char_classes["space"] = new range(" \t\r\n\v\f");
      named_char_classes["u"] = named_char_classes["upper"] = new range("A-Z");
    }

  if (named_char_classes.find(name) == named_char_classes.end())
    {
      throw regex_error (_F("unknown character class '%s'", name.c_str())); // XXX: position unknown
    }

  return new range(*named_char_classes[name]);
}

range *
stapregex_getrange (cursor& cur)
{
  rchar c = cur.peek ();

  if (c == '\\')
    {
      // Grab escaped char regardless of what it is.
      cur.next (); c = cur.peek (); cur.next ();
    }
  else if (c == '[')
    {
      // Check for '[:' digraph.
      rchar old_c = c; cur.next (); c = cur.peek ();

      if (c == ':')
        {
          cur.next (); c = cur.peek (); // skip ':'
          string charclass;

          for (;;)
            {
              if (cur.finished)
                throw regex_error (_F("unclosed character class '[:%s'", charclass.c_str()), cur.pos);

              if (cur.has(2) && c == ':' && (*cur.input)[cur.pos] == ']')
                {
                  cur.next (); cur.next (); // skip ':]'
                  return named_char_class(charclass);
                }

              charclass.push_back(c); cur.next(); c = cur.peek();
            }
        }
      else
        {
          // Backtrack; fall through to processing c.
          c = old_c;
        }
    }
  else
    cur.next ();

  rchar lb = c, ub;

  if (!cur.has(2) || cur.peek () != '-' || (*cur.input)[cur.pos] == ']')
    {
      ub = lb;
    }
  else
    {
      cur.next (); // skip '-'
      ub = cur.peek ();

      if (ub < lb)
        throw regex_error (_F("Inverted character range %c-%c", lb, ub), cur.pos);

      cur.next ();
    }

  return new range(lb, ub);
}

};

/* vim: set sw=2 ts=8 cino=>4,n-2,{2,^-2,t0,(0,u0,w1,M1 : */