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