-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
syz-declextract.cpp
995 lines (919 loc) · 36.2 KB
/
syz-declextract.cpp
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
// Copyright 2024 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.
//go:build ignore
#include "clang/AST/APValue.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Attrs.inc"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclarationName.h"
#include "clang/AST/Expr.h"
#include "clang/AST/PrettyPrinter.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/Type.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/ASTMatchers/ASTMatchersInternal.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TypeTraits.h"
#include "clang/Lex/Lexer.h"
#include "clang/Sema/Ownership.h"
#include "clang/Tooling/CommonOptionsParser.h"
#include "clang/Tooling/Tooling.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Frontend/OpenMP/OMP.h.inc"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <stdio.h>
#include <string>
#include <string_view>
#include <unordered_map>
#include <vector>
using namespace clang;
using namespace clang::ast_matchers;
const char *const AccessUnknown = "-";
const char *const AccessUser = "user";
const char *const AccessNsAdmin = "ns_admin";
const char *const AccessAdmin = "admin";
struct Param {
std::string type;
std::string name;
};
struct NetlinkOps {
std::string cmd;
std::string func;
const char *access;
std::optional<std::string> policy;
};
struct NetlinkType {
RecordDecl *decl;
int64_t len;
};
struct StructMember {
std::string type;
std::string name;
unsigned int countedBy;
};
void emitInterface(const char *type, std::string_view name, std::string_view identifying_const,
std::string_view entry_func = "", const char *access = AccessUnknown) {
if (entry_func.empty())
entry_func = "-";
printf("\n#INTERFACE: %s %s %s %s %s\n\n", type, std::string(name).c_str(), std::string(identifying_const).c_str(),
std::string(entry_func).c_str(), access);
}
std::string toIdentifier(std::string name) {
if (name == "resource" || name == "include" || name == "define" || name == "incdir" || name == "syscall" ||
name == "parent") {
return "_" + name;
}
std::replace(name.begin(), name.end(), '.', '_');
std::replace(name.begin(), name.end(), ' ', '_');
std::replace(name.begin(), name.end(), '-', '_');
return name;
}
struct SyzRecordDecl {
std::string name;
std::vector<StructMember> members;
std::string attr;
bool isUnion;
bool isVarlen;
bool operator==(const SyzRecordDecl &decl) { return name == decl.name; }
bool operator<(const SyzRecordDecl &decl) { return name < decl.name; }
void print() const {
if (name.empty()) {
return;
}
const char openBracket = isUnion ? '[' : '{';
const char closeBracket = isUnion ? ']' : '}';
printf("%s %c\n", name.c_str(), openBracket);
for (const auto &member : members) {
printf("\t%s %s\n", toIdentifier(member.name).c_str(), member.type.c_str());
}
putchar(closeBracket);
if (isUnion && isVarlen) {
printf("[%s]", "varlen");
} else if (!isUnion && !attr.empty()) {
printf("[%s]", attr.c_str());
}
puts("");
}
};
// If expression refers to some identifier, returns the identifier name.
// Otherwise returns an empty string.
// For example, if the expression is `function_name`, returns "function_name" string.
std::string getDeclName(ASTContext &context, const clang::Expr *expr) {
if (!expr) {
return "";
}
// The expression can be complex and include casts and e.g. InitListExpr,
// to remove all of these we match the first/any DeclRefExpr.
struct Matcher : MatchFinder::MatchCallback {
const DeclRefExpr *decl = nullptr;
void run(const MatchFinder::MatchResult &Result) override { decl = Result.Nodes.getNodeAs<DeclRefExpr>("decl"); }
};
MatchFinder finder;
Matcher matcher;
finder.addMatcher(stmt(forEachDescendant(declRefExpr().bind("decl"))), &matcher);
finder.match(*expr, context);
return matcher.decl ? matcher.decl->getDecl()->getNameAsString() : "";
}
bool endsWith(const std::string_view &str, const std::string_view end) {
size_t substrBegin = str.rfind(end);
return substrBegin != std::string::npos && str.substr(substrBegin) == end;
}
bool beginsWith(const std::string_view &str, const std::string_view begin) {
size_t substrBegin = str.find(begin);
return substrBegin != std::string::npos && str.substr(0, begin.size()) == begin;
}
bool contains(const std::string_view &str, const std::string_view sub) { return str.find(sub) != std::string::npos; }
std::string makeArray(const std::string &type, const size_t min = 0, const size_t max = -1) {
if (max != size_t(-1)) {
return "array[" + type + ", " + std::to_string(min) + ":" + std::to_string(max) + "]";
}
if (min == 1) {
return type;
}
if (min) {
return "array[" + type + ", " + std::to_string(min) + "]";
}
return "array[" + type + "]";
}
std::string makePtr(const std::string &dir, const std::string &type, bool isOpt = false) {
std::string ptr = "ptr[" + dir + ", " + type;
if (isOpt) {
return ptr + ", opt]";
}
return ptr + "]";
}
std::string makeConst(bool isSyscallArg, const std::string &type, const std::string &val) {
if (isSyscallArg) {
return "const[" + val + "]";
}
return "const[" + val + ", " + type + "]";
}
std::string makeFlags(bool isSyscallArg, const std::string &type, const std::string &flags) {
if (isSyscallArg) {
return "flags[" + flags + "]";
}
return "flags[" + flags + ", " + type + "]";
}
std::string int8Subtype(const std::string &name, const bool isSyscallParam) { return "int8"; }
std::string int16Subtype(const std::string &name, const bool isSyscallParam) {
if (contains(name, "port")) {
return "sock_port";
}
return "int16";
}
std::string int32Subtype(const std::string &name, const bool isSyscallParam) {
if (contains(name, "ipv4")) {
return "ipv4_addr";
}
if (endsWith(name, "_pid") || endsWith(name, "_tid") || endsWith(name, "_pgid") || endsWith(name, "_tgid") ||
name == "pid" || name == "tid" || name == "pgid" || name == "tgid") {
return "pid";
}
if (endsWith(name, "dfd") && !endsWith(name, "oldfd") && !endsWith(name, "pidfd")) {
return "fd_dir";
}
if (endsWith(name, "ns_fd")) {
return "fd_namespace";
}
if (endsWith(name, "_uid") || name == "uid" || name == "user" || name == "ruid" || name == "euid" || name == "suid") {
return "uid";
}
if (endsWith(name, "_gid") || name == "gid" || name == "group" || name == "rgid" || name == "egid" ||
name == "sgid") {
return "gid";
}
if (endsWith(name, "fd") || beginsWith(name, "fd_") || contains(name, "fildes") || name == "fdin" ||
name == "fdout") {
return "fd";
}
if (contains(name, "ifindex") || contains(name, "dev_index")) {
return "ifindex";
}
return "int32";
}
std::string int64Subtype(const std::string &name, const bool isSyscallParam) { return "int64"; }
std::string intptrSubtype(const std::string &name, const bool isSyscallParam) {
if (name == "sigsetsize") {
return makeConst(isSyscallParam, "intptr", "8");
}
return "intptr";
}
std::string stringSubtype(const std::string &name, const char *defaultName = "string") {
if (contains(name, "ifname") || endsWith(name, "dev_name")) {
return "devname";
}
if (contains(name, "filename") || contains(name, "pathname") || contains(name, "dir_name") || name == "oldname" ||
name == "newname" || name == "path") {
return "filename";
}
return defaultName;
}
enum IntType {
INVALID_INT = 0,
INT_8 = 1,
INT_16 = 2,
INT_32 = 4,
INT_64 = 8,
INT_PTR,
};
IntType getIntType(const std::string &ctype, const bool isSyscallParam) {
// TODO: Handle arm32 passing 64bit arguments
if (!isSyscallParam && (contains(ctype, "long long") || contains(ctype, "64"))) {
return INT_64;
}
if (contains(ctype, "16") || contains(ctype, "short")) {
return INT_16;
}
if (contains(ctype, "8") || contains(ctype, "char") || ctype == "_Bool") {
return INT_8;
}
if (contains(ctype, "32") || contains(ctype, "int")) {
return INT_32;
}
if (contains(ctype, "long")) {
return INT_PTR;
}
fprintf(stderr, "Unhandled int length for type: %s\n", ctype.c_str());
exit(1);
}
const std::string intNSubtype(const std::string &name, const IntType len, const bool isSyscallParam) {
switch (len) {
case INT_8:
return int8Subtype(name, isSyscallParam);
case INT_16:
return int16Subtype(name, isSyscallParam);
case INT_32:
return int32Subtype(name, isSyscallParam);
case INT_64:
return int64Subtype(name, isSyscallParam);
case INT_PTR:
return intptrSubtype(name, isSyscallParam);
default:
fprintf(stderr, "invalid int type: %d\n", static_cast<int>(len));
exit(1);
}
}
bool isIntN(const std::string &type) {
return (!type.compare(0, 3, "int") && std::all_of(type.begin() + 3, type.end(), ::isDigit)) || (type == "intptr");
}
const std::string intSubtype(const std::string &name, const IntType len, const bool isSyscallParam = false) {
if (len == INVALID_INT) {
fprintf(stderr, "Invalid int type\n");
exit(1);
}
const std::string subType = intNSubtype(name, len, isSyscallParam);
if (!isIntN(subType)) {
return subType;
}
if (endsWith(name, "enabled") || endsWith(name, "enable")) {
// Replace "int" with "bool".
return "bool" + subType.substr(3);
}
return subType;
}
const std::string getSyzType(const std::string &ctype, std::string name, const bool isSyscallParam,
const int bitFieldWidth = 0) {
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
IntType len = getIntType(ctype, isSyscallParam);
const int byteLen = len * 8;
if (INT_8 <= len && len <= INT_64 && contains(ctype, "be")) {
return "int" + std::to_string(byteLen) + "be";
}
std::string type;
const bool isBitField = bitFieldWidth;
if (isBitField) {
type = "int" + std::to_string(byteLen);
if (byteLen != bitFieldWidth) {
type += ":" + std::to_string(bitFieldWidth);
}
} else {
type = intSubtype(name, len, isSyscallParam);
}
if (isBitField || isIntN(type)) {
if (name.empty() || contains(name, "pad") || contains(name, "unused") || contains(name, "_reserved")) {
return makeConst(isSyscallParam, type, "0");
}
}
return type;
}
class RecordExtractor {
private:
const SourceManager *const SM;
std::vector<std::string> includes;
std::vector<std::string> flags;
std::unordered_map<std::string, SyzRecordDecl> extractedRecords;
const std::string emptyStructType = "empty struct";
const std::string autoTodo = "auto_todo";
unsigned int getCountedBy(const FieldDecl *const &field) {
return field->getType()->isCountAttributedType()
? llvm::dyn_cast<FieldDecl>(
field->getType()->getAs<CountAttributedType>()->getCountExpr()->getReferencedDeclOfCallee())
->getFieldIndex()
: UINT_MAX;
}
bool isFieldVarlen(const QualType &fieldType) {
return fieldType->isIncompleteArrayType() ||
(fieldType->isConstantArrayType() && llvm::dyn_cast<ConstantArrayType>(fieldType)->getSize().isZero());
}
std::string getStructAttr(const RecordDecl *const recordDecl, ASTContext *context) {
if (recordDecl->isStruct() && recordDecl->hasAttrs()) {
for (const auto &item : recordDecl->getAttrs()) {
if (item->getKind() == clang::attr::Aligned) {
return "align[" + std::to_string(llvm::dyn_cast<AlignedAttr>(item)->getAlignment(*context) / 8) + "]";
} else if (item->getKind() == clang::attr::Packed) {
return "packed";
}
}
}
return "";
}
public:
RecordExtractor(const SourceManager *const SM) : SM(SM){};
std::string getFieldType(const QualType &fieldType, ASTContext *context, const std::string &fieldName,
const std::string &parent = "", bool isSyscallParam = false,
const std::string &fieldTypeName = "") {
const auto &field = fieldType.IgnoreParens().getUnqualifiedType().getDesugaredType(*context);
switch (fieldType.IgnoreParens()->getTypeClass()) {
case clang::Type::Record: {
std::string backupName;
if (!parent.empty()) {
backupName = parent + "_" + fieldName;
} else if (!fieldTypeName.empty()) {
backupName = fieldTypeName;
} else {
backupName = fieldName;
}
return extractRecord(field->getAsRecordDecl(), context, backupName);
}
case clang::Type::IncompleteArray: // Defined as type[]
return makeArray(getFieldType(llvm::dyn_cast<IncompleteArrayType>(field)->getElementType(), context, fieldName));
case clang::Type::ConstantArray: {
const auto &array = llvm::dyn_cast<ConstantArrayType>(field);
return makeArray(getFieldType(array->getElementType(), context, fieldName), array->getSize().getZExtValue());
}
case clang::Type::Pointer: {
const auto &pointerType = llvm::dyn_cast<PointerType>(field);
const auto &pointeeType = pointerType->getPointeeType();
std::string fieldType;
if (pointeeType->isAnyCharacterType()) {
fieldType = stringSubtype(fieldName);
} else if (pointeeType->isVoidType()) {
fieldType = makeArray(autoTodo);
} else {
fieldType = getFieldType(pointeeType, context, fieldName);
}
const auto &ptrDir = pointeeType.isConstQualified() ? "in" : "inout"; // TODO: Infer direction of non-const.
return makePtr(ptrDir, fieldType,
parent + "$auto_record" == fieldType); // Checks if the direct parent is the same as the node.
}
case clang::Type::Builtin:
return getSyzType(field.getAsString(), fieldName, isSyscallParam);
case clang::Type::CountAttributed: // Has the attribute counted_by. Handled by getCountedBy
case clang::Type::BTFTagAttributed: // Currently Unused
case clang::Type::Typedef:
return getFieldType(field, context, fieldName, parent, isSyscallParam, field.getAsString());
case clang::Type::Elaborated:
return getFieldType(llvm::dyn_cast<ElaboratedType>(fieldType)->desugar(), context, fieldName, parent,
isSyscallParam); // NOTE: The fieldType contains information we need, don't use field instead.
case clang::Type::Enum: {
const auto &enumDecl = llvm::dyn_cast<EnumType>(field)->getDecl();
auto name = enumDecl->getNameAsString();
flags.push_back(name);
includes.push_back(std::filesystem::relative(SM->getFilename(enumDecl->getSourceRange().getBegin()).str()));
const char *sep = " = ";
for (const auto &enumerator : enumDecl->enumerators()) {
flags.back() += sep + enumerator->getNameAsString();
sep = ", ";
}
std::string baseType = "int" + std::to_string(context->getTypeInfo(field).Width);
return makeFlags(isSyscallParam, baseType, name);
}
case clang::Type::FunctionProto:
return makePtr("in", autoTodo);
default:
field->dump();
fprintf(stderr, "Unhandled field type %s\n", field->getTypeClassName());
exit(1);
}
}
std::string extractRecord(const RecordDecl *recordDecl, ASTContext *context, const std::string &backupName) {
recordDecl = recordDecl->getDefinition();
if (!recordDecl) { // When the definition is in a different translation unit.
return autoTodo;
}
const auto &name = (recordDecl->getNameAsString().empty() ? backupName : recordDecl->getNameAsString());
const auto &recordName = name + "$auto_record";
if (extractedRecords.find(name) != extractedRecords.end()) { // Don't extract the same record twice.
return recordName;
}
extractedRecords[name];
bool isVarlen = false;
std::vector<StructMember> members;
for (const auto &field : recordDecl->fields()) {
std::string fieldName;
if (field->getName().empty()) {
fieldName = name + "_" + std::to_string(field->getFieldIndex());
} else if (field->isAnonymousStructOrUnion()) {
fieldName = name;
} else {
fieldName = field->getNameAsString();
}
const std::string &parentName = field->isAnonymousStructOrUnion() ? "" : name;
const std::string &fieldType =
field->isBitField() ? getSyzType(field->getType().getAsString(), field->isUnnamedBitField() ? "" : fieldName,
false, field->getBitWidthValue(*context))
: getFieldType(field->getType(), context, fieldName, parentName);
if (fieldType == emptyStructType) {
continue;
}
isVarlen |= isFieldVarlen(field->getType()) ||
(extractedRecords.find(fieldName) != extractedRecords.end() &&
!extractedRecords[fieldName].name.empty() && extractedRecords[fieldName].isVarlen);
members.push_back({fieldType, fieldName, getCountedBy(field)});
}
if (members.empty()) { // Empty structs are not allowed in Syzlang.
return emptyStructType;
}
extractedRecords[name] = {recordName, std::move(members), getStructAttr(recordDecl, context), recordDecl->isUnion(),
isVarlen};
return recordName;
}
void print() {
puts("type auto_todo intptr");
for (const auto &inc : includes) {
printf("include<%s>\n", inc.c_str());
}
for (const auto &flag : flags) {
puts(flag.c_str());
}
for (auto &[_, decl] : extractedRecords) {
for (auto &member : decl.members) {
if (member.countedBy != UINT_MAX) {
auto &type = decl.members[member.countedBy].type;
type = "len[" + member.name + ", " + type + "]";
}
}
}
for (const auto &[_, decl] : extractedRecords) {
decl.print();
}
}
};
struct EnumData {
std::string name;
unsigned long long value;
std::string file;
};
// Extracts enum info from array variable designated initialization.
// For example, for the following code:
//
// enum Foo {
// FooA = 11,
// FooB = 42,
// };
//
// struct Bar bars[] = {
// [FooA] = {...},
// [FooB] = {...},
// };
//
// it returns the following map:
// 11: {"FooA", 11, file.c},
// 42: {"FooB", 42, file.c},
std::map<int, EnumData> extractDesignatedInitConsts(ASTContext &context, const VarDecl &arrayDecl) {
struct DesignatedInitMatcher : MatchFinder::MatchCallback {
std::vector<EnumData> Inits;
DesignatedInitMatcher(MatchFinder &Finder) {
Finder.addMatcher(
decl(forEachDescendant(designatedInitExpr(optionally(has(constantExpr(has(declRefExpr())).bind("init")))))),
this);
}
void run(const MatchFinder::MatchResult &Result) override {
const auto *init = Result.Nodes.getNodeAs<ConstantExpr>("init");
if (!init) {
return;
}
const auto &name = init->getEnumConstantDecl()->getNameAsString();
const auto value = *init->getAPValueResult().getInt().getRawData();
const auto &path = std::filesystem::relative(
Result.SourceManager->getFilename(init->getEnumConstantDecl()->getSourceRange().getBegin()).str());
Inits.push_back({std::move(name), value, std::move(path)});
}
};
MatchFinder finder;
DesignatedInitMatcher matcher(finder);
finder.match(arrayDecl, context);
std::map<int, EnumData> ordered;
for (auto &init : matcher.Inits) {
ordered[init.value] = init;
}
return ordered;
}
class SyscallMatcher : public MatchFinder::MatchCallback {
public:
SyscallMatcher(MatchFinder &Finder) {
Finder.addMatcher(functionDecl(isExpandedFromMacro("SYSCALL_DEFINEx"), matchesName("__do_sys_.*")).bind("syscall"),
this);
}
private:
void run(const MatchFinder::MatchResult &Result) override {
ASTContext *context = Result.Context;
const auto *syscall = Result.Nodes.getNodeAs<FunctionDecl>("syscall");
RecordExtractor recordExtractor(Result.SourceManager);
const char *sep = "";
const auto func = syscall->getNameAsString();
const auto &name = func.substr(9); // Remove "__do_sys_" prefix.
emitInterface("SYSCALL", name, "__NR_" + name, func);
printf("%s(", name.c_str());
for (const auto ¶m : syscall->parameters()) {
const auto &type = recordExtractor.getFieldType(param->getType(), context, param->getNameAsString(), "", true);
const auto &name = param->getNameAsString();
printf("%s%s %s", sep, toIdentifier(name).c_str(), type.c_str());
sep = ", ";
}
printf(") (automatic)\n");
recordExtractor.print();
}
};
class NetlinkPolicyMatcher : public MatchFinder::MatchCallback {
public:
NetlinkPolicyMatcher(MatchFinder &Finder) {
Finder.addMatcher(
translationUnitDecl(
hasDescendant(enumDecl(has(enumConstantDecl(hasName("__NLA_TYPE_MAX")))).bind("NLA_ENUM")),
forEachDescendant(
varDecl(hasType(constantArrayType(hasElementType(hasDeclaration(
recordDecl(hasName("nla_policy")).bind("nla_policy"))))
.bind("nla_policy_array")),
isDefinition())
.bind("netlink"))),
this);
Finder.addMatcher(varDecl(hasType(recordDecl(hasName("genl_family")).bind("genl_family")),
has(initListExpr().bind("genl_family_init")))
.bind("genl_family_decl"),
this);
}
private:
void run(const MatchFinder::MatchResult &Result) override {
nlaEnum(Result); // NOTE: Must be executed first, as it generates maps that are used in the following methods.
netlink(Result);
genlFamily(Result);
}
// u8ToNlaEnum stores the Enum values to string conversions. This is later used to transfer types from an unnamed
// integer to a readable form. E.g. 1 -> NLA_U8
// See: https://elixir.bootlin.com/linux/v6.10/source/include/net/netlink.h#L172
std::unordered_map<uint8_t, std::string> u8ToNlaEnum;
void nlaEnum(const MatchFinder::MatchResult &Result) {
const auto &num = Result.Nodes.getNodeAs<EnumDecl>("NLA_ENUM");
if (!num || !u8ToNlaEnum.empty()) { // Don't evaluate the Enum twice
return;
}
for (const auto &enumerator : num->enumerators()) {
const auto &name = enumerator->getNameAsString();
const auto val = uint8_t(enumerator->getValue().getZExtValue());
u8ToNlaEnum[val] = name.substr(4); // Remove NLA_ prefix
}
}
const std::string nlaArraySubtype(const std::string &name, const std::string &type, const size_t len,
const std::string &typeOfLen) {
if (!typeOfLen.empty()) {
return len == 0 ? typeOfLen : makeArray(typeOfLen, 0, len);
}
switch (len) {
case 0:
return makeArray("int8");
case 1:
case 2:
case 4:
case 8:
return intSubtype(name, IntType(len));
default:
if (contains(name, "IPV6")) {
return "ipv6_addr";
}
if (type == "BINARY") {
return makeArray("int8", 0, len);
}
return makeArray("int8", len);
}
}
const std::string nlaToSyz(std::string name, const std::string &type, const size_t len,
const std::string &typeOfLen) {
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
// TODO:Gather information from other defined fields to better specify a type.
// Loosely based on https://elixir.bootlin.com/linux/v6.10/source/lib/nlattr.c
if (type == "U8" || type == "S8") {
return intSubtype(name, INT_8);
}
if (type == "U16" || type == "S16") {
return intSubtype(name, INT_16);
}
if (type == "U32" || type == "S32") {
return intSubtype(name, INT_32);
}
if (type == "U64" || type == "S64" || type == "SINT" || type == "UINT" || type == "MSECS") {
return intSubtype(name, INT_64);
}
if (type == "BINARY") {
return nlaArraySubtype(name, type, len, typeOfLen);
}
if (type == "BE16") {
return "int16be";
}
if (type == "BE32") {
return "int32be";
}
if (type == "FLAG") {
return "void";
}
if (type == "STRING") {
return stringSubtype(name, "stringnoz");
}
if (type == "NUL_STRING") {
return stringSubtype(name);
}
if (type == "BITFIELD32") { // TODO:Extract valued values from NLA_POLICY_BITFIELD32 macro.
return "int32";
}
if (type == "UNSPEC" || type == "NESTED" || type == "NESTED_ARRAY" || type == "REJECT" || type == "TYPE_MAX") {
return nlaArraySubtype(name, type, len, typeOfLen);
}
fprintf(stderr, "Unsupported netlink type %s\n", type.c_str());
exit(1);
}
RecordDecl *getStructFromSizeof(UnaryExprOrTypeTraitExpr *stmt) {
if (!stmt || stmt->getKind() != clang::UETT_SizeOf) {
return NULL;
}
return stmt->getTypeOfArgument()->getAsRecordDecl();
}
NetlinkType getStructAndLenFromBinary(BinaryOperator *stmt, ASTContext *context) {
const auto &lhs = stmt->getLHS();
const auto &rhs = stmt->getRHS();
// NOTE: Usually happens in case of NESTED_POLICY which is not handled currently.
// TODO: Handle NESTED_POLICY
if (lhs->getStmtClass() == clang::Stmt::BinaryOperatorClass ||
rhs->getStmtClass() == clang::Stmt::BinaryOperatorClass) {
return {NULL, 0};
}
auto decl = getStructFromSizeof(llvm::dyn_cast<UnaryExprOrTypeTraitExpr>(lhs));
Expr::EvalResult len;
if (!decl) {
decl = getStructFromSizeof(llvm::dyn_cast<UnaryExprOrTypeTraitExpr>(rhs));
lhs->EvaluateAsConstantExpr(len, *context);
} else {
rhs->EvaluateAsConstantExpr(len, *context);
}
return NetlinkType{decl, len.Val.getInt().getExtValue()};
}
// Returns the struct type from .len field.
// e.g. if .len = sizeof(struct x * LEN), returns the declaration of struct x and LEN
NetlinkType getNetlinkStruct(clang::Expr *stmt, ASTContext *context) {
stmt = stmt->IgnoreParens();
Expr::EvalResult len;
stmt->EvaluateAsConstantExpr(len, *context);
switch (stmt->getStmtClass()) {
case clang::Stmt::ImplicitValueInitExprClass:
return NetlinkType{NULL, 0};
case clang::Stmt::BinaryOperatorClass:
return getStructAndLenFromBinary(llvm::dyn_cast<BinaryOperator>(stmt), context);
case clang::Stmt::UnaryExprOrTypeTraitExprClass:
return NetlinkType{getStructFromSizeof(llvm::dyn_cast<UnaryExprOrTypeTraitExpr>(stmt)), 0};
case clang::Stmt::UnaryOperatorClass:
case clang::Stmt::DeclRefExprClass:
case clang::Stmt::CStyleCastExprClass:
case clang::Stmt::IntegerLiteralClass:
return NetlinkType{NULL, len.Val.getInt().getExtValue()};
default:
fprintf(stderr, "Unhandled .len case %s\n", stmt->getStmtClassName());
exit(1);
}
}
void netlink(const MatchFinder::MatchResult &Result) {
ASTContext *context = Result.Context;
const auto *netlinkDecl = Result.Nodes.getNodeAs<VarDecl>("netlink");
if (!netlinkDecl) {
return;
}
const auto *init = netlinkDecl->getInit();
if (!init) {
return;
}
std::vector<std::vector<Expr *>> fields;
for (const auto &policy : *llvm::dyn_cast<InitListExpr>(init)) {
fields.push_back(std::vector<Expr *>());
for (const auto &member : policy->children()) {
fields.back().push_back(llvm::dyn_cast<Expr>(member));
}
}
auto enumData = extractDesignatedInitConsts(*context, *netlinkDecl);
if (enumData.empty()) {
// We need to emit at least some type for it.
// Ideally it should be void, but typedef to void currently does not work.
printf("type %s auto_todo\n", getPolicyName(Result, netlinkDecl)->c_str());
return;
}
for (const auto &[_, item] : enumData) {
if (!endsWith(item.file, ".h")) {
continue;
}
printf("include <%s>\n", item.file.c_str());
}
RecordExtractor recordExtractor(Result.SourceManager);
printf("%s [\n", getPolicyName(Result, netlinkDecl)->c_str());
for (size_t i = 0; i < fields.size(); ++i) {
// The array could have an implicitly initialized policy (i.e. empty) or an unnamed attribute
if (fields[i].empty() || enumData[i].name.empty()) {
continue;
}
Expr::EvalResult evalResult;
fields[i][0]->EvaluateAsConstantExpr(evalResult, *context); // This contains the NLA Enum type
const auto &nlaEnum = u8ToNlaEnum[evalResult.Val.getInt().getZExtValue()];
auto [structDecl, len] = getNetlinkStruct(fields[i][2]->IgnoreCasts(), context);
std::string netlinkStruct;
if (!structDecl) {
fields[i][2]->EvaluateAsConstantExpr(evalResult, *context);
len = evalResult.Val.getInt().getExtValue();
} else {
netlinkStruct = recordExtractor.extractRecord(structDecl, context, enumData[i].name);
}
printf("\t%s nlattr[%s, %s]\n", enumData[i].name.c_str(), enumData[i].name.c_str(),
nlaToSyz(enumData[i].name, nlaEnum, len, netlinkStruct).c_str());
}
puts("] [varlen]");
recordExtractor.print();
}
std::map<std::string, unsigned> genlFamilyMember;
std::optional<std::string> getPolicyName(const MatchFinder::MatchResult &Result, const ValueDecl *decl) {
if (!decl) {
return std::nullopt;
}
std::string filename =
toIdentifier(std::filesystem::path(
Result.SourceManager->getFilename(decl->getCanonicalDecl()->getSourceRange().getBegin()).str())
.filename()
.stem()
.string());
// Filename is added to address ambiguity when multiple policies
// are named the same but have different definitions.
return decl->getNameAsString() + "$auto_" + filename;
}
std::vector<NetlinkOps> getOps(const MatchFinder::MatchResult &Result, const std::string &opsName,
const InitListExpr *init) {
ASTContext *context = Result.Context;
const auto n_ops = init->getInit(genlFamilyMember["n_" + opsName])->getIntegerConstantExpr(*context);
const auto &opsRef = init->getInit(genlFamilyMember[opsName])->getAsBuiltinConstantDeclRef(*context);
if (!n_ops || !opsRef) {
return {};
}
const auto *opsDecl = llvm::dyn_cast<VarDecl>(opsRef);
if (!opsDecl->getInit()) {
// NOTE: This usually happens when the ops is defined as an extern variable
// TODO: Extract extern variables
return {};
}
const auto *opsInit = llvm::dyn_cast<InitListExpr>(opsDecl->getInit());
std::map<std::string, unsigned> opsMember;
for (const auto &field : opsInit->getInit(0)->getType()->getAsRecordDecl()->fields()) {
opsMember[field->getNameAsString()] = field->getFieldIndex();
}
std::vector<NetlinkOps> ops;
for (int i = 0; i < n_ops; ++i) {
const auto &init = llvm::dyn_cast<InitListExpr>(opsInit->getInit(i));
const auto &cmdInit = init->getInit(opsMember["cmd"])->getEnumConstantDecl();
if (!cmdInit) {
continue;
}
const auto &cmd = cmdInit->getNameAsString();
const ValueDecl *policyDecl = nullptr;
if (opsName != "small_ops") {
policyDecl = init->getInit(opsMember["policy"])->getAsBuiltinConstantDeclRef(*context);
}
std::string func = getDeclName(*context, init->getInit(opsMember["doit"]));
if (func.empty())
func = getDeclName(*context, init->getInit(opsMember["dumpit"]));
const Expr *flagsDecl = init->getInit(opsMember["flags"]);
Expr::EvalResult flags;
flagsDecl->EvaluateAsConstantExpr(flags, *context);
auto flagsVal = flags.Val.getInt().getExtValue();
const char *access = AccessUser;
constexpr int GENL_ADMIN_PERM = 0x01;
constexpr int GENL_UNS_ADMIN_PERM = 0x10;
if (flagsVal & GENL_ADMIN_PERM)
access = AccessAdmin;
else if (flagsVal & GENL_UNS_ADMIN_PERM)
access = AccessNsAdmin;
ops.push_back({std::move(cmd), func, access, getPolicyName(Result, policyDecl)});
}
return ops;
}
void genlFamily(const MatchFinder::MatchResult &Result) {
ASTContext *context = Result.Context;
const auto *genlFamilyInit = Result.Nodes.getNodeAs<InitListExpr>("genl_family_init");
if (!genlFamilyInit) {
return;
}
if (genlFamilyMember.empty()) {
const auto *genlFamily = Result.Nodes.getNodeAs<RecordDecl>("genl_family");
for (const auto &field : genlFamily->fields()) {
genlFamilyMember[field->getNameAsString()] = field->getFieldIndex();
}
}
const auto &globalPolicyName =
genlFamilyInit->getInit(genlFamilyMember["policy"])->getAsBuiltinConstantDeclRef(*context);
std::string familyPolicyName;
if (globalPolicyName) {
familyPolicyName = *getPolicyName(Result, globalPolicyName);
}
std::string familyName =
llvm::dyn_cast<StringLiteral>(genlFamilyInit->getInit(genlFamilyMember["name"]))->getString().str();
std::string identifierName = toIdentifier(familyName);
std::string msghdr = "msghdr_" + identifierName + "_auto";
bool printedCmds = false;
for (const auto &opsType : {"ops", "small_ops", "split_ops"}) {
for (auto &ops : getOps(Result, opsType, genlFamilyInit)) {
const char *policyName;
if (ops.policy) {
policyName = ops.policy->c_str();
} else if (globalPolicyName) {
policyName = familyPolicyName.c_str();
} else {
continue;
}
emitInterface("NETLINK", ops.cmd, ops.cmd, ops.func, ops.access);
printf("sendmsg$auto_%s(fd sock_nl_generic, msg ptr[in, %s[%s, %s]], f flags[send_flags]) (automatic)\n",
ops.cmd.c_str(), msghdr.c_str(), ops.cmd.c_str(), policyName);
printedCmds = true;
}
}
if (!printedCmds) { // Do not print resources and types if they're not used in any cmds
return;
}
std::string resourceName = "genl_" + identifierName + "_family_id_auto";
printf("resource %s[int16]\n", resourceName.c_str());
printf("type %s[CMD, POLICY] msghdr_netlink[netlink_msg_t[%s, genlmsghdr_t[CMD], POLICY]]\n", msghdr.c_str(),
resourceName.c_str());
printf("syz_genetlink_get_family_id$auto_%s(name ptr[in, string[\"%s\"]], fd sock_nl_generic) %s (automatic)\n",
identifierName.c_str(), familyName.c_str(), resourceName.c_str());
}
};
class IouringMatcher : public MatchFinder::MatchCallback {
public:
IouringMatcher(MatchFinder &Finder) {
Finder.addMatcher(
translationUnitDecl(forEachDescendant(
varDecl(hasType(constantArrayType(hasElementType(hasDeclaration(recordDecl(hasName("io_issue_def")))))),
isDefinition())
.bind("io_issue_defs"))),
this);
}
private:
void run(const MatchFinder::MatchResult &Result) override {
ASTContext *context = Result.Context;
const auto *ioIssueDefs = Result.Nodes.getNodeAs<VarDecl>("io_issue_defs");
if (!ioIssueDefs) {
return;
}
auto elements = extractDesignatedInitConsts(*Result.Context, *ioIssueDefs);
const auto *initList = llvm::dyn_cast<InitListExpr>(ioIssueDefs->getInit());
std::map<std::string, unsigned> fields;
for (const auto &field : initList->getInit(0)->getType()->getAsRecordDecl()->fields()) {
fields[field->getNameAsString()] = field->getFieldIndex();
}
for (const auto &[i, op] : elements) {
const auto &init = llvm::dyn_cast<InitListExpr>(initList->getInit(i));
std::string prep = getDeclName(*context, init->getInit(fields["prep"]));
if (prep == "io_eopnotsupp_prep") {
continue;
}
std::string issue = getDeclName(*context, init->getInit(fields["issue"]));
emitInterface("IOURING", op.name, op.name, issue, AccessUser);
}
}
};
int main(int argc, const char **argv) {
llvm::cl::OptionCategory SyzDeclExtractOptionCategory("syz-declextract options");
auto ExpectedParser = clang::tooling::CommonOptionsParser::create(argc, argv, SyzDeclExtractOptionCategory);
if (!ExpectedParser) {
llvm::errs() << ExpectedParser.takeError();
return 1;
}
MatchFinder Finder;
SyscallMatcher SyscallMatcher(Finder);
NetlinkPolicyMatcher NetlinkPolicyMatcher(Finder);
IouringMatcher IouringMatcher(Finder);
clang::tooling::CommonOptionsParser &OptionsParser = ExpectedParser.get();
clang::tooling::ClangTool Tool(OptionsParser.getCompilations(), OptionsParser.getSourcePathList());
return Tool.run(clang::tooling::newFrontendActionFactory(&Finder).get());
}