Skip to main content
Glama

ida_rename_multi_local_variables

Rename multiple local variables simultaneously within a specified function in IDA Pro to improve code readability and maintain consistency during reverse engineering analysis.

Instructions

Rename multiple local variables within a function at once in the IDA database

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
function_nameYes
rename_pairs_old2newYes

Implementation Reference

  • Core handler that implements the tool logic: iterates over rename pairs, calls single rename internal function for each, collects success/failure stats.
    def rename_multi_local_variables(self, function_name: str, rename_pairs_old2new: List[Dict[str, str]]) -> Dict[str, Any]:
        """Rename multiple local variables within a function at once"""
        try:
            success_count: int = 0
            failed_pairs: List[Dict[str, str]] = []
    
            for pair in rename_pairs_old2new:
                old_name = next(iter(pair.keys()))
                new_name = pair[old_name]
                
                # Call existing rename_local_variable_internal for each pair
                result = self._rename_local_variable_internal(function_name, old_name, new_name)
                
                if result.get("success", False):
                    success_count += 1
                else:
                    failed_pairs.append({
                        "old_name": old_name,
                        "new_name": new_name,
                        "error": result.get("message", "Unknown error")
                    })
    
            return {
                "success": True,
                "message": f"Renamed {success_count} out of {len(rename_pairs_old2new)} local variables",
                "success_count": success_count,
                "failed_pairs": failed_pairs
            }
    
        except Exception as e:
            print(f"Error in rename_multi_local_variables: {str(e)}")
            traceback.print_exc()
            return {
                "success": False,
                "message": str(e),
                "success_count": 0,
                "failed_pairs": rename_pairs_old2new
            }
  • Supporting function that performs the actual single local variable rename using IDA Hex-Rays decompiler API: decompiles function, finds lvar, calls ida_hexrays.rename_lvar.
    def _rename_local_variable_internal(self, function_name: str, old_name: str, new_name: str) -> Dict[str, Any]:
        """Internal implementation for rename_local_variable without sync wrapper"""
        try:
            # Parameter validation
            if not function_name:
                return {"success": False, "message": "Function name cannot be empty"}
            if not old_name:
                return {"success": False, "message": "Old variable name cannot be empty"}
            if not new_name:
                return {"success": False, "message": "New variable name cannot be empty"}
            
            # Get function address
            func_addr: int = ida_name.get_name_ea(0, function_name)
            if func_addr == idaapi.BADADDR:
                return {"success": False, "message": f"Function '{function_name}' not found"}
            
            # Check if it's a function
            func: Optional[ida_funcs.func_t] = ida_funcs.get_func(func_addr)
            if not func:
                return {"success": False, "message": f"'{function_name}' is not a function"}
            
            # Check if decompiler is available
            if not ida_hexrays.init_hexrays_plugin():
                return {"success": False, "message": "Hex-Rays decompiler is not available"}
            
            # Get decompilation result
            cfunc: Optional[ida_hexrays.cfunc_t] = ida_hexrays.decompile(func_addr)
            if not cfunc:
                return {"success": False, "message": f"Failed to decompile function '{function_name}'"}
            
            ida_hexrays.open_pseudocode(func_addr, 0)
            
            # Find local variable to rename
            found: bool = False
            renamed: bool = False
            lvar: Optional[ida_hexrays.lvar_t] = None
            
            # Iterate through all local variables
            lvars = cfunc.get_lvars()
            for i in range(lvars.size()):
                v = lvars[i]
                if v.name == old_name:
                    lvar = v
                    found = True
                    break
            
            if not found:
                return {"success": False, "message": f"Local variable '{old_name}' not found in function '{function_name}'"}
            
            # Rename local variable
            if ida_hexrays.rename_lvar(cfunc.entry_ea, lvar.name, new_name):
                renamed = True
            
            if renamed:
                # Refresh view
                self._refresh_view_internal()
                return {"success": True, "message": f"Local variable renamed from '{old_name}' to '{new_name}' in function '{function_name}'"}
            else:
                return {"success": False, "message": f"Failed to rename local variable from '{old_name}' to '{new_name}', possibly due to invalid name format or other IDA restrictions"}
        
        except Exception as e:
            print(f"Error renaming local variable: {str(e)}")
            traceback.print_exc()
            return {"success": False, "message": str(e)}
  • Pydantic schema defining input for the MCP tool: function name and list of old-to-new name pairs.
    class RenameMultiLocalVariables(BaseModel):
        function_name: str
        rename_pairs_old2new: List[Dict[str, str]]  # List of dictionaries with "old_name" and "new_name" keys
  • MCP tool registration in @server.list_tools(): defines name, description, and input schema.
    Tool(
        name=IDATools.RENAME_MULTI_LOCAL_VARIABLES,
        description="Rename multiple local variables within a function at once in the IDA database",
        inputSchema=RenameMultiLocalVariables.schema(),
    ),
  • Dispatch/registration in IDA socket server: handles 'rename_multi_local_variables' request type by calling core handler.
    elif request_type == "rename_multi_local_variables":
        response.update(self.core.rename_multi_local_variables(
            request_data.get("function_name", ""),
            request_data.get("rename_pairs_old2new", [])
        ))

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/MxIris-Reverse-Engineering/ida-mcp-server'

If you have feedback or need assistance with the MCP directory API, please join our Discord server