Xianjian Bao

14 papers Journal 7Unranked 7
YearRankTypeTitle / Venue / Authors
2025 conf
ICIC (5)
Rui Ling, Yunfei Yin, Xianjian Bao
2025 J jnl
IEEE Trans. Knowl. Data Eng.
Yunfei Yin, Yiming Pan, Xianjian Bao, Faliang Huang
2025 J jnl
CoRR
Zhiwen Zeng, Yunfei Yin, Zheng Yuan, Argho Dey, Xianjian Bao
2025 J jnl
IEEE Trans. Artif. Intell.
Yunfei Yin, Zheng Yuan, Yu He, Xianjian Bao
2024 J jnl
Eng. Appl. Artif. Intell.
Yunfei Yin, Zhiling Chen, Xianjian Bao
2024 J jnl
BioData Min.
Yunfei Yin, Zheng Yuan, Md Tanvir Islam, Xianjian Bao
2024 conf
LREC/COLING
Yunfei Yin, Congrui Zou, Zheng Yuan, Xianjian Bao
2024 conf
ITSC
Xiaoqin Wang, Yunfei Yin, Caizhi Zhang, Xianjian Bao
2024 conf
BIBM
Yunfei Yin, Zheng Yuan, Zhiwei Yuan, Xianjian Bao
2024 J jnl
Expert Syst. Appl.
Yunfei Yin, Jiameng Wang, Himo Arnob Barua, Xianjian Bao
2023 J jnl
IEEE Trans. Intell. Transp. Syst.
Hao Ran, Yunfei Yin, Faliang Huang, Xianjian Bao
2023 conf
ITSC
Xiaoqin Wang, Yunfei Yin, Faliang Huang, Xianjian Bao
2023 conf
ITSC
Yunfei Yin, Tingli Kou, Nyambega D. Ochieng, Xianjian Bao
2022 conf
ITSC
Hao Ran, Yunfei Yin, Faliang Huang, Xianjian Bao
redb/extractors/decompiler/_archive/ghidra-test.py
← Index redb/extractors/decompiler/_archive/ghidra-test.py python
import subprocess
import json
import os
import tempfile
import uuid
import shutil
import sys
import time


def run_command(cmd, env=None):
    try:
        print(f"Starting command: {' '.join(cmd)}")
        start_time = time.time()
        process = subprocess.Popen(
            cmd, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True
        )

        while True:
            output = process.stdout.readline()
            if output:
                print(output.strip())
            if process.poll() is not None:
                break

        stdout, stderr = process.communicate()
        end_time = time.time()

        print(f"Command finished. Execution time: {end_time - start_time:.2f} seconds")
        print(f"Return code: {process.returncode}")

        if process.returncode != 0:
            print(f"Error output:\n{stderr}")
            return None
        return stdout
    except Exception as e:
        print(f"Error running command {' '.join(cmd)}: {e}")
        return None


def analyze_binary(ghidra_path, binary_path, java_script_path):
    print(f"Ghidra path: {ghidra_path}")
    print(f"Binary path: {binary_path}")
    print(f"Java script path: {java_script_path}")

    # Check if Java script exists
    if not os.path.exists(java_script_path):
        print(f"Error: Java script not found at {java_script_path}")
        return None

    # Set up environment variables
    env = os.environ.copy()
    java_home = "/usr/lib/jvm/java-17-openjdk-amd64"  # Adjust this path if needed
    env["JAVA_HOME"] = java_home
    env["PATH"] = f"{java_home}/bin:{env['PATH']}"
    env["LD_LIBRARY_PATH"] = f"{java_home}/lib:{env.get('LD_LIBRARY_PATH', '')}"

    # Print environment variables for debugging
    print(f"JAVA_HOME: {env['JAVA_HOME']}")
    print(f"PATH: {env['PATH']}")
    print(f"LD_LIBRARY_PATH: {env['LD_LIBRARY_PATH']}")

    # Check Ghidra installation
    analyzeHeadless_path = f"{ghidra_path}/support/analyzeHeadless"
    print(f"analyzeHeadless exists: {os.path.exists(analyzeHeadless_path)}")

    print(f"Binary file exists: {os.path.exists(binary_path)}")

    # Check Java
    java_version = run_command(["java", "-version"], env=env)
    print(f"Java version: {java_version}")

    # Create a temporary project directory
    project_path = tempfile.gettempdir() + "/ghidra_" + str(uuid.uuid4())
    os.makedirs(project_path, exist_ok=True)
    print(f"Created temporary project path: {project_path}")
    output_file = ""

    try:
        # Run Ghidra's headless analyzer
        analyze_cmd = [
            analyzeHeadless_path,
            project_path,
            "TempProject",
            "-import",
            binary_path,
            "-postScript",
            java_script_path,
            "-deleteProject",
        ]

        result = run_command(analyze_cmd, env=env)
        if result is None:
            return None

        # Read the output JSON file
        output_file = "ghidra_output.json"
        if os.path.exists(output_file):
            with open(output_file, "r") as f:
                functions = json.load(f)
            return functions
        else:
            print(
                f"Output file {output_file} not found. Ghidra analysis may have failed."
            )
            # List files in the current directory
            print("Files in the current directory:")
            print("\n".join(os.listdir(".")))
            return None
    finally:
        # Clean up
        if os.path.exists(output_file):
            os.remove(output_file)
        if os.path.exists(project_path):
            shutil.rmtree(project_path)


# Example usage
if __name__ == "__main__":
    # if len(sys.argv) != 4:
    #     print("Usage: python script.py <ghidra_path> <binary_path> <java_script_path>")
    #     sys.exit(1)

    # ghidra_path = sys.argv[1]
    # binary_path = sys.argv[2]
    # java_script_path = sys.argv[3]

    ghidra_path = "/opt/ghidra"
    binary_path = "/home/p4c0/dev/redb/test_files/hello"
    java_script_path = (
        "/opt/ghidra/Ghidra/Features/Base/ghidra_scripts/GhidraDecompilerScript.java"
    )

    functions = analyze_binary(ghidra_path, binary_path, java_script_path)

    if functions:
        print(f"Extracted functions from {binary_path}:")
        for func in functions:
            print(f"\nFunction: {func['name']}")
            print(f"Address: {func['address']}")
            print(f"Decompiled code:\n{func['decompiled']}")
    else:
        print("Failed to extract functions.")