grep.c 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210
  1. #include "cache.h"
  2. #include "config.h"
  3. #include "grep.h"
  4. #include "object-store.h"
  5. #include "userdiff.h"
  6. #include "xdiff-interface.h"
  7. #include "diff.h"
  8. #include "diffcore.h"
  9. #include "commit.h"
  10. #include "quote.h"
  11. #include "help.h"
  12. static int grep_source_load(struct grep_source *gs);
  13. static int grep_source_is_binary(struct grep_source *gs,
  14. struct index_state *istate);
  15. static struct grep_opt grep_defaults;
  16. #ifdef USE_LIBPCRE2
  17. static pcre2_general_context *pcre2_global_context;
  18. static void *pcre2_malloc(PCRE2_SIZE size, MAYBE_UNUSED void *memory_data)
  19. {
  20. return malloc(size);
  21. }
  22. static void pcre2_free(void *pointer, MAYBE_UNUSED void *memory_data)
  23. {
  24. free(pointer);
  25. }
  26. #endif
  27. static const char *color_grep_slots[] = {
  28. [GREP_COLOR_CONTEXT] = "context",
  29. [GREP_COLOR_FILENAME] = "filename",
  30. [GREP_COLOR_FUNCTION] = "function",
  31. [GREP_COLOR_LINENO] = "lineNumber",
  32. [GREP_COLOR_COLUMNNO] = "column",
  33. [GREP_COLOR_MATCH_CONTEXT] = "matchContext",
  34. [GREP_COLOR_MATCH_SELECTED] = "matchSelected",
  35. [GREP_COLOR_SELECTED] = "selected",
  36. [GREP_COLOR_SEP] = "separator",
  37. };
  38. static void std_output(struct grep_opt *opt, const void *buf, size_t size)
  39. {
  40. fwrite(buf, size, 1, stdout);
  41. }
  42. static void color_set(char *dst, const char *color_bytes)
  43. {
  44. xsnprintf(dst, COLOR_MAXLEN, "%s", color_bytes);
  45. }
  46. /*
  47. * Initialize the grep_defaults template with hardcoded defaults.
  48. * We could let the compiler do this, but without C99 initializers
  49. * the code gets unwieldy and unreadable, so...
  50. */
  51. void init_grep_defaults(struct repository *repo)
  52. {
  53. struct grep_opt *opt = &grep_defaults;
  54. static int run_once;
  55. if (run_once)
  56. return;
  57. run_once++;
  58. memset(opt, 0, sizeof(*opt));
  59. opt->repo = repo;
  60. opt->relative = 1;
  61. opt->pathname = 1;
  62. opt->max_depth = -1;
  63. opt->pattern_type_option = GREP_PATTERN_TYPE_UNSPECIFIED;
  64. color_set(opt->colors[GREP_COLOR_CONTEXT], "");
  65. color_set(opt->colors[GREP_COLOR_FILENAME], "");
  66. color_set(opt->colors[GREP_COLOR_FUNCTION], "");
  67. color_set(opt->colors[GREP_COLOR_LINENO], "");
  68. color_set(opt->colors[GREP_COLOR_COLUMNNO], "");
  69. color_set(opt->colors[GREP_COLOR_MATCH_CONTEXT], GIT_COLOR_BOLD_RED);
  70. color_set(opt->colors[GREP_COLOR_MATCH_SELECTED], GIT_COLOR_BOLD_RED);
  71. color_set(opt->colors[GREP_COLOR_SELECTED], "");
  72. color_set(opt->colors[GREP_COLOR_SEP], GIT_COLOR_CYAN);
  73. opt->only_matching = 0;
  74. opt->color = -1;
  75. opt->output = std_output;
  76. }
  77. static int parse_pattern_type_arg(const char *opt, const char *arg)
  78. {
  79. if (!strcmp(arg, "default"))
  80. return GREP_PATTERN_TYPE_UNSPECIFIED;
  81. else if (!strcmp(arg, "basic"))
  82. return GREP_PATTERN_TYPE_BRE;
  83. else if (!strcmp(arg, "extended"))
  84. return GREP_PATTERN_TYPE_ERE;
  85. else if (!strcmp(arg, "fixed"))
  86. return GREP_PATTERN_TYPE_FIXED;
  87. else if (!strcmp(arg, "perl"))
  88. return GREP_PATTERN_TYPE_PCRE;
  89. die("bad %s argument: %s", opt, arg);
  90. }
  91. define_list_config_array_extra(color_grep_slots, {"match"});
  92. /*
  93. * Read the configuration file once and store it in
  94. * the grep_defaults template.
  95. */
  96. int grep_config(const char *var, const char *value, void *cb)
  97. {
  98. struct grep_opt *opt = &grep_defaults;
  99. const char *slot;
  100. if (userdiff_config(var, value) < 0)
  101. return -1;
  102. if (!strcmp(var, "grep.extendedregexp")) {
  103. opt->extended_regexp_option = git_config_bool(var, value);
  104. return 0;
  105. }
  106. if (!strcmp(var, "grep.patterntype")) {
  107. opt->pattern_type_option = parse_pattern_type_arg(var, value);
  108. return 0;
  109. }
  110. if (!strcmp(var, "grep.linenumber")) {
  111. opt->linenum = git_config_bool(var, value);
  112. return 0;
  113. }
  114. if (!strcmp(var, "grep.column")) {
  115. opt->columnnum = git_config_bool(var, value);
  116. return 0;
  117. }
  118. if (!strcmp(var, "grep.fullname")) {
  119. opt->relative = !git_config_bool(var, value);
  120. return 0;
  121. }
  122. if (!strcmp(var, "color.grep"))
  123. opt->color = git_config_colorbool(var, value);
  124. if (!strcmp(var, "color.grep.match")) {
  125. if (grep_config("color.grep.matchcontext", value, cb) < 0)
  126. return -1;
  127. if (grep_config("color.grep.matchselected", value, cb) < 0)
  128. return -1;
  129. } else if (skip_prefix(var, "color.grep.", &slot)) {
  130. int i = LOOKUP_CONFIG(color_grep_slots, slot);
  131. char *color;
  132. if (i < 0)
  133. return -1;
  134. color = opt->colors[i];
  135. if (!value)
  136. return config_error_nonbool(var);
  137. return color_parse(value, color);
  138. }
  139. return 0;
  140. }
  141. /*
  142. * Initialize one instance of grep_opt and copy the
  143. * default values from the template we read the configuration
  144. * information in an earlier call to git_config(grep_config).
  145. *
  146. * If using PCRE, make sure that the library is configured
  147. * to use the same allocator as Git (e.g. nedmalloc on Windows).
  148. *
  149. * Any allocated memory needs to be released in grep_destroy().
  150. */
  151. void grep_init(struct grep_opt *opt, struct repository *repo, const char *prefix)
  152. {
  153. struct grep_opt *def = &grep_defaults;
  154. int i;
  155. #if defined(USE_LIBPCRE2)
  156. if (!pcre2_global_context)
  157. pcre2_global_context = pcre2_general_context_create(
  158. pcre2_malloc, pcre2_free, NULL);
  159. #endif
  160. #ifdef USE_LIBPCRE1
  161. pcre_malloc = malloc;
  162. pcre_free = free;
  163. #endif
  164. memset(opt, 0, sizeof(*opt));
  165. opt->repo = repo;
  166. opt->prefix = prefix;
  167. opt->prefix_length = (prefix && *prefix) ? strlen(prefix) : 0;
  168. opt->pattern_tail = &opt->pattern_list;
  169. opt->header_tail = &opt->header_list;
  170. opt->only_matching = def->only_matching;
  171. opt->color = def->color;
  172. opt->extended_regexp_option = def->extended_regexp_option;
  173. opt->pattern_type_option = def->pattern_type_option;
  174. opt->linenum = def->linenum;
  175. opt->columnnum = def->columnnum;
  176. opt->max_depth = def->max_depth;
  177. opt->pathname = def->pathname;
  178. opt->relative = def->relative;
  179. opt->output = def->output;
  180. for (i = 0; i < NR_GREP_COLORS; i++)
  181. color_set(opt->colors[i], def->colors[i]);
  182. }
  183. void grep_destroy(void)
  184. {
  185. #ifdef USE_LIBPCRE2
  186. pcre2_general_context_free(pcre2_global_context);
  187. #endif
  188. }
  189. static void grep_set_pattern_type_option(enum grep_pattern_type pattern_type, struct grep_opt *opt)
  190. {
  191. /*
  192. * When committing to the pattern type by setting the relevant
  193. * fields in grep_opt it's generally not necessary to zero out
  194. * the fields we're not choosing, since they won't have been
  195. * set by anything. The extended_regexp_option field is the
  196. * only exception to this.
  197. *
  198. * This is because in the process of parsing grep.patternType
  199. * & grep.extendedRegexp we set opt->pattern_type_option and
  200. * opt->extended_regexp_option, respectively. We then
  201. * internally use opt->extended_regexp_option to see if we're
  202. * compiling an ERE. It must be unset if that's not actually
  203. * the case.
  204. */
  205. if (pattern_type != GREP_PATTERN_TYPE_ERE &&
  206. opt->extended_regexp_option)
  207. opt->extended_regexp_option = 0;
  208. switch (pattern_type) {
  209. case GREP_PATTERN_TYPE_UNSPECIFIED:
  210. /* fall through */
  211. case GREP_PATTERN_TYPE_BRE:
  212. break;
  213. case GREP_PATTERN_TYPE_ERE:
  214. opt->extended_regexp_option = 1;
  215. break;
  216. case GREP_PATTERN_TYPE_FIXED:
  217. opt->fixed = 1;
  218. break;
  219. case GREP_PATTERN_TYPE_PCRE:
  220. #ifdef USE_LIBPCRE2
  221. opt->pcre2 = 1;
  222. #else
  223. /*
  224. * It's important that pcre1 always be assigned to
  225. * even when there's no USE_LIBPCRE* defined. We still
  226. * call the PCRE stub function, it just dies with
  227. * "cannot use Perl-compatible regexes[...]".
  228. */
  229. opt->pcre1 = 1;
  230. #endif
  231. break;
  232. }
  233. }
  234. void grep_commit_pattern_type(enum grep_pattern_type pattern_type, struct grep_opt *opt)
  235. {
  236. if (pattern_type != GREP_PATTERN_TYPE_UNSPECIFIED)
  237. grep_set_pattern_type_option(pattern_type, opt);
  238. else if (opt->pattern_type_option != GREP_PATTERN_TYPE_UNSPECIFIED)
  239. grep_set_pattern_type_option(opt->pattern_type_option, opt);
  240. else if (opt->extended_regexp_option)
  241. /*
  242. * This branch *must* happen after setting from the
  243. * opt->pattern_type_option above, we don't want
  244. * grep.extendedRegexp to override grep.patternType!
  245. */
  246. grep_set_pattern_type_option(GREP_PATTERN_TYPE_ERE, opt);
  247. }
  248. static struct grep_pat *create_grep_pat(const char *pat, size_t patlen,
  249. const char *origin, int no,
  250. enum grep_pat_token t,
  251. enum grep_header_field field)
  252. {
  253. struct grep_pat *p = xcalloc(1, sizeof(*p));
  254. p->pattern = xmemdupz(pat, patlen);
  255. p->patternlen = patlen;
  256. p->origin = origin;
  257. p->no = no;
  258. p->token = t;
  259. p->field = field;
  260. return p;
  261. }
  262. static void do_append_grep_pat(struct grep_pat ***tail, struct grep_pat *p)
  263. {
  264. **tail = p;
  265. *tail = &p->next;
  266. p->next = NULL;
  267. switch (p->token) {
  268. case GREP_PATTERN: /* atom */
  269. case GREP_PATTERN_HEAD:
  270. case GREP_PATTERN_BODY:
  271. for (;;) {
  272. struct grep_pat *new_pat;
  273. size_t len = 0;
  274. char *cp = p->pattern + p->patternlen, *nl = NULL;
  275. while (++len <= p->patternlen) {
  276. if (*(--cp) == '\n') {
  277. nl = cp;
  278. break;
  279. }
  280. }
  281. if (!nl)
  282. break;
  283. new_pat = create_grep_pat(nl + 1, len - 1, p->origin,
  284. p->no, p->token, p->field);
  285. new_pat->next = p->next;
  286. if (!p->next)
  287. *tail = &new_pat->next;
  288. p->next = new_pat;
  289. *nl = '\0';
  290. p->patternlen -= len;
  291. }
  292. break;
  293. default:
  294. break;
  295. }
  296. }
  297. void append_header_grep_pattern(struct grep_opt *opt,
  298. enum grep_header_field field, const char *pat)
  299. {
  300. struct grep_pat *p = create_grep_pat(pat, strlen(pat), "header", 0,
  301. GREP_PATTERN_HEAD, field);
  302. if (field == GREP_HEADER_REFLOG)
  303. opt->use_reflog_filter = 1;
  304. do_append_grep_pat(&opt->header_tail, p);
  305. }
  306. void append_grep_pattern(struct grep_opt *opt, const char *pat,
  307. const char *origin, int no, enum grep_pat_token t)
  308. {
  309. append_grep_pat(opt, pat, strlen(pat), origin, no, t);
  310. }
  311. void append_grep_pat(struct grep_opt *opt, const char *pat, size_t patlen,
  312. const char *origin, int no, enum grep_pat_token t)
  313. {
  314. struct grep_pat *p = create_grep_pat(pat, patlen, origin, no, t, 0);
  315. do_append_grep_pat(&opt->pattern_tail, p);
  316. }
  317. struct grep_opt *grep_opt_dup(const struct grep_opt *opt)
  318. {
  319. struct grep_pat *pat;
  320. struct grep_opt *ret = xmalloc(sizeof(struct grep_opt));
  321. *ret = *opt;
  322. ret->pattern_list = NULL;
  323. ret->pattern_tail = &ret->pattern_list;
  324. for(pat = opt->pattern_list; pat != NULL; pat = pat->next)
  325. {
  326. if(pat->token == GREP_PATTERN_HEAD)
  327. append_header_grep_pattern(ret, pat->field,
  328. pat->pattern);
  329. else
  330. append_grep_pat(ret, pat->pattern, pat->patternlen,
  331. pat->origin, pat->no, pat->token);
  332. }
  333. return ret;
  334. }
  335. static NORETURN void compile_regexp_failed(const struct grep_pat *p,
  336. const char *error)
  337. {
  338. char where[1024];
  339. if (p->no)
  340. xsnprintf(where, sizeof(where), "In '%s' at %d, ", p->origin, p->no);
  341. else if (p->origin)
  342. xsnprintf(where, sizeof(where), "%s, ", p->origin);
  343. else
  344. where[0] = 0;
  345. die("%s'%s': %s", where, p->pattern, error);
  346. }
  347. static int is_fixed(const char *s, size_t len)
  348. {
  349. size_t i;
  350. for (i = 0; i < len; i++) {
  351. if (is_regex_special(s[i]))
  352. return 0;
  353. }
  354. return 1;
  355. }
  356. #ifdef USE_LIBPCRE1
  357. static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
  358. {
  359. const char *error;
  360. int erroffset;
  361. int options = PCRE_MULTILINE;
  362. int study_options = 0;
  363. if (opt->ignore_case) {
  364. if (!opt->ignore_locale && has_non_ascii(p->pattern))
  365. p->pcre1_tables = pcre_maketables();
  366. options |= PCRE_CASELESS;
  367. }
  368. if (!opt->ignore_locale && is_utf8_locale() && has_non_ascii(p->pattern))
  369. options |= PCRE_UTF8;
  370. p->pcre1_regexp = pcre_compile(p->pattern, options, &error, &erroffset,
  371. p->pcre1_tables);
  372. if (!p->pcre1_regexp)
  373. compile_regexp_failed(p, error);
  374. #if defined(PCRE_CONFIG_JIT) && !defined(NO_LIBPCRE1_JIT)
  375. pcre_config(PCRE_CONFIG_JIT, &p->pcre1_jit_on);
  376. if (opt->debug)
  377. fprintf(stderr, "pcre1_jit_on=%d\n", p->pcre1_jit_on);
  378. if (p->pcre1_jit_on)
  379. study_options = PCRE_STUDY_JIT_COMPILE;
  380. #endif
  381. p->pcre1_extra_info = pcre_study(p->pcre1_regexp, study_options, &error);
  382. if (!p->pcre1_extra_info && error)
  383. die("%s", error);
  384. }
  385. static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
  386. regmatch_t *match, int eflags)
  387. {
  388. int ovector[30], ret, flags = PCRE_NO_UTF8_CHECK;
  389. if (eflags & REG_NOTBOL)
  390. flags |= PCRE_NOTBOL;
  391. ret = pcre_exec(p->pcre1_regexp, p->pcre1_extra_info, line,
  392. eol - line, 0, flags, ovector,
  393. ARRAY_SIZE(ovector));
  394. if (ret < 0 && ret != PCRE_ERROR_NOMATCH)
  395. die("pcre_exec failed with error code %d", ret);
  396. if (ret > 0) {
  397. ret = 0;
  398. match->rm_so = ovector[0];
  399. match->rm_eo = ovector[1];
  400. }
  401. return ret;
  402. }
  403. static void free_pcre1_regexp(struct grep_pat *p)
  404. {
  405. pcre_free(p->pcre1_regexp);
  406. #ifdef PCRE_CONFIG_JIT
  407. if (p->pcre1_jit_on)
  408. pcre_free_study(p->pcre1_extra_info);
  409. else
  410. #endif
  411. pcre_free(p->pcre1_extra_info);
  412. pcre_free((void *)p->pcre1_tables);
  413. }
  414. #else /* !USE_LIBPCRE1 */
  415. static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
  416. {
  417. die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
  418. }
  419. static int pcre1match(struct grep_pat *p, const char *line, const char *eol,
  420. regmatch_t *match, int eflags)
  421. {
  422. return 1;
  423. }
  424. static void free_pcre1_regexp(struct grep_pat *p)
  425. {
  426. }
  427. #endif /* !USE_LIBPCRE1 */
  428. #ifdef USE_LIBPCRE2
  429. static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
  430. {
  431. int error;
  432. PCRE2_UCHAR errbuf[256];
  433. PCRE2_SIZE erroffset;
  434. int options = PCRE2_MULTILINE;
  435. int jitret;
  436. int patinforet;
  437. size_t jitsizearg;
  438. assert(opt->pcre2);
  439. p->pcre2_compile_context = NULL;
  440. /* pcre2_global_context is initialized in append_grep_pattern */
  441. if (opt->ignore_case) {
  442. if (!opt->ignore_locale && has_non_ascii(p->pattern)) {
  443. if (!pcre2_global_context)
  444. BUG("pcre2_global_context uninitialized");
  445. p->pcre2_tables = pcre2_maketables(pcre2_global_context);
  446. p->pcre2_compile_context = pcre2_compile_context_create(NULL);
  447. pcre2_set_character_tables(p->pcre2_compile_context,
  448. p->pcre2_tables);
  449. }
  450. options |= PCRE2_CASELESS;
  451. }
  452. if (!opt->ignore_locale && is_utf8_locale() && has_non_ascii(p->pattern) &&
  453. !(!opt->ignore_case && (p->fixed || p->is_fixed)))
  454. options |= PCRE2_UTF;
  455. p->pcre2_pattern = pcre2_compile((PCRE2_SPTR)p->pattern,
  456. p->patternlen, options, &error, &erroffset,
  457. p->pcre2_compile_context);
  458. if (p->pcre2_pattern) {
  459. p->pcre2_match_data = pcre2_match_data_create_from_pattern(p->pcre2_pattern, NULL);
  460. if (!p->pcre2_match_data)
  461. die("Couldn't allocate PCRE2 match data");
  462. } else {
  463. pcre2_get_error_message(error, errbuf, sizeof(errbuf));
  464. compile_regexp_failed(p, (const char *)&errbuf);
  465. }
  466. pcre2_config(PCRE2_CONFIG_JIT, &p->pcre2_jit_on);
  467. if (opt->debug)
  468. fprintf(stderr, "pcre2_jit_on=%d\n", p->pcre2_jit_on);
  469. if (p->pcre2_jit_on) {
  470. jitret = pcre2_jit_compile(p->pcre2_pattern, PCRE2_JIT_COMPLETE);
  471. if (jitret)
  472. die("Couldn't JIT the PCRE2 pattern '%s', got '%d'\n", p->pattern, jitret);
  473. /*
  474. * The pcre2_config(PCRE2_CONFIG_JIT, ...) call just
  475. * tells us whether the library itself supports JIT,
  476. * but to see whether we're going to be actually using
  477. * JIT we need to extract PCRE2_INFO_JITSIZE from the
  478. * pattern *after* we do pcre2_jit_compile() above.
  479. *
  480. * This is because if the pattern contains the
  481. * (*NO_JIT) verb (see pcre2syntax(3))
  482. * pcre2_jit_compile() will exit early with 0. If we
  483. * then proceed to call pcre2_jit_match() further down
  484. * the line instead of pcre2_match() we'll either
  485. * segfault (pre PCRE 10.31) or run into a fatal error
  486. * (post PCRE2 10.31)
  487. */
  488. patinforet = pcre2_pattern_info(p->pcre2_pattern, PCRE2_INFO_JITSIZE, &jitsizearg);
  489. if (patinforet)
  490. BUG("pcre2_pattern_info() failed: %d", patinforet);
  491. if (jitsizearg == 0) {
  492. p->pcre2_jit_on = 0;
  493. if (opt->debug)
  494. fprintf(stderr, "pcre2_jit_on=%d: (*NO_JIT) in regex\n",
  495. p->pcre2_jit_on);
  496. return;
  497. }
  498. }
  499. }
  500. static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
  501. regmatch_t *match, int eflags)
  502. {
  503. int ret, flags = 0;
  504. PCRE2_SIZE *ovector;
  505. PCRE2_UCHAR errbuf[256];
  506. if (eflags & REG_NOTBOL)
  507. flags |= PCRE2_NOTBOL;
  508. if (p->pcre2_jit_on)
  509. ret = pcre2_jit_match(p->pcre2_pattern, (unsigned char *)line,
  510. eol - line, 0, flags, p->pcre2_match_data,
  511. NULL);
  512. else
  513. ret = pcre2_match(p->pcre2_pattern, (unsigned char *)line,
  514. eol - line, 0, flags, p->pcre2_match_data,
  515. NULL);
  516. if (ret < 0 && ret != PCRE2_ERROR_NOMATCH) {
  517. pcre2_get_error_message(ret, errbuf, sizeof(errbuf));
  518. die("%s failed with error code %d: %s",
  519. (p->pcre2_jit_on ? "pcre2_jit_match" : "pcre2_match"), ret,
  520. errbuf);
  521. }
  522. if (ret > 0) {
  523. ovector = pcre2_get_ovector_pointer(p->pcre2_match_data);
  524. ret = 0;
  525. match->rm_so = (int)ovector[0];
  526. match->rm_eo = (int)ovector[1];
  527. }
  528. return ret;
  529. }
  530. static void free_pcre2_pattern(struct grep_pat *p)
  531. {
  532. pcre2_compile_context_free(p->pcre2_compile_context);
  533. pcre2_code_free(p->pcre2_pattern);
  534. pcre2_match_data_free(p->pcre2_match_data);
  535. free((void *)p->pcre2_tables);
  536. }
  537. #else /* !USE_LIBPCRE2 */
  538. static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt)
  539. {
  540. /*
  541. * Unreachable until USE_LIBPCRE2 becomes synonymous with
  542. * USE_LIBPCRE. See the sibling comment in
  543. * grep_set_pattern_type_option().
  544. */
  545. die("cannot use Perl-compatible regexes when not compiled with USE_LIBPCRE");
  546. }
  547. static int pcre2match(struct grep_pat *p, const char *line, const char *eol,
  548. regmatch_t *match, int eflags)
  549. {
  550. return 1;
  551. }
  552. static void free_pcre2_pattern(struct grep_pat *p)
  553. {
  554. }
  555. static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
  556. {
  557. struct strbuf sb = STRBUF_INIT;
  558. int err;
  559. int regflags = 0;
  560. basic_regex_quote_buf(&sb, p->pattern);
  561. if (opt->ignore_case)
  562. regflags |= REG_ICASE;
  563. err = regcomp(&p->regexp, sb.buf, regflags);
  564. if (opt->debug)
  565. fprintf(stderr, "fixed %s\n", sb.buf);
  566. strbuf_release(&sb);
  567. if (err) {
  568. char errbuf[1024];
  569. regerror(err, &p->regexp, errbuf, sizeof(errbuf));
  570. compile_regexp_failed(p, errbuf);
  571. }
  572. }
  573. #endif /* !USE_LIBPCRE2 */
  574. static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
  575. {
  576. int err;
  577. int regflags = REG_NEWLINE;
  578. p->word_regexp = opt->word_regexp;
  579. p->ignore_case = opt->ignore_case;
  580. p->fixed = opt->fixed;
  581. if (memchr(p->pattern, 0, p->patternlen) && !opt->pcre2)
  582. die(_("given pattern contains NULL byte (via -f <file>). This is only supported with -P under PCRE v2"));
  583. p->is_fixed = is_fixed(p->pattern, p->patternlen);
  584. #ifdef USE_LIBPCRE2
  585. if (!p->fixed && !p->is_fixed) {
  586. const char *no_jit = "(*NO_JIT)";
  587. const int no_jit_len = strlen(no_jit);
  588. if (starts_with(p->pattern, no_jit) &&
  589. is_fixed(p->pattern + no_jit_len,
  590. p->patternlen - no_jit_len))
  591. p->is_fixed = 1;
  592. }
  593. #endif
  594. if (p->fixed || p->is_fixed) {
  595. #ifdef USE_LIBPCRE2
  596. opt->pcre2 = 1;
  597. if (p->is_fixed) {
  598. compile_pcre2_pattern(p, opt);
  599. } else {
  600. /*
  601. * E.g. t7811-grep-open.sh relies on the
  602. * pattern being restored.
  603. */
  604. char *old_pattern = p->pattern;
  605. size_t old_patternlen = p->patternlen;
  606. struct strbuf sb = STRBUF_INIT;
  607. /*
  608. * There is the PCRE2_LITERAL flag, but it's
  609. * only in PCRE v2 10.30 and later. Needing to
  610. * ifdef our way around that and dealing with
  611. * it + PCRE2_MULTILINE being an error is more
  612. * complex than just quoting this ourselves.
  613. */
  614. strbuf_add(&sb, "\\Q", 2);
  615. strbuf_add(&sb, p->pattern, p->patternlen);
  616. strbuf_add(&sb, "\\E", 2);
  617. p->pattern = sb.buf;
  618. p->patternlen = sb.len;
  619. compile_pcre2_pattern(p, opt);
  620. p->pattern = old_pattern;
  621. p->patternlen = old_patternlen;
  622. strbuf_release(&sb);
  623. }
  624. #else /* !USE_LIBPCRE2 */
  625. compile_fixed_regexp(p, opt);
  626. #endif /* !USE_LIBPCRE2 */
  627. return;
  628. }
  629. if (opt->pcre2) {
  630. compile_pcre2_pattern(p, opt);
  631. return;
  632. }
  633. if (opt->pcre1) {
  634. compile_pcre1_regexp(p, opt);
  635. return;
  636. }
  637. if (p->ignore_case)
  638. regflags |= REG_ICASE;
  639. if (opt->extended_regexp_option)
  640. regflags |= REG_EXTENDED;
  641. err = regcomp(&p->regexp, p->pattern, regflags);
  642. if (err) {
  643. char errbuf[1024];
  644. regerror(err, &p->regexp, errbuf, 1024);
  645. compile_regexp_failed(p, errbuf);
  646. }
  647. }
  648. static struct grep_expr *compile_pattern_or(struct grep_pat **);
  649. static struct grep_expr *compile_pattern_atom(struct grep_pat **list)
  650. {
  651. struct grep_pat *p;
  652. struct grep_expr *x;
  653. p = *list;
  654. if (!p)
  655. return NULL;
  656. switch (p->token) {
  657. case GREP_PATTERN: /* atom */
  658. case GREP_PATTERN_HEAD:
  659. case GREP_PATTERN_BODY:
  660. x = xcalloc(1, sizeof (struct grep_expr));
  661. x->node = GREP_NODE_ATOM;
  662. x->u.atom = p;
  663. *list = p->next;
  664. return x;
  665. case GREP_OPEN_PAREN:
  666. *list = p->next;
  667. x = compile_pattern_or(list);
  668. if (!*list || (*list)->token != GREP_CLOSE_PAREN)
  669. die("unmatched parenthesis");
  670. *list = (*list)->next;
  671. return x;
  672. default:
  673. return NULL;
  674. }
  675. }
  676. static struct grep_expr *compile_pattern_not(struct grep_pat **list)
  677. {
  678. struct grep_pat *p;
  679. struct grep_expr *x;
  680. p = *list;
  681. if (!p)
  682. return NULL;
  683. switch (p->token) {
  684. case GREP_NOT:
  685. if (!p->next)
  686. die("--not not followed by pattern expression");
  687. *list = p->next;
  688. x = xcalloc(1, sizeof (struct grep_expr));
  689. x->node = GREP_NODE_NOT;
  690. x->u.unary = compile_pattern_not(list);
  691. if (!x->u.unary)
  692. die("--not followed by non pattern expression");
  693. return x;
  694. default:
  695. return compile_pattern_atom(list);
  696. }
  697. }
  698. static struct grep_expr *compile_pattern_and(struct grep_pat **list)
  699. {
  700. struct grep_pat *p;
  701. struct grep_expr *x, *y, *z;
  702. x = compile_pattern_not(list);
  703. p = *list;
  704. if (p && p->token == GREP_AND) {
  705. if (!p->next)
  706. die("--and not followed by pattern expression");
  707. *list = p->next;
  708. y = compile_pattern_and(list);
  709. if (!y)
  710. die("--and not followed by pattern expression");
  711. z = xcalloc(1, sizeof (struct grep_expr));
  712. z->node = GREP_NODE_AND;
  713. z->u.binary.left = x;
  714. z->u.binary.right = y;
  715. return z;
  716. }
  717. return x;
  718. }
  719. static struct grep_expr *compile_pattern_or(struct grep_pat **list)
  720. {
  721. struct grep_pat *p;
  722. struct grep_expr *x, *y, *z;
  723. x = compile_pattern_and(list);
  724. p = *list;
  725. if (x && p && p->token != GREP_CLOSE_PAREN) {
  726. y = compile_pattern_or(list);
  727. if (!y)
  728. die("not a pattern expression %s", p->pattern);
  729. z = xcalloc(1, sizeof (struct grep_expr));
  730. z->node = GREP_NODE_OR;
  731. z->u.binary.left = x;
  732. z->u.binary.right = y;
  733. return z;
  734. }
  735. return x;
  736. }
  737. static struct grep_expr *compile_pattern_expr(struct grep_pat **list)
  738. {
  739. return compile_pattern_or(list);
  740. }
  741. static void indent(int in)
  742. {
  743. while (in-- > 0)
  744. fputc(' ', stderr);
  745. }
  746. static void dump_grep_pat(struct grep_pat *p)
  747. {
  748. switch (p->token) {
  749. case GREP_AND: fprintf(stderr, "*and*"); break;
  750. case GREP_OPEN_PAREN: fprintf(stderr, "*(*"); break;
  751. case GREP_CLOSE_PAREN: fprintf(stderr, "*)*"); break;
  752. case GREP_NOT: fprintf(stderr, "*not*"); break;
  753. case GREP_OR: fprintf(stderr, "*or*"); break;
  754. case GREP_PATTERN: fprintf(stderr, "pattern"); break;
  755. case GREP_PATTERN_HEAD: fprintf(stderr, "pattern_head"); break;
  756. case GREP_PATTERN_BODY: fprintf(stderr, "pattern_body"); break;
  757. }
  758. switch (p->token) {
  759. default: break;
  760. case GREP_PATTERN_HEAD:
  761. fprintf(stderr, "<head %d>", p->field); break;
  762. case GREP_PATTERN_BODY:
  763. fprintf(stderr, "<body>"); break;
  764. }
  765. switch (p->token) {
  766. default: break;
  767. case GREP_PATTERN_HEAD:
  768. case GREP_PATTERN_BODY:
  769. case GREP_PATTERN:
  770. fprintf(stderr, "%.*s", (int)p->patternlen, p->pattern);
  771. break;
  772. }
  773. fputc('\n', stderr);
  774. }
  775. static void dump_grep_expression_1(struct grep_expr *x, int in)
  776. {
  777. indent(in);
  778. switch (x->node) {
  779. case GREP_NODE_TRUE:
  780. fprintf(stderr, "true\n");
  781. break;
  782. case GREP_NODE_ATOM:
  783. dump_grep_pat(x->u.atom);
  784. break;
  785. case GREP_NODE_NOT:
  786. fprintf(stderr, "(not\n");
  787. dump_grep_expression_1(x->u.unary, in+1);
  788. indent(in);
  789. fprintf(stderr, ")\n");
  790. break;
  791. case GREP_NODE_AND:
  792. fprintf(stderr, "(and\n");
  793. dump_grep_expression_1(x->u.binary.left, in+1);
  794. dump_grep_expression_1(x->u.binary.right, in+1);
  795. indent(in);
  796. fprintf(stderr, ")\n");
  797. break;
  798. case GREP_NODE_OR:
  799. fprintf(stderr, "(or\n");
  800. dump_grep_expression_1(x->u.binary.left, in+1);
  801. dump_grep_expression_1(x->u.binary.right, in+1);
  802. indent(in);
  803. fprintf(stderr, ")\n");
  804. break;
  805. }
  806. }
  807. static void dump_grep_expression(struct grep_opt *opt)
  808. {
  809. struct grep_expr *x = opt->pattern_expression;
  810. if (opt->all_match)
  811. fprintf(stderr, "[all-match]\n");
  812. dump_grep_expression_1(x, 0);
  813. fflush(NULL);
  814. }
  815. static struct grep_expr *grep_true_expr(void)
  816. {
  817. struct grep_expr *z = xcalloc(1, sizeof(*z));
  818. z->node = GREP_NODE_TRUE;
  819. return z;
  820. }
  821. static struct grep_expr *grep_or_expr(struct grep_expr *left, struct grep_expr *right)
  822. {
  823. struct grep_expr *z = xcalloc(1, sizeof(*z));
  824. z->node = GREP_NODE_OR;
  825. z->u.binary.left = left;
  826. z->u.binary.right = right;
  827. return z;
  828. }
  829. static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
  830. {
  831. struct grep_pat *p;
  832. struct grep_expr *header_expr;
  833. struct grep_expr *(header_group[GREP_HEADER_FIELD_MAX]);
  834. enum grep_header_field fld;
  835. if (!opt->header_list)
  836. return NULL;
  837. for (p = opt->header_list; p; p = p->next) {
  838. if (p->token != GREP_PATTERN_HEAD)
  839. BUG("a non-header pattern in grep header list.");
  840. if (p->field < GREP_HEADER_FIELD_MIN ||
  841. GREP_HEADER_FIELD_MAX <= p->field)
  842. BUG("unknown header field %d", p->field);
  843. compile_regexp(p, opt);
  844. }
  845. for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++)
  846. header_group[fld] = NULL;
  847. for (p = opt->header_list; p; p = p->next) {
  848. struct grep_expr *h;
  849. struct grep_pat *pp = p;
  850. h = compile_pattern_atom(&pp);
  851. if (!h || pp != p->next)
  852. BUG("malformed header expr");
  853. if (!header_group[p->field]) {
  854. header_group[p->field] = h;
  855. continue;
  856. }
  857. header_group[p->field] = grep_or_expr(h, header_group[p->field]);
  858. }
  859. header_expr = NULL;
  860. for (fld = 0; fld < GREP_HEADER_FIELD_MAX; fld++) {
  861. if (!header_group[fld])
  862. continue;
  863. if (!header_expr)
  864. header_expr = grep_true_expr();
  865. header_expr = grep_or_expr(header_group[fld], header_expr);
  866. }
  867. return header_expr;
  868. }
  869. static struct grep_expr *grep_splice_or(struct grep_expr *x, struct grep_expr *y)
  870. {
  871. struct grep_expr *z = x;
  872. while (x) {
  873. assert(x->node == GREP_NODE_OR);
  874. if (x->u.binary.right &&
  875. x->u.binary.right->node == GREP_NODE_TRUE) {
  876. x->u.binary.right = y;
  877. break;
  878. }
  879. x = x->u.binary.right;
  880. }
  881. return z;
  882. }
  883. static void compile_grep_patterns_real(struct grep_opt *opt)
  884. {
  885. struct grep_pat *p;
  886. struct grep_expr *header_expr = prep_header_patterns(opt);
  887. for (p = opt->pattern_list; p; p = p->next) {
  888. switch (p->token) {
  889. case GREP_PATTERN: /* atom */
  890. case GREP_PATTERN_HEAD:
  891. case GREP_PATTERN_BODY:
  892. compile_regexp(p, opt);
  893. break;
  894. default:
  895. opt->extended = 1;
  896. break;
  897. }
  898. }
  899. if (opt->all_match || header_expr)
  900. opt->extended = 1;
  901. else if (!opt->extended && !opt->debug)
  902. return;
  903. p = opt->pattern_list;
  904. if (p)
  905. opt->pattern_expression = compile_pattern_expr(&p);
  906. if (p)
  907. die("incomplete pattern expression: %s", p->pattern);
  908. if (!header_expr)
  909. return;
  910. if (!opt->pattern_expression)
  911. opt->pattern_expression = header_expr;
  912. else if (opt->all_match)
  913. opt->pattern_expression = grep_splice_or(header_expr,
  914. opt->pattern_expression);
  915. else
  916. opt->pattern_expression = grep_or_expr(opt->pattern_expression,
  917. header_expr);
  918. opt->all_match = 1;
  919. }
  920. void compile_grep_patterns(struct grep_opt *opt)
  921. {
  922. compile_grep_patterns_real(opt);
  923. if (opt->debug)
  924. dump_grep_expression(opt);
  925. }
  926. static void free_pattern_expr(struct grep_expr *x)
  927. {
  928. switch (x->node) {
  929. case GREP_NODE_TRUE:
  930. case GREP_NODE_ATOM:
  931. break;
  932. case GREP_NODE_NOT:
  933. free_pattern_expr(x->u.unary);
  934. break;
  935. case GREP_NODE_AND:
  936. case GREP_NODE_OR:
  937. free_pattern_expr(x->u.binary.left);
  938. free_pattern_expr(x->u.binary.right);
  939. break;
  940. }
  941. free(x);
  942. }
  943. void free_grep_patterns(struct grep_opt *opt)
  944. {
  945. struct grep_pat *p, *n;
  946. for (p = opt->pattern_list; p; p = n) {
  947. n = p->next;
  948. switch (p->token) {
  949. case GREP_PATTERN: /* atom */
  950. case GREP_PATTERN_HEAD:
  951. case GREP_PATTERN_BODY:
  952. if (p->pcre1_regexp)
  953. free_pcre1_regexp(p);
  954. else if (p->pcre2_pattern)
  955. free_pcre2_pattern(p);
  956. else
  957. regfree(&p->regexp);
  958. free(p->pattern);
  959. break;
  960. default:
  961. break;
  962. }
  963. free(p);
  964. }
  965. if (!opt->extended)
  966. return;
  967. free_pattern_expr(opt->pattern_expression);
  968. }
  969. static char *end_of_line(char *cp, unsigned long *left)
  970. {
  971. unsigned long l = *left;
  972. while (l && *cp != '\n') {
  973. l--;
  974. cp++;
  975. }
  976. *left = l;
  977. return cp;
  978. }
  979. static int word_char(char ch)
  980. {
  981. return isalnum(ch) || ch == '_';
  982. }
  983. static void output_color(struct grep_opt *opt, const void *data, size_t size,
  984. const char *color)
  985. {
  986. if (want_color(opt->color) && color && color[0]) {
  987. opt->output(opt, color, strlen(color));
  988. opt->output(opt, data, size);
  989. opt->output(opt, GIT_COLOR_RESET, strlen(GIT_COLOR_RESET));
  990. } else
  991. opt->output(opt, data, size);
  992. }
  993. static void output_sep(struct grep_opt *opt, char sign)
  994. {
  995. if (opt->null_following_name)
  996. opt->output(opt, "\0", 1);
  997. else
  998. output_color(opt, &sign, 1, opt->colors[GREP_COLOR_SEP]);
  999. }
  1000. static void show_name(struct grep_opt *opt, const char *name)
  1001. {
  1002. output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
  1003. opt->output(opt, opt->null_following_name ? "\0" : "\n", 1);
  1004. }
  1005. static int patmatch(struct grep_pat *p, char *line, char *eol,
  1006. regmatch_t *match, int eflags)
  1007. {
  1008. int hit;
  1009. if (p->pcre1_regexp)
  1010. hit = !pcre1match(p, line, eol, match, eflags);
  1011. else if (p->pcre2_pattern)
  1012. hit = !pcre2match(p, line, eol, match, eflags);
  1013. else
  1014. hit = !regexec_buf(&p->regexp, line, eol - line, 1, match,
  1015. eflags);
  1016. return hit;
  1017. }
  1018. static int strip_timestamp(char *bol, char **eol_p)
  1019. {
  1020. char *eol = *eol_p;
  1021. int ch;
  1022. while (bol < --eol) {
  1023. if (*eol != '>')
  1024. continue;
  1025. *eol_p = ++eol;
  1026. ch = *eol;
  1027. *eol = '\0';
  1028. return ch;
  1029. }
  1030. return 0;
  1031. }
  1032. static struct {
  1033. const char *field;
  1034. size_t len;
  1035. } header_field[] = {
  1036. { "author ", 7 },
  1037. { "committer ", 10 },
  1038. { "reflog ", 7 },
  1039. };
  1040. static int match_one_pattern(struct grep_pat *p, char *bol, char *eol,
  1041. enum grep_context ctx,
  1042. regmatch_t *pmatch, int eflags)
  1043. {
  1044. int hit = 0;
  1045. int saved_ch = 0;
  1046. const char *start = bol;
  1047. if ((p->token != GREP_PATTERN) &&
  1048. ((p->token == GREP_PATTERN_HEAD) != (ctx == GREP_CONTEXT_HEAD)))
  1049. return 0;
  1050. if (p->token == GREP_PATTERN_HEAD) {
  1051. const char *field;
  1052. size_t len;
  1053. assert(p->field < ARRAY_SIZE(header_field));
  1054. field = header_field[p->field].field;
  1055. len = header_field[p->field].len;
  1056. if (strncmp(bol, field, len))
  1057. return 0;
  1058. bol += len;
  1059. switch (p->field) {
  1060. case GREP_HEADER_AUTHOR:
  1061. case GREP_HEADER_COMMITTER:
  1062. saved_ch = strip_timestamp(bol, &eol);
  1063. break;
  1064. default:
  1065. break;
  1066. }
  1067. }
  1068. again:
  1069. hit = patmatch(p, bol, eol, pmatch, eflags);
  1070. if (hit && p->word_regexp) {
  1071. if ((pmatch[0].rm_so < 0) ||
  1072. (eol - bol) < pmatch[0].rm_so ||
  1073. (pmatch[0].rm_eo < 0) ||
  1074. (eol - bol) < pmatch[0].rm_eo)
  1075. die("regexp returned nonsense");
  1076. /* Match beginning must be either beginning of the
  1077. * line, or at word boundary (i.e. the last char must
  1078. * not be a word char). Similarly, match end must be
  1079. * either end of the line, or at word boundary
  1080. * (i.e. the next char must not be a word char).
  1081. */
  1082. if ( ((pmatch[0].rm_so == 0) ||
  1083. !word_char(bol[pmatch[0].rm_so-1])) &&
  1084. ((pmatch[0].rm_eo == (eol-bol)) ||
  1085. !word_char(bol[pmatch[0].rm_eo])) )
  1086. ;
  1087. else
  1088. hit = 0;
  1089. /* Words consist of at least one character. */
  1090. if (pmatch->rm_so == pmatch->rm_eo)
  1091. hit = 0;
  1092. if (!hit && pmatch[0].rm_so + bol + 1 < eol) {
  1093. /* There could be more than one match on the
  1094. * line, and the first match might not be
  1095. * strict word match. But later ones could be!
  1096. * Forward to the next possible start, i.e. the
  1097. * next position following a non-word char.
  1098. */
  1099. bol = pmatch[0].rm_so + bol + 1;
  1100. while (word_char(bol[-1]) && bol < eol)
  1101. bol++;
  1102. eflags |= REG_NOTBOL;
  1103. if (bol < eol)
  1104. goto again;
  1105. }
  1106. }
  1107. if (p->token == GREP_PATTERN_HEAD && saved_ch)
  1108. *eol = saved_ch;
  1109. if (hit) {
  1110. pmatch[0].rm_so += bol - start;
  1111. pmatch[0].rm_eo += bol - start;
  1112. }
  1113. return hit;
  1114. }
  1115. static int match_expr_eval(struct grep_opt *opt, struct grep_expr *x, char *bol,
  1116. char *eol, enum grep_context ctx, ssize_t *col,
  1117. ssize_t *icol, int collect_hits)
  1118. {
  1119. int h = 0;
  1120. if (!x)
  1121. die("Not a valid grep expression");
  1122. switch (x->node) {
  1123. case GREP_NODE_TRUE:
  1124. h = 1;
  1125. break;
  1126. case GREP_NODE_ATOM:
  1127. {
  1128. regmatch_t tmp;
  1129. h = match_one_pattern(x->u.atom, bol, eol, ctx,
  1130. &tmp, 0);
  1131. if (h && (*col < 0 || tmp.rm_so < *col))
  1132. *col = tmp.rm_so;
  1133. }
  1134. break;
  1135. case GREP_NODE_NOT:
  1136. /*
  1137. * Upon visiting a GREP_NODE_NOT, col and icol become swapped.
  1138. */
  1139. h = !match_expr_eval(opt, x->u.unary, bol, eol, ctx, icol, col,
  1140. 0);
  1141. break;
  1142. case GREP_NODE_AND:
  1143. h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
  1144. icol, 0);
  1145. if (h || opt->columnnum) {
  1146. /*
  1147. * Don't short-circuit AND when given --column, since a
  1148. * NOT earlier in the tree may turn this into an OR. In
  1149. * this case, see the below comment.
  1150. */
  1151. h &= match_expr_eval(opt, x->u.binary.right, bol, eol,
  1152. ctx, col, icol, 0);
  1153. }
  1154. break;
  1155. case GREP_NODE_OR:
  1156. if (!(collect_hits || opt->columnnum)) {
  1157. /*
  1158. * Don't short-circuit OR when given --column (or
  1159. * collecting hits) to ensure we don't skip a later
  1160. * child that would produce an earlier match.
  1161. */
  1162. return (match_expr_eval(opt, x->u.binary.left, bol, eol,
  1163. ctx, col, icol, 0) ||
  1164. match_expr_eval(opt, x->u.binary.right, bol,
  1165. eol, ctx, col, icol, 0));
  1166. }
  1167. h = match_expr_eval(opt, x->u.binary.left, bol, eol, ctx, col,
  1168. icol, 0);
  1169. if (collect_hits)
  1170. x->u.binary.left->hit |= h;
  1171. h |= match_expr_eval(opt, x->u.binary.right, bol, eol, ctx, col,
  1172. icol, collect_hits);
  1173. break;
  1174. default:
  1175. die("Unexpected node type (internal error) %d", x->node);
  1176. }
  1177. if (collect_hits)
  1178. x->hit |= h;
  1179. return h;
  1180. }
  1181. static int match_expr(struct grep_opt *opt, char *bol, char *eol,
  1182. enum grep_context ctx, ssize_t *col,
  1183. ssize_t *icol, int collect_hits)
  1184. {
  1185. struct grep_expr *x = opt->pattern_expression;
  1186. return match_expr_eval(opt, x, bol, eol, ctx, col, icol, collect_hits);
  1187. }
  1188. static int match_line(struct grep_opt *opt, char *bol, char *eol,
  1189. ssize_t *col, ssize_t *icol,
  1190. enum grep_context ctx, int collect_hits)
  1191. {
  1192. struct grep_pat *p;
  1193. int hit = 0;
  1194. if (opt->extended)
  1195. return match_expr(opt, bol, eol, ctx, col, icol,
  1196. collect_hits);
  1197. /* we do not call with collect_hits without being extended */
  1198. for (p = opt->pattern_list; p; p = p->next) {
  1199. regmatch_t tmp;
  1200. if (match_one_pattern(p, bol, eol, ctx, &tmp, 0)) {
  1201. hit |= 1;
  1202. if (!opt->columnnum) {
  1203. /*
  1204. * Without --column, any single match on a line
  1205. * is enough to know that it needs to be
  1206. * printed. With --column, scan _all_ patterns
  1207. * to find the earliest.
  1208. */
  1209. break;
  1210. }
  1211. if (*col < 0 || tmp.rm_so < *col)
  1212. *col = tmp.rm_so;
  1213. }
  1214. }
  1215. return hit;
  1216. }
  1217. static int match_next_pattern(struct grep_pat *p, char *bol, char *eol,
  1218. enum grep_context ctx,
  1219. regmatch_t *pmatch, int eflags)
  1220. {
  1221. regmatch_t match;
  1222. if (!match_one_pattern(p, bol, eol, ctx, &match, eflags))
  1223. return 0;
  1224. if (match.rm_so < 0 || match.rm_eo < 0)
  1225. return 0;
  1226. if (pmatch->rm_so >= 0 && pmatch->rm_eo >= 0) {
  1227. if (match.rm_so > pmatch->rm_so)
  1228. return 1;
  1229. if (match.rm_so == pmatch->rm_so && match.rm_eo < pmatch->rm_eo)
  1230. return 1;
  1231. }
  1232. pmatch->rm_so = match.rm_so;
  1233. pmatch->rm_eo = match.rm_eo;
  1234. return 1;
  1235. }
  1236. static int next_match(struct grep_opt *opt, char *bol, char *eol,
  1237. enum grep_context ctx, regmatch_t *pmatch, int eflags)
  1238. {
  1239. struct grep_pat *p;
  1240. int hit = 0;
  1241. pmatch->rm_so = pmatch->rm_eo = -1;
  1242. if (bol < eol) {
  1243. for (p = opt->pattern_list; p; p = p->next) {
  1244. switch (p->token) {
  1245. case GREP_PATTERN: /* atom */
  1246. case GREP_PATTERN_HEAD:
  1247. case GREP_PATTERN_BODY:
  1248. hit |= match_next_pattern(p, bol, eol, ctx,
  1249. pmatch, eflags);
  1250. break;
  1251. default:
  1252. break;
  1253. }
  1254. }
  1255. }
  1256. return hit;
  1257. }
  1258. static void show_line_header(struct grep_opt *opt, const char *name,
  1259. unsigned lno, ssize_t cno, char sign)
  1260. {
  1261. if (opt->heading && opt->last_shown == 0) {
  1262. output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
  1263. opt->output(opt, "\n", 1);
  1264. }
  1265. opt->last_shown = lno;
  1266. if (!opt->heading && opt->pathname) {
  1267. output_color(opt, name, strlen(name), opt->colors[GREP_COLOR_FILENAME]);
  1268. output_sep(opt, sign);
  1269. }
  1270. if (opt->linenum) {
  1271. char buf[32];
  1272. xsnprintf(buf, sizeof(buf), "%d", lno);
  1273. output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_LINENO]);
  1274. output_sep(opt, sign);
  1275. }
  1276. /*
  1277. * Treat 'cno' as the 1-indexed offset from the start of a non-context
  1278. * line to its first match. Otherwise, 'cno' is 0 indicating that we are
  1279. * being called with a context line.
  1280. */
  1281. if (opt->columnnum && cno) {
  1282. char buf[32];
  1283. xsnprintf(buf, sizeof(buf), "%"PRIuMAX, (uintmax_t)cno);
  1284. output_color(opt, buf, strlen(buf), opt->colors[GREP_COLOR_COLUMNNO]);
  1285. output_sep(opt, sign);
  1286. }
  1287. }
  1288. static void show_line(struct grep_opt *opt, char *bol, char *eol,
  1289. const char *name, unsigned lno, ssize_t cno, char sign)
  1290. {
  1291. int rest = eol - bol;
  1292. const char *match_color = NULL;
  1293. const char *line_color = NULL;
  1294. if (opt->file_break && opt->last_shown == 0) {
  1295. if (opt->show_hunk_mark)
  1296. opt->output(opt, "\n", 1);
  1297. } else if (opt->pre_context || opt->post_context || opt->funcbody) {
  1298. if (opt->last_shown == 0) {
  1299. if (opt->show_hunk_mark) {
  1300. output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
  1301. opt->output(opt, "\n", 1);
  1302. }
  1303. } else if (lno > opt->last_shown + 1) {
  1304. output_color(opt, "--", 2, opt->colors[GREP_COLOR_SEP]);
  1305. opt->output(opt, "\n", 1);
  1306. }
  1307. }
  1308. if (!opt->only_matching) {
  1309. /*
  1310. * In case the line we're being called with contains more than
  1311. * one match, leave printing each header to the loop below.
  1312. */
  1313. show_line_header(opt, name, lno, cno, sign);
  1314. }
  1315. if (opt->color || opt->only_matching) {
  1316. regmatch_t match;
  1317. enum grep_context ctx = GREP_CONTEXT_BODY;
  1318. int ch = *eol;
  1319. int eflags = 0;
  1320. if (opt->color) {
  1321. if (sign == ':')
  1322. match_color = opt->colors[GREP_COLOR_MATCH_SELECTED];
  1323. else
  1324. match_color = opt->colors[GREP_COLOR_MATCH_CONTEXT];
  1325. if (sign == ':')
  1326. line_color = opt->colors[GREP_COLOR_SELECTED];
  1327. else if (sign == '-')
  1328. line_color = opt->colors[GREP_COLOR_CONTEXT];
  1329. else if (sign == '=')
  1330. line_color = opt->colors[GREP_COLOR_FUNCTION];
  1331. }
  1332. *eol = '\0';
  1333. while (next_match(opt, bol, eol, ctx, &match, eflags)) {
  1334. if (match.rm_so == match.rm_eo)
  1335. break;
  1336. if (opt->only_matching)
  1337. show_line_header(opt, name, lno, cno, sign);
  1338. else
  1339. output_color(opt, bol, match.rm_so, line_color);
  1340. output_color(opt, bol + match.rm_so,
  1341. match.rm_eo - match.rm_so, match_color);
  1342. if (opt->only_matching)
  1343. opt->output(opt, "\n", 1);
  1344. bol += match.rm_eo;
  1345. cno += match.rm_eo;
  1346. rest -= match.rm_eo;
  1347. eflags = REG_NOTBOL;
  1348. }
  1349. *eol = ch;
  1350. }
  1351. if (!opt->only_matching) {
  1352. output_color(opt, bol, rest, line_color);
  1353. opt->output(opt, "\n", 1);
  1354. }
  1355. }
  1356. int grep_use_locks;
  1357. /*
  1358. * This lock protects access to the gitattributes machinery, which is
  1359. * not thread-safe.
  1360. */
  1361. pthread_mutex_t grep_attr_mutex;
  1362. static inline void grep_attr_lock(void)
  1363. {
  1364. if (grep_use_locks)
  1365. pthread_mutex_lock(&grep_attr_mutex);
  1366. }
  1367. static inline void grep_attr_unlock(void)
  1368. {
  1369. if (grep_use_locks)
  1370. pthread_mutex_unlock(&grep_attr_mutex);
  1371. }
  1372. static int match_funcname(struct grep_opt *opt, struct grep_source *gs, char *bol, char *eol)
  1373. {
  1374. xdemitconf_t *xecfg = opt->priv;
  1375. if (xecfg && !xecfg->find_func) {
  1376. grep_source_load_driver(gs, opt->repo->index);
  1377. if (gs->driver->funcname.pattern) {
  1378. const struct userdiff_funcname *pe = &gs->driver->funcname;
  1379. xdiff_set_find_func(xecfg, pe->pattern, pe->cflags);
  1380. } else {
  1381. xecfg = opt->priv = NULL;
  1382. }
  1383. }
  1384. if (xecfg) {
  1385. char buf[1];
  1386. return xecfg->find_func(bol, eol - bol, buf, 1,
  1387. xecfg->find_func_priv) >= 0;
  1388. }
  1389. if (bol == eol)
  1390. return 0;
  1391. if (isalpha(*bol) || *bol == '_' || *bol == '$')
  1392. return 1;
  1393. return 0;
  1394. }
  1395. static void show_funcname_line(struct grep_opt *opt, struct grep_source *gs,
  1396. char *bol, unsigned lno)
  1397. {
  1398. while (bol > gs->buf) {
  1399. char *eol = --bol;
  1400. while (bol > gs->buf && bol[-1] != '\n')
  1401. bol--;
  1402. lno--;
  1403. if (lno <= opt->last_shown)
  1404. break;
  1405. if (match_funcname(opt, gs, bol, eol)) {
  1406. show_line(opt, bol, eol, gs->name, lno, 0, '=');
  1407. break;
  1408. }
  1409. }
  1410. }
  1411. static int is_empty_line(const char *bol, const char *eol);
  1412. static void show_pre_context(struct grep_opt *opt, struct grep_source *gs,
  1413. char *bol, char *end, unsigned lno)
  1414. {
  1415. unsigned cur = lno, from = 1, funcname_lno = 0, orig_from;
  1416. int funcname_needed = !!opt->funcname, comment_needed = 0;
  1417. if (opt->pre_context < lno)
  1418. from = lno - opt->pre_context;
  1419. if (from <= opt->last_shown)
  1420. from = opt->last_shown + 1;
  1421. orig_from = from;
  1422. if (opt->funcbody) {
  1423. if (match_funcname(opt, gs, bol, end))
  1424. comment_needed = 1;
  1425. else
  1426. funcname_needed = 1;
  1427. from = opt->last_shown + 1;
  1428. }
  1429. /* Rewind. */
  1430. while (bol > gs->buf && cur > from) {
  1431. char *next_bol = bol;
  1432. char *eol = --bol;
  1433. while (bol > gs->buf && bol[-1] != '\n')
  1434. bol--;
  1435. cur--;
  1436. if (comment_needed && (is_empty_line(bol, eol) ||
  1437. match_funcname(opt, gs, bol, eol))) {
  1438. comment_needed = 0;
  1439. from = orig_from;
  1440. if (cur < from) {
  1441. cur++;
  1442. bol = next_bol;
  1443. break;
  1444. }
  1445. }
  1446. if (funcname_needed && match_funcname(opt, gs, bol, eol)) {
  1447. funcname_lno = cur;
  1448. funcname_needed = 0;
  1449. if (opt->funcbody)
  1450. comment_needed = 1;
  1451. else
  1452. from = orig_from;
  1453. }
  1454. }
  1455. /* We need to look even further back to find a function signature. */
  1456. if (opt->funcname && funcname_needed)
  1457. show_funcname_line(opt, gs, bol, cur);
  1458. /* Back forward. */
  1459. while (cur < lno) {
  1460. char *eol = bol, sign = (cur == funcname_lno) ? '=' : '-';
  1461. while (*eol != '\n')
  1462. eol++;
  1463. show_line(opt, bol, eol, gs->name, cur, 0, sign);
  1464. bol = eol + 1;
  1465. cur++;
  1466. }
  1467. }
  1468. static int should_lookahead(struct grep_opt *opt)
  1469. {
  1470. struct grep_pat *p;
  1471. if (opt->extended)
  1472. return 0; /* punt for too complex stuff */
  1473. if (opt->invert)
  1474. return 0;
  1475. for (p = opt->pattern_list; p; p = p->next) {
  1476. if (p->token != GREP_PATTERN)
  1477. return 0; /* punt for "header only" and stuff */
  1478. }
  1479. return 1;
  1480. }
  1481. static int look_ahead(struct grep_opt *opt,
  1482. unsigned long *left_p,
  1483. unsigned *lno_p,
  1484. char **bol_p)
  1485. {
  1486. unsigned lno = *lno_p;
  1487. char *bol = *bol_p;
  1488. struct grep_pat *p;
  1489. char *sp, *last_bol;
  1490. regoff_t earliest = -1;
  1491. for (p = opt->pattern_list; p; p = p->next) {
  1492. int hit;
  1493. regmatch_t m;
  1494. hit = patmatch(p, bol, bol + *left_p, &m, 0);
  1495. if (!hit || m.rm_so < 0 || m.rm_eo < 0)
  1496. continue;
  1497. if (earliest < 0 || m.rm_so < earliest)
  1498. earliest = m.rm_so;
  1499. }
  1500. if (earliest < 0) {
  1501. *bol_p = bol + *left_p;
  1502. *left_p = 0;
  1503. return 1;
  1504. }
  1505. for (sp = bol + earliest; bol < sp && sp[-1] != '\n'; sp--)
  1506. ; /* find the beginning of the line */
  1507. last_bol = sp;
  1508. for (sp = bol; sp < last_bol; sp++) {
  1509. if (*sp == '\n')
  1510. lno++;
  1511. }
  1512. *left_p -= last_bol - bol;
  1513. *bol_p = last_bol;
  1514. *lno_p = lno;
  1515. return 0;
  1516. }
  1517. static int fill_textconv_grep(struct repository *r,
  1518. struct userdiff_driver *driver,
  1519. struct grep_source *gs)
  1520. {
  1521. struct diff_filespec *df;
  1522. char *buf;
  1523. size_t size;
  1524. if (!driver || !driver->textconv)
  1525. return grep_source_load(gs);
  1526. /*
  1527. * The textconv interface is intimately tied to diff_filespecs, so we
  1528. * have to pretend to be one. If we could unify the grep_source
  1529. * and diff_filespec structs, this mess could just go away.
  1530. */
  1531. df = alloc_filespec(gs->path);
  1532. switch (gs->type) {
  1533. case GREP_SOURCE_OID:
  1534. fill_filespec(df, gs->identifier, 1, 0100644);
  1535. break;
  1536. case GREP_SOURCE_FILE:
  1537. fill_filespec(df, &null_oid, 0, 0100644);
  1538. break;
  1539. default:
  1540. BUG("attempt to textconv something without a path?");
  1541. }
  1542. /*
  1543. * fill_textconv is not remotely thread-safe; it modifies the global
  1544. * diff tempfile structure, writes to the_repo's odb and might
  1545. * internally call thread-unsafe functions such as the
  1546. * prepare_packed_git() lazy-initializator. Because of the last two, we
  1547. * must ensure mutual exclusion between this call and the object reading
  1548. * API, thus we use obj_read_lock() here.
  1549. *
  1550. * TODO: allowing text conversion to run in parallel with object
  1551. * reading operations might increase performance in the multithreaded
  1552. * non-worktreee git-grep with --textconv.
  1553. */
  1554. obj_read_lock();
  1555. size = fill_textconv(r, driver, df, &buf);
  1556. obj_read_unlock();
  1557. free_filespec(df);
  1558. /*
  1559. * The normal fill_textconv usage by the diff machinery would just keep
  1560. * the textconv'd buf separate from the diff_filespec. But much of the
  1561. * grep code passes around a grep_source and assumes that its "buf"
  1562. * pointer is the beginning of the thing we are searching. So let's
  1563. * install our textconv'd version into the grep_source, taking care not
  1564. * to leak any existing buffer.
  1565. */
  1566. grep_source_clear_data(gs);
  1567. gs->buf = buf;
  1568. gs->size = size;
  1569. return 0;
  1570. }
  1571. static int is_empty_line(const char *bol, const char *eol)
  1572. {
  1573. while (bol < eol && isspace(*bol))
  1574. bol++;
  1575. return bol == eol;
  1576. }
  1577. static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int collect_hits)
  1578. {
  1579. char *bol;
  1580. char *peek_bol = NULL;
  1581. unsigned long left;
  1582. unsigned lno = 1;
  1583. unsigned last_hit = 0;
  1584. int binary_match_only = 0;
  1585. unsigned count = 0;
  1586. int try_lookahead = 0;
  1587. int show_function = 0;
  1588. struct userdiff_driver *textconv = NULL;
  1589. enum grep_context ctx = GREP_CONTEXT_HEAD;
  1590. xdemitconf_t xecfg;
  1591. if (!opt->status_only && gs->name == NULL)
  1592. BUG("grep call which could print a name requires "
  1593. "grep_source.name be non-NULL");
  1594. if (!opt->output)
  1595. opt->output = std_output;
  1596. if (opt->pre_context || opt->post_context || opt->file_break ||
  1597. opt->funcbody) {
  1598. /* Show hunk marks, except for the first file. */
  1599. if (opt->last_shown)
  1600. opt->show_hunk_mark = 1;
  1601. /*
  1602. * If we're using threads then we can't easily identify
  1603. * the first file. Always put hunk marks in that case
  1604. * and skip the very first one later in work_done().
  1605. */
  1606. if (opt->output != std_output)
  1607. opt->show_hunk_mark = 1;
  1608. }
  1609. opt->last_shown = 0;
  1610. if (opt->allow_textconv) {
  1611. grep_source_load_driver(gs, opt->repo->index);
  1612. /*
  1613. * We might set up the shared textconv cache data here, which
  1614. * is not thread-safe. Also, get_oid_with_context() and
  1615. * parse_object() might be internally called. As they are not
  1616. * currently thread-safe and might be racy with object reading,
  1617. * obj_read_lock() must be called.
  1618. */
  1619. grep_attr_lock();
  1620. obj_read_lock();
  1621. textconv = userdiff_get_textconv(opt->repo, gs->driver);
  1622. obj_read_unlock();
  1623. grep_attr_unlock();
  1624. }
  1625. /*
  1626. * We know the result of a textconv is text, so we only have to care
  1627. * about binary handling if we are not using it.
  1628. */
  1629. if (!textconv) {
  1630. switch (opt->binary) {
  1631. case GREP_BINARY_DEFAULT:
  1632. if (grep_source_is_binary(gs, opt->repo->index))
  1633. binary_match_only = 1;
  1634. break;
  1635. case GREP_BINARY_NOMATCH:
  1636. if (grep_source_is_binary(gs, opt->repo->index))
  1637. return 0; /* Assume unmatch */
  1638. break;
  1639. case GREP_BINARY_TEXT:
  1640. break;
  1641. default:
  1642. BUG("unknown binary handling mode");
  1643. }
  1644. }
  1645. memset(&xecfg, 0, sizeof(xecfg));
  1646. opt->priv = &xecfg;
  1647. try_lookahead = should_lookahead(opt);
  1648. if (fill_textconv_grep(opt->repo, textconv, gs) < 0)
  1649. return 0;
  1650. bol = gs->buf;
  1651. left = gs->size;
  1652. while (left) {
  1653. char *eol, ch;
  1654. int hit;
  1655. ssize_t cno;
  1656. ssize_t col = -1, icol = -1;
  1657. /*
  1658. * look_ahead() skips quickly to the line that possibly
  1659. * has the next hit; don't call it if we need to do
  1660. * something more than just skipping the current line
  1661. * in response to an unmatch for the current line. E.g.
  1662. * inside a post-context window, we will show the current
  1663. * line as a context around the previous hit when it
  1664. * doesn't hit.
  1665. */
  1666. if (try_lookahead
  1667. && !(last_hit
  1668. && (show_function ||
  1669. lno <= last_hit + opt->post_context))
  1670. && look_ahead(opt, &left, &lno, &bol))
  1671. break;
  1672. eol = end_of_line(bol, &left);
  1673. ch = *eol;
  1674. *eol = 0;
  1675. if ((ctx == GREP_CONTEXT_HEAD) && (eol == bol))
  1676. ctx = GREP_CONTEXT_BODY;
  1677. hit = match_line(opt, bol, eol, &col, &icol, ctx, collect_hits);
  1678. *eol = ch;
  1679. if (collect_hits)
  1680. goto next_line;
  1681. /* "grep -v -e foo -e bla" should list lines
  1682. * that do not have either, so inversion should
  1683. * be done outside.
  1684. */
  1685. if (opt->invert)
  1686. hit = !hit;
  1687. if (opt->unmatch_name_only) {
  1688. if (hit)
  1689. return 0;
  1690. goto next_line;
  1691. }
  1692. if (hit) {
  1693. count++;
  1694. if (opt->status_only)
  1695. return 1;
  1696. if (opt->name_only) {
  1697. show_name(opt, gs->name);
  1698. return 1;
  1699. }
  1700. if (opt->count)
  1701. goto next_line;
  1702. if (binary_match_only) {
  1703. opt->output(opt, "Binary file ", 12);
  1704. output_color(opt, gs->name, strlen(gs->name),
  1705. opt->colors[GREP_COLOR_FILENAME]);
  1706. opt->output(opt, " matches\n", 9);
  1707. return 1;
  1708. }
  1709. /* Hit at this line. If we haven't shown the
  1710. * pre-context lines, we would need to show them.
  1711. */
  1712. if (opt->pre_context || opt->funcbody)
  1713. show_pre_context(opt, gs, bol, eol, lno);
  1714. else if (opt->funcname)
  1715. show_funcname_line(opt, gs, bol, lno);
  1716. cno = opt->invert ? icol : col;
  1717. if (cno < 0) {
  1718. /*
  1719. * A negative cno indicates that there was no
  1720. * match on the line. We are thus inverted and
  1721. * being asked to show all lines that _don't_
  1722. * match a given expression. Therefore, set cno
  1723. * to 0 to suggest the whole line matches.
  1724. */
  1725. cno = 0;
  1726. }
  1727. show_line(opt, bol, eol, gs->name, lno, cno + 1, ':');
  1728. last_hit = lno;
  1729. if (opt->funcbody)
  1730. show_function = 1;
  1731. goto next_line;
  1732. }
  1733. if (show_function && (!peek_bol || peek_bol < bol)) {
  1734. unsigned long peek_left = left;
  1735. char *peek_eol = eol;
  1736. /*
  1737. * Trailing empty lines are not interesting.
  1738. * Peek past them to see if they belong to the
  1739. * body of the current function.
  1740. */
  1741. peek_bol = bol;
  1742. while (is_empty_line(peek_bol, peek_eol)) {
  1743. peek_bol = peek_eol + 1;
  1744. peek_eol = end_of_line(peek_bol, &peek_left);
  1745. }
  1746. if (match_funcname(opt, gs, peek_bol, peek_eol))
  1747. show_function = 0;
  1748. }
  1749. if (show_function ||
  1750. (last_hit && lno <= last_hit + opt->post_context)) {
  1751. /* If the last hit is within the post context,
  1752. * we need to show this line.
  1753. */
  1754. show_line(opt, bol, eol, gs->name, lno, col + 1, '-');
  1755. }
  1756. next_line:
  1757. bol = eol + 1;
  1758. if (!left)
  1759. break;
  1760. left--;
  1761. lno++;
  1762. }
  1763. if (collect_hits)
  1764. return 0;
  1765. if (opt->status_only)
  1766. return opt->unmatch_name_only;
  1767. if (opt->unmatch_name_only) {
  1768. /* We did not see any hit, so we want to show this */
  1769. show_name(opt, gs->name);
  1770. return 1;
  1771. }
  1772. xdiff_clear_find_func(&xecfg);
  1773. opt->priv = NULL;
  1774. /* NEEDSWORK:
  1775. * The real "grep -c foo *.c" gives many "bar.c:0" lines,
  1776. * which feels mostly useless but sometimes useful. Maybe
  1777. * make it another option? For now suppress them.
  1778. */
  1779. if (opt->count && count) {
  1780. char buf[32];
  1781. if (opt->pathname) {
  1782. output_color(opt, gs->name, strlen(gs->name),
  1783. opt->colors[GREP_COLOR_FILENAME]);
  1784. output_sep(opt, ':');
  1785. }
  1786. xsnprintf(buf, sizeof(buf), "%u\n", count);
  1787. opt->output(opt, buf, strlen(buf));
  1788. return 1;
  1789. }
  1790. return !!last_hit;
  1791. }
  1792. static void clr_hit_marker(struct grep_expr *x)
  1793. {
  1794. /* All-hit markers are meaningful only at the very top level
  1795. * OR node.
  1796. */
  1797. while (1) {
  1798. x->hit = 0;
  1799. if (x->node != GREP_NODE_OR)
  1800. return;
  1801. x->u.binary.left->hit = 0;
  1802. x = x->u.binary.right;
  1803. }
  1804. }
  1805. static int chk_hit_marker(struct grep_expr *x)
  1806. {
  1807. /* Top level nodes have hit markers. See if they all are hits */
  1808. while (1) {
  1809. if (x->node != GREP_NODE_OR)
  1810. return x->hit;
  1811. if (!x->u.binary.left->hit)
  1812. return 0;
  1813. x = x->u.binary.right;
  1814. }
  1815. }
  1816. int grep_source(struct grep_opt *opt, struct grep_source *gs)
  1817. {
  1818. /*
  1819. * we do not have to do the two-pass grep when we do not check
  1820. * buffer-wide "all-match".
  1821. */
  1822. if (!opt->all_match)
  1823. return grep_source_1(opt, gs, 0);
  1824. /* Otherwise the toplevel "or" terms hit a bit differently.
  1825. * We first clear hit markers from them.
  1826. */
  1827. clr_hit_marker(opt->pattern_expression);
  1828. grep_source_1(opt, gs, 1);
  1829. if (!chk_hit_marker(opt->pattern_expression))
  1830. return 0;
  1831. return grep_source_1(opt, gs, 0);
  1832. }
  1833. int grep_buffer(struct grep_opt *opt, char *buf, unsigned long size)
  1834. {
  1835. struct grep_source gs;
  1836. int r;
  1837. grep_source_init(&gs, GREP_SOURCE_BUF, NULL, NULL, NULL);
  1838. gs.buf = buf;
  1839. gs.size = size;
  1840. r = grep_source(opt, &gs);
  1841. grep_source_clear(&gs);
  1842. return r;
  1843. }
  1844. void grep_source_init(struct grep_source *gs, enum grep_source_type type,
  1845. const char *name, const char *path,
  1846. const void *identifier)
  1847. {
  1848. gs->type = type;
  1849. gs->name = xstrdup_or_null(name);
  1850. gs->path = xstrdup_or_null(path);
  1851. gs->buf = NULL;
  1852. gs->size = 0;
  1853. gs->driver = NULL;
  1854. switch (type) {
  1855. case GREP_SOURCE_FILE:
  1856. gs->identifier = xstrdup(identifier);
  1857. break;
  1858. case GREP_SOURCE_OID:
  1859. gs->identifier = oiddup(identifier);
  1860. break;
  1861. case GREP_SOURCE_BUF:
  1862. gs->identifier = NULL;
  1863. break;
  1864. }
  1865. }
  1866. void grep_source_clear(struct grep_source *gs)
  1867. {
  1868. FREE_AND_NULL(gs->name);
  1869. FREE_AND_NULL(gs->path);
  1870. FREE_AND_NULL(gs->identifier);
  1871. grep_source_clear_data(gs);
  1872. }
  1873. void grep_source_clear_data(struct grep_source *gs)
  1874. {
  1875. switch (gs->type) {
  1876. case GREP_SOURCE_FILE:
  1877. case GREP_SOURCE_OID:
  1878. FREE_AND_NULL(gs->buf);
  1879. gs->size = 0;
  1880. break;
  1881. case GREP_SOURCE_BUF:
  1882. /* leave user-provided buf intact */
  1883. break;
  1884. }
  1885. }
  1886. static int grep_source_load_oid(struct grep_source *gs)
  1887. {
  1888. enum object_type type;
  1889. gs->buf = read_object_file(gs->identifier, &type, &gs->size);
  1890. if (!gs->buf)
  1891. return error(_("'%s': unable to read %s"),
  1892. gs->name,
  1893. oid_to_hex(gs->identifier));
  1894. return 0;
  1895. }
  1896. static int grep_source_load_file(struct grep_source *gs)
  1897. {
  1898. const char *filename = gs->identifier;
  1899. struct stat st;
  1900. char *data;
  1901. size_t size;
  1902. int i;
  1903. if (lstat(filename, &st) < 0) {
  1904. err_ret:
  1905. if (errno != ENOENT)
  1906. error_errno(_("failed to stat '%s'"), filename);
  1907. return -1;
  1908. }
  1909. if (!S_ISREG(st.st_mode))
  1910. return -1;
  1911. size = xsize_t(st.st_size);
  1912. i = open(filename, O_RDONLY);
  1913. if (i < 0)
  1914. goto err_ret;
  1915. data = xmallocz(size);
  1916. if (st.st_size != read_in_full(i, data, size)) {
  1917. error_errno(_("'%s': short read"), filename);
  1918. close(i);
  1919. free(data);
  1920. return -1;
  1921. }
  1922. close(i);
  1923. gs->buf = data;
  1924. gs->size = size;
  1925. return 0;
  1926. }
  1927. static int grep_source_load(struct grep_source *gs)
  1928. {
  1929. if (gs->buf)
  1930. return 0;
  1931. switch (gs->type) {
  1932. case GREP_SOURCE_FILE:
  1933. return grep_source_load_file(gs);
  1934. case GREP_SOURCE_OID:
  1935. return grep_source_load_oid(gs);
  1936. case GREP_SOURCE_BUF:
  1937. return gs->buf ? 0 : -1;
  1938. }
  1939. BUG("invalid grep_source type to load");
  1940. }
  1941. void grep_source_load_driver(struct grep_source *gs,
  1942. struct index_state *istate)
  1943. {
  1944. if (gs->driver)
  1945. return;
  1946. grep_attr_lock();
  1947. if (gs->path)
  1948. gs->driver = userdiff_find_by_path(istate, gs->path);
  1949. if (!gs->driver)
  1950. gs->driver = userdiff_find_by_name("default");
  1951. grep_attr_unlock();
  1952. }
  1953. static int grep_source_is_binary(struct grep_source *gs,
  1954. struct index_state *istate)
  1955. {
  1956. grep_source_load_driver(gs, istate);
  1957. if (gs->driver->binary != -1)
  1958. return gs->driver->binary;
  1959. if (!grep_source_load(gs))
  1960. return buffer_is_binary(gs->buf, gs->size);
  1961. return 0;
  1962. }