-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgen_autoinspectors.cpp
More file actions
executable file
·277 lines (243 loc) · 9.53 KB
/
Copy pathgen_autoinspectors.cpp
File metadata and controls
executable file
·277 lines (243 loc) · 9.53 KB
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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
// gen_autoinspectors.cpp
// Usage: gen_autoinspectors <out_AutoInspectors.inc> [clang-args...]
// Parses a dummy TU with -include AllHeaders.h and emits AI_* macros for SGNV_* records.
#include <clang-c/Index.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <set>
#include <string>
#include <string_view>
#include <vector>
static std::string toStd(CXString s)
{
const char *p = clang_getCString(s);
std::string out = p ? p : "";
clang_disposeString(s);
return out;
}
static bool starts_with(std::string_view s, std::string_view pfx)
{
return s.size() >= pfx.size() && memcmp(s.data(), pfx.data(), pfx.size()) == 0;
}
static std::string getCursorSpelling(CXCursor c) { return toStd(clang_getCursorSpelling(c)); }
static std::string getTypeSpelling(CXType t) { return toStd(clang_getTypeSpelling(t)); }
struct Emitter
{
std::ofstream os;
explicit Emitter(const char *path) : os(path, std::ios::binary)
{
if (!os)
std::fprintf(stderr, "gen_autoinspectors: cannot open output: %s\n", path);
os << "// Auto-generated by gen_autoinspectors. Do not edit.\n";
os << "// Macros expected: AI_BEGIN(Name, Size), AI_FIELD(Rec, Field, Type, Offset), AI_END(Name)\n\n";
}
void begin(const std::string &name, long long sizeBytes)
{
os << "AI_BEGIN(" << name << ", " << sizeBytes << ")\n";
}
void field(const std::string &rec, const std::string &fieldName, const std::string &typeSpelling, long long byteOffset)
{
// Escape any quotes in type spelling
std::string ts = typeSpelling;
for (char &ch : ts)
if (ch == '\n' || ch == '\r')
ch = ' ';
os << " AI_FIELD(" << rec << ", " << fieldName << ", \"" << ts << "\", " << byteOffset << ")\n";
}
void end(const std::string &name)
{
os << "AI_END(" << name << ")\n\n";
}
bool good() const { return !!os; }
};
struct FieldVisitorData {
std::string recName;
Emitter *out;
CXType recType;
};
static void collectFields(CXCursor recordCursor,
const std::string &recName,
CXType recType,
Emitter &out)
{
// size in bytes; -1 means incomplete
long long sz = clang_Type_getSizeOf(recType);
if (sz < 0)
return;
out.begin(recName, sz);
FieldVisitorData data{recName, &out, recType};
clang_visitChildren(
recordCursor,
[](CXCursor c, CXCursor /*parent*/, CXClientData client)
{
auto *data = static_cast<FieldVisitorData *>(client);
const std::string &recName = data->recName;
Emitter *out = data->out;
if (clang_getCursorKind(c) == CXCursor_FieldDecl)
{
std::string fieldName = getCursorSpelling(c);
if (fieldName.empty())
return CXChildVisit_Continue;
long long bits = clang_Cursor_getOffsetOfField(c);
if (bits < 0)
bits = 0; // unknown → 0
long long bytes = bits / 8;
CXType ft = clang_getCursorType(c);
std::string ts = getTypeSpelling(ft);
out->field(recName, fieldName, ts, bytes);
}
return CXChildVisit_Continue;
},
&data);
out.end(recName);
}
struct TopLevelVisitorData {
Emitter *emitter;
std::set<std::string> *seen;
};
int main(int argc, char **argv)
{
if (argc < 2)
{
std::fprintf(stderr, "usage: gen_autoinspectors <out_AutoInspectors.inc> [clang-args...]\n");
return 2;
}
const char *outPath = argv[1];
// Build clang argv from the rest of args
std::vector<std::string> argsCopy;
argsCopy.reserve((size_t)argc);
for (int i = 2; i < argc; ++i)
argsCopy.emplace_back(argv[i]);
// Create a real dummy file instead of unsaved buffer
const char *kDummy = "dummy_parse.cpp";
std::vector<const char *> cargs;
cargs.reserve(argsCopy.size());
for (auto &s : argsCopy)
cargs.push_back(s.c_str());
// Create actual dummy file
std::ofstream dummy(kDummy);
if (dummy) {
dummy << "// Dummy file for libclang parsing\n";
dummy.close();
}
// Debug: print the command line
std::fprintf(stderr, "Parsing %s with arguments:\n", kDummy);
for (size_t i = 0; i < cargs.size(); ++i)
std::fprintf(stderr, " [%zu] %s\n", i, cargs[i]);
std::fprintf(stderr, "\n");
CXIndex idx = clang_createIndex(/*excludeDeclsFromPCH*/ 0, /*displayDiagnostics*/ 1);
// Parse the actual dummy file
CXTranslationUnit tu = clang_parseTranslationUnit(
idx,
kDummy,
cargs.data(), (int)cargs.size(),
nullptr, 0,
CXTranslationUnit_DetailedPreprocessingRecord |
CXTranslationUnit_SkipFunctionBodies |
CXTranslationUnit_KeepGoing);
if (!tu)
{
std::fprintf(stderr, "\n=== PARSE FAILED ===\n");
std::fprintf(stderr, "gen_autoinspectors: failed to parse translation unit.\n");
std::fprintf(stderr, "\nCommon issues:\n");
std::fprintf(stderr, " 1. Check that WinShim.h exists: ls -la WinShim.h\n");
std::fprintf(stderr, " 2. Check that AllHeaders.h was generated: ls -la AllHeaders.h\n");
std::fprintf(stderr, " 3. Check header syntax: clang -fsyntax-only -include WinShim.h -include AllHeaders.h dummy_parse.cpp\n");
std::fprintf(stderr, " 4. Verify resource-dir: clang -print-resource-dir\n");
std::remove(kDummy);
clang_disposeIndex(idx);
return 3;
}
// Emit diagnostics - this will show us what went wrong during parsing
std::fprintf(stderr, "=== DIAGNOSTICS ===\n");
unsigned opts = clang_defaultDiagnosticDisplayOptions();
unsigned n = clang_getNumDiagnostics(tu);
unsigned errorCount = 0;
unsigned warningCount = 0;
for (unsigned i = 0; i < n; ++i)
{
CXDiagnostic d = clang_getDiagnostic(tu, i);
CXDiagnosticSeverity sev = clang_getDiagnosticSeverity(d);
if (sev >= CXDiagnostic_Error)
errorCount++;
else if (sev == CXDiagnostic_Warning)
warningCount++;
CXString s = clang_formatDiagnostic(d, opts);
std::fprintf(stderr, "%s\n", clang_getCString(s));
clang_disposeString(s);
clang_disposeDiagnostic(d);
}
std::fprintf(stderr, "=== SUMMARY: %u errors, %u warnings ===\n\n", errorCount, warningCount);
if (errorCount > 0) {
std::fprintf(stderr, "Warning: Parse succeeded but there were %u errors in headers.\n", errorCount);
std::fprintf(stderr, "Output may be incomplete. Fix errors above for complete results.\n\n");
}
Emitter emitter(outPath);
if (!emitter.good())
{
std::remove(kDummy);
clang_disposeTranslationUnit(tu);
clang_disposeIndex(idx);
return 2;
}
std::set<std::string> seen;
TopLevelVisitorData topData{&emitter, &seen};
CXCursor root = clang_getTranslationUnitCursor(tu);
clang_visitChildren(
root,
[](CXCursor c, CXCursor /*parent*/, CXClientData client)
{
auto *data = static_cast<TopLevelVisitorData *>(client);
Emitter &out = *data->emitter;
std::set<std::string> &seen = *data->seen;
CXCursorKind k = clang_getCursorKind(c);
if (k == CXCursor_StructDecl || k == CXCursor_ClassDecl)
{
// Must be a definition with a name
if (!clang_isCursorDefinition(c))
return CXChildVisit_Recurse;
std::string name = getCursorSpelling(c);
if (name.empty())
return CXChildVisit_Recurse;
if (!starts_with(name, "SGNV"))
return CXChildVisit_Recurse;
if (seen.insert(name).second)
{
CXType rt = clang_getCursorType(c);
collectFields(c, name, rt, out);
}
return CXChildVisit_Recurse;
}
else if (k == CXCursor_TypedefDecl)
{
std::string tname = getCursorSpelling(c);
if (tname.empty())
return CXChildVisit_Recurse;
if (!starts_with(tname, "SGNV"))
return CXChildVisit_Recurse;
// Underlying record?
CXType ut = clang_getTypedefDeclUnderlyingType(c);
if (ut.kind == CXType_Record)
{
// Find the definition cursor for the record type if available
CXCursor rc = clang_getTypeDeclaration(ut);
if (clang_Cursor_isNull(rc))
return CXChildVisit_Recurse;
if (seen.insert(tname).second)
{
collectFields(rc, tname, ut, out);
}
}
return CXChildVisit_Recurse;
}
return CXChildVisit_Recurse;
},
&topData);
std::remove(kDummy);
clang_disposeTranslationUnit(tu);
clang_disposeIndex(idx);
std::printf("Wrote %s with %zu records.\n", outPath, seen.size());
return 0;
}