o
    i                     @   sJ   d dl mZ d dlmZ d dlmZ ddlmZ ee	Z
ejZdd ZdS )	    )iast_compiling_debug_log)
get_logger)config   )astpatch_modulec                 C   s(  d}d}t r zt|\}}W n ty   tddd d}Y nw |r<zt||d}W n ty;   tddd d}Y nw |retd|  z	t||j W dS  tyd   tddd | j	| Y dS w | jdurztd	|  | j	| W dS  t
y   td
dd Y dS w td|  dS )a  Execute a Python module with IAST (Interactive Application Security Testing) instrumentation.

    This function performs dynamic code transformation using AST (Abstract Syntax Tree) patching
    to inject security vulnerability detection capabilities into Python modules at runtime.
    It's a core component of the IAST engine that enables taint tracking and vulnerability
    detection without modifying the original source code.

    How it works:
    1. Attempts to patch the module's AST using astpatch_module()
    2. If successful, compiles the patched AST into executable bytecode
    3. Executes the instrumented bytecode instead of the original module
    4. Falls back to executing the original module if patching fails

    Runtime Considerations:
    - The AST analysis could yield unexpected or incorrect results when analyzing
      code that overwrites built-in or global names at runtime
    - A notable example is `mysqlsh` (MySQL Shell), which reassigns `globals` with
      something like: `globals = ShellGlobals()`. Since `globals` is a built-in
      function in Python, reassigning it alters the global namespace's behavior
      during analysis. This can cause dynamic instrumentation, taint tracking,
      or symbol resolution to behave incorrectly or inconsistently
    - The function gracefully handles compilation and execution errors by falling
      back to the original module execution
    - All exceptions during patching are logged but don't prevent module execution
    Nz'Unexpected exception while AST patchingT)exc_infoexecz1Unexpected exception while compiling patched codezINSTRUMENTED CODE. executing z'INSTRUMENTED CODE. Unexpected exceptionzDEFAULT CODE. executing z.Unexpected exception on import loader fallbackz6Module loader is not available, cannot execute module )IS_IAST_ENABLEDr   	Exceptionr   compiler   __dict__	TypeErrorloaderexec_moduleImportError)module_watchdogmodulepatched_astcompiled_codemodule_path r   P/home/ubuntu/.local/lib/python3.10/site-packages/ddtrace/appsec/_iast/_loader.py_exec_iast_patched_module   s@   
r   N)ddtrace.appsec._iast._logsr   ddtrace.internal.loggerr   ddtrace.internal.settings.asmr   
asm_config_ast.ast_patchingr   __name__log_iast_enabledr	   r   r   r   r   r   <module>   s    