1 /*
2 * Copyright (C) 2020, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 #include "diagnostics.h"
17
18 #include <functional>
19 #include <stack>
20
21 #include "aidl_language.h"
22 #include "logging.h"
23
24 using std::placeholders::_1;
25
26 namespace android {
27 namespace aidl {
28
29 const std::map<std::string, DiagnosticOption> kAllDiagnostics = {
30 #define DIAG(ENUM, NAME, ENABLED) {NAME, DiagnosticOption{DiagnosticID::ENUM, NAME, ENABLED}},
31 #include "diagnostics.inc"
32 #undef DIAG
33 };
34
35 static const std::map<DiagnosticID, std::string> kDiagnosticsNames = {
36 #define DIAG(ENUM, NAME, ENABLED) {DiagnosticID::ENUM, NAME},
37 #include "diagnostics.inc"
38 #undef DIAG
39 };
40
Severity(DiagnosticID id,DiagnosticSeverity severity)41 void DiagnosticMapping::Severity(DiagnosticID id, DiagnosticSeverity severity) {
42 mapping_[id] = severity;
43 }
44
Severity(DiagnosticID id) const45 DiagnosticSeverity DiagnosticMapping::Severity(DiagnosticID id) const {
46 return mapping_.at(id);
47 }
48
to_string(DiagnosticID id)49 std::string to_string(DiagnosticID id) {
50 return kDiagnosticsNames.at(id);
51 }
52
53 class DiagnosticsContext {
54 public:
DiagnosticsContext(DiagnosticMapping mapping)55 DiagnosticsContext(DiagnosticMapping mapping) : mapping_({std::move(mapping)}) {}
Report(const AidlLocation & loc,DiagnosticID id,DiagnosticSeverity force_severity=DiagnosticSeverity::DISABLED)56 AidlErrorLog Report(const AidlLocation& loc, DiagnosticID id,
57 DiagnosticSeverity force_severity = DiagnosticSeverity::DISABLED) {
58 if (loc.IsInternal()) {
59 return AidlErrorLog(AidlErrorLog::NO_OP, loc);
60 }
61 const std::string suffix = " [-W" + to_string(id) + "]";
62 auto severity = std::max(force_severity, mapping_.top().Severity(id));
63 switch (severity) {
64 case DiagnosticSeverity::DISABLED:
65 return AidlErrorLog(AidlErrorLog::NO_OP, loc);
66 case DiagnosticSeverity::WARNING:
67 return AidlErrorLog(AidlErrorLog::WARNING, loc, suffix);
68 case DiagnosticSeverity::ERROR:
69 error_count_++;
70 return AidlErrorLog(AidlErrorLog::ERROR, loc, suffix);
71 }
72 }
ErrorCount() const73 size_t ErrorCount() const { return error_count_; }
Suppress(const AidlAnnotatable & a)74 void Suppress(const AidlAnnotatable& a) {
75 const auto& warnings = a.SuppressWarnings();
76 DiagnosticMapping new_mapping = mapping_.top();
77 for (const auto& w : warnings) {
78 auto it = kAllDiagnostics.find(w);
79 if (it == kAllDiagnostics.end()) {
80 Report(a.GetLocation(), DiagnosticID::unknown_warning, DiagnosticSeverity::ERROR)
81 << "unknown warning: " << w;
82 continue;
83 }
84 new_mapping.Severity(it->second.id, DiagnosticSeverity::DISABLED);
85 }
86 mapping_.push(std::move(new_mapping));
87 }
Restore(const AidlAnnotatable &)88 void Restore(const AidlAnnotatable&) {
89 mapping_.pop();
90 }
91 private:
92 std::stack<DiagnosticMapping> mapping_;
93 size_t error_count_ = {};
94 };
95
96 class DiagnosticsVisitor : public AidlVisitor {
97 public:
DiagnosticsVisitor(DiagnosticsContext & diag)98 DiagnosticsVisitor(DiagnosticsContext& diag) : diag(diag) {}
Check(const AidlDocument & doc)99 void Check(const AidlDocument& doc) {
100 DiagnosticsVisitor* visitor = this;
101 using Fun = std::function<void(const AidlAnnotatable&)>;
102 struct Hook : public AidlVisitor {
103 Fun fun;
104 Hook(Fun fun) : fun(fun) {}
105 void Visit(const AidlInterface& a) override { fun(a); }
106 void Visit(const AidlEnumDeclaration& a) override { fun(a); }
107 void Visit(const AidlStructuredParcelable& a) override { fun(a); }
108 void Visit(const AidlUnionDecl& a) override { fun(a); }
109 void Visit(const AidlParcelable& a) override { fun(a); }
110 void Visit(const AidlMethod& a) override { fun(a.GetType()); }
111 };
112 Hook suppress{std::bind(&DiagnosticsContext::Suppress, &diag, _1)};
113 Hook restore{std::bind(&DiagnosticsContext::Restore, &diag, _1)};
114 std::function<void(const AidlNode&)> top_down = [&top_down, &suppress, &restore,
115 visitor](const AidlNode& a) {
116 a.DispatchVisit(suppress);
117 a.DispatchVisit(*visitor);
118 a.TraverseChildren(top_down);
119 a.DispatchVisit(restore);
120 };
121 top_down(doc);
122 }
123 protected:
124 DiagnosticsContext& diag;
125 };
126
127 struct DiagnoseInterfaceName : DiagnosticsVisitor {
DiagnoseInterfaceNameandroid::aidl::DiagnoseInterfaceName128 DiagnoseInterfaceName(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseInterfaceName129 void Visit(const AidlInterface& i) override {
130 if (auto name = i.GetName(); name.size() < 1 || name[0] != 'I') {
131 diag.Report(i.GetLocation(), DiagnosticID::interface_name)
132 << "Interface names should start with I.";
133 }
134 }
135 };
136
137 struct DiagnoseInoutParameter : DiagnosticsVisitor {
DiagnoseInoutParameterandroid::aidl::DiagnoseInoutParameter138 DiagnoseInoutParameter(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseInoutParameter139 void Visit(const AidlArgument& a) override {
140 if (a.GetDirection() == AidlArgument::INOUT_DIR) {
141 diag.Report(a.GetLocation(), DiagnosticID::inout_parameter)
142 << a.GetName()
143 << " is 'inout'. Avoid inout parameters. This is somewhat confusing for clients "
144 "because although the parameters are 'in', they look out 'out' parameters.";
145 }
146 }
147 };
148
149 struct DiagnoseConstName : DiagnosticsVisitor {
DiagnoseConstNameandroid::aidl::DiagnoseConstName150 DiagnoseConstName(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseConstName151 void Visit(const AidlEnumerator& e) override {
152 if (ToUpper(e.GetName()) != e.GetName()) {
153 diag.Report(e.GetLocation(), DiagnosticID::const_name)
154 << "Enum values should be named in upper case: " << e.GetName();
155 }
156 }
Visitandroid::aidl::DiagnoseConstName157 void Visit(const AidlConstantDeclaration& c) override {
158 if (ToUpper(c.GetName()) != c.GetName()) {
159 diag.Report(c.GetLocation(), DiagnosticID::const_name)
160 << "Constants should be named in upper case: " << c.GetName();
161 }
162 }
ToUpperandroid::aidl::DiagnoseConstName163 static std::string ToUpper(std::string name) {
164 for (auto& c : name) c = std::toupper(c);
165 return name;
166 }
167 };
168
169 struct DiagnoseExplicitDefault : DiagnosticsVisitor {
DiagnoseExplicitDefaultandroid::aidl::DiagnoseExplicitDefault170 DiagnoseExplicitDefault(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseExplicitDefault171 void Visit(const AidlStructuredParcelable& p) override {
172 for (const auto& var : p.GetFields()) {
173 CheckExplicitDefault(*var);
174 }
175 }
Visitandroid::aidl::DiagnoseExplicitDefault176 void Visit(const AidlUnionDecl& u) override {
177 AIDL_FATAL_IF(u.GetFields().empty(), u) << "The union '" << u.GetName() << "' has no fields.";
178 const auto& first = u.GetFields()[0];
179 CheckExplicitDefault(*first);
180 }
CheckExplicitDefaultandroid::aidl::DiagnoseExplicitDefault181 void CheckExplicitDefault(const AidlVariableDeclaration& v) {
182 if (v.IsDefaultUserSpecified()) return;
183 if (v.GetType().IsNullable()) return;
184 if (v.GetType().IsArray()) return;
185 const auto defined_type = v.GetType().GetDefinedType();
186 if (defined_type && defined_type->AsEnumDeclaration()) {
187 diag.Report(v.GetLocation(), DiagnosticID::enum_explicit_default)
188 << "The enum field '" << v.GetName() << "' has no explicit value.";
189 return;
190 }
191 }
192 };
193
194 struct DiagnoseMixedOneway : DiagnosticsVisitor {
DiagnoseMixedOnewayandroid::aidl::DiagnoseMixedOneway195 DiagnoseMixedOneway(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseMixedOneway196 void Visit(const AidlInterface& i) override {
197 bool has_oneway = false;
198 bool has_twoway = false;
199 for (const auto& m : i.GetMethods()) {
200 if (!m->IsUserDefined()) continue;
201 if (Suppressed(*m)) continue;
202 if (m->IsOneway()) {
203 has_oneway = true;
204 } else {
205 has_twoway = true;
206 }
207 }
208 if (has_oneway && has_twoway) {
209 diag.Report(i.GetLocation(), DiagnosticID::mixed_oneway)
210 << "The interface '" << i.GetName()
211 << "' has both one-way and two-way methods. This makes it hard to reason about threading "
212 "of client code.";
213 }
214 }
Suppressedandroid::aidl::DiagnoseMixedOneway215 bool Suppressed(const AidlMethod& m) const {
216 for (const auto& w : m.GetType().SuppressWarnings()) {
217 if (w == to_string(DiagnosticID::mixed_oneway)) {
218 return true;
219 }
220 }
221 return false;
222 }
223 };
224
225 struct DiagnoseOutArray : DiagnosticsVisitor {
DiagnoseOutArrayandroid::aidl::DiagnoseOutArray226 DiagnoseOutArray(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseOutArray227 void Visit(const AidlMethod& m) override {
228 for (const auto& a : m.GetArguments()) {
229 if (a->GetType().IsArray() && a->IsOut()) {
230 diag.Report(m.GetLocation(), DiagnosticID::out_array)
231 << "The method '" << m.GetName() << "' an array output parameter '" << a->GetName()
232 << "'. Instead prefer APIs like '" << a->GetType().Signature() << " " << m.GetName()
233 << "(...).";
234 }
235 }
236 }
237 };
238
239 struct DiagnoseFileDescriptor : DiagnosticsVisitor {
DiagnoseFileDescriptorandroid::aidl::DiagnoseFileDescriptor240 DiagnoseFileDescriptor(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseFileDescriptor241 void Visit(const AidlTypeSpecifier& t) override {
242 if (t.GetName() == "FileDescriptor") {
243 diag.Report(t.GetLocation(), DiagnosticID::file_descriptor)
244 << "Please use ParcelFileDescriptor instead of FileDescriptor.";
245 }
246 }
247 };
248
249 struct DiagnoseOutNullable : DiagnosticsVisitor {
DiagnoseOutNullableandroid::aidl::DiagnoseOutNullable250 DiagnoseOutNullable(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseOutNullable251 void Visit(const AidlArgument& a) override {
252 if (a.GetType().IsArray()) return;
253 if (a.IsOut() && a.GetType().IsNullable()) {
254 diag.Report(a.GetLocation(), DiagnosticID::out_nullable)
255 << "'" << a.GetName() << "' is an " << a.GetDirectionSpecifier()
256 << " parameter and also nullable. Some backends don't support setting null value to out "
257 "parameters. Please use it as return value or drop @nullable to avoid potential "
258 "errors.";
259 }
260 }
261 };
262
263 struct DiagnoseImports : DiagnosticsVisitor {
DiagnoseImportsandroid::aidl::DiagnoseImports264 DiagnoseImports(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseImports265 void Visit(const AidlDocument& doc) override {
266 auto collide_with_decls = [&](const auto& import) {
267 for (const auto& type : doc.DefinedTypes()) {
268 if (type->GetCanonicalName() != import && type->GetName() == SimpleName(import)) {
269 return true;
270 }
271 }
272 return false;
273 };
274
275 std::set<std::string> imported_names;
276 for (const auto& import : doc.Imports()) {
277 if (collide_with_decls(import)) {
278 diag.Report(doc.GetLocation(), DiagnosticID::unique_import)
279 << SimpleName(import) << " is already defined in this file.";
280 }
281 auto [_, inserted] = imported_names.insert(SimpleName(import));
282 if (!inserted) {
283 diag.Report(doc.GetLocation(), DiagnosticID::unique_import)
284 << SimpleName(import) << " is already imported.";
285 }
286 }
287 }
288 };
289
290 struct DiagnoseUntypedCollection : DiagnosticsVisitor {
DiagnoseUntypedCollectionandroid::aidl::DiagnoseUntypedCollection291 DiagnoseUntypedCollection(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseUntypedCollection292 void Visit(const AidlTypeSpecifier& t) override {
293 if (t.GetName() == "List" || t.GetName() == "Map") {
294 if (!t.IsGeneric()) {
295 diag.Report(t.GetLocation(), DiagnosticID::untyped_collection)
296 << "Use List<V> or Map<K,V> instead.";
297 }
298 }
299 }
300 };
301
302 struct DiagnosePermissionAnnotations : DiagnosticsVisitor {
DiagnosePermissionAnnotationsandroid::aidl::DiagnosePermissionAnnotations303 DiagnosePermissionAnnotations(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnosePermissionAnnotations304 void Visit(const AidlInterface& intf) override {
305 const std::string diag_message =
306 " is not annotated for permissions. Declare which permissions are "
307 "required using @EnforcePermission. If permissions are manually "
308 "verified within the implementation, use @PermissionManuallyEnforced. "
309 "If no permissions are required, use @RequiresNoPermission.";
310 if (intf.IsPermissionAnnotated()) {
311 return;
312 }
313 const auto& methods = intf.GetMethods();
314 std::vector<size_t> methods_without_annotations;
315 size_t num_user_defined_methods = 0;
316 for (size_t i = 0; i < methods.size(); ++i) {
317 auto& m = methods[i];
318 if (!m->IsUserDefined()) continue;
319 num_user_defined_methods++;
320 if (m->GetType().IsPermissionAnnotated()) {
321 continue;
322 }
323 methods_without_annotations.push_back(i);
324 }
325 if (methods_without_annotations.size() == num_user_defined_methods) {
326 diag.Report(intf.GetLocation(), DiagnosticID::missing_permission_annotation)
327 << intf.GetName() << diag_message
328 << " This can be done for the whole interface or for each method.";
329 } else {
330 for (size_t i : methods_without_annotations) {
331 auto& m = methods[i];
332 diag.Report(m->GetLocation(), DiagnosticID::missing_permission_annotation)
333 << m->GetName() << diag_message;
334 }
335 }
336 }
337 };
338
Diagnose(const AidlDocument & doc,const DiagnosticMapping & mapping)339 bool Diagnose(const AidlDocument& doc, const DiagnosticMapping& mapping) {
340 DiagnosticsContext diag(mapping);
341
342 DiagnoseInterfaceName{diag}.Check(doc);
343 DiagnoseInoutParameter{diag}.Check(doc);
344 DiagnoseConstName{diag}.Check(doc);
345 DiagnoseExplicitDefault{diag}.Check(doc);
346 DiagnoseMixedOneway{diag}.Check(doc);
347 DiagnoseOutArray{diag}.Check(doc);
348 DiagnoseFileDescriptor{diag}.Check(doc);
349 DiagnoseOutNullable{diag}.Check(doc);
350 DiagnoseImports{diag}.Check(doc);
351 DiagnoseUntypedCollection{diag}.Check(doc);
352 DiagnosePermissionAnnotations{diag}.Check(doc);
353
354 return diag.ErrorCount() == 0;
355 }
356 } // namespace aidl
357 } // namespace android
358