1 #include <stddef.h>
2 #include <stdio.h>
3 #include <string.h>
4
5 #include "regex.h"
6
7 static struct rerr {
8 int code;
9 char *name;
10 char *explain;
11 } rerrs[] = {
12 {REG_OKAY, "REG_OKAY", "no errors detected"},
13 {REG_NOMATCH, "REG_NOMATCH", "regexec() failed to match"},
14 {REG_BADPAT, "REG_BADPAT", "invalid regular expression"},
15 {REG_ECOLLATE, "REG_ECOLLATE", "invalid collating element"},
16 {REG_ECTYPE, "REG_ECTYPE", "invalid character class"},
17 {REG_EESCAPE, "REG_EESCAPE", "trailing backslash (\\)"},
18 {REG_ESUBREG, "REG_ESUBREG", "invalid backreference number"},
19 {REG_EBRACK, "REG_EBRACK", "brackets ([ ]) not balanced"},
20 {REG_EPAREN, "REG_EPAREN", "parentheses not balanced"},
21 {REG_EBRACE, "REG_EBRACE", "braces not balanced"},
22 {REG_BADBR, "REG_BADBR", "invalid repetition count(s)"},
23 {REG_ERANGE, "REG_ERANGE", "invalid character range"},
24 {REG_ESPACE, "REG_ESPACE", "out of memory"},
25 {REG_BADRPT, "REG_BADRPT", "repetition-operator operand invalid"},
26 {REG_EMPTY, "REG_EMPTY", "empty (sub)expression"},
27 {REG_ASSERT, "REG_ASSERT", "\"can't happen\" -- you found a bug"},
28 {REG_INVARG, "REG_INVARG", "invalid argument to regex routine"},
29 {-1, "", "*** unknown regexp error code ***"},
30 };
31
32 static size_t
set_result(char * errbuf,size_t errbuf_size,char * result)33 set_result(char *errbuf, size_t errbuf_size, char *result) {
34 size_t result_len = strlen(result);
35 if (errbuf_size > 0) {
36 size_t copy_len = result_len < errbuf_size ? result_len : errbuf_size - 1;
37 memcpy(errbuf, result, copy_len);
38 errbuf[copy_len] = '\0';
39 }
40 return result_len + 1;
41 }
42
43 /*
44 - regerror - the interface to error numbers
45 */
46 size_t
regerror(int errorcode,const regex_t * preg,char * errbuf,size_t errbuf_size)47 regerror(int errorcode, const regex_t *preg, char *errbuf, size_t errbuf_size)
48 {
49 struct rerr *r;
50 char convbuf[50];
51
52 if (errorcode == REG_ATOI) {
53 if (preg == NULL || preg->re_endp == NULL)
54 return set_result(errbuf, errbuf_size, "0");
55 for (r = rerrs; r->code >= 0; r++)
56 if (strcmp(r->name, preg->re_endp) == 0)
57 break;
58 if (r->code < 0)
59 return set_result(errbuf, errbuf_size, "0");
60 snprintf(convbuf, sizeof convbuf, "%d", r->code);
61 return set_result(errbuf, errbuf_size, convbuf);
62 }
63 else {
64 int target = errorcode &~ REG_ITOA;
65
66 for (r = rerrs; r->code >= 0; r++)
67 if (r->code == target)
68 break;
69 if (errorcode & REG_ITOA) {
70 if (r->code >= 0)
71 return set_result(errbuf, errbuf_size, r->name);
72 snprintf(convbuf, sizeof convbuf, "REG_0x%x", target);
73 return set_result(errbuf, errbuf_size, convbuf);
74 }
75 return set_result(errbuf, errbuf_size, r->explain);
76 }
77 }
78