File: MachOStandalone.py

package info (click to toggle)
python-macholib 1.16.3%2Bds-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 520 kB
  • sloc: python: 4,284; makefile: 131; sh: 10
file content (181 lines) | stat: -rw-r--r-- 6,207 bytes parent folder | download | duplicates (2)
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
import os
from collections import deque

from macholib.dyld import framework_info
from macholib.MachOGraph import MachOGraph, MissingMachO
from macholib.util import (
    flipwritable,
    has_filename_filter,
    in_system_path,
    iter_platform_files,
    mergecopy,
    mergetree,
)


class ExcludedMachO(MissingMachO):
    pass


class FilteredMachOGraph(MachOGraph):
    def __init__(self, delegate, *args, **kwargs):
        super(FilteredMachOGraph, self).__init__(*args, **kwargs)
        self.delegate = delegate

    def createNode(self, cls, name):
        cls = self.delegate.getClass(name, cls)
        res = super(FilteredMachOGraph, self).createNode(cls, name)
        return self.delegate.update_node(res)

    def locate(self, filename, loader=None):
        newname = super(FilteredMachOGraph, self).locate(filename, loader)
        if newname is None:
            return None
        return self.delegate.locate(newname, loader=loader)


class MachOStandalone(object):
    def __init__(self, base, dest=None, graph=None, env=None, executable_path=None):
        self.base = os.path.join(os.path.abspath(base), "")
        if dest is None:
            dest = os.path.join(self.base, "Contents", "Frameworks")
        self.dest = dest
        self.mm = FilteredMachOGraph(
            self, graph=graph, env=env, executable_path=executable_path
        )
        self.changemap = {}
        self.excludes = []
        self.pending = deque()

    def update_node(self, m):
        return m

    def getClass(self, name, cls):
        if in_system_path(name):
            return ExcludedMachO
        for base in self.excludes:
            if name.startswith(base):
                return ExcludedMachO
        return cls

    def locate(self, filename, loader=None):
        if in_system_path(filename):
            return filename
        if filename.startswith(self.base):
            return filename
        for base in self.excludes:
            if filename.startswith(base):
                return filename
        if filename in self.changemap:
            return self.changemap[filename]
        info = framework_info(filename)
        if info is None:
            res = self.copy_dylib(filename)
            self.changemap[filename] = res
            return res
        else:
            res = self.copy_framework(info)
            self.changemap[filename] = res
            return res

    def copy_dylib(self, filename):
        # When the filename is a symlink use the basename of the target of
        # the link as the name in standalone bundle. This avoids problems
        # when two libraries link to the same dylib but using different
        # symlinks.
        if os.path.islink(filename):
            dest = os.path.join(self.dest, os.path.basename(os.path.realpath(filename)))
        else:
            dest = os.path.join(self.dest, os.path.basename(filename))

        if not os.path.exists(dest):
            self.mergecopy(filename, dest)
        return dest

    def mergecopy(self, src, dest):
        return mergecopy(src, dest)

    def mergetree(self, src, dest):
        return mergetree(src, dest)

    def copy_framework(self, info):
        dest = os.path.join(self.dest, info["shortname"] + ".framework")
        destfn = os.path.join(self.dest, info["name"])
        src = os.path.join(info["location"], info["shortname"] + ".framework")
        if not os.path.exists(dest):
            self.mergetree(src, dest)
            self.pending.append((destfn, iter_platform_files(dest)))
        return destfn

    def run(self, platfiles=None, contents=None):
        mm = self.mm
        if contents is None:
            contents = "@executable_path/.."
        if platfiles is None:
            platfiles = iter_platform_files(self.base)

        for fn in platfiles:
            mm.run_file(fn)

        while self.pending:
            fmwk, files = self.pending.popleft()
            ref = mm.findNode(fmwk)
            for fn in files:
                mm.run_file(fn, caller=ref)

        changemap = {}
        skipcontents = os.path.join(os.path.dirname(self.dest), "")
        machfiles = []

        for node in mm.flatten(has_filename_filter):
            machfiles.append(node)
            dest = os.path.join(
                contents,
                os.path.normpath(node.filename[len(skipcontents) :]),  # noqa: E203
            )
            changemap[node.filename] = dest

        def changefunc(path):
            print("changefunc: ", path)
            if path.startswith("@loader_path/"):
                # This is a quick hack for py2app: In that
                # usecase paths like this are found in the load
                # commands of relocatable wheels. Those don't
                # need rewriting.
                return path

            elif path.startswith("@rpath/"):
                # Another hack for py2app: In most cases an
                # @rpath path doesn't require updates.
                return path

            res = mm.locate(path)
            rv = changemap.get(res)
            if rv is None and path.startswith("@loader_path/"):
                rv = changemap.get(mm.locate(mm.trans_table.get((node.filename, path))))
            if rv is None and path.startswith("@rpath/"):
                rv = changemap.get(mm.locate(mm.trans_table.get((node.filename, path))))
            return rv

        for node in machfiles:
            fn = mm.locate(node.filename)
            if fn is None:
                continue
            rewroteAny = False
            for _header in node.headers:
                if node.rewriteLoadCommands(changefunc):
                    rewroteAny = True
            if rewroteAny:
                old_mode = flipwritable(fn)
                try:
                    with open(fn, "rb+") as f:
                        for _header in node.headers:
                            f.seek(0)
                            node.write(f)
                        f.seek(0, 2)
                        f.flush()
                finally:
                    flipwritable(fn, old_mode)

        allfiles = [mm.locate(node.filename) for node in machfiles]
        return set(filter(None, allfiles))