[libcxx] Use libtool when merging archives on Apple platforms

ar doesn't produce the correct results when used for linking static
archives on Apple platforms, so instead use libtool -static which is
the official way to build static archives on those platforms.

Differential Revision: https://reviews.llvm.org/D62770

llvm-svn: 362311
Cr-Mirrored-From: sso://chromium.googlesource.com/_direct/external/github.com/llvm/llvm-project
Cr-Mirrored-Commit: 737de4d363ede4b90dd5609af0494fb39af53865
diff --git a/utils/merge_archives.py b/utils/merge_archives.py
index 75d7a54..5c04bc9 100755
--- a/utils/merge_archives.py
+++ b/utils/merge_archives.py
@@ -98,6 +98,12 @@
         help='The ar executable to use, finds \'ar\' in the path if not given',
         type=str, action='store')
     parser.add_argument(
+        '--use-libtool', dest='use_libtool', action='store_true', default=False)
+    parser.add_argument(
+        '--libtool', dest='libtool_exe', required=False,
+        help='The libtool executable to use, finds \'libtool\' in the path if not given',
+        type=str, action='store')
+    parser.add_argument(
         'archives', metavar='archives',  nargs='+',
         help='The archives to merge')
 
@@ -109,6 +115,13 @@
     if not ar_exe:
         print_and_exit("failed to find 'ar' executable")
 
+    if args.use_libtool:
+        libtool_exe = args.libtool_exe
+        if not libtool_exe:
+            libtool_exe = distutils.spawn.find_executable('libtool')
+        if not libtool_exe:
+            print_and_exit("failed to find 'libtool' executable")
+
     if len(args.archives) < 2:
         print_and_exit('fewer than 2 inputs provided')
     archives = [find_and_diagnose_missing(ar, args.search_paths)
@@ -127,8 +140,13 @@
         out = execute_command_verbose([ar_exe, 't', arc])
         files.extend(out.splitlines())
 
-    execute_command_verbose([ar_exe, 'rcs', args.output] + files,
-                            cwd=temp_directory_root, verbose=args.verbose)
+    if args.use_libtool:
+        files = [f for f in files if not f.startswith('__.SYMDEF')]
+        execute_command_verbose([libtool_exe, '-static', '-o', args.output] + files,
+                                cwd=temp_directory_root, verbose=args.verbose)
+    else:
+        execute_command_verbose([ar_exe, 'rcs', args.output] + files,
+                                cwd=temp_directory_root, verbose=args.verbose)
 
 
 if __name__ == '__main__':