borenet@google.com | efb1d77 | 2012-10-10 19:45:51 +0000 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 3 | # Use of this source code is governed by a BSD-style license that can be |
| 4 | # found in the LICENSE file. |
| 5 | |
| 6 | import os |
| 7 | import shutil |
| 8 | import subprocess |
| 9 | import sys |
| 10 | import tempfile |
| 11 | |
| 12 | def _Usage(): |
| 13 | print 'Usage: merge_static_libs OUTPUT_LIB INPUT_LIB [INPUT_LIB]*' |
| 14 | sys.exit(1) |
| 15 | |
| 16 | def MergeLibs(in_libs, out_lib): |
| 17 | """ Merges multiple static libraries into one. |
| 18 | |
| 19 | in_libs: list of paths to static libraries to be merged |
| 20 | out_lib: path to the static library which will be created from in_libs |
| 21 | """ |
| 22 | if os.name == 'posix': |
| 23 | tempdir = tempfile.mkdtemp() |
| 24 | abs_in_libs = [] |
| 25 | for in_lib in in_libs: |
| 26 | abs_in_libs.append(os.path.abspath(in_lib)) |
| 27 | curdir = os.getcwd() |
| 28 | os.chdir(tempdir) |
| 29 | objects = [] |
| 30 | ar = os.environ.get('AR', 'ar') |
| 31 | for in_lib in abs_in_libs: |
| 32 | proc = subprocess.Popen([ar, '-t', in_lib], stdout=subprocess.PIPE) |
| 33 | proc.wait() |
| 34 | obj_str = proc.communicate()[0] |
| 35 | current_objects = obj_str.rstrip().split('\n') |
| 36 | proc = subprocess.Popen([ar, '-x', in_lib], stdout=subprocess.PIPE, |
| 37 | stderr=subprocess.STDOUT) |
| 38 | proc.wait() |
| 39 | if proc.poll() == 0: |
| 40 | # The static library is non-thin, and we extracted objects |
| 41 | for object in current_objects: |
| 42 | objects.append(os.path.abspath(object)) |
| 43 | elif 'thin archive' in proc.communicate()[0]: |
| 44 | # The static library is thin, so it contains the paths to its objects |
| 45 | for object in current_objects: |
| 46 | objects.append(object) |
| 47 | else: |
| 48 | raise Exception('Failed to extract objects from %s.' % in_lib) |
| 49 | os.chdir(curdir) |
| 50 | if not subprocess.call([ar, '-crs', out_lib] + objects) == 0: |
| 51 | raise Exception('Failed to add object files to %s' % out_lib) |
| 52 | shutil.rmtree(tempdir) |
| 53 | elif os.name == 'nt': |
| 54 | subprocess.call(['lib', '/OUT:%s' % out_lib] + in_libs) |
| 55 | else: |
| 56 | raise Exception('Error: Your platform is not supported') |
| 57 | |
| 58 | def Main(): |
| 59 | if len(sys.argv) < 3: |
| 60 | _Usage() |
| 61 | out_lib = sys.argv[1] |
| 62 | in_libs = sys.argv[2:] |
| 63 | MergeLibs(in_libs, out_lib) |
| 64 | |
| 65 | if '__main__' == __name__: |
| 66 | sys.exit(Main()) |