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