Advertisement
Python253

disassembler

Mar 12th, 2024 (edited)
625
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.73 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. # Filename: disassembler.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6. # For use with example_functions.py: https://pastebin.com/edit/vhDzGwHQ
  7.  
  8. """
  9. Python Disassembler Script
  10.  
  11. This Python script provides a tool for dynamically disassembling functions within a specified Python script.
  12. It aims to assist developers in inspecting the bytecode of functions to better understand their internal workings.
  13. The script dynamically generates disassembler code for each function found in the target script and saves the output to a text file.
  14.  
  15. Requirements:
  16. - Python 3
  17.  
  18. Usage:
  19. 1. Ensure the target Python script is in the current working directory and has a '.py' extension.
  20. 2. Run the 'disassembler.py' script in a terminal or command prompt.
  21. 3. Enter the name of the target script (without the '.py' extension) when prompted.
  22. 4. The script will check if the target script exists. If not, it will create an 'example.py' script with predefined functions.
  23. 5. The script will then generate disassembler code for each function in the target script and save the output to a text file named '<script_name>_disassembled.txt'.
  24. 6. View the list of functions and their disassembled bytecode in the terminal, and find the detailed output in the generated text file.
  25. """
  26.  
  27. import os
  28. import sys
  29. import dis
  30. import inspect
  31.  
  32. def get_functions_from_script(script_path):
  33.     """
  34.    Extracts the list of functions from the specified Python script.
  35.  
  36.    Parameters:
  37.    - script_path (str): The path to the Python script.
  38.  
  39.    Returns:
  40.    - list: A list of function names found in the script.
  41.    """
  42.     functions = []
  43.     with open(script_path, 'r', encoding='utf-8') as script_file:
  44.         script_content = script_file.read()
  45.         script_module = compile(script_content, script_path, 'exec')
  46.         for item in script_module.co_consts:
  47.             if inspect.iscode(item):
  48.                 functions.append(item.co_name)
  49.     return functions
  50.  
  51. def disassemble_functions(script_path, functions, output_file):
  52.     """
  53.    Generates disassembler code for each function in the specified script and saves the output to a text file.
  54.  
  55.    Parameters:
  56.    - script_path (str): The path to the Python script.
  57.    - functions (list): A list of function names.
  58.    - output_file (str): The path to the output text file.
  59.    """
  60.     with open(script_path, 'r', encoding='utf-8') as script_file:
  61.         script_content = script_file.read()
  62.         script_module = compile(script_content, script_path, 'exec')
  63.         with open(output_file, 'w', encoding='utf-8') as output:
  64.             sys.stdout = output  # Redirect stdout to the output file
  65.             for item in script_module.co_consts:
  66.                 if inspect.iscode(item) and item.co_name in functions:
  67.                     print(f"\nDisassembly for function '{item.co_name}':")
  68.                     dis.dis(item)
  69.             sys.stdout = sys.__stdout__  # Reset stdout to its original value
  70.  
  71. def create_example_script(script_path):
  72.     """
  73.    Creates an example Python script with predefined functions if the specified script is not found.
  74.  
  75.    Parameters:
  76.    - script_path (str): The path to the Python script.
  77.    """
  78.     with open(script_path, 'w', encoding='utf-8') as example_file:
  79.         example_file.write("""
  80. # example.py
  81.  
  82. def print_hello_world():
  83.    print("Hello, World!")
  84.  
  85. def print_hello_world_uppercase():
  86.    print("HELLO, WORLD!")
  87.  
  88. def print_hello_world_reverse():
  89.    print("dlroW ,olleH"[::-1])
  90.  
  91. if __name__ == "__main__":
  92.    print_hello_world()
  93.    print_hello_world_uppercase()
  94.    print_hello_world_reverse()
  95. """)
  96.  
  97. def main():
  98.     """
  99.    The main function that orchestrates the execution of the disassembler script.
  100.    """
  101.     cwd = os.getcwd()
  102.  
  103.     # Assume the script is in the cwd and has a .py extension edit "example" below to the name of your file.
  104.     script_name = "example_functions"
  105.     script_path = os.path.join(cwd, f"{script_name}.py")
  106.     output_file = os.path.join(cwd, f"{script_name}_disassembled.txt")
  107.    
  108.     # Create Hello World Example Script To Disassemble If No File Is Found
  109.     if not os.path.exists(script_path):
  110.         print(f"Error: Script '{script_name}.py' not found in the current working directory.\nCreating Example Script...")
  111.         create_example_script(script_path)
  112.  
  113.     functions = get_functions_from_script(script_path)
  114.  
  115.     if not functions:
  116.         print("No functions found in the script.")
  117.         return
  118.  
  119.     print("List of functions in the script:")
  120.     for function in functions:
  121.         print(f"- {function}")
  122.  
  123.     disassemble_functions(script_path, functions, output_file)
  124.     print(f"\nDisassembled output saved to '{output_file}'.")
  125.  
  126. if __name__ == "__main__":
  127.     main()
  128.  
  129.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement