-
Notifications
You must be signed in to change notification settings - Fork 0
/
aidl_language.cpp
1829 lines (1629 loc) · 63.2 KB
/
aidl_language.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
996
997
998
999
1000
/*
* Copyright (C) 2015, The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "aidl_language.h"
#include "aidl_typenames.h"
#include "parser.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
#include <iostream>
#include <set>
#include <sstream>
#include <string>
#include <utility>
#include <android-base/parsedouble.h>
#include <android-base/parseint.h>
#include <android-base/result.h>
#include <android-base/strings.h>
#include "aidl.h"
#include "aidl_language_y.h"
#include "comments.h"
#include "logging.h"
#include "permission.h"
#ifdef _WIN32
int isatty(int fd)
{
return (fd == 0);
}
#endif
using android::aidl::IoDelegate;
using android::base::Error;
using android::base::Join;
using android::base::Result;
using android::base::Split;
using std::cerr;
using std::pair;
using std::set;
using std::string;
using std::unique_ptr;
using std::vector;
namespace {
bool IsJavaKeyword(const char* str) {
static const std::vector<std::string> kJavaKeywords{
"abstract", "assert", "boolean", "break", "byte", "case", "catch",
"char", "class", "const", "continue", "default", "do", "double",
"else", "enum", "extends", "final", "finally", "float", "for",
"goto", "if", "implements", "import", "instanceof", "int", "interface",
"long", "native", "new", "package", "private", "protected", "public",
"return", "short", "static", "strictfp", "super", "switch", "synchronized",
"this", "throw", "throws", "transient", "try", "void", "volatile",
"while", "true", "false", "null",
};
return std::find(kJavaKeywords.begin(), kJavaKeywords.end(), str) != kJavaKeywords.end();
}
} // namespace
AidlNode::~AidlNode() {
if (!visited_) {
unvisited_locations_.push_back(location_);
}
}
void AidlNode::ClearUnvisitedNodes() {
unvisited_locations_.clear();
}
const std::vector<AidlLocation>& AidlNode::GetLocationsOfUnvisitedNodes() {
return unvisited_locations_;
}
void AidlNode::MarkVisited() const {
visited_ = true;
}
AidlNode::AidlNode(const AidlLocation& location, const Comments& comments)
: location_(location), comments_(comments) {}
std::string AidlNode::PrintLine() const {
std::stringstream ss;
ss << location_.file_ << ":" << location_.begin_.line;
return ss.str();
}
std::string AidlNode::PrintLocation() const {
std::stringstream ss;
ss << location_.file_ << ":" << location_.begin_.line << ":" << location_.begin_.column << ":"
<< location_.end_.line << ":" << location_.end_.column;
return ss.str();
}
std::vector<AidlLocation> AidlNode::unvisited_locations_;
static const AidlTypeSpecifier kStringType{AIDL_LOCATION_HERE, "String", /*array=*/std::nullopt,
nullptr, Comments{}};
static const AidlTypeSpecifier kStringArrayType{AIDL_LOCATION_HERE, "String", DynamicArray{},
nullptr, Comments{}};
static const AidlTypeSpecifier kIntType{AIDL_LOCATION_HERE, "int", /*array=*/std::nullopt, nullptr,
Comments{}};
static const AidlTypeSpecifier kLongType{AIDL_LOCATION_HERE, "long", /*array=*/std::nullopt,
nullptr, Comments{}};
static const AidlTypeSpecifier kBooleanType{AIDL_LOCATION_HERE, "boolean", /*array=*/std::nullopt,
nullptr, Comments{}};
const std::vector<AidlAnnotation::Schema>& AidlAnnotation::AllSchemas() {
static const std::vector<Schema> kSchemas{
{AidlAnnotation::Type::NULLABLE,
"nullable",
CONTEXT_TYPE_SPECIFIER,
{{"heap", kBooleanType}}},
{AidlAnnotation::Type::UTF8_IN_CPP, "utf8InCpp", CONTEXT_TYPE_SPECIFIER, {}},
{AidlAnnotation::Type::SENSITIVE_DATA, "SensitiveData", CONTEXT_TYPE_INTERFACE, {}},
{AidlAnnotation::Type::VINTF_STABILITY, "VintfStability", CONTEXT_TYPE, {}},
{AidlAnnotation::Type::UNSUPPORTED_APP_USAGE,
"UnsupportedAppUsage",
CONTEXT_TYPE | CONTEXT_MEMBER,
{{"expectedSignature", kStringType},
{"implicitMember", kStringType},
{"maxTargetSdk", kIntType},
{"publicAlternatives", kStringType},
{"trackingBug", kLongType}}},
{AidlAnnotation::Type::JAVA_STABLE_PARCELABLE,
"JavaOnlyStableParcelable",
CONTEXT_TYPE_UNSTRUCTURED_PARCELABLE,
{}},
{AidlAnnotation::Type::NDK_STABLE_PARCELABLE,
"NdkOnlyStableParcelable",
CONTEXT_TYPE_UNSTRUCTURED_PARCELABLE,
{}},
{AidlAnnotation::Type::BACKING,
"Backing",
CONTEXT_TYPE_ENUM,
{{"type", kStringType, /* required= */ true}}},
{AidlAnnotation::Type::JAVA_PASSTHROUGH,
"JavaPassthrough",
CONTEXT_ALL,
{{"annotation", kStringType, /* required= */ true}},
/* repeatable= */ true},
{AidlAnnotation::Type::JAVA_DERIVE,
"JavaDerive",
CONTEXT_TYPE_STRUCTURED_PARCELABLE | CONTEXT_TYPE_UNION | CONTEXT_TYPE_ENUM,
{{"toString", kBooleanType}, {"equals", kBooleanType}}},
{AidlAnnotation::Type::JAVA_DEFAULT, "JavaDefault", CONTEXT_TYPE_INTERFACE, {}},
{AidlAnnotation::Type::JAVA_DELEGATOR, "JavaDelegator", CONTEXT_TYPE_INTERFACE, {}},
{AidlAnnotation::Type::JAVA_ONLY_IMMUTABLE,
"JavaOnlyImmutable",
CONTEXT_TYPE_STRUCTURED_PARCELABLE | CONTEXT_TYPE_UNION |
CONTEXT_TYPE_UNSTRUCTURED_PARCELABLE,
{}},
{AidlAnnotation::Type::JAVA_SUPPRESS_LINT,
"JavaSuppressLint",
CONTEXT_ALL,
{{"value", kStringArrayType, /* required= */ true}}},
{AidlAnnotation::Type::FIXED_SIZE,
"FixedSize",
CONTEXT_TYPE_STRUCTURED_PARCELABLE | CONTEXT_TYPE_UNION,
{}},
{AidlAnnotation::Type::DESCRIPTOR,
"Descriptor",
CONTEXT_TYPE_INTERFACE,
{{"value", kStringType, /* required= */ true}}},
{AidlAnnotation::Type::RUST_DERIVE,
"RustDerive",
CONTEXT_TYPE_STRUCTURED_PARCELABLE | CONTEXT_TYPE_UNION,
{{"Copy", kBooleanType},
{"Clone", kBooleanType},
{"PartialOrd", kBooleanType},
{"Ord", kBooleanType},
{"PartialEq", kBooleanType},
{"Eq", kBooleanType},
{"Hash", kBooleanType}}},
{AidlAnnotation::Type::SUPPRESS_WARNINGS,
"SuppressWarnings",
CONTEXT_TYPE | CONTEXT_MEMBER,
{{"value", kStringArrayType, /* required= */ true}}},
{AidlAnnotation::Type::PERMISSION_ENFORCE,
"EnforcePermission",
CONTEXT_TYPE_INTERFACE | CONTEXT_METHOD,
{{"value", kStringType}, {"anyOf", kStringArrayType}, {"allOf", kStringArrayType}}},
{AidlAnnotation::Type::PERMISSION_MANUAL,
"PermissionManuallyEnforced",
CONTEXT_TYPE_INTERFACE | CONTEXT_METHOD,
{}},
{AidlAnnotation::Type::PERMISSION_NONE,
"RequiresNoPermission",
CONTEXT_TYPE_INTERFACE | CONTEXT_METHOD,
{}},
{AidlAnnotation::Type::PROPAGATE_ALLOW_BLOCKING,
"PropagateAllowBlocking",
CONTEXT_METHOD,
{}},
};
return kSchemas;
}
std::string AidlAnnotation::TypeToString(Type type) {
for (const Schema& schema : AllSchemas()) {
if (type == schema.type) return schema.name;
}
AIDL_FATAL(AIDL_LOCATION_HERE) << "Unrecognized type: " << static_cast<size_t>(type);
__builtin_unreachable();
}
std::unique_ptr<AidlAnnotation> AidlAnnotation::Parse(
const AidlLocation& location, const string& name,
std::map<std::string, std::shared_ptr<AidlConstantValue>> parameter_list,
const Comments& comments) {
const Schema* schema = nullptr;
for (const Schema& a_schema : AllSchemas()) {
if (a_schema.name == name) {
schema = &a_schema;
}
}
if (schema == nullptr) {
std::ostringstream stream;
stream << "'" << name << "' is not a recognized annotation. ";
stream << "It must be one of:";
for (const Schema& s : AllSchemas()) {
stream << " " << s.name;
}
stream << ".";
AIDL_ERROR(location) << stream.str();
return {};
}
return std::unique_ptr<AidlAnnotation>(
new AidlAnnotation(location, *schema, std::move(parameter_list), comments));
}
AidlAnnotation::AidlAnnotation(const AidlLocation& location, const Schema& schema,
std::map<std::string, std::shared_ptr<AidlConstantValue>> parameters,
const Comments& comments)
: AidlNode(location, comments), schema_(schema), parameters_(std::move(parameters)) {}
struct ConstReferenceFinder : AidlVisitor {
const AidlConstantReference* found = nullptr;
void Visit(const AidlConstantReference& ref) override {
if (!found) found = &ref;
}
static const AidlConstantReference* Find(const AidlConstantValue& c) {
ConstReferenceFinder finder;
VisitTopDown(finder, c);
return finder.found;
}
};
// Checks if annotation complies with the schema
// - every parameter is known and has well-typed value.
// - every required parameter is present.
bool AidlAnnotation::CheckValid() const {
for (const auto& name_and_param : parameters_) {
const std::string& param_name = name_and_param.first;
const std::shared_ptr<AidlConstantValue>& param = name_and_param.second;
const ParamType* param_type = schema_.ParamType(param_name);
if (!param_type) {
std::ostringstream stream;
stream << "Parameter " << param_name << " not supported ";
stream << "for annotation " << GetName() << ". ";
stream << "It must be one of:";
for (const auto& param : schema_.parameters) {
stream << " " << param.name;
}
AIDL_ERROR(this) << stream.str();
return false;
}
const auto& found = ConstReferenceFinder::Find(*param);
if (found) {
AIDL_ERROR(found) << "Value must be a constant expression but contains reference to "
<< found->GetFieldName() << ".";
return false;
}
if (!param->CheckValid()) {
AIDL_ERROR(this) << "Invalid value for parameter " << param_name << " on annotation "
<< GetName() << ".";
return false;
}
const std::string param_value =
param->ValueString(param_type->type, AidlConstantValueDecorator);
// Assume error on empty string.
if (param_value == "") {
AIDL_ERROR(this) << "Invalid value for parameter " << param_name << " on annotation "
<< GetName() << ".";
return false;
}
}
bool success = true;
for (const auto& param : schema_.parameters) {
if (param.required && parameters_.count(param.name) == 0) {
AIDL_ERROR(this) << "Missing '" << param.name << "' on @" << GetName() << ".";
success = false;
}
}
if (!success) {
return false;
}
// For @Enforce annotations, validates the expression.
if (schema_.type == AidlAnnotation::Type::PERMISSION_ENFORCE) {
auto expr = EnforceExpression();
if (!expr.ok()) {
AIDL_ERROR(this) << "Unable to parse @EnforcePermission annotation: " << expr.error();
return false;
}
}
return true;
}
Result<unique_ptr<android::aidl::perm::Expression>> AidlAnnotation::EnforceExpression() const {
auto single = ParamValue<std::string>("value");
auto anyOf = ParamValue<std::vector<std::string>>("anyOf");
auto allOf = ParamValue<std::vector<std::string>>("allOf");
if (single.has_value()) {
return std::make_unique<android::aidl::perm::Expression>(single.value());
} else if (anyOf.has_value()) {
auto v = android::aidl::perm::AnyOf{anyOf.value()};
return std::make_unique<android::aidl::perm::Expression>(v);
} else if (allOf.has_value()) {
auto v = android::aidl::perm::AllOf{allOf.value()};
return std::make_unique<android::aidl::perm::Expression>(v);
}
return Error() << "No parameter for @EnforcePermission";
}
// Checks if the annotation is applicable to the current context.
// For example, annotations like @VintfStability, @FixedSize is not applicable to AidlTypeSpecifier
// nodes.
bool AidlAnnotation::CheckContext(TargetContext context) const {
if (schema_.target_context & static_cast<uint32_t>(context)) {
return true;
}
const static map<TargetContext, string> context_name_map{
{CONTEXT_TYPE_INTERFACE, "interface"},
{CONTEXT_TYPE_ENUM, "enum"},
{CONTEXT_TYPE_STRUCTURED_PARCELABLE, "parcelable definition"},
{CONTEXT_TYPE_UNION, "union"},
{CONTEXT_TYPE_UNSTRUCTURED_PARCELABLE, "parcelable declaration"},
{CONTEXT_CONST, "constant"},
{CONTEXT_FIELD, "field"},
{CONTEXT_METHOD, "method"},
{CONTEXT_TYPE_SPECIFIER, "type"},
};
vector<string> available;
for (const auto& [context, name] : context_name_map) {
if (schema_.target_context & context) {
available.push_back(name);
}
}
AIDL_ERROR(this) << "@" << GetName()
<< " is not available. It can only annotate: " << Join(available, ", ") << ".";
return false;
}
std::map<std::string, std::string> AidlAnnotation::AnnotationParams(
const ConstantValueDecorator& decorator) const {
std::map<std::string, std::string> raw_params;
for (const auto& name_and_param : parameters_) {
const std::string& param_name = name_and_param.first;
const std::shared_ptr<AidlConstantValue>& param = name_and_param.second;
const ParamType* param_type = schema_.ParamType(param_name);
AIDL_FATAL_IF(!param_type, this);
raw_params.emplace(param_name, param->ValueString(param_type->type, decorator));
}
return raw_params;
}
std::string AidlAnnotation::ToString() const {
if (parameters_.empty()) {
return "@" + GetName();
} else {
vector<string> param_strings;
for (const auto& [name, value] : AnnotationParams(AidlConstantValueDecorator)) {
param_strings.emplace_back(name + "=" + value);
}
return "@" + GetName() + "(" + Join(param_strings, ", ") + ")";
}
}
void AidlAnnotation::TraverseChildren(std::function<void(const AidlNode&)> traverse) const {
for (const auto& [name, value] : parameters_) {
(void)name;
traverse(*value);
}
}
static const AidlAnnotation* GetAnnotation(
const vector<std::unique_ptr<AidlAnnotation>>& annotations, AidlAnnotation::Type type) {
for (const auto& a : annotations) {
if (a->GetType() == type) {
AIDL_FATAL_IF(a->Repeatable(), a)
<< "Trying to get a single annotation when it is repeatable.";
return a.get();
}
}
return nullptr;
}
static const AidlAnnotation* GetScopedAnnotation(const AidlDefinedType& defined_type,
AidlAnnotation::Type type) {
const AidlAnnotation* annotation = GetAnnotation(defined_type.GetAnnotations(), type);
if (annotation) {
return annotation;
}
const AidlDefinedType* enclosing_type = defined_type.GetParentType();
if (enclosing_type) {
return GetScopedAnnotation(*enclosing_type, type);
}
return nullptr;
}
AidlAnnotatable::AidlAnnotatable(const AidlLocation& location, const Comments& comments)
: AidlCommentable(location, comments) {}
bool AidlAnnotatable::IsNullable() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::NULLABLE);
}
bool AidlAnnotatable::IsHeapNullable() const {
auto annot = GetAnnotation(annotations_, AidlAnnotation::Type::NULLABLE);
if (annot) {
return annot->ParamValue<bool>("heap").value_or(false);
}
return false;
}
bool AidlAnnotatable::IsUtf8InCpp() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::UTF8_IN_CPP);
}
bool AidlAnnotatable::IsSensitiveData() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::SENSITIVE_DATA);
}
bool AidlAnnotatable::IsVintfStability() const {
auto defined_type = AidlCast<AidlDefinedType>(*this);
AIDL_FATAL_IF(!defined_type, *this) << "@VintfStability is not attached to a type";
return GetScopedAnnotation(*defined_type, AidlAnnotation::Type::VINTF_STABILITY);
}
bool AidlAnnotatable::IsJavaOnlyImmutable() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::JAVA_ONLY_IMMUTABLE);
}
bool AidlAnnotatable::IsFixedSize() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::FIXED_SIZE);
}
const AidlAnnotation* AidlAnnotatable::UnsupportedAppUsage() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::UNSUPPORTED_APP_USAGE);
}
std::vector<std::string> AidlAnnotatable::RustDerive() const {
std::vector<std::string> ret;
if (const auto* ann = GetAnnotation(annotations_, AidlAnnotation::Type::RUST_DERIVE)) {
for (const auto& name_and_param : ann->AnnotationParams(AidlConstantValueDecorator)) {
if (name_and_param.second == "true") {
ret.push_back(name_and_param.first);
}
}
}
return ret;
}
const AidlAnnotation* AidlAnnotatable::BackingType() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::BACKING);
}
std::vector<std::string> AidlAnnotatable::SuppressWarnings() const {
auto annot = GetAnnotation(annotations_, AidlAnnotation::Type::SUPPRESS_WARNINGS);
if (annot) {
auto names = annot->ParamValue<std::vector<std::string>>("value");
AIDL_FATAL_IF(!names.has_value(), this);
return std::move(names.value());
}
return {};
}
// Parses the @Enforce annotation expression.
std::unique_ptr<android::aidl::perm::Expression> AidlAnnotatable::EnforceExpression() const {
auto annot = GetAnnotation(annotations_, AidlAnnotation::Type::PERMISSION_ENFORCE);
if (annot) {
auto perm_expr = annot->EnforceExpression();
if (!perm_expr.ok()) {
// This should have been caught during validation.
AIDL_FATAL(this) << "Unable to parse @EnforcePermission annotation: " << perm_expr.error();
}
return std::move(perm_expr.value());
}
return {};
}
bool AidlAnnotatable::IsPermissionManual() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::PERMISSION_MANUAL);
}
bool AidlAnnotatable::IsPermissionNone() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::PERMISSION_NONE);
}
bool AidlAnnotatable::IsPermissionAnnotated() const {
return IsPermissionNone() || IsPermissionManual() || EnforceExpression();
}
bool AidlAnnotatable::IsPropagateAllowBlocking() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::PROPAGATE_ALLOW_BLOCKING);
}
bool AidlAnnotatable::IsStableApiParcelable(Options::Language lang) const {
if (lang == Options::Language::JAVA)
return GetAnnotation(annotations_, AidlAnnotation::Type::JAVA_STABLE_PARCELABLE);
if (lang == Options::Language::NDK)
return GetAnnotation(annotations_, AidlAnnotation::Type::NDK_STABLE_PARCELABLE);
return false;
}
bool AidlAnnotatable::JavaDerive(const std::string& method) const {
auto annotation = GetAnnotation(annotations_, AidlAnnotation::Type::JAVA_DERIVE);
if (annotation != nullptr) {
return annotation->ParamValue<bool>(method).value_or(false);
}
return false;
}
bool AidlAnnotatable::IsJavaDefault() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::JAVA_DEFAULT);
}
bool AidlAnnotatable::IsJavaDelegator() const {
return GetAnnotation(annotations_, AidlAnnotation::Type::JAVA_DELEGATOR);
}
std::string AidlAnnotatable::GetDescriptor() const {
auto annotation = GetAnnotation(annotations_, AidlAnnotation::Type::DESCRIPTOR);
if (annotation != nullptr) {
return annotation->ParamValue<std::string>("value").value();
}
return "";
}
bool AidlAnnotatable::CheckValid(const AidlTypenames&) const {
for (const auto& annotation : GetAnnotations()) {
if (!annotation->CheckValid()) {
return false;
}
}
std::map<AidlAnnotation::Type, AidlLocation> declared;
for (const auto& annotation : GetAnnotations()) {
const auto& [iter, inserted] =
declared.emplace(annotation->GetType(), annotation->GetLocation());
if (!inserted && !annotation->Repeatable()) {
AIDL_ERROR(this) << "'" << annotation->GetName()
<< "' is repeated, but not allowed. Previous location: " << iter->second;
return false;
}
}
return true;
}
string AidlAnnotatable::ToString() const {
vector<string> ret;
for (const auto& a : annotations_) {
ret.emplace_back(a->ToString());
}
std::sort(ret.begin(), ret.end());
return Join(ret, " ");
}
AidlTypeSpecifier::AidlTypeSpecifier(const AidlLocation& location, const string& unresolved_name,
std::optional<ArrayType> array,
vector<unique_ptr<AidlTypeSpecifier>>* type_params,
const Comments& comments)
: AidlAnnotatable(location, comments),
AidlParameterizable<unique_ptr<AidlTypeSpecifier>>(type_params),
unresolved_name_(unresolved_name),
array_(std::move(array)),
split_name_(Split(unresolved_name, ".")) {}
void AidlTypeSpecifier::ViewAsArrayBase(std::function<void(const AidlTypeSpecifier&)> func) const {
AIDL_FATAL_IF(!array_.has_value(), this);
// Declaring array of generic type cannot happen, it is grammar error.
AIDL_FATAL_IF(IsGeneric(), this);
bool is_mutated = mutated_;
mutated_ = true;
// mutate the array type to its base by removing a single dimension
// e.g.) T[] => T, T[N][M] => T[M] (note that, M is removed)
if (IsFixedSizeArray() && std::get<FixedSizeArray>(*array_).dimensions.size() > 1) {
auto& dimensions = std::get<FixedSizeArray>(*array_).dimensions;
auto dim = std::move(dimensions.front());
dimensions.erase(dimensions.begin());
func(*this);
dimensions.insert(dimensions.begin(), std::move(dim));
} else {
ArrayType array_type = std::move(array_.value());
array_ = std::nullopt;
func(*this);
array_ = std::move(array_type);
}
mutated_ = is_mutated;
}
bool AidlTypeSpecifier::MakeArray(ArrayType array_type) {
// T becomes T[] or T[N]
if (!IsArray()) {
array_ = std::move(array_type);
return true;
}
// T[N] becomes T[N][M]
if (auto fixed_size_array = std::get_if<FixedSizeArray>(&array_type);
fixed_size_array != nullptr && IsFixedSizeArray()) {
// concat dimensions
for (auto& dim : fixed_size_array->dimensions) {
std::get<FixedSizeArray>(*array_).dimensions.push_back(std::move(dim));
}
return true;
}
return false;
}
std::vector<int32_t> FixedSizeArray::GetDimensionInts() const {
std::vector<int32_t> ints;
for (const auto& dim : dimensions) {
ints.push_back(dim->EvaluatedValue<int32_t>());
}
return ints;
}
std::vector<int32_t> AidlTypeSpecifier::GetFixedSizeArrayDimensions() const {
AIDL_FATAL_IF(!IsFixedSizeArray(), "not a fixed-size array");
return std::get<FixedSizeArray>(GetArray()).GetDimensionInts();
}
string AidlTypeSpecifier::Signature() const {
string ret = GetName();
if (IsGeneric()) {
vector<string> arg_names;
for (const auto& ta : GetTypeParameters()) {
arg_names.emplace_back(ta->Signature());
}
ret += "<" + Join(arg_names, ",") + ">";
}
if (IsArray()) {
if (IsFixedSizeArray()) {
for (const auto& dim : GetFixedSizeArrayDimensions()) {
ret += "[" + std::to_string(dim) + "]";
}
} else {
ret += "[]";
}
}
return ret;
}
string AidlTypeSpecifier::ToString() const {
string ret = Signature();
string annotations = AidlAnnotatable::ToString();
if (annotations != "") {
ret = annotations + " " + ret;
}
return ret;
}
// When `scope` is specified, name is resolved first based on it.
// `scope` can be null for built-in types and fully-qualified types.
bool AidlTypeSpecifier::Resolve(const AidlTypenames& typenames, const AidlScope* scope) {
AIDL_FATAL_IF(IsResolved(), this);
std::string name = unresolved_name_;
if (scope) {
name = scope->ResolveName(name);
}
AidlTypenames::ResolvedTypename result = typenames.ResolveTypename(name);
if (result.is_resolved) {
fully_qualified_name_ = result.canonical_name;
split_name_ = Split(fully_qualified_name_, ".");
defined_type_ = result.defined_type;
}
return result.is_resolved;
}
const AidlDefinedType* AidlTypeSpecifier::GetDefinedType() const {
return defined_type_;
}
bool AidlTypeSpecifier::CheckValid(const AidlTypenames& typenames) const {
if (!AidlAnnotatable::CheckValid(typenames)) {
return false;
}
if (IsGeneric()) {
const auto& types = GetTypeParameters();
for (const auto& arg : types) {
if (!arg->CheckValid(typenames)) {
return false;
}
}
const string& type_name = GetName();
// TODO(b/136048684) Disallow to use primitive types only if it is List or Map.
if (type_name == "List" || type_name == "Map") {
if (std::any_of(types.begin(), types.end(), [&](auto& type_ptr) {
return !type_ptr->IsArray() &&
(typenames.GetEnumDeclaration(*type_ptr) ||
AidlTypenames::IsPrimitiveTypename(type_ptr->GetName()));
})) {
AIDL_ERROR(this) << "A generic type cannot have any primitive type parameters.";
return false;
}
}
const auto defined_type = typenames.TryGetDefinedType(type_name);
const auto parameterizable =
defined_type != nullptr ? defined_type->AsParameterizable() : nullptr;
const bool is_user_defined_generic_type =
parameterizable != nullptr && parameterizable->IsGeneric();
const size_t num_params = GetTypeParameters().size();
if (type_name == "List") {
if (num_params > 1) {
AIDL_ERROR(this) << "List can only have one type parameter, but got: '" << Signature()
<< "'";
return false;
}
static const char* kListUsage =
"List<T> supports interface/parcelable/union, String, IBinder, and ParcelFileDescriptor.";
const AidlTypeSpecifier& contained_type = *GetTypeParameters()[0];
if (contained_type.IsArray()) {
AIDL_ERROR(this) << "List of arrays is not supported. " << kListUsage;
return false;
}
const string& contained_type_name = contained_type.GetName();
if (AidlTypenames::IsBuiltinTypename(contained_type_name)) {
if (contained_type_name != "String" && contained_type_name != "IBinder" &&
contained_type_name != "ParcelFileDescriptor") {
AIDL_ERROR(this) << "List<" << contained_type_name << "> is not supported. "
<< kListUsage;
return false;
}
}
} else if (type_name == "Map") {
if (num_params != 0 && num_params != 2) {
AIDL_ERROR(this) << "Map must have 0 or 2 type parameters, but got "
<< "'" << Signature() << "'";
return false;
}
if (num_params == 2) {
const string& key_type = GetTypeParameters()[0]->Signature();
if (key_type != "String") {
AIDL_ERROR(this) << "The type of key in map must be String, but it is "
<< "'" << key_type << "'";
return false;
}
}
} else if (is_user_defined_generic_type) {
const size_t allowed = parameterizable->GetTypeParameters().size();
if (num_params != allowed) {
AIDL_ERROR(this) << type_name << " must have " << allowed << " type parameters, but got "
<< num_params;
return false;
}
} else {
AIDL_ERROR(this) << type_name << " is not a generic type.";
return false;
}
}
const bool is_generic_string_list = GetName() == "List" && IsGeneric() &&
GetTypeParameters().size() == 1 &&
GetTypeParameters()[0]->GetName() == "String";
if (IsUtf8InCpp() && (GetName() != "String" && !is_generic_string_list)) {
AIDL_ERROR(this) << "@utf8InCpp can only be used on String, String[], and List<String>.";
return false;
}
if (GetName() == "void") {
if (IsArray() || IsNullable() || IsUtf8InCpp()) {
AIDL_ERROR(this) << "void type cannot be an array or nullable or utf8 string";
return false;
}
}
if (IsArray()) {
if (GetName() == "ParcelableHolder" || GetName() == "List" || GetName() == "Map" ||
GetName() == "CharSequence") {
AIDL_ERROR(this) << "Arrays of " << GetName() << " are not supported.";
return false;
}
}
if (IsNullable()) {
if (AidlTypenames::IsPrimitiveTypename(GetName()) && !IsArray()) {
AIDL_ERROR(this) << "Primitive type cannot get nullable annotation";
return false;
}
const auto defined_type = typenames.TryGetDefinedType(GetName());
if (defined_type != nullptr && defined_type->AsEnumDeclaration() != nullptr && !IsArray()) {
AIDL_ERROR(this) << "Enum type cannot get nullable annotation";
return false;
}
if (GetName() == "ParcelableHolder") {
AIDL_ERROR(this) << "ParcelableHolder cannot be nullable.";
return false;
}
if (IsHeapNullable()) {
if (!defined_type || IsArray() || !defined_type->AsParcelable()) {
AIDL_ERROR(this) << "@nullable(heap=true) is available to parcelables.";
return false;
}
}
}
if (IsFixedSizeArray()) {
for (const auto& dim : std::get<FixedSizeArray>(GetArray()).dimensions) {
if (!dim->Evaluate()) {
return false;
}
if (dim->GetType() > AidlConstantValue::Type::INT32) {
AIDL_ERROR(this) << "Array size must be a positive number: " << dim->Literal();
return false;
}
auto value = dim->EvaluatedValue<int32_t>();
if (value < 0) {
AIDL_ERROR(this) << "Array size must be a positive number: " << value;
return false;
}
}
}
return true;
}
void AidlTypeSpecifier::TraverseChildren(std::function<void(const AidlNode&)> traverse) const {
AidlAnnotatable::TraverseChildren(traverse);
if (IsGeneric()) {
for (const auto& tp : GetTypeParameters()) {
traverse(*tp);
}
}
if (IsFixedSizeArray()) {
for (const auto& dim : std::get<FixedSizeArray>(GetArray()).dimensions) {
traverse(*dim);
}
}
}
std::string AidlConstantValueDecorator(
const AidlTypeSpecifier& type,
const std::variant<std::string, std::vector<std::string>>& raw_value) {
if (type.IsArray()) {
const auto& values = std::get<std::vector<std::string>>(raw_value);
return "{" + Join(values, ", ") + "}";
}
const std::string& value = std::get<std::string>(raw_value);
if (auto defined_type = type.GetDefinedType(); defined_type) {
auto enum_type = defined_type->AsEnumDeclaration();
AIDL_FATAL_IF(!enum_type, type) << "Invalid type for \"" << value << "\"";
return type.GetName() + "." + value.substr(value.find_last_of('.') + 1);
}
return value;
}
AidlVariableDeclaration::AidlVariableDeclaration(const AidlLocation& location,
AidlTypeSpecifier* type, const std::string& name)
: AidlVariableDeclaration(location, type, name, AidlConstantValue::Default(*type)) {
default_user_specified_ = false;
}
AidlVariableDeclaration::AidlVariableDeclaration(const AidlLocation& location,
AidlTypeSpecifier* type, const std::string& name,
AidlConstantValue* default_value)
: AidlMember(location, type->GetComments()),
type_(type),
name_(name),
default_user_specified_(true),
default_value_(default_value) {}
bool AidlVariableDeclaration::HasUsefulDefaultValue() const {
if (GetDefaultValue()) {
return true;
}
// null is accepted as a valid default value in all backends
if (GetType().IsNullable()) {
return true;
}
return false;
}
bool AidlVariableDeclaration::CheckValid(const AidlTypenames& typenames) const {
bool valid = true;
valid &= type_->CheckValid(typenames);
if (type_->GetName() == "void") {
AIDL_ERROR(this) << "Declaration " << name_
<< " is void, but declarations cannot be of void type.";
valid = false;
}
if (default_value_ == nullptr) return valid;
valid &= default_value_->CheckValid();
if (!valid) return false;
return !ValueString(AidlConstantValueDecorator).empty();
}
string AidlVariableDeclaration::GetCapitalizedName() const {
AIDL_FATAL_IF(name_.size() <= 0, *this) << "Name can't be empty.";
string str = name_;
str[0] = static_cast<char>(toupper(str[0]));
return str;
}
string AidlVariableDeclaration::ToString() const {
string ret = type_->ToString() + " " + name_;
if (default_value_ != nullptr && default_user_specified_) {
ret += " = " + ValueString(AidlConstantValueDecorator);
}
return ret;
}
string AidlVariableDeclaration::Signature() const {
return type_->Signature() + " " + name_;
}
std::string AidlVariableDeclaration::ValueString(const ConstantValueDecorator& decorator) const {
if (default_value_ != nullptr) {
return default_value_->ValueString(GetType(), decorator);
} else {
return "";
}
}
void AidlVariableDeclaration::TraverseChildren(
std::function<void(const AidlNode&)> traverse) const {
traverse(GetType());
if (auto default_value = GetDefaultValue(); default_value) {
traverse(*default_value);
}
}
AidlArgument::AidlArgument(const AidlLocation& location, AidlArgument::Direction direction,
AidlTypeSpecifier* type, const std::string& name)
: AidlVariableDeclaration(location, type, name),
direction_(direction),
direction_specified_(true) {}
AidlArgument::AidlArgument(const AidlLocation& location, AidlTypeSpecifier* type,
const std::string& name)
: AidlVariableDeclaration(location, type, name),
direction_(AidlArgument::IN_DIR),
direction_specified_(false) {}
static std::string to_string(AidlArgument::Direction direction) {
switch (direction) {
case AidlArgument::IN_DIR:
return "in";
case AidlArgument::OUT_DIR:
return "out";
case AidlArgument::INOUT_DIR:
return "inout";
}
}
string AidlArgument::GetDirectionSpecifier() const {
string ret;
if (direction_specified_) {
ret = to_string(direction_);
}
return ret;
}
string AidlArgument::ToString() const {
if (direction_specified_) {
return GetDirectionSpecifier() + " " + AidlVariableDeclaration::ToString();
} else {
return AidlVariableDeclaration::ToString();
}
}
static std::string FormatDirections(const std::set<AidlArgument::Direction>& directions) {