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