Files
semios-packages/hooks/autostrip.py
T
2026-08-15 12:47:13 +08:00

60 lines
1.7 KiB
Python

import os
import stat
import subprocess
import tempfile
import shutil
from lib import common
strip = os.environ.get("STRIP", "strip")
def _is_elf(filepath):
with open(filepath, "rb") as f:
return f.read(4) == b"\x7fELF"
def autostrip(composer):
processed_inodes = {}
for ent in common.treedir(composer.workdir):
if not ent.is_file(follow_symlinks=False):
continue
if not (os.access(ent.path, os.X_OK) or ".so" in ent.name):
continue
if not _is_elf(ent.path):
continue
stat_info = os.stat(ent.path)
inode_key = (stat_info.st_dev, stat_info.st_ino)
if inode_key in processed_inodes:
continue
processed_inodes[inode_key] = True
oldperm = stat.S_IMODE(stat_info.st_mode)
try:
with tempfile.NamedTemporaryFile(mode='wb', delete=False) as tmp_file:
tmp_path = tmp_file.name
shutil.copy2(ent.path, tmp_path)
os.chmod(tmp_path, 0o777)
subprocess.run([strip, tmp_path], check=True)
with open(tmp_path, 'rb') as tmp_file:
stripped_data = tmp_file.read()
with open(ent.path, 'r+b') as original_file:
original_file.truncate(0)
original_file.write(stripped_data)
original_file.flush()
os.fsync(original_file.fileno())
os.chmod(ent.path, oldperm)
os.unlink(tmp_path)
except Exception as e:
if 'tmp_path' in locals() and os.path.exists(tmp_path):
os.unlink(tmp_path)
raise RuntimeError(f"Failed to strip {ent.path}: {e}") from e