File: pcre-c.c

package info (click to toggle)
guestfs-tools 1.52.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 69,236 kB
  • sloc: ansic: 15,698; ml: 15,621; sh: 7,396; xml: 5,478; makefile: 3,601; perl: 1,535; lex: 135; yacc: 128; python: 80
file content (330 lines) | stat: -rw-r--r-- 8,262 bytes parent folder | download | duplicates (3)
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
/* Bindings for Perl-compatible Regular Expressions.
 * Copyright (C) 2017 Red Hat 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 2 of the License, 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.
 */

#include <config.h>

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <assert.h>
#include <pthread.h>

#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>

#include <caml/alloc.h>
#include <caml/callback.h>
#include <caml/custom.h>
#include <caml/fail.h>
#include <caml/memory.h>
#include <caml/mlvalues.h>

#include "cleanups.h"

#pragma GCC diagnostic ignored "-Wmissing-prototypes"

/* Replacement if caml_alloc_initialized_string is missing, added
 * to OCaml runtime in 2017.
 */
#ifndef HAVE_CAML_ALLOC_INITIALIZED_STRING
static inline value
caml_alloc_initialized_string (mlsize_t len, const char *p)
{
  value sv = caml_alloc_string (len);
  memcpy ((char *) String_val (sv), p, len);
  return sv;
}
#endif

/* Data on the most recent match is stored in this thread-local
 * variable.  It is freed either by the next call to PCRE.matches or
 * by (clean) thread exit.
 */
static pthread_key_t last_match;

struct last_match {
  char *subject;                /* subject string */
  pcre2_match_data *match_data; /* match offsets */
  int r;                        /* value returned by pcre2_match */
};

static void
free_last_match (struct last_match *data)
{
  if (data) {
    free (data->subject);
    pcre2_match_data_free (data->match_data);
    free (data);
  }
}

static void lm_init (void) __attribute__((constructor));
static void lm_free (void) __attribute__((destructor));

static void
lm_init (void)
{
  int err;

  err = pthread_key_create (&last_match, (void (*) (void *))free_last_match);
  if (err != 0) abort ();
}

static void
lm_free (void)
{
  pthread_key_delete (last_match);
}

/* Raises PCRE.error (errnum). */
static void
raise_pcre_error (int errnum)
{
  PCRE2_UCHAR err[256];
  value args[2];

  pcre2_get_error_message (errnum, err, sizeof err);

  args[0] = caml_copy_string ((char *) err);
  args[1] = Val_int (errnum);
  caml_raise_with_args (*caml_named_value ("PCRE.Error"), 2, args);
}

/* Raises PCRE.error with a non-library error.  The code field will be 0. */
static void
raise_pcre_other_error (const char *msg)
{
  value args[2];

  args[0] = caml_copy_string (msg);
  args[1] = Val_int (0);
  caml_raise_with_args (*caml_named_value ("PCRE.Error"), 2, args);
}

/* Wrap and unwrap pcre regular expression handles, with a finalizer. */
#define Regexp_val(rv) (*(pcre2_code **)Data_custom_val(rv))

static void
regexp_finalize (value rev)
{
  pcre2_code *re = Regexp_val (rev);
  if (re) pcre2_code_free (re);
}

static struct custom_operations custom_operations = {
  (char *) "pcre_custom_operations",
  regexp_finalize,
  custom_compare_default,
  custom_hash_default,
  custom_serialize_default,
  custom_deserialize_default,
  custom_compare_ext_default,
};

static value
Val_regexp (pcre2_code *re)
{
  CAMLparam0 ();
  CAMLlocal1 (rv);

  rv = caml_alloc_custom (&custom_operations, sizeof (pcre2_code *), 0, 1);
  Regexp_val (rv) = re;

  CAMLreturn (rv);
}

static int
is_Some_true (value v)
{
  return
    v != Val_int (0) /* !None */ &&
    Bool_val (Field (v, 0)) /* Some true */;
}

static int
Optint_val (value intv, int defval)
{
  if (intv == Val_int (0))      /* None */
    return defval;
  else                          /* Some int */
    return Int_val (Field (intv, 0));
}

