#!/usr/bin/env python3
"""Diagnose why shell commands fail: test system() with jbroot paths, find posix_spawn export."""
import frida, sys, time, json

sys.stdout.reconfigure(encoding='utf-8')

JS = r"""
const libc = Process.getModuleByName('libsystem_c.dylib');
const system = new NativeFunction(libc.getExportByName('system'), 'int', ['pointer']);
function run(c) { send({c: c, rc: system(Memory.allocUtf8String(c))}); }

run('/bin/sh -c "echo SHOK > /var/mobile/Media/frout.txt"');
run('export PATH=/var/containers/Bundle/Application/.jbroot-F65244869E171CF3/usr/bin:/var/containers/Bundle/Application/.jbroot-F65244869E171CF3/bin:$PATH; id > /var/mobile/Media/frout2.txt 2>&1; echo RC=$? >> /var/mobile/Media/frout2.txt');

var hits = [];
Process.enumerateModules().forEach(function (m) {
    try {
        m.enumerateExports().forEach(function (x) {
            if (x.name.indexOf('posix_spawn') >= 0) hits.push(m.name + ':' + x.name);
        });
    } catch (e) {}
});
send({spawn_exports: hits.slice(0, 10)});
"""

dev = frida.get_device_manager().add_remote_device('127.0.0.1:7777')
ps = {p.name: p.pid for p in dev.enumerate_processes()}
session = dev.attach(ps['launchd'])
script = session.create_script(JS)
msgs = []
script.on('message', lambda m, d: (msgs.append(m), print('[frida]', m)))
script.load()
time.sleep(3)
session.detach()
