File: pcresearch.c

package info (click to toggle)
grep 2.27-2
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 12,844 kB
  • ctags: 7,321
  • sloc: ansic: 69,540; sh: 10,958; perl: 564; makefile: 363; awk: 71; sed: 16
file content (392 lines) | stat: -rw-r--r-- 11,798 bytes parent folder | download
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
/* pcresearch.c - searching subroutines using PCRE for grep.
   Copyright 2000, 2007, 2009-2016 Free Software Foundation, Inc.

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 3, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA
   02110-1301, USA.  */

/* Written August 1992 by Mike Haertel. */

#include <config.h>
#include "search.h"
#include "die.h"

#if HAVE_LIBPCRE
# include <pcre.h>
# ifdef HAVE_DYNAMIC_LIBPCRE
#  include <dlfcn.h>
# endif

/* This must be at least 2; everything after that is for performance
   in pcre_exec.  */
enum { NSUB = 300 };

/* Compiled internal form of a Perl regular expression.  */
static pcre *cre;

/* Additional information about the pattern.  */
static pcre_extra *extra;

# ifndef PCRE_STUDY_JIT_COMPILE
#  define PCRE_STUDY_JIT_COMPILE 0
# endif

# if PCRE_STUDY_JIT_COMPILE
/* Maximum size of the JIT stack.  */
static int jit_stack_size;
# endif

/* Match the already-compiled PCRE pattern against the data in SUBJECT,
   of size SEARCH_BYTES and starting with offset SEARCH_OFFSET, with
   options OPTIONS, and storing resulting matches into SUB.  Return
   the (nonnegative) match location or a (negative) error number.  */
static int
jit_exec (char const *subject, int search_bytes, int search_offset,
          int options, int *sub)
{
  while (true)
    {
      int e = pcre_exec (cre, extra, subject, search_bytes, search_offset,
                         options, sub, NSUB);

# if PCRE_STUDY_JIT_COMPILE
      if (e == PCRE_ERROR_JIT_STACKLIMIT
          && 0 < jit_stack_size && jit_stack_size <= INT_MAX / 2)
        {
          int old_size = jit_stack_size;
          int new_size = jit_stack_size = old_size * 2;
          static pcre_jit_stack *jit_stack;
          if (jit_stack)
            pcre_jit_stack_free (jit_stack);
          jit_stack = pcre_jit_stack_alloc (old_size, new_size);
          if (!jit_stack)
            die (EXIT_TROUBLE, 0,
                 _("failed to allocate memory for the PCRE JIT stack"));
          pcre_assign_jit_stack (extra, NULL, jit_stack);
          continue;
        }
# endif

      return e;
    }
}

#endif

#if HAVE_LIBPCRE
/* Table, indexed by ! (flag & PCRE_NOTBOL), of whether the empty
   string matches when that flag is used.  */
static int empty_match[2];
#endif

#ifdef HAVE_DYNAMIC_LIBPCRE

# define pcre_compile dl_pcre_compile
# define pcre_study dl_pcre_study
# define pcre_exec dl_pcre_exec
# define pcre_maketables dl_pcre_maketables
# define pcre_fullinfo dl_pcre_fullinfo
# define pcre_jit_stack_alloc dl_pcre_jit_stack_alloc
# define pcre_assign_jit_stack dl_pcre_assign_jit_stack

static pcre *(*pcre_compile)(const char *pattern, int options,
const char **errptr, int *erroffset,
                               const unsigned char *tableptr);
static pcre_extra *(*pcre_study)(const pcre *code, int options,
                                   const char **errptr);
static int (*pcre_exec)(const pcre *code, const pcre_extra *extra,
                          const char *subject, int length, int startoffset,
                          int options, int *ovector, int ovecsize);
static const unsigned char *(*pcre_maketables)(void);

static int (*pcre_fullinfo)(const pcre *, const pcre_extra *, int,
                  void *);

static pcre_jit_stack *(*pcre_jit_stack_alloc)(int, int);

static void (*pcre_assign_jit_stack)(pcre_extra *,
                  pcre_jit_callback, void *);

