-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcopy_dylibs.py
executable file
·212 lines (166 loc) · 6.09 KB
/
copy_dylibs.py
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
#!/usr/bin/env python3
from __future__ import print_function
"""Copy dylibs into the build folder.
Usage: copy_dylibs.py [dylib ... dylib]
If additional dylibs are specified on the command line, they will be copied into the app bundle.
Copyright (c)2019,2021 Andy Duplain <trojanfoe@gmail.com>
"""
import sys, os, traceback, shutil, subprocess, re
# Any dependencies outside of these directories need copying and fixing
good_dirs = ["/System/", "/usr/lib/", "@rpath/"]
# Turn on for more output
debug = True
frameworks_dir = None
# Module and library install_name changes:
# {
# dylib_path : [ old_name, new_name ], ..., [old_name, new_name]
# ...
# }
install_names = {}
# List of dylibs copied
copied_dylibs = set()
def echo(message):
print(message)
sys.stdout.flush()
def echon(message):
sys.stdout.write(message)
sys.stdout.flush()
def is_file_good(file):
for dir in good_dirs:
if file.startswith(dir):
return True
return False
def copy_dylib(src):
global copied_dylibs
if src.startswith("@"):
return None
(dylib_path, dylib_filename) = os.path.split(src)
dest = os.path.join(frameworks_dir, dylib_filename)
if not os.path.exists(dest):
if debug:
echo("Copying {0} into bundle".format(src))
shutil.copyfile(src, dest)
os.chmod(dest, 0o644)
copied_dylibs.add(dest)
copy_dependencies(dest)
return dest
else:
return None
def copy_dependencies(file):
global install_names
if file.startswith("@"):
return
(file_path, file_filename) = os.path.split(file)
echo("Examining {0}".format(file_filename))
found = 0
pipe = subprocess.Popen(["otool", "-L", file], stdout=subprocess.PIPE)
while True:
line = pipe.stdout.readline().decode("utf-8")
if line == "":
break
# /opt/local/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.8)
m = re.match(r"\s*(\S+)\s*\(compatibility version .+\)$", line)
if m:
dep = m.group(1)
if not is_file_good(dep):
(dep_path, dep_filename) = os.path.split(dep)
if dep_filename != file_filename:
echo(" ...found {0}".format(dep))
found += 1
save_install_name(file, dep, "@rpath/" + dep_filename)
dest = copy_dylib(dep)
if dest is not None:
save_install_name(dest, dep, "@rpath/" + dep_filename)
def save_install_name(file, old_name, new_name):
global install_names
list = []
if file in install_names:
list = install_names[file]
list.append([old_name, new_name])
install_names[file] = list
def change_install_names():
for dylib in install_names.keys():
(dylib_path, dylib_filename) = os.path.split(dylib)
list = install_names[dylib]
for install_name in list:
old_name = install_name[0]
new_name = install_name[1]
# echo("{0}: old={1} new={2}".format(dylib, old_name, new_name))
(old_name_path, old_name_filename) = os.path.split(old_name)
if dylib_filename == old_name_filename:
cmdline = ["install_name_tool", "-id", new_name, dylib]
else:
cmdline = ["install_name_tool", "-change", old_name, new_name, dylib]
if debug:
echo("Running: " + " ".join(cmdline))
exitcode = subprocess.call(cmdline)
if exitcode != 0:
raise RuntimeError(
"Failed to change '{0}' to '{1}' in '{2}".format(
old_name, new_name, dylib
)
)
def codesign():
if os.environ["CODE_SIGNING_ALLOWED"] == "YES":
code_sign_identity = os.environ["EXPANDED_CODE_SIGN_IDENTITY"]
for dylib in copied_dylibs:
echo("Codesigning {0}".format(os.path.basename(dylib)))
cmdline = [
"/usr/bin/codesign",
"--force",
"--sign",
code_sign_identity,
dylib,
]
if debug:
echo("Running: " + " ".join(cmdline))
exitcode = subprocess.call(cmdline)
if exitcode != 0:
raise RuntimeError("Failed to codesign '{0}'".format(dylib))
def main(args):
global frameworks_dir
if not "ACTION" in os.environ or not "TARGET_BUILD_DIR" in os.environ:
print("This is an Xcode Build Phase script!")
return 1
# Only work during builds
action = os.environ["ACTION"]
if action != "build" and action != "install":
return 0
# Set-up output directories within app bundle
build_dir = os.environ["TARGET_BUILD_DIR"]
frameworks_path = os.environ["FRAMEWORKS_FOLDER_PATH"]
frameworks_dir = os.path.join(build_dir, frameworks_path)
executable_path = os.environ["EXECUTABLE_PATH"]
executable_file = os.path.join(build_dir, executable_path)
if os.path.exists(frameworks_dir):
# Process existing .dylib files in Frameworks directory first as Xcode might have copied them and they might need attention
for file in os.listdir(frameworks_dir):
if file.endswith(".dylib"):
copy_dependencies(os.path.join(frameworks_dir, file))
else:
os.makedirs(frameworks_dir)
# Copy additional dylibs
if len(args) > 1:
for arg in args[1:]:
copy_dylib(arg)
# Process main executable
copy_dependencies(executable_file)
change_install_names()
codesign()
if debug:
echo("This is what your executable looks like now:")
pipe = subprocess.Popen(
["otool", "-L", executable_file], stdout=subprocess.PIPE
)
while True:
line = pipe.stdout.readline().decode("utf-8")
if line == "":
break
echon(line)
if __name__ == "__main__":
exitcode = 99
try:
exitcode = main(sys.argv)
except Exception as e:
echo(traceback.format_exc())
sys.exit(exitcode)