Fart修改源码注释

libcore\dalvik\src\main\java\dalvik\system\DexFile.java

    //增加dumpMethodCode,对应 art\runtime\native\dalvik_system_DexFile.cc  DexFile_dumpMethodCode
    private static native void dumpMethodCode(Object m);
    

frameworks\base\core\java\android\app\ActivityThread.java

  • 主要是增加了在Activity OnCreate时,遍历所有dex并且遍历所有类,遍历所有方法,然后dump method
    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
        //在Activity ONCREATE 后 增加了调用
        fartthread();
        //add    
    }
    
    public static void fartthread() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    Log.e("ActivityThread", "start sleep,wait for fartthread start......");
                    Thread.sleep(1 * 60 * 1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Log.e("ActivityThread", "sleep over and start fartthread");
                fart();
                Log.e("ActivityThread", "fart run over");

            }
        }).start();
    }
    
    public static void fart() {
        ClassLoader appClassloader = getClassloader();
        List<Object> dexFilesArray = new ArrayList<Object>();
        Field pathList_Field = (Field) getClassField(appClassloader, "dalvik.system.BaseDexClassLoader", "pathList");
        Object pathList_object = getFieldOjbect("dalvik.system.BaseDexClassLoader", appClassloader, "pathList");
        Object[] ElementsArray = (Object[]) getFieldOjbect("dalvik.system.DexPathList", pathList_object, "dexElements");
        Field dexFile_fileField = null;
        try {
            dexFile_fileField = (Field) getClassField(appClassloader, "dalvik.system.DexPathList$Element", "dexFile");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Class DexFileClazz = null;
        try {
            DexFileClazz = appClassloader.loadClass("dalvik.system.DexFile");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Method getClassNameList_method = null;
        Method defineClass_method = null;
        Method dumpDexFile_method = null;
        Method dumpMethodCode_method = null;

        for (Method field : DexFileClazz.getDeclaredMethods()) {
            if (field.getName().equals("getClassNameList")) {
                getClassNameList_method = field;
                getClassNameList_method.setAccessible(true);
            }
            if (field.getName().equals("defineClassNative")) {
                defineClass_method = field;
                defineClass_method.setAccessible(true);
            }
            if (field.getName().equals("dumpMethodCode")) {
                dumpMethodCode_method = field;
                dumpMethodCode_method.setAccessible(true);
            }
        }
        Field mCookiefield = getClassField(appClassloader, "dalvik.system.DexFile", "mCookie");
        for (int j = 0; j < ElementsArray.length; j++) {
            Object element = ElementsArray[j];
            Object dexfile = null;
            try {
                dexfile = (Object) dexFile_fileField.get(element);
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (dexfile == null) {
                continue;
            }
            if (dexfile != null) {
                dexFilesArray.add(dexfile);
                Object mcookie = getClassFieldObject(appClassloader, "dalvik.system.DexFile", dexfile, "mCookie");
                if (mcookie == null) {
                    continue;
                }
                String[] classnames = null;
                try {
                    //获取dex中所有的类名
                    classnames = (String[]) getClassNameList_method.invoke(dexfile, mcookie);
                } catch (Exception e) {
                    e.printStackTrace();
                    continue;
                } catch (Error e) {
                    e.printStackTrace();
                    continue;
                }
                if (classnames != null) {
                    for (String eachclassname : classnames) {
                        //遍历所有的类,并且调用新增的dumpMethodCode_method
                        loadClassAndInvoke(appClassloader, eachclassname, dumpMethodCode_method);
                    }
                }

            }
        }
        return;
    }
    //遍历类,并且调用方法的dumpMethodCode_method
    public static void loadClassAndInvoke(ClassLoader appClassloader, String eachclassname, Method dumpMethodCode_method) {
        Log.i("ActivityThread", "go into loadClassAndInvoke->" + "classname:" + eachclassname);
        Class resultclass = null;
        try {
            resultclass = appClassloader.loadClass(eachclassname);
        } catch (Exception e) {
            e.printStackTrace();
            return;
        } catch (Error e) {
            e.printStackTrace();
            return;
        } 
        if (resultclass != null) {
            try {
                Constructor<?> cons[] = resultclass.getDeclaredConstructors();
                for (Constructor<?> constructor : cons) {
                    if (dumpMethodCode_method != null) {
                        try {
                            dumpMethodCode_method.invoke(null, constructor);
                        } catch (Exception e) {
                            e.printStackTrace();
                            continue;
                        } catch (Error e) {
                            e.printStackTrace();
                            continue;
                        } 
                    } else {
                        Log.e("ActivityThread", "dumpMethodCode_method is null ");
                    }

                }
            } catch (Exception e) {
                e.printStackTrace();
            } catch (Error e) {
                e.printStackTrace();
            } 
            try {
                Method[] methods = resultclass.getDeclaredMethods();
                if (methods != null) {
                    for (Method m : methods) {
                        if (dumpMethodCode_method != null) {
                            try {
                               dumpMethodCode_method.invoke(null, m);
                             } catch (Exception e) {
                                e.printStackTrace();
                                continue;
                            } catch (Error e) {
                                e.printStackTrace();
                                continue;
                            } 
                        } else {
                            Log.e("ActivityThread", "dumpMethodCode_method is null ");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            } catch (Error e) {
                e.printStackTrace();
            } 
        }
    }
    

art\runtime\interpreter\interpreter.cc

  • 解释执行时dump 整体的dex
static inline JValue Execute(Thread* self, const DexFile::CodeItem* code_item,
                             ShadowFrame& shadow_frame, JValue result_register) {
                                 
            
    //ADD END 这里是解释执行模式,art虚拟机的clinit方法一定会走这里,但是其他的oat优化的方法 不一定会走这里。
  if(strstr(PrettyMethod(shadow_frame.GetMethod()).c_str(),"<clinit>")!=nullptr)
  {
  //在执行类初始化方法的时候 整体dump , 由于类加载的多,所以这里应该会dump多次
      dumpDexFileByExecute(shadow_frame.GetMethod());
      }
    //ADD END
    *******

}
      

art\runtime\native\dalvik_system_DexFile.cc

  • 增加DexFile_dumpMethodCode ,在ACtivity oncreate时,主动遍历所有方法,调用此方法dump
  • dumpDexFileByExecute 实现,在解释执行时整体的dump
//addfunction
static void DexFile_dumpMethodCode(JNIEnv* env, jclass,jobject method) {
ScopedFastNativeObjectAccess soa(env);
  if(method!=nullptr)
  {
          ArtMethod* artmethod = ArtMethod::FromReflectedMethod(soa, method);
          myfartInvoke(artmethod);
      }   


  return;
}

//addfunction

art\runtime\art_method.cc 主要逻辑

  • ArtMethod::Invoke 时,根据标示Thread=null, dumpArtMethod
  • 主动调用 myfartInvoke 实现,主要进行ArtMethod的Invoke调用,但是在invoke的时候根据标示Thread *self = nullptr; 进行dump
  • 在dumpArtMethod时,再次整体dump了dex,虽然dump了整体的dex,但是抽取壳,可能函数体还是空的,所以会进行codeitem的dump
  • dumpArtMethod生成bin文件
    void ArtMethod::Invoke(Thread * self, uint32_t * args,
                   1. uint32_t args_size, JValue * result,
                   const char *shorty) {

        //ADD self等于null的时候 是自己调用的,dump方法
        if (self == nullptr) {
            dumpArtMethod(this);
            return;
        }
        //ADD END
        *******
    }
    
    //导出 myfartInvoke 在DexFile_dumpMethodCode 调用
    extern "C" void myfartInvoke(ArtMethod * artmethod)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
        JValue *result = nullptr;
        Thread *self = nullptr;//nullptr 标示 主动调用 不执行代码逻辑,只进行方法的dump
        uint32_t temp = 6;
        uint32_t *args = &temp;
        uint32_t args_size = 6;
        artmethod->Invoke(self, args, args_size, result, "fart");
    }
    
    //计算有异常的codeitem长度
    uint8_t *codeitem_end(const uint8_t ** pData) {
        uint32_t num_of_list = DecodeUnsignedLeb128(pData);
        for (; num_of_list > 0; num_of_list--) {
            int32_t num_of_handlers =
                DecodeSignedLeb128(pData);
            int num = num_of_handlers;
            if (num_of_handlers <= 0) {
                num = -num_of_handlers;
            }
            for (; num > 0; num--) {
                DecodeUnsignedLeb128(pData);
                DecodeUnsignedLeb128(pData);
            }
            if (num_of_handlers <= 0) {
                DecodeUnsignedLeb128(pData);
            }
        }
        return (uint8_t *) (*pData);
    }

    //将code item 进行base64的输出,方便阅读
    extern "C" char *base64_encode(char *str, long str_len,
                       long *outlen) {
        long len;
        char *res;
        int i, j;
        const char *base64_table =
            "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        if (str_len % 3 == 0)
            len = str_len / 3 * 4;
        else
            len = (str_len / 3 + 1) * 4;

        res = (char *) malloc(sizeof(char) * (len + 1));
        res[len] = '\0';
        *outlen = len;
        for (i = 0, j = 0; i < len - 2; j += 3, i += 4) {
            res[i] = base64_table[str[j] >> 2];
            res[i + 1] =
                base64_table[(str[j] & 0x3) << 4 |
                     (str[j + 1] >> 4)];
            res[i + 2] =
                base64_table[(str[j + 1] & 0xf) << 2 |
                     (str[j + 2] >> 6)];
            res[i + 3] = base64_table[str[j + 2] & 0x3f];
        }

        switch (str_len % 3) {
        case 1:
            res[i - 2] = '=';
            res[i - 1] = '=';
            break;
        case 2:
            res[i - 1] = '=';
            break;
        }

        return res;
    }
    
    //整体dump d_dexfile_execute.dex 调用时机在解释器解释执行类cliniT的时候
    extern "C" void dumpDexFileByExecute(ArtMethod * artmethod)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
        char *dexfilepath = (char *) malloc(sizeof(char) * 2000);
        if (dexfilepath == nullptr) {
            LOG(INFO) <<
                "ArtMethod::dumpDexFileByExecute,methodname:"
                << PrettyMethod(artmethod).
                c_str() << "malloc 2000 byte failed";
            return;
        }
        int fcmdline = -1;
        char szCmdline[64] = { 0 };
        char szProcName[256] = { 0 };
        int procid = getpid();
        sprintf(szCmdline, "/proc/%d/cmdline", procid);
        fcmdline = open(szCmdline, O_RDONLY, 0644);
        if (fcmdline > 0) {
            read(fcmdline, szProcName, 256);
            close(fcmdline);
        }

        if (szProcName[0]) {

            const DexFile *dex_file = artmethod->GetDexFile();
            const uint8_t *begin_ = dex_file->Begin();  // Start of data.
            size_t size_ = dex_file->Size();    // Length of data.

            memset(dexfilepath, 0, 2000);
            int size_int_ = (int) size_;

            memset(dexfilepath, 0, 2000);
            sprintf(dexfilepath, "%s", "/sdcard/fart");
            mkdir(dexfilepath, 0777);

            memset(dexfilepath, 0, 2000);
            sprintf(dexfilepath, "/sdcard/fart/%s",
                szProcName);
            mkdir(dexfilepath, 0777);

            memset(dexfilepath, 0, 2000);
            sprintf(dexfilepath,
                "/sdcard/fart/%s/%d_dexfile_execute.dex",
                szProcName, size_int_);
            int dexfilefp = open(dexfilepath, O_RDONLY, 0666);
            if (dexfilefp > 0) {
                close(dexfilefp);
                dexfilefp = 0;

            } else {
                dexfilefp =
                    open(dexfilepath, O_CREAT | O_RDWR,
                     0666);
                if (dexfilefp > 0) {
                    write(dexfilefp, (void *) begin_,
                          size_);
                    fsync(dexfilefp);
                    close(dexfilefp);
                }


            }


        }

        if (dexfilepath != nullptr) {
            free(dexfilepath);
            dexfilepath = nullptr;
        }

    }
    //主动调用了invoke,如果壳在这个时机,将代码还原,那么将可以dumP出method
    //方法的code-item dump
    //在这里进行了_dexfile.dex的dump
    extern "C" void dumpArtMethod(ArtMethod * artmethod)
     SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
        char *dexfilepath = (char *) malloc(sizeof(char) * 2000);
        if (dexfilepath == nullptr) {
            LOG(INFO) <<
                "ArtMethod::dumpArtMethodinvoked,methodname:"
                << PrettyMethod(artmethod).
                c_str() << "malloc 2000 byte failed";
            return;
        }
        int fcmdline = -1;
        char szCmdline[64] = { 0 };
        char szProcName[256] = { 0 };
        int procid = getpid();
        sprintf(szCmdline, "/proc/%d/cmdline", procid);
        fcmdline = open(szCmdline, O_RDONLY, 0644);
        if (fcmdline > 0) {
            read(fcmdline, szProcName, 256);
            close(fcmdline);
        }

        if (szProcName[0]) {

            const DexFile *dex_file = artmethod->GetDexFile();
            const char *methodname =
                PrettyMethod(artmethod).c_str();
            const uint8_t *begin_ = dex_file->Begin();
            size_t size_ = dex_file->Size();

            memset(dexfilepath, 0, 2000);
            int size_int_ = (int) size_;

            memset(dexfilepath, 0, 2000);
            sprintf(dexfilepath, "%s", "/sdcard/fart");
            mkdir(dexfilepath, 0777);

            memset(dexfilepath, 0, 2000);
            sprintf(dexfilepath, "/sdcard/fart/%s",
                szProcName);
            mkdir(dexfilepath, 0777);

            memset(dexfilepath, 0, 2000);
            sprintf(dexfilepath,
                "/sdcard/fart/%s/%d_dexfile.dex",//dump整体的dex
                szProcName, size_int_);
            int dexfilefp = open(dexfilepath, O_RDONLY, 0666);
            if (dexfilefp > 0) {
                close(dexfilefp);
                dexfilefp = 0;

            } else {
                dexfilefp =
                    open(dexfilepath, O_CREAT | O_RDWR,
                     0666);
                if (dexfilefp > 0) {
                    write(dexfilefp, (void *) begin_,
                          size_);
                    fsync(dexfilefp);
                    close(dexfilefp);
                }


            }
            const DexFile::CodeItem * code_item =
                artmethod->GetCodeItem();
            if (LIKELY(code_item != nullptr)) {
                int code_item_len = 0;//这里计算code item的长度
                uint8_t *item = (uint8_t *) code_item;
                if (code_item->tries_size_ > 0) {//有异常的计算方式要加上try catch的长度
                    const uint8_t *handler_data =
                        (const uint8_t *) (DexFile::
                                   GetTryItems
                                   (*code_item,
                                code_item->
                                tries_size_));
                    uint8_t *tail =
                        codeitem_end(&handler_data);
                    code_item_len =
                        (int) (tail - item);
                } else {//没有try catch 
                    code_item_len =
                        16 +
                        code_item->
                        insns_size_in_code_units_ * 2;
                }
                memset(dexfilepath, 0, 2000);
                int size_int = (int) dex_file->Size();  // Length of data
                uint32_t method_idx =
                    artmethod->get_method_idx();
                sprintf(dexfilepath,
                    "/sdcard/fart/%s/%d_%ld.bin",//生成BIN文件。
                    szProcName, size_int, gettidv1());
                int fp2 =
                    open(dexfilepath,
                     O_CREAT | O_APPEND | O_RDWR,
                     0666);
                if (fp2 > 0) {
                    lseek(fp2, 0, SEEK_END);
                    memset(dexfilepath, 0, 2000);
                    int offset = (int) (item - begin_);
                    sprintf(dexfilepath,
                        "{name:%s,method_idx:%d,offset:%d,code_item_len:%d,ins:",
                        methodname, method_idx,
                        offset, code_item_len);
                    int contentlength = 0;
                    while (dexfilepath[contentlength]
                           != 0)
                        contentlength++;
                    write(fp2, (void *) dexfilepath,
                          contentlength);
                    long outlen = 0;
                    char *base64result =
                        base64_encode((char *) item,
                              (long)
                              code_item_len,
                              &outlen);
                    write(fp2, base64result, outlen);
                    write(fp2, "};", 2);
                    fsync(fp2);
                    close(fp2);
                    if (base64result != nullptr) {
                        free(base64result);
                        base64result = nullptr;
                    }
                }

            }


        }

        if (dexfilepath != nullptr) {
            free(dexfilepath);
            dexfilepath = nullptr;
        }

    }
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 196,099评论 5 462
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 82,473评论 2 373
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 143,229评论 0 325
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,570评论 1 267
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,427评论 5 358
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,335评论 1 273
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,737评论 3 386
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,392评论 0 254
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,693评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,730评论 2 312
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,512评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,349评论 3 314
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,750评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,017评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,290评论 1 251
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,706评论 2 342
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,904评论 2 335

推荐阅读更多精彩内容