"""Turn a rootfs tarball listing into debugfs scripts that restore it exactly. macOS cannot extract a Linux rootfs faithfully as an ordinary user: tar drops setuid/setgid bits, applies the umask, cannot chown to foreign uids and cannot create device nodes. mke2fs -d then copies those damaged modes into the image. This reads the tarball's own metadata (tar tv --numeric-owner) and writes: mknods.debugfs -- every block/char device node, with mode and owner metadata.debugfs -- mode, uid and gid for every other entry so the filesystem ends up exactly as the tarball describes it. Written for the genuine soho image, whose setuid apm.orig is what makes the power button work. python3 tarmeta2debugfs.py [--skip PATH ...] --skip leaves an entry's metadata alone (for files deliberately changed after extraction, e.g. a CF-adapted fstab, which then keeps its tarball mode anyway). """ import re, sys, os TYPE = {'-': 0o100000, 'd': 0o040000, 'l': 0o120000, 'c': 0o020000, 'b': 0o060000} def perm(s): """'rwsr-xr-x' -> 0o4755, handling s/S/t/T.""" v = 0 for i, (r, w, x) in enumerate((s[0:3], s[3:6], s[6:9])): bits = (4 if r == 'r' else 0) | (2 if w == 'w' else 0) | (1 if x in 'xst' else 0) v |= bits << (3 * (2 - i)) if s[2] in 'sS': v |= 0o4000 if s[5] in 'sS': v |= 0o2000 if s[8] in 'tT': v |= 0o1000 return v listing, outdir = sys.argv[1], sys.argv[2] skip = set(a.lstrip('./') for a in sys.argv[4:]) if '--skip' in sys.argv else set() rx = re.compile(r'^(\S)(\S{9})\s+\d+\s+(\d+)\s+(\d+)\s+(\S+)\s+\S+\s+\d+\s+\S+\s+(.*)$') mk, meta = ['cd /dev'], [] n_dev = n_meta = n_suid = 0 for line in open(listing, errors='replace'): m = rx.match(line.rstrip('\n')) if not m: continue t, p, uid, gid, size, name = m.groups() if t == 'l': name = name.split(' -> ')[0] rel = name[2:] if name.startswith('./') else name rel = rel.rstrip('/') if not rel or rel in skip: continue mode = TYPE[t] | perm(p) if mode & 0o7000: n_suid += 1 if t in 'cb': maj, mnr = size.split(',') dev = rel[len('dev/'):] if rel.startswith('dev/') else rel mk += [f'mknod {dev} {t} {int(maj)} {int(mnr)}', f'sif {dev} mode 0{mode:o}', f'sif {dev} uid {uid}', f'sif {dev} gid {gid}'] n_dev += 1 continue q = f'"/{rel}"' if t != 'l': meta.append(f'sif {q} mode 0{mode:o}') meta += [f'sif {q} uid {uid}', f'sif {q} gid {gid}'] n_meta += 1 open(os.path.join(outdir, 'mknods.debugfs'), 'w').write('\n'.join(mk) + '\n') open(os.path.join(outdir, 'metadata.debugfs'), 'w').write('\n'.join(meta) + '\n') print(f' {n_dev} device nodes, {n_meta} entries with exact metadata, {n_suid} setuid/setgid/sticky')