File: compose-libs.py

package info (click to toggle)
roc-toolkit 0.4.0%2Bdfsg-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 9,684 kB
  • sloc: cpp: 102,987; ansic: 8,959; python: 6,125; sh: 942; makefile: 16; javascript: 9
file content (198 lines) | stat: -rw-r--r-- 6,000 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
from __future__ import print_function

import argparse
import glob
import os.path
import shutil
import subprocess
import sys
import tempfile

try:
    from shlex import quote
except:
    from pipes import quote

VERBOSE = False

def path_dirname(path):
    return os.path.dirname(path)

def path_basename(path):
    return os.path.splitext(os.path.basename(path))[0]

def is_gnu_tool(tool):
    try:
        out = subprocess.check_output([tool, '-V'], stderr=subprocess.STDOUT)
        try:
            out = out.decode()
        except:
            pass
        try:
            out = str(out)
        except:
            pass
        return 'GNU' in out
    except:
        return False

def execute_command(cmd):
    if VERBOSE:
        print(cmd, file=sys.stderr)
    proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    out = proc.stdout.read().decode()
    code = proc.wait()
    if code != 0:
        print(cmd, file=sys.stderr)
        print(out, file=sys.stderr)
        print("command exited with code {}".format(code))
        exit(1)

parser = argparse.ArgumentParser(description='compose multiple static libs into one')

parser.add_argument('--out', dest='output', type=str, required=True,
                    help='output library')

parser.add_argument('--in', dest='inputs', type=str, nargs='+', required=True,
                    help='input libraries')

parser.add_argument('--arch', dest='arch', type=str, nargs='*',
                    help='binary achitecture(s)')

parser.add_argument('--tools', dest='tools', type=str, nargs='*',
                    help='paths to tools')

parser.add_argument('--verbose', dest='verbose', action='store_true',
                    help='enable verbose output')

args = parser.parse_args()

VERBOSE = args.verbose

dst_lib = os.path.abspath(args.output)
src_libs = [os.path.abspath(arg) for arg in args.inputs]

archs = args.arch or [None]
is_fat = len(archs) > 1

tools = dict()
for e in args.tools:
    k, v = e.split('=', 1)
    tools[k] = v

for exe in ['ar', 'objcopy', 'lipo']:
    if not tools.get(exe.upper(), None):
        tools[exe.upper()] = exe

have_gnu_objcopy = is_gnu_tool(tools['OBJCOPY'])

try:
    temp_dir = tempfile.mkdtemp()
    os.chdir(temp_dir)

    # remove output lib(s)
    for path in glob.glob(dst_lib+'*'):
        os.remove(path)

    for arch in archs:
        dst_arch_lib = '{}/{}.{}.a'.format(
            path_dirname(dst_lib),
            path_basename(dst_lib),
            arch)

        for path in glob.glob(dst_arch_lib+'*'):
            os.remove(path)

    for src_lib in src_libs:
        for arch in archs:
            basename = path_basename(src_lib)

            # unpack object files for given arch from input lib
            if is_fat:
                arch_lib = '{}.{}.a'.format(basename, arch)

                execute_command(
                    '{lipo} -extract_family {arch} -output {arch_lib} {src_lib}'.format(
                        lipo=quote(tools['LIPO']),
                        arch=quote(arch),
                        arch_lib=quote(arch_lib),
                        src_lib=quote(src_lib)))

                execute_command(
                    '{ar} x {arch_lib}'.format(
                        ar=quote(tools['AR']),
                        arch_lib=quote(arch_lib)))

                os.remove(arch_lib)
            else:
                execute_command(
                    '{ar} x {src_lib}'.format(
                        ar=quote(tools['AR']),
                        src_lib=quote(src_lib)))

            for obj in list(glob.glob('*.o')):
                new_obj = '{}-{}'.format(basename, obj)

                # transform object file
                if have_gnu_objcopy:
                    execute_command(
                        '{objcopy} --localize-hidden --strip-unneeded {obj} {new_obj}'.format(
                            objcopy=quote(tools['OBJCOPY']),
                            obj=quote(obj),
                            new_obj=quote(new_obj)))
                    os.remove(obj)
                else:
                    os.rename(obj, new_obj)

                # add object file to resulting static lib for given arch
                if is_fat:
                    dst_arch_lib = '{}/{}.{}.a'.format(
                        path_dirname(dst_lib),
                        path_basename(dst_lib),
                        arch)

                    # quick mode (disable checks, disable symbol index)
                    execute_command(
                        '{ar} qS {dst_arch_lib} {new_obj}'.format(
                            ar=quote(tools['AR']),
                            dst_arch_lib=quote(dst_arch_lib),
                            new_obj=quote(new_obj)))
                else:
                    execute_command(
                        '{ar} r {dst_lib} {new_obj}'.format(
                            ar=quote(tools['AR']),
                            dst_lib=quote(dst_lib),
                            new_obj=quote(new_obj)))

                os.remove(new_obj)

    # compose per-arch static libs into one
    if is_fat:
        dst_arch_libs = [
            '{}/{}.{}.a'.format(
                    path_dirname(dst_lib),
                    path_basename(dst_lib),
                    arch)
            for arch in archs]

        # build symbol index
        for dst_arch_lib in dst_arch_libs:
            execute_command(
                '{ar} s {dst_arch_lib}'.format(
                    ar=quote(tools['AR']),
                    dst_arch_lib=quote(dst_arch_lib)))

        execute_command(
              '{lipo} -create -output {dst_lib} {dst_arch_libs}'.format(
                  lipo=quote(tools['LIPO']),
                  dst_lib=quote(dst_lib),
                  dst_arch_libs=' '.join(map(quote, dst_arch_libs))))

except:
    if os.path.isfile(dst_lib):
        os.remove(dst_lib)
    raise

finally:
    if os.path.isdir(temp_dir):
        shutil.rmtree(temp_dir)