//@category Vegvisir
import ghidra.app.script.GhidraScript;
import ghidra.program.model.symbol.*;

public class VegvisirSearchSymbols extends GhidraScript {
    private static String q(String s){ if(s==null)return"null"; StringBuilder b=new StringBuilder("\""); for(int i=0;i<s.length();i++){char c=s.charAt(i); switch(c){case '\\':b.append("\\\\");break;case '"':b.append("\\\"");break;case '\n':b.append("\\n");break;case '\r':b.append("\\r");break;case '\t':b.append("\\t");break;default: if(c<0x20)b.append(String.format("\\u%04x",(int)c)); else b.append(c);}} return b.append('"').toString(); }
    public void run() throws Exception { String[] args=getScriptArgs(); String needle=args.length>0?args[0]:""; int limit=args.length>1?Integer.parseInt(args[1]):100; boolean ci=args.length<=2 || Boolean.parseBoolean(args[2]); String n=ci?needle.toLowerCase():needle; SymbolIterator it=currentProgram.getSymbolTable().getSymbolIterator(true); StringBuilder out=new StringBuilder(); out.append("{\n  \"ok\": true,\n  \"query\": ").append(q(needle)).append(",\n  \"symbols\": [\n"); int total=0, emitted=0; while(it.hasNext()){ Symbol s=it.next(); String name=s.getName(true); String cmp=ci?name.toLowerCase():name; if(!cmp.contains(n))continue; total++; if(emitted>=limit)continue; if(emitted>0)out.append(",\n"); out.append("    {"); out.append("\"name\": ").append(q(name)).append(", "); out.append("\"address\": ").append(q(s.getAddress().toString())).append(", "); out.append("\"type\": ").append(q(s.getSymbolType().toString())).append(", "); out.append("\"source\": ").append(q(s.getSource().toString())); out.append("}"); emitted++; } out.append("\n  ],\n  \"emitted\": ").append(emitted).append(",\n  \"total\": ").append(total).append("\n}"); println("VEGVISIR_JSON:"+out.toString()); }
}