value
guestfs_int_pcre_compile (value caselessv, value dotallv,
                          value extendedv, value multilinev,
                          value pattv)
{
  CAMLparam4 (caselessv, dotallv, extendedv, multilinev);
  CAMLxparam1 (pattv);
  const char *patt;
  int options = 0;
  pcre2_code *re;
  int errcode = 0;
  PCRE2_SIZE errnum;

  /* Flag parameters are all ‘bool option’, defaulting to false. */
  if (is_Some_true (caselessv))
    options |= PCRE2_CASELESS;
  if (is_Some_true (dotallv))
    options |= PCRE2_DOTALL;
  if (is_Some_true (extendedv))
    options |= PCRE2_EXTENDED;
  if (is_Some_true (multilinev))
    options |= PCRE2_MULTILINE;

  patt = String_val (pattv);

  re = pcre2_compile ((PCRE2_SPTR) patt, strlen (patt),
                      options, &errcode, &errnum, NULL);
  if (re == NULL)
    raise_pcre_error (errcode);

  CAMLreturn (Val_regexp (re));
}

value
guestfs_int_pcre_matches (value offsetv, value rev, value strv)
{
  CAMLparam3 (offsetv, rev, strv);
  pcre2_code *re = Regexp_val (rev);
  struct last_match *m, *oldm;
  size_t len = caml_string_length (strv);
  int r;

  m = calloc (1, sizeof *m);
  if (m == NULL)
    caml_raise_out_of_memory ();

  /* We will need the original subject string when fetching
   * substrings, so take a copy.
   */
  m->subject = malloc (len+1);
  if (m->subject == NULL) {
    free_last_match (m);
    caml_raise_out_of_memory ();
  }
  memcpy (m->subject, String_val (strv), len+1);

  /* Allocate the match_data. */
  m->match_data = pcre2_match_data_create_from_pattern (re, NULL);
  if (m->match_data == NULL) {
    free_last_match (m);
    caml_raise_out_of_memory ();
  }

  m->r = pcre2_match (re, (PCRE2_SPTR) m->subject, len,
                      Optint_val (offsetv, 0), 0,
                      m->match_data, NULL);
  if (m->r < 0 && m->r != PCRE2_ERROR_NOMATCH) {
    int ret = m->r;
    free_last_match (m);
    raise_pcre_error (ret);
  }

  /* This error would indicate that pcre_exec ran out of space in the
   * vector.  However if we are calculating the size of the vector
   * correctly above, then this should never happen.
   */
  assert (m->r != 0);

  r = m->r != PCRE2_ERROR_NOMATCH;

  /* Replace the old TLS match data, but only if we're going
   * to return a match.
   */
  if (r) {
    oldm = pthread_getspecific (last_match);
    free_last_match (oldm);
    pthread_setspecific (last_match, m);
  }
  else
    free_last_match (m);

  CAMLreturn (r ? Val_true : Val_false);
}

value
guestfs_int_pcre_sub (value nv)
{
  CAMLparam1 (nv);
  const int n = Int_val (nv);
  CAMLlocal1 (strv);
  const struct last_match *m = pthread_getspecific (last_match);
  PCRE2_SIZE len;
  int r;

  if (m == NULL)
    raise_pcre_other_error ("PCRE.sub called without calling PCRE.matches");

  if (n < 0)
    caml_invalid_argument ("PCRE.sub: n must be >= 0");

  r = pcre2_substring_length_bynumber (m->match_data, n, &len);
  if (r == PCRE2_ERROR_NOSUBSTRING || r == PCRE2_ERROR_UNSET)
    caml_raise_not_found ();
  if (r < 0)
    raise_pcre_error (r);

  strv = caml_alloc_string (len);

  /* This is fine.  OCaml allocates space for the trailing \0
   * and pcre expects that the buffer will be large enough to
   * store it.
   */
  len++;

  r = pcre2_substring_copy_bynumber (m->match_data, n,
                                     (PCRE2_UCHAR *) String_val (strv),
                                     &len);
  if (r < 0)
    raise_pcre_error (r);

  CAMLreturn (strv);
}

value
guestfs_int_pcre_subi (value nv)
{
  CAMLparam1 (nv);
  const int n = Int_val (nv);
  CAMLlocal1 (rv);
  const struct last_match *m = pthread_getspecific (last_match);
  PCRE2_SIZE *vec;

  if (m == NULL)
    raise_pcre_other_error ("PCRE.subi called without calling PCRE.matches");

  if (n < 0)
    caml_invalid_argument ("PCRE.subi: n must be >= 0");

  /* eg if there are 2 captures, m->r == 3, and valid values of n are
   * 0, 1 or 2.
   */
  if (n >= m->r)
    caml_raise_not_found ();

  vec = pcre2_get_ovector_pointer (m->match_data);

  rv = caml_alloc (2, 0);
  Store_field (rv, 0, Val_int (vec[n*2]));
  Store_field (rv, 1, Val_int (vec[n*2+1]));

  CAMLreturn (rv);
}