Merge branch 'ab/config-based-hooks-base' into seen
[git] / merge-ort.c
1 /*
2  * "Ostensibly Recursive's Twin" merge strategy, or "ort" for short.  Meant
3  * as a drop-in replacement for the "recursive" merge strategy, allowing one
4  * to replace
5  *
6  *   git merge [-s recursive]
7  *
8  * with
9  *
10  *   git merge -s ort
11  *
12  * Note: git's parser allows the space between '-s' and its argument to be
13  * missing.  (Should I have backronymed "ham", "alsa", "kip", "nap, "alvo",
14  * "cale", "peedy", or "ins" instead of "ort"?)
15  */
16
17 #include "cache.h"
18 #include "merge-ort.h"
19
20 #include "alloc.h"
21 #include "attr.h"
22 #include "blob.h"
23 #include "cache-tree.h"
24 #include "commit.h"
25 #include "commit-reach.h"
26 #include "diff.h"
27 #include "diffcore.h"
28 #include "dir.h"
29 #include "entry.h"
30 #include "ll-merge.h"
31 #include "object-store.h"
32 #include "promisor-remote.h"
33 #include "revision.h"
34 #include "strmap.h"
35 #include "submodule.h"
36 #include "tree.h"
37 #include "unpack-trees.h"
38 #include "xdiff-interface.h"
39
40 /*
41  * We have many arrays of size 3.  Whenever we have such an array, the
42  * indices refer to one of the sides of the three-way merge.  This is so
43  * pervasive that the constants 0, 1, and 2 are used in many places in the
44  * code (especially in arithmetic operations to find the other side's index
45  * or to compute a relevant mask), but sometimes these enum names are used
46  * to aid code clarity.
47  *
48  * See also 'filemask' and 'dirmask' in struct conflict_info; the "ith side"
49  * referred to there is one of these three sides.
50  */
51 enum merge_side {
52         MERGE_BASE = 0,
53         MERGE_SIDE1 = 1,
54         MERGE_SIDE2 = 2
55 };
56
57 static unsigned RESULT_INITIALIZED = 0x1abe11ed; /* unlikely accidental value */
58
59 struct traversal_callback_data {
60         unsigned long mask;
61         unsigned long dirmask;
62         struct name_entry names[3];
63 };
64
65 struct rename_info {
66         /*
67          * All variables that are arrays of size 3 correspond to data tracked
68          * for the sides in enum merge_side.  Index 0 is almost always unused
69          * because we often only need to track information for MERGE_SIDE1 and
70          * MERGE_SIDE2 (MERGE_BASE can't have rename information since renames
71          * are determined relative to what changed since the MERGE_BASE).
72          */
73
74         /*
75          * pairs: pairing of filenames from diffcore_rename()
76          */
77         struct diff_queue_struct pairs[3];
78
79         /*
80          * dirs_removed: directories removed on a given side of history.
81          *
82          * The keys of dirs_removed[side] are the directories that were removed
83          * on the given side of history.  The value of the strintmap for each
84          * directory is a value from enum dir_rename_relevance.
85          */
86         struct strintmap dirs_removed[3];
87
88         /*
89          * dir_rename_count: tracking where parts of a directory were renamed to
90          *
91          * When files in a directory are renamed, they may not all go to the
92          * same location.  Each strmap here tracks:
93          *      old_dir => {new_dir => int}
94          * That is, dir_rename_count[side] is a strmap to a strintmap.
95          */
96         struct strmap dir_rename_count[3];
97
98         /*
99          * dir_renames: computed directory renames
100          *
101          * This is a map of old_dir => new_dir and is derived in part from
102          * dir_rename_count.
103          */
104         struct strmap dir_renames[3];
105
106         /*
107          * relevant_sources: deleted paths wanted in rename detection, and why
108          *
109          * relevant_sources is a set of deleted paths on each side of
110          * history for which we need rename detection.  If a path is deleted
111          * on one side of history, we need to detect if it is part of a
112          * rename if either
113          *    * the file is modified/deleted on the other side of history
114          *    * we need to detect renames for an ancestor directory
115          * If neither of those are true, we can skip rename detection for
116          * that path.  The reason is stored as a value from enum
117          * file_rename_relevance, as the reason can inform the algorithm in
118          * diffcore_rename_extended().
119          */
120         struct strintmap relevant_sources[3];
121
122         /*
123          * dir_rename_mask:
124          *   0: optimization removing unmodified potential rename source okay
125          *   2 or 4: optimization okay, but must check for files added to dir
126          *   7: optimization forbidden; need rename source in case of dir rename
127          */
128         unsigned dir_rename_mask:3;
129
130         /*
131          * callback_data_*: supporting data structures for alternate traversal
132          *
133          * We sometimes need to be able to traverse through all the files
134          * in a given tree before all immediate subdirectories within that
135          * tree.  Since traverse_trees() doesn't do that naturally, we have
136          * a traverse_trees_wrapper() that stores any immediate
137          * subdirectories while traversing files, then traverses the
138          * immediate subdirectories later.  These callback_data* variables
139          * store the information for the subdirectories so that we can do
140          * that traversal order.
141          */
142         struct traversal_callback_data *callback_data;
143         int callback_data_nr, callback_data_alloc;
144         char *callback_data_traverse_path;
145
146         /*
147          * merge_trees: trees passed to the merge algorithm for the merge
148          *
149          * merge_trees records the trees passed to the merge algorithm.  But,
150          * this data also is stored in merge_result->priv.  If a sequence of
151          * merges are being done (such as when cherry-picking or rebasing),
152          * the next merge can look at this and re-use information from
153          * previous merges under certain circumstances.
154          *
155          * See also all the cached_* variables.
156          */
157         struct tree *merge_trees[3];
158
159         /*
160          * cached_pairs_valid_side: which side's cached info can be reused
161          *
162          * See the description for merge_trees.  For repeated merges, at most
163          * only one side's cached information can be used.  Valid values:
164          *   MERGE_SIDE2: cached data from side2 can be reused
165          *   MERGE_SIDE1: cached data from side1 can be reused
166          *   0:           no cached data can be reused
167          */
168         int cached_pairs_valid_side;
169
170         /*
171          * cached_pairs: Caching of renames and deletions.
172          *
173          * These are mappings recording renames and deletions of individual
174          * files (not directories).  They are thus a map from an old
175          * filename to either NULL (for deletions) or a new filename (for
176          * renames).
177          */
178         struct strmap cached_pairs[3];
179
180         /*
181          * cached_target_names: just the destinations from cached_pairs
182          *
183          * We sometimes want a fast lookup to determine if a given filename
184          * is one of the destinations in cached_pairs.  cached_target_names
185          * is thus duplicative information, but it provides a fast lookup.
186          */
187         struct strset cached_target_names[3];
188
189         /*
190          * cached_irrelevant: Caching of rename_sources that aren't relevant.
191          *
192          * If we try to detect a rename for a source path and succeed, it's
193          * part of a rename.  If we try to detect a rename for a source path
194          * and fail, then it's a delete.  If we do not try to detect a rename
195          * for a path, then we don't know if it's a rename or a delete.  If
196          * merge-ort doesn't think the path is relevant, then we just won't
197          * cache anything for that path.  But there's a slight problem in
198          * that merge-ort can think a path is RELEVANT_LOCATION, but due to
199          * commit 9bd342137e ("diffcore-rename: determine which
200          * relevant_sources are no longer relevant", 2021-03-13),
201          * diffcore-rename can downgrade the path to RELEVANT_NO_MORE.  To
202          * avoid excessive calls to diffcore_rename_extended() we still need
203          * to cache such paths, though we cannot record them as either
204          * renames or deletes.  So we cache them here as a "turned out to be
205          * irrelevant *for this commit*" as they are often also irrelevant
206          * for subsequent commits, though we will have to do some extra
207          * checking to see whether such paths become relevant for rename
208          * detection when cherry-picking/rebasing subsequent commits.
209          */
210         struct strset cached_irrelevant[3];
211
212         /*
213          * needed_limit: value needed for inexact rename detection to run
214          *
215          * If the current rename limit wasn't high enough for inexact
216          * rename detection to run, this records the limit needed.  Otherwise,
217          * this value remains 0.
218          */
219         int needed_limit;
220 };
221
222 struct merge_options_internal {
223         /*
224          * paths: primary data structure in all of merge ort.
225          *
226          * The keys of paths:
227          *   * are full relative paths from the toplevel of the repository
228          *     (e.g. "drivers/firmware/raspberrypi.c").
229          *   * store all relevant paths in the repo, both directories and
230          *     files (e.g. drivers, drivers/firmware would also be included)
231          *   * these keys serve to intern all the path strings, which allows
232          *     us to do pointer comparison on directory names instead of
233          *     strcmp; we just have to be careful to use the interned strings.
234          *     (Technically paths_to_free may track some strings that were
235          *      removed from froms paths.)
236          *
237          * The values of paths:
238          *   * either a pointer to a merged_info, or a conflict_info struct
239          *   * merged_info contains all relevant information for a
240          *     non-conflicted entry.
241          *   * conflict_info contains a merged_info, plus any additional
242          *     information about a conflict such as the higher orders stages
243          *     involved and the names of the paths those came from (handy
244          *     once renames get involved).
245          *   * a path may start "conflicted" (i.e. point to a conflict_info)
246          *     and then a later step (e.g. three-way content merge) determines
247          *     it can be cleanly merged, at which point it'll be marked clean
248          *     and the algorithm will ignore any data outside the contained
249          *     merged_info for that entry
250          *   * If an entry remains conflicted, the merged_info portion of a
251          *     conflict_info will later be filled with whatever version of
252          *     the file should be placed in the working directory (e.g. an
253          *     as-merged-as-possible variation that contains conflict markers).
254          */
255         struct strmap paths;
256
257         /*
258          * conflicted: a subset of keys->values from "paths"
259          *
260          * conflicted is basically an optimization between process_entries()
261          * and record_conflicted_index_entries(); the latter could loop over
262          * ALL the entries in paths AGAIN and look for the ones that are
263          * still conflicted, but since process_entries() has to loop over
264          * all of them, it saves the ones it couldn't resolve in this strmap
265          * so that record_conflicted_index_entries() can iterate just the
266          * relevant entries.
267          */
268         struct strmap conflicted;
269
270         /*
271          * paths_to_free: additional list of strings to free
272          *
273          * If keys are removed from "paths", they are added to paths_to_free
274          * to ensure they are later freed.  We avoid free'ing immediately since
275          * other places (e.g. conflict_info.pathnames[]) may still be
276          * referencing these paths.
277          */
278         struct string_list paths_to_free;
279
280         /*
281          * output: special messages and conflict notices for various paths
282          *
283          * This is a map of pathnames (a subset of the keys in "paths" above)
284          * to strbufs.  It gathers various warning/conflict/notice messages
285          * for later processing.
286          */
287         struct strmap output;
288
289         /*
290          * renames: various data relating to rename detection
291          */
292         struct rename_info renames;
293
294         /*
295          * attr_index: hacky minimal index used for renormalization
296          *
297          * renormalization code _requires_ an index, though it only needs to
298          * find a .gitattributes file within the index.  So, when
299          * renormalization is important, we create a special index with just
300          * that one file.
301          */
302         struct index_state attr_index;
303
304         /*
305          * current_dir_name, toplevel_dir: temporary vars
306          *
307          * These are used in collect_merge_info_callback(), and will set the
308          * various merged_info.directory_name for the various paths we get;
309          * see documentation for that variable and the requirements placed on
310          * that field.
311          */
312         const char *current_dir_name;
313         const char *toplevel_dir;
314
315         /* call_depth: recursion level counter for merging merge bases */
316         int call_depth;
317 };
318
319 struct version_info {
320         struct object_id oid;
321         unsigned short mode;
322 };
323
324 struct merged_info {
325         /* if is_null, ignore result.  otherwise result has oid & mode */
326         struct version_info result;
327         unsigned is_null:1;
328
329         /*
330          * clean: whether the path in question is cleanly merged.
331          *
332          * see conflict_info.merged for more details.
333          */
334         unsigned clean:1;
335
336         /*
337          * basename_offset: offset of basename of path.
338          *
339          * perf optimization to avoid recomputing offset of final '/'
340          * character in pathname (0 if no '/' in pathname).
341          */
342         size_t basename_offset;
343
344          /*
345           * directory_name: containing directory name.
346           *
347           * Note that we assume directory_name is constructed such that
348           *    strcmp(dir1_name, dir2_name) == 0 iff dir1_name == dir2_name,
349           * i.e. string equality is equivalent to pointer equality.  For this
350           * to hold, we have to be careful setting directory_name.
351           */
352         const char *directory_name;
353 };
354
355 struct conflict_info {
356         /*
357          * merged: the version of the path that will be written to working tree
358          *
359          * WARNING: It is critical to check merged.clean and ensure it is 0
360          * before reading any conflict_info fields outside of merged.
361          * Allocated merge_info structs will always have clean set to 1.
362          * Allocated conflict_info structs will have merged.clean set to 0
363          * initially.  The merged.clean field is how we know if it is safe
364          * to access other parts of conflict_info besides merged; if a
365          * conflict_info's merged.clean is changed to 1, the rest of the
366          * algorithm is not allowed to look at anything outside of the
367          * merged member anymore.
368          */
369         struct merged_info merged;
370
371         /* oids & modes from each of the three trees for this path */
372         struct version_info stages[3];
373
374         /* pathnames for each stage; may differ due to rename detection */
375         const char *pathnames[3];
376
377         /* Whether this path is/was involved in a directory/file conflict */
378         unsigned df_conflict:1;
379
380         /*
381          * Whether this path is/was involved in a non-content conflict other
382          * than a directory/file conflict (e.g. rename/rename, rename/delete,
383          * file location based on possible directory rename).
384          */
385         unsigned path_conflict:1;
386
387         /*
388          * For filemask and dirmask, the ith bit corresponds to whether the
389          * ith entry is a file (filemask) or a directory (dirmask).  Thus,
390          * filemask & dirmask is always zero, and filemask | dirmask is at
391          * most 7 but can be less when a path does not appear as either a
392          * file or a directory on at least one side of history.
393          *
394          * Note that these masks are related to enum merge_side, as the ith
395          * entry corresponds to side i.
396          *
397          * These values come from a traverse_trees() call; more info may be
398          * found looking at tree-walk.h's struct traverse_info,
399          * particularly the documentation above the "fn" member (note that
400          * filemask = mask & ~dirmask from that documentation).
401          */
402         unsigned filemask:3;
403         unsigned dirmask:3;
404
405         /*
406          * Optimization to track which stages match, to avoid the need to
407          * recompute it in multiple steps. Either 0 or at least 2 bits are
408          * set; if at least 2 bits are set, their corresponding stages match.
409          */
410         unsigned match_mask:3;
411 };
412
413 /*** Function Grouping: various utility functions ***/
414
415 /*
416  * For the next three macros, see warning for conflict_info.merged.
417  *
418  * In each of the below, mi is a struct merged_info*, and ci was defined
419  * as a struct conflict_info* (but we need to verify ci isn't actually
420  * pointed at a struct merged_info*).
421  *
422  * INITIALIZE_CI: Assign ci to mi but only if it's safe; set to NULL otherwise.
423  * VERIFY_CI: Ensure that something we assigned to a conflict_info* is one.
424  * ASSIGN_AND_VERIFY_CI: Similar to VERIFY_CI but do assignment first.
425  */
426 #define INITIALIZE_CI(ci, mi) do {                                           \
427         (ci) = (!(mi) || (mi)->clean) ? NULL : (struct conflict_info *)(mi); \
428 } while (0)
429 #define VERIFY_CI(ci) assert(ci && !ci->merged.clean);
430 #define ASSIGN_AND_VERIFY_CI(ci, mi) do {    \
431         (ci) = (struct conflict_info *)(mi);  \
432         assert((ci) && !(mi)->clean);        \
433 } while (0)
434
435 static void free_strmap_strings(struct strmap *map)
436 {
437         struct hashmap_iter iter;
438         struct strmap_entry *entry;
439
440         strmap_for_each_entry(map, &iter, entry) {
441                 free((char*)entry->key);
442         }
443 }
444
445 static void clear_or_reinit_internal_opts(struct merge_options_internal *opti,
446                                           int reinitialize)
447 {
448         struct rename_info *renames = &opti->renames;
449         int i;
450         void (*strmap_func)(struct strmap *, int) =
451                 reinitialize ? strmap_partial_clear : strmap_clear;
452         void (*strintmap_func)(struct strintmap *) =
453                 reinitialize ? strintmap_partial_clear : strintmap_clear;
454         void (*strset_func)(struct strset *) =
455                 reinitialize ? strset_partial_clear : strset_clear;
456
457         /*
458          * We marked opti->paths with strdup_strings = 0, so that we
459          * wouldn't have to make another copy of the fullpath created by
460          * make_traverse_path from setup_path_info().  But, now that we've
461          * used it and have no other references to these strings, it is time
462          * to deallocate them.
463          */
464         free_strmap_strings(&opti->paths);
465         strmap_func(&opti->paths, 1);
466
467         /*
468          * All keys and values in opti->conflicted are a subset of those in
469          * opti->paths.  We don't want to deallocate anything twice, so we
470          * don't free the keys and we pass 0 for free_values.
471          */
472         strmap_func(&opti->conflicted, 0);
473
474         /*
475          * opti->paths_to_free is similar to opti->paths; we created it with
476          * strdup_strings = 0 to avoid making _another_ copy of the fullpath
477          * but now that we've used it and have no other references to these
478          * strings, it is time to deallocate them.  We do so by temporarily
479          * setting strdup_strings to 1.
480          */
481         opti->paths_to_free.strdup_strings = 1;
482         string_list_clear(&opti->paths_to_free, 0);
483         opti->paths_to_free.strdup_strings = 0;
484
485         if (opti->attr_index.cache_nr) /* true iff opt->renormalize */
486                 discard_index(&opti->attr_index);
487
488         /* Free memory used by various renames maps */
489         for (i = MERGE_SIDE1; i <= MERGE_SIDE2; ++i) {
490                 strintmap_func(&renames->dirs_removed[i]);
491                 strmap_func(&renames->dir_renames[i], 0);
492                 strintmap_func(&renames->relevant_sources[i]);
493                 if (!reinitialize)
494                         assert(renames->cached_pairs_valid_side == 0);
495                 if (i != renames->cached_pairs_valid_side) {
496                         strset_func(&renames->cached_target_names[i]);
497                         strmap_func(&renames->cached_pairs[i], 1);
498                         strset_func(&renames->cached_irrelevant[i]);
499                         partial_clear_dir_rename_count(&renames->dir_rename_count[i]);
500                         if (!reinitialize)
501                                 strmap_clear(&renames->dir_rename_count[i], 1);
502                 }
503         }
504         renames->cached_pairs_valid_side = 0;
505         renames->dir_rename_mask = 0;
506
507         if (!reinitialize) {
508                 struct hashmap_iter iter;
509                 struct strmap_entry *e;
510
511                 /* Release and free each strbuf found in output */
512                 strmap_for_each_entry(&opti->output, &iter, e) {
513                         struct strbuf *sb = e->value;
514                         strbuf_release(sb);
515                         /*
516                          * While strictly speaking we don't need to free(sb)
517                          * here because we could pass free_values=1 when
518                          * calling strmap_clear() on opti->output, that would
519                          * require strmap_clear to do another
520                          * strmap_for_each_entry() loop, so we just free it
521                          * while we're iterating anyway.
522                          */
523                         free(sb);
524                 }
525                 strmap_clear(&opti->output, 0);
526         }
527
528         /* Clean out callback_data as well. */
529         FREE_AND_NULL(renames->callback_data);
530         renames->callback_data_nr = renames->callback_data_alloc = 0;
531 }
532
533 static int err(struct merge_options *opt, const char *err, ...)
534 {
535         va_list params;
536         struct strbuf sb = STRBUF_INIT;
537
538         strbuf_addstr(&sb, "error: ");
539         va_start(params, err);
540         strbuf_vaddf(&sb, err, params);
541         va_end(params);
542
543         error("%s", sb.buf);
544         strbuf_release(&sb);
545
546         return -1;
547 }
548
549 static void format_commit(struct strbuf *sb,
550                           int indent,
551                           struct commit *commit)
552 {
553         struct merge_remote_desc *desc;
554         struct pretty_print_context ctx = {0};
555         ctx.abbrev = DEFAULT_ABBREV;
556
557         strbuf_addchars(sb, ' ', indent);
558         desc = merge_remote_util(commit);
559         if (desc) {
560                 strbuf_addf(sb, "virtual %s\n", desc->name);
561                 return;
562         }
563
564         format_commit_message(commit, "%h %s", sb, &ctx);
565         strbuf_addch(sb, '\n');
566 }
567
568 __attribute__((format (printf, 4, 5)))
569 static void path_msg(struct merge_options *opt,
570                      const char *path,
571                      int omittable_hint, /* skippable under --remerge-diff */
572                      const char *fmt, ...)
573 {
574         va_list ap;
575         struct strbuf *sb = strmap_get(&opt->priv->output, path);
576         if (!sb) {
577                 sb = xmalloc(sizeof(*sb));
578                 strbuf_init(sb, 0);
579                 strmap_put(&opt->priv->output, path, sb);
580         }
581
582         va_start(ap, fmt);
583         strbuf_vaddf(sb, fmt, ap);
584         va_end(ap);
585
586         strbuf_addch(sb, '\n');
587 }
588
589 /* add a string to a strbuf, but converting "/" to "_" */
590 static void add_flattened_path(struct strbuf *out, const char *s)
591 {
592         size_t i = out->len;
593         strbuf_addstr(out, s);
594         for (; i < out->len; i++)
595                 if (out->buf[i] == '/')
596                         out->buf[i] = '_';
597 }
598
599 static char *unique_path(struct strmap *existing_paths,
600                          const char *path,
601                          const char *branch)
602 {
603         struct strbuf newpath = STRBUF_INIT;
604         int suffix = 0;
605         size_t base_len;
606
607         strbuf_addf(&newpath, "%s~", path);
608         add_flattened_path(&newpath, branch);
609
610         base_len = newpath.len;
611         while (strmap_contains(existing_paths, newpath.buf)) {
612                 strbuf_setlen(&newpath, base_len);
613                 strbuf_addf(&newpath, "_%d", suffix++);
614         }
615
616         return strbuf_detach(&newpath, NULL);
617 }
618
619 /*** Function Grouping: functions related to collect_merge_info() ***/
620
621 static int traverse_trees_wrapper_callback(int n,
622                                            unsigned long mask,
623                                            unsigned long dirmask,
624                                            struct name_entry *names,
625                                            struct traverse_info *info)
626 {
627         struct merge_options *opt = info->data;
628         struct rename_info *renames = &opt->priv->renames;
629         unsigned filemask = mask & ~dirmask;
630
631         assert(n==3);
632
633         if (!renames->callback_data_traverse_path)
634                 renames->callback_data_traverse_path = xstrdup(info->traverse_path);
635
636         if (filemask && filemask == renames->dir_rename_mask)
637                 renames->dir_rename_mask = 0x07;
638
639         ALLOC_GROW(renames->callback_data, renames->callback_data_nr + 1,
640                    renames->callback_data_alloc);
641         renames->callback_data[renames->callback_data_nr].mask = mask;
642         renames->callback_data[renames->callback_data_nr].dirmask = dirmask;
643         COPY_ARRAY(renames->callback_data[renames->callback_data_nr].names,
644                    names, 3);
645         renames->callback_data_nr++;
646
647         return mask;
648 }
649
650 /*
651  * Much like traverse_trees(), BUT:
652  *   - read all the tree entries FIRST, saving them
653  *   - note that the above step provides an opportunity to compute necessary
654  *     additional details before the "real" traversal
655  *   - loop through the saved entries and call the original callback on them
656  */
657 static int traverse_trees_wrapper(struct index_state *istate,
658                                   int n,
659                                   struct tree_desc *t,
660                                   struct traverse_info *info)
661 {
662         int ret, i, old_offset;
663         traverse_callback_t old_fn;
664         char *old_callback_data_traverse_path;
665         struct merge_options *opt = info->data;
666         struct rename_info *renames = &opt->priv->renames;
667
668         assert(renames->dir_rename_mask == 2 || renames->dir_rename_mask == 4);
669
670         old_callback_data_traverse_path = renames->callback_data_traverse_path;
671         old_fn = info->fn;
672         old_offset = renames->callback_data_nr;
673
674         renames->callback_data_traverse_path = NULL;
675         info->fn = traverse_trees_wrapper_callback;
676         ret = traverse_trees(istate, n, t, info);
677         if (ret < 0)
678                 return ret;
679
680         info->traverse_path = renames->callback_data_traverse_path;
681         info->fn = old_fn;
682         for (i = old_offset; i < renames->callback_data_nr; ++i) {
683                 info->fn(n,
684                          renames->callback_data[i].mask,
685                          renames->callback_data[i].dirmask,
686                          renames->callback_data[i].names,
687                          info);
688         }
689
690         renames->callback_data_nr = old_offset;
691         free(renames->callback_data_traverse_path);
692         renames->callback_data_traverse_path = old_callback_data_traverse_path;
693         info->traverse_path = NULL;
694         return 0;
695 }
696
697 static void setup_path_info(struct merge_options *opt,
698                             struct string_list_item *result,
699                             const char *current_dir_name,
700                             int current_dir_name_len,
701                             char *fullpath, /* we'll take over ownership */
702                             struct name_entry *names,
703                             struct name_entry *merged_version,
704                             unsigned is_null,     /* boolean */
705                             unsigned df_conflict, /* boolean */
706                             unsigned filemask,
707                             unsigned dirmask,
708                             int resolved          /* boolean */)
709 {
710         /* result->util is void*, so mi is a convenience typed variable */
711         struct merged_info *mi;
712
713         assert(!is_null || resolved);
714         assert(!df_conflict || !resolved); /* df_conflict implies !resolved */
715         assert(resolved == (merged_version != NULL));
716
717         mi = xcalloc(1, resolved ? sizeof(struct merged_info) :
718                                    sizeof(struct conflict_info));
719         mi->directory_name = current_dir_name;
720         mi->basename_offset = current_dir_name_len;
721         mi->clean = !!resolved;
722         if (resolved) {
723                 mi->result.mode = merged_version->mode;
724                 oidcpy(&mi->result.oid, &merged_version->oid);
725                 mi->is_null = !!is_null;
726         } else {
727                 int i;
728                 struct conflict_info *ci;
729
730                 ASSIGN_AND_VERIFY_CI(ci, mi);
731                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
732                         ci->pathnames[i] = fullpath;
733                         ci->stages[i].mode = names[i].mode;
734                         oidcpy(&ci->stages[i].oid, &names[i].oid);
735                 }
736                 ci->filemask = filemask;
737                 ci->dirmask = dirmask;
738                 ci->df_conflict = !!df_conflict;
739                 if (dirmask)
740                         /*
741                          * Assume is_null for now, but if we have entries
742                          * under the directory then when it is complete in
743                          * write_completed_directory() it'll update this.
744                          * Also, for D/F conflicts, we have to handle the
745                          * directory first, then clear this bit and process
746                          * the file to see how it is handled -- that occurs
747                          * near the top of process_entry().
748                          */
749                         mi->is_null = 1;
750         }
751         strmap_put(&opt->priv->paths, fullpath, mi);
752         result->string = fullpath;
753         result->util = mi;
754 }
755
756 static void add_pair(struct merge_options *opt,
757                      struct name_entry *names,
758                      const char *pathname,
759                      unsigned side,
760                      unsigned is_add /* if false, is_delete */,
761                      unsigned match_mask,
762                      unsigned dir_rename_mask)
763 {
764         struct diff_filespec *one, *two;
765         struct rename_info *renames = &opt->priv->renames;
766         int names_idx = is_add ? side : 0;
767
768         if (is_add) {
769                 assert(match_mask == 0 || match_mask == 6);
770                 if (strset_contains(&renames->cached_target_names[side],
771                                     pathname))
772                         return;
773         } else {
774                 unsigned content_relevant = (match_mask == 0);
775                 unsigned location_relevant = (dir_rename_mask == 0x07);
776
777                 assert(match_mask == 0 || match_mask == 3 || match_mask == 5);
778
779                 /*
780                  * If pathname is found in cached_irrelevant[side] due to
781                  * previous pick but for this commit content is relevant,
782                  * then we need to remove it from cached_irrelevant.
783                  */
784                 if (content_relevant)
785                         /* strset_remove is no-op if strset doesn't have key */
786                         strset_remove(&renames->cached_irrelevant[side],
787                                       pathname);
788
789                 /*
790                  * We do not need to re-detect renames for paths that we already
791                  * know the pairing, i.e. for cached_pairs (or
792                  * cached_irrelevant).  However, handle_deferred_entries() needs
793                  * to loop over the union of keys from relevant_sources[side] and
794                  * cached_pairs[side], so for simplicity we set relevant_sources
795                  * for all the cached_pairs too and then strip them back out in
796                  * prune_cached_from_relevant() at the beginning of
797                  * detect_regular_renames().
798                  */
799                 if (content_relevant || location_relevant) {
800                         /* content_relevant trumps location_relevant */
801                         strintmap_set(&renames->relevant_sources[side], pathname,
802                                       content_relevant ? RELEVANT_CONTENT : RELEVANT_LOCATION);
803                 }
804
805                 /*
806                  * Avoid creating pair if we've already cached rename results.
807                  * Note that we do this after setting relevant_sources[side]
808                  * as noted in the comment above.
809                  */
810                 if (strmap_contains(&renames->cached_pairs[side], pathname) ||
811                     strset_contains(&renames->cached_irrelevant[side], pathname))
812                         return;
813         }
814
815         one = alloc_filespec(pathname);
816         two = alloc_filespec(pathname);
817         fill_filespec(is_add ? two : one,
818                       &names[names_idx].oid, 1, names[names_idx].mode);
819         diff_queue(&renames->pairs[side], one, two);
820 }
821
822 static void collect_rename_info(struct merge_options *opt,
823                                 struct name_entry *names,
824                                 const char *dirname,
825                                 const char *fullname,
826                                 unsigned filemask,
827                                 unsigned dirmask,
828                                 unsigned match_mask)
829 {
830         struct rename_info *renames = &opt->priv->renames;
831         unsigned side;
832
833         /*
834          * Update dir_rename_mask (determines ignore-rename-source validity)
835          *
836          * dir_rename_mask helps us keep track of when directory rename
837          * detection may be relevant.  Basically, whenver a directory is
838          * removed on one side of history, and a file is added to that
839          * directory on the other side of history, directory rename
840          * detection is relevant (meaning we have to detect renames for all
841          * files within that directory to deduce where the directory
842          * moved).  Also, whenever a directory needs directory rename
843          * detection, due to the "majority rules" choice for where to move
844          * it (see t6423 testcase 1f), we also need to detect renames for
845          * all files within subdirectories of that directory as well.
846          *
847          * Here we haven't looked at files within the directory yet, we are
848          * just looking at the directory itself.  So, if we aren't yet in
849          * a case where a parent directory needed directory rename detection
850          * (i.e. dir_rename_mask != 0x07), and if the directory was removed
851          * on one side of history, record the mask of the other side of
852          * history in dir_rename_mask.
853          */
854         if (renames->dir_rename_mask != 0x07 &&
855             (dirmask == 3 || dirmask == 5)) {
856                 /* simple sanity check */
857                 assert(renames->dir_rename_mask == 0 ||
858                        renames->dir_rename_mask == (dirmask & ~1));
859                 /* update dir_rename_mask; have it record mask of new side */
860                 renames->dir_rename_mask = (dirmask & ~1);
861         }
862
863         /* Update dirs_removed, as needed */
864         if (dirmask == 1 || dirmask == 3 || dirmask == 5) {
865                 /* absent_mask = 0x07 - dirmask; sides = absent_mask/2 */
866                 unsigned sides = (0x07 - dirmask)/2;
867                 unsigned relevance = (renames->dir_rename_mask == 0x07) ?
868                                         RELEVANT_FOR_ANCESTOR : NOT_RELEVANT;
869                 /*
870                  * Record relevance of this directory.  However, note that
871                  * when collect_merge_info_callback() recurses into this
872                  * directory and calls collect_rename_info() on paths
873                  * within that directory, if we find a path that was added
874                  * to this directory on the other side of history, we will
875                  * upgrade this value to RELEVANT_FOR_SELF; see below.
876                  */
877                 if (sides & 1)
878                         strintmap_set(&renames->dirs_removed[1], fullname,
879                                       relevance);
880                 if (sides & 2)
881                         strintmap_set(&renames->dirs_removed[2], fullname,
882                                       relevance);
883         }
884
885         /*
886          * Here's the block that potentially upgrades to RELEVANT_FOR_SELF.
887          * When we run across a file added to a directory.  In such a case,
888          * find the directory of the file and upgrade its relevance.
889          */
890         if (renames->dir_rename_mask == 0x07 &&
891             (filemask == 2 || filemask == 4)) {
892                 /*
893                  * Need directory rename for parent directory on other side
894                  * of history from added file.  Thus
895                  *    side = (~filemask & 0x06) >> 1
896                  * or
897                  *    side = 3 - (filemask/2).
898                  */
899                 unsigned side = 3 - (filemask >> 1);
900                 strintmap_set(&renames->dirs_removed[side], dirname,
901                               RELEVANT_FOR_SELF);
902         }
903
904         if (filemask == 0 || filemask == 7)
905                 return;
906
907         for (side = MERGE_SIDE1; side <= MERGE_SIDE2; ++side) {
908                 unsigned side_mask = (1 << side);
909
910                 /* Check for deletion on side */
911                 if ((filemask & 1) && !(filemask & side_mask))
912                         add_pair(opt, names, fullname, side, 0 /* delete */,
913                                  match_mask & filemask,
914                                  renames->dir_rename_mask);
915
916                 /* Check for addition on side */
917                 if (!(filemask & 1) && (filemask & side_mask))
918                         add_pair(opt, names, fullname, side, 1 /* add */,
919                                  match_mask & filemask,
920                                  renames->dir_rename_mask);
921         }
922 }
923
924 static int collect_merge_info_callback(int n,
925                                        unsigned long mask,
926                                        unsigned long dirmask,
927                                        struct name_entry *names,
928                                        struct traverse_info *info)
929 {
930         /*
931          * n is 3.  Always.
932          * common ancestor (mbase) has mask 1, and stored in index 0 of names
933          * head of side 1  (side1) has mask 2, and stored in index 1 of names
934          * head of side 2  (side2) has mask 4, and stored in index 2 of names
935          */
936         struct merge_options *opt = info->data;
937         struct merge_options_internal *opti = opt->priv;
938         struct rename_info *renames = &opt->priv->renames;
939         struct string_list_item pi;  /* Path Info */
940         struct conflict_info *ci; /* typed alias to pi.util (which is void*) */
941         struct name_entry *p;
942         size_t len;
943         char *fullpath;
944         const char *dirname = opti->current_dir_name;
945         unsigned prev_dir_rename_mask = renames->dir_rename_mask;
946         unsigned filemask = mask & ~dirmask;
947         unsigned match_mask = 0; /* will be updated below */
948         unsigned mbase_null = !(mask & 1);
949         unsigned side1_null = !(mask & 2);
950         unsigned side2_null = !(mask & 4);
951         unsigned side1_matches_mbase = (!side1_null && !mbase_null &&
952                                         names[0].mode == names[1].mode &&
953                                         oideq(&names[0].oid, &names[1].oid));
954         unsigned side2_matches_mbase = (!side2_null && !mbase_null &&
955                                         names[0].mode == names[2].mode &&
956                                         oideq(&names[0].oid, &names[2].oid));
957         unsigned sides_match = (!side1_null && !side2_null &&
958                                 names[1].mode == names[2].mode &&
959                                 oideq(&names[1].oid, &names[2].oid));
960
961         /*
962          * Note: When a path is a file on one side of history and a directory
963          * in another, we have a directory/file conflict.  In such cases, if
964          * the conflict doesn't resolve from renames and deletions, then we
965          * always leave directories where they are and move files out of the
966          * way.  Thus, while struct conflict_info has a df_conflict field to
967          * track such conflicts, we ignore that field for any directories at
968          * a path and only pay attention to it for files at the given path.
969          * The fact that we leave directories were they are also means that
970          * we do not need to worry about getting additional df_conflict
971          * information propagated from parent directories down to children
972          * (unlike, say traverse_trees_recursive() in unpack-trees.c, which
973          * sets a newinfo.df_conflicts field specifically to propagate it).
974          */
975         unsigned df_conflict = (filemask != 0) && (dirmask != 0);
976
977         /* n = 3 is a fundamental assumption. */
978         if (n != 3)
979                 BUG("Called collect_merge_info_callback wrong");
980
981         /*
982          * A bunch of sanity checks verifying that traverse_trees() calls
983          * us the way I expect.  Could just remove these at some point,
984          * though maybe they are helpful to future code readers.
985          */
986         assert(mbase_null == is_null_oid(&names[0].oid));
987         assert(side1_null == is_null_oid(&names[1].oid));
988         assert(side2_null == is_null_oid(&names[2].oid));
989         assert(!mbase_null || !side1_null || !side2_null);
990         assert(mask > 0 && mask < 8);
991
992         /* Determine match_mask */
993         if (side1_matches_mbase)
994                 match_mask = (side2_matches_mbase ? 7 : 3);
995         else if (side2_matches_mbase)
996                 match_mask = 5;
997         else if (sides_match)
998                 match_mask = 6;
999
1000         /*
1001          * Get the name of the relevant filepath, which we'll pass to
1002          * setup_path_info() for tracking.
1003          */
1004         p = names;
1005         while (!p->mode)
1006                 p++;
1007         len = traverse_path_len(info, p->pathlen);
1008
1009         /* +1 in both of the following lines to include the NUL byte */
1010         fullpath = xmalloc(len + 1);
1011         make_traverse_path(fullpath, len + 1, info, p->path, p->pathlen);
1012
1013         /*
1014          * If mbase, side1, and side2 all match, we can resolve early.  Even
1015          * if these are trees, there will be no renames or anything
1016          * underneath.
1017          */
1018         if (side1_matches_mbase && side2_matches_mbase) {
1019                 /* mbase, side1, & side2 all match; use mbase as resolution */
1020                 setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1021                                 names, names+0, mbase_null, 0,
1022                                 filemask, dirmask, 1);
1023                 return mask;
1024         }
1025
1026         /*
1027          * Gather additional information used in rename detection.
1028          */
1029         collect_rename_info(opt, names, dirname, fullpath,
1030                             filemask, dirmask, match_mask);
1031
1032         /*
1033          * Record information about the path so we can resolve later in
1034          * process_entries.
1035          */
1036         setup_path_info(opt, &pi, dirname, info->pathlen, fullpath,
1037                         names, NULL, 0, df_conflict, filemask, dirmask, 0);
1038
1039         ci = pi.util;
1040         VERIFY_CI(ci);
1041         ci->match_mask = match_mask;
1042
1043         /* If dirmask, recurse into subdirectories */
1044         if (dirmask) {
1045                 struct traverse_info newinfo;
1046                 struct tree_desc t[3];
1047                 void *buf[3] = {NULL, NULL, NULL};
1048                 const char *original_dir_name;
1049                 int i, ret;
1050
1051                 ci->match_mask &= filemask;
1052                 newinfo = *info;
1053                 newinfo.prev = info;
1054                 newinfo.name = p->path;
1055                 newinfo.namelen = p->pathlen;
1056                 newinfo.pathlen = st_add3(newinfo.pathlen, p->pathlen, 1);
1057                 /*
1058                  * If this directory we are about to recurse into cared about
1059                  * its parent directory (the current directory) having a D/F
1060                  * conflict, then we'd propagate the masks in this way:
1061                  *    newinfo.df_conflicts |= (mask & ~dirmask);
1062                  * But we don't worry about propagating D/F conflicts.  (See
1063                  * comment near setting of local df_conflict variable near
1064                  * the beginning of this function).
1065                  */
1066
1067                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
1068                         if (i == 1 && side1_matches_mbase)
1069                                 t[1] = t[0];
1070                         else if (i == 2 && side2_matches_mbase)
1071                                 t[2] = t[0];
1072                         else if (i == 2 && sides_match)
1073                                 t[2] = t[1];
1074                         else {
1075                                 const struct object_id *oid = NULL;
1076                                 if (dirmask & 1)
1077                                         oid = &names[i].oid;
1078                                 buf[i] = fill_tree_descriptor(opt->repo,
1079                                                               t + i, oid);
1080                         }
1081                         dirmask >>= 1;
1082                 }
1083
1084                 original_dir_name = opti->current_dir_name;
1085                 opti->current_dir_name = pi.string;
1086                 if (renames->dir_rename_mask == 0 ||
1087                     renames->dir_rename_mask == 0x07)
1088                         ret = traverse_trees(NULL, 3, t, &newinfo);
1089                 else
1090                         ret = traverse_trees_wrapper(NULL, 3, t, &newinfo);
1091                 opti->current_dir_name = original_dir_name;
1092                 renames->dir_rename_mask = prev_dir_rename_mask;
1093
1094                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++)
1095                         free(buf[i]);
1096
1097                 if (ret < 0)
1098                         return -1;
1099         }
1100
1101         return mask;
1102 }
1103
1104 static int collect_merge_info(struct merge_options *opt,
1105                               struct tree *merge_base,
1106                               struct tree *side1,
1107                               struct tree *side2)
1108 {
1109         int ret;
1110         struct tree_desc t[3];
1111         struct traverse_info info;
1112
1113         opt->priv->toplevel_dir = "";
1114         opt->priv->current_dir_name = opt->priv->toplevel_dir;
1115         setup_traverse_info(&info, opt->priv->toplevel_dir);
1116         info.fn = collect_merge_info_callback;
1117         info.data = opt;
1118         info.show_all_errors = 1;
1119
1120         parse_tree(merge_base);
1121         parse_tree(side1);
1122         parse_tree(side2);
1123         init_tree_desc(t + 0, merge_base->buffer, merge_base->size);
1124         init_tree_desc(t + 1, side1->buffer, side1->size);
1125         init_tree_desc(t + 2, side2->buffer, side2->size);
1126
1127         trace2_region_enter("merge", "traverse_trees", opt->repo);
1128         ret = traverse_trees(NULL, 3, t, &info);
1129         trace2_region_leave("merge", "traverse_trees", opt->repo);
1130
1131         return ret;
1132 }
1133
1134 /*** Function Grouping: functions related to threeway content merges ***/
1135
1136 static int find_first_merges(struct repository *repo,
1137                              const char *path,
1138                              struct commit *a,
1139                              struct commit *b,
1140                              struct object_array *result)
1141 {
1142         int i, j;
1143         struct object_array merges = OBJECT_ARRAY_INIT;
1144         struct commit *commit;
1145         int contains_another;
1146
1147         char merged_revision[GIT_MAX_HEXSZ + 2];
1148         const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
1149                                    "--all", merged_revision, NULL };
1150         struct rev_info revs;
1151         struct setup_revision_opt rev_opts;
1152
1153         memset(result, 0, sizeof(struct object_array));
1154         memset(&rev_opts, 0, sizeof(rev_opts));
1155
1156         /* get all revisions that merge commit a */
1157         xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
1158                   oid_to_hex(&a->object.oid));
1159         repo_init_revisions(repo, &revs, NULL);
1160         rev_opts.submodule = path;
1161         /* FIXME: can't handle linked worktrees in submodules yet */
1162         revs.single_worktree = path != NULL;
1163         setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
1164
1165         /* save all revisions from the above list that contain b */
1166         if (prepare_revision_walk(&revs))
1167                 die("revision walk setup failed");
1168         while ((commit = get_revision(&revs)) != NULL) {
1169                 struct object *o = &(commit->object);
1170                 if (in_merge_bases(b, commit))
1171                         add_object_array(o, NULL, &merges);
1172         }
1173         reset_revision_walk();
1174
1175         /* Now we've got all merges that contain a and b. Prune all
1176          * merges that contain another found merge and save them in
1177          * result.
1178          */
1179         for (i = 0; i < merges.nr; i++) {
1180                 struct commit *m1 = (struct commit *) merges.objects[i].item;
1181
1182                 contains_another = 0;
1183                 for (j = 0; j < merges.nr; j++) {
1184                         struct commit *m2 = (struct commit *) merges.objects[j].item;
1185                         if (i != j && in_merge_bases(m2, m1)) {
1186                                 contains_another = 1;
1187                                 break;
1188                         }
1189                 }
1190
1191                 if (!contains_another)
1192                         add_object_array(merges.objects[i].item, NULL, result);
1193         }
1194
1195         object_array_clear(&merges);
1196         return result->nr;
1197 }
1198
1199 static int merge_submodule(struct merge_options *opt,
1200                            const char *path,
1201                            const struct object_id *o,
1202                            const struct object_id *a,
1203                            const struct object_id *b,
1204                            struct object_id *result)
1205 {
1206         struct commit *commit_o, *commit_a, *commit_b;
1207         int parent_count;
1208         struct object_array merges;
1209         struct strbuf sb = STRBUF_INIT;
1210
1211         int i;
1212         int search = !opt->priv->call_depth;
1213
1214         /* store fallback answer in result in case we fail */
1215         oidcpy(result, opt->priv->call_depth ? o : a);
1216
1217         /* we can not handle deletion conflicts */
1218         if (is_null_oid(o))
1219                 return 0;
1220         if (is_null_oid(a))
1221                 return 0;
1222         if (is_null_oid(b))
1223                 return 0;
1224
1225         if (add_submodule_odb(path)) {
1226                 path_msg(opt, path, 0,
1227                          _("Failed to merge submodule %s (not checked out)"),
1228                          path);
1229                 return 0;
1230         }
1231
1232         if (!(commit_o = lookup_commit_reference(opt->repo, o)) ||
1233             !(commit_a = lookup_commit_reference(opt->repo, a)) ||
1234             !(commit_b = lookup_commit_reference(opt->repo, b))) {
1235                 path_msg(opt, path, 0,
1236                          _("Failed to merge submodule %s (commits not present)"),
1237                          path);
1238                 return 0;
1239         }
1240
1241         /* check whether both changes are forward */
1242         if (!in_merge_bases(commit_o, commit_a) ||
1243             !in_merge_bases(commit_o, commit_b)) {
1244                 path_msg(opt, path, 0,
1245                          _("Failed to merge submodule %s "
1246                            "(commits don't follow merge-base)"),
1247                          path);
1248                 return 0;
1249         }
1250
1251         /* Case #1: a is contained in b or vice versa */
1252         if (in_merge_bases(commit_a, commit_b)) {
1253                 oidcpy(result, b);
1254                 path_msg(opt, path, 1,
1255                          _("Note: Fast-forwarding submodule %s to %s"),
1256                          path, oid_to_hex(b));
1257                 return 1;
1258         }
1259         if (in_merge_bases(commit_b, commit_a)) {
1260                 oidcpy(result, a);
1261                 path_msg(opt, path, 1,
1262                          _("Note: Fast-forwarding submodule %s to %s"),
1263                          path, oid_to_hex(a));
1264                 return 1;
1265         }
1266
1267         /*
1268          * Case #2: There are one or more merges that contain a and b in
1269          * the submodule. If there is only one, then present it as a
1270          * suggestion to the user, but leave it marked unmerged so the
1271          * user needs to confirm the resolution.
1272          */
1273
1274         /* Skip the search if makes no sense to the calling context.  */
1275         if (!search)
1276                 return 0;
1277
1278         /* find commit which merges them */
1279         parent_count = find_first_merges(opt->repo, path, commit_a, commit_b,
1280                                          &merges);
1281         switch (parent_count) {
1282         case 0:
1283                 path_msg(opt, path, 0, _("Failed to merge submodule %s"), path);
1284                 break;
1285
1286         case 1:
1287                 format_commit(&sb, 4,
1288                               (struct commit *)merges.objects[0].item);
1289                 path_msg(opt, path, 0,
1290                          _("Failed to merge submodule %s, but a possible merge "
1291                            "resolution exists:\n%s\n"),
1292                          path, sb.buf);
1293                 path_msg(opt, path, 1,
1294                          _("If this is correct simply add it to the index "
1295                            "for example\n"
1296                            "by using:\n\n"
1297                            "  git update-index --cacheinfo 160000 %s \"%s\"\n\n"
1298                            "which will accept this suggestion.\n"),
1299                          oid_to_hex(&merges.objects[0].item->oid), path);
1300                 strbuf_release(&sb);
1301                 break;
1302         default:
1303                 for (i = 0; i < merges.nr; i++)
1304                         format_commit(&sb, 4,
1305                                       (struct commit *)merges.objects[i].item);
1306                 path_msg(opt, path, 0,
1307                          _("Failed to merge submodule %s, but multiple "
1308                            "possible merges exist:\n%s"), path, sb.buf);
1309                 strbuf_release(&sb);
1310         }
1311
1312         object_array_clear(&merges);
1313         return 0;
1314 }
1315
1316 static void initialize_attr_index(struct merge_options *opt)
1317 {
1318         /*
1319          * The renormalize_buffer() functions require attributes, and
1320          * annoyingly those can only be read from the working tree or from
1321          * an index_state.  merge-ort doesn't have an index_state, so we
1322          * generate a fake one containing only attribute information.
1323          */
1324         struct merged_info *mi;
1325         struct index_state *attr_index = &opt->priv->attr_index;
1326         struct cache_entry *ce;
1327
1328         attr_index->initialized = 1;
1329
1330         if (!opt->renormalize)
1331                 return;
1332
1333         mi = strmap_get(&opt->priv->paths, GITATTRIBUTES_FILE);
1334         if (!mi)
1335                 return;
1336
1337         if (mi->clean) {
1338                 int len = strlen(GITATTRIBUTES_FILE);
1339                 ce = make_empty_cache_entry(attr_index, len);
1340                 ce->ce_mode = create_ce_mode(mi->result.mode);
1341                 ce->ce_flags = create_ce_flags(0);
1342                 ce->ce_namelen = len;
1343                 oidcpy(&ce->oid, &mi->result.oid);
1344                 memcpy(ce->name, GITATTRIBUTES_FILE, len);
1345                 add_index_entry(attr_index, ce,
1346                                 ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
1347                 get_stream_filter(attr_index, GITATTRIBUTES_FILE, &ce->oid);
1348         } else {
1349                 int stage, len;
1350                 struct conflict_info *ci;
1351
1352                 ASSIGN_AND_VERIFY_CI(ci, mi);
1353                 for (stage = 0; stage < 3; stage++) {
1354                         unsigned stage_mask = (1 << stage);
1355
1356                         if (!(ci->filemask & stage_mask))
1357                                 continue;
1358                         len = strlen(GITATTRIBUTES_FILE);
1359                         ce = make_empty_cache_entry(attr_index, len);
1360                         ce->ce_mode = create_ce_mode(ci->stages[stage].mode);
1361                         ce->ce_flags = create_ce_flags(stage);
1362                         ce->ce_namelen = len;
1363                         oidcpy(&ce->oid, &ci->stages[stage].oid);
1364                         memcpy(ce->name, GITATTRIBUTES_FILE, len);
1365                         add_index_entry(attr_index, ce,
1366                                         ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
1367                         get_stream_filter(attr_index, GITATTRIBUTES_FILE,
1368                                           &ce->oid);
1369                 }
1370         }
1371 }
1372
1373 static int merge_3way(struct merge_options *opt,
1374                       const char *path,
1375                       const struct object_id *o,
1376                       const struct object_id *a,
1377                       const struct object_id *b,
1378                       const char *pathnames[3],
1379                       const int extra_marker_size,
1380                       mmbuffer_t *result_buf)
1381 {
1382         mmfile_t orig, src1, src2;
1383         struct ll_merge_options ll_opts = {0};
1384         char *base, *name1, *name2;
1385         int merge_status;
1386
1387         if (!opt->priv->attr_index.initialized)
1388                 initialize_attr_index(opt);
1389
1390         ll_opts.renormalize = opt->renormalize;
1391         ll_opts.extra_marker_size = extra_marker_size;
1392         ll_opts.xdl_opts = opt->xdl_opts;
1393
1394         if (opt->priv->call_depth) {
1395                 ll_opts.virtual_ancestor = 1;
1396                 ll_opts.variant = 0;
1397         } else {
1398                 switch (opt->recursive_variant) {
1399                 case MERGE_VARIANT_OURS:
1400                         ll_opts.variant = XDL_MERGE_FAVOR_OURS;
1401                         break;
1402                 case MERGE_VARIANT_THEIRS:
1403                         ll_opts.variant = XDL_MERGE_FAVOR_THEIRS;
1404                         break;
1405                 default:
1406                         ll_opts.variant = 0;
1407                         break;
1408                 }
1409         }
1410
1411         assert(pathnames[0] && pathnames[1] && pathnames[2] && opt->ancestor);
1412         if (pathnames[0] == pathnames[1] && pathnames[1] == pathnames[2]) {
1413                 base  = mkpathdup("%s", opt->ancestor);
1414                 name1 = mkpathdup("%s", opt->branch1);
1415                 name2 = mkpathdup("%s", opt->branch2);
1416         } else {
1417                 base  = mkpathdup("%s:%s", opt->ancestor, pathnames[0]);
1418                 name1 = mkpathdup("%s:%s", opt->branch1,  pathnames[1]);
1419                 name2 = mkpathdup("%s:%s", opt->branch2,  pathnames[2]);
1420         }
1421
1422         read_mmblob(&orig, o);
1423         read_mmblob(&src1, a);
1424         read_mmblob(&src2, b);
1425
1426         merge_status = ll_merge(result_buf, path, &orig, base,
1427                                 &src1, name1, &src2, name2,
1428                                 &opt->priv->attr_index, &ll_opts);
1429
1430         free(base);
1431         free(name1);
1432         free(name2);
1433         free(orig.ptr);
1434         free(src1.ptr);
1435         free(src2.ptr);
1436         return merge_status;
1437 }
1438
1439 static int handle_content_merge(struct merge_options *opt,
1440                                 const char *path,
1441                                 const struct version_info *o,
1442                                 const struct version_info *a,
1443                                 const struct version_info *b,
1444                                 const char *pathnames[3],
1445                                 const int extra_marker_size,
1446                                 struct version_info *result)
1447 {
1448         /*
1449          * path is the target location where we want to put the file, and
1450          * is used to determine any normalization rules in ll_merge.
1451          *
1452          * The normal case is that path and all entries in pathnames are
1453          * identical, though renames can affect which path we got one of
1454          * the three blobs to merge on various sides of history.
1455          *
1456          * extra_marker_size is the amount to extend conflict markers in
1457          * ll_merge; this is neeed if we have content merges of content
1458          * merges, which happens for example with rename/rename(2to1) and
1459          * rename/add conflicts.
1460          */
1461         unsigned clean = 1;
1462
1463         /*
1464          * handle_content_merge() needs both files to be of the same type, i.e.
1465          * both files OR both submodules OR both symlinks.  Conflicting types
1466          * needs to be handled elsewhere.
1467          */
1468         assert((S_IFMT & a->mode) == (S_IFMT & b->mode));
1469
1470         /* Merge modes */
1471         if (a->mode == b->mode || a->mode == o->mode)
1472                 result->mode = b->mode;
1473         else {
1474                 /* must be the 100644/100755 case */
1475                 assert(S_ISREG(a->mode));
1476                 result->mode = a->mode;
1477                 clean = (b->mode == o->mode);
1478                 /*
1479                  * FIXME: If opt->priv->call_depth && !clean, then we really
1480                  * should not make result->mode match either a->mode or
1481                  * b->mode; that causes t6036 "check conflicting mode for
1482                  * regular file" to fail.  It would be best to use some other
1483                  * mode, but we'll confuse all kinds of stuff if we use one
1484                  * where S_ISREG(result->mode) isn't true, and if we use
1485                  * something like 0100666, then tree-walk.c's calls to
1486                  * canon_mode() will just normalize that to 100644 for us and
1487                  * thus not solve anything.
1488                  *
1489                  * Figure out if there's some kind of way we can work around
1490                  * this...
1491                  */
1492         }
1493
1494         /*
1495          * Trivial oid merge.
1496          *
1497          * Note: While one might assume that the next four lines would
1498          * be unnecessary due to the fact that match_mask is often
1499          * setup and already handled, renames don't always take care
1500          * of that.
1501          */
1502         if (oideq(&a->oid, &b->oid) || oideq(&a->oid, &o->oid))
1503                 oidcpy(&result->oid, &b->oid);
1504         else if (oideq(&b->oid, &o->oid))
1505                 oidcpy(&result->oid, &a->oid);
1506
1507         /* Remaining rules depend on file vs. submodule vs. symlink. */
1508         else if (S_ISREG(a->mode)) {
1509                 mmbuffer_t result_buf;
1510                 int ret = 0, merge_status;
1511                 int two_way;
1512
1513                 /*
1514                  * If 'o' is different type, treat it as null so we do a
1515                  * two-way merge.
1516                  */
1517                 two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
1518
1519                 merge_status = merge_3way(opt, path,
1520                                           two_way ? null_oid() : &o->oid,
1521                                           &a->oid, &b->oid,
1522                                           pathnames, extra_marker_size,
1523                                           &result_buf);
1524
1525                 if ((merge_status < 0) || !result_buf.ptr)
1526                         ret = err(opt, _("Failed to execute internal merge"));
1527
1528                 if (!ret &&
1529                     write_object_file(result_buf.ptr, result_buf.size,
1530                                       blob_type, &result->oid))
1531                         ret = err(opt, _("Unable to add %s to database"),
1532                                   path);
1533
1534                 free(result_buf.ptr);
1535                 if (ret)
1536                         return -1;
1537                 clean &= (merge_status == 0);
1538                 path_msg(opt, path, 1, _("Auto-merging %s"), path);
1539         } else if (S_ISGITLINK(a->mode)) {
1540                 int two_way = ((S_IFMT & o->mode) != (S_IFMT & a->mode));
1541                 clean = merge_submodule(opt, pathnames[0],
1542                                         two_way ? null_oid() : &o->oid,
1543                                         &a->oid, &b->oid, &result->oid);
1544                 if (opt->priv->call_depth && two_way && !clean) {
1545                         result->mode = o->mode;
1546                         oidcpy(&result->oid, &o->oid);
1547                 }
1548         } else if (S_ISLNK(a->mode)) {
1549                 if (opt->priv->call_depth) {
1550                         clean = 0;
1551                         result->mode = o->mode;
1552                         oidcpy(&result->oid, &o->oid);
1553                 } else {
1554                         switch (opt->recursive_variant) {
1555                         case MERGE_VARIANT_NORMAL:
1556                                 clean = 0;
1557                                 oidcpy(&result->oid, &a->oid);
1558                                 break;
1559                         case MERGE_VARIANT_OURS:
1560                                 oidcpy(&result->oid, &a->oid);
1561                                 break;
1562                         case MERGE_VARIANT_THEIRS:
1563                                 oidcpy(&result->oid, &b->oid);
1564                                 break;
1565                         }
1566                 }
1567         } else
1568                 BUG("unsupported object type in the tree: %06o for %s",
1569                     a->mode, path);
1570
1571         return clean;
1572 }
1573
1574 /*** Function Grouping: functions related to detect_and_process_renames(), ***
1575  *** which are split into directory and regular rename detection sections. ***/
1576
1577 /*** Function Grouping: functions related to directory rename detection ***/
1578
1579 struct collision_info {
1580         struct string_list source_files;
1581         unsigned reported_already:1;
1582 };
1583
1584 /*
1585  * Return a new string that replaces the beginning portion (which matches
1586  * rename_info->key), with rename_info->util.new_dir.  In perl-speak:
1587  *   new_path_name = (old_path =~ s/rename_info->key/rename_info->value/);
1588  * NOTE:
1589  *   Caller must ensure that old_path starts with rename_info->key + '/'.
1590  */
1591 static char *apply_dir_rename(struct strmap_entry *rename_info,
1592                               const char *old_path)
1593 {
1594         struct strbuf new_path = STRBUF_INIT;
1595         const char *old_dir = rename_info->key;
1596         const char *new_dir = rename_info->value;
1597         int oldlen, newlen, new_dir_len;
1598
1599         oldlen = strlen(old_dir);
1600         if (*new_dir == '\0')
1601                 /*
1602                  * If someone renamed/merged a subdirectory into the root
1603                  * directory (e.g. 'some/subdir' -> ''), then we want to
1604                  * avoid returning
1605                  *     '' + '/filename'
1606                  * as the rename; we need to make old_path + oldlen advance
1607                  * past the '/' character.
1608                  */
1609                 oldlen++;
1610         new_dir_len = strlen(new_dir);
1611         newlen = new_dir_len + (strlen(old_path) - oldlen) + 1;
1612         strbuf_grow(&new_path, newlen);
1613         strbuf_add(&new_path, new_dir, new_dir_len);
1614         strbuf_addstr(&new_path, &old_path[oldlen]);
1615
1616         return strbuf_detach(&new_path, NULL);
1617 }
1618
1619 static int path_in_way(struct strmap *paths, const char *path, unsigned side_mask)
1620 {
1621         struct merged_info *mi = strmap_get(paths, path);
1622         struct conflict_info *ci;
1623         if (!mi)
1624                 return 0;
1625         INITIALIZE_CI(ci, mi);
1626         return mi->clean || (side_mask & (ci->filemask | ci->dirmask));
1627 }
1628
1629 /*
1630  * See if there is a directory rename for path, and if there are any file
1631  * level conflicts on the given side for the renamed location.  If there is
1632  * a rename and there are no conflicts, return the new name.  Otherwise,
1633  * return NULL.
1634  */
1635 static char *handle_path_level_conflicts(struct merge_options *opt,
1636                                          const char *path,
1637                                          unsigned side_index,
1638                                          struct strmap_entry *rename_info,
1639                                          struct strmap *collisions)
1640 {
1641         char *new_path = NULL;
1642         struct collision_info *c_info;
1643         int clean = 1;
1644         struct strbuf collision_paths = STRBUF_INIT;
1645
1646         /*
1647          * entry has the mapping of old directory name to new directory name
1648          * that we want to apply to path.
1649          */
1650         new_path = apply_dir_rename(rename_info, path);
1651         if (!new_path)
1652                 BUG("Failed to apply directory rename!");
1653
1654         /*
1655          * The caller needs to have ensured that it has pre-populated
1656          * collisions with all paths that map to new_path.  Do a quick check
1657          * to ensure that's the case.
1658          */
1659         c_info = strmap_get(collisions, new_path);
1660         if (c_info == NULL)
1661                 BUG("c_info is NULL");
1662
1663         /*
1664          * Check for one-sided add/add/.../add conflicts, i.e.
1665          * where implicit renames from the other side doing
1666          * directory rename(s) can affect this side of history
1667          * to put multiple paths into the same location.  Warn
1668          * and bail on directory renames for such paths.
1669          */
1670         if (c_info->reported_already) {
1671                 clean = 0;
1672         } else if (path_in_way(&opt->priv->paths, new_path, 1 << side_index)) {
1673                 c_info->reported_already = 1;
1674                 strbuf_add_separated_string_list(&collision_paths, ", ",
1675                                                  &c_info->source_files);
1676                 path_msg(opt, new_path, 0,
1677                          _("CONFLICT (implicit dir rename): Existing file/dir "
1678                            "at %s in the way of implicit directory rename(s) "
1679                            "putting the following path(s) there: %s."),
1680                        new_path, collision_paths.buf);
1681                 clean = 0;
1682         } else if (c_info->source_files.nr > 1) {
1683                 c_info->reported_already = 1;
1684                 strbuf_add_separated_string_list(&collision_paths, ", ",
1685                                                  &c_info->source_files);
1686                 path_msg(opt, new_path, 0,
1687                          _("CONFLICT (implicit dir rename): Cannot map more "
1688                            "than one path to %s; implicit directory renames "
1689                            "tried to put these paths there: %s"),
1690                        new_path, collision_paths.buf);
1691                 clean = 0;
1692         }
1693
1694         /* Free memory we no longer need */
1695         strbuf_release(&collision_paths);
1696         if (!clean && new_path) {
1697                 free(new_path);
1698                 return NULL;
1699         }
1700
1701         return new_path;
1702 }
1703
1704 static void get_provisional_directory_renames(struct merge_options *opt,
1705                                               unsigned side,
1706                                               int *clean)
1707 {
1708         struct hashmap_iter iter;
1709         struct strmap_entry *entry;
1710         struct rename_info *renames = &opt->priv->renames;
1711
1712         /*
1713          * Collapse
1714          *    dir_rename_count: old_directory -> {new_directory -> count}
1715          * down to
1716          *    dir_renames: old_directory -> best_new_directory
1717          * where best_new_directory is the one with the unique highest count.
1718          */
1719         strmap_for_each_entry(&renames->dir_rename_count[side], &iter, entry) {
1720                 const char *source_dir = entry->key;
1721                 struct strintmap *counts = entry->value;
1722                 struct hashmap_iter count_iter;
1723                 struct strmap_entry *count_entry;
1724                 int max = 0;
1725                 int bad_max = 0;
1726                 const char *best = NULL;
1727
1728                 strintmap_for_each_entry(counts, &count_iter, count_entry) {
1729                         const char *target_dir = count_entry->key;
1730                         intptr_t count = (intptr_t)count_entry->value;
1731
1732                         if (count == max)
1733                                 bad_max = max;
1734                         else if (count > max) {
1735                                 max = count;
1736                                 best = target_dir;
1737                         }
1738                 }
1739
1740                 if (max == 0)
1741                         continue;
1742
1743                 if (bad_max == max) {
1744                         path_msg(opt, source_dir, 0,
1745                                _("CONFLICT (directory rename split): "
1746                                  "Unclear where to rename %s to; it was "
1747                                  "renamed to multiple other directories, with "
1748                                  "no destination getting a majority of the "
1749                                  "files."),
1750                                source_dir);
1751                         *clean = 0;
1752                 } else {
1753                         strmap_put(&renames->dir_renames[side],
1754                                    source_dir, (void*)best);
1755                 }
1756         }
1757 }
1758
1759 static void handle_directory_level_conflicts(struct merge_options *opt)
1760 {
1761         struct hashmap_iter iter;
1762         struct strmap_entry *entry;
1763         struct string_list duplicated = STRING_LIST_INIT_NODUP;
1764         struct rename_info *renames = &opt->priv->renames;
1765         struct strmap *side1_dir_renames = &renames->dir_renames[MERGE_SIDE1];
1766         struct strmap *side2_dir_renames = &renames->dir_renames[MERGE_SIDE2];
1767         int i;
1768
1769         strmap_for_each_entry(side1_dir_renames, &iter, entry) {
1770                 if (strmap_contains(side2_dir_renames, entry->key))
1771                         string_list_append(&duplicated, entry->key);
1772         }
1773
1774         for (i = 0; i < duplicated.nr; i++) {
1775                 strmap_remove(side1_dir_renames, duplicated.items[i].string, 0);
1776                 strmap_remove(side2_dir_renames, duplicated.items[i].string, 0);
1777         }
1778         string_list_clear(&duplicated, 0);
1779 }
1780
1781 static struct strmap_entry *check_dir_renamed(const char *path,
1782                                               struct strmap *dir_renames)
1783 {
1784         char *temp = xstrdup(path);
1785         char *end;
1786         struct strmap_entry *e = NULL;
1787
1788         while ((end = strrchr(temp, '/'))) {
1789                 *end = '\0';
1790                 e = strmap_get_entry(dir_renames, temp);
1791                 if (e)
1792                         break;
1793         }
1794         free(temp);
1795         return e;
1796 }
1797
1798 static void compute_collisions(struct strmap *collisions,
1799                                struct strmap *dir_renames,
1800                                struct diff_queue_struct *pairs)
1801 {
1802         int i;
1803
1804         strmap_init_with_options(collisions, NULL, 0);
1805         if (strmap_empty(dir_renames))
1806                 return;
1807
1808         /*
1809          * Multiple files can be mapped to the same path due to directory
1810          * renames done by the other side of history.  Since that other
1811          * side of history could have merged multiple directories into one,
1812          * if our side of history added the same file basename to each of
1813          * those directories, then all N of them would get implicitly
1814          * renamed by the directory rename detection into the same path,
1815          * and we'd get an add/add/.../add conflict, and all those adds
1816          * from *this* side of history.  This is not representable in the
1817          * index, and users aren't going to easily be able to make sense of
1818          * it.  So we need to provide a good warning about what's
1819          * happening, and fall back to no-directory-rename detection
1820          * behavior for those paths.
1821          *
1822          * See testcases 9e and all of section 5 from t6043 for examples.
1823          */
1824         for (i = 0; i < pairs->nr; ++i) {
1825                 struct strmap_entry *rename_info;
1826                 struct collision_info *collision_info;
1827                 char *new_path;
1828                 struct diff_filepair *pair = pairs->queue[i];
1829
1830                 if (pair->status != 'A' && pair->status != 'R')
1831                         continue;
1832                 rename_info = check_dir_renamed(pair->two->path, dir_renames);
1833                 if (!rename_info)
1834                         continue;
1835
1836                 new_path = apply_dir_rename(rename_info, pair->two->path);
1837                 assert(new_path);
1838                 collision_info = strmap_get(collisions, new_path);
1839                 if (collision_info) {
1840                         free(new_path);
1841                 } else {
1842                         CALLOC_ARRAY(collision_info, 1);
1843                         string_list_init(&collision_info->source_files, 0);
1844                         strmap_put(collisions, new_path, collision_info);
1845                 }
1846                 string_list_insert(&collision_info->source_files,
1847                                    pair->two->path);
1848         }
1849 }
1850
1851 static char *check_for_directory_rename(struct merge_options *opt,
1852                                         const char *path,
1853                                         unsigned side_index,
1854                                         struct strmap *dir_renames,
1855                                         struct strmap *dir_rename_exclusions,
1856                                         struct strmap *collisions,
1857                                         int *clean_merge)
1858 {
1859         char *new_path = NULL;
1860         struct strmap_entry *rename_info;
1861         struct strmap_entry *otherinfo = NULL;
1862         const char *new_dir;
1863
1864         if (strmap_empty(dir_renames))
1865                 return new_path;
1866         rename_info = check_dir_renamed(path, dir_renames);
1867         if (!rename_info)
1868                 return new_path;
1869         /* old_dir = rename_info->key; */
1870         new_dir = rename_info->value;
1871
1872         /*
1873          * This next part is a little weird.  We do not want to do an
1874          * implicit rename into a directory we renamed on our side, because
1875          * that will result in a spurious rename/rename(1to2) conflict.  An
1876          * example:
1877          *   Base commit: dumbdir/afile, otherdir/bfile
1878          *   Side 1:      smrtdir/afile, otherdir/bfile
1879          *   Side 2:      dumbdir/afile, dumbdir/bfile
1880          * Here, while working on Side 1, we could notice that otherdir was
1881          * renamed/merged to dumbdir, and change the diff_filepair for
1882          * otherdir/bfile into a rename into dumbdir/bfile.  However, Side
1883          * 2 will notice the rename from dumbdir to smrtdir, and do the
1884          * transitive rename to move it from dumbdir/bfile to
1885          * smrtdir/bfile.  That gives us bfile in dumbdir vs being in
1886          * smrtdir, a rename/rename(1to2) conflict.  We really just want
1887          * the file to end up in smrtdir.  And the way to achieve that is
1888          * to not let Side1 do the rename to dumbdir, since we know that is
1889          * the source of one of our directory renames.
1890          *
1891          * That's why otherinfo and dir_rename_exclusions is here.
1892          *
1893          * As it turns out, this also prevents N-way transient rename
1894          * confusion; See testcases 9c and 9d of t6043.
1895          */
1896         otherinfo = strmap_get_entry(dir_rename_exclusions, new_dir);
1897         if (otherinfo) {
1898                 path_msg(opt, rename_info->key, 1,
1899                          _("WARNING: Avoiding applying %s -> %s rename "
1900                            "to %s, because %s itself was renamed."),
1901                          rename_info->key, new_dir, path, new_dir);
1902                 return NULL;
1903         }
1904
1905         new_path = handle_path_level_conflicts(opt, path, side_index,
1906                                                rename_info, collisions);
1907         *clean_merge &= (new_path != NULL);
1908
1909         return new_path;
1910 }
1911
1912 static void apply_directory_rename_modifications(struct merge_options *opt,
1913                                                  struct diff_filepair *pair,
1914                                                  char *new_path)
1915 {
1916         /*
1917          * The basic idea is to get the conflict_info from opt->priv->paths
1918          * at old path, and insert it into new_path; basically just this:
1919          *     ci = strmap_get(&opt->priv->paths, old_path);
1920          *     strmap_remove(&opt->priv->paths, old_path, 0);
1921          *     strmap_put(&opt->priv->paths, new_path, ci);
1922          * However, there are some factors complicating this:
1923          *     - opt->priv->paths may already have an entry at new_path
1924          *     - Each ci tracks its containing directory, so we need to
1925          *       update that
1926          *     - If another ci has the same containing directory, then
1927          *       the two char*'s MUST point to the same location.  See the
1928          *       comment in struct merged_info.  strcmp equality is not
1929          *       enough; we need pointer equality.
1930          *     - opt->priv->paths must hold the parent directories of any
1931          *       entries that are added.  So, if this directory rename
1932          *       causes entirely new directories, we must recursively add
1933          *       parent directories.
1934          *     - For each parent directory added to opt->priv->paths, we
1935          *       also need to get its parent directory stored in its
1936          *       conflict_info->merged.directory_name with all the same
1937          *       requirements about pointer equality.
1938          */
1939         struct string_list dirs_to_insert = STRING_LIST_INIT_NODUP;
1940         struct conflict_info *ci, *new_ci;
1941         struct strmap_entry *entry;
1942         const char *branch_with_new_path, *branch_with_dir_rename;
1943         const char *old_path = pair->two->path;
1944         const char *parent_name;
1945         const char *cur_path;
1946         int i, len;
1947
1948         entry = strmap_get_entry(&opt->priv->paths, old_path);
1949         old_path = entry->key;
1950         ci = entry->value;
1951         VERIFY_CI(ci);
1952
1953         /* Find parent directories missing from opt->priv->paths */
1954         cur_path = new_path;
1955         while (1) {
1956                 /* Find the parent directory of cur_path */
1957                 char *last_slash = strrchr(cur_path, '/');
1958                 if (last_slash) {
1959                         parent_name = xstrndup(cur_path, last_slash - cur_path);
1960                 } else {
1961                         parent_name = opt->priv->toplevel_dir;
1962                         break;
1963                 }
1964
1965                 /* Look it up in opt->priv->paths */
1966                 entry = strmap_get_entry(&opt->priv->paths, parent_name);
1967                 if (entry) {
1968                         free((char*)parent_name);
1969                         parent_name = entry->key; /* reuse known pointer */
1970                         break;
1971                 }
1972
1973                 /* Record this is one of the directories we need to insert */
1974                 string_list_append(&dirs_to_insert, parent_name);
1975                 cur_path = parent_name;
1976         }
1977
1978         /* Traverse dirs_to_insert and insert them into opt->priv->paths */
1979         for (i = dirs_to_insert.nr-1; i >= 0; --i) {
1980                 struct conflict_info *dir_ci;
1981                 char *cur_dir = dirs_to_insert.items[i].string;
1982
1983                 CALLOC_ARRAY(dir_ci, 1);
1984
1985                 dir_ci->merged.directory_name = parent_name;
1986                 len = strlen(parent_name);
1987                 /* len+1 because of trailing '/' character */
1988                 dir_ci->merged.basename_offset = (len > 0 ? len+1 : len);
1989                 dir_ci->dirmask = ci->filemask;
1990                 strmap_put(&opt->priv->paths, cur_dir, dir_ci);
1991
1992                 parent_name = cur_dir;
1993         }
1994
1995         /*
1996          * We are removing old_path from opt->priv->paths.  old_path also will
1997          * eventually need to be freed, but it may still be used by e.g.
1998          * ci->pathnames.  So, store it in another string-list for now.
1999          */
2000         string_list_append(&opt->priv->paths_to_free, old_path);
2001
2002         assert(ci->filemask == 2 || ci->filemask == 4);
2003         assert(ci->dirmask == 0);
2004         strmap_remove(&opt->priv->paths, old_path, 0);
2005
2006         branch_with_new_path   = (ci->filemask == 2) ? opt->branch1 : opt->branch2;
2007         branch_with_dir_rename = (ci->filemask == 2) ? opt->branch2 : opt->branch1;
2008
2009         /* Now, finally update ci and stick it into opt->priv->paths */
2010         ci->merged.directory_name = parent_name;
2011         len = strlen(parent_name);
2012         ci->merged.basename_offset = (len > 0 ? len+1 : len);
2013         new_ci = strmap_get(&opt->priv->paths, new_path);
2014         if (!new_ci) {
2015                 /* Place ci back into opt->priv->paths, but at new_path */
2016                 strmap_put(&opt->priv->paths, new_path, ci);
2017         } else {
2018                 int index;
2019
2020                 /* A few sanity checks */
2021                 VERIFY_CI(new_ci);
2022                 assert(ci->filemask == 2 || ci->filemask == 4);
2023                 assert((new_ci->filemask & ci->filemask) == 0);
2024                 assert(!new_ci->merged.clean);
2025
2026                 /* Copy stuff from ci into new_ci */
2027                 new_ci->filemask |= ci->filemask;
2028                 if (new_ci->dirmask)
2029                         new_ci->df_conflict = 1;
2030                 index = (ci->filemask >> 1);
2031                 new_ci->pathnames[index] = ci->pathnames[index];
2032                 new_ci->stages[index].mode = ci->stages[index].mode;
2033                 oidcpy(&new_ci->stages[index].oid, &ci->stages[index].oid);
2034
2035                 free(ci);
2036                 ci = new_ci;
2037         }
2038
2039         if (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE) {
2040                 /* Notify user of updated path */
2041                 if (pair->status == 'A')
2042                         path_msg(opt, new_path, 1,
2043                                  _("Path updated: %s added in %s inside a "
2044                                    "directory that was renamed in %s; moving "
2045                                    "it to %s."),
2046                                  old_path, branch_with_new_path,
2047                                  branch_with_dir_rename, new_path);
2048                 else
2049                         path_msg(opt, new_path, 1,
2050                                  _("Path updated: %s renamed to %s in %s, "
2051                                    "inside a directory that was renamed in %s; "
2052                                    "moving it to %s."),
2053                                  pair->one->path, old_path, branch_with_new_path,
2054                                  branch_with_dir_rename, new_path);
2055         } else {
2056                 /*
2057                  * opt->detect_directory_renames has the value
2058                  * MERGE_DIRECTORY_RENAMES_CONFLICT, so mark these as conflicts.
2059                  */
2060                 ci->path_conflict = 1;
2061                 if (pair->status == 'A')
2062                         path_msg(opt, new_path, 0,
2063                                  _("CONFLICT (file location): %s added in %s "
2064                                    "inside a directory that was renamed in %s, "
2065                                    "suggesting it should perhaps be moved to "
2066                                    "%s."),
2067                                  old_path, branch_with_new_path,
2068                                  branch_with_dir_rename, new_path);
2069                 else
2070                         path_msg(opt, new_path, 0,
2071                                  _("CONFLICT (file location): %s renamed to %s "
2072                                    "in %s, inside a directory that was renamed "
2073                                    "in %s, suggesting it should perhaps be "
2074                                    "moved to %s."),
2075                                  pair->one->path, old_path, branch_with_new_path,
2076                                  branch_with_dir_rename, new_path);
2077         }
2078
2079         /*
2080          * Finally, record the new location.
2081          */
2082         pair->two->path = new_path;
2083 }
2084
2085 /*** Function Grouping: functions related to regular rename detection ***/
2086
2087 static int process_renames(struct merge_options *opt,
2088                            struct diff_queue_struct *renames)
2089 {
2090         int clean_merge = 1, i;
2091
2092         for (i = 0; i < renames->nr; ++i) {
2093                 const char *oldpath = NULL, *newpath;
2094                 struct diff_filepair *pair = renames->queue[i];
2095                 struct conflict_info *oldinfo = NULL, *newinfo = NULL;
2096                 struct strmap_entry *old_ent, *new_ent;
2097                 unsigned int old_sidemask;
2098                 int target_index, other_source_index;
2099                 int source_deleted, collision, type_changed;
2100                 const char *rename_branch = NULL, *delete_branch = NULL;
2101
2102                 old_ent = strmap_get_entry(&opt->priv->paths, pair->one->path);
2103                 new_ent = strmap_get_entry(&opt->priv->paths, pair->two->path);
2104                 if (old_ent) {
2105                         oldpath = old_ent->key;
2106                         oldinfo = old_ent->value;
2107                 }
2108                 newpath = pair->two->path;
2109                 if (new_ent) {
2110                         newpath = new_ent->key;
2111                         newinfo = new_ent->value;
2112                 }
2113
2114                 /*
2115                  * If pair->one->path isn't in opt->priv->paths, that means
2116                  * that either directory rename detection removed that
2117                  * path, or a parent directory of oldpath was resolved and
2118                  * we don't even need the rename; in either case, we can
2119                  * skip it.  If oldinfo->merged.clean, then the other side
2120                  * of history had no changes to oldpath and we don't need
2121                  * the rename and can skip it.
2122                  */
2123                 if (!oldinfo || oldinfo->merged.clean)
2124                         continue;
2125
2126                 /*
2127                  * diff_filepairs have copies of pathnames, thus we have to
2128                  * use standard 'strcmp()' (negated) instead of '=='.
2129                  */
2130                 if (i + 1 < renames->nr &&
2131                     !strcmp(oldpath, renames->queue[i+1]->one->path)) {
2132                         /* Handle rename/rename(1to2) or rename/rename(1to1) */
2133                         const char *pathnames[3];
2134                         struct version_info merged;
2135                         struct conflict_info *base, *side1, *side2;
2136                         unsigned was_binary_blob = 0;
2137
2138                         pathnames[0] = oldpath;
2139                         pathnames[1] = newpath;
2140                         pathnames[2] = renames->queue[i+1]->two->path;
2141
2142                         base = strmap_get(&opt->priv->paths, pathnames[0]);
2143                         side1 = strmap_get(&opt->priv->paths, pathnames[1]);
2144                         side2 = strmap_get(&opt->priv->paths, pathnames[2]);
2145
2146                         VERIFY_CI(base);
2147                         VERIFY_CI(side1);
2148                         VERIFY_CI(side2);
2149
2150                         if (!strcmp(pathnames[1], pathnames[2])) {
2151                                 struct rename_info *ri = &opt->priv->renames;
2152                                 int j;
2153
2154                                 /* Both sides renamed the same way */
2155                                 assert(side1 == side2);
2156                                 memcpy(&side1->stages[0], &base->stages[0],
2157                                        sizeof(merged));
2158                                 side1->filemask |= (1 << MERGE_BASE);
2159                                 /* Mark base as resolved by removal */
2160                                 base->merged.is_null = 1;
2161                                 base->merged.clean = 1;
2162
2163                                 /*
2164                                  * Disable remembering renames optimization;
2165                                  * rename/rename(1to1) is incredibly rare, and
2166                                  * just disabling the optimization is easier
2167                                  * than purging cached_pairs,
2168                                  * cached_target_names, and dir_rename_counts.
2169                                  */
2170                                 for (j = 0; j < 3; j++)
2171                                         ri->merge_trees[j] = NULL;
2172
2173                                 /* We handled both renames, i.e. i+1 handled */
2174                                 i++;
2175                                 /* Move to next rename */
2176                                 continue;
2177                         }
2178
2179                         /* This is a rename/rename(1to2) */
2180                         clean_merge = handle_content_merge(opt,
2181                                                            pair->one->path,
2182                                                            &base->stages[0],
2183                                                            &side1->stages[1],
2184                                                            &side2->stages[2],
2185                                                            pathnames,
2186                                                            1 + 2 * opt->priv->call_depth,
2187                                                            &merged);
2188                         if (!clean_merge &&
2189                             merged.mode == side1->stages[1].mode &&
2190                             oideq(&merged.oid, &side1->stages[1].oid))
2191                                 was_binary_blob = 1;
2192                         memcpy(&side1->stages[1], &merged, sizeof(merged));
2193                         if (was_binary_blob) {
2194                                 /*
2195                                  * Getting here means we were attempting to
2196                                  * merge a binary blob.
2197                                  *
2198                                  * Since we can't merge binaries,
2199                                  * handle_content_merge() just takes one
2200                                  * side.  But we don't want to copy the
2201                                  * contents of one side to both paths.  We
2202                                  * used the contents of side1 above for
2203                                  * side1->stages, let's use the contents of
2204                                  * side2 for side2->stages below.
2205                                  */
2206                                 oidcpy(&merged.oid, &side2->stages[2].oid);
2207                                 merged.mode = side2->stages[2].mode;
2208                         }
2209                         memcpy(&side2->stages[2], &merged, sizeof(merged));
2210
2211                         side1->path_conflict = 1;
2212                         side2->path_conflict = 1;
2213                         /*
2214                          * TODO: For renames we normally remove the path at the
2215                          * old name.  It would thus seem consistent to do the
2216                          * same for rename/rename(1to2) cases, but we haven't
2217                          * done so traditionally and a number of the regression
2218                          * tests now encode an expectation that the file is
2219                          * left there at stage 1.  If we ever decide to change
2220                          * this, add the following two lines here:
2221                          *    base->merged.is_null = 1;
2222                          *    base->merged.clean = 1;
2223                          * and remove the setting of base->path_conflict to 1.
2224                          */
2225                         base->path_conflict = 1;
2226                         path_msg(opt, oldpath, 0,
2227                                  _("CONFLICT (rename/rename): %s renamed to "
2228                                    "%s in %s and to %s in %s."),
2229                                  pathnames[0],
2230                                  pathnames[1], opt->branch1,
2231                                  pathnames[2], opt->branch2);
2232
2233                         i++; /* We handled both renames, i.e. i+1 handled */
2234                         continue;
2235                 }
2236
2237                 VERIFY_CI(oldinfo);
2238                 VERIFY_CI(newinfo);
2239                 target_index = pair->score; /* from collect_renames() */
2240                 assert(target_index == 1 || target_index == 2);
2241                 other_source_index = 3 - target_index;
2242                 old_sidemask = (1 << other_source_index); /* 2 or 4 */
2243                 source_deleted = (oldinfo->filemask == 1);
2244                 collision = ((newinfo->filemask & old_sidemask) != 0);
2245                 type_changed = !source_deleted &&
2246                         (S_ISREG(oldinfo->stages[other_source_index].mode) !=
2247                          S_ISREG(newinfo->stages[target_index].mode));
2248                 if (type_changed && collision) {
2249                         /*
2250                          * special handling so later blocks can handle this...
2251                          *
2252                          * if type_changed && collision are both true, then this
2253                          * was really a double rename, but one side wasn't
2254                          * detected due to lack of break detection.  I.e.
2255                          * something like
2256                          *    orig: has normal file 'foo'
2257                          *    side1: renames 'foo' to 'bar', adds 'foo' symlink
2258                          *    side2: renames 'foo' to 'bar'
2259                          * In this case, the foo->bar rename on side1 won't be
2260                          * detected because the new symlink named 'foo' is
2261                          * there and we don't do break detection.  But we detect
2262                          * this here because we don't want to merge the content
2263                          * of the foo symlink with the foo->bar file, so we
2264                          * have some logic to handle this special case.  The
2265                          * easiest way to do that is make 'bar' on side1 not
2266                          * be considered a colliding file but the other part
2267                          * of a normal rename.  If the file is very different,
2268                          * well we're going to get content merge conflicts
2269                          * anyway so it doesn't hurt.  And if the colliding
2270                          * file also has a different type, that'll be handled
2271                          * by the content merge logic in process_entry() too.
2272                          *
2273                          * See also t6430, 'rename vs. rename/symlink'
2274                          */
2275                         collision = 0;
2276                 }
2277                 if (source_deleted) {
2278                         if (target_index == 1) {
2279                                 rename_branch = opt->branch1;
2280                                 delete_branch = opt->branch2;
2281                         } else {
2282                                 rename_branch = opt->branch2;
2283                                 delete_branch = opt->branch1;
2284                         }
2285                 }
2286
2287                 assert(source_deleted || oldinfo->filemask & old_sidemask);
2288
2289                 /* Need to check for special types of rename conflicts... */
2290                 if (collision && !source_deleted) {
2291                         /* collision: rename/add or rename/rename(2to1) */
2292                         const char *pathnames[3];
2293                         struct version_info merged;
2294
2295                         struct conflict_info *base, *side1, *side2;
2296                         unsigned clean;
2297
2298                         pathnames[0] = oldpath;
2299                         pathnames[other_source_index] = oldpath;
2300                         pathnames[target_index] = newpath;
2301
2302                         base = strmap_get(&opt->priv->paths, pathnames[0]);
2303                         side1 = strmap_get(&opt->priv->paths, pathnames[1]);
2304                         side2 = strmap_get(&opt->priv->paths, pathnames[2]);
2305
2306                         VERIFY_CI(base);
2307                         VERIFY_CI(side1);
2308                         VERIFY_CI(side2);
2309
2310                         clean = handle_content_merge(opt, pair->one->path,
2311                                                      &base->stages[0],
2312                                                      &side1->stages[1],
2313                                                      &side2->stages[2],
2314                                                      pathnames,
2315                                                      1 + 2 * opt->priv->call_depth,
2316                                                      &merged);
2317
2318                         memcpy(&newinfo->stages[target_index], &merged,
2319                                sizeof(merged));
2320                         if (!clean) {
2321                                 path_msg(opt, newpath, 0,
2322                                          _("CONFLICT (rename involved in "
2323                                            "collision): rename of %s -> %s has "
2324                                            "content conflicts AND collides "
2325                                            "with another path; this may result "
2326                                            "in nested conflict markers."),
2327                                          oldpath, newpath);
2328                         }
2329                 } else if (collision && source_deleted) {
2330                         /*
2331                          * rename/add/delete or rename/rename(2to1)/delete:
2332                          * since oldpath was deleted on the side that didn't
2333                          * do the rename, there's not much of a content merge
2334                          * we can do for the rename.  oldinfo->merged.is_null
2335                          * was already set, so we just leave things as-is so
2336                          * they look like an add/add conflict.
2337                          */
2338
2339                         newinfo->path_conflict = 1;
2340                         path_msg(opt, newpath, 0,
2341                                  _("CONFLICT (rename/delete): %s renamed "
2342                                    "to %s in %s, but deleted in %s."),
2343                                  oldpath, newpath, rename_branch, delete_branch);
2344                 } else {
2345                         /*
2346                          * a few different cases...start by copying the
2347                          * existing stage(s) from oldinfo over the newinfo
2348                          * and update the pathname(s).
2349                          */
2350                         memcpy(&newinfo->stages[0], &oldinfo->stages[0],
2351                                sizeof(newinfo->stages[0]));
2352                         newinfo->filemask |= (1 << MERGE_BASE);
2353                         newinfo->pathnames[0] = oldpath;
2354                         if (type_changed) {
2355                                 /* rename vs. typechange */
2356                                 /* Mark the original as resolved by removal */
2357                                 memcpy(&oldinfo->stages[0].oid, null_oid(),
2358                                        sizeof(oldinfo->stages[0].oid));
2359                                 oldinfo->stages[0].mode = 0;
2360                                 oldinfo->filemask &= 0x06;
2361                         } else if (source_deleted) {
2362                                 /* rename/delete */
2363                                 newinfo->path_conflict = 1;
2364                                 path_msg(opt, newpath, 0,
2365                                          _("CONFLICT (rename/delete): %s renamed"
2366                                            " to %s in %s, but deleted in %s."),
2367                                          oldpath, newpath,
2368                                          rename_branch, delete_branch);
2369                         } else {
2370                                 /* normal rename */
2371                                 memcpy(&newinfo->stages[other_source_index],
2372                                        &oldinfo->stages[other_source_index],
2373                                        sizeof(newinfo->stages[0]));
2374                                 newinfo->filemask |= (1 << other_source_index);
2375                                 newinfo->pathnames[other_source_index] = oldpath;
2376                         }
2377                 }
2378
2379                 if (!type_changed) {
2380                         /* Mark the original as resolved by removal */
2381                         oldinfo->merged.is_null = 1;
2382                         oldinfo->merged.clean = 1;
2383                 }
2384
2385         }
2386
2387         return clean_merge;
2388 }
2389
2390 static inline int possible_side_renames(struct rename_info *renames,
2391                                         unsigned side_index)
2392 {
2393         return renames->pairs[side_index].nr > 0 &&
2394                !strintmap_empty(&renames->relevant_sources[side_index]);
2395 }
2396
2397 static inline int possible_renames(struct rename_info *renames)
2398 {
2399         return possible_side_renames(renames, 1) ||
2400                possible_side_renames(renames, 2) ||
2401                !strmap_empty(&renames->cached_pairs[1]) ||
2402                !strmap_empty(&renames->cached_pairs[2]);
2403 }
2404
2405 static void resolve_diffpair_statuses(struct diff_queue_struct *q)
2406 {
2407         /*
2408          * A simplified version of diff_resolve_rename_copy(); would probably
2409          * just use that function but it's static...
2410          */
2411         int i;
2412         struct diff_filepair *p;
2413
2414         for (i = 0; i < q->nr; ++i) {
2415                 p = q->queue[i];
2416                 p->status = 0; /* undecided */
2417                 if (!DIFF_FILE_VALID(p->one))
2418                         p->status = DIFF_STATUS_ADDED;
2419                 else if (!DIFF_FILE_VALID(p->two))
2420                         p->status = DIFF_STATUS_DELETED;
2421                 else if (DIFF_PAIR_RENAME(p))
2422                         p->status = DIFF_STATUS_RENAMED;
2423         }
2424 }
2425
2426 static void prune_cached_from_relevant(struct rename_info *renames,
2427                                        unsigned side)
2428 {
2429         /* Reason for this function described in add_pair() */
2430         struct hashmap_iter iter;
2431         struct strmap_entry *entry;
2432
2433         /* Remove from relevant_sources all entries in cached_pairs[side] */
2434         strmap_for_each_entry(&renames->cached_pairs[side], &iter, entry) {
2435                 strintmap_remove(&renames->relevant_sources[side],
2436                                  entry->key);
2437         }
2438         /* Remove from relevant_sources all entries in cached_irrelevant[side] */
2439         strset_for_each_entry(&renames->cached_irrelevant[side], &iter, entry) {
2440                 strintmap_remove(&renames->relevant_sources[side],
2441                                  entry->key);
2442         }
2443 }
2444
2445 static void use_cached_pairs(struct merge_options *opt,
2446                              struct strmap *cached_pairs,
2447                              struct diff_queue_struct *pairs)
2448 {
2449         struct hashmap_iter iter;
2450         struct strmap_entry *entry;
2451
2452         /*
2453          * Add to side_pairs all entries from renames->cached_pairs[side_index].
2454          * (Info in cached_irrelevant[side_index] is not relevant here.)
2455          */
2456         strmap_for_each_entry(cached_pairs, &iter, entry) {
2457                 struct diff_filespec *one, *two;
2458                 const char *old_name = entry->key;
2459                 const char *new_name = entry->value;
2460                 if (!new_name)
2461                         new_name = old_name;
2462
2463                 /* We don't care about oid/mode, only filenames and status */
2464                 one = alloc_filespec(old_name);
2465                 two = alloc_filespec(new_name);
2466                 diff_queue(pairs, one, two);
2467                 pairs->queue[pairs->nr-1]->status = entry->value ? 'R' : 'D';
2468         }
2469 }
2470
2471 static void cache_new_pair(struct rename_info *renames,
2472                            int side,
2473                            char *old_path,
2474                            char *new_path,
2475                            int free_old_value)
2476 {
2477         char *old_value;
2478         new_path = xstrdup(new_path);
2479         old_value = strmap_put(&renames->cached_pairs[side],
2480                                old_path, new_path);
2481         strset_add(&renames->cached_target_names[side], new_path);
2482         if (free_old_value)
2483                 free(old_value);
2484         else
2485                 assert(!old_value);
2486 }
2487
2488 static void possibly_cache_new_pair(struct rename_info *renames,
2489                                     struct diff_filepair *p,
2490                                     unsigned side,
2491                                     char *new_path)
2492 {
2493         int dir_renamed_side = 0;
2494
2495         if (new_path) {
2496                 /*
2497                  * Directory renames happen on the other side of history from
2498                  * the side that adds new files to the old directory.
2499                  */
2500                 dir_renamed_side = 3 - side;
2501         } else {
2502                 int val = strintmap_get(&renames->relevant_sources[side],
2503                                         p->one->path);
2504                 if (val == RELEVANT_NO_MORE) {
2505                         assert(p->status == 'D');
2506                         strset_add(&renames->cached_irrelevant[side],
2507                                    p->one->path);
2508                 }
2509                 if (val <= 0)
2510                         return;
2511         }
2512
2513         if (p->status == 'D') {
2514                 /*
2515                  * If we already had this delete, we'll just set it's value
2516                  * to NULL again, so no harm.
2517                  */
2518                 strmap_put(&renames->cached_pairs[side], p->one->path, NULL);
2519         } else if (p->status == 'R') {
2520                 if (!new_path)
2521                         new_path = p->two->path;
2522                 else
2523                         cache_new_pair(renames, dir_renamed_side,
2524                                        p->two->path, new_path, 0);
2525                 cache_new_pair(renames, side, p->one->path, new_path, 1);
2526         } else if (p->status == 'A' && new_path) {
2527                 cache_new_pair(renames, dir_renamed_side,
2528                                p->two->path, new_path, 0);
2529         }
2530 }
2531
2532 static int compare_pairs(const void *a_, const void *b_)
2533 {
2534         const struct diff_filepair *a = *((const struct diff_filepair **)a_);
2535         const struct diff_filepair *b = *((const struct diff_filepair **)b_);
2536
2537         return strcmp(a->one->path, b->one->path);
2538 }
2539
2540 /* Call diffcore_rename() to update deleted/added pairs into rename pairs */
2541 static void detect_regular_renames(struct merge_options *opt,
2542                                    unsigned side_index)
2543 {
2544         struct diff_options diff_opts;
2545         struct rename_info *renames = &opt->priv->renames;
2546
2547         prune_cached_from_relevant(renames, side_index);
2548         if (!possible_side_renames(renames, side_index)) {
2549                 /*
2550                  * No rename detection needed for this side, but we still need
2551                  * to make sure 'adds' are marked correctly in case the other
2552                  * side had directory renames.
2553                  */
2554                 resolve_diffpair_statuses(&renames->pairs[side_index]);
2555                 return;
2556         }
2557
2558         partial_clear_dir_rename_count(&renames->dir_rename_count[side_index]);
2559         repo_diff_setup(opt->repo, &diff_opts);
2560         diff_opts.flags.recursive = 1;
2561         diff_opts.flags.rename_empty = 0;
2562         diff_opts.detect_rename = DIFF_DETECT_RENAME;
2563         diff_opts.rename_limit = opt->rename_limit;
2564         if (opt->rename_limit <= 0)
2565                 diff_opts.rename_limit = 1000;
2566         diff_opts.rename_score = opt->rename_score;
2567         diff_opts.show_rename_progress = opt->show_rename_progress;
2568         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2569         diff_setup_done(&diff_opts);
2570
2571         diff_queued_diff = renames->pairs[side_index];
2572         trace2_region_enter("diff", "diffcore_rename", opt->repo);
2573         diffcore_rename_extended(&diff_opts,
2574                                  &renames->relevant_sources[side_index],
2575                                  &renames->dirs_removed[side_index],
2576                                  &renames->dir_rename_count[side_index],
2577                                  &renames->cached_pairs[side_index]);
2578         trace2_region_leave("diff", "diffcore_rename", opt->repo);
2579         resolve_diffpair_statuses(&diff_queued_diff);
2580
2581         if (diff_opts.needed_rename_limit > renames->needed_limit)
2582                 renames->needed_limit = diff_opts.needed_rename_limit;
2583
2584         renames->pairs[side_index] = diff_queued_diff;
2585
2586         diff_opts.output_format = DIFF_FORMAT_NO_OUTPUT;
2587         diff_queued_diff.nr = 0;
2588         diff_queued_diff.queue = NULL;
2589         diff_flush(&diff_opts);
2590 }
2591
2592 /*
2593  * Get information of all renames which occurred in 'side_pairs', making use
2594  * of any implicit directory renames in side_dir_renames (also making use of
2595  * implicit directory renames rename_exclusions as needed by
2596  * check_for_directory_rename()).  Add all (updated) renames into result.
2597  */
2598 static int collect_renames(struct merge_options *opt,
2599                            struct diff_queue_struct *result,
2600                            unsigned side_index,
2601                            struct strmap *dir_renames_for_side,
2602                            struct strmap *rename_exclusions)
2603 {
2604         int i, clean = 1;
2605         struct strmap collisions;
2606         struct diff_queue_struct *side_pairs;
2607         struct hashmap_iter iter;
2608         struct strmap_entry *entry;
2609         struct rename_info *renames = &opt->priv->renames;
2610
2611         side_pairs = &renames->pairs[side_index];
2612         compute_collisions(&collisions, dir_renames_for_side, side_pairs);
2613
2614         for (i = 0; i < side_pairs->nr; ++i) {
2615                 struct diff_filepair *p = side_pairs->queue[i];
2616                 char *new_path; /* non-NULL only with directory renames */
2617
2618                 if (p->status != 'A' && p->status != 'R') {
2619                         possibly_cache_new_pair(renames, p, side_index, NULL);
2620                         diff_free_filepair(p);
2621                         continue;
2622                 }
2623
2624                 new_path = check_for_directory_rename(opt, p->two->path,
2625                                                       side_index,
2626                                                       dir_renames_for_side,
2627                                                       rename_exclusions,
2628                                                       &collisions,
2629                                                       &clean);
2630
2631                 possibly_cache_new_pair(renames, p, side_index, new_path);
2632                 if (p->status != 'R' && !new_path) {
2633                         diff_free_filepair(p);
2634                         continue;
2635                 }
2636
2637                 if (new_path)
2638                         apply_directory_rename_modifications(opt, p, new_path);
2639
2640                 /*
2641                  * p->score comes back from diffcore_rename_extended() with
2642                  * the similarity of the renamed file.  The similarity is
2643                  * was used to determine that the two files were related
2644                  * and are a rename, which we have already used, but beyond
2645                  * that we have no use for the similarity.  So p->score is
2646                  * now irrelevant.  However, process_renames() will need to
2647                  * know which side of the merge this rename was associated
2648                  * with, so overwrite p->score with that value.
2649                  */
2650                 p->score = side_index;
2651                 result->queue[result->nr++] = p;
2652         }
2653
2654         /* Free each value in the collisions map */
2655         strmap_for_each_entry(&collisions, &iter, entry) {
2656                 struct collision_info *info = entry->value;
2657                 string_list_clear(&info->source_files, 0);
2658         }
2659         /*
2660          * In compute_collisions(), we set collisions.strdup_strings to 0
2661          * so that we wouldn't have to make another copy of the new_path
2662          * allocated by apply_dir_rename().  But now that we've used them
2663          * and have no other references to these strings, it is time to
2664          * deallocate them.
2665          */
2666         free_strmap_strings(&collisions);
2667         strmap_clear(&collisions, 1);
2668         return clean;
2669 }
2670
2671 static int detect_and_process_renames(struct merge_options *opt,
2672                                       struct tree *merge_base,
2673                                       struct tree *side1,
2674                                       struct tree *side2)
2675 {
2676         struct diff_queue_struct combined;
2677         struct rename_info *renames = &opt->priv->renames;
2678         int need_dir_renames, s, clean = 1;
2679
2680         memset(&combined, 0, sizeof(combined));
2681         if (!possible_renames(renames))
2682                 goto cleanup;
2683
2684         trace2_region_enter("merge", "regular renames", opt->repo);
2685         detect_regular_renames(opt, MERGE_SIDE1);
2686         detect_regular_renames(opt, MERGE_SIDE2);
2687         use_cached_pairs(opt, &renames->cached_pairs[1], &renames->pairs[1]);
2688         use_cached_pairs(opt, &renames->cached_pairs[2], &renames->pairs[2]);
2689         trace2_region_leave("merge", "regular renames", opt->repo);
2690
2691         trace2_region_enter("merge", "directory renames", opt->repo);
2692         need_dir_renames =
2693           !opt->priv->call_depth &&
2694           (opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_TRUE ||
2695            opt->detect_directory_renames == MERGE_DIRECTORY_RENAMES_CONFLICT);
2696
2697         if (need_dir_renames) {
2698                 get_provisional_directory_renames(opt, MERGE_SIDE1, &clean);
2699                 get_provisional_directory_renames(opt, MERGE_SIDE2, &clean);
2700                 handle_directory_level_conflicts(opt);
2701         }
2702
2703         ALLOC_GROW(combined.queue,
2704                    renames->pairs[1].nr + renames->pairs[2].nr,
2705                    combined.alloc);
2706         clean &= collect_renames(opt, &combined, MERGE_SIDE1,
2707                                  &renames->dir_renames[2],
2708                                  &renames->dir_renames[1]);
2709         clean &= collect_renames(opt, &combined, MERGE_SIDE2,
2710                                  &renames->dir_renames[1],
2711                                  &renames->dir_renames[2]);
2712         STABLE_QSORT(combined.queue, combined.nr, compare_pairs);
2713         trace2_region_leave("merge", "directory renames", opt->repo);
2714
2715         trace2_region_enter("merge", "process renames", opt->repo);
2716         clean &= process_renames(opt, &combined);
2717         trace2_region_leave("merge", "process renames", opt->repo);
2718
2719         goto simple_cleanup; /* collect_renames() handles some of cleanup */
2720
2721 cleanup:
2722         /*
2723          * Free now unneeded filepairs, which would have been handled
2724          * in collect_renames() normally but we skipped that code.
2725          */
2726         for (s = MERGE_SIDE1; s <= MERGE_SIDE2; s++) {
2727                 struct diff_queue_struct *side_pairs;
2728                 int i;
2729
2730                 side_pairs = &renames->pairs[s];
2731                 for (i = 0; i < side_pairs->nr; ++i) {
2732                         struct diff_filepair *p = side_pairs->queue[i];
2733                         diff_free_filepair(p);
2734                 }
2735         }
2736
2737 simple_cleanup:
2738         /* Free memory for renames->pairs[] and combined */
2739         for (s = MERGE_SIDE1; s <= MERGE_SIDE2; s++) {
2740                 free(renames->pairs[s].queue);
2741                 DIFF_QUEUE_CLEAR(&renames->pairs[s]);
2742         }
2743         if (combined.nr) {
2744                 int i;
2745                 for (i = 0; i < combined.nr; i++)
2746                         diff_free_filepair(combined.queue[i]);
2747                 free(combined.queue);
2748         }
2749
2750         return clean;
2751 }
2752
2753 /*** Function Grouping: functions related to process_entries() ***/
2754
2755 static int sort_dirs_next_to_their_children(const char *one, const char *two)
2756 {
2757         unsigned char c1, c2;
2758
2759         /*
2760          * Here we only care that entries for directories appear adjacent
2761          * to and before files underneath the directory.  We can achieve
2762          * that by pretending to add a trailing slash to every file and
2763          * then sorting.  In other words, we do not want the natural
2764          * sorting of
2765          *     foo
2766          *     foo.txt
2767          *     foo/bar
2768          * Instead, we want "foo" to sort as though it were "foo/", so that
2769          * we instead get
2770          *     foo.txt
2771          *     foo
2772          *     foo/bar
2773          * To achieve this, we basically implement our own strcmp, except that
2774          * if we get to the end of either string instead of comparing NUL to
2775          * another character, we compare '/' to it.
2776          *
2777          * If this unusual "sort as though '/' were appended" perplexes
2778          * you, perhaps it will help to note that this is not the final
2779          * sort.  write_tree() will sort again without the trailing slash
2780          * magic, but just on paths immediately under a given tree.
2781          *
2782          * The reason to not use df_name_compare directly was that it was
2783          * just too expensive (we don't have the string lengths handy), so
2784          * it was reimplemented.
2785          */
2786
2787         /*
2788          * NOTE: This function will never be called with two equal strings,
2789          * because it is used to sort the keys of a strmap, and strmaps have
2790          * unique keys by construction.  That simplifies our c1==c2 handling
2791          * below.
2792          */
2793
2794         while (*one && (*one == *two)) {
2795                 one++;
2796                 two++;
2797         }
2798
2799         c1 = *one ? *one : '/';
2800         c2 = *two ? *two : '/';
2801
2802         if (c1 == c2) {
2803                 /* Getting here means one is a leading directory of the other */
2804                 return (*one) ? 1 : -1;
2805         } else
2806                 return c1 - c2;
2807 }
2808
2809 static int read_oid_strbuf(struct merge_options *opt,
2810                            const struct object_id *oid,
2811                            struct strbuf *dst)
2812 {
2813         void *buf;
2814         enum object_type type;
2815         unsigned long size;
2816         buf = read_object_file(oid, &type, &size);
2817         if (!buf)
2818                 return err(opt, _("cannot read object %s"), oid_to_hex(oid));
2819         if (type != OBJ_BLOB) {
2820                 free(buf);
2821                 return err(opt, _("object %s is not a blob"), oid_to_hex(oid));
2822         }
2823         strbuf_attach(dst, buf, size, size + 1);
2824         return 0;
2825 }
2826
2827 static int blob_unchanged(struct merge_options *opt,
2828                           const struct version_info *base,
2829                           const struct version_info *side,
2830                           const char *path)
2831 {
2832         struct strbuf basebuf = STRBUF_INIT;
2833         struct strbuf sidebuf = STRBUF_INIT;
2834         int ret = 0; /* assume changed for safety */
2835         struct index_state *idx = &opt->priv->attr_index;
2836
2837         if (!idx->initialized)
2838                 initialize_attr_index(opt);
2839
2840         if (base->mode != side->mode)
2841                 return 0;
2842         if (oideq(&base->oid, &side->oid))
2843                 return 1;
2844
2845         if (read_oid_strbuf(opt, &base->oid, &basebuf) ||
2846             read_oid_strbuf(opt, &side->oid, &sidebuf))
2847                 goto error_return;
2848         /*
2849          * Note: binary | is used so that both renormalizations are
2850          * performed.  Comparison can be skipped if both files are
2851          * unchanged since their sha1s have already been compared.
2852          */
2853         if (renormalize_buffer(idx, path, basebuf.buf, basebuf.len, &basebuf) |
2854             renormalize_buffer(idx, path, sidebuf.buf, sidebuf.len, &sidebuf))
2855                 ret = (basebuf.len == sidebuf.len &&
2856                        !memcmp(basebuf.buf, sidebuf.buf, basebuf.len));
2857
2858 error_return:
2859         strbuf_release(&basebuf);
2860         strbuf_release(&sidebuf);
2861         return ret;
2862 }
2863
2864 struct directory_versions {
2865         /*
2866          * versions: list of (basename -> version_info)
2867          *
2868          * The basenames are in reverse lexicographic order of full pathnames,
2869          * as processed in process_entries().  This puts all entries within
2870          * a directory together, and covers the directory itself after
2871          * everything within it, allowing us to write subtrees before needing
2872          * to record information for the tree itself.
2873          */
2874         struct string_list versions;
2875
2876         /*
2877          * offsets: list of (full relative path directories -> integer offsets)
2878          *
2879          * Since versions contains basenames from files in multiple different
2880          * directories, we need to know which entries in versions correspond
2881          * to which directories.  Values of e.g.
2882          *     ""             0
2883          *     src            2
2884          *     src/moduleA    5
2885          * Would mean that entries 0-1 of versions are files in the toplevel
2886          * directory, entries 2-4 are files under src/, and the remaining
2887          * entries starting at index 5 are files under src/moduleA/.
2888          */
2889         struct string_list offsets;
2890
2891         /*
2892          * last_directory: directory that previously processed file found in
2893          *
2894          * last_directory starts NULL, but records the directory in which the
2895          * previous file was found within.  As soon as
2896          *    directory(current_file) != last_directory
2897          * then we need to start updating accounting in versions & offsets.
2898          * Note that last_directory is always the last path in "offsets" (or
2899          * NULL if "offsets" is empty) so this exists just for quick access.
2900          */
2901         const char *last_directory;
2902
2903         /* last_directory_len: cached computation of strlen(last_directory) */
2904         unsigned last_directory_len;
2905 };
2906
2907 static int tree_entry_order(const void *a_, const void *b_)
2908 {
2909         const struct string_list_item *a = a_;
2910         const struct string_list_item *b = b_;
2911
2912         const struct merged_info *ami = a->util;
2913         const struct merged_info *bmi = b->util;
2914         return base_name_compare(a->string, strlen(a->string), ami->result.mode,
2915                                  b->string, strlen(b->string), bmi->result.mode);
2916 }
2917
2918 static void write_tree(struct object_id *result_oid,
2919                        struct string_list *versions,
2920                        unsigned int offset,
2921                        size_t hash_size)
2922 {
2923         size_t maxlen = 0, extra;
2924         unsigned int nr;
2925         struct strbuf buf = STRBUF_INIT;
2926         int i;
2927
2928         assert(offset <= versions->nr);
2929         nr = versions->nr - offset;
2930         if (versions->nr)
2931                 /* No need for STABLE_QSORT -- filenames must be unique */
2932                 QSORT(versions->items + offset, nr, tree_entry_order);
2933
2934         /* Pre-allocate some space in buf */
2935         extra = hash_size + 8; /* 8: 6 for mode, 1 for space, 1 for NUL char */
2936         for (i = 0; i < nr; i++) {
2937                 maxlen += strlen(versions->items[offset+i].string) + extra;
2938         }
2939         strbuf_grow(&buf, maxlen);
2940
2941         /* Write each entry out to buf */
2942         for (i = 0; i < nr; i++) {
2943                 struct merged_info *mi = versions->items[offset+i].util;
2944                 struct version_info *ri = &mi->result;
2945                 strbuf_addf(&buf, "%o %s%c",
2946                             ri->mode,
2947                             versions->items[offset+i].string, '\0');
2948                 strbuf_add(&buf, ri->oid.hash, hash_size);
2949         }
2950
2951         /* Write this object file out, and record in result_oid */
2952         write_object_file(buf.buf, buf.len, tree_type, result_oid);
2953         strbuf_release(&buf);
2954 }
2955
2956 static void record_entry_for_tree(struct directory_versions *dir_metadata,
2957                                   const char *path,
2958                                   struct merged_info *mi)
2959 {
2960         const char *basename;
2961
2962         if (mi->is_null)
2963                 /* nothing to record */
2964                 return;
2965
2966         basename = path + mi->basename_offset;
2967         assert(strchr(basename, '/') == NULL);
2968         string_list_append(&dir_metadata->versions,
2969                            basename)->util = &mi->result;
2970 }
2971
2972 static void write_completed_directory(struct merge_options *opt,
2973                                       const char *new_directory_name,
2974                                       struct directory_versions *info)
2975 {
2976         const char *prev_dir;
2977         struct merged_info *dir_info = NULL;
2978         unsigned int offset;
2979
2980         /*
2981          * Some explanation of info->versions and info->offsets...
2982          *
2983          * process_entries() iterates over all relevant files AND
2984          * directories in reverse lexicographic order, and calls this
2985          * function.  Thus, an example of the paths that process_entries()
2986          * could operate on (along with the directories for those paths
2987          * being shown) is:
2988          *
2989          *     xtract.c             ""
2990          *     tokens.txt           ""
2991          *     src/moduleB/umm.c    src/moduleB
2992          *     src/moduleB/stuff.h  src/moduleB
2993          *     src/moduleB/baz.c    src/moduleB
2994          *     src/moduleB          src
2995          *     src/moduleA/foo.c    src/moduleA
2996          *     src/moduleA/bar.c    src/moduleA
2997          *     src/moduleA          src
2998          *     src                  ""
2999          *     Makefile             ""
3000          *
3001          * info->versions:
3002          *
3003          *     always contains the unprocessed entries and their
3004          *     version_info information.  For example, after the first five
3005          *     entries above, info->versions would be:
3006          *
3007          *         xtract.c     <xtract.c's version_info>
3008          *         token.txt    <token.txt's version_info>
3009          *         umm.c        <src/moduleB/umm.c's version_info>
3010          *         stuff.h      <src/moduleB/stuff.h's version_info>
3011          *         baz.c        <src/moduleB/baz.c's version_info>
3012          *
3013          *     Once a subdirectory is completed we remove the entries in
3014          *     that subdirectory from info->versions, writing it as a tree
3015          *     (write_tree()).  Thus, as soon as we get to src/moduleB,
3016          *     info->versions would be updated to
3017          *
3018          *         xtract.c     <xtract.c's version_info>
3019          *         token.txt    <token.txt's version_info>
3020          *         moduleB      <src/moduleB's version_info>
3021          *
3022          * info->offsets:
3023          *
3024          *     helps us track which entries in info->versions correspond to
3025          *     which directories.  When we are N directories deep (e.g. 4
3026          *     for src/modA/submod/subdir/), we have up to N+1 unprocessed
3027          *     directories (+1 because of toplevel dir).  Corresponding to
3028          *     the info->versions example above, after processing five entries
3029          *     info->offsets will be:
3030          *
3031          *         ""           0
3032          *         src/moduleB  2
3033          *
3034          *     which is used to know that xtract.c & token.txt are from the
3035          *     toplevel dirctory, while umm.c & stuff.h & baz.c are from the
3036          *     src/moduleB directory.  Again, following the example above,
3037          *     once we need to process src/moduleB, then info->offsets is
3038          *     updated to
3039          *
3040          *         ""           0
3041          *         src          2
3042          *
3043          *     which says that moduleB (and only moduleB so far) is in the
3044          *     src directory.
3045          *
3046          *     One unique thing to note about info->offsets here is that
3047          *     "src" was not added to info->offsets until there was a path
3048          *     (a file OR directory) immediately below src/ that got
3049          *     processed.
3050          *
3051          * Since process_entry() just appends new entries to info->versions,
3052          * write_completed_directory() only needs to do work if the next path
3053          * is in a directory that is different than the last directory found
3054          * in info->offsets.
3055          */
3056
3057         /*
3058          * If we are working with the same directory as the last entry, there
3059          * is no work to do.  (See comments above the directory_name member of
3060          * struct merged_info for why we can use pointer comparison instead of
3061          * strcmp here.)
3062          */
3063         if (new_directory_name == info->last_directory)
3064                 return;
3065
3066         /*
3067          * If we are just starting (last_directory is NULL), or last_directory
3068          * is a prefix of the current directory, then we can just update
3069          * info->offsets to record the offset where we started this directory
3070          * and update last_directory to have quick access to it.
3071          */
3072         if (info->last_directory == NULL ||
3073             !strncmp(new_directory_name, info->last_directory,
3074                      info->last_directory_len)) {
3075                 uintptr_t offset = info->versions.nr;
3076
3077                 info->last_directory = new_directory_name;
3078                 info->last_directory_len = strlen(info->last_directory);
3079                 /*
3080                  * Record the offset into info->versions where we will
3081                  * start recording basenames of paths found within
3082                  * new_directory_name.
3083                  */
3084                 string_list_append(&info->offsets,
3085                                    info->last_directory)->util = (void*)offset;
3086                 return;
3087         }
3088
3089         /*
3090          * The next entry that will be processed will be within
3091          * new_directory_name.  Since at this point we know that
3092          * new_directory_name is within a different directory than
3093          * info->last_directory, we have all entries for info->last_directory
3094          * in info->versions and we need to create a tree object for them.
3095          */
3096         dir_info = strmap_get(&opt->priv->paths, info->last_directory);
3097         assert(dir_info);
3098         offset = (uintptr_t)info->offsets.items[info->offsets.nr-1].util;
3099         if (offset == info->versions.nr) {
3100                 /*
3101                  * Actually, we don't need to create a tree object in this
3102                  * case.  Whenever all files within a directory disappear
3103                  * during the merge (e.g. unmodified on one side and
3104                  * deleted on the other, or files were renamed elsewhere),
3105                  * then we get here and the directory itself needs to be
3106                  * omitted from its parent tree as well.
3107                  */
3108                 dir_info->is_null = 1;
3109         } else {
3110                 /*
3111                  * Write out the tree to the git object directory, and also
3112                  * record the mode and oid in dir_info->result.
3113                  */
3114                 dir_info->is_null = 0;
3115                 dir_info->result.mode = S_IFDIR;
3116                 write_tree(&dir_info->result.oid, &info->versions, offset,
3117                            opt->repo->hash_algo->rawsz);
3118         }
3119
3120         /*
3121          * We've now used several entries from info->versions and one entry
3122          * from info->offsets, so we get rid of those values.
3123          */
3124         info->offsets.nr--;
3125         info->versions.nr = offset;
3126
3127         /*
3128          * Now we've taken care of the completed directory, but we need to
3129          * prepare things since future entries will be in
3130          * new_directory_name.  (In particular, process_entry() will be
3131          * appending new entries to info->versions.)  So, we need to make
3132          * sure new_directory_name is the last entry in info->offsets.
3133          */
3134         prev_dir = info->offsets.nr == 0 ? NULL :
3135                    info->offsets.items[info->offsets.nr-1].string;
3136         if (new_directory_name != prev_dir) {
3137                 uintptr_t c = info->versions.nr;
3138                 string_list_append(&info->offsets,
3139                                    new_directory_name)->util = (void*)c;
3140         }
3141
3142         /* And, of course, we need to update last_directory to match. */
3143         info->last_directory = new_directory_name;
3144         info->last_directory_len = strlen(info->last_directory);
3145 }
3146
3147 /* Per entry merge function */
3148 static void process_entry(struct merge_options *opt,
3149                           const char *path,
3150                           struct conflict_info *ci,
3151                           struct directory_versions *dir_metadata)
3152 {
3153         int df_file_index = 0;
3154
3155         VERIFY_CI(ci);
3156         assert(ci->filemask >= 0 && ci->filemask <= 7);
3157         /* ci->match_mask == 7 was handled in collect_merge_info_callback() */
3158         assert(ci->match_mask == 0 || ci->match_mask == 3 ||
3159                ci->match_mask == 5 || ci->match_mask == 6);
3160
3161         if (ci->dirmask) {
3162                 record_entry_for_tree(dir_metadata, path, &ci->merged);
3163                 if (ci->filemask == 0)
3164                         /* nothing else to handle */
3165                         return;
3166                 assert(ci->df_conflict);
3167         }
3168
3169         if (ci->df_conflict && ci->merged.result.mode == 0) {
3170                 int i;
3171
3172                 /*
3173                  * directory no longer in the way, but we do have a file we
3174                  * need to place here so we need to clean away the "directory
3175                  * merges to nothing" result.
3176                  */
3177                 ci->df_conflict = 0;
3178                 assert(ci->filemask != 0);
3179                 ci->merged.clean = 0;
3180                 ci->merged.is_null = 0;
3181                 /* and we want to zero out any directory-related entries */
3182                 ci->match_mask = (ci->match_mask & ~ci->dirmask);
3183                 ci->dirmask = 0;
3184                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3185                         if (ci->filemask & (1 << i))
3186                                 continue;
3187                         ci->stages[i].mode = 0;
3188                         oidcpy(&ci->stages[i].oid, null_oid());
3189                 }
3190         } else if (ci->df_conflict && ci->merged.result.mode != 0) {
3191                 /*
3192                  * This started out as a D/F conflict, and the entries in
3193                  * the competing directory were not removed by the merge as
3194                  * evidenced by write_completed_directory() writing a value
3195                  * to ci->merged.result.mode.
3196                  */
3197                 struct conflict_info *new_ci;
3198                 const char *branch;
3199                 const char *old_path = path;
3200                 int i;
3201
3202                 assert(ci->merged.result.mode == S_IFDIR);
3203
3204                 /*
3205                  * If filemask is 1, we can just ignore the file as having
3206                  * been deleted on both sides.  We do not want to overwrite
3207                  * ci->merged.result, since it stores the tree for all the
3208                  * files under it.
3209                  */
3210                 if (ci->filemask == 1) {
3211                         ci->filemask = 0;
3212                         return;
3213                 }
3214
3215                 /*
3216                  * This file still exists on at least one side, and we want
3217                  * the directory to remain here, so we need to move this
3218                  * path to some new location.
3219                  */
3220                 CALLOC_ARRAY(new_ci, 1);
3221                 /* We don't really want new_ci->merged.result copied, but it'll
3222                  * be overwritten below so it doesn't matter.  We also don't
3223                  * want any directory mode/oid values copied, but we'll zero
3224                  * those out immediately.  We do want the rest of ci copied.
3225                  */
3226                 memcpy(new_ci, ci, sizeof(*ci));
3227                 new_ci->match_mask = (new_ci->match_mask & ~new_ci->dirmask);
3228                 new_ci->dirmask = 0;
3229                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3230                         if (new_ci->filemask & (1 << i))
3231                                 continue;
3232                         /* zero out any entries related to directories */
3233                         new_ci->stages[i].mode = 0;
3234                         oidcpy(&new_ci->stages[i].oid, null_oid());
3235                 }
3236
3237                 /*
3238                  * Find out which side this file came from; note that we
3239                  * cannot just use ci->filemask, because renames could cause
3240                  * the filemask to go back to 7.  So we use dirmask, then
3241                  * pick the opposite side's index.
3242                  */
3243                 df_file_index = (ci->dirmask & (1 << 1)) ? 2 : 1;
3244                 branch = (df_file_index == 1) ? opt->branch1 : opt->branch2;
3245                 path = unique_path(&opt->priv->paths, path, branch);
3246                 strmap_put(&opt->priv->paths, path, new_ci);
3247
3248                 path_msg(opt, path, 0,
3249                          _("CONFLICT (file/directory): directory in the way "
3250                            "of %s from %s; moving it to %s instead."),
3251                          old_path, branch, path);
3252
3253                 /*
3254                  * Zero out the filemask for the old ci.  At this point, ci
3255                  * was just an entry for a directory, so we don't need to
3256                  * do anything more with it.
3257                  */
3258                 ci->filemask = 0;
3259
3260                 /*
3261                  * Now note that we're working on the new entry (path was
3262                  * updated above.
3263                  */
3264                 ci = new_ci;
3265         }
3266
3267         /*
3268          * NOTE: Below there is a long switch-like if-elseif-elseif... block
3269          *       which the code goes through even for the df_conflict cases
3270          *       above.
3271          */
3272         if (ci->match_mask) {
3273                 ci->merged.clean = 1;
3274                 if (ci->match_mask == 6) {
3275                         /* stages[1] == stages[2] */
3276                         ci->merged.result.mode = ci->stages[1].mode;
3277                         oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
3278                 } else {
3279                         /* determine the mask of the side that didn't match */
3280                         unsigned int othermask = 7 & ~ci->match_mask;
3281                         int side = (othermask == 4) ? 2 : 1;
3282
3283                         ci->merged.result.mode = ci->stages[side].mode;
3284                         ci->merged.is_null = !ci->merged.result.mode;
3285                         oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
3286
3287                         assert(othermask == 2 || othermask == 4);
3288                         assert(ci->merged.is_null ==
3289                                (ci->filemask == ci->match_mask));
3290                 }
3291         } else if (ci->filemask >= 6 &&
3292                    (S_IFMT & ci->stages[1].mode) !=
3293                    (S_IFMT & ci->stages[2].mode)) {
3294                 /* Two different items from (file/submodule/symlink) */
3295                 if (opt->priv->call_depth) {
3296                         /* Just use the version from the merge base */
3297                         ci->merged.clean = 0;
3298                         oidcpy(&ci->merged.result.oid, &ci->stages[0].oid);
3299                         ci->merged.result.mode = ci->stages[0].mode;
3300                         ci->merged.is_null = (ci->merged.result.mode == 0);
3301                 } else {
3302                         /* Handle by renaming one or both to separate paths. */
3303                         unsigned o_mode = ci->stages[0].mode;
3304                         unsigned a_mode = ci->stages[1].mode;
3305                         unsigned b_mode = ci->stages[2].mode;
3306                         struct conflict_info *new_ci;
3307                         const char *a_path = NULL, *b_path = NULL;
3308                         int rename_a = 0, rename_b = 0;
3309
3310                         new_ci = xmalloc(sizeof(*new_ci));
3311
3312                         if (S_ISREG(a_mode))
3313                                 rename_a = 1;
3314                         else if (S_ISREG(b_mode))
3315                                 rename_b = 1;
3316                         else {
3317                                 rename_a = 1;
3318                                 rename_b = 1;
3319                         }
3320
3321                         if (rename_a && rename_b) {
3322                                 path_msg(opt, path, 0,
3323                                          _("CONFLICT (distinct types): %s had "
3324                                            "different types on each side; "
3325                                            "renamed both of them so each can "
3326                                            "be recorded somewhere."),
3327                                          path);
3328                         } else {
3329                                 path_msg(opt, path, 0,
3330                                          _("CONFLICT (distinct types): %s had "
3331                                            "different types on each side; "
3332                                            "renamed one of them so each can be "
3333                                            "recorded somewhere."),
3334                                          path);
3335                         }
3336
3337                         ci->merged.clean = 0;
3338                         memcpy(new_ci, ci, sizeof(*new_ci));
3339
3340                         /* Put b into new_ci, removing a from stages */
3341                         new_ci->merged.result.mode = ci->stages[2].mode;
3342                         oidcpy(&new_ci->merged.result.oid, &ci->stages[2].oid);
3343                         new_ci->stages[1].mode = 0;
3344                         oidcpy(&new_ci->stages[1].oid, null_oid());
3345                         new_ci->filemask = 5;
3346                         if ((S_IFMT & b_mode) != (S_IFMT & o_mode)) {
3347                                 new_ci->stages[0].mode = 0;
3348                                 oidcpy(&new_ci->stages[0].oid, null_oid());
3349                                 new_ci->filemask = 4;
3350                         }
3351
3352                         /* Leave only a in ci, fixing stages. */
3353                         ci->merged.result.mode = ci->stages[1].mode;
3354                         oidcpy(&ci->merged.result.oid, &ci->stages[1].oid);
3355                         ci->stages[2].mode = 0;
3356                         oidcpy(&ci->stages[2].oid, null_oid());
3357                         ci->filemask = 3;
3358                         if ((S_IFMT & a_mode) != (S_IFMT & o_mode)) {
3359                                 ci->stages[0].mode = 0;
3360                                 oidcpy(&ci->stages[0].oid, null_oid());
3361                                 ci->filemask = 2;
3362                         }
3363
3364                         /* Insert entries into opt->priv_paths */
3365                         assert(rename_a || rename_b);
3366                         if (rename_a) {
3367                                 a_path = unique_path(&opt->priv->paths,
3368                                                      path, opt->branch1);
3369                                 strmap_put(&opt->priv->paths, a_path, ci);
3370                         }
3371
3372                         if (rename_b)
3373                                 b_path = unique_path(&opt->priv->paths,
3374                                                      path, opt->branch2);
3375                         else
3376                                 b_path = path;
3377                         strmap_put(&opt->priv->paths, b_path, new_ci);
3378
3379                         if (rename_a && rename_b) {
3380                                 strmap_remove(&opt->priv->paths, path, 0);
3381                                 /*
3382                                  * We removed path from opt->priv->paths.  path
3383                                  * will also eventually need to be freed, but
3384                                  * it may still be used by e.g.  ci->pathnames.
3385                                  * So, store it in another string-list for now.
3386                                  */
3387                                 string_list_append(&opt->priv->paths_to_free,
3388                                                    path);
3389                         }
3390
3391                         /*
3392                          * Do special handling for b_path since process_entry()
3393                          * won't be called on it specially.
3394                          */
3395                         strmap_put(&opt->priv->conflicted, b_path, new_ci);
3396                         record_entry_for_tree(dir_metadata, b_path,
3397                                               &new_ci->merged);
3398
3399                         /*
3400                          * Remaining code for processing this entry should
3401                          * think in terms of processing a_path.
3402                          */
3403                         if (a_path)
3404                                 path = a_path;
3405                 }
3406         } else if (ci->filemask >= 6) {
3407                 /* Need a two-way or three-way content merge */
3408                 struct version_info merged_file;
3409                 unsigned clean_merge;
3410                 struct version_info *o = &ci->stages[0];
3411                 struct version_info *a = &ci->stages[1];
3412                 struct version_info *b = &ci->stages[2];
3413
3414                 clean_merge = handle_content_merge(opt, path, o, a, b,
3415                                                    ci->pathnames,
3416                                                    opt->priv->call_depth * 2,
3417                                                    &merged_file);
3418                 ci->merged.clean = clean_merge &&
3419                                    !ci->df_conflict && !ci->path_conflict;
3420                 ci->merged.result.mode = merged_file.mode;
3421                 ci->merged.is_null = (merged_file.mode == 0);
3422                 oidcpy(&ci->merged.result.oid, &merged_file.oid);
3423                 if (clean_merge && ci->df_conflict) {
3424                         assert(df_file_index == 1 || df_file_index == 2);
3425                         ci->filemask = 1 << df_file_index;
3426                         ci->stages[df_file_index].mode = merged_file.mode;
3427                         oidcpy(&ci->stages[df_file_index].oid, &merged_file.oid);
3428                 }
3429                 if (!clean_merge) {
3430                         const char *reason = _("content");
3431                         if (ci->filemask == 6)
3432                                 reason = _("add/add");
3433                         if (S_ISGITLINK(merged_file.mode))
3434                                 reason = _("submodule");
3435                         path_msg(opt, path, 0,
3436                                  _("CONFLICT (%s): Merge conflict in %s"),
3437                                  reason, path);
3438                 }
3439         } else if (ci->filemask == 3 || ci->filemask == 5) {
3440                 /* Modify/delete */
3441                 const char *modify_branch, *delete_branch;
3442                 int side = (ci->filemask == 5) ? 2 : 1;
3443                 int index = opt->priv->call_depth ? 0 : side;
3444
3445                 ci->merged.result.mode = ci->stages[index].mode;
3446                 oidcpy(&ci->merged.result.oid, &ci->stages[index].oid);
3447                 ci->merged.clean = 0;
3448
3449                 modify_branch = (side == 1) ? opt->branch1 : opt->branch2;
3450                 delete_branch = (side == 1) ? opt->branch2 : opt->branch1;
3451
3452                 if (opt->renormalize &&
3453                     blob_unchanged(opt, &ci->stages[0], &ci->stages[side],
3454                                    path)) {
3455                         ci->merged.is_null = 1;
3456                         ci->merged.clean = 1;
3457                 } else if (ci->path_conflict &&
3458                            oideq(&ci->stages[0].oid, &ci->stages[side].oid)) {
3459                         /*
3460                          * This came from a rename/delete; no action to take,
3461                          * but avoid printing "modify/delete" conflict notice
3462                          * since the contents were not modified.
3463                          */
3464                 } else {
3465                         path_msg(opt, path, 0,
3466                                  _("CONFLICT (modify/delete): %s deleted in %s "
3467                                    "and modified in %s.  Version %s of %s left "
3468                                    "in tree."),
3469                                  path, delete_branch, modify_branch,
3470                                  modify_branch, path);
3471                 }
3472         } else if (ci->filemask == 2 || ci->filemask == 4) {
3473                 /* Added on one side */
3474                 int side = (ci->filemask == 4) ? 2 : 1;
3475                 ci->merged.result.mode = ci->stages[side].mode;
3476                 oidcpy(&ci->merged.result.oid, &ci->stages[side].oid);
3477                 ci->merged.clean = !ci->df_conflict && !ci->path_conflict;
3478         } else if (ci->filemask == 1) {
3479                 /* Deleted on both sides */
3480                 ci->merged.is_null = 1;
3481                 ci->merged.result.mode = 0;
3482                 oidcpy(&ci->merged.result.oid, null_oid());
3483                 ci->merged.clean = !ci->path_conflict;
3484         }
3485
3486         /*
3487          * If still conflicted, record it separately.  This allows us to later
3488          * iterate over just conflicted entries when updating the index instead
3489          * of iterating over all entries.
3490          */
3491         if (!ci->merged.clean)
3492                 strmap_put(&opt->priv->conflicted, path, ci);
3493
3494         /* Record metadata for ci->merged in dir_metadata */
3495         record_entry_for_tree(dir_metadata, path, &ci->merged);
3496 }
3497
3498 static void prefetch_for_content_merges(struct merge_options *opt,
3499                                         struct string_list *plist)
3500 {
3501         struct string_list_item *e;
3502         struct oid_array to_fetch = OID_ARRAY_INIT;
3503
3504         if (opt->repo != the_repository || !has_promisor_remote())
3505                 return;
3506
3507         for (e = &plist->items[plist->nr-1]; e >= plist->items; --e) {
3508                 /* char *path = e->string; */
3509                 struct conflict_info *ci = e->util;
3510                 int i;
3511
3512                 /* Ignore clean entries */
3513                 if (ci->merged.clean)
3514                         continue;
3515
3516                 /* Ignore entries that don't need a content merge */
3517                 if (ci->match_mask || ci->filemask < 6 ||
3518                     !S_ISREG(ci->stages[1].mode) ||
3519                     !S_ISREG(ci->stages[2].mode) ||
3520                     oideq(&ci->stages[1].oid, &ci->stages[2].oid))
3521                         continue;
3522
3523                 /* Also don't need content merge if base matches either side */
3524                 if (ci->filemask == 7 &&
3525                     S_ISREG(ci->stages[0].mode) &&
3526                     (oideq(&ci->stages[0].oid, &ci->stages[1].oid) ||
3527                      oideq(&ci->stages[0].oid, &ci->stages[2].oid)))
3528                         continue;
3529
3530                 for (i = 0; i < 3; i++) {
3531                         unsigned side_mask = (1 << i);
3532                         struct version_info *vi = &ci->stages[i];
3533
3534                         if ((ci->filemask & side_mask) &&
3535                             S_ISREG(vi->mode) &&
3536                             oid_object_info_extended(opt->repo, &vi->oid, NULL,
3537                                                      OBJECT_INFO_FOR_PREFETCH))
3538                                 oid_array_append(&to_fetch, &vi->oid);
3539                 }
3540         }
3541
3542         promisor_remote_get_direct(opt->repo, to_fetch.oid, to_fetch.nr);
3543         oid_array_clear(&to_fetch);
3544 }
3545
3546 static void process_entries(struct merge_options *opt,
3547                             struct object_id *result_oid)
3548 {
3549         struct hashmap_iter iter;
3550         struct strmap_entry *e;
3551         struct string_list plist = STRING_LIST_INIT_NODUP;
3552         struct string_list_item *entry;
3553         struct directory_versions dir_metadata = { STRING_LIST_INIT_NODUP,
3554                                                    STRING_LIST_INIT_NODUP,
3555                                                    NULL, 0 };
3556
3557         trace2_region_enter("merge", "process_entries setup", opt->repo);
3558         if (strmap_empty(&opt->priv->paths)) {
3559                 oidcpy(result_oid, opt->repo->hash_algo->empty_tree);
3560                 return;
3561         }
3562
3563         /* Hack to pre-allocate plist to the desired size */
3564         trace2_region_enter("merge", "plist grow", opt->repo);
3565         ALLOC_GROW(plist.items, strmap_get_size(&opt->priv->paths), plist.alloc);
3566         trace2_region_leave("merge", "plist grow", opt->repo);
3567
3568         /* Put every entry from paths into plist, then sort */
3569         trace2_region_enter("merge", "plist copy", opt->repo);
3570         strmap_for_each_entry(&opt->priv->paths, &iter, e) {
3571                 string_list_append(&plist, e->key)->util = e->value;
3572         }
3573         trace2_region_leave("merge", "plist copy", opt->repo);
3574
3575         trace2_region_enter("merge", "plist special sort", opt->repo);
3576         plist.cmp = sort_dirs_next_to_their_children;
3577         string_list_sort(&plist);
3578         trace2_region_leave("merge", "plist special sort", opt->repo);
3579
3580         trace2_region_leave("merge", "process_entries setup", opt->repo);
3581
3582         /*
3583          * Iterate over the items in reverse order, so we can handle paths
3584          * below a directory before needing to handle the directory itself.
3585          *
3586          * This allows us to write subtrees before we need to write trees,
3587          * and it also enables sane handling of directory/file conflicts
3588          * (because it allows us to know whether the directory is still in
3589          * the way when it is time to process the file at the same path).
3590          */
3591         trace2_region_enter("merge", "processing", opt->repo);
3592         prefetch_for_content_merges(opt, &plist);
3593         for (entry = &plist.items[plist.nr-1]; entry >= plist.items; --entry) {
3594                 char *path = entry->string;
3595                 /*
3596                  * NOTE: mi may actually be a pointer to a conflict_info, but
3597                  * we have to check mi->clean first to see if it's safe to
3598                  * reassign to such a pointer type.
3599                  */
3600                 struct merged_info *mi = entry->util;
3601
3602                 write_completed_directory(opt, mi->directory_name,
3603                                           &dir_metadata);
3604                 if (mi->clean)
3605                         record_entry_for_tree(&dir_metadata, path, mi);
3606                 else {
3607                         struct conflict_info *ci = (struct conflict_info *)mi;
3608                         process_entry(opt, path, ci, &dir_metadata);
3609                 }
3610         }
3611         trace2_region_leave("merge", "processing", opt->repo);
3612
3613         trace2_region_enter("merge", "process_entries cleanup", opt->repo);
3614         if (dir_metadata.offsets.nr != 1 ||
3615             (uintptr_t)dir_metadata.offsets.items[0].util != 0) {
3616                 printf("dir_metadata.offsets.nr = %d (should be 1)\n",
3617                        dir_metadata.offsets.nr);
3618                 printf("dir_metadata.offsets.items[0].util = %u (should be 0)\n",
3619                        (unsigned)(uintptr_t)dir_metadata.offsets.items[0].util);
3620                 fflush(stdout);
3621                 BUG("dir_metadata accounting completely off; shouldn't happen");
3622         }
3623         write_tree(result_oid, &dir_metadata.versions, 0,
3624                    opt->repo->hash_algo->rawsz);
3625         string_list_clear(&plist, 0);
3626         string_list_clear(&dir_metadata.versions, 0);
3627         string_list_clear(&dir_metadata.offsets, 0);
3628         trace2_region_leave("merge", "process_entries cleanup", opt->repo);
3629 }
3630
3631 /*** Function Grouping: functions related to merge_switch_to_result() ***/
3632
3633 static int checkout(struct merge_options *opt,
3634                     struct tree *prev,
3635                     struct tree *next)
3636 {
3637         /* Switch the index/working copy from old to new */
3638         int ret;
3639         struct tree_desc trees[2];
3640         struct unpack_trees_options unpack_opts;
3641
3642         memset(&unpack_opts, 0, sizeof(unpack_opts));
3643         unpack_opts.head_idx = -1;
3644         unpack_opts.src_index = opt->repo->index;
3645         unpack_opts.dst_index = opt->repo->index;
3646
3647         setup_unpack_trees_porcelain(&unpack_opts, "merge");
3648
3649         /*
3650          * NOTE: if this were just "git checkout" code, we would probably
3651          * read or refresh the cache and check for a conflicted index, but
3652          * builtin/merge.c or sequencer.c really needs to read the index
3653          * and check for conflicted entries before starting merging for a
3654          * good user experience (no sense waiting for merges/rebases before
3655          * erroring out), so there's no reason to duplicate that work here.
3656          */
3657
3658         /* 2-way merge to the new branch */
3659         unpack_opts.update = 1;
3660         unpack_opts.merge = 1;
3661         unpack_opts.quiet = 0; /* FIXME: sequencer might want quiet? */
3662         unpack_opts.verbose_update = (opt->verbosity > 2);
3663         unpack_opts.fn = twoway_merge;
3664         if (1/* FIXME: opts->overwrite_ignore*/) {
3665                 CALLOC_ARRAY(unpack_opts.dir, 1);
3666                 unpack_opts.dir->flags |= DIR_SHOW_IGNORED;
3667                 setup_standard_excludes(unpack_opts.dir);
3668         }
3669         parse_tree(prev);
3670         init_tree_desc(&trees[0], prev->buffer, prev->size);
3671         parse_tree(next);
3672         init_tree_desc(&trees[1], next->buffer, next->size);
3673
3674         ret = unpack_trees(2, trees, &unpack_opts);
3675         clear_unpack_trees_porcelain(&unpack_opts);
3676         dir_clear(unpack_opts.dir);
3677         FREE_AND_NULL(unpack_opts.dir);
3678         return ret;
3679 }
3680
3681 static int record_conflicted_index_entries(struct merge_options *opt)
3682 {
3683         struct hashmap_iter iter;
3684         struct strmap_entry *e;
3685         struct index_state *index = opt->repo->index;
3686         struct checkout state = CHECKOUT_INIT;
3687         int errs = 0;
3688         int original_cache_nr;
3689
3690         if (strmap_empty(&opt->priv->conflicted))
3691                 return 0;
3692
3693         /* If any entries have skip_worktree set, we'll have to check 'em out */
3694         state.force = 1;
3695         state.quiet = 1;
3696         state.refresh_cache = 1;
3697         state.istate = index;
3698         original_cache_nr = index->cache_nr;
3699
3700         /* Put every entry from paths into plist, then sort */
3701         strmap_for_each_entry(&opt->priv->conflicted, &iter, e) {
3702                 const char *path = e->key;
3703                 struct conflict_info *ci = e->value;
3704                 int pos;
3705                 struct cache_entry *ce;
3706                 int i;
3707
3708                 VERIFY_CI(ci);
3709
3710                 /*
3711                  * The index will already have a stage=0 entry for this path,
3712                  * because we created an as-merged-as-possible version of the
3713                  * file and checkout() moved the working copy and index over
3714                  * to that version.
3715                  *
3716                  * However, previous iterations through this loop will have
3717                  * added unstaged entries to the end of the cache which
3718                  * ignore the standard alphabetical ordering of cache
3719                  * entries and break invariants needed for index_name_pos()
3720                  * to work.  However, we know the entry we want is before
3721                  * those appended cache entries, so do a temporary swap on
3722                  * cache_nr to only look through entries of interest.
3723                  */
3724                 SWAP(index->cache_nr, original_cache_nr);
3725                 pos = index_name_pos(index, path, strlen(path));
3726                 SWAP(index->cache_nr, original_cache_nr);
3727                 if (pos < 0) {
3728                         if (ci->filemask != 1)
3729                                 BUG("Conflicted %s but nothing in basic working tree or index; this shouldn't happen", path);
3730                         cache_tree_invalidate_path(index, path);
3731                 } else {
3732                         ce = index->cache[pos];
3733
3734                         /*
3735                          * Clean paths with CE_SKIP_WORKTREE set will not be
3736                          * written to the working tree by the unpack_trees()
3737                          * call in checkout().  Our conflicted entries would
3738                          * have appeared clean to that code since we ignored
3739                          * the higher order stages.  Thus, we need override
3740                          * the CE_SKIP_WORKTREE bit and manually write those
3741                          * files to the working disk here.
3742                          */
3743                         if (ce_skip_worktree(ce)) {
3744                                 struct stat st;
3745
3746                                 if (!lstat(path, &st)) {
3747                                         char *new_name = unique_path(&opt->priv->paths,
3748                                                                      path,
3749                                                                      "cruft");
3750
3751                                         path_msg(opt, path, 1,
3752                                                  _("Note: %s not up to date and in way of checking out conflicted version; old copy renamed to %s"),
3753                                                  path, new_name);
3754                                         errs |= rename(path, new_name);
3755                                         free(new_name);
3756                                 }
3757                                 errs |= checkout_entry(ce, &state, NULL, NULL);
3758                         }
3759
3760                         /*
3761                          * Mark this cache entry for removal and instead add
3762                          * new stage>0 entries corresponding to the
3763                          * conflicts.  If there are many conflicted entries, we
3764                          * want to avoid memmove'ing O(NM) entries by
3765                          * inserting the new entries one at a time.  So,
3766                          * instead, we just add the new cache entries to the
3767                          * end (ignoring normal index requirements on sort
3768                          * order) and sort the index once we're all done.
3769                          */
3770                         ce->ce_flags |= CE_REMOVE;
3771                 }
3772
3773                 for (i = MERGE_BASE; i <= MERGE_SIDE2; i++) {
3774                         struct version_info *vi;
3775                         if (!(ci->filemask & (1ul << i)))
3776                                 continue;
3777                         vi = &ci->stages[i];
3778                         ce = make_cache_entry(index, vi->mode, &vi->oid,
3779                                               path, i+1, 0);
3780                         add_index_entry(index, ce, ADD_CACHE_JUST_APPEND);
3781                 }
3782         }
3783
3784         /*
3785          * Remove the unused cache entries (and invalidate the relevant
3786          * cache-trees), then sort the index entries to get the conflicted
3787          * entries we added to the end into their right locations.
3788          */
3789         remove_marked_cache_entries(index, 1);
3790         /*
3791          * No need for STABLE_QSORT -- cmp_cache_name_compare sorts primarily
3792          * on filename and secondarily on stage, and (name, stage #) are a
3793          * unique tuple.
3794          */
3795         QSORT(index->cache, index->cache_nr, cmp_cache_name_compare);
3796
3797         return errs;
3798 }
3799
3800 void merge_switch_to_result(struct merge_options *opt,
3801                             struct tree *head,
3802                             struct merge_result *result,
3803                             int update_worktree_and_index,
3804                             int display_update_msgs)
3805 {
3806         assert(opt->priv == NULL);
3807         if (result->clean >= 0 && update_worktree_and_index) {
3808                 const char *filename;
3809                 FILE *fp;
3810
3811                 trace2_region_enter("merge", "checkout", opt->repo);
3812                 if (checkout(opt, head, result->tree)) {
3813                         /* failure to function */
3814                         result->clean = -1;
3815                         return;
3816                 }
3817                 trace2_region_leave("merge", "checkout", opt->repo);
3818
3819                 trace2_region_enter("merge", "record_conflicted", opt->repo);
3820                 opt->priv = result->priv;
3821                 if (record_conflicted_index_entries(opt)) {
3822                         /* failure to function */
3823                         opt->priv = NULL;
3824                         result->clean = -1;
3825                         return;
3826                 }
3827                 opt->priv = NULL;
3828                 trace2_region_leave("merge", "record_conflicted", opt->repo);
3829
3830                 trace2_region_enter("merge", "write_auto_merge", opt->repo);
3831                 filename = git_path_auto_merge(opt->repo);
3832                 fp = xfopen(filename, "w");
3833                 fprintf(fp, "%s\n", oid_to_hex(&result->tree->object.oid));
3834                 fclose(fp);
3835                 trace2_region_leave("merge", "write_auto_merge", opt->repo);
3836         }
3837
3838         if (display_update_msgs) {
3839                 struct merge_options_internal *opti = result->priv;
3840                 struct hashmap_iter iter;
3841                 struct strmap_entry *e;
3842                 struct string_list olist = STRING_LIST_INIT_NODUP;
3843                 int i;
3844
3845                 trace2_region_enter("merge", "display messages", opt->repo);
3846
3847                 /* Hack to pre-allocate olist to the desired size */
3848                 ALLOC_GROW(olist.items, strmap_get_size(&opti->output),
3849                            olist.alloc);
3850
3851                 /* Put every entry from output into olist, then sort */
3852                 strmap_for_each_entry(&opti->output, &iter, e) {
3853                         string_list_append(&olist, e->key)->util = e->value;
3854                 }
3855                 string_list_sort(&olist);
3856
3857                 /* Iterate over the items, printing them */
3858                 for (i = 0; i < olist.nr; ++i) {
3859                         struct strbuf *sb = olist.items[i].util;
3860
3861                         printf("%s", sb->buf);
3862                 }
3863                 string_list_clear(&olist, 0);
3864
3865                 /* Also include needed rename limit adjustment now */
3866                 diff_warn_rename_limit("merge.renamelimit",
3867                                        opti->renames.needed_limit, 0);
3868
3869                 trace2_region_leave("merge", "display messages", opt->repo);
3870         }
3871
3872         merge_finalize(opt, result);
3873 }
3874
3875 void merge_finalize(struct merge_options *opt,
3876                     struct merge_result *result)
3877 {
3878         struct merge_options_internal *opti = result->priv;
3879
3880         if (opt->renormalize)
3881                 git_attr_set_direction(GIT_ATTR_CHECKIN);
3882         assert(opt->priv == NULL);
3883
3884         clear_or_reinit_internal_opts(opti, 0);
3885         FREE_AND_NULL(opti);
3886 }
3887
3888 /*** Function Grouping: helper functions for merge_incore_*() ***/
3889
3890 static struct tree *shift_tree_object(struct repository *repo,
3891                                       struct tree *one, struct tree *two,
3892                                       const char *subtree_shift)
3893 {
3894         struct object_id shifted;
3895
3896         if (!*subtree_shift) {
3897                 shift_tree(repo, &one->object.oid, &two->object.oid, &shifted, 0);
3898         } else {
3899                 shift_tree_by(repo, &one->object.oid, &two->object.oid, &shifted,
3900                               subtree_shift);
3901         }
3902         if (oideq(&two->object.oid, &shifted))
3903                 return two;
3904         return lookup_tree(repo, &shifted);
3905 }
3906
3907 static inline void set_commit_tree(struct commit *c, struct tree *t)
3908 {
3909         c->maybe_tree = t;
3910 }
3911
3912 static struct commit *make_virtual_commit(struct repository *repo,
3913                                           struct tree *tree,
3914                                           const char *comment)
3915 {
3916         struct commit *commit = alloc_commit_node(repo);
3917
3918         set_merge_remote_desc(commit, comment, (struct object *)commit);
3919         set_commit_tree(commit, tree);
3920         commit->object.parsed = 1;
3921         return commit;
3922 }
3923
3924 static void merge_start(struct merge_options *opt, struct merge_result *result)
3925 {
3926         struct rename_info *renames;
3927         int i;
3928
3929         /* Sanity checks on opt */
3930         trace2_region_enter("merge", "sanity checks", opt->repo);
3931         assert(opt->repo);
3932
3933         assert(opt->branch1 && opt->branch2);
3934
3935         assert(opt->detect_directory_renames >= MERGE_DIRECTORY_RENAMES_NONE &&
3936                opt->detect_directory_renames <= MERGE_DIRECTORY_RENAMES_TRUE);
3937         assert(opt->rename_limit >= -1);
3938         assert(opt->rename_score >= 0 && opt->rename_score <= MAX_SCORE);
3939         assert(opt->show_rename_progress >= 0 && opt->show_rename_progress <= 1);
3940
3941         assert(opt->xdl_opts >= 0);
3942         assert(opt->recursive_variant >= MERGE_VARIANT_NORMAL &&
3943                opt->recursive_variant <= MERGE_VARIANT_THEIRS);
3944
3945         /*
3946          * detect_renames, verbosity, buffer_output, and obuf are ignored
3947          * fields that were used by "recursive" rather than "ort" -- but
3948          * sanity check them anyway.
3949          */
3950         assert(opt->detect_renames >= -1 &&
3951                opt->detect_renames <= DIFF_DETECT_COPY);
3952         assert(opt->verbosity >= 0 && opt->verbosity <= 5);
3953         assert(opt->buffer_output <= 2);
3954         assert(opt->obuf.len == 0);
3955
3956         assert(opt->priv == NULL);
3957         if (result->_properly_initialized != 0 &&
3958             result->_properly_initialized != RESULT_INITIALIZED)
3959                 BUG("struct merge_result passed to merge_incore_*recursive() must be zeroed or filled with values from a previous run");
3960         assert(!!result->priv == !!result->_properly_initialized);
3961         if (result->priv) {
3962                 opt->priv = result->priv;
3963                 result->priv = NULL;
3964                 /*
3965                  * opt->priv non-NULL means we had results from a previous
3966                  * run; do a few sanity checks that user didn't mess with
3967                  * it in an obvious fashion.
3968                  */
3969                 assert(opt->priv->call_depth == 0);
3970                 assert(!opt->priv->toplevel_dir ||
3971                        0 == strlen(opt->priv->toplevel_dir));
3972         }
3973         trace2_region_leave("merge", "sanity checks", opt->repo);
3974
3975         /* Default to histogram diff.  Actually, just hardcode it...for now. */
3976         opt->xdl_opts = DIFF_WITH_ALG(opt, HISTOGRAM_DIFF);
3977
3978         /* Handle attr direction stuff for renormalization */
3979         if (opt->renormalize)
3980                 git_attr_set_direction(GIT_ATTR_CHECKOUT);
3981
3982         /* Initialization of opt->priv, our internal merge data */
3983         trace2_region_enter("merge", "allocate/init", opt->repo);
3984         if (opt->priv) {
3985                 clear_or_reinit_internal_opts(opt->priv, 1);
3986                 trace2_region_leave("merge", "allocate/init", opt->repo);
3987                 return;
3988         }
3989         opt->priv = xcalloc(1, sizeof(*opt->priv));
3990
3991         /* Initialization of various renames fields */
3992         renames = &opt->priv->renames;
3993         for (i = MERGE_SIDE1; i <= MERGE_SIDE2; i++) {
3994                 strintmap_init_with_options(&renames->dirs_removed[i],
3995                                             NOT_RELEVANT, NULL, 0);
3996                 strmap_init_with_options(&renames->dir_rename_count[i],
3997                                          NULL, 1);
3998                 strmap_init_with_options(&renames->dir_renames[i],
3999                                          NULL, 0);
4000                 /*
4001                  * relevant_sources uses -1 for the default, because we need
4002                  * to be able to distinguish not-in-strintmap from valid
4003                  * relevant_source values from enum file_rename_relevance.
4004                  * In particular, possibly_cache_new_pair() expects a negative
4005                  * value for not-found entries.
4006                  */
4007                 strintmap_init_with_options(&renames->relevant_sources[i],
4008                                             -1 /* explicitly invalid */,
4009                                             NULL, 0);
4010                 strmap_init_with_options(&renames->cached_pairs[i],
4011                                          NULL, 1);
4012                 strset_init_with_options(&renames->cached_irrelevant[i],
4013                                          NULL, 1);
4014                 strset_init_with_options(&renames->cached_target_names[i],
4015                                          NULL, 0);
4016         }
4017
4018         /*
4019          * Although we initialize opt->priv->paths with strdup_strings=0,
4020          * that's just to avoid making yet another copy of an allocated
4021          * string.  Putting the entry into paths means we are taking
4022          * ownership, so we will later free it.  paths_to_free is similar.
4023          *
4024          * In contrast, conflicted just has a subset of keys from paths, so
4025          * we don't want to free those (it'd be a duplicate free).
4026          */
4027         strmap_init_with_options(&opt->priv->paths, NULL, 0);
4028         strmap_init_with_options(&opt->priv->conflicted, NULL, 0);
4029         string_list_init(&opt->priv->paths_to_free, 0);
4030
4031         /*
4032          * keys & strbufs in output will sometimes need to outlive "paths",
4033          * so it will have a copy of relevant keys.  It's probably a small
4034          * subset of the overall paths that have special output.
4035          */
4036         strmap_init(&opt->priv->output);
4037
4038         trace2_region_leave("merge", "allocate/init", opt->repo);
4039 }
4040
4041 static void merge_check_renames_reusable(struct merge_options *opt,
4042                                          struct merge_result *result,
4043                                          struct tree *merge_base,
4044                                          struct tree *side1,
4045                                          struct tree *side2)
4046 {
4047         struct rename_info *renames;
4048         struct tree **merge_trees;
4049         struct merge_options_internal *opti = result->priv;
4050
4051         if (!opti)
4052                 return;
4053
4054         renames = &opti->renames;
4055         merge_trees = renames->merge_trees;
4056
4057         /*
4058          * Handle case where previous merge operation did not want cache to
4059          * take effect, e.g. because rename/rename(1to1) makes it invalid.
4060          */
4061         if (!merge_trees[0]) {
4062                 assert(!merge_trees[0] && !merge_trees[1] && !merge_trees[2]);
4063                 renames->cached_pairs_valid_side = 0; /* neither side valid */
4064                 return;
4065         }
4066
4067         /*
4068          * Handle other cases; note that merge_trees[0..2] will only
4069          * be NULL if opti is, or if all three were manually set to
4070          * NULL by e.g. rename/rename(1to1) handling.
4071          */
4072         assert(merge_trees[0] && merge_trees[1] && merge_trees[2]);
4073
4074         /* Check if we meet a condition for re-using cached_pairs */
4075         if (oideq(&merge_base->object.oid, &merge_trees[2]->object.oid) &&
4076             oideq(&side1->object.oid, &result->tree->object.oid))
4077                 renames->cached_pairs_valid_side = MERGE_SIDE1;
4078         else if (oideq(&merge_base->object.oid, &merge_trees[1]->object.oid) &&
4079                  oideq(&side2->object.oid, &result->tree->object.oid))
4080                 renames->cached_pairs_valid_side = MERGE_SIDE2;
4081         else
4082                 renames->cached_pairs_valid_side = 0; /* neither side valid */
4083 }
4084
4085 /*** Function Grouping: merge_incore_*() and their internal variants ***/
4086
4087 /*
4088  * Originally from merge_trees_internal(); heavily adapted, though.
4089  */
4090 static void merge_ort_nonrecursive_internal(struct merge_options *opt,
4091                                             struct tree *merge_base,
4092                                             struct tree *side1,
4093                                             struct tree *side2,
4094                                             struct merge_result *result)
4095 {
4096         struct object_id working_tree_oid;
4097
4098         if (opt->subtree_shift) {
4099                 side2 = shift_tree_object(opt->repo, side1, side2,
4100                                           opt->subtree_shift);
4101                 merge_base = shift_tree_object(opt->repo, side1, merge_base,
4102                                                opt->subtree_shift);
4103         }
4104
4105         trace2_region_enter("merge", "collect_merge_info", opt->repo);
4106         if (collect_merge_info(opt, merge_base, side1, side2) != 0) {
4107                 /*
4108                  * TRANSLATORS: The %s arguments are: 1) tree hash of a merge
4109                  * base, and 2-3) the trees for the two trees we're merging.
4110                  */
4111                 err(opt, _("collecting merge info failed for trees %s, %s, %s"),
4112                     oid_to_hex(&merge_base->object.oid),
4113                     oid_to_hex(&side1->object.oid),
4114                     oid_to_hex(&side2->object.oid));
4115                 result->clean = -1;
4116                 return;
4117         }
4118         trace2_region_leave("merge", "collect_merge_info", opt->repo);
4119
4120         trace2_region_enter("merge", "renames", opt->repo);
4121         result->clean = detect_and_process_renames(opt, merge_base,
4122                                                    side1, side2);
4123         trace2_region_leave("merge", "renames", opt->repo);
4124
4125         trace2_region_enter("merge", "process_entries", opt->repo);
4126         process_entries(opt, &working_tree_oid);
4127         trace2_region_leave("merge", "process_entries", opt->repo);
4128
4129         /* Set return values */
4130         result->tree = parse_tree_indirect(&working_tree_oid);
4131         /* existence of conflicted entries implies unclean */
4132         result->clean &= strmap_empty(&opt->priv->conflicted);
4133         if (!opt->priv->call_depth) {
4134                 result->priv = opt->priv;
4135                 result->_properly_initialized = RESULT_INITIALIZED;
4136                 opt->priv = NULL;
4137         }
4138 }
4139
4140 /*
4141  * Originally from merge_recursive_internal(); somewhat adapted, though.
4142  */
4143 static void merge_ort_internal(struct merge_options *opt,
4144                                struct commit_list *merge_bases,
4145                                struct commit *h1,
4146                                struct commit *h2,
4147                                struct merge_result *result)
4148 {
4149         struct commit_list *iter;
4150         struct commit *merged_merge_bases;
4151         const char *ancestor_name;
4152         struct strbuf merge_base_abbrev = STRBUF_INIT;
4153
4154         if (!merge_bases) {
4155                 merge_bases = get_merge_bases(h1, h2);
4156                 /* See merge-ort.h:merge_incore_recursive() declaration NOTE */
4157                 merge_bases = reverse_commit_list(merge_bases);
4158         }
4159
4160         merged_merge_bases = pop_commit(&merge_bases);
4161         if (merged_merge_bases == NULL) {
4162                 /* if there is no common ancestor, use an empty tree */
4163                 struct tree *tree;
4164
4165                 tree = lookup_tree(opt->repo, opt->repo->hash_algo->empty_tree);
4166                 merged_merge_bases = make_virtual_commit(opt->repo, tree,
4167                                                          "ancestor");
4168                 ancestor_name = "empty tree";
4169         } else if (merge_bases) {
4170                 ancestor_name = "merged common ancestors";
4171         } else {
4172                 strbuf_add_unique_abbrev(&merge_base_abbrev,
4173                                          &merged_merge_bases->object.oid,
4174                                          DEFAULT_ABBREV);
4175                 ancestor_name = merge_base_abbrev.buf;
4176         }
4177
4178         for (iter = merge_bases; iter; iter = iter->next) {
4179                 const char *saved_b1, *saved_b2;
4180                 struct commit *prev = merged_merge_bases;
4181
4182                 opt->priv->call_depth++;
4183                 /*
4184                  * When the merge fails, the result contains files
4185                  * with conflict markers. The cleanness flag is
4186                  * ignored (unless indicating an error), it was never
4187                  * actually used, as result of merge_trees has always
4188                  * overwritten it: the committed "conflicts" were
4189                  * already resolved.
4190                  */
4191                 saved_b1 = opt->branch1;
4192                 saved_b2 = opt->branch2;
4193                 opt->branch1 = "Temporary merge branch 1";
4194                 opt->branch2 = "Temporary merge branch 2";
4195                 merge_ort_internal(opt, NULL, prev, iter->item, result);
4196                 if (result->clean < 0)
4197                         return;
4198                 opt->branch1 = saved_b1;
4199                 opt->branch2 = saved_b2;
4200                 opt->priv->call_depth--;
4201
4202                 merged_merge_bases = make_virtual_commit(opt->repo,
4203                                                          result->tree,
4204                                                          "merged tree");
4205                 commit_list_insert(prev, &merged_merge_bases->parents);
4206                 commit_list_insert(iter->item,
4207                                    &merged_merge_bases->parents->next);
4208
4209                 clear_or_reinit_internal_opts(opt->priv, 1);
4210         }
4211
4212         opt->ancestor = ancestor_name;
4213         merge_ort_nonrecursive_internal(opt,
4214                                         repo_get_commit_tree(opt->repo,
4215                                                              merged_merge_bases),
4216                                         repo_get_commit_tree(opt->repo, h1),
4217                                         repo_get_commit_tree(opt->repo, h2),
4218                                         result);
4219         strbuf_release(&merge_base_abbrev);
4220         opt->ancestor = NULL;  /* avoid accidental re-use of opt->ancestor */
4221 }
4222
4223 void merge_incore_nonrecursive(struct merge_options *opt,
4224                                struct tree *merge_base,
4225                                struct tree *side1,
4226                                struct tree *side2,
4227                                struct merge_result *result)
4228 {
4229         trace2_region_enter("merge", "incore_nonrecursive", opt->repo);
4230
4231         trace2_region_enter("merge", "merge_start", opt->repo);
4232         assert(opt->ancestor != NULL);
4233         merge_check_renames_reusable(opt, result, merge_base, side1, side2);
4234         merge_start(opt, result);
4235         /*
4236          * Record the trees used in this merge, so if there's a next merge in
4237          * a cherry-pick or rebase sequence it might be able to take advantage
4238          * of the cached_pairs in that next merge.
4239          */
4240         opt->priv->renames.merge_trees[0] = merge_base;
4241         opt->priv->renames.merge_trees[1] = side1;
4242         opt->priv->renames.merge_trees[2] = side2;
4243         trace2_region_leave("merge", "merge_start", opt->repo);
4244
4245         merge_ort_nonrecursive_internal(opt, merge_base, side1, side2, result);
4246         trace2_region_leave("merge", "incore_nonrecursive", opt->repo);
4247 }
4248
4249 void merge_incore_recursive(struct merge_options *opt,
4250                             struct commit_list *merge_bases,
4251                             struct commit *side1,
4252                             struct commit *side2,
4253                             struct merge_result *result)
4254 {
4255         trace2_region_enter("merge", "incore_recursive", opt->repo);
4256
4257         /* We set the ancestor label based on the merge_bases */
4258         assert(opt->ancestor == NULL);
4259
4260         trace2_region_enter("merge", "merge_start", opt->repo);
4261         merge_start(opt, result);
4262         trace2_region_leave("merge", "merge_start", opt->repo);
4263
4264         merge_ort_internal(opt, merge_bases, side1, side2, result);
4265         trace2_region_leave("merge", "incore_recursive", opt->repo);
4266 }