1
0

relocate.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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_PKG):
  164. paths = glob.glob(HOST_PKG + '*')
  165. if paths:
  166. HOST_PKG = paths[0]
  167. PYTHON_PKG = PYTHON_LIB + '/' + os.path.basename(HOST_PKG)
  168. else:
  169. raise ValueError('could not find {0:}'.format(HOST_PKG))
  170. if not os.path.exists(HOST_INC):
  171. paths = glob.glob(HOST_INC + '*')
  172. if paths:
  173. HOST_INC = paths[0]
  174. PYTHON_INC = PYTHON_INC + '/' + os.path.basename(HOST_INC)
  175. else:
  176. raise ValueError('could not find {0:}'.format(HOST_INC))
  177. # Copy the running Python's install
  178. log('CLONE', '%s from %s', PYTHON_X_Y, HOST_PREFIX)
  179. source = HOST_BIN + '/' + PYTHON_X_Y
  180. if not os.path.exists(source):
  181. raise ValueError('could not find {0:} executable'.format(PYTHON_X_Y))
  182. make_tree(PYTHON_BIN)
  183. target = PYTHON_BIN + '/' + PYTHON_X_Y
  184. copy_file(source, target, update=True)
  185. copy_tree(HOST_PKG, PYTHON_PKG)
  186. copy_tree(HOST_INC, PYTHON_INC)
  187. make_tree(APPDIR_BIN)
  188. pip_source = HOST_BIN + '/' + PIP_X_Y
  189. if not os.path.exists(pip_source):
  190. pip_source = HOST_BIN + '/' + PIP_X
  191. if os.path.exists(pip_source):
  192. with open(pip_source) as f:
  193. f.readline()
  194. body = f.read()
  195. target = PYTHON_BIN + '/' + PIP_X_Y
  196. with open(target, 'w') as f:
  197. f.write('#! /bin/sh\n')
  198. f.write(' '.join((
  199. '"exec"',
  200. '"$(dirname $(readlink -f ${0}))/../../../usr/bin/' +
  201. PYTHON_X_Y + '"',
  202. '"$0"',
  203. '"$@"\n'
  204. )))
  205. f.write(body)
  206. shutil.copymode(pip_source, target)
  207. relpath = os.path.relpath(target, APPDIR_BIN)
  208. os.symlink(relpath, APPDIR_BIN + '/' + PIP_X_Y)
  209. # Remove unrelevant files
  210. log('PRUNE', '%s packages', PYTHON_X_Y)
  211. remove_file(PYTHON_LIB + '/lib' + PYTHON_X_Y + '.a')
  212. remove_tree(PYTHON_PKG + '/test')
  213. remove_file(PYTHON_PKG + '/dist-packages')
  214. matches = glob.glob(PYTHON_PKG + '/config-*-linux-*')
  215. for path in matches:
  216. remove_tree(path)
  217. # Add a runtime patch for sys.executable, before site.main() execution
  218. log('PATCH', '%s sys.executable', PYTHON_X_Y)
  219. set_executable_patch(VERSION, PYTHON_PKG, PREFIX + '/data/_initappimage.py')
  220. # Set a hook for cleaning sys.path, after site.main() execution
  221. log('HOOK', '%s sys.path', PYTHON_X_Y)
  222. sitepkgs = PYTHON_PKG + '/site-packages'
  223. make_tree(sitepkgs)
  224. copy_file(PREFIX + '/data/sitecustomize.py', sitepkgs)
  225. # Set RPATHs and bundle external libraries
  226. log('LINK', '%s C-extensions', PYTHON_X_Y)
  227. make_tree(APPDIR_LIB)
  228. patch_binary(PYTHON_BIN + '/' + PYTHON_X_Y, APPDIR_LIB, recursive=False)
  229. for root, dirs, files in os.walk(PYTHON_PKG + '/lib-dynload'):
  230. for file_ in files:
  231. if not file_.endswith('.so'):
  232. continue
  233. patch_binary(os.path.join(root, file_), APPDIR_LIB, recursive=False)
  234. for file_ in glob.iglob(APPDIR_LIB + '/lib*.so*'):
  235. patch_binary(file_, APPDIR_LIB, recursive=True)
  236. # Copy shared data for TCl/Tk
  237. tk_version = _get_tk_version(PYTHON_PKG)
  238. if tk_version is not None:
  239. tcltkdir = APPDIR_SHARE + '/tcltk'
  240. if (not os.path.exists(tcltkdir + '/tcl' + tk_version)) or \
  241. (not os.path.exists(tcltkdir + '/tk' + tk_version)):
  242. libdir = _get_tk_libdir(tk_version)
  243. log('INSTALL', 'Tcl/Tk' + tk_version)
  244. make_tree(tcltkdir)
  245. tclpath = libdir + '/tcl' + tk_version
  246. copy_tree(tclpath, tcltkdir + '/tcl' + tk_version)
  247. tkpath = libdir + '/tk' + tk_version
  248. copy_tree(tkpath, tcltkdir + '/tk' + tk_version)
  249. # Copy any SSL certificate
  250. cert_file = os.getenv('SSL_CERT_FILE')
  251. if cert_file:
  252. # Package certificates as well for SSL
  253. # (see https://github.com/niess/python-appimage/issues/24)
  254. dirname, basename = os.path.split(cert_file)
  255. make_tree('AppDir' + dirname)
  256. copy_file(cert_file, 'AppDir' + cert_file)
  257. log('INSTALL', basename)
  258. # Bundle the python wrapper
  259. wrapper = APPDIR_BIN + '/' + PYTHON_X_Y
  260. if not os.path.exists(wrapper):
  261. log('INSTALL', '%s wrapper', PYTHON_X_Y)
  262. entrypoint_path = PREFIX + '/data/entrypoint.sh'
  263. entrypoint = load_template(entrypoint_path, python=PYTHON_X_Y)
  264. dictionary = {'entrypoint': entrypoint,
  265. 'shebang': '#! /bin/bash',
  266. 'tcltk-env': tcltk_env_string(PYTHON_PKG),
  267. 'cert-file': cert_file_env_string(cert_file)}
  268. _copy_template('python-wrapper.sh', wrapper, **dictionary)
  269. # Set or update symlinks to python
  270. pythons = glob.glob(APPDIR_BIN + '/python?.*')
  271. versions = [os.path.basename(python)[6:] for python in pythons]
  272. latest2, latest3 = '0.0', '0.0'
  273. for version in versions:
  274. if version.startswith('2') and version >= latest2:
  275. latest2 = version
  276. elif version.startswith('3') and version >= latest3:
  277. latest3 = version
  278. if latest2 == VERSION:
  279. python2 = APPDIR_BIN + '/python2'
  280. remove_file(python2)
  281. os.symlink(PYTHON_X_Y, python2)
  282. has_pip = os.path.exists(APPDIR_BIN + '/' + PIP_X_Y)
  283. if has_pip:
  284. pip2 = APPDIR_BIN + '/pip2'
  285. remove_file(pip2)
  286. os.symlink(PIP_X_Y, pip2)
  287. if latest3 == '0.0':
  288. log('SYMLINK', 'python, python2 to ' + PYTHON_X_Y)
  289. python = APPDIR_BIN + '/python'
  290. remove_file(python)
  291. os.symlink('python2', python)
  292. if has_pip:
  293. log('SYMLINK', 'pip, pip2 to ' + PIP_X_Y)
  294. pip = APPDIR_BIN + '/pip'
  295. remove_file(pip)
  296. os.symlink('pip2', pip)
  297. else:
  298. log('SYMLINK', 'python2 to ' + PYTHON_X_Y)
  299. if has_pip:
  300. log('SYMLINK', 'pip2 to ' + PIP_X_Y)
  301. elif latest3 == VERSION:
  302. log('SYMLINK', 'python, python3 to ' + PYTHON_X_Y)
  303. python3 = APPDIR_BIN + '/python3'
  304. remove_file(python3)
  305. os.symlink(PYTHON_X_Y, python3)
  306. python = APPDIR_BIN + '/python'
  307. remove_file(python)
  308. os.symlink('python3', python)
  309. if os.path.exists(APPDIR_BIN + '/' + PIP_X_Y):
  310. log('SYMLINK', 'pip, pip3 to ' + PIP_X_Y)
  311. pip3 = APPDIR_BIN + '/pip3'
  312. remove_file(pip3)
  313. os.symlink(PIP_X_Y, pip3)
  314. pip = APPDIR_BIN + '/pip'
  315. remove_file(pip)
  316. os.symlink('pip3', pip)
  317. # Bundle the entry point
  318. apprun = APPDIR + '/AppRun'
  319. if not os.path.exists(apprun):
  320. log('INSTALL', 'AppRun')
  321. relpath = os.path.relpath(wrapper, APPDIR)
  322. os.symlink(relpath, APPDIR + '/AppRun')
  323. # Bundle the desktop file
  324. desktop_name = 'python{:}.desktop'.format(FULLVERSION)
  325. desktop = os.path.join(APPDIR, desktop_name)
  326. if not os.path.exists(desktop):
  327. log('INSTALL', desktop_name)
  328. apps = 'usr/share/applications'
  329. appfile = '{:}/{:}/python{:}.desktop'.format(APPDIR, apps, FULLVERSION)
  330. if not os.path.exists(appfile):
  331. make_tree(os.path.join(APPDIR, apps))
  332. _copy_template('python.desktop', appfile, version=VERSION,
  333. fullversion=FULLVERSION)
  334. os.symlink(os.path.join(apps, desktop_name), desktop)
  335. # Bundle icons
  336. icons = 'usr/share/icons/hicolor/256x256/apps'
  337. icon = os.path.join(APPDIR, 'python.png')
  338. if not os.path.exists(icon):
  339. log('INSTALL', 'python.png')
  340. make_tree(os.path.join(APPDIR, icons))
  341. copy_file(PREFIX + '/data/python.png',
  342. os.path.join(APPDIR, icons, 'python.png'))
  343. os.symlink(os.path.join(icons, 'python.png'), icon)
  344. diricon = os.path.join(APPDIR, '.DirIcon')
  345. if not os.path.exists(diricon):
  346. os.symlink('python.png', diricon)
  347. # Bundle metadata
  348. meta_name = 'python{:}.appdata.xml'.format(FULLVERSION)
  349. meta_dir = os.path.join(APPDIR, 'usr/share/metainfo')
  350. meta_file = os.path.join(meta_dir, meta_name)
  351. if not os.path.exists(meta_file):
  352. log('INSTALL', meta_name)
  353. make_tree(meta_dir)
  354. _copy_template('python.appdata.xml', meta_file, version=VERSION,
  355. fullversion=FULLVERSION)