grep.con commit Extract Git::SVN from git-svn into its own .pm file. (29499c0)
   1#include "cache.h"
   2#include "grep.h"
   3#include "userdiff.h"
   4#include "xdiff-interface.h"
   5
   6static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
   7                                        const char *origin, int no,
   8                                        enum grep_pat_token t,
   9                                        enum grep_header_field field)
  10{
  11        struct grep_pat *p = xcalloc(1, sizeof(*p));
  12        p->pattern = xmemdupz(pat, patlen);
  13        p->patternlen = patlen;
  14        p->origin = origin;
  15        p->no = no;
  16        p->token = t;
  17        p->field = field;
  18        return p;
  19}
  20
  21static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
  22{
  23        **tail = p;
  24        *tail = &p->next;
  25        p->next = NULL;
  26
  27        switch (p->token) {
  28        case GREP_PATTERN: /* atom */
  29        case GREP_PATTERN_HEAD:
  30        case GREP_PATTERN_BODY:
  31                for (;;) {
  32                        struct grep_pat *new_pat;
  33                        size_t len = 0;
  34                        char *cp = p->pattern + p->patternlen, *nl = NULL;
  35                        while (++len <= p->patternlen) {
  36                                if (*(--cp) == '\n') {
  37                                        nl = cp;
  38                                        break;
  39                                }
  40                        }
  41                        if (!nl)
  42                                break;
  43                        new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
  44                                                  p->no, p->token, p->field);
  45                        new_pat->next = p->next;
  46                        if (!p->next)
  47                                *tail = &new_pat->next;
  48                        p->next = new_pat;
  49                        *nl = '\0';
  50                        p->patternlen -= len;
  51                }
  52                break;
  53        default:
  54                break;
  55        }
  56}
  57
  58void append_header_grep_pattern(struct grep_opt *opt,
  59                                enum grep_header_field field, const char *pat)
  60{
  61        struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
  62                                             GREP_PATTERN_HEAD, field);
  63        do_append_grep_pat(&opt->header_tail, p);
  64}
  65
  66void append_grep_pattern(struct grep_opt *opt, const char *pat,
  67                         const char *origin, int no, enum grep_pat_token t)
  68{
  69        append_grep_pat(opt, pat, strlen(pat), origin, no, t);
  70}
  71
  72void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
  73                     const char *origin, int no, enum grep_pat_token t)
  74{
  75        struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
  76        do_append_grep_pat(&opt->pattern_tail, p);
  77}
  78
  79struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
  80{
  81        struct grep_pat *pat;
  82        struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
  83        *ret = *opt;
  84
  85        ret->pattern_list = NULL;
  86        ret->pattern_tail = &ret->pattern_list;
  87
  88        for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
  89        {
  90                if(pat->token == GREP_PATTERN_HEAD)
  91                        append_header_grep_pattern(ret, pat->field,
  92                                                   pat->pattern);
  93                else
  94                        append_grep_pat(ret, pat->pattern, pat->patternlen,
  95                                        pat->origin, pat->no, pat->token);
  96        }
  97
  98        return ret;
  99}
 100
 101static NORETURN void compile_regexp_failed(const struct grep_pat *p,
 102                const char *error)
 103{
 104        char where[1024];
 105
 106        if (p->no)
 107                sprintf(where, "In '%s' at %d, ", p->origin, p->no);
 108        else if (p->origin)
 109                sprintf(where, "%s, ", p->origin);
 110        else
 111                where[0] = 0;
 112
 113        die("%s'%s': %s", where, p->pattern, error);
 114}
 115
 116#ifdef USE_LIBPCRE
 117static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
 118{
 119        const char *error;
 120        int erroffset;
 121        int options = PCRE_MULTILINE;
 122
 123        if (opt->ignore_case)
 124                options |= PCRE_CASELESS;
 125
 126        p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
 127                        NULL);
 128        if (!p->pcre_regexp)
 129                compile_regexp_failed(p, error);
 130
 131        p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
 132        if (!p->pcre_extra_info && error)
 133                die("%s", error);
 134}
 135
 136static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
 137                regmatch_t *match, int eflags)
 138{
 139        int ovector[30], ret, flags = 0;
 140
 141        if (eflags & REG_NOTBOL)
 142                flags |= PCRE_NOTBOL;
 143
 144        ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
 145                        0, flags, ovector, ARRAY_SIZE(ovector));
 146        if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
 147                die("pcre_exec failed with error code %d", ret);
 148        if (ret > 0) {
 149                ret = 0;
 150                match->rm_so = ovector[0];
 151                match->rm_eo = ovector[1];
 152        }
 153
 154        return ret;
 155}
 156
 157static void free_pcre_regexp(struct grep_pat *p)
 158{
 159        pcre_free(p->pcre_regexp);
 160        pcre_free(p->pcre_extra_info);
 161}
 162#else /* !USE_LIBPCRE */
 163static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
 164{
 165        die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
 166}
 167
 168static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
 169                regmatch_t *match, int eflags)
 170{
 171        return 1;
 172}
 173
 174static void free_pcre_regexp(struct grep_pat *p)
 175{
 176}
 177#endif /* !USE_LIBPCRE */
 178
 179static int is_fixed(const char *s, size_t len)
 180{
 181        size_t i;
 182
 183        /* regcomp cannot accept patterns with NULs so we
 184         * consider any pattern containing a NUL fixed.
 185         */
 186        if (memchr(s, 0, len))
 187                return 1;
 188
 189        for (i = 0; i < len; i++) {
 190                if (is_regex_special(s[i]))
 191                        return 0;
 192        }
 193
 194        return 1;
 195}
 196
 197static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
 198{
 199        int err;
 200
 201        p->word_regexp = opt->word_regexp;
 202        p->ignore_case = opt->ignore_case;
 203
 204        if (opt->fixed || is_fixed(p->pattern, p->patternlen))
 205                p->fixed = 1;
 206        else
 207                p->fixed = 0;
 208
 209        if (p->fixed) {
 210                if (opt->regflags & REG_ICASE || p->ignore_case)
 211                        p->kws = kwsalloc(tolower_trans_tbl);
 212                else
 213                        p->kws = kwsalloc(NULL);
 214                kwsincr(p->kws, p->pattern, p->patternlen);
 215                kwsprep(p->kws);
 216                return;
 217        }
 218
 219        if (opt->pcre) {
 220                compile_pcre_regexp(p, opt);
 221                return;
 222        }
 223
 224        err = regcomp(&p->regexp, p->pattern, opt->regflags);
 225        if (err) {
 226                char errbuf[1024];
 227                regerror(err, &p->regexp, errbuf, 1024);
 228                regfree(&p->regexp);
 229                compile_regexp_failed(p, errbuf);
 230        }
 231}
 232
 233static struct grep_expr *compile_pattern_or(struct grep_pat **);
 234static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
 235{
 236        struct grep_pat *p;
 237        struct grep_expr *x;
 238
 239        p = *list;
 240        if (!p)
 241                return NULL;
 242        switch (p->token) {
 243        case GREP_PATTERN: /* atom */
 244        case GREP_PATTERN_HEAD:
 245        case GREP_PATTERN_BODY:
 246                x = xcalloc(1, sizeof (struct grep_expr));
 247                x->node = GREP_NODE_ATOM;
 248                x->u.atom = p;
 249                *list = p->next;
 250                return x;
 251        case GREP_OPEN_PAREN:
 252                *list = p->next;
 253                x = compile_pattern_or(list);
 254                if (!*list || (*list)->token != GREP_CLOSE_PAREN)
 255                        die("unmatched parenthesis");
 256                *list = (*list)->next;
 257                return x;
 258        default:
 259                return NULL;
 260        }
 261}
 262
 263static struct grep_expr *compile_pattern_not(struct grep_pat **list)
 264{
 265        struct grep_pat *p;
 266        struct grep_expr *x;
 267
 268        p = *list;
 269        if (!p)
 270                return NULL;
 271        switch (p->token) {
 272        case GREP_NOT:
 273                if (!p->next)
 274                        die("--not not followed by pattern expression");
 275                *list = p->next;
 276                x = xcalloc(1, sizeof (struct grep_expr));
 277                x->node = GREP_NODE_NOT;
 278                x->u.unary = compile_pattern_not(list);
 279                if (!x->u.unary)
 280                        die("--not followed by non pattern expression");
 281                return x;
 282        default:
 283                return compile_pattern_atom(list);
 284        }
 285}
 286
 287static struct grep_expr *compile_pattern_and(struct grep_pat **list)
 288{
 289        struct grep_pat *p;
 290        struct grep_expr *x, *y, *z;
 291
 292        x = compile_pattern_not(list);
 293        p = *list;
 294        if (p && p->token == GREP_AND) {
 295                if (!p->next)
 296                        die("--and not followed by pattern expression");
 297                *list = p->next;
 298                y = compile_pattern_and(list);
 299                if (!y)
 300                        die("--and not followed by pattern expression");
 301                z = xcalloc(1, sizeof (struct grep_expr));
 302                z->node = GREP_NODE_AND;
 303                z->u.binary.left = x;
 304                z->u.binary.right = y;
 305                return z;
 306        }
 307        return x;
 308}
 309
 310static struct grep_expr *compile_pattern_or(struct grep_pat **list)
 311{
 312        struct grep_pat *p;
 313        struct grep_expr *x, *y, *z;
 314
 315        x = compile_pattern_and(list);
 316        p = *list;
 317        if (x && p && p->token != GREP_CLOSE_PAREN) {
 318                y = compile_pattern_or(list);
 319                if (!y)
 320                        die("not a pattern expression %s", p->pattern);
 321                z = xcalloc(1, sizeof (struct grep_expr));
 322                z->node = GREP_NODE_OR;
 323                z->u.binary.left = x;
 324                z->u.binary.right = y;
 325                return z;
 326        }
 327        return x;
 328}
 329
 330static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
 331{
 332        return compile_pattern_or(list);
 333}
 334
 335static struct grep_expr *grep_true_expr(void)
 336{
 337        struct grep_expr *z = xcalloc(1, sizeof(*z));
 338        z->node = GREP_NODE_TRUE;
 339        return z;
 340}
 341
 342static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
 343{
 344        struct grep_expr *z = xcalloc(1, sizeof(*z));
 345        z->node = GREP_NODE_OR;
 346        z->u.binary.left = left;
 347        z->u.binary.right = right;
 348        return z;
 349}
 350
 351static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
 352{
 353        struct grep_pat *p;
 354        struct grep_expr *header_expr;
 355        struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
 356        enum grep_header_field fld;
 357
 358        if (!opt->header_list)
 359                return NULL;
 360
 361        for (p = opt->header_list; p; p = p->next) {
 362                if (p->token != GREP_PATTERN_HEAD)
 363                        die("bug: a non-header pattern in grep header list.");
 364                if (p->field < 0 || GREP_HEADER_FIELD_MAX <= p->field)
 365                        die("bug: unknown header field %d", p->field);
 366                compile_regexp(p, opt);
 367        }
 368
 369        for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
 370                header_group[fld] = NULL;
 371
 372        for (p = opt->header_list; p; p = p->next) {
 373                struct grep_expr *h;
 374                struct grep_pat *pp = p;
 375
 376                h = compile_pattern_atom(&pp);
 377                if (!h || pp != p->next)
 378                        die("bug: malformed header expr");
 379                if (!header_group[p->field]) {
 380                        header_group[p->field] = h;
 381                        continue;
 382                }
 383                header_group[p->field] = grep_or_expr(h, header_group[p->field]);
 384        }
 385
 386        header_expr = NULL;
 387
 388        for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
 389                if (!header_group[fld])
 390                        continue;
 391                if (!header_expr)
 392                        header_expr = grep_true_expr();
 393                header_expr = grep_or_expr(header_group[fld], header_expr);
 394        }
 395        return header_expr;
 396}
 397
 398void compile_grep_patterns(struct grep_opt *opt)
 399{
 400        struct grep_pat *p;
 401        struct grep_expr *header_expr = prep_header_patterns(opt);
 402
 403        for (p = opt->pattern_list; p; p = p->next) {
 404                switch (p->token) {
 405                case GREP_PATTERN: /* atom */
 406                case GREP_PATTERN_HEAD:
 407                case GREP_PATTERN_BODY:
 408                        compile_regexp(p, opt);
 409                        break;
 410                default:
 411                        opt->extended = 1;
 412                        break;
 413                }
 414        }
 415
 416        if (opt->all_match || header_expr)
 417                opt->extended = 1;
 418        else if (!opt->extended)
 419                return;
 420
 421        p = opt->pattern_list;
 422        if (p)
 423                opt->pattern_expression = compile_pattern_expr(&p);
 424        if (p)
 425                die("incomplete pattern expression: %s", p->pattern);
 426
 427        if (!header_expr)
 428                return;
 429
 430        if (!opt->pattern_expression)
 431                opt->pattern_expression = header_expr;
 432        else
 433                opt->pattern_expression = grep_or_expr(opt->pattern_expression,
 434                                                       header_expr);
 435        opt->all_match = 1;
 436}
 437
 438static void free_pattern_expr(struct grep_expr *x)
 439{
 440        switch (x->node) {
 441        case GREP_NODE_TRUE:
 442        case GREP_NODE_ATOM:
 443                break;
 444        case GREP_NODE_NOT:
 445                free_pattern_expr(x->u.unary);
 446                break;
 447        case GREP_NODE_AND:
 448        case GREP_NODE_OR:
 449                free_pattern_expr(x->u.binary.left);
 450                free_pattern_expr(x->u.binary.right);
 451                break;
 452        }
 453        free(x);
 454}
 455
 456void free_grep_patterns(struct grep_opt *opt)
 457{
 458        struct grep_pat *p, *n;
 459
 460        for (p = opt->pattern_list; p; p = n) {
 461                n = p->next;
 462                switch (p->token) {
 463                case GREP_PATTERN: /* atom */
 464                case GREP_PATTERN_HEAD:
 465                case GREP_PATTERN_BODY:
 466                        if (p->kws)
 467                                kwsfree(p->kws);
 468                        else if (p->pcre_regexp)
 469                                free_pcre_regexp(p);
 470                        else
 471                                regfree(&p->regexp);
 472                        free(p->pattern);
 473                        break;
 474                default:
 475                        break;
 476                }
 477                free(p);
 478        }
 479
 480        if (!opt->extended)
 481                return;
 482        free_pattern_expr(opt->pattern_expression);
 483}
 484
 485static char *end_of_line(char *cp, unsigned long *left)
 486{
 487        unsigned long l = *left;
 488        while (l && *cp != '\n') {
 489                l--;
 490                cp++;
 491        }
 492        *left = l;
 493        return cp;
 494}
 495
 496static int word_char(char ch)
 497{
 498        return isalnum(ch) || ch == '_';
 499}
 500
 501static void output_color(struct grep_opt *opt, const void *data, size_t size,
 502                         const char *color)
 503{
 504        if (want_color(opt->color) && color && color[0]) {
 505                opt->output(opt, color, strlen(color));
 506                opt->output(opt, data, size);
 507                opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
 508        } else
 509                opt->output(opt, data, size);
 510}
 511
 512static void output_sep(struct grep_opt *opt, char sign)
 513{
 514        if (opt->null_following_name)
 515                opt->output(opt, "\0", 1);
 516        else
 517                output_color(opt, &sign, 1, opt->color_sep);
 518}
 519
 520static void show_name(struct grep_opt *opt, const char *name)
 521{
 522        output_color(opt, name, strlen(name), opt->color_filename);
 523        opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
 524}
 525
 526static int fixmatch(struct grep_pat *p, char *line, char *eol,
 527                    regmatch_t *match)
 528{
 529        struct kwsmatch kwsm;
 530        size_t offset = kwsexec(p->kws, line, eol - line, &kwsm);
 531        if (offset == -1) {
 532                match->rm_so = match->rm_eo = -1;
 533                return REG_NOMATCH;
 534        } else {
 535                match->rm_so = offset;
 536                match->rm_eo = match->rm_so + kwsm.size[0];
 537                return 0;
 538        }
 539}
 540
 541static int regmatch(const regex_t *preg, char *line, char *eol,
 542                    regmatch_t *match, int eflags)
 543{
 544#ifdef REG_STARTEND
 545        match->rm_so = 0;
 546        match->rm_eo = eol - line;
 547        eflags |= REG_STARTEND;
 548#endif
 549        return regexec(preg, line, 1, match, eflags);
 550}
 551
 552static int patmatch(struct grep_pat *p, char *line, char *eol,
 553                    regmatch_t *match, int eflags)
 554{
 555        int hit;
 556
 557        if (p->fixed)
 558                hit = !fixmatch(p, line, eol, match);
 559        else if (p->pcre_regexp)
 560                hit = !pcrematch(p, line, eol, match, eflags);
 561        else
 562                hit = !regmatch(&p->regexp, line, eol, match, eflags);
 563
 564        return hit;
 565}
 566
 567static int strip_timestamp(char *bol, char **eol_p)
 568{
 569        char *eol = *eol_p;
 570        int ch;
 571
 572        while (bol < --eol) {
 573                if (*eol != '>')
 574                        continue;
 575                *eol_p = ++eol;
 576                ch = *eol;
 577                *eol = '\0';
 578                return ch;
 579        }
 580        return 0;
 581}
 582
 583static struct {
 584        const char *field;
 585        size_t len;
 586} header_field[] = {
 587        { "author ", 7 },
 588        { "committer ", 10 },
 589};
 590
 591static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
 592                             enum grep_context ctx,
 593                             regmatch_t *pmatch, int eflags)
 594{
 595        int hit = 0;
 596        int saved_ch = 0;
 597        const char *start = bol;
 598
 599        if ((p->token != GREP_PATTERN) &&
 600            ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
 601                return 0;
 602
 603        if (p->token == GREP_PATTERN_HEAD) {
 604                const char *field;
 605                size_t len;
 606                assert(p->field < ARRAY_SIZE(header_field));
 607                field = header_field[p->field].field;
 608                len = header_field[p->field].len;
 609                if (strncmp(bol, field, len))
 610                        return 0;
 611                bol += len;
 612                saved_ch = strip_timestamp(bol, &eol);
 613        }
 614
 615 again:
 616        hit = patmatch(p, bol, eol, pmatch, eflags);
 617
 618        if (hit && p->word_regexp) {
 619                if ((pmatch[0].rm_so < 0) ||
 620                    (eol - bol) < pmatch[0].rm_so ||
 621                    (pmatch[0].rm_eo < 0) ||
 622                    (eol - bol) < pmatch[0].rm_eo)
 623                        die("regexp returned nonsense");
 624
 625                /* Match beginning must be either beginning of the
 626                 * line, or at word boundary (i.e. the last char must
 627                 * not be a word char).  Similarly, match end must be
 628                 * either end of the line, or at word boundary
 629                 * (i.e. the next char must not be a word char).
 630                 */
 631                if ( ((pmatch[0].rm_so == 0) ||
 632                      !word_char(bol[pmatch[0].rm_so-1])) &&
 633                     ((pmatch[0].rm_eo == (eol-bol)) ||
 634                      !word_char(bol[pmatch[0].rm_eo])) )
 635                        ;
 636                else
 637                        hit = 0;
 638
 639                /* Words consist of at least one character. */
 640                if (pmatch->rm_so == pmatch->rm_eo)
 641                        hit = 0;
 642
 643                if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
 644                        /* There could be more than one match on the
 645                         * line, and the first match might not be
 646                         * strict word match.  But later ones could be!
 647                         * Forward to the next possible start, i.e. the
 648                         * next position following a non-word char.
 649                         */
 650                        bol = pmatch[0].rm_so + bol + 1;
 651                        while (word_char(bol[-1]) && bol < eol)
 652                                bol++;
 653                        eflags |= REG_NOTBOL;
 654                        if (bol < eol)
 655                                goto again;
 656                }
 657        }
 658        if (p->token == GREP_PATTERN_HEAD && saved_ch)
 659                *eol = saved_ch;
 660        if (hit) {
 661                pmatch[0].rm_so += bol - start;
 662                pmatch[0].rm_eo += bol - start;
 663        }
 664        return hit;
 665}
 666
 667static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
 668                           enum grep_context ctx, int collect_hits)
 669{
 670        int h = 0;
 671        regmatch_t match;
 672
 673        if (!x)
 674                die("Not a valid grep expression");
 675        switch (x->node) {
 676        case GREP_NODE_TRUE:
 677                h = 1;
 678                break;
 679        case GREP_NODE_ATOM:
 680                h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
 681                break;
 682        case GREP_NODE_NOT:
 683                h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
 684                break;
 685        case GREP_NODE_AND:
 686                if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
 687                        return 0;
 688                h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
 689                break;
 690        case GREP_NODE_OR:
 691                if (!collect_hits)
 692                        return (match_expr_eval(x->u.binary.left,
 693                                                bol, eol, ctx, 0) ||
 694                                match_expr_eval(x->u.binary.right,
 695                                                bol, eol, ctx, 0));
 696                h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
 697                x->u.binary.left->hit |= h;
 698                h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
 699                break;
 700        default:
 701                die("Unexpected node type (internal error) %d", x->node);
 702        }
 703        if (collect_hits)
 704                x->hit |= h;
 705        return h;
 706}
 707
 708static int match_expr(struct grep_opt *opt, char *bol, char *eol,
 709                      enum grep_context ctx, int collect_hits)
 710{
 711        struct grep_expr *x = opt->pattern_expression;
 712        return match_expr_eval(x, bol, eol, ctx, collect_hits);
 713}
 714
 715static int match_line(struct grep_opt *opt, char *bol, char *eol,
 716                      enum grep_context ctx, int collect_hits)
 717{
 718        struct grep_pat *p;
 719        regmatch_t match;
 720
 721        if (opt->extended)
 722                return match_expr(opt, bol, eol, ctx, collect_hits);
 723
 724        /* we do not call with collect_hits without being extended */
 725        for (p = opt->pattern_list; p; p = p->next) {
 726                if (match_one_pattern(p, bol, eol, ctx, &match, 0))
 727                        return 1;
 728        }
 729        return 0;
 730}
 731
 732static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
 733                              enum grep_context ctx,
 734                              regmatch_t *pmatch, int eflags)
 735{
 736        regmatch_t match;
 737
 738        if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
 739                return 0;
 740        if (match.rm_so < 0 || match.rm_eo < 0)
 741                return 0;
 742        if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
 743                if (match.rm_so > pmatch->rm_so)
 744                        return 1;
 745                if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
 746                        return 1;
 747        }
 748        pmatch->rm_so = match.rm_so;
 749        pmatch->rm_eo = match.rm_eo;
 750        return 1;
 751}
 752
 753static int next_match(struct grep_opt *opt, char *bol, char *eol,
 754                      enum grep_context ctx, regmatch_t *pmatch, int eflags)
 755{
 756        struct grep_pat *p;
 757        int hit = 0;
 758
 759        pmatch->rm_so = pmatch->rm_eo = -1;
 760        if (bol < eol) {
 761                for (p = opt->pattern_list; p; p = p->next) {
 762                        switch (p->token) {
 763                        case GREP_PATTERN: /* atom */
 764                        case GREP_PATTERN_HEAD:
 765                        case GREP_PATTERN_BODY:
 766                                hit |= match_next_pattern(p, bol, eol, ctx,
 767                                                          pmatch, eflags);
 768                                break;
 769                        default:
 770                                break;
 771                        }
 772                }
 773        }
 774        return hit;
 775}
 776
 777static void show_line(struct grep_opt *opt, char *bol, char *eol,
 778                      const char *name, unsigned lno, char sign)
 779{
 780        int rest = eol - bol;
 781        char *line_color = NULL;
 782
 783        if (opt->file_break && opt->last_shown == 0) {
 784                if (opt->show_hunk_mark)
 785                        opt->output(opt, "\n", 1);
 786        } else if (opt->pre_context || opt->post_context || opt->funcbody) {
 787                if (opt->last_shown == 0) {
 788                        if (opt->show_hunk_mark) {
 789                                output_color(opt, "--", 2, opt->color_sep);
 790                                opt->output(opt, "\n", 1);
 791                        }
 792                } else if (lno > opt->last_shown + 1) {
 793                        output_color(opt, "--", 2, opt->color_sep);
 794                        opt->output(opt, "\n", 1);
 795                }
 796        }
 797        if (opt->heading && opt->last_shown == 0) {
 798                output_color(opt, name, strlen(name), opt->color_filename);
 799                opt->output(opt, "\n", 1);
 800        }
 801        opt->last_shown = lno;
 802
 803        if (!opt->heading && opt->pathname) {
 804                output_color(opt, name, strlen(name), opt->color_filename);
 805                output_sep(opt, sign);
 806        }
 807        if (opt->linenum) {
 808                char buf[32];
 809                snprintf(buf, sizeof(buf), "%d", lno);
 810                output_color(opt, buf, strlen(buf), opt->color_lineno);
 811                output_sep(opt, sign);
 812        }
 813        if (opt->color) {
 814                regmatch_t match;
 815                enum grep_context ctx = GREP_CONTEXT_BODY;
 816                int ch = *eol;
 817                int eflags = 0;
 818
 819                if (sign == ':')
 820                        line_color = opt->color_selected;
 821                else if (sign == '-')
 822                        line_color = opt->color_context;
 823                else if (sign == '=')
 824                        line_color = opt->color_function;
 825                *eol = '\0';
 826                while (next_match(opt, bol, eol, ctx, &match, eflags)) {
 827                        if (match.rm_so == match.rm_eo)
 828                                break;
 829
 830                        output_color(opt, bol, match.rm_so, line_color);
 831                        output_color(opt, bol + match.rm_so,
 832                                     match.rm_eo - match.rm_so,
 833                                     opt->color_match);
 834                        bol += match.rm_eo;
 835                        rest -= match.rm_eo;
 836                        eflags = REG_NOTBOL;
 837                }
 838                *eol = ch;
 839        }
 840        output_color(opt, bol, rest, line_color);
 841        opt->output(opt, "\n", 1);
 842}
 843
 844#ifndef NO_PTHREADS
 845int grep_use_locks;
 846
 847/*
 848 * This lock protects access to the gitattributes machinery, which is
 849 * not thread-safe.
 850 */
 851pthread_mutex_t grep_attr_mutex;
 852
 853static inline void grep_attr_lock(void)
 854{
 855        if (grep_use_locks)
 856                pthread_mutex_lock(&grep_attr_mutex);
 857}
 858
 859static inline void grep_attr_unlock(void)
 860{
 861        if (grep_use_locks)
 862                pthread_mutex_unlock(&grep_attr_mutex);
 863}
 864
 865/*
 866 * Same as git_attr_mutex, but protecting the thread-unsafe object db access.
 867 */
 868pthread_mutex_t grep_read_mutex;
 869
 870#else
 871#define grep_attr_lock()
 872#define grep_attr_unlock()
 873#endif
 874
 875static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
 876{
 877        xdemitconf_t *xecfg = opt->priv;
 878        if (xecfg && !xecfg->find_func) {
 879                grep_source_load_driver(gs);
 880                if (gs->driver->funcname.pattern) {
 881                        const struct userdiff_funcname *pe = &gs->driver->funcname;
 882                        xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
 883                } else {
 884                        xecfg = opt->priv = NULL;
 885                }
 886        }
 887
 888        if (xecfg) {
 889                char buf[1];
 890                return xecfg->find_func(bol, eol - bol, buf, 1,
 891                                        xecfg->find_func_priv) >= 0;
 892        }
 893
 894        if (bol == eol)
 895                return 0;
 896        if (isalpha(*bol) || *bol == '_' || *bol == '$')
 897                return 1;
 898        return 0;
 899}
 900
 901static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
 902                               char *bol, unsigned lno)
 903{
 904        while (bol > gs->buf) {
 905                char *eol = --bol;
 906
 907                while (bol > gs->buf && bol[-1] != '\n')
 908                        bol--;
 909                lno--;
 910
 911                if (lno <= opt->last_shown)
 912                        break;
 913
 914                if (match_funcname(opt, gs, bol, eol)) {
 915                        show_line(opt, bol, eol, gs->name, lno, '=');
 916                        break;
 917                }
 918        }
 919}
 920
 921static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
 922                             char *bol, char *end, unsigned lno)
 923{
 924        unsigned cur = lno, from = 1, funcname_lno = 0;
 925        int funcname_needed = !!opt->funcname;
 926
 927        if (opt->funcbody && !match_funcname(opt, gs, bol, end))
 928                funcname_needed = 2;
 929
 930        if (opt->pre_context < lno)
 931                from = lno - opt->pre_context;
 932        if (from <= opt->last_shown)
 933                from = opt->last_shown + 1;
 934
 935        /* Rewind. */
 936        while (bol > gs->buf &&
 937               cur > (funcname_needed == 2 ? opt->last_shown + 1 : from)) {
 938                char *eol = --bol;
 939
 940                while (bol > gs->buf && bol[-1] != '\n')
 941                        bol--;
 942                cur--;
 943                if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
 944                        funcname_lno = cur;
 945                        funcname_needed = 0;
 946                }
 947        }
 948
 949        /* We need to look even further back to find a function signature. */
 950        if (opt->funcname && funcname_needed)
 951                show_funcname_line(opt, gs, bol, cur);
 952
 953        /* Back forward. */
 954        while (cur < lno) {
 955                char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
 956
 957                while (*eol != '\n')
 958                        eol++;
 959                show_line(opt, bol, eol, gs->name, cur, sign);
 960                bol = eol + 1;
 961                cur++;
 962        }
 963}
 964
 965static int should_lookahead(struct grep_opt *opt)
 966{
 967        struct grep_pat *p;
 968
 969        if (opt->extended)
 970                return 0; /* punt for too complex stuff */
 971        if (opt->invert)
 972                return 0;
 973        for (p = opt->pattern_list; p; p = p->next) {
 974                if (p->token != GREP_PATTERN)
 975                        return 0; /* punt for "header only" and stuff */
 976        }
 977        return 1;
 978}
 979
 980static int look_ahead(struct grep_opt *opt,
 981                      unsigned long *left_p,
 982                      unsigned *lno_p,
 983                      char **bol_p)
 984{
 985        unsigned lno = *lno_p;
 986        char *bol = *bol_p;
 987        struct grep_pat *p;
 988        char *sp, *last_bol;
 989        regoff_t earliest = -1;
 990
 991        for (p = opt->pattern_list; p; p = p->next) {
 992                int hit;
 993                regmatch_t m;
 994
 995                hit = patmatch(p, bol, bol + *left_p, &m, 0);
 996                if (!hit || m.rm_so < 0 || m.rm_eo < 0)
 997                        continue;
 998                if (earliest < 0 || m.rm_so < earliest)
 999                        earliest = m.rm_so;
1000        }
1001
1002        if (earliest < 0) {
1003                *bol_p = bol + *left_p;
1004                *left_p = 0;
1005                return 1;
1006        }
1007        for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
1008                ; /* find the beginning of the line */
1009        last_bol = sp;
1010
1011        for (sp = bol; sp < last_bol; sp++) {
1012                if (*sp == '\n')
1013                        lno++;
1014        }
1015        *left_p -= last_bol - bol;
1016        *bol_p = last_bol;
1017        *lno_p = lno;
1018        return 0;
1019}
1020
1021static void std_output(struct grep_opt *opt, const void *buf, size_t size)
1022{
1023        fwrite(buf, size, 1, stdout);
1024}
1025
1026static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
1027{
1028        char *bol;
1029        unsigned long left;
1030        unsigned lno = 1;
1031        unsigned last_hit = 0;
1032        int binary_match_only = 0;
1033        unsigned count = 0;
1034        int try_lookahead = 0;
1035        int show_function = 0;
1036        enum grep_context ctx = GREP_CONTEXT_HEAD;
1037        xdemitconf_t xecfg;
1038
1039        if (!opt->output)
1040                opt->output = std_output;
1041
1042        if (opt->pre_context || opt->post_context || opt->file_break ||
1043            opt->funcbody) {
1044                /* Show hunk marks, except for the first file. */
1045                if (opt->last_shown)
1046                        opt->show_hunk_mark = 1;
1047                /*
1048                 * If we're using threads then we can't easily identify
1049                 * the first file.  Always put hunk marks in that case
1050                 * and skip the very first one later in work_done().
1051                 */
1052                if (opt->output != std_output)
1053                        opt->show_hunk_mark = 1;
1054        }
1055        opt->last_shown = 0;
1056
1057        switch (opt->binary) {
1058        case GREP_BINARY_DEFAULT:
1059                if (grep_source_is_binary(gs))
1060                        binary_match_only = 1;
1061                break;
1062        case GREP_BINARY_NOMATCH:
1063                if (grep_source_is_binary(gs))
1064                        return 0; /* Assume unmatch */
1065                break;
1066        case GREP_BINARY_TEXT:
1067                break;
1068        default:
1069                die("bug: unknown binary handling mode");
1070        }
1071
1072        memset(&xecfg, 0, sizeof(xecfg));
1073        opt->priv = &xecfg;
1074
1075        try_lookahead = should_lookahead(opt);
1076
1077        if (grep_source_load(gs) < 0)
1078                return 0;
1079
1080        bol = gs->buf;
1081        left = gs->size;
1082        while (left) {
1083                char *eol, ch;
1084                int hit;
1085
1086                /*
1087                 * look_ahead() skips quickly to the line that possibly
1088                 * has the next hit; don't call it if we need to do
1089                 * something more than just skipping the current line
1090                 * in response to an unmatch for the current line.  E.g.
1091                 * inside a post-context window, we will show the current
1092                 * line as a context around the previous hit when it
1093                 * doesn't hit.
1094                 */
1095                if (try_lookahead
1096                    && !(last_hit
1097                         && (show_function ||
1098                             lno <= last_hit + opt->post_context))
1099                    && look_ahead(opt, &left, &lno, &bol))
1100                        break;
1101                eol = end_of_line(bol, &left);
1102                ch = *eol;
1103                *eol = 0;
1104
1105                if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1106                        ctx = GREP_CONTEXT_BODY;
1107
1108                hit = match_line(opt, bol, eol, ctx, collect_hits);
1109                *eol = ch;
1110
1111                if (collect_hits)
1112                        goto next_line;
1113
1114                /* "grep -v -e foo -e bla" should list lines
1115                 * that do not have either, so inversion should
1116                 * be done outside.
1117                 */
1118                if (opt->invert)
1119                        hit = !hit;
1120                if (opt->unmatch_name_only) {
1121                        if (hit)
1122                                return 0;
1123                        goto next_line;
1124                }
1125                if (hit) {
1126                        count++;
1127                        if (opt->status_only)
1128                                return 1;
1129                        if (opt->name_only) {
1130                                show_name(opt, gs->name);
1131                                return 1;
1132                        }
1133                        if (opt->count)
1134                                goto next_line;
1135                        if (binary_match_only) {
1136                                opt->output(opt, "Binary file ", 12);
1137                                output_color(opt, gs->name, strlen(gs->name),
1138                                             opt->color_filename);
1139                                opt->output(opt, " matches\n", 9);
1140                                return 1;
1141                        }
1142                        /* Hit at this line.  If we haven't shown the
1143                         * pre-context lines, we would need to show them.
1144                         */
1145                        if (opt->pre_context || opt->funcbody)
1146                                show_pre_context(opt, gs, bol, eol, lno);
1147                        else if (opt->funcname)
1148                                show_funcname_line(opt, gs, bol, lno);
1149                        show_line(opt, bol, eol, gs->name, lno, ':');
1150                        last_hit = lno;
1151                        if (opt->funcbody)
1152                                show_function = 1;
1153                        goto next_line;
1154                }
1155                if (show_function && match_funcname(opt, gs, bol, eol))
1156                        show_function = 0;
1157                if (show_function ||
1158                    (last_hit && lno <= last_hit + opt->post_context)) {
1159                        /* If the last hit is within the post context,
1160                         * we need to show this line.
1161                         */
1162                        show_line(opt, bol, eol, gs->name, lno, '-');
1163                }
1164
1165        next_line:
1166                bol = eol + 1;
1167                if (!left)
1168                        break;
1169                left--;
1170                lno++;
1171        }
1172
1173        if (collect_hits)
1174                return 0;
1175
1176        if (opt->status_only)
1177                return 0;
1178        if (opt->unmatch_name_only) {
1179                /* We did not see any hit, so we want to show this */
1180                show_name(opt, gs->name);
1181                return 1;
1182        }
1183
1184        xdiff_clear_find_func(&xecfg);
1185        opt->priv = NULL;
1186
1187        /* NEEDSWORK:
1188         * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1189         * which feels mostly useless but sometimes useful.  Maybe
1190         * make it another option?  For now suppress them.
1191         */
1192        if (opt->count && count) {
1193                char buf[32];
1194                output_color(opt, gs->name, strlen(gs->name), opt->color_filename);
1195                output_sep(opt, ':');
1196                snprintf(buf, sizeof(buf), "%u\n", count);
1197                opt->output(opt, buf, strlen(buf));
1198                return 1;
1199        }
1200        return !!last_hit;
1201}
1202
1203static void clr_hit_marker(struct grep_expr *x)
1204{
1205        /* All-hit markers are meaningful only at the very top level
1206         * OR node.
1207         */
1208        while (1) {
1209                x->hit = 0;
1210                if (x->node != GREP_NODE_OR)
1211                        return;
1212                x->u.binary.left->hit = 0;
1213                x = x->u.binary.right;
1214        }
1215}
1216
1217static int chk_hit_marker(struct grep_expr *x)
1218{
1219        /* Top level nodes have hit markers.  See if they all are hits */
1220        while (1) {
1221                if (x->node != GREP_NODE_OR)
1222                        return x->hit;
1223                if (!x->u.binary.left->hit)
1224                        return 0;
1225                x = x->u.binary.right;
1226        }
1227}
1228
1229int grep_source(struct grep_opt *opt, struct grep_source *gs)
1230{
1231        /*
1232         * we do not have to do the two-pass grep when we do not check
1233         * buffer-wide "all-match".
1234         */
1235        if (!opt->all_match)
1236                return grep_source_1(opt, gs, 0);
1237
1238        /* Otherwise the toplevel "or" terms hit a bit differently.
1239         * We first clear hit markers from them.
1240         */
1241        clr_hit_marker(opt->pattern_expression);
1242        grep_source_1(opt, gs, 1);
1243
1244        if (!chk_hit_marker(opt->pattern_expression))
1245                return 0;
1246
1247        return grep_source_1(opt, gs, 0);
1248}
1249
1250int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
1251{
1252        struct grep_source gs;
1253        int r;
1254
1255        grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL);
1256        gs.buf = buf;
1257        gs.size = size;
1258
1259        r = grep_source(opt, &gs);
1260
1261        grep_source_clear(&gs);
1262        return r;
1263}
1264
1265void grep_source_init(struct grep_source *gs, enum grep_source_type type,
1266                      const char *name, const void *identifier)
1267{
1268        gs->type = type;
1269        gs->name = name ? xstrdup(name) : NULL;
1270        gs->buf = NULL;
1271        gs->size = 0;
1272        gs->driver = NULL;
1273
1274        switch (type) {
1275        case GREP_SOURCE_FILE:
1276                gs->identifier = xstrdup(identifier);
1277                break;
1278        case GREP_SOURCE_SHA1:
1279                gs->identifier = xmalloc(20);
1280                memcpy(gs->identifier, identifier, 20);
1281                break;
1282        case GREP_SOURCE_BUF:
1283                gs->identifier = NULL;
1284        }
1285}
1286
1287void grep_source_clear(struct grep_source *gs)
1288{
1289        free(gs->name);
1290        gs->name = NULL;
1291        free(gs->identifier);
1292        gs->identifier = NULL;
1293        grep_source_clear_data(gs);
1294}
1295
1296void grep_source_clear_data(struct grep_source *gs)
1297{
1298        switch (gs->type) {
1299        case GREP_SOURCE_FILE:
1300        case GREP_SOURCE_SHA1:
1301                free(gs->buf);
1302                gs->buf = NULL;
1303                gs->size = 0;
1304                break;
1305        case GREP_SOURCE_BUF:
1306                /* leave user-provided buf intact */
1307                break;
1308        }
1309}
1310
1311static int grep_source_load_sha1(struct grep_source *gs)
1312{
1313        enum object_type type;
1314
1315        grep_read_lock();
1316        gs->buf = read_sha1_file(gs->identifier, &type, &gs->size);
1317        grep_read_unlock();
1318
1319        if (!gs->buf)
1320                return error(_("'%s': unable to read %s"),
1321                             gs->name,
1322                             sha1_to_hex(gs->identifier));
1323        return 0;
1324}
1325
1326static int grep_source_load_file(struct grep_source *gs)
1327{
1328        const char *filename = gs->identifier;
1329        struct stat st;
1330        char *data;
1331        size_t size;
1332        int i;
1333
1334        if (lstat(filename, &st) < 0) {
1335        err_ret:
1336                if (errno != ENOENT)
1337                        error(_("'%s': %s"), filename, strerror(errno));
1338                return -1;
1339        }
1340        if (!S_ISREG(st.st_mode))
1341                return -1;
1342        size = xsize_t(st.st_size);
1343        i = open(filename, O_RDONLY);
1344        if (i < 0)
1345                goto err_ret;
1346        data = xmalloc(size + 1);
1347        if (st.st_size != read_in_full(i, data, size)) {
1348                error(_("'%s': short read %s"), filename, strerror(errno));
1349                close(i);
1350                free(data);
1351                return -1;
1352        }
1353        close(i);
1354        data[size] = 0;
1355
1356        gs->buf = data;
1357        gs->size = size;
1358        return 0;
1359}
1360
1361int grep_source_load(struct grep_source *gs)
1362{
1363        if (gs->buf)
1364                return 0;
1365
1366        switch (gs->type) {
1367        case GREP_SOURCE_FILE:
1368                return grep_source_load_file(gs);
1369        case GREP_SOURCE_SHA1:
1370                return grep_source_load_sha1(gs);
1371        case GREP_SOURCE_BUF:
1372                return gs->buf ? 0 : -1;
1373        }
1374        die("BUG: invalid grep_source type");
1375}
1376
1377void grep_source_load_driver(struct grep_source *gs)
1378{
1379        if (gs->driver)
1380                return;
1381
1382        grep_attr_lock();
1383        gs->driver = userdiff_find_by_path(gs->name);
1384        if (!gs->driver)
1385                gs->driver = userdiff_find_by_name("default");
1386        grep_attr_unlock();
1387}
1388
1389int grep_source_is_binary(struct grep_source *gs)
1390{
1391        grep_source_load_driver(gs);
1392        if (gs->driver->binary != -1)
1393                return gs->driver->binary;
1394
1395        if (!grep_source_load(gs))
1396                return buffer_is_binary(gs->buf, gs->size);
1397
1398        return 0;
1399}