Debian Codegraph @

bindings/python/setup.py

raw symbols SCIP
1 #!/usr/bin/env python3
2
3 import glob
4 import os
5 import shutil
6 import sys
7 import platform
8
9 import logging
10 from setuptools import setup
11 from sysconfig import get_platform
12 from setuptools.command.build import build
13 from setuptools.command.sdist import sdist
14 from setuptools.command.bdist_egg import bdist_egg
15
16 logger = logging.getLogger(__name__)
17 logging.basicConfig(level=logging.INFO)
18
19 SYSTEM = sys.platform
20
21 # adapted from commit e504b81 of Nguyen Tan Cong
22 # Reference: https://docs.python.org/2/library/platform.html#cross-platform
23 IS_64BITS = sys.maxsize > 2**32
24
25 # are we building from the repository or from a source distribution?
26 ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
27 LIBS_DIR = os.path.join(ROOT_DIR, 'capstone', 'lib')
28 HEADERS_DIR = os.path.join(ROOT_DIR, 'capstone', 'include')
29 SRC_DIR = os.path.join(ROOT_DIR, 'src')
30 BUILD_DIR = SRC_DIR if os.path.exists(SRC_DIR) else os.path.join(ROOT_DIR, '../..')
31
32 # Parse version from pkgconfig.mk
33 VERSION_DATA = {}
34 with open(os.path.join(BUILD_DIR, 'pkgconfig.mk')) as fp:
35 lines = fp.readlines()
36 for line in lines:
37 line = line.strip()
38 if len(line) == 0:
39 continue
40 if line.startswith('#'):
41 continue
42 if '=' not in line:
43 continue
44
45 k, v = line.split('=', 1)
46 k = k.strip()
47 v = v.strip()
48 if len(k) == 0 or len(v) == 0:
49 continue
50 VERSION_DATA[k] = v
51
52 if 'PKG_MAJOR' not in VERSION_DATA or \
53 'PKG_MINOR' not in VERSION_DATA or \
54 'PKG_EXTRA' not in VERSION_DATA:
55 raise Exception("Malformed pkgconfig.mk")
56
57 if 'PKG_TAG' in VERSION_DATA:
58 VERSION = '{PKG_MAJOR}.{PKG_MINOR}.{PKG_EXTRA}{PKG_TAG}'.format(**VERSION_DATA)
59 else:
60 VERSION = '{PKG_MAJOR}.{PKG_MINOR}.{PKG_EXTRA}'.format(**VERSION_DATA)
61
62 if SYSTEM == 'darwin':
63 VERSIONED_LIBRARY_FILE = "libcapstone.{PKG_MAJOR}.dylib".format(**VERSION_DATA)
64 LIBRARY_FILE = "libcapstone.dylib"
65 elif SYSTEM in ('win32', 'cygwin'):
66 VERSIONED_LIBRARY_FILE = "capstone.dll"
67 LIBRARY_FILE = "capstone.dll"
68 else:
69 VERSIONED_LIBRARY_FILE = "libcapstone.so.{PKG_MAJOR}".format(**VERSION_DATA)
70 LIBRARY_FILE = "libcapstone.so"
71
72 def clean_bins():
73 shutil.rmtree(LIBS_DIR, ignore_errors=True)
74 shutil.rmtree(HEADERS_DIR, ignore_errors=True)
75
76 def copy_sources():
77 """Copy the C sources into the source directory.
78 This rearranges the source files under the python distribution
79 directory.
80 """
81 src = []
82
83 try:
84 shutil.rmtree("src/")
85 except (IOError, OSError):
86 pass
87
88 shutil.copytree(os.path.join(BUILD_DIR, "arch"), os.path.join(SRC_DIR, "arch"))
89 shutil.copytree(os.path.join(BUILD_DIR, "include"), os.path.join(SRC_DIR, "include"))
90
91 src.extend(glob.glob(os.path.join(BUILD_DIR, "*.[ch]")))
92 src.extend(glob.glob(os.path.join(BUILD_DIR, "*.in")))
93 src.extend(glob.glob(os.path.join(BUILD_DIR, "*.mk")))
94
95 src.extend(glob.glob(os.path.join(BUILD_DIR, "Makefile")))
96 src.extend(glob.glob(os.path.join(BUILD_DIR, "LICENSE*")))
97 src.extend(glob.glob(os.path.join(BUILD_DIR, "README")))
98 src.extend(glob.glob(os.path.join(BUILD_DIR, "*.TXT")))
99 src.extend(glob.glob(os.path.join(BUILD_DIR, "RELEASE_NOTES")))
100 src.extend(glob.glob(os.path.join(BUILD_DIR, "make.sh")))
101 src.extend(glob.glob(os.path.join(BUILD_DIR, "CMakeLists.txt")))
102 src.extend(glob.glob(os.path.join(BUILD_DIR, "pkgconfig.mk")))
103 src.extend(glob.glob(os.path.join(BUILD_DIR, "CPackConfig.txt")))
104 src.extend(glob.glob(os.path.join(BUILD_DIR, "CPackConfig.cmake")))
105
106 for filename in src:
107 outpath = os.path.join(SRC_DIR, os.path.basename(filename))
108 logger.info("%s -> %s" % (filename, outpath))
109 shutil.copy(filename, outpath)
110
111 def build_libraries():
112 """
113 Prepare the capstone directory for a binary distribution or installation.
114 Builds shared libraries and copies header files.
115
116 Will use a src/ dir if one exists in the current directory, otherwise assumes it's in the repo
117 """
118 cwd = os.getcwd()
119 clean_bins()
120 os.mkdir(HEADERS_DIR)
121 os.mkdir(LIBS_DIR)
122
123 # copy public headers
124 shutil.copytree(os.path.join(BUILD_DIR, 'include', 'capstone'), os.path.join(HEADERS_DIR, 'capstone'))
125
126 # if prebuilt libraries are available, use those and cancel build
127 if os.path.exists(os.path.join(ROOT_DIR, 'prebuilt', LIBRARY_FILE)):
128 logger.info('Using prebuilt libraries')
129 shutil.copy(os.path.join(ROOT_DIR, 'prebuilt', LIBRARY_FILE), LIBS_DIR)
130 return
131
132 os.chdir(BUILD_DIR)
133
134 # platform description refers at https://docs.python.org/3/library/sys.html#sys.platform
135 # Use cmake for both Darwin and Windows since it can generate fat binaries
136 if SYSTEM == "win32" or SYSTEM == 'darwin':
137 # Windows build: this process requires few things:
138 # - CMake + MSVC installed
139 # - Run this command in an environment setup for MSVC
140 if not os.path.exists("build"):
141 os.mkdir("build")
142 os.chdir("build")
143 print("Build Directory: {}\n".format(os.getcwd()))
144 # Only build capstone.dll / libcapstone.dylib
145 if SYSTEM in ('win32', 'cygwin'):
146 os.system('cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=OFF -DCAPSTONE_BUILD_TESTS=OFF -DCAPSTONE_BUILD_CSTOOL=OFF -G "NMake Makefiles" ..')
147 else:
148 os.system('cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_SHARED_LIBS=ON -DCAPSTONE_BUILD_TESTS=OFF -DCAPSTONE_BUILD_CSTOOL=OFF -G "Unix Makefiles" ..')
149 os.system("cmake --build .")
150 else: # Unix incl. cygwin
151 os.system("CAPSTONE_BUILD_CORE_ONLY=yes bash ./make.sh")
152
153 shutil.copy(VERSIONED_LIBRARY_FILE, os.path.join(LIBS_DIR, LIBRARY_FILE))
154 os.chdir(cwd)
155
156
157 class custom_sdist(sdist):
158 def run(self):
159 clean_bins()
160 copy_sources()
161 return sdist.run(self)
162
163
164 class custom_build(build):
165 def run(self):
166 if 'LIBCAPSTONE_PATH' in os.environ:
167 logger.info('Skipping building C extensions since LIBCAPSTONE_PATH is set')
168 else:
169 logger.info('Building C extensions')
170 build_libraries()
171 return build.run(self)
172
173
174 class custom_bdist_egg(bdist_egg):
175 def run(self):
176 self.run_command('build')
177 return bdist_egg.run(self)
178
179 def dummy_src():
180 return []
181
182 cmdclass = {}
183 cmdclass['build'] = custom_build
184 cmdclass['sdist'] = custom_sdist
185 cmdclass['bdist_egg'] = custom_bdist_egg
186
187 try:
188 from setuptools.command.develop import develop
189 class custom_develop(develop):
190 def run(self):
191 logger.info("Building C extensions")
192 build_libraries()
193 return develop.run(self)
194
195 cmdclass['develop'] = custom_develop
196 except ImportError:
197 print("Proper 'develop' support unavailable.")
198
199 if 'bdist_wheel' in sys.argv and '--plat-name' not in sys.argv:
200 # Inject the platform identifier into argv.
201 # Platform tags are described here:
202 # https://packaging.python.org/en/latest/specifications/platform-compatibility-tags
203 #
204 # I couldn't really find out in time why we need to inject the platform here?
205 # The cibuildwheel doesn't need it for the Windows job. But for Mac and Linux.
206 # This here is very dirty and will maybe break in the future.
207 # Sorry if this is the case and you read this.
208 # See: https://github.com/capstone-engine/capstone/issues/2445
209 idx = sys.argv.index('bdist_wheel') + 1
210 sys.argv.insert(idx, '--plat-name')
211 name = get_platform()
212 sys.argv.insert(idx + 1, name.replace('.', '_').replace('-', '_'))
213
214 setup(
215 provides=['capstone'],
216 packages=['capstone'],
217 name='capstone',
218 version=VERSION,
219 author='Nguyen Anh Quynh',
220 author_email='[email protected]',
221 description='Capstone disassembly engine',
222 url='https://www.capstone-engine.org',
223 long_description=open('README.txt', encoding="utf8").read(),
224 long_description_content_type='text/markdown',
225 python_requires='>=3.8',
226 classifiers=[
227 'License :: OSI Approved :: BSD License',
228 'Programming Language :: Python :: 3',
229 ],
230 cmdclass=cmdclass,
231 zip_safe=False,
232 include_package_data=True,
233 package_data={
234 "capstone": ["lib/*", "include/capstone/*"],
235 },
236 install_requires=[
237 "importlib_resources;python_version<'3.9'",
238 ],
239 )