使用sa-jdi.jar dump 記憶體中的class

來源:互聯網
上載者:User

標籤:分享圖片   輸出   利用   window   src   att   介紹   alt   with   

前言

在分析一個 jar 包時發現他把關鍵類採用了運行時使用 classloader 的方式載入了。懶得分析演算法了,可以使用 jdk 內建的工具 dump 出需要的class.

本文

從啟動並執行java進程裡dump出運行中的類的class檔案的方法,所知道的有兩種

  • 用agent attatch 到進程,然後利用 Instrumentation和 ClassFileTransformer就可以擷取 到類的位元組碼了。

  • 使用 sd-jdi.jar裡的工具

本文介紹的就是使用 sd-jdi.jar 來dump. sd-jdi.jar裡內建的的 sun.jvm.hotspot.tools.jcore.ClassDump 可以把類的class內容dump到檔案裡。

ClassDump 裡可以設定兩個 System properties

  • sun.jvm.hotspot.tools.jcore.filter Filter的類名
  • sun.jvm.hotspot.tools.jcore.outputDir 輸出的目錄
樣本

首先寫一個 filter

import sun.jvm.hotspot.tools.jcore.ClassFilter;import sun.jvm.hotspot.oops.InstanceKlass;import sun.jvm.hotspot.tools.jcore.ClassDump;public class MyFilter implements ClassFilter {    @Override    public boolean canInclude(InstanceKlass kls) {        String klassName = kls.getName().asString();        return klassName.startsWith("com/fr/license/selector/");    }}  

代碼很顯而易見了, 作用是 dump 所有 以 com/fr/license/selector/ 開頭的 類的· 位元組碼。

然後編譯成class檔案

要使用這個首先需要把 sa-jdi.jar 加到 javaclasspath 裡。

進入 剛剛寫的 filter 類的class檔案的目錄下。執行

java  -Dsun.jvm.hotspot.tools.jcore.filter=MyFilter  -Dsun.jvm.hotspot.tools.jcore.outputDir=d:\dump  sun.jvm.hotspot.tools.jcore.ClassDump 5308

MyFilter 改為你自己的類名, 5308 為目標 java進程的 pid(可以使用 jps 查看)。然後就會在 d:\dump 產生相應的 class 檔案。

問題解決
  • 如果直接點擊應用的 exe, 來啟動應用,使用 jps 擷取到的 pid, 可能沒有辦法附加, 所以我們要找到啟動的命令, 比如 bat指令碼裡面。

  • 一般大型應用會內建 jre, 我們要使用上面的技術,替換 jre,為我們的,才能正常dump, 否則會出現版本不匹配。
  • windows下還需把 sawindbg.dll 放到 jre/bin/ 和java.exe 同目錄下。否則可能會遇到 載入不了這個 dll 的問題。

最後

搞java應用第一步還是找到啟動的命令,便於後面的分析。一般別使用 exe啟動應用

使用sa-jdi.jar dump 記憶體中的class

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.