#!/usr/bin/env python3
# Nvidia driver builder for Porteus
# Author: Blaze
import os, sys, subprocess, re, tempfile, shutil, signal, time, fnmatch, stat
import urllib.request, threading, hashlib
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GLib
NVIDIA_BASE_64 = 'https://download.nvidia.com/XFree86/Linux-x86_64'
NVIDIA_US_BASE_64 = 'https://us.download.nvidia.com/XFree86/Linux-x86_64'
NVIDIA_BASE_32 = 'https://download.nvidia.com/XFree86/Linux-x86'
NVIDIA_US_BASE_32 = 'https://us.download.nvidia.com/XFree86/Linux-x86'
IMGS = '/mnt/live/memory/images'
PKGDIR = '/var/lib/pkgtools/packages'
ICON_NAMES = ('nvidia', 'video-display', 'preferences-desktop-display', 'computer')
VER_RE = r'\d+(?:\.\d+)+'
LOG = '/var/log/nvidia-installer.log'
# Live-system paths the installer may write outside the given prefixes.
# Covers both old (/etc/...) and new (/usr/share/..., /lib/firmware/...) layouts.
LIVE_DIRS = ('/etc/vulkan', '/etc/vulkansc', '/etc/OpenCL',
'/usr/share/nvidia', '/usr/share/vulkan', '/usr/share/vulkansc',
'/lib/firmware/nvidia')
LIVE_ETC_FILES = ('/etc/X11/xorg.conf.d/nvidia-drm-outputclass.conf',
'/etc/modprobe.d/nvidia-installer-disable-nouveau.conf')
SNAP_MAX = 1048576 # do not buffer large files (GSP firmware) in RAM
T = {
'en': {
'title': 'Nvidia driver builder for Porteus',
'desc': 'Select a file or download a version.\nThe file will be converted to a Porteus module.',
'file:': 'Select file:', 'dl': 'Download latest version', 'browse': 'Browse',
'cancel': 'Cancel', 'ok': 'OK', 'close': 'Close', '_cancel': '_Cancel', '_open': '_Open',
'no_opt': 'Select file or download!', 'no_file': 'File not found',
'all': 'All files', 'f_run': 'Nvidia files (*.run)',
'no_ver': 'Could not determine version from filename.\nRename file to include version, e.g.:\n NVIDIA-Linux-x86_64-550.120.run',
'bad_ver': 'Invalid driver version.', 'no_link': 'Could not get link',
'downloading': 'Downloading', 'building': 'Building', 'preparing': 'Preparing environment...',
'mkmod': 'Creating XZM module...', 'ready': 'Module ready:', 'fail': 'Build failed',
'mv_act': 'Move and activate', 'open_dir': 'Open folder',
'moved': 'moved to', 'act_ok': 'successfully activated', 'act_ng': 'activation failed',
'mv_fail': 'Move error', 'act_fail': 'Activation failed',
'action': 'Choose action:', 'more': 'You can build more or close.',
'no_moddir': 'Modules folder not found', 'low_space': 'Low space in',
'need': 'Need', 'free': 'Free', 'root': 'Root required!', 'x11': 'X session required!',
'sel_ver': 'Select version', 'version': 'Version',
'installed': 'Installed Nvidia version', 'na': 'n/a',
'dl_fail': 'Download failed', 'show_all': 'Show all versions',
'no_src': 'Kernel sources not found.\nPlease get and activate module:\n 06-crippled_sources-*.xzm\n(available on Porteus server or USB)',
'no_tools': 'Build tools not found (gcc/make).\nPlease get and activate module:\n 05-devel-*.xzm\n(available on Porteus server or USB)',
'no_multilib_libs': '32-bit runtime libraries not found.\nPlease activate module:\n 0050-multilib-*.xzm\n(multilib-lite is enough: 32-bit libraries only)\nor uncheck the 32-bit libs option.',
'stage_fail': 'Staging build failed. The live system was not modified.',
'extracting': 'Extracting installer...', 'compiling': 'Compiling kernel modules...',
'staging': 'Staging files...',
'reboot_host': 'Recommended: reboot or run /etc/rc.d/init.d/rc.nvidia to load Nvidia modules.',
'multilib': 'Include 32-bit libraries (for Wine/multilib)',
'multilib_tooltip': 'Requires 32-bit runtime libraries (multilib-lite is enough; no 32-bit compiler needed)',
'cancelled': 'Build cancelled.', 'no_ko': 'Kernel module (nvidia.ko) not found after build.',
'hash': 'SHA256', 'ram_low': 'RAM check',
'missing_deps_title': 'Missing build dependencies',
'missing_deps': 'Missing build dependencies:\n{}\n\nActivate them and try again, or continue at your own risk (build will likely fail).',
'continue_anyway': 'Continue anyway',
'abort': 'Abort',
'no_dir2xzm': 'Module packing tool dir2xzm not found.',
'no_compat32': '32-bit compatibility libraries not found after build.\nUse a standard .run package (not the -no-compat32 variant).',
'log_saved': 'Full installer log saved to {}',
'mod_in_use': 'Old Nvidia module is still active (in use by the running session).\nReboot and try again.',
'old_renamed': 'Old driver modules renamed to *.xzm.bak',
'src_mismatch': 'Kernel sources version ({}) does not match the running kernel ({}).\nActivate the matching 06-crippled_sources-*.xzm module.',
'dl_trunc': 'Downloaded file is truncated (size mismatch)',
},
'ru': {
'title': 'Сборка драйвера Nvidia для Porteus',
'desc': 'Выберите файл или загрузите версию.\nФайл будет преобразован в модуль Porteus.',
'file:': 'Выберите файл:', 'dl': 'Загрузить последнюю версию', 'browse': 'Указать файл',
'cancel': 'Отмена', 'ok': 'ОК', 'close': 'Закрыть', '_cancel': '_Отмена', '_open': '_Открыть',
'no_opt': 'Выберите файл или загрузку!', 'no_file': 'Файл не найден',
'all': 'Все файлы', 'f_run': 'Файлы Nvidia (*.run)',
'no_ver': 'Не удалось определить версию из имени файла.\nПереименуйте файл, включив версию, например:\n NVIDIA-Linux-x86_64-550.120.run',
'bad_ver': 'Некорректная версия драйвера.', 'no_link': 'Не удалось получить ссылку',
'downloading': 'Загрузка', 'building': 'Сборка', 'preparing': 'Подготовка окружения...',
'mkmod': 'Создание модуля XZM...', 'ready': 'Модуль готов:', 'fail': 'Сборка не удалась',
'mv_act': 'Переместить и активировать', 'open_dir': 'Открыть папку',
'moved': 'перемещён в', 'act_ok': 'успешно активирован', 'act_ng': 'активация не удалась',
'mv_fail': 'Ошибка перемещения', 'act_fail': 'Ошибка активации',
'action': 'Выберите действие:', 'more': 'Можно собрать ещё или закрыть.',
'no_moddir': 'Папка модулей не найдена', 'low_space': 'Мало места в',
'need': 'Нужно', 'free': 'Свободно', 'root': 'Нужен root!', 'x11': 'Нужна X-сессия!',
'sel_ver': 'Выбор версии', 'version': 'Версия',
'installed': 'Установленная версия Nvidia', 'na': 'н/д',
'dl_fail': 'Ошибка загрузки', 'show_all': 'Показывать все версии',
'no_src': 'Исходники ядра не найдены.\nПолучите и активируйте модуль:\n 06-crippled_sources-*.xzm\n(доступен на сервере Porteus или USB)',
'no_tools': 'Инструменты сборки не найдены (gcc/make).\nПолучите и активируйте модуль:\n 05-devel-*.xzm\n(доступен на сервере Porteus или USB)',
'no_multilib_libs': '32-битные runtime-библиотеки не найдены.\nАктивируйте модуль:\n 0050-multilib-*.xzm\n(multilib-lite достаточен: только 32-битные библиотеки)\nили отключите опцию 32-битных библиотек.',
'stage_fail': 'Изолированная сборка не удалась. Живая система не была изменена.',
'extracting': 'Извлечение установщика...', 'compiling': 'Компиляция модулей ядра...',
'staging': 'Подготовка файлов...',
'reboot_host': 'Рекомендуется перезагрузка или запуск /etc/rc.d/init.d/rc.nvidia.',
'multilib': '32-битные библиотеки (для Wine/multilib)',
'multilib_tooltip': 'Требуются 32-битные runtime-библиотеки (достаточно multilib-lite; 32-битный компилятор не нужен)',
'cancelled': 'Сборка отменена.', 'no_ko': 'Модуль ядра (nvidia.ko) не найден после сборки.',
'hash': 'SHA256', 'ram_low': 'Проверка памяти',
'missing_deps_title': 'Отсутствуют зависимости для сборки',
'missing_deps': 'Отсутствуют зависимости для сборки:\n{}\n\nАктивируйте их и попробуйте снова, или продолжите на свой страх и риск (сборка, скорее всего, завершится ошибкой).',
'continue_anyway': 'Всё равно продолжить',
'abort': 'Прервать',
'no_dir2xzm': 'Не найден инструмент упаковки модулей dir2xzm.',
'no_compat32': '32-битные библиотеки не найдены после сборки.\nИспользуйте стандартный .run-пакет (не вариант -no-compat32).',
'log_saved': 'Полный лог установщика сохранён в {}',
'mod_in_use': 'Старый модуль Nvidia всё ещё активен (занят текущей сессией).\nПерезагрузитесь и попробуйте снова.',
'old_renamed': 'Старые модули драйвера переименованы в *.xzm.bak',
'src_mismatch': 'Версия исходников ядра ({}) не совпадает с запущенным ядром ({}).\nАктивируйте подходящий модуль 06-crippled_sources-*.xzm.',
'dl_trunc': 'Загруженный файл повреждён (не совпадает размер)',
}
}
def _(k): return T.get(os.environ.get('LANG', 'en')[:2], T['en']).get(k, k)
class BuildError(Exception): pass
class Cancelled(Exception): pass
_RUN = set()
def safe_rm(p):
try: os.remove(p)
except Exception: pass
def _kill_tree(p):
try: os.killpg(os.getpgid(p.pid), signal.SIGKILL)
except Exception:
try: p.kill()
except Exception: pass
def cmd(c, t=60, env=None, cancel=None):
"""subprocess.run with timeout and cooperative cancellation (process group kill)."""
try:
p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, errors='replace', env=env,
stdin=subprocess.DEVNULL, start_new_session=True)
except Exception as e:
return subprocess.CompletedProcess(c, 1, '', str(e))
_RUN.add(p)
deadline = time.time() + t
try:
while True:
try:
out, err = p.communicate(timeout=1)
return subprocess.CompletedProcess(c, p.returncode, out, err)
except subprocess.TimeoutExpired:
if cancel is not None and cancel():
_kill_tree(p)
try: out, err = p.communicate(timeout=5)
except subprocess.TimeoutExpired: out, err = '', 'Cancelled (hard kill timeout)'
return subprocess.CompletedProcess(c, 130, out, err or 'Cancelled')
if time.time() >= deadline:
_kill_tree(p)
try: out, err = p.communicate(timeout=5)
except subprocess.TimeoutExpired: out, err = '', f'Timeout after {t}s (hard kill timeout)'
return subprocess.CompletedProcess(c, 124, out, err or f'Timeout after {t}s')
finally:
_RUN.discard(p)
def private_dir(name):
"""Root-only 0700 working dir under /tmp. Refuses pre-created dirs owned by
other users, group/other-accessible dirs and symlinks (anti-poisoning)."""
p = os.path.join('/tmp', name)
try:
os.makedirs(p, mode=0o700, exist_ok=True)
st = os.lstat(p)
if stat.S_ISDIR(st.st_mode) and st.st_uid == 0 and not (st.st_mode & 0o077):
return p
except Exception:
pass
return tempfile.mkdtemp(prefix=name + '-')
def space_ok(p, mb=1500):
try:
s = os.statvfs(p)
free = s.f_bavail * s.f_frsize // 1048576
except Exception:
return False, 0
return free >= mb, free
def tmp_is_tmpfs(p='/tmp'):
try:
with open('/proc/mounts') as f:
for line in f:
parts = line.split()
if len(parts) >= 3 and parts[1] == p:
return parts[2] == 'tmpfs'
except Exception:
pass
return False
def mem_available_mb():
try:
with open('/proc/meminfo') as f:
for line in f:
if line.startswith('MemAvailable:'):
return int(line.split()[1]) // 1024
except Exception:
pass
return 0
def snapshot_live():
"""Snapshot of live-system paths the installer may touch outside staging.
Small files are buffered; large ones (firmware) get an existence marker only."""
snap, dirs = {}, set()
def remember(p):
try:
if os.path.getsize(p) <= SNAP_MAX:
with open(p, 'rb') as f: snap[p] = f.read()
else:
snap[p] = None
except Exception:
pass
for base in LIVE_DIRS:
if not os.path.isdir(base): continue
for dp, dn, fn in os.walk(base):
dirs.add(dp)
for f in fn: remember(os.path.join(dp, f))
for p in LIVE_ETC_FILES + (LOG,):
if os.path.isfile(p): remember(p)
return snap, dirs
def collect_and_revert(snap, snap_dirs, bd):
"""Stow NEW files from live dirs into staging (they end up in the module),
restore modified/deleted pre-existing files, clean up the log.
Idempotent: called before packaging and again in finally."""
def stow(p):
rel = os.path.relpath(p, '/')
dst = os.path.join(bd, rel)
try:
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copy2(p, dst)
os.remove(p)
except Exception:
pass
def revert(fp):
try:
if snap.get(fp) is None: return
with open(fp, 'rb') as rf: cur = rf.read()
if cur != snap[fp]:
with open(fp, 'wb') as wf: wf.write(snap[fp])
except Exception:
pass
for p in LIVE_DIRS:
if not os.path.isdir(p): continue
for dp, dn, fn in os.walk(p):
for f in fn:
fp = os.path.join(dp, f)
if fp not in snap: stow(fp)
else: revert(fp)
for p in LIVE_ETC_FILES:
if not os.path.isfile(p): continue
if p not in snap: stow(p)
else: revert(p)
# restore pre-existing files the installer deleted
for p, content in snap.items():
if content is None or os.path.exists(p): continue
try:
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, 'wb') as wf: wf.write(content)
except Exception:
pass
# remove empty dirs that did not exist before the build
for p in LIVE_DIRS:
if not os.path.isdir(p): continue
for dp, dn, fn in os.walk(p, topdown=False):
if not dn and not fn and dp not in snap_dirs:
try: os.rmdir(dp)
except Exception: pass
# log: remove if new, revert if pre-existing and modified
try:
if os.path.isfile(LOG):
if LOG not in snap: os.remove(LOG)
else: revert(LOG)
except Exception:
pass
def log_tail(n=3000, path=LOG):
try:
with open(path, 'r', errors='replace') as f:
return f.read()[-n:]
except Exception:
return ''
def installer_supported_options(inst):
"""Ask the installer itself which options it supports (--advanced-options
prints common options too), so unknown options are filtered out before the
first run. Old installers (e.g. 470.x) lack several flags used by newer ones."""
try:
r = cmd([inst, '--advanced-options'], t=60)
if r.returncode != 0:
return None
text = (r.stdout or '') + (r.stderr or '')
opts = set(re.findall(r'(? len(best):
best = mp
opts = parts[3]
return opts
except Exception:
return ''
def is_noexec(path):
return 'noexec' in mount_options(path).split(',')
def ensure_installer(fp, td):
"""Make the installer executable; copy it to tmp if the source is noexec."""
try: os.chmod(fp, 0o755)
except Exception: pass
if os.access(fp, os.X_OK) and not is_noexec(fp):
return fp
dst = os.path.join(td, 'installer.run')
try:
shutil.copy2(fp, dst)
os.chmod(dst, 0o755)
if os.access(dst, os.X_OK) and not is_noexec(dst):
return dst
except Exception:
pass
return fp
def nvidia_version_lists(arch='x86_64'):
latest, all_vs = [], []
base = NVIDIA_BASE_64 if arch == 'x86_64' else NVIDIA_BASE_32
for attempt in range(2):
try:
html = urllib.request.urlopen(f'{base}/', timeout=30).read().decode()
vs = [v for v in set(re.findall(r'href=["\']?(?:[^"\'>]*/)?(\d+(?:\.\d+)+)/["\']?', html, re.IGNORECASE)) if clean_ver(v)]
all_vs = sorted(vs, key=lambda v: [int(x) for x in v.split('.')], reverse=True)
if all_vs: latest = [all_vs[0]]
break
except Exception:
if attempt == 0: time.sleep(2)
if not latest:
try:
txt = urllib.request.urlopen(f'{base}/latest.txt', timeout=20).read().decode()
m = re.search(VER_RE, txt)
if m: latest = [clean_ver(m.group(0))]
except Exception:
pass
return latest, all_vs
def nvidia_urls(v, is64):
if is64:
fn = f'NVIDIA-Linux-x86_64-{v}.run'
return [f'{NVIDIA_US_BASE_64}/{v}/{fn}', f'{NVIDIA_BASE_64}/{v}/{fn}']
fn = f'NVIDIA-Linux-x86-{v}.run'
return [f'{NVIDIA_US_BASE_32}/{v}/{fn}', f'{NVIDIA_BASE_32}/{v}/{fn}']
def inst_ver():
try:
r = cmd(['nvidia-smi', '--query-gpu=driver_version', '--format=csv,noheader'], t=5)
if r.returncode == 0 and r.stdout.strip(): return r.stdout.strip().split('\n')[0]
except Exception:
pass
try:
with open('/proc/driver/nvidia/version') as f:
m = re.search(r'(\d+(?:\.\d+)+)', f.read())
if m: return m.group(1)
except Exception:
pass
v, _ = pkg_ver(); return v
def inst_short():
f = inst_ver(); m = re.match(r'(\d+(?:\.\d+)+)', f) if f else None
return m.group(1) if m else None
def find_file(root, name):
for dp, dn, fn in os.walk(root, onerror=lambda e: None):
if name in fn: return os.path.join(dp, name)
return None
def find_files_pattern(root, pattern):
return [os.path.join(dp, f) for dp, dn, fn in os.walk(root, onerror=lambda e: None)
for f in fn if fnmatch.fnmatch(f.lower(), pattern.lower())]
def strip_unwanted(path):
bad_dirs = {'sdk', 'doc', 'docs', 'manual', 'src', 'source', 'sources', 'dtrace',
'additions', 'unattendedtemplates', 'init', 'installer', 'temp', 'nv-extract'}
bad_files = ('*.cmd', '*.o', '*.mod', '*.mod.c', '*.order', '*.symvers', '*.c', '*.h',
'*.cpp', '*.cc', '*.s', '*.S', 'Makefile', 'Makefile.*', 'Kbuild', '*.debug',
'*.pdb', '*.sym', '*.map', '*.a', '*.la', '*.spec', 'UserManual.pdf',
'UserManual.qch', 'UserManual.qhc', 'postinst-common.sh', 'prerm-common.sh',
'routines.sh', 'check_module_dependencies.sh', 'uninstall.sh', 'nvidia-uninstall',
'.autoreg', '*.log', 'nvidia-installer', '*.backup', '*.orig')
for root, dirs, files in os.walk(path, topdown=False, onerror=lambda e: None):
for d in list(dirs):
if d.lower() in bad_dirs:
shutil.rmtree(os.path.join(root, d), ignore_errors=True); dirs.remove(d)
for f in files:
if any(fnmatch.fnmatch(f.lower(), p.lower()) for p in bad_files):
safe_rm(os.path.join(root, f))
try:
if not os.listdir(root): os.rmdir(root)
except Exception:
pass
def has_lib32(name):
return any(os.path.exists(os.path.join(d, name))
for d in ('/usr/lib', '/lib', '/usr/lib32', '/lib32'))
def protect_glvnd(bd, libdir, multilib=False, keep32=False):
"""Never ship libglvnd's vendor-neutral libraries for the native arch:
the module would shadow the base system's GL stack (mesa/glvnd) and break
it on deactivation. Vendor-specific files (libGLX_nvidia.so.*,
libEGL_nvidia.so.*) do not match these prefixes and are preserved.
32-bit neutrals are removed only when the system already has a 32-bit
glvnd (mesa-compat32); otherwise they are shipped so Wine GL works
(keep32=True)."""
neutrals = ('libGL.so', 'libEGL.so', 'libGLX.so', 'libOpenGL.so',
'libGLESv1_CM.so', 'libGLESv2.so', 'libGLdispatch.so')
dirs = [f'usr/{libdir}']
if multilib and not keep32 and f'usr/{libdir}' != 'usr/lib':
dirs.append('usr/lib')
for rel in dirs:
d = os.path.join(bd, rel)
if not os.path.isdir(d): continue
for f in os.listdir(d):
if any(f == p or f.startswith(p + '.') for p in neutrals):
safe_rm(os.path.join(d, f))
def file_sha256(p):
h = hashlib.sha256()
with open(p, 'rb') as f:
for chunk in iter(lambda: f.read(1048576), b''): h.update(chunk)
return h.hexdigest()
class Prog(Gtk.Dialog):
def __init__(self, par, t, m, on_cancel=None):
super().__init__(title=t, transient_for=par, modal=True)
self.set_deletable(False); self.set_default_size(340, 110)
self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
b = self.get_content_area(); b.set_spacing(12)
b.set_margin_top(20); b.set_margin_bottom(20)
try: b.set_margin_start(24); b.set_margin_end(24)
except Exception: b.set_margin_left(24); b.set_margin_right(24)
self.lbl = Gtk.Label(label=m); self.lbl.set_line_wrap(True)
self.bar = Gtk.ProgressBar(); self.bar.set_pulse_step(0.08)
b.pack_start(self.lbl, False, False, 0)
b.pack_start(self.bar, False, False, 0)
if on_cancel:
h = Gtk.Box(spacing=6, halign=Gtk.Align.CENTER)
cb = Gtk.Button(label=_('cancel')); cb.connect('clicked', lambda w: on_cancel())
h.pack_start(cb, False, False, 0)
b.pack_start(h, False, False, 0)
self.show_all()
self._tid = GLib.timeout_add(80, self._tk); self._d = False
def _tk(self):
if not self._d: self.bar.pulse(); return True
return False
def msg(self, m):
if not self._d: self.lbl.set_text(m)
def close(self):
if not self._d:
self._d = True
if self._tid: GLib.source_remove(self._tid)
self.destroy()
class VerDlg(Gtk.Dialog):
def __init__(self, par, latest, all_vs, iv):
super().__init__(title=_('sel_ver'), transient_for=par, modal=True)
self.set_default_size(360, 430)
self.set_position(Gtk.WindowPosition.CENTER_ON_PARENT)
b = self.get_content_area(); b.set_spacing(8)
b.set_margin_top(12); b.set_margin_bottom(12)
try: b.set_margin_start(16); b.set_margin_end(16)
except Exception: b.set_margin_left(16); b.set_margin_right(16)
il = Gtk.Label(); il.set_markup(f'{_("installed")}: {iv or _("na")}')
il.set_halign(Gtk.Align.START); b.pack_start(il, False, False, 0)
self.latest, self.all = latest, all_vs
self.chk_all = Gtk.CheckButton(label=_('show_all'))
self.chk_all.connect('toggled', self._fill)
b.pack_start(self.chk_all, False, False, 0)
sw = Gtk.ScrolledWindow(); sw.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC)
self.st = Gtk.ListStore(str)
self.tv = Gtk.TreeView(model=self.st)
self.tv.append_column(Gtk.TreeViewColumn(_('version'), Gtk.CellRendererText(), text=0))
self.tv.set_headers_visible(True)
self.tv.get_selection().set_mode(Gtk.SelectionMode.SINGLE)
sw.add(self.tv); b.pack_start(sw, True, True, 0)
self._fill()
self.add_button(_('_cancel'), Gtk.ResponseType.CANCEL)
self.add_button(_('ok'), Gtk.ResponseType.OK)
self.show_all()
def _fill(self, *a):
self.st.clear()
for v in (self.all if self.chk_all.get_active() else self.latest):
self.st.append([v])
if len(self.st): self.tv.get_selection().select_path(Gtk.TreePath.new_first())
def chosen(self):
_, it = self.tv.get_selection().get_selected()
return self.st[it][0] if it else None
class App(Gtk.Window):
def __init__(self, cli_file=None):
super().__init__(title=_('title'))
self._icon = load_icon(48)
if self._icon: self.set_icon(self._icon)
self.set_border_width(12); self.set_resizable(True)
self.set_default_size(640, 360)
self.set_position(Gtk.WindowPosition.CENTER)
self.connect('destroy', self._on_destroy)
raw = os.uname().machine
self.arch = 'i586' if raw in ('i386', 'i486', 'i586', 'i686') else raw
self.is64 = self.arch == 'x86_64'
self.nvidia_libdir = 'lib64' if self.is64 else 'lib'
self.multilib_enabled = False
self.workdir = private_dir('nvidia-builder')
self._prog = None
self._busy = False
self._worker = None
self._cancelled = threading.Event()
self._ui()
if cli_file and os.path.isfile(cli_file): self._set_path(cli_file)
def _on_destroy(self, w):
# let the worker unwind (revert live system, clean staging) before exit
self._cancelled.set()
for p in list(_RUN): _kill_tree(p)
t = self._worker
if t and t.is_alive():
t.join(timeout=6)
Gtk.main_quit()
def _ui(self):
vb = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=12); self.add(vb)
hb = Gtk.Box(spacing=12)
if self._icon: hb.pack_start(Gtk.Image.new_from_pixbuf(self._icon), False, False, 0)
t = Gtk.Label(); t.set_markup(f'{_("title")}')
hb.pack_start(t, True, True, 0)
vb.pack_start(hb, False, False, 0)
vb.pack_start(Gtk.Separator(), False, False, 0)
d = Gtk.Label(label=_('desc')); d.set_line_wrap(True); d.set_max_width_chars(80)
d.set_halign(Gtk.Align.START); vb.pack_start(d, False, False, 0)
fh = Gtk.Box(spacing=6)
fh.pack_start(Gtk.Label(label=_('file:')), False, False, 0)
self.ent = Gtk.Entry(); self.ent.set_editable(False); self.ent.set_width_chars(52)
fh.pack_start(self.ent, True, True, 0)
bb = Gtk.Button(label=_('browse')); bb.connect('clicked', self._br)
fh.pack_start(bb, False, False, 0)
vb.pack_start(fh, False, False, 0)
self.chk = Gtk.CheckButton(label=_('dl'))
self.chk.connect('toggled', lambda w: self.ent.set_sensitive(not w.get_active()))
vb.pack_start(self.chk, False, False, 0)
self.chk_multilib = Gtk.CheckButton(label=_('multilib'))
self.chk_multilib.set_tooltip_text(_('multilib_tooltip'))
if not self.is64:
self.chk_multilib.set_no_show_all(True); self.chk_multilib.hide()
else:
vb.pack_start(self.chk_multilib, False, False, 0)
vb.pack_start(Gtk.Separator(), False, False, 4)
bh = Gtk.Box(spacing=8, halign=Gtk.Align.END)
bc = Gtk.Button(label=_('cancel')); bc.connect('clicked', lambda w: self.destroy())
bo = Gtk.Button(label=_('ok')); bo.connect('clicked', self._ok)
bh.pack_end(bo, False, False, 0)
bh.pack_end(bc, False, False, 0)
vb.pack_end(bh, False, False, 0)
self.show_all()
def _set_path(self, p):
p = p or ''
self.ent.set_text(p); self.ent.set_tooltip_text(p)
def _set_no_dl(self):
self.chk.set_active(False); return False
def _br(self, w):
d = Gtk.FileChooserDialog(title=_('browse'), parent=self, action=Gtk.FileChooserAction.OPEN)
d.add_buttons(_('_cancel'), Gtk.ResponseType.CANCEL, _('_open'), Gtk.ResponseType.OK)
fa = Gtk.FileFilter(); fa.set_name(_('all')); fa.add_pattern('*'); d.add_filter(fa)
ff = Gtk.FileFilter(); ff.set_name(_('f_run')); ff.add_pattern('*.run')
d.add_filter(ff); d.set_filter(ff); d.set_current_folder('/mnt')
if d.run() == Gtk.ResponseType.OK:
self._set_path(d.get_filename()); self.chk.set_active(False)
d.destroy()
def _ok(self, w):
if self._busy: return
if self.chk.get_active(): return self._pick()
p = self.ent.get_text().strip()
if not p: self._err(_('no_opt'))
elif not os.path.exists(p): self._err(_('no_file'))
else: self._set_path(p); self._build(p)
def _msg(self, mt, tx):
def f():
bt = Gtk.ButtonsType.OK if mt == Gtk.MessageType.INFO else Gtk.ButtonsType.CLOSE
d = Gtk.MessageDialog(transient_for=self, modal=True, message_type=mt, buttons=bt, text=tx)
d.run(); d.destroy(); return False
GLib.idle_add(f)
def _err(self, m): self._msg(Gtk.MessageType.ERROR, m)
def _info(self, m): self._msg(Gtk.MessageType.INFO, m)
def _po(self, t, m, cancelable=True):
def f():
if self._prog: self._prog.close()
self._busy = True
self._cancelled.clear()
self._prog = Prog(self, t, m, on_cancel=self._cancelled.set if cancelable else None)
return False
GLib.idle_add(f)
def _pm(self, m): GLib.idle_add(lambda: (self._prog and self._prog.msg(m)) or False)
def _pc(self):
def f():
if self._prog: self._prog.close(); self._prog = None
self._busy = False
return False
GLib.idle_add(f)
def _chk(self):
if self._cancelled.is_set(): raise Cancelled()
def _thread(self, fn, *args):
self._worker = threading.Thread(target=fn, args=args, daemon=True)
self._worker.start()
def _pick(self):
self._po(_('downloading'), _('downloading'))
def w():
try:
self._chk()
latest, all_vs = nvidia_version_lists(self.arch)
self._chk()
GLib.idle_add(self._after_pick, latest, all_vs, inst_short())
except Cancelled:
GLib.idle_add(self._pc); GLib.idle_add(self._info, _('cancelled'))
except Exception as e:
GLib.idle_add(self._pc); GLib.idle_add(self._err, f'{_("no_link")}: {e}')
self._thread(w)
def _after_pick(self, latest, all_vs, iv):
self._pc()
if latest or all_vs: self._verdlg(latest, all_vs, iv)
else: self._err(_('no_link'))
def _verdlg(self, latest, all_vs, iv):
d = VerDlg(self, latest, all_vs, iv)
r = d.run(); v = d.chosen(); d.destroy()
if r == Gtk.ResponseType.OK and v: self._dlver(v)
def _download(self, url, part):
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
h = hashlib.sha256(); done = 0; t0 = time.time(); last = 0.0
with urllib.request.urlopen(req, timeout=60) as r, open(part, 'wb') as f:
total = int(r.headers.get('Content-Length') or 0)
while True:
self._chk()
chunk = r.read(262144)
if not chunk: break
f.write(chunk); h.update(chunk); done += len(chunk)
now = time.time()
if now - last >= 0.5:
last = now
pct = f' ({done * 100 // total}%)' if total else ''
rate = done / max(now - t0, 0.1) / 1048576
self._pm(f'{_("downloading")}: {done // 1048576} MB{pct}, {rate:.1f} MB/s')
if total and done != total:
raise BuildError(_('dl_trunc'))
return h.hexdigest()
def _dlver(self, ver):
ver = clean_ver(ver)
if not ver: self._err(_('bad_ver')); return
self._po(_('downloading'), _('downloading'))
def w():
part = None
try:
fn = f'NVIDIA-Linux-{"x86_64" if self.is64 else "x86"}-{ver}.run'
dest = os.path.join(self.workdir, fn); part = dest + '.part'
safe_rm(part)
self._chk()
if os.path.exists(dest) and os.path.getsize(dest) > 1048576:
self._pm(f'{_("downloading")} {fn} (cached)')
sha = file_sha256(dest)
else:
sha, last_err = None, None
for url in nvidia_urls(ver, self.is64):
try:
self._pm(f'{_("downloading")} {fn}...')
sha = self._download(url, part)
break
except Cancelled:
raise
except Exception as e:
safe_rm(part); last_err = e
if sha is None: raise BuildError(f'{_("dl_fail")}: {last_err}')
os.rename(part, dest)
expected = os.environ.get('NVIDIA_SHA256', '').strip().lower()
if expected and expected != sha:
raise BuildError(f'{_("dl_fail")}: SHA256 mismatch (expected {expected}, got {sha})')
GLib.idle_add(self._pc)
GLib.idle_add(self._set_path, dest)
GLib.idle_add(self._set_no_dl)
GLib.idle_add(self._build, dest)
except Cancelled:
if part: safe_rm(part)
GLib.idle_add(self._pc); GLib.idle_add(self._info, _('cancelled'))
except BuildError as e:
if part: safe_rm(part)
GLib.idle_add(self._pc); GLib.idle_add(self._err, str(e))
except Exception as e:
if part: safe_rm(part)
GLib.idle_add(self._pc); GLib.idle_add(self._err, f'{_("dl_fail")}: {e}')
self._thread(w)
def _build(self, fp):
if self._busy: return False
self.multilib_enabled = bool(self.chk_multilib.get_active()) and self.is64
force = False
missing = check_prerequisites()
if missing:
deps_str = '\n'.join(f' • {m}' for m in missing)
d = Gtk.MessageDialog(
transient_for=self,
modal=True,
message_type=Gtk.MessageType.WARNING,
buttons=Gtk.ButtonsType.NONE,
text=_('missing_deps_title')
)
d.set_property('secondary-text', _('missing_deps').format(deps_str))
d.add_button(_('abort'), Gtk.ResponseType.CANCEL)
d.add_button(_('continue_anyway'), Gtk.ResponseType.OK)
r = d.run()
d.destroy()
if r != Gtk.ResponseType.OK:
return False
force = True
self._po(_('building'), _('preparing'))
def w():
try:
self._do(fp, force)
except Cancelled:
GLib.idle_add(self._pc); GLib.idle_add(self._info, _('cancelled'))
except BuildError as e:
GLib.idle_add(self._pc); GLib.idle_add(self._err, str(e))
except Exception as e:
GLib.idle_add(self._pc); GLib.idle_add(self._err, f'{_("fail")}: {e}')
self._thread(w)
return False
def _file_version(self, fn):
m = re.search(r'NVIDIA-Linux-(?:x86_64|x86|i586|i686|i386)-(\d+(?:\.\d+)+(?:[-_.][^\s/\\]+)?)', fn)
if m:
clean = re.search(r'(\d+(?:\.\d+)+)', m.group(1))
if clean: return clean.group(1)
m = re.search(r'(\d+(?:\.\d+)+)', fn)
return m.group(1) if m else None
def _actual_version(self, exd, inst):
"""Real driver version from the installer binary / extracted dir name.
The firmware directory must match it exactly, so do not trust the
(possibly renamed) .run filename."""
try:
r = cmd([inst, '--version'], t=30)
m = re.search(VER_RE, (r.stdout or '') + ' ' + (r.stderr or ''))
if r.returncode == 0 and m: return clean_ver(m.group(0))
except Exception:
pass
try:
for name in os.listdir(exd):
m = re.search(r'NVIDIA-Linux-(?:x86_64|x86)-(\d+(?:\.\d+)+)', name)
if m: return m.group(1)
except Exception:
pass
return None
def _mki(self, bd):
os.makedirs(os.path.join(bd, 'etc/rc.d/init.d'), exist_ok=True)
os.makedirs(os.path.join(bd, 'etc/rc.d/rc4.d'), exist_ok=True)
ip = os.path.join(bd, 'etc/rc.d/init.d/rc.nvidia')
body = (
'#!/bin/sh\n'
'/sbin/depmod -a\n'
'/sbin/modprobe nvidia\n'
'/sbin/modprobe nvidia-modeset\n'
'/sbin/modprobe nvidia-drm\n'
'/sbin/modprobe nvidia-uvm\n'
'if [ -x /usr/bin/nvidia-modprobe ] && [ ! -c /dev/nvidia0 ]; then\n'
' /usr/bin/nvidia-modprobe -c 0 -u 2>/dev/null\n'
'fi\n'
'/sbin/ldconfig\n'
'[ -x /usr/bin/nvidia-persistenced ] && /usr/bin/nvidia-persistenced --daemon >/dev/null 2>&1\n'
)
with open(ip, 'w') as f: f.write(body)
os.chmod(ip, 0o755)
link = os.path.join(bd, 'etc/rc.d/rc4.d', 'S99nvidia')
if not os.path.lexists(link):
try: os.symlink('/etc/rc.d/init.d/rc.nvidia', link)
except Exception: pass
os.makedirs(os.path.join(bd, 'etc/modprobe.d'), exist_ok=True)
with open(os.path.join(bd, 'etc/modprobe.d/nvidia.conf'), 'w') as f:
f.write('blacklist nouveau\noptions nouveau modeset=0\noptions nvidia-drm modeset=1\n')
os.makedirs(os.path.join(bd, 'etc/X11/xorg.conf.d'), exist_ok=True)
with open(os.path.join(bd, 'etc/X11/xorg.conf.d/10-nvidia.conf'), 'w') as f:
f.write('Section "OutputClass"\n Identifier "nvidia"\n MatchDriver "nvidia-drm"\n'
' Driver "nvidia"\n Option "AllowEmptyInitialConfiguration"\n'
f' ModulePath "/usr/{self.nvidia_libdir}/xorg/modules"\nEndSection\n')
os.makedirs(os.path.join(bd, 'etc/profile.d'), exist_ok=True)
ps = os.path.join(bd, 'etc/profile.d/nvidia.sh')
with open(ps, 'w') as f:
f.write('#!/bin/sh\n'
'# Load Nvidia modules on first login, only if an Nvidia GPU is present\n'
'[ -c /dev/nvidia0 ] && exit 0\n'
'if command -v lspci >/dev/null 2>&1; then\n'
' lspci -d 10de: 2>/dev/null | grep -q . || exit 0\n'
' /etc/rc.d/init.d/rc.nvidia >/dev/null 2>&1\n'
'fi\n')
os.chmod(ps, 0o755)
def _do(self, fp, force=False):
self._chk()
try: os.chmod(fp, 0o755)
except Exception: pass
extra_copy = (not os.access(fp, os.X_OK)) or is_noexec(fp)
# peak usage: .run + extracted tree + staging + packed xzm
try: sz = os.path.getsize(fp) // 1048576
except Exception: sz = 400
need_mb = sz * 4 + 800
if self.multilib_enabled: need_mb += 500
if extra_copy: need_mb += sz + 100
ok, free = space_ok('/tmp', need_mb)
if not ok:
raise BuildError(f'{_("low_space")} /tmp\n{_("need")}: {need_mb} MB, {_("free")}: {free} MB')
if tmp_is_tmpfs('/tmp'):
ram = mem_available_mb()
if ram and ram < need_mb:
raise BuildError(f'{_("low_space")} /tmp (tmpfs, RAM)\n'
f'{_("need")}: {need_mb} MB, {_("ram_low")}: {ram} MB')
if not force:
if not os.path.isdir('/usr/src/linux'): raise BuildError(_('no_src'))
if not shutil.which('gcc') or not shutil.which('make'): raise BuildError(_('no_tools'))
if not shutil.which('dir2xzm'): raise BuildError(_('no_dir2xzm'))
kr = None
try:
with open('/usr/src/linux/include/config/kernel.release') as f: kr = f.read().strip()
except Exception:
pass
# kernel.release vs uname -r is ALWAYS strict (even with force):
# a module built for another kernel cannot load (vermagic mismatch).
if kr and kr != os.uname().release:
raise BuildError(_('src_mismatch').format(kr, os.uname().release))
self._chk()
if self.multilib_enabled:
# compat32 driver libs ship prebuilt inside the .run: no 32-bit
# compiler needed, only the 32-bit runtime (multilib-lite).
# Always strict, not bypassed by force.
if not (os.path.isfile('/lib/ld-linux.so.2')
or os.path.isfile('/usr/lib/ld-linux.so.2')
or os.path.isfile('/lib32/ld-linux.so.2')
or os.path.isfile('/usr/lib32/ld-linux.so.2')):
raise BuildError(_('no_multilib_libs'))
fv = self._file_version(os.path.basename(fp))
if not fv: raise BuildError(_('no_ver'))
self._do_staging(fp, fv)
def _relativize_symlinks(self, bd, td):
"""Rewrite absolute symlinks pointing into the staging area into
relative links; legitimate absolute targets are left intact."""
for dp, dn, fn in os.walk(bd):
for name in list(dn) + fn:
p = os.path.join(dp, name)
if not os.path.islink(p): continue
try: tgt = os.readlink(p)
except Exception: continue
if not (tgt.startswith(td) or '/nvidia-stage-' in tgt):
continue
try:
os.unlink(p)
os.symlink(os.path.relpath(tgt, dp), p)
except Exception:
pass
def _ensure_critical_files(self, bd, extract_dir, kpath, fv):
usr_lib = os.path.join(bd, 'usr', self.nvidia_libdir)
drv_dir = os.path.join(usr_lib, 'xorg', 'modules', 'drivers')
os.makedirs(drv_dir, exist_ok=True)
drv = os.path.join(drv_dir, 'nvidia_drv.so')
if not os.path.exists(drv):
src = find_file(extract_dir, 'nvidia_drv.so')
if src:
shutil.copy2(src, drv); os.chmod(drv, 0o755)
ext_dir = os.path.join(usr_lib, 'xorg', 'modules', 'extensions')
os.makedirs(ext_dir, exist_ok=True)
copied = set()
for ext in find_files_pattern(extract_dir, 'libglxserver_nvidia*'):
if os.path.realpath(ext).startswith(os.path.realpath(extract_dir)):
n = os.path.basename(ext)
if n not in copied:
# preserve symlinks instead of duplicating the real file
shutil.copy2(ext, os.path.join(ext_dir, n), follow_symlinks=False)
copied.add(n)
mp = os.path.join(bd, 'usr', 'bin', 'nvidia-modprobe')
if not os.path.exists(mp):
src = find_file(extract_dir, 'nvidia-modprobe')
if src:
os.makedirs(os.path.dirname(mp), exist_ok=True)
shutil.copy2(src, mp); os.chmod(mp, 0o4755)
json_map = {
'nvidia_icd.json': 'usr/share/vulkan/icd.d',
'nvidia_icd_vksc.json': 'usr/share/vulkansc/icd.d',
'nvidia_layers.json': 'usr/share/vulkan/implicit_layer.d',
'10_nvidia.json': 'usr/share/glvnd/egl_vendor.d',
'10_nvidia_wayland.json': 'usr/share/egl/egl_external_platform.d',
'10_nvidia_drm.json': 'usr/share/egl/egl_external_platform.d',
'15_nvidia_gbm.json': 'usr/share/egl/egl_external_platform.d',
}
icd_src = None
for jf in find_files_pattern(extract_dir, '*.json'):
n = os.path.basename(jf)
if n in json_map:
d = os.path.join(bd, json_map[n])
if not os.path.exists(os.path.join(d, n)):
os.makedirs(d, exist_ok=True)
shutil.copy2(jf, d)
if n == 'nvidia_icd.json' and icd_src is None:
icd_src = jf
# Layer manifests must not live in icd.d/: the VULKAN_ICD_JSON
# override in newer manifests covers nvidia_layers.json too, so the
# installer drops it there. The Vulkan loader warns on non-ICD
# manifests in icd.d/. Layer manifests belong to implicit_layer.d/
# only; icd.d/ keeps exactly one entry per ICD.
for icd_dir in (os.path.join(bd, 'usr', 'share', 'vulkan', 'icd.d'),
os.path.join(bd, 'usr', 'share', 'vulkansc', 'icd.d')):
if not os.path.isdir(icd_dir): continue
for f in list(os.listdir(icd_dir)):
if 'layer' in f.lower():
safe_rm(os.path.join(icd_dir, f))
# Vulkan ICD: mirror into etc/vulkan/icd.d as well (valid loader path)
vdir = os.path.join(bd, 'etc', 'vulkan', 'icd.d')
if not os.path.exists(os.path.join(vdir, 'nvidia_icd.json')):
os.makedirs(vdir, exist_ok=True)
if icd_src:
shutil.copy2(icd_src, os.path.join(vdir, 'nvidia_icd.json'))
else:
with open(os.path.join(vdir, 'nvidia_icd.json'), 'w') as f:
f.write(f'{{"file_format_version":"1.0.0",'
f'"ICD":{{"library_path":"/usr/{self.nvidia_libdir}/libGLX_nvidia.so.0",'
f'"api_version":"1.3"}}}}\n')
# OpenCL ICD
ocl_dir = os.path.join(bd, 'etc', 'OpenCL', 'vendors')
ocl = os.path.join(ocl_dir, 'nvidia.icd')
if not os.path.exists(ocl):
os.makedirs(ocl_dir, exist_ok=True)
ocl_src = find_file(extract_dir, 'nvidia.icd')
if ocl_src:
shutil.copy2(ocl_src, ocl)
else:
with open(ocl, 'w') as f: f.write('libnvidia-opencl.so.1\n')
fw_dir = os.path.join(bd, 'lib', 'firmware', 'nvidia', fv)
for fw in find_files_pattern(extract_dir, 'gsp_*.bin'):
os.makedirs(fw_dir, exist_ok=True)
dst = os.path.join(fw_dir, os.path.basename(fw))
if not os.path.exists(dst): shutil.copy2(fw, dst)
for ko in find_files_pattern(bd, '*.ko*'):
dest = os.path.join(kpath, os.path.basename(ko))
if not os.path.exists(dest) and os.path.dirname(ko) != kpath:
try: shutil.move(ko, dest)
except Exception: pass
def _do_staging(self, fp, fv):
with tempfile.TemporaryDirectory(dir='/tmp', prefix='nvidia-stage-') as td:
bd = os.path.join(td, 'build'); os.makedirs(bd, exist_ok=True)
snap, snap_dirs = snapshot_live()
try:
self._chk()
self._pm(_('extracting'))
exd = os.path.join(td, 'nv-extract')
run_path = ensure_installer(fp, td)
extract_args = ['--extract-only', '--target', exd]
runner = [run_path] if os.access(run_path, os.X_OK) else ['sh', run_path]
r = cmd(runner + extract_args, t=600, cancel=self._cancelled.is_set)
if r.returncode == 130: raise Cancelled()
if r.returncode != 0 and runner[0] != 'sh':
r2 = cmd(['sh', run_path] + extract_args, t=600, cancel=self._cancelled.is_set)
if r2.returncode == 130: raise Cancelled()
if r2.returncode == 0: r = r2
if r.returncode != 0 or not os.path.isdir(exd):
raise BuildError(_('stage_fail'))
inst = find_file(exd, 'nvidia-installer')
if not inst: raise BuildError(_('stage_fail'))
try: os.chmod(inst, 0o755)
except Exception: pass
# exact version: firmware dir and module name must match it
fv = self._actual_version(exd, inst) or fv
self._chk()
self._pm(_('compiling'))
kver = os.uname().release
kpath = os.path.join(bd, 'lib', 'modules', kver, 'kernel', 'drivers', 'video')
os.makedirs(kpath, exist_ok=True)
usr = os.path.join(bd, 'usr'); os.makedirs(usr, exist_ok=True)
os.makedirs(os.path.join(usr, self.nvidia_libdir), exist_ok=True)
os.makedirs(os.path.join(usr, 'lib'), exist_ok=True)
env = os.environ.copy()
env['PATH'] = '/usr/sbin:/usr/bin:/sbin:/bin'
env['IGNORE_CC_MISMATCH'] = '1'
args = [
inst, '--silent', '--no-x-check', '--no-nouveau-check', '--no-abi-note',
'--no-cc-version-check', '--allow-installation-with-running-driver',
'--kernel-source-path=/usr/src/linux', '--skip-module-load',
'--no-distro-scripts', '--no-rpms', '--no-systemd',
'--no-kernel-module-source', '--skip-depmod', '--no-rebuild-initramfs',
f'--utility-prefix={usr}', f'--opengl-prefix={usr}', f'--x-prefix={usr}',
f'--opengl-libdir={self.nvidia_libdir}', f'--utility-libdir={self.nvidia_libdir}',
f'--x-module-path={usr}/{self.nvidia_libdir}/xorg/modules',
f'--x-library-path={self.nvidia_libdir}',
f'--kernel-install-path={kpath}'
]
if self.is64 and self.multilib_enabled:
os.makedirs(os.path.join(usr, 'lib'), exist_ok=True)
args.extend(['--install-compat32-libs',
f'--compat32-prefix={usr}', '--compat32-libdir=lib'])
args.extend([
f'--wine-prefix={usr}',
f'--documentation-prefix={usr}',
f'--x-sysconfig-path={usr}/share/X11/xorg.conf.d',
f'--xdg-data-dir={usr}/share',
f'--application-profile-path={usr}/share/nvidia',
f'--gbm-backend-dir={self.nvidia_libdir}/gbm',
f'--glvnd-egl-config-path={usr}/share/glvnd/egl_vendor.d',
f'--egl-external-platform-config-path={usr}/share/egl/egl_external_platform.d',
'--no-disable-nouveau',
'--no-dkms',
])
# Redirect file types whose default destinations ignore the
# prefixes above (profiles -> /usr/share/nvidia, GSP firmware
# -> /lib/firmware/nvidia/, ICD jsons). Only request types
# actually present in this package's .manifest, so older
# installers do not choke on unknown type names.
manifest_txt = ''
mf = find_file(exd, '.manifest')
if mf:
try:
with open(mf, 'r', errors='replace') as f: manifest_txt = f.read()
except Exception:
pass
for ftype, dest in (
('VULKAN_ICD_JSON', f'{bd}/usr/share/vulkan/icd.d'),
('VULKANSC_ICD_JSON', f'{bd}/usr/share/vulkansc/icd.d'),
('CUDA_ICD', f'{bd}/etc/OpenCL/vendors'),
('FIRMWARE', f'{bd}/lib/firmware/nvidia/{fv}'),
('FIRMWARE_SYMLINK', f'{bd}/lib/firmware/nvidia/{fv}'),
):
if not manifest_txt or ftype in manifest_txt:
args.append(f'--override-file-type-destination={ftype}:{dest}')
supported = installer_supported_options(inst)
args = filter_args(args, supported)
logp = LOG
if supported and 'log-file-name' in supported:
args.append(f'--log-file-name={td}/nvidia-installer.log')
logp = os.path.join(td, 'nvidia-installer.log')
if supported and 'tmpdir' in supported:
os.makedirs(os.path.join(td, 'tmp'), exist_ok=True)
args.append(f'--tmpdir={td}/tmp')
if supported and 'no-install-libglvnd' in supported:
args.append('--no-install-libglvnd')
# Shim tools that would touch the live kernel / ld cache on
# old installers lacking --skip-module-load/--skip-depmod.
shim = os.path.join(td, 'shim')
os.makedirs(shim, exist_ok=True)
for tool in ('modprobe', 'insmod', 'rmmod', 'depmod', 'ldconfig'):
p = os.path.join(shim, tool)
with open(p, 'w') as f: f.write('#!/bin/sh\nexit 0\n')
os.chmod(p, 0o755)
env['PATH'] = f'{shim}:{env["PATH"]}'
installer_args = args
for _attempt in range(6):
r = cmd(installer_args, t=3600, env=env, cancel=self._cancelled.is_set)
if r.returncode in (0, 130):
break
blob = (r.stderr or '') + ' ' + log_tail(path=logp)
m = re.search(r"unrecognized option[:\s]+'?(-{2}[A-Za-z0-9-]+)", blob, re.IGNORECASE) \
or re.search(r"unknown option[:\s]+'?(-{2}[A-Za-z0-9-]+)", blob, re.IGNORECASE)
if not m:
break
dropped = m.group(1)
installer_args = [a for a in installer_args
if a != dropped and not a.startswith(dropped + '=')]
if r.returncode == 130: raise Cancelled()
if r.returncode != 0:
err = (r.stderr or '').strip()
if not err:
lt = log_tail(n=20000, path=logp).strip()
err = lt[-800:] if lt else _('fail')
errlog = os.path.join(self.workdir, 'nvidia-installer-error.log')
try:
if os.path.isfile(logp):
shutil.copy2(logp, errlog)
except Exception:
pass
tail_note = f'\n{_("log_saved").format(errlog)}' if os.path.isfile(errlog) else ''
raise BuildError(f'{_("stage_fail")}: {err}{tail_note}')
self._chk()
self._pm(_('staging'))
self._relativize_symlinks(bd, td)
self._ensure_critical_files(bd, exd, kpath, fv)
mp = find_file(bd, 'nvidia-modprobe')
if mp:
try: os.chmod(mp, 0o4755)
except Exception: pass
self._mki(bd); strip_unwanted(bd)
protect_glvnd(bd, self.nvidia_libdir, self.multilib_enabled,
keep32=not has_lib32('libGLX.so.0'))
if self.multilib_enabled and not find_files_pattern(
os.path.join(bd, 'usr', 'lib'), 'libGLX_nvidia.so*'):
raise BuildError(_('no_compat32'))
self._chk()
# stow live-side leftovers into the module BEFORE packing
collect_and_revert(snap, snap_dirs, bd)
self._package(bd, fv)
finally:
try: collect_and_revert(snap, snap_dirs, bd)
except Exception: pass
def _package(self, bd, fv):
self._chk()
if not find_files_pattern(bd, 'nvidia.ko*'):
raise BuildError(_('no_ko'))
self._pm(_('mkmod'))
pn = 'nvidia-driver'
suf = 'x86_64-multilib' if self.multilib_enabled else self.arch
nm = f'{pn}-{fv}-porteus-{pver()}-{suf}-1prt'
out = os.path.join(self.workdir, nm + '.xzm')
safe_rm(out)
pd = os.path.join(bd, 'var/lib/pkgtools/packages'); os.makedirs(pd, exist_ok=True)
with open(os.path.join(pd, nm), 'w') as f:
f.write(f'PACKAGE NAME: {nm}\nPACKAGE DESCRIPTION:\n'
f'{pn}: {pn} (proprietary graphics driver)\n{pn}:\n'
f'{pn}: Nvidia proprietary driver for X.org and Wayland.\n'
f'{pn}: Includes kernel modules and user-space libraries.\n')
if self.multilib_enabled: f.write(f'{pn}: (32-bit libs included for Wine/Steam)\n')
f.write(f'{pn}:\n{pn}: https://www.nvidia.com/\n{pn}:\nFILE LIST:\n')
for root, dirs, files in os.walk(bd):
for fn in files:
rel = os.path.relpath(os.path.join(root, fn), bd)
if not rel.startswith('var/lib/pkgtools/packages'): f.write(rel + '\n')
r = cmd(['dir2xzm', bd, out], t=600, cancel=self._cancelled.is_set)
if r.returncode == 130:
safe_rm(out); raise Cancelled()
if r.returncode != 0:
safe_rm(out)
err = (r.stderr or '').strip() or (r.stdout or '').strip() or _('fail')
raise BuildError(f'{_("fail")}: {err[:800]}')
self._pc()
# keep the downloaded .run in the private cache for rebuilds
GLib.idle_add(self._result, out, file_sha256(out))
return True
def _result(self, out, sha=None):
txt = f'{_("ready")}\n{out}'
if sha: txt += f'\n{_("hash")}: {sha}'
d = Gtk.MessageDialog(transient_for=self, modal=True, message_type=Gtk.MessageType.INFO,
buttons=Gtk.ButtonsType.NONE, text=txt)
d.set_property('secondary-text', f'{_("action")}\n{_("more")}')
d.add_button(_('mv_act'), 1); d.add_button(_('open_dir'), 2); d.add_button(_('close'), 3)
r = d.run(); d.destroy()
if r == 1: self._thread(self._move_act, out)
elif r == 2: fm_open(os.path.dirname(out))
return False
def _move_act(self, out):
md = mod_dir()
if not md: GLib.idle_add(self._err, _('no_moddir')); return
try:
mn = os.path.basename(out)
dest = os.path.join(md, mn)
try: need = os.path.getsize(out) // 1048576 + 100
except Exception: need = 100
ok, free = space_ok(md, need)
if not ok:
GLib.idle_add(self._err, f'{_("mv_fail")}: {_("low_space")} {md}\n'
f'{_("need")}: {need} MB, {_("free")}: {free} MB')
return
try: old_mods = [f for f in os.listdir(md) if is_nvidia_file(f) and f != mn]
except Exception: old_mods = []
if not deactivate_all_wait(self._cancelled.is_set):
if self._cancelled.is_set(): GLib.idle_add(self._info, _('cancelled'))
else: GLib.idle_add(self._err, _('mod_in_use'))
return
if not os.path.isfile(out):
GLib.idle_add(self._err, f'{_("mv_fail")}: {out}'); return
GLib.idle_add(self._po, _('building'), _('mv_act'))
shutil.move(out, dest)
try:
fd = os.open(dest, os.O_RDONLY); os.fsync(fd); os.close(fd)
except Exception:
os.sync()
r = cmd(['activate', dest], t=60, cancel=self._cancelled.is_set)
GLib.idle_add(self._pc)
if r.returncode == 0:
renamed = 0
for f in old_mods:
try:
os.rename(os.path.join(md, f), os.path.join(md, f + '.bak'))
renamed += 1
except Exception:
pass
# .bak retention: keep the two newest backups. os.rename preserves
# mtime, so sorting reflects build age, not rename time. Runs only
# after successful activation; on failure backups stay untouched.
try:
baks = [os.path.join(md, f) for f in os.listdir(md)
if f.startswith(('nvidia-driver-', 'nvidia-linux-'))
and f.endswith('.xzm.bak')]
baks.sort(key=lambda p: os.path.getmtime(p), reverse=True)
for p in baks[2:]:
safe_rm(p)
except Exception:
pass
msg = f'{mn}\n{_("moved")} {md}\n{_("act_ok")}'
if renamed: msg += f'\n{_("old_renamed")}'
msg += f'\n\n{_("reboot_host")}'
GLib.idle_add(self._info, msg)
else:
GLib.idle_add(self._err, f'{_("act_fail")}\n{(r.stderr or "").strip() or (r.stdout or "").strip() or _("act_ng")}')
except Exception as e:
GLib.idle_add(self._pc)
GLib.idle_add(self._err, f'{_("mv_fail")}: {e}')
if __name__ == '__main__':
mach = os.uname().machine
if mach not in ('x86_64', 'i386', 'i486', 'i586', 'i686'):
print(f'Unsupported architecture: {mach}')
sys.exit(1)
if os.getuid() != 0: print(_('root')); sys.exit(1)
if not os.environ.get('DISPLAY'): print(_('x11')); sys.exit(1)
pix = load_icon(48)
if pix:
try: Gtk.Window.set_default_icon(pix)
except Exception: pass
GLib.set_prgname('nvidia-builder')
GLib.set_application_name(_('title'))
fp = sys.argv[1] if len(sys.argv) > 1 and os.path.isfile(sys.argv[1]) else None
app = App(fp)
signal.signal(signal.SIGINT, lambda *_: GLib.idle_add(app.destroy))
app.show_all()
Gtk.main()