Skip to main content
Glama

ida_get_global_variable_by_address

Retrieve global variable information from IDA database using memory address to analyze binary code structure and data references.

Instructions

Get information about a global variable by address

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
addressYes

Implementation Reference

  • Core handler implementation in IDA plugin that retrieves global variable information (name, segment, type, size, value, string content if applicable) using IDA Pro APIs.
    def get_global_variable_by_address(self, address: int) -> Dict[str, Any]:
        """Get global variable information by its address"""
        return self._get_global_variable_by_address_internal(address)
    
    def _get_global_variable_by_address_internal(self, address: int) -> Dict[str, Any]:
        """Internal implementation for get_global_variable_by_address without sync wrapper"""
        try:
            # Verify address is valid
            if address == idaapi.BADADDR:
                return {"error": f"Invalid address: {hex(address)}"}
            
            # Get variable name if available
            variable_name = ida_name.get_name(address)
            if not variable_name:
                variable_name = f"unnamed_{hex(address)}"
            
            # Get variable segment
            segment: Optional[ida_segment.segment_t] = ida_segment.getseg(address)
            if not segment:
                return {"error": f"No segment found for address {hex(address)}"}
            
            segment_name: str = ida_segment.get_segm_name(segment)
            segment_class: str = ida_segment.get_segm_class(segment)
            
            # Get variable type
            tinfo = idaapi.tinfo_t()
            guess_type: bool = idaapi.guess_tinfo(tinfo, address)
            type_str: str = tinfo.get_type_name() if guess_type else "unknown"
            
            # Try to get variable value
            size: int = ida_bytes.get_item_size(address)
            if size <= 0:
                size = 8  # Default to 8 bytes
            
            # Read data based on size
            value: Optional[int] = None
            if size == 1:
                value = ida_bytes.get_byte(address)
            elif size == 2:
                value = ida_bytes.get_word(address)
            elif size == 4:
                value = ida_bytes.get_dword(address)
            elif size == 8:
                value = ida_bytes.get_qword(address)
            
            # Build variable info
            var_info: Dict[str, Any] = {
                "name": variable_name,
                "address": hex(address),
                "segment": segment_name,
                "segment_class": segment_class,
                "type": type_str,
                "size": size,
                "value": hex(value) if value is not None else "N/A"
            }
            
            # If it's a string, try to read string content
            if ida_bytes.is_strlit(ida_bytes.get_flags(address)):
                str_value = idc.get_strlit_contents(address, -1, 0)
                if str_value:
                    try:
                        var_info["string_value"] = str_value.decode('utf-8', errors='replace')
                    except:
                        var_info["string_value"] = str(str_value)
            
            return {"variable_info": json.dumps(var_info, indent=2)}
        except Exception as e:
            print(f"Error getting global variable by address: {str(e)}")
            traceback.print_exc()
            return {"error": str(e)}
  • MCP server handler that converts address to int, sends socket request to IDA plugin, processes response, and formats output string.
    def get_global_variable_by_address(self, address: str) -> str:
        """Get global variable information by its address"""
        try:
            # Convert string address to int
            try:
                addr_int = int(address, 16) if address.startswith("0x") else int(address)
            except ValueError:
                return f"Error: Invalid address format '{address}', expected hexadecimal (0x...) or decimal"
                
            response: Dict[str, Any] = self.communicator.send_request(
                "get_global_variable_by_address", 
                {"address": addr_int}
            )
            
            if "error" in response:
                return f"Error retrieving global variable at address '{address}': {response['error']}"
            
            variable_info: Any = response.get("variable_info")
            
            # Verify variable_info is string type
            if variable_info is None:
                return f"Error: No variable info returned for address '{address}'"
            if not isinstance(variable_info, str):
                self.logger.warning(f"Variable info type is not string but {type(variable_info).__name__}, attempting conversion")
                try:
                    # If it's a dictionary, convert to JSON string first
                    if isinstance(variable_info, dict):
                        variable_info = json.dumps(variable_info, indent=2)
                    else:
                        variable_info = str(variable_info)
                except Exception as e:
                    return f"Error: Failed to convert variable info to string: {str(e)}"
            
            # Try to extract the variable name from the JSON for a better message
            var_name = "Unknown"
            try:
                var_info_dict = json.loads(variable_info)
                if isinstance(var_info_dict, dict) and "name" in var_info_dict:
                    var_name = var_info_dict["name"]
            except:
                pass
            
            return f"Global variable '{var_name}' at address {address}:\n{variable_info}"
        except Exception as e:
            self.logger.error(f"Error getting global variable by address: {str(e)}", exc_info=True)
            return f"Error retrieving global variable at address '{address}': {str(e)}"
  • Pydantic model defining input schema: address as string (hexadecimal).
    class GetGlobalVariableByAddress(BaseModel):
        address: str  # Hexadecimal address as string
  • MCP tool registration in list_tools() with name, description, and input schema.
    Tool(
        name=IDATools.GET_GLOBAL_VARIABLE_BY_ADDRESS,
        description="Get information about a global variable by address",
        inputSchema=GetGlobalVariableByAddress.schema(),
    ),
  • Socket request dispatch in IDA plugin that maps 'get_global_variable_by_address' to core handler call.
    elif request_type == "get_global_variable_by_address":
        response.update(self.core.get_global_variable_by_address(request_data.get("address", 0)))

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