package asia.malware.dexhook;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.callbacks.XC_LoadPackage;

import static de.robv.android.xposed.XposedHelpers.findAndHookConstructor;

/**
 * Created by jcase on 9/7/15.
 */
public class DexHook implements IXposedHookLoadPackage {

    //mkdir /data/local/tmp/dump, chmod 777 /data/local/tmp/dump
    String outDir = "/data/local/tmp/dump";
    String targetClass = "dalvik.system.BaseDexClassLoader";
    String packageName = null;

    @Override
    public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {

        packageName = lpparam.packageName;

        findAndHookConstructor(targetClass, lpparam.classLoader, String.class, File.class, String.class, ClassLoader.class, new XC_MethodHook() {
            @Override
            protected void beforeHookedMethod(MethodHookParam param) throws Throwable {

                String dexPath = (String) param.args[0];

                if (dexPath.startsWith("/system/"))
                    return;

                XposedBridge.log("Entering classloader for " + packageName);
                String uniq = UUID.randomUUID().toString();
                outDir = outDir + "/" + packageName + "_" + dexPath.replace("/", "_") + "-" + uniq;

                XposedBridge.log("Capturing " + dexPath);
                XposedBridge.log("Writing to " + outDir);

                InputStream in = new FileInputStream(dexPath);
                OutputStream out = new FileOutputStream(outDir);
                byte[] buf = new byte[1024];
                int len;
                while ((len = in.read(buf)) > 0) {
                    out.write(buf, 0, len);
                }
                in.close();
                out.close();
            }
        });
    }
}
