// node main.js MyTestMFC-vcpkg.exe
import frida from "frida";


// 消息通知处理函数
function onMessage(message, data) {
  if (message.type === 'send') {
      console.log('[*] ', message.payload);
  } else if (message.type === 'error') {
      console.error(message.stack);
  }
}

async function 获取进程ID() {
  let exeName = process.argv[2]
  console.log("exeName:", exeName)
  
  var device = await frida.getLocalDevice();
  var processes = await device.enumerateProcesses();  // 尽量使用管理员权限执行脚本。
  var pid = -1;
  processes.forEach(async (p_) => {
    // console.log(p_.name, p_.pid, p_);
    if (p_.name == exeName) {
      // 找到第一个就是
      if (pid == -1) {
        pid = p_.pid;
      }
    }
  });
  console.log("主进程 pid = " + pid);

  return pid;
}

async function 获取注入脚本() {
  return `
  console.log("开始注入脚本");

  // 获取MessageBoxA地址
  const funcAddr = Module.findExportByName('user32.dll', 'MessageBoxA')
  // hook MessageBoxA
  Interceptor.attach(funcAddr, {
    // 进入函数前打印第一个参数（从0开始计算，第0个参数为句柄）
    onEnter(args) {
      send("HOOK MessageBoxA args[1] = " + args[1].readAnsiString())
      send("HOOK MessageBoxA args[2] = " + args[2].readAnsiString())
    }
  });
`
}

async function main() {
  let jsSource = await 获取注入脚本()
  const pid = await 获取进程ID();
  if (pid == -1) {
    return -1;
  }

  let session = await frida.attach(pid);
  let script = await session.createScript(jsSource);
  script.message.connect(onMessage);
  await script.load();
}

main().catch(error => {
    console.error(error);
});
