Created
November 8, 2014 23:12
-
-
Save thegedge/7887529e5b5570d718e6 to your computer and use it in GitHub Desktop.
Fix broken shared library links in binaries/dylibs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ----------------------------------------------------------------------------- | |
# Copyright (C) 2014 Jason Gedge | |
# | |
# Permission is hereby granted, free of charge, to any person obtaining a copy | |
# of this software and associated documentation files (the "Software"), to deal | |
# in the Software without restriction, including without limitation the rights | |
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | |
# copies of the Software, and to permit persons to whom the Software is | |
# furnished to do so, subject to the following conditions: | |
# | |
# The above copyright notice and this permission notice shall be included in | |
# all copies or substantial portions of the Software. | |
# | |
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | |
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | |
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | |
# SOFTWARE. | |
# ----------------------------------------------------------------------------- | |
"""Fix broken shared library links in binaries. | |
Makes use of otool and install_name_tool to apply changes. Additional search | |
paths can be given, but by default this utility looks in the following paths | |
for possible link replacements: | |
- /usr/lib | |
- /usr/local/lib | |
- /usr/local/opt/lib | |
- /usr/local/Cellar/**/lib (if Homebrew installed) | |
Note that this script is only useful if the ABI of the old and new links are | |
the same. Chances are though, if you run this script you already have a broken | |
library so changing the broken links may not affect you. | |
""" | |
import argparse | |
import os | |
import subprocess | |
# Get the library name for a given path | |
libname = lambda path: os.path.basename(path).partition('.')[0] | |
def execute(*args): | |
"""Execute a command and return the output. | |
Args: | |
*args: arguments to pass to the command | |
Returns: | |
The output as a string, or None if the command failed. | |
""" | |
try: | |
return subprocess.check_output(args) | |
except subprocess.CalledProcessError: | |
return None | |
def collect_dynamic_libs(*search_paths): | |
"""Collects a list of dynamic libraries. | |
Args: | |
*search_paths: String, paths to search in | |
Returns: | |
Dictionary, mapping library names to their respective paths. | |
""" | |
dylibs = {} | |
for search_path in search_paths: | |
output = execute('find', search_path, '-name', '*.dylib') | |
if output: | |
for filename in output.split(): | |
if filename.endswith('.dylib'): | |
dylibs[libname(filename)] = filename | |
return dylibs | |
def get_links(paths): | |
"""Get shared library links using otool. | |
Args: | |
paths: Iterable (strings), paths to get links for | |
Returns: | |
Dictionary, mapping the path to the list of links it has | |
""" | |
links = {} | |
output = execute('otool', '-L', *paths) | |
if output: | |
output_iter = iter(output.split('\n')) | |
try: | |
current_path = None | |
while True: | |
line = next(output_iter) | |
if line: | |
if line[0].isspace(): | |
if current_path is None: | |
continue # you makin' me a sad | |
link = line.strip().partition(' ')[0] | |
links.setdefault(current_path, []).append(link) | |
else: | |
# Trim the colon at the end | |
current_path = line.strip()[:-1] | |
except StopIteration: | |
pass | |
return links | |
def fix_links(paths, search_paths=None): | |
"""Fix broken shared library links in a file. | |
Args: | |
paths: Iterable (strings), paths to files to attempt to fix | |
search_paths: Iterable (strings, optional), optional set of search | |
paths to use when looking for replacement paths | |
""" | |
search_paths = list(search_paths or []) | |
search_paths.extend(( | |
'/usr/lib', | |
'/usr/local/lib', | |
'/usr/local/opt/lib', | |
'/usr/local/Cellar', | |
)) | |
# Collect dynamic library locations | |
search_paths = set(filter(os.path.exists, search_paths)) | |
dylibs = collect_dynamic_libs(*search_paths) | |
# install_name_tool doesn't play nice with symbolic links, so resolve them | |
paths = set(map(os.path.realpath, paths)) | |
# Find shared library links in binaries | |
path_links = get_links(filter(os.path.exists, paths)) | |
# See if any of them are broken, and fix them if so | |
for path, links in path_links.iteritems(): | |
changes = [] | |
for link in filter(lambda s: s.startswith('/'), links): | |
if not os.path.exists(link): | |
link_libname = libname(link) | |
new_link = dylibs.get(link_libname) | |
changes.append((link, new_link)) | |
if changes: | |
print 'Fixing broken links in', path | |
for old_link, new_link in changes: | |
if new_link: | |
print ' ', old_link, '-->', new_link | |
execute('install_name_tool', '-change', old_link, new_link, | |
path) | |
else: | |
print ' ', 'No lib found for', old_link | |
if __name__ == '__main__': | |
desc, epilog = __doc__.split('\n', 1) | |
parser = argparse.ArgumentParser( | |
description=desc, epilog=epilog, | |
formatter_class=argparse.RawDescriptionHelpFormatter) | |
parser.add_argument( | |
'paths', nargs='+', | |
help='paths to binaries with broken shared library links') | |
parser.add_argument( | |
'--search_paths', action='append', | |
help='additional search paths when looking for replacement libs') | |
# TODO: option to specify a library name and specific version to change | |
# to use when changing links | |
args = parser.parse_args() | |
fix_links(args.paths, search_paths=args.search_paths) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment