1
0

relocate.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. import glob
  2. import os
  3. import re
  4. import shutil
  5. import sys
  6. from ..utils.deps import EXCLUDELIST, PATCHELF, PREFIX, ensure_excludelist, \
  7. ensure_patchelf
  8. from ..utils.fs import copy_file, copy_tree, make_tree, remove_file, remove_tree
  9. from ..utils.log import debug, log
  10. from ..utils.system import ldd, system
  11. from ..utils.template import copy_template, load_template
  12. __all__ = ["cert_file_env_string", "patch_binary", "relocate_python",
  13. "tcltk_env_string"]
  14. def _copy_template(name, destination, **kwargs):
  15. path = os.path.join(PREFIX, 'data', name)
  16. copy_template(path, destination, **kwargs)
  17. def _get_tk_version(python_pkg):
  18. tkinter = glob.glob(python_pkg + '/lib-dynload/_tkinter*.so')
  19. if tkinter:
  20. tkinter = tkinter[0]
  21. for dep in ldd(tkinter):
  22. name = os.path.basename(dep)
  23. if name.startswith('libtk'):
  24. match = re.search('libtk([0-9]+[.][0-9]+)', name)
  25. return match.group(1)
  26. else:
  27. raise RuntimeError('could not guess Tcl/Tk version')
  28. def _get_tk_libdir(version):
  29. try:
  30. library = system(('tclsh' + version,), stdin='puts [info library]')
  31. except SystemError:
  32. raise RuntimeError('could not locate Tcl/Tk' + version + ' library')
  33. return os.path.dirname(library)
  34. def tcltk_env_string(python_pkg):
  35. '''Environment for using AppImage's TCl/Tk
  36. '''
  37. tk_version = _get_tk_version(python_pkg)
  38. if tk_version:
  39. return '''
  40. # Export TCl/Tk
  41. export TCL_LIBRARY="${{APPDIR}}/usr/share/tcltk/tcl{tk_version:}"
  42. export TK_LIBRARY="${{APPDIR}}/usr/share/tcltk/tk{tk_version:}"
  43. export TKPATH="${{TK_LIBRARY}}"'''.format(
  44. tk_version=tk_version)
  45. else:
  46. return ''
  47. def cert_file_env_string(cert_file):
  48. '''Environment for using a bundled certificate
  49. '''
  50. if cert_file:
  51. return '''
  52. # Export SSL certificate
  53. export SSL_CERT_FILE="${{APPDIR}}{cert_file:}"'''.format(
  54. cert_file=cert_file)
  55. else:
  56. return ''
  57. _excluded_libs = None
  58. '''Appimage excluded libraries, i.e. assumed to be installed on the host
  59. '''
  60. def patch_binary(path, libdir, recursive=True):
  61. '''Patch the RPATH of a binary and and fetch its dependencies
  62. '''
  63. global _excluded_libs
  64. if _excluded_libs is None:
  65. ensure_excludelist()
  66. excluded = []
  67. with open(EXCLUDELIST) as f:
  68. for line in f:
  69. line = line.strip()
  70. if (not line) or line.startswith('#'):
  71. continue
  72. excluded.append(line.split(' ', 1)[0])
  73. _excluded_libs = excluded
  74. else:
  75. excluded = _excluded_libs
  76. ensure_patchelf()
  77. rpath = '\'' + system((PATCHELF, '--print-rpath', path)) + '\''
  78. relpath = os.path.relpath(libdir, os.path.dirname(path))
  79. relpath = '' if relpath == '.' else '/' + relpath
  80. expected = '\'$ORIGIN' + relpath + ':$ORIGIN/../lib\''
  81. if rpath != expected:
  82. system((PATCHELF, '--set-rpath', expected, path))
  83. deps = ldd(path)
  84. for dep in deps:
  85. name = os.path.basename(dep)
  86. if name in excluded:
  87. continue
  88. target = libdir + '/' + name
  89. if not os.path.exists(target):
  90. libname = os.path.basename(dep)
  91. copy_file(dep, target)
  92. if recursive:
  93. patch_binary(target, libdir, recursive=True)
  94. def set_executable_patch(version, pkgpath, patch):
  95. '''Set a runtime patch for sys.executable name
  96. '''
  97. # This patch needs to be executed before site.main() is called. A natural
  98. # option is to apply it directy to the site module. But, starting with
  99. # Python 3.11, the site module is frozen within Python executable. Then,
  100. # doing so would require to recompile Python. Thus, starting with 3.11 we
  101. # instead apply the patch to the encodings package. Indeed, the latter is
  102. # loaded before the site module, and it is not frozen (as for now).
  103. major, minor = [int(v) for v in version.split('.')]
  104. if (major >= 3) and (minor >= 11):
  105. path = os.path.join(pkgpath, 'encodings', '__init__.py')
  106. else:
  107. path = os.path.join(pkgpath, 'site.py')
  108. with open(path) as f:
  109. source = f.read()
  110. if '_initappimage' in source: return
  111. lines = source.split(os.linesep)
  112. if path.endswith('site.py'):
  113. # Insert the patch before the main function
  114. for i, line in enumerate(lines):
  115. if line.startswith('def main('): break
  116. else:
  117. # Append the patch at end of file
  118. i = len(lines)
  119. with open(patch) as f:
  120. patch = f.read()
  121. lines.insert(i, patch)
  122. lines.insert(i + 1, '')
  123. source = os.linesep.join(lines)
  124. with open(path, 'w') as f:
  125. f.write(source)
  126. def relocate_python(python=None, appdir=None):
  127. '''Bundle a Python install inside an AppDir
  128. '''
  129. if python is not None:
  130. if not os.path.exists(python):
  131. raise ValueError('could not access ' + python)
  132. if appdir is None:
  133. appdir = 'AppDir'
  134. # Set some key variables & paths
  135. if python:
  136. FULLVERSION = system((python, '-c',
  137. '"import sys; print(\'{:}.{:}.{:}\'.format(*sys.version_info[:3]))"'))
  138. FULLVERSION = FULLVERSION.strip()
  139. else:
  140. FULLVERSION = '{:}.{:}.{:}'.format(*sys.version_info[:3])
  141. VERSION = '.'.join(FULLVERSION.split('.')[:2])
  142. PYTHON_X_Y = 'python' + VERSION
  143. PIP_X_Y = 'pip' + VERSION
  144. PIP_X = 'pip' + VERSION[0]
  145. APPDIR = os.path.abspath(appdir)
  146. APPDIR_BIN = APPDIR + '/usr/bin'
  147. APPDIR_LIB = APPDIR + '/usr/lib'
  148. APPDIR_SHARE = APPDIR + '/usr/share'
  149. if python:
  150. HOST_PREFIX = system((
  151. python, '-c', '"import sys; print(sys.prefix)"')).strip()
  152. else:
  153. HOST_PREFIX = sys.prefix
  154. HOST_BIN = HOST_PREFIX + '/bin'
  155. HOST_INC = HOST_PREFIX + '/include/' + PYTHON_X_Y
  156. HOST_LIB = HOST_PREFIX + '/lib'
  157. HOST_PKG = HOST_LIB + '/' + PYTHON_X_Y
  158. PYTHON_PREFIX = APPDIR + '/opt/' + PYTHON_X_Y
  159. PYTHON_BIN = PYTHON_PREFIX + '/bin'
  160. PYTHON_INC = PYTHON_PREFIX + '/include/' + PYTHON_X_Y
  161. PYTHON_LIB = PYTHON_PREFIX + '/lib'
  162. PYTHON_PKG = PYTHON_LIB + '/' + PYTHON_X_Y
  163. if not os.path.exists(HOST_INC):
  164. HOST_INC += 'm'
  165. PYTHON_INC += 'm'
  166. # Copy the running Python's install
  167. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  168. source = HOST_BIN + '/' + PYTHON_X_Y
  169. if not os.path.exists(source):
  170. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  171. make_tree(PYTHON_BIN)
  172. target = PYTHON_BIN + '/' + PYTHON_X_Y
  173. copy_file(source, target, update=True)
  174. copy_tree(HOST_PKG, PYTHON_PKG)
  175. copy_tree(HOST_INC, PYTHON_INC)
  176. make_tree(APPDIR_BIN)
  177. pip_source = HOST_BIN + '/' + PIP_X_Y
  178. if not os.path.exists(pip_source):
  179. pip_source = HOST_BIN + '/' + PIP_X
  180. if os.path.exists(pip_source):
  181. with open(pip_source) as f:
  182. f.readline()
  183. body = f.read()
  184. target = PYTHON_BIN + '/' + PIP_X_Y
  185. with open(target, 'w') as f:
  186. f.write('#! /bin/sh\n')
  187. f.write(' '.join((
  188. '"exec"',
  189. '"$(dirname $(readlink -f ${0}))/../../../usr/bin/' +
  190. PYTHON_X_Y + '"',
  191. '"$0"',
  192. '"$@"\n'
  193. )))
  194. f.write(body)
  195. shutil.copymode(pip_source, target)
  196. relpath = os.path.relpath(target, APPDIR_BIN)
  197. os.symlink(relpath, APPDIR_BIN + '/' + PIP_X_Y)
  198. # Remove unrelevant files
  199. log('PRUNE', '%s packages', PYTHON_X_Y)
  200. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  201. remove_tree(PYTHON_PKG + '/test')
  202. remove_file(PYTHON_PKG + '/dist-packages')
  203. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  204. for path in matches:
  205. remove_tree(path)
  206. # Add a runtime patch for sys.executable, before site.main() execution
  207. log('PATCH', '%s sys.executable', PYTHON_X_Y)
  208. set_executable_patch(VERSION, PYTHON_PKG, PREFIX + '/data/_initappimage.py')
  209. # Set a hook for cleaning sys.path, after site.main() execution
  210. log('HOOK', '%s sys.path', PYTHON_X_Y)
  211. sitepkgs = PYTHON_PKG + '/site-packages'
  212. make_tree(sitepkgs)
  213. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  214. # Set RPATHs and bundle external libraries
  215. log('LINK', '%s C-extensions', PYTHON_X_Y)
  216. make_tree(APPDIR_LIB)
  217. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  218. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  219. for file_ in files:
  220. if not file_.endswith('.so'):
  221. continue
  222. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  223. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  224. patch_binary(file_, APPDIR_LIB, recursive=True)
  225. # Copy shared data for TCl/Tk
  226. tk_version = _get_tk_version(PYTHON_PKG)
  227. if tk_version is not None:
  228. tcltkdir = APPDIR_SHARE + '/tcltk'
  229. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  230. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  231. libdir = _get_tk_libdir(tk_version)
  232. log('INSTALL', 'Tcl/Tk' + tk_version)
  233. make_tree(tcltkdir)
  234. tclpath = libdir + '/tcl' + tk_version
  235. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  236. tkpath = libdir + '/tk' + tk_version
  237. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  238. # Copy any SSL certificate
  239. cert_file = os.getenv('SSL_CERT_FILE')
  240. if cert_file:
  241. # Package certificates as well for SSL
  242. # (see https://github.com/niess/python-appimage/issues/24)
  243. dirname, basename = os.path.split(cert_file)
  244. make_tree('AppDir' + dirname)
  245. copy_file(cert_file, 'AppDir' + cert_file)
  246. log('INSTALL', basename)
  247. # Bundle the python wrapper
  248. wrapper = APPDIR_BIN + '/' + PYTHON_X_Y
  249. if not os.path.exists(wrapper):
  250. log('INSTALL', '%s wrapper', PYTHON_X_Y)
  251. entrypoint_path = PREFIX + '/data/entrypoint.sh'
  252. entrypoint = load_template(entrypoint_path, python=PYTHON_X_Y)
  253. dictionary = {'entrypoint': entrypoint,
  254. 'shebang': '#! /bin/bash',
  255. 'tcltk-env': tcltk_env_string(PYTHON_PKG),
  256. 'cert-file': cert_file_env_string(cert_file)}
  257. _copy_template('python-wrapper.sh', wrapper, **dictionary)
  258. # Set or update symlinks to python
  259. pythons = glob.glob(APPDIR_BIN + '/python?.*')
  260. versions = [os.path.basename(python)[6:] for python in pythons]
  261. latest2, latest3 = '0.0', '0.0'
  262. for version in versions:
  263. if version.startswith('2') and version >= latest2:
  264. latest2 = version
  265. elif version.startswith('3') and version >= latest3:
  266. latest3 = version
  267. if latest2 == VERSION:
  268. python2 = APPDIR_BIN + '/python2'
  269. remove_file(python2)
  270. os.symlink(PYTHON_X_Y, python2)
  271. has_pip = os.path.exists(APPDIR_BIN + '/' + PIP_X_Y)
  272. if has_pip:
  273. pip2 = APPDIR_BIN + '/pip2'
  274. remove_file(pip2)
  275. os.symlink(PIP_X_Y, pip2)
  276. if latest3 == '0.0':
  277. log('SYMLINK', 'python, python2 to ' + PYTHON_X_Y)
  278. python = APPDIR_BIN + '/python'
  279. remove_file(python)
  280. os.symlink('python2', python)
  281. if has_pip:
  282. log('SYMLINK', 'pip, pip2 to ' + PIP_X_Y)
  283. pip = APPDIR_BIN + '/pip'
  284. remove_file(pip)
  285. os.symlink('pip2', pip)
  286. else:
  287. log('SYMLINK', 'python2 to ' + PYTHON_X_Y)
  288. if has_pip:
  289. log('SYMLINK', 'pip2 to ' + PIP_X_Y)
  290. elif latest3 == VERSION:
  291. log('SYMLINK', 'python, python3 to ' + PYTHON_X_Y)
  292. python3 = APPDIR_BIN + '/python3'
  293. remove_file(python3)
  294. os.symlink(PYTHON_X_Y, python3)
  295. python = APPDIR_BIN + '/python'
  296. remove_file(python)
  297. os.symlink('python3', python)
  298. if os.path.exists(APPDIR_BIN + '/' + PIP_X_Y):
  299. log('SYMLINK', 'pip, pip3 to ' + PIP_X_Y)
  300. pip3 = APPDIR_BIN + '/pip3'
  301. remove_file(pip3)
  302. os.symlink(PIP_X_Y, pip3)
  303. pip = APPDIR_BIN + '/pip'
  304. remove_file(pip)
  305. os.symlink('pip3', pip)
  306. # Bundle the entry point
  307. apprun = APPDIR + '/AppRun'
  308. if not os.path.exists(apprun):
  309. log('INSTALL', 'AppRun')
  310. relpath = os.path.relpath(wrapper, APPDIR)
  311. os.symlink(relpath, APPDIR + '/AppRun')
  312. # Bundle the desktop file
  313. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  314. desktop = os.path.join(APPDIR, desktop_name)
  315. if not os.path.exists(desktop):
  316. log('INSTALL', desktop_name)
  317. apps = 'usr/share/applications'
  318. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  319. if not os.path.exists(appfile):
  320. make_tree(os.path.join(APPDIR, apps))
  321. _copy_template('python.desktop', appfile, version=VERSION,
  322. fullversion=FULLVERSION)
  323. os.symlink(os.path.join(apps, desktop_name), desktop)
  324. # Bundle icons
  325. icons = 'usr/share/icons/hicolor/256x256/apps'
  326. icon = os.path.join(APPDIR, 'python.png')
  327. if not os.path.exists(icon):
  328. log('INSTALL', 'python.png')
  329. make_tree(os.path.join(APPDIR, icons))
  330. copy_file(PREFIX + '/data/python.png',
  331. os.path.join(APPDIR, icons, 'python.png'))
  332. os.symlink(os.path.join(icons, 'python.png'), icon)
  333. diricon = os.path.join(APPDIR, '.DirIcon')
  334. if not os.path.exists(diricon):
  335. os.symlink('python.png', diricon)
  336. # Bundle metadata
  337. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  338. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  339. meta_file = os.path.join(meta_dir, meta_name)
  340. if not os.path.exists(meta_file):
  341. log('INSTALL', meta_name)
  342. make_tree(meta_dir)
  343. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  344. fullversion=FULLVERSION)