static int
map_pcre(void)
{
  void *library;

  if (pcre_maketables)
    return 1;

  if (!(library = dlopen("libpcre.so.3", RTLD_NOW)))
    return 0;

  if (!(pcre_compile = dlsym(library, "pcre_compile")))
    return 0;
  if (!(pcre_study = dlsym(library, "pcre_study")))
    return 0;
  if (!(pcre_exec = dlsym(library, "pcre_exec")))
    return 0;
  if (!(pcre_maketables = dlsym(library, "pcre_maketables")))
    return 0;
  if (!(pcre_fullinfo = dlsym(library, "pcre_fullinfo")))
    return 0;
  if (!(pcre_jit_stack_alloc = dlsym(library, "pcre_jit_stack_alloc")))
    return 0;
  if (!(pcre_assign_jit_stack = dlsym(library, "pcre_assign_jit_stack")))
    return 0;

  return 1;
}

#else
#define map_pcre() (1)
#endif /* HAVE_DYNAMIC_LIBPCRE */

void
Pcompile (char const *pattern, size_t size)
{
#if !HAVE_LIBPCRE
  die (EXIT_TROUBLE, 0,
       _("support for the -P option is not compiled into "
         "this --disable-perl-regexp binary"));
#else
  int e;
  char const *ep;
  static char const wprefix[] = "(?<!\\w)(?:";
  static char const wsuffix[] = ")(?!\\w)";
  static char const xprefix[] = "^(?:";
  static char const xsuffix[] = ")$";
  int fix_len_max = MAX (sizeof wprefix - 1 + sizeof wsuffix - 1,
                         sizeof xprefix - 1 + sizeof xsuffix - 1);
  char *re = xnmalloc (4, size + (fix_len_max + 4 - 1) / 4);
  int flags = PCRE_DOLLAR_ENDONLY | (match_icase ? PCRE_CASELESS : 0);
  char const *patlim = pattern + size;
  char *n = re;
  char const *p;
  char const *pnul;

  if (1 < MB_CUR_MAX)
    {
      if (! localeinfo.using_utf8)
        die (EXIT_TROUBLE, 0, _("-P supports only unibyte and UTF-8 locales"));
      flags |= PCRE_UTF8;
    }

  if (!map_pcre ())
    die (EXIT_TROUBLE, 0, "%s",
      _("The -P option is not supported: libpcre.so.3 is not available"));

  /* FIXME: Remove this restriction.  */
  if (memchr (pattern, '\n', size))
    die (EXIT_TROUBLE, 0, _("the -P option only supports a single pattern"));

  *n = '\0';
  if (match_words)
    strcpy (n, wprefix);
  if (match_lines)
    strcpy (n, xprefix);
  n += strlen (n);

  /* The PCRE interface doesn't allow NUL bytes in the pattern, so
     replace each NUL byte in the pattern with the four characters
     "\000", removing a preceding backslash if there are an odd
     number of backslashes before the NUL.  */
  for (p = pattern; (pnul = memchr (p, '\0', patlim - p)); p = pnul + 1)
    {
      memcpy (n, p, pnul - p);
      n += pnul - p;
      for (p = pnul; pattern < p && p[-1] == '\\'; p--)
        continue;
      n -= (pnul - p) & 1;
      strcpy (n, "\\000");
      n += 4;
    }

  memcpy (n, p, patlim - p);
  n += patlim - p;
  *n = '\0';
  if (match_words)
    strcpy (n, wsuffix);
  if (match_lines)
    strcpy (n, xsuffix);

  cre = pcre_compile (re, flags, &ep, &e, pcre_maketables ());
  if (!cre)
    die (EXIT_TROUBLE, 0, "%s", ep);

  extra = pcre_study (cre, PCRE_STUDY_JIT_COMPILE, &ep);
  if (ep)
    die (EXIT_TROUBLE, 0, "%s", ep);

# if PCRE_STUDY_JIT_COMPILE
  if (pcre_fullinfo (cre, extra, PCRE_INFO_JIT, &e))
    die (EXIT_TROUBLE, 0, _("internal error (should never happen)"));

  /* The PCRE documentation says that a 32 KiB stack is the default.  */
  if (e)
    jit_stack_size = 32 << 10;
# endif

  free (re);

  int sub[NSUB];
  empty_match[false] = pcre_exec (cre, extra, "", 0, 0,
                                  PCRE_NOTBOL, sub, NSUB);
  empty_match[true] = pcre_exec (cre, extra, "", 0, 0, 0, sub, NSUB);
#endif /* HAVE_LIBPCRE */
}

size_t
Pexecute (char const *buf, size_t size, size_t *match_size,
          char const *start_ptr)
{
#if !HAVE_LIBPCRE
  /* We can't get here, because Pcompile would have been called earlier.  */
  die (EXIT_TROUBLE, 0, _("internal error"));
#else
  int sub[NSUB];
  char const *p = start_ptr ? start_ptr : buf;
  bool bol = p[-1] == eolbyte;
  char const *line_start = buf;
  int e = PCRE_ERROR_NOMATCH;
  char const *line_end;

  /* The search address to pass to pcre_exec.  This is the start of
     the buffer, or just past the most-recently discovered encoding
     error or line end.  */
  char const *subject = buf;

  do
    {
      /* Search line by line.  Although this code formerly used
         PCRE_MULTILINE for performance, the performance wasn't always
         better and the correctness issues were too puzzling.  See
         Bug#22655.  */
      line_end = memchr (p, eolbyte, buf + size - p);
      if (INT_MAX < line_end - p)
        die (EXIT_TROUBLE, 0, _("exceeded PCRE's line length limit"));

      for (;;)
        {
          /* Skip past bytes that are easily determined to be encoding
             errors, treating them as data that cannot match.  This is
             faster than having pcre_exec check them.  */
          while (localeinfo.sbclen[to_uchar (*p)] == -1)
            {
              p++;
              subject = p;
              bol = false;
            }

          int search_offset = p - subject;

          /* Check for an empty match; this is faster than letting
             pcre_exec do it.  */
          if (p == line_end)
            {
              sub[0] = sub[1] = search_offset;
              e = empty_match[bol];
              break;
            }

          int options = 0;
          if (!bol)
            options |= PCRE_NOTBOL;

          e = jit_exec (subject, line_end - subject, search_offset,
                        options, sub);
          if (e != PCRE_ERROR_BADUTF8)
            break;
          int valid_bytes = sub[0];

          if (search_offset <= valid_bytes)
            {
              /* Try to match the string before the encoding error.  */
              if (valid_bytes == 0)
                {
                  /* Handle the empty-match case specially, for speed.
                     This optimization is valid if VALID_BYTES is zero,
                     which means SEARCH_OFFSET is also zero.  */
                  sub[1] = 0;
                  e = empty_match[bol];
                }
              else
                e = jit_exec (subject, valid_bytes, search_offset,
                              options | PCRE_NO_UTF8_CHECK | PCRE_NOTEOL, sub);

              if (e != PCRE_ERROR_NOMATCH)
                break;

              /* Treat the encoding error as data that cannot match.  */
              p = subject + valid_bytes + 1;
              bol = false;
            }

          subject += valid_bytes + 1;
        }

      if (e != PCRE_ERROR_NOMATCH)
        break;
      bol = true;
      p = subject = line_start = line_end + 1;
    }
  while (p < buf + size);

  if (e <= 0)
    {
      switch (e)
        {
        case PCRE_ERROR_NOMATCH:
          break;

        case PCRE_ERROR_NOMEMORY:
          die (EXIT_TROUBLE, 0, _("memory exhausted"));

# if PCRE_STUDY_JIT_COMPILE
        case PCRE_ERROR_JIT_STACKLIMIT:
          die (EXIT_TROUBLE, 0, _("exhausted PCRE JIT stack"));
# endif

        case PCRE_ERROR_MATCHLIMIT:
          die (EXIT_TROUBLE, 0, _("exceeded PCRE's backtracking limit"));

        default:
          /* For now, we lump all remaining PCRE failures into this basket.
             If anyone cares to provide sample grep usage that can trigger
             particular PCRE errors, we can add to the list (above) of more
             detailed diagnostics.  */
          die (EXIT_TROUBLE, 0, _("internal PCRE error: %d"), e);
        }

      return -1;
    }
  else
    {
      char const *matchbeg = subject + sub[0];
      char const *matchend = subject + sub[1];
      char const *beg;
      char const *end;
      if (start_ptr)
        {
          beg = matchbeg;
          end = matchend;
        }
      else
        {
          beg = line_start;
          end = line_end + 1;
        }
      *match_size = end - beg;
      return beg - buf;
    }
#endif
}