2b77c477643b825cb2ea46a0bfbddd2da32b8bea
   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 = pat;
  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
  21void append_header_grep_pattern(struct grep_opt *opt,
  22                                enum grep_header_field field, const char *pat)
  23{
  24        struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
  25                                             GREP_PATTERN_HEAD, field);
  26        *opt->header_tail = p;
  27        opt->header_tail = &p->next;
  28        p->next = NULL;
  29}
  30
  31void append_grep_pattern(struct grep_opt *opt, const char *pat,
  32                         const char *origin, int no, enum grep_pat_token t)
  33{
  34        append_grep_pat(opt, pat, strlen(pat), origin, no, t);
  35}
  36
  37void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
  38                     const char *origin, int no, enum grep_pat_token t)
  39{
  40        struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
  41        *opt->pattern_tail = p;
  42        opt->pattern_tail = &p->next;
  43        p->next = NULL;
  44}
  45
  46struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
  47{
  48        struct grep_pat *pat;
  49        struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
  50        *ret = *opt;
  51
  52        ret->pattern_list = NULL;
  53        ret->pattern_tail = &ret->pattern_list;
  54
  55        for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
  56        {
  57                if(pat->token == GREP_PATTERN_HEAD)
  58                        append_header_grep_pattern(ret, pat->field,
  59                                                   pat->pattern);
  60                else
  61                        append_grep_pat(ret, pat->pattern, pat->patternlen,
  62                                        pat->origin, pat->no, pat->token);
  63        }
  64
  65        return ret;
  66}
  67
  68static NORETURN void compile_regexp_failed(const struct grep_pat *p,
  69                const char *error)
  70{
  71        char where[1024];
  72
  73        if (p->no)
  74                sprintf(where, "In '%s' at %d, ", p->origin, p->no);
  75        else if (p->origin)
  76                sprintf(where, "%s, ", p->origin);
  77        else
  78                where[0] = 0;
  79
  80        die("%s'%s': %s", where, p->pattern, error);
  81}
  82
  83#ifdef USE_LIBPCRE
  84static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
  85{
  86        const char *error;
  87        int erroffset;
  88        int options = 0;
  89
  90        if (opt->ignore_case)
  91                options |= PCRE_CASELESS;
  92
  93        p->pcre_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
  94                        NULL);
  95        if (!p->pcre_regexp)
  96                compile_regexp_failed(p, error);
  97
  98        p->pcre_extra_info = pcre_study(p->pcre_regexp, 0, &error);
  99        if (!p->pcre_extra_info && error)
 100                die("%s", error);
 101}
 102
 103static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
 104                regmatch_t *match, int eflags)
 105{
 106        int ovector[30], ret, flags = 0;
 107
 108        if (eflags & REG_NOTBOL)
 109                flags |= PCRE_NOTBOL;
 110
 111        ret = pcre_exec(p->pcre_regexp, p->pcre_extra_info, line, eol - line,
 112                        0, flags, ovector, ARRAY_SIZE(ovector));
 113        if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
 114                die("pcre_exec failed with error code %d", ret);
 115        if (ret > 0) {
 116                ret = 0;
 117                match->rm_so = ovector[0];
 118                match->rm_eo = ovector[1];
 119        }
 120
 121        return ret;
 122}
 123
 124static void free_pcre_regexp(struct grep_pat *p)
 125{
 126        pcre_free(p->pcre_regexp);
 127        pcre_free(p->pcre_extra_info);
 128}
 129#else /* !USE_LIBPCRE */
 130static void compile_pcre_regexp(struct grep_pat *p, const struct grep_opt *opt)
 131{
 132        die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
 133}
 134
 135static int pcrematch(struct grep_pat *p, const char *line, const char *eol,
 136                regmatch_t *match, int eflags)
 137{
 138        return 1;
 139}
 140
 141static void free_pcre_regexp(struct grep_pat *p)
 142{
 143}
 144#endif /* !USE_LIBPCRE */
 145
 146static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
 147{
 148        int err;
 149
 150        p->word_regexp = opt->word_regexp;
 151        p->ignore_case = opt->ignore_case;
 152        p->fixed = opt->fixed;
 153
 154        if (p->fixed)
 155                return;
 156
 157        if (opt->pcre) {
 158                compile_pcre_regexp(p, opt);
 159                return;
 160        }
 161
 162        err = regcomp(&p->regexp, p->pattern, opt->regflags);
 163        if (err) {
 164                char errbuf[1024];
 165                regerror(err, &p->regexp, errbuf, 1024);
 166                regfree(&p->regexp);
 167                compile_regexp_failed(p, errbuf);
 168        }
 169}
 170
 171static struct grep_expr *compile_pattern_or(struct grep_pat **);
 172static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
 173{
 174        struct grep_pat *p;
 175        struct grep_expr *x;
 176
 177        p = *list;
 178        if (!p)
 179                return NULL;
 180        switch (p->token) {
 181        case GREP_PATTERN: /* atom */
 182        case GREP_PATTERN_HEAD:
 183        case GREP_PATTERN_BODY:
 184                x = xcalloc(1, sizeof (struct grep_expr));
 185                x->node = GREP_NODE_ATOM;
 186                x->u.atom = p;
 187                *list = p->next;
 188                return x;
 189        case GREP_OPEN_PAREN:
 190                *list = p->next;
 191                x = compile_pattern_or(list);
 192                if (!*list || (*list)->token != GREP_CLOSE_PAREN)
 193                        die("unmatched parenthesis");
 194                *list = (*list)->next;
 195                return x;
 196        default:
 197                return NULL;
 198        }
 199}
 200
 201static struct grep_expr *compile_pattern_not(struct grep_pat **list)
 202{
 203        struct grep_pat *p;
 204        struct grep_expr *x;
 205
 206        p = *list;
 207        if (!p)
 208                return NULL;
 209        switch (p->token) {
 210        case GREP_NOT:
 211                if (!p->next)
 212                        die("--not not followed by pattern expression");
 213                *list = p->next;
 214                x = xcalloc(1, sizeof (struct grep_expr));
 215                x->node = GREP_NODE_NOT;
 216                x->u.unary = compile_pattern_not(list);
 217                if (!x->u.unary)
 218                        die("--not followed by non pattern expression");
 219                return x;
 220        default:
 221                return compile_pattern_atom(list);
 222        }
 223}
 224
 225static struct grep_expr *compile_pattern_and(struct grep_pat **list)
 226{
 227        struct grep_pat *p;
 228        struct grep_expr *x, *y, *z;
 229
 230        x = compile_pattern_not(list);
 231        p = *list;
 232        if (p && p->token == GREP_AND) {
 233                if (!p->next)
 234                        die("--and not followed by pattern expression");
 235                *list = p->next;
 236                y = compile_pattern_and(list);
 237                if (!y)
 238                        die("--and not followed by pattern expression");
 239                z = xcalloc(1, sizeof (struct grep_expr));
 240                z->node = GREP_NODE_AND;
 241                z->u.binary.left = x;
 242                z->u.binary.right = y;
 243                return z;
 244        }
 245        return x;
 246}
 247
 248static struct grep_expr *compile_pattern_or(struct grep_pat **list)
 249{
 250        struct grep_pat *p;
 251        struct grep_expr *x, *y, *z;
 252
 253        x = compile_pattern_and(list);
 254        p = *list;
 255        if (x && p && p->token != GREP_CLOSE_PAREN) {
 256                y = compile_pattern_or(list);
 257                if (!y)
 258                        die("not a pattern expression %s", p->pattern);
 259                z = xcalloc(1, sizeof (struct grep_expr));
 260                z->node = GREP_NODE_OR;
 261                z->u.binary.left = x;
 262                z->u.binary.right = y;
 263                return z;
 264        }
 265        return x;
 266}
 267
 268static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
 269{
 270        return compile_pattern_or(list);
 271}
 272
 273static struct grep_expr *grep_true_expr(void)
 274{
 275        struct grep_expr *z = xcalloc(1, sizeof(*z));
 276        z->node = GREP_NODE_TRUE;
 277        return z;
 278}
 279
 280static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
 281{
 282        struct grep_expr *z = xcalloc(1, sizeof(*z));
 283        z->node = GREP_NODE_OR;
 284        z->u.binary.left = left;
 285        z->u.binary.right = right;
 286        return z;
 287}
 288
 289static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
 290{
 291        struct grep_pat *p;
 292        struct grep_expr *header_expr;
 293        struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
 294        enum grep_header_field fld;
 295
 296        if (!opt->header_list)
 297                return NULL;
 298        p = opt->header_list;
 299        for (p = opt->header_list; p; p = p->next) {
 300                if (p->token != GREP_PATTERN_HEAD)
 301                        die("bug: a non-header pattern in grep header list.");
 302                if (p->field < 0 || GREP_HEADER_FIELD_MAX <= p->field)
 303                        die("bug: unknown header field %d", p->field);
 304                compile_regexp(p, opt);
 305        }
 306
 307        for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
 308                header_group[fld] = NULL;
 309
 310        for (p = opt->header_list; p; p = p->next) {
 311                struct grep_expr *h;
 312                struct grep_pat *pp = p;
 313
 314                h = compile_pattern_atom(&pp);
 315                if (!h || pp != p->next)
 316                        die("bug: malformed header expr");
 317                if (!header_group[p->field]) {
 318                        header_group[p->field] = h;
 319                        continue;
 320                }
 321                header_group[p->field] = grep_or_expr(h, header_group[p->field]);
 322        }
 323
 324        header_expr = NULL;
 325
 326        for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
 327                if (!header_group[fld])
 328                        continue;
 329                if (!header_expr)
 330                        header_expr = grep_true_expr();
 331                header_expr = grep_or_expr(header_group[fld], header_expr);
 332        }
 333        return header_expr;
 334}
 335
 336void compile_grep_patterns(struct grep_opt *opt)
 337{
 338        struct grep_pat *p;
 339        struct grep_expr *header_expr = prep_header_patterns(opt);
 340
 341        for (p = opt->pattern_list; p; p = p->next) {
 342                switch (p->token) {
 343                case GREP_PATTERN: /* atom */
 344                case GREP_PATTERN_HEAD:
 345                case GREP_PATTERN_BODY:
 346                        compile_regexp(p, opt);
 347                        break;
 348                default:
 349                        opt->extended = 1;
 350                        break;
 351                }
 352        }
 353
 354        if (opt->all_match || header_expr)
 355                opt->extended = 1;
 356        else if (!opt->extended)
 357                return;
 358
 359        p = opt->pattern_list;
 360        if (p)
 361                opt->pattern_expression = compile_pattern_expr(&p);
 362        if (p)
 363                die("incomplete pattern expression: %s", p->pattern);
 364
 365        if (!header_expr)
 366                return;
 367
 368        if (!opt->pattern_expression)
 369                opt->pattern_expression = header_expr;
 370        else
 371                opt->pattern_expression = grep_or_expr(opt->pattern_expression,
 372                                                       header_expr);
 373        opt->all_match = 1;
 374}
 375
 376static void free_pattern_expr(struct grep_expr *x)
 377{
 378        switch (x->node) {
 379        case GREP_NODE_TRUE:
 380        case GREP_NODE_ATOM:
 381                break;
 382        case GREP_NODE_NOT:
 383                free_pattern_expr(x->u.unary);
 384                break;
 385        case GREP_NODE_AND:
 386        case GREP_NODE_OR:
 387                free_pattern_expr(x->u.binary.left);
 388                free_pattern_expr(x->u.binary.right);
 389                break;
 390        }
 391        free(x);
 392}
 393
 394void free_grep_patterns(struct grep_opt *opt)
 395{
 396        struct grep_pat *p, *n;
 397
 398        for (p = opt->pattern_list; p; p = n) {
 399                n = p->next;
 400                switch (p->token) {
 401                case GREP_PATTERN: /* atom */
 402                case GREP_PATTERN_HEAD:
 403                case GREP_PATTERN_BODY:
 404                        if (p->pcre_regexp)
 405                                free_pcre_regexp(p);
 406                        else
 407                                regfree(&p->regexp);
 408                        break;
 409                default:
 410                        break;
 411                }
 412                free(p);
 413        }
 414
 415        if (!opt->extended)
 416                return;
 417        free_pattern_expr(opt->pattern_expression);
 418}
 419
 420static char *end_of_line(char *cp, unsigned long *left)
 421{
 422        unsigned long l = *left;
 423        while (l && *cp != '\n') {
 424                l--;
 425                cp++;
 426        }
 427        *left = l;
 428        return cp;
 429}
 430
 431static int word_char(char ch)
 432{
 433        return isalnum(ch) || ch == '_';
 434}
 435
 436static void output_color(struct grep_opt *opt, const void *data, size_t size,
 437                         const char *color)
 438{
 439        if (opt->color && color && color[0]) {
 440                opt->output(opt, color, strlen(color));
 441                opt->output(opt, data, size);
 442                opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
 443        } else
 444                opt->output(opt, data, size);
 445}
 446
 447static void output_sep(struct grep_opt *opt, char sign)
 448{
 449        if (opt->null_following_name)
 450                opt->output(opt, "\0", 1);
 451        else
 452                output_color(opt, &sign, 1, opt->color_sep);
 453}
 454
 455static void show_name(struct grep_opt *opt, const char *name)
 456{
 457        output_color(opt, name, strlen(name), opt->color_filename);
 458        opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
 459}
 460
 461static int fixmatch(struct grep_pat *p, char *line, char *eol,
 462                    regmatch_t *match)
 463{
 464        char *hit;
 465
 466        if (p->ignore_case) {
 467                char *s = line;
 468                do {
 469                        hit = strcasestr(s, p->pattern);
 470                        if (hit)
 471                                break;
 472                        s += strlen(s) + 1;
 473                } while (s < eol);
 474        } else
 475                hit = memmem(line, eol - line, p->pattern, p->patternlen);
 476
 477        if (!hit) {
 478                match->rm_so = match->rm_eo = -1;
 479                return REG_NOMATCH;
 480        }
 481        else {
 482                match->rm_so = hit - line;
 483                match->rm_eo = match->rm_so + p->patternlen;
 484                return 0;
 485        }
 486}
 487
 488static int regmatch(const regex_t *preg, char *line, char *eol,
 489                    regmatch_t *match, int eflags)
 490{
 491#ifdef REG_STARTEND
 492        match->rm_so = 0;
 493        match->rm_eo = eol - line;
 494        eflags |= REG_STARTEND;
 495#endif
 496        return regexec(preg, line, 1, match, eflags);
 497}
 498
 499static int patmatch(struct grep_pat *p, char *line, char *eol,
 500                    regmatch_t *match, int eflags)
 501{
 502        int hit;
 503
 504        if (p->fixed)
 505                hit = !fixmatch(p, line, eol, match);
 506        else if (p->pcre_regexp)
 507                hit = !pcrematch(p, line, eol, match, eflags);
 508        else
 509                hit = !regmatch(&p->regexp, line, eol, match, eflags);
 510
 511        return hit;
 512}
 513
 514static int strip_timestamp(char *bol, char **eol_p)
 515{
 516        char *eol = *eol_p;
 517        int ch;
 518
 519        while (bol < --eol) {
 520                if (*eol != '>')
 521                        continue;
 522                *eol_p = ++eol;
 523                ch = *eol;
 524                *eol = '\0';
 525                return ch;
 526        }
 527        return 0;
 528}
 529
 530static struct {
 531        const char *field;
 532        size_t len;
 533} header_field[] = {
 534        { "author ", 7 },
 535        { "committer ", 10 },
 536};
 537
 538static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
 539                             enum grep_context ctx,
 540                             regmatch_t *pmatch, int eflags)
 541{
 542        int hit = 0;
 543        int saved_ch = 0;
 544        const char *start = bol;
 545
 546        if ((p->token != GREP_PATTERN) &&
 547            ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
 548                return 0;
 549
 550        if (p->token == GREP_PATTERN_HEAD) {
 551                const char *field;
 552                size_t len;
 553                assert(p->field < ARRAY_SIZE(header_field));
 554                field = header_field[p->field].field;
 555                len = header_field[p->field].len;
 556                if (strncmp(bol, field, len))
 557                        return 0;
 558                bol += len;
 559                saved_ch = strip_timestamp(bol, &eol);
 560        }
 561
 562 again:
 563        hit = patmatch(p, bol, eol, pmatch, eflags);
 564
 565        if (hit && p->word_regexp) {
 566                if ((pmatch[0].rm_so < 0) ||
 567                    (eol - bol) < pmatch[0].rm_so ||
 568                    (pmatch[0].rm_eo < 0) ||
 569                    (eol - bol) < pmatch[0].rm_eo)
 570                        die("regexp returned nonsense");
 571
 572                /* Match beginning must be either beginning of the
 573                 * line, or at word boundary (i.e. the last char must
 574                 * not be a word char).  Similarly, match end must be
 575                 * either end of the line, or at word boundary
 576                 * (i.e. the next char must not be a word char).
 577                 */
 578                if ( ((pmatch[0].rm_so == 0) ||
 579                      !word_char(bol[pmatch[0].rm_so-1])) &&
 580                     ((pmatch[0].rm_eo == (eol-bol)) ||
 581                      !word_char(bol[pmatch[0].rm_eo])) )
 582                        ;
 583                else
 584                        hit = 0;
 585
 586                /* Words consist of at least one character. */
 587                if (pmatch->rm_so == pmatch->rm_eo)
 588                        hit = 0;
 589
 590                if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
 591                        /* There could be more than one match on the
 592                         * line, and the first match might not be
 593                         * strict word match.  But later ones could be!
 594                         * Forward to the next possible start, i.e. the
 595                         * next position following a non-word char.
 596                         */
 597                        bol = pmatch[0].rm_so + bol + 1;
 598                        while (word_char(bol[-1]) && bol < eol)
 599                                bol++;
 600                        eflags |= REG_NOTBOL;
 601                        if (bol < eol)
 602                                goto again;
 603                }
 604        }
 605        if (p->token == GREP_PATTERN_HEAD && saved_ch)
 606                *eol = saved_ch;
 607        if (hit) {
 608                pmatch[0].rm_so += bol - start;
 609                pmatch[0].rm_eo += bol - start;
 610        }
 611        return hit;
 612}
 613
 614static int match_expr_eval(struct grep_expr *x, char *bol, char *eol,
 615                           enum grep_context ctx, int collect_hits)
 616{
 617        int h = 0;
 618        regmatch_t match;
 619
 620        if (!x)
 621                die("Not a valid grep expression");
 622        switch (x->node) {
 623        case GREP_NODE_TRUE:
 624                h = 1;
 625                break;
 626        case GREP_NODE_ATOM:
 627                h = match_one_pattern(x->u.atom, bol, eol, ctx, &match, 0);
 628                break;
 629        case GREP_NODE_NOT:
 630                h = !match_expr_eval(x->u.unary, bol, eol, ctx, 0);
 631                break;
 632        case GREP_NODE_AND:
 633                if (!match_expr_eval(x->u.binary.left, bol, eol, ctx, 0))
 634                        return 0;
 635                h = match_expr_eval(x->u.binary.right, bol, eol, ctx, 0);
 636                break;
 637        case GREP_NODE_OR:
 638                if (!collect_hits)
 639                        return (match_expr_eval(x->u.binary.left,
 640                                                bol, eol, ctx, 0) ||
 641                                match_expr_eval(x->u.binary.right,
 642                                                bol, eol, ctx, 0));
 643                h = match_expr_eval(x->u.binary.left, bol, eol, ctx, 0);
 644                x->u.binary.left->hit |= h;
 645                h |= match_expr_eval(x->u.binary.right, bol, eol, ctx, 1);
 646                break;
 647        default:
 648                die("Unexpected node type (internal error) %d", x->node);
 649        }
 650        if (collect_hits)
 651                x->hit |= h;
 652        return h;
 653}
 654
 655static int match_expr(struct grep_opt *opt, char *bol, char *eol,
 656                      enum grep_context ctx, int collect_hits)
 657{
 658        struct grep_expr *x = opt->pattern_expression;
 659        return match_expr_eval(x, bol, eol, ctx, collect_hits);
 660}
 661
 662static int match_line(struct grep_opt *opt, char *bol, char *eol,
 663                      enum grep_context ctx, int collect_hits)
 664{
 665        struct grep_pat *p;
 666        regmatch_t match;
 667
 668        if (opt->extended)
 669                return match_expr(opt, bol, eol, ctx, collect_hits);
 670
 671        /* we do not call with collect_hits without being extended */
 672        for (p = opt->pattern_list; p; p = p->next) {
 673                if (match_one_pattern(p, bol, eol, ctx, &match, 0))
 674                        return 1;
 675        }
 676        return 0;
 677}
 678
 679static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
 680                              enum grep_context ctx,
 681                              regmatch_t *pmatch, int eflags)
 682{
 683        regmatch_t match;
 684
 685        if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
 686                return 0;
 687        if (match.rm_so < 0 || match.rm_eo < 0)
 688                return 0;
 689        if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
 690                if (match.rm_so > pmatch->rm_so)
 691                        return 1;
 692                if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
 693                        return 1;
 694        }
 695        pmatch->rm_so = match.rm_so;
 696        pmatch->rm_eo = match.rm_eo;
 697        return 1;
 698}
 699
 700static int next_match(struct grep_opt *opt, char *bol, char *eol,
 701                      enum grep_context ctx, regmatch_t *pmatch, int eflags)
 702{
 703        struct grep_pat *p;
 704        int hit = 0;
 705
 706        pmatch->rm_so = pmatch->rm_eo = -1;
 707        if (bol < eol) {
 708                for (p = opt->pattern_list; p; p = p->next) {
 709                        switch (p->token) {
 710                        case GREP_PATTERN: /* atom */
 711                        case GREP_PATTERN_HEAD:
 712                        case GREP_PATTERN_BODY:
 713                                hit |= match_next_pattern(p, bol, eol, ctx,
 714                                                          pmatch, eflags);
 715                                break;
 716                        default:
 717                                break;
 718                        }
 719                }
 720        }
 721        return hit;
 722}
 723
 724static void show_line(struct grep_opt *opt, char *bol, char *eol,
 725                      const char *name, unsigned lno, char sign)
 726{
 727        int rest = eol - bol;
 728        char *line_color = NULL;
 729
 730        if (opt->pre_context || opt->post_context) {
 731                if (opt->last_shown == 0) {
 732                        if (opt->show_hunk_mark) {
 733                                output_color(opt, "--", 2, opt->color_sep);
 734                                opt->output(opt, "\n", 1);
 735                        }
 736                } else if (lno > opt->last_shown + 1) {
 737                        output_color(opt, "--", 2, opt->color_sep);
 738                        opt->output(opt, "\n", 1);
 739                }
 740        }
 741        opt->last_shown = lno;
 742
 743        if (opt->pathname) {
 744                output_color(opt, name, strlen(name), opt->color_filename);
 745                output_sep(opt, sign);
 746        }
 747        if (opt->linenum) {
 748                char buf[32];
 749                snprintf(buf, sizeof(buf), "%d", lno);
 750                output_color(opt, buf, strlen(buf), opt->color_lineno);
 751                output_sep(opt, sign);
 752        }
 753        if (opt->color) {
 754                regmatch_t match;
 755                enum grep_context ctx = GREP_CONTEXT_BODY;
 756                int ch = *eol;
 757                int eflags = 0;
 758
 759                if (sign == ':')
 760                        line_color = opt->color_selected;
 761                else if (sign == '-')
 762                        line_color = opt->color_context;
 763                else if (sign == '=')
 764                        line_color = opt->color_function;
 765                *eol = '\0';
 766                while (next_match(opt, bol, eol, ctx, &match, eflags)) {
 767                        if (match.rm_so == match.rm_eo)
 768                                break;
 769
 770                        output_color(opt, bol, match.rm_so, line_color);
 771                        output_color(opt, bol + match.rm_so,
 772                                     match.rm_eo - match.rm_so,
 773                                     opt->color_match);
 774                        bol += match.rm_eo;
 775                        rest -= match.rm_eo;
 776                        eflags = REG_NOTBOL;
 777                }
 778                *eol = ch;
 779        }
 780        output_color(opt, bol, rest, line_color);
 781        opt->output(opt, "\n", 1);
 782}
 783
 784static int match_funcname(struct grep_opt *opt, char *bol, char *eol)
 785{
 786        xdemitconf_t *xecfg = opt->priv;
 787        if (xecfg && xecfg->find_func) {
 788                char buf[1];
 789                return xecfg->find_func(bol, eol - bol, buf, 1,
 790                                        xecfg->find_func_priv) >= 0;
 791        }
 792
 793        if (bol == eol)
 794                return 0;
 795        if (isalpha(*bol) || *bol == '_' || *bol == '$')
 796                return 1;
 797        return 0;
 798}
 799
 800static void show_funcname_line(struct grep_opt *opt, const char *name,
 801                               char *buf, char *bol, unsigned lno)
 802{
 803        while (bol > buf) {
 804                char *eol = --bol;
 805
 806                while (bol > buf && bol[-1] != '\n')
 807                        bol--;
 808                lno--;
 809
 810                if (lno <= opt->last_shown)
 811                        break;
 812
 813                if (match_funcname(opt, bol, eol)) {
 814                        show_line(opt, bol, eol, name, lno, '=');
 815                        break;
 816                }
 817        }
 818}
 819
 820static void show_pre_context(struct grep_opt *opt, const char *name, char *buf,
 821                             char *bol, unsigned lno)
 822{
 823        unsigned cur = lno, from = 1, funcname_lno = 0;
 824        int funcname_needed = opt->funcname;
 825
 826        if (opt->pre_context < lno)
 827                from = lno - opt->pre_context;
 828        if (from <= opt->last_shown)
 829                from = opt->last_shown + 1;
 830
 831        /* Rewind. */
 832        while (bol > buf && cur > from) {
 833                char *eol = --bol;
 834
 835                while (bol > buf && bol[-1] != '\n')
 836                        bol--;
 837                cur--;
 838                if (funcname_needed && match_funcname(opt, bol, eol)) {
 839                        funcname_lno = cur;
 840                        funcname_needed = 0;
 841                }
 842        }
 843
 844        /* We need to look even further back to find a function signature. */
 845        if (opt->funcname && funcname_needed)
 846                show_funcname_line(opt, name, buf, bol, cur);
 847
 848        /* Back forward. */
 849        while (cur < lno) {
 850                char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
 851
 852                while (*eol != '\n')
 853                        eol++;
 854                show_line(opt, bol, eol, name, cur, sign);
 855                bol = eol + 1;
 856                cur++;
 857        }
 858}
 859
 860static int should_lookahead(struct grep_opt *opt)
 861{
 862        struct grep_pat *p;
 863
 864        if (opt->extended)
 865                return 0; /* punt for too complex stuff */
 866        if (opt->invert)
 867                return 0;
 868        for (p = opt->pattern_list; p; p = p->next) {
 869                if (p->token != GREP_PATTERN)
 870                        return 0; /* punt for "header only" and stuff */
 871        }
 872        return 1;
 873}
 874
 875static int look_ahead(struct grep_opt *opt,
 876                      unsigned long *left_p,
 877                      unsigned *lno_p,
 878                      char **bol_p)
 879{
 880        unsigned lno = *lno_p;
 881        char *bol = *bol_p;
 882        struct grep_pat *p;
 883        char *sp, *last_bol;
 884        regoff_t earliest = -1;
 885
 886        for (p = opt->pattern_list; p; p = p->next) {
 887                int hit;
 888                regmatch_t m;
 889
 890                hit = patmatch(p, bol, bol + *left_p, &m, 0);
 891                if (!hit || m.rm_so < 0 || m.rm_eo < 0)
 892                        continue;
 893                if (earliest < 0 || m.rm_so < earliest)
 894                        earliest = m.rm_so;
 895        }
 896
 897        if (earliest < 0) {
 898                *bol_p = bol + *left_p;
 899                *left_p = 0;
 900                return 1;
 901        }
 902        for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
 903                ; /* find the beginning of the line */
 904        last_bol = sp;
 905
 906        for (sp = bol; sp < last_bol; sp++) {
 907                if (*sp == '\n')
 908                        lno++;
 909        }
 910        *left_p -= last_bol - bol;
 911        *bol_p = last_bol;
 912        *lno_p = lno;
 913        return 0;
 914}
 915
 916int grep_threads_ok(const struct grep_opt *opt)
 917{
 918        /* If this condition is true, then we may use the attribute
 919         * machinery in grep_buffer_1. The attribute code is not
 920         * thread safe, so we disable the use of threads.
 921         */
 922        if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
 923            !opt->name_only)
 924                return 0;
 925
 926        return 1;
 927}
 928
 929static void std_output(struct grep_opt *opt, const void *buf, size_t size)
 930{
 931        fwrite(buf, size, 1, stdout);
 932}
 933
 934static int grep_buffer_1(struct grep_opt *opt, const char *name,
 935                         char *buf, unsigned long size, int collect_hits)
 936{
 937        char *bol = buf;
 938        unsigned long left = size;
 939        unsigned lno = 1;
 940        unsigned last_hit = 0;
 941        int binary_match_only = 0;
 942        unsigned count = 0;
 943        int try_lookahead = 0;
 944        enum grep_context ctx = GREP_CONTEXT_HEAD;
 945        xdemitconf_t xecfg;
 946
 947        if (!opt->output)
 948                opt->output = std_output;
 949
 950        if (opt->last_shown && (opt->pre_context || opt->post_context) &&
 951            opt->output == std_output)
 952                opt->show_hunk_mark = 1;
 953        opt->last_shown = 0;
 954
 955        switch (opt->binary) {
 956        case GREP_BINARY_DEFAULT:
 957                if (buffer_is_binary(buf, size))
 958                        binary_match_only = 1;
 959                break;
 960        case GREP_BINARY_NOMATCH:
 961                if (buffer_is_binary(buf, size))
 962                        return 0; /* Assume unmatch */
 963                break;
 964        case GREP_BINARY_TEXT:
 965                break;
 966        default:
 967                die("bug: unknown binary handling mode");
 968        }
 969
 970        memset(&xecfg, 0, sizeof(xecfg));
 971        if (opt->funcname && !opt->unmatch_name_only && !opt->status_only &&
 972            !opt->name_only && !binary_match_only && !collect_hits) {
 973                struct userdiff_driver *drv = userdiff_find_by_path(name);
 974                if (drv && drv->funcname.pattern) {
 975                        const struct userdiff_funcname *pe = &drv->funcname;
 976                        xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags);
 977                        opt->priv = &xecfg;
 978                }
 979        }
 980        try_lookahead = should_lookahead(opt);
 981
 982        while (left) {
 983                char *eol, ch;
 984                int hit;
 985
 986                /*
 987                 * look_ahead() skips quickly to the line that possibly
 988                 * has the next hit; don't call it if we need to do
 989                 * something more than just skipping the current line
 990                 * in response to an unmatch for the current line.  E.g.
 991                 * inside a post-context window, we will show the current
 992                 * line as a context around the previous hit when it
 993                 * doesn't hit.
 994                 */
 995                if (try_lookahead
 996                    && !(last_hit
 997                         && lno <= last_hit + opt->post_context)
 998                    && look_ahead(opt, &left, &lno, &bol))
 999                        break;
1000                eol = end_of_line(bol, &left);
1001                ch = *eol;
1002                *eol = 0;
1003
1004                if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
1005                        ctx = GREP_CONTEXT_BODY;
1006
1007                hit = match_line(opt, bol, eol, ctx, collect_hits);
1008                *eol = ch;
1009
1010                if (collect_hits)
1011                        goto next_line;
1012
1013                /* "grep -v -e foo -e bla" should list lines
1014                 * that do not have either, so inversion should
1015                 * be done outside.
1016                 */
1017                if (opt->invert)
1018                        hit = !hit;
1019                if (opt->unmatch_name_only) {
1020                        if (hit)
1021                                return 0;
1022                        goto next_line;
1023                }
1024                if (hit) {
1025                        count++;
1026                        if (opt->status_only)
1027                                return 1;
1028                        if (opt->name_only) {
1029                                show_name(opt, name);
1030                                return 1;
1031                        }
1032                        if (opt->count)
1033                                goto next_line;
1034                        if (binary_match_only) {
1035                                opt->output(opt, "Binary file ", 12);
1036                                output_color(opt, name, strlen(name),
1037                                             opt->color_filename);
1038                                opt->output(opt, " matches\n", 9);
1039                                return 1;
1040                        }
1041                        /* Hit at this line.  If we haven't shown the
1042                         * pre-context lines, we would need to show them.
1043                         */
1044                        if (opt->pre_context)
1045                                show_pre_context(opt, name, buf, bol, lno);
1046                        else if (opt->funcname)
1047                                show_funcname_line(opt, name, buf, bol, lno);
1048                        show_line(opt, bol, eol, name, lno, ':');
1049                        last_hit = lno;
1050                }
1051                else if (last_hit &&
1052                         lno <= last_hit + opt->post_context) {
1053                        /* If the last hit is within the post context,
1054                         * we need to show this line.
1055                         */
1056                        show_line(opt, bol, eol, name, lno, '-');
1057                }
1058
1059        next_line:
1060                bol = eol + 1;
1061                if (!left)
1062                        break;
1063                left--;
1064                lno++;
1065        }
1066
1067        if (collect_hits)
1068                return 0;
1069
1070        if (opt->status_only)
1071                return 0;
1072        if (opt->unmatch_name_only) {
1073                /* We did not see any hit, so we want to show this */
1074                show_name(opt, name);
1075                return 1;
1076        }
1077
1078        xdiff_clear_find_func(&xecfg);
1079        opt->priv = NULL;
1080
1081        /* NEEDSWORK:
1082         * The real "grep -c foo *.c" gives many "bar.c:0" lines,
1083         * which feels mostly useless but sometimes useful.  Maybe
1084         * make it another option?  For now suppress them.
1085         */
1086        if (opt->count && count) {
1087                char buf[32];
1088                output_color(opt, name, strlen(name), opt->color_filename);
1089                output_sep(opt, ':');
1090                snprintf(buf, sizeof(buf), "%u\n", count);
1091                opt->output(opt, buf, strlen(buf));
1092                return 1;
1093        }
1094        return !!last_hit;
1095}
1096
1097static void clr_hit_marker(struct grep_expr *x)
1098{
1099        /* All-hit markers are meaningful only at the very top level
1100         * OR node.
1101         */
1102        while (1) {
1103                x->hit = 0;
1104                if (x->node != GREP_NODE_OR)
1105                        return;
1106                x->u.binary.left->hit = 0;
1107                x = x->u.binary.right;
1108        }
1109}
1110
1111static int chk_hit_marker(struct grep_expr *x)
1112{
1113        /* Top level nodes have hit markers.  See if they all are hits */
1114        while (1) {
1115                if (x->node != GREP_NODE_OR)
1116                        return x->hit;
1117                if (!x->u.binary.left->hit)
1118                        return 0;
1119                x = x->u.binary.right;
1120        }
1121}
1122
1123int grep_buffer(struct grep_opt *opt, const char *name, char *buf, unsigned long size)
1124{
1125        /*
1126         * we do not have to do the two-pass grep when we do not check
1127         * buffer-wide "all-match".
1128         */
1129        if (!opt->all_match)
1130                return grep_buffer_1(opt, name, buf, size, 0);
1131
1132        /* Otherwise the toplevel "or" terms hit a bit differently.
1133         * We first clear hit markers from them.
1134         */
1135        clr_hit_marker(opt->pattern_expression);
1136        grep_buffer_1(opt, name, buf, size, 1);
1137
1138        if (!chk_hit_marker(opt->pattern_expression))
1139                return 0;
1140
1141        return grep_buffer_1(opt, name, buf, size, 0);
1142}