summaryrefslogtreecommitdiffstats
path: root/userspace/cuda/tools/ghidra/ExportFunctionIndex.java
blob: c36f98f813578e304f97882ac73a2b3283d913fd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
// SPDX-License-Identifier: BSD-3-Clause
//
// ExportFunctionIndex.java - Ghidra post-script: dump a complete inventory of
// the analyzed program: functions, symbols (exports/imports), memory blocks
// and per-function references to interesting callees, plus the address of
// every function that is reachable from the exported CUDA entry points.
//
// This is the primary "map" artifact for a CUDA userspace driver version: it
// lets later tooling and analysis answer "what is at libcuda+0xNNNNNN" and
// "which internal function implements exported cuFoo".
//
// Usage (analyzeHeadless, on an already analyzed program):
//   -process <program> -noanalysis \
//     -postScript ExportFunctionIndex.java <outdir>
//
// Outputs (all TSV, one row per item, with a header row):
//   <outdir>/functions.tsv    addr  size  name  namespace  is_exported
//                             is_external  is_thunk  has_body  entry_bytes
//   <outdir>/exports.tsv      addr  size  name
//   <outdir>/imports.tsv      addr  name  library
//   <outdir>/blocks.tsv       name  start  end  size  r/w/x
//   <outdir>/callgraph.tsv    caller_addr  callee_addr  call_sites
//   <outdir>/strings.tsv      addr  length  string (first 200 chars)
//
// The callgraph is produced from Ghidra's reference model for call
// instructions inside each function body.

import ghidra.app.script.GhidraScript;
import ghidra.program.model.address.Address;
import ghidra.program.model.address.AddressSetView;
import ghidra.program.model.listing.Data;
import ghidra.program.model.listing.DataIterator;
import ghidra.program.model.listing.Function;
import ghidra.program.model.listing.FunctionIterator;
import ghidra.program.model.listing.Listing;
import ghidra.program.model.mem.MemoryBlock;
import ghidra.program.model.symbol.Reference;
import ghidra.program.model.symbol.ReferenceIterator;
import ghidra.program.model.symbol.Symbol;
import ghidra.program.model.symbol.SymbolIterator;
import ghidra.program.model.symbol.SymbolTable;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class ExportFunctionIndex extends GhidraScript {

    private PrintWriter open(String dir, String name) throws Exception {
        return new PrintWriter(new BufferedWriter(new FileWriter(dir + "/" + name)));
    }

    @Override
    public void run() throws Exception {
        String[] args = getScriptArgs();
        if (args.length < 1) {
            println("usage: ExportFunctionIndex.java <outdir>");
            return;
        }
        String outdir = args[0];
        new java.io.File(outdir).mkdirs();

        Listing listing = currentProgram.getListing();
        SymbolTable symtab = currentProgram.getSymbolTable();
        // Ghidra may load a PIE/shared object at a non-zero image base (this
        // build uses 0x100000). All *file virtual addresses* (what the public
        // docs cite as libcuda+0x...) are program addresses minus this base.
        long imageBase = currentProgram.getImageBase().getOffset();

        // ---- functions -------------------------------------------------------
        int nfunc = 0, nexport = 0, nexternal = 0;
        Map<Long, String> exported = new HashMap<>();
        try (PrintWriter w = open(outdir, "functions.tsv")) {
            w.println("addr\tfile_addr\tsize\tname\tnamespace\texported\texternal\tthunk\tbody");
            FunctionIterator fit = listing.getFunctions(true);
            while (fit.hasNext() && !monitor.isCancelled()) {
                Function f = fit.next();
                Address ep = f.getEntryPoint();
                boolean isExt = f.isExternal();
                boolean isThunk = f.isThunk();
                String ns = f.getParentNamespace() != null
                        ? f.getParentNamespace().getName(true) : "";
                String name = f.getName();
                long size = f.getBody().getNumAddresses();
                w.printf("0x%08x\t0x%08x\t%d\t%s\t%s\t%s\t%s\t%s\t%s%n",
                        ep.getOffset(), ep.getOffset() - imageBase, size, name, ns,
                        isExt ? "0" : (symtab.isExternalEntryPoint(ep) ? "1" : "0"),
                        isExt ? "1" : "0", isThunk ? "1" : "0",
                        size > 0 ? "1" : "0");
                nfunc++;
                if (!isExt) {
                    for (Symbol s : symtab.getSymbols(ep)) {
                        if (s.isExternalEntryPoint() || s.isGlobal()) {
                            exported.put(ep.getOffset(), s.getName(true));
                        }
                    }
                }
                if (isExt) nexternal++;
            }
        }

        // ---- exports: symbols flagged external-entry / global in .text ------
        // The loader marks ELF .dynsym definitions; enumerating them via the
        // symbol table is exact and independent of the function iterator.
        try (PrintWriter w = open(outdir, "exports.tsv")) {
            w.println("addr\tfile_addr\tsize\tname");
            SymbolIterator sit = symtab.getAllSymbols(true);
            while (sit.hasNext() && !monitor.isCancelled()) {
                Symbol s = sit.next();
                Address a = s.getAddress();
                if (a == null || !a.isMemoryAddress()) continue;
                if (!symtab.isExternalEntryPoint(a)) continue;
                Function f = listing.getFunctionAt(a);
                long size = f != null ? f.getBody().getNumAddresses() : 0;
                w.printf("0x%08x\t0x%08x\t%d\t%s%n", a.getOffset(), a.getOffset() - imageBase, size, s.getName(true));
                nexport++;
            }
        }

        // ---- imports: external functions and the library they come from ----
        try (PrintWriter w = open(outdir, "imports.tsv")) {
            w.println("addr\tfile_addr\tname\tlibrary");
            FunctionIterator fit = listing.getFunctions(true);
            while (fit.hasNext() && !monitor.isCancelled()) {
                Function f = fit.next();
                if (!f.isExternal()) continue;
                String lib = f.getParentNamespace() != null
                        ? f.getParentNamespace().getName(true) : "";
                w.printf("0x%08x\t0x%08x\t%s\t%s%n",
                        f.getEntryPoint().getOffset(),
                        f.getEntryPoint().getOffset() - imageBase, f.getName(), lib);
            }
        }

        // ---- memory blocks ---------------------------------------------------
        try (PrintWriter w = open(outdir, "blocks.tsv")) {
            w.println("name\tstart\tend\tsize\tr\tw\tx\tinitialized");
            for (MemoryBlock b : currentProgram.getMemory().getBlocks()) {
                w.printf("%s\t0x%08x\t0x%08x\t%d\t%s\t%s\t%s\t%s%n",
                        b.getName(), b.getStart().getOffset(), b.getEnd().getOffset(),
                        b.getSize(), b.isRead() ? "1" : "0", b.isWrite() ? "1" : "0",
                        b.isExecute() ? "1" : "0", b.isInitialized() ? "1" : "0");
            }
        }

        // ---- call graph ------------------------------------------------------
        // Function.getCalledFunctions() is the reliable API: it resolves both
        // direct calls and call-through references recorded by the analyzers,
        // independent of how the reference manager indexes them.
        int edges = 0;
        try (PrintWriter w = open(outdir, "callgraph.tsv")) {
            w.println("caller\tcallee\tcaller_file\tcallee_file");
            FunctionIterator fit = listing.getFunctions(true);
            while (fit.hasNext() && !monitor.isCancelled()) {
                Function f = fit.next();
                if (f.isExternal()) continue;
                for (Function callee : f.getCalledFunctions(monitor)) {
                    w.printf("0x%08x\t0x%08x\t0x%08x\t0x%08x%n",
                            f.getEntryPoint().getOffset(),
                            callee.getEntryPoint().getOffset(),
                            f.getEntryPoint().getOffset() - imageBase,
                            callee.getEntryPoint().getOffset() - imageBase);
                    edges++;
                }
            }
        }

        // ---- defined strings -------------------------------------------------
        int nstr = 0;
        try (PrintWriter w = open(outdir, "strings.tsv")) {
            w.println("addr\tfile_addr\tlength\tstring");
            DataIterator dit = listing.getDefinedData(true);
            while (dit.hasNext() && !monitor.isCancelled()) {
                Data d = dit.next();
                if (!d.hasStringValue()) continue;
                Object v = d.getValue();
                if (v == null) continue;
                String s = v.toString().replace("\t", " ").replace("\n", "\\n");
                if (s.length() > 200) s = s.substring(0, 200);
                w.printf("0x%08x\t0x%08x\t%d\t%s%n", d.getAddress().getOffset(),
                        d.getAddress().getOffset() - imageBase, d.getLength(), s);
                nstr++;
            }
        }

        println(String.format(
                "[ExportFunctionIndex] functions=%d exports=%d imports=%d callgraph_edges=%d strings=%d",
                nfunc, nexport, nexternal, edges, nstr));
    }
}