• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
ToUpper(const std::string & name)53 static std::string ToUpper(const std::string& name) {
54   std::string nameCopy(name);
55   for (auto& c : nameCopy) c = std::toupper(c);
56   return nameCopy;
57 }
58 
59 class DiagnosticsContext {
60  public:
DiagnosticsContext(DiagnosticMapping mapping)61   DiagnosticsContext(DiagnosticMapping mapping) : mapping_({std::move(mapping)}) {}
Report(const AidlLocation & loc,DiagnosticID id,DiagnosticSeverity force_severity=DiagnosticSeverity::DISABLED)62   AidlErrorLog Report(const AidlLocation& loc, DiagnosticID id,
63                       DiagnosticSeverity force_severity = DiagnosticSeverity::DISABLED) {
64     if (loc.IsInternal()) {
65       return AidlErrorLog(AidlErrorLog::NO_OP, loc);
66     }
67     const std::string suffix = " [-W" + to_string(id) + "]";
68     auto severity = std::max(force_severity, mapping_.top().Severity(id));
69     switch (severity) {
70       case DiagnosticSeverity::DISABLED:
71         return AidlErrorLog(AidlErrorLog::NO_OP, loc);
72       case DiagnosticSeverity::WARNING:
73         return AidlErrorLog(AidlErrorLog::WARNING, loc, suffix);
74       case DiagnosticSeverity::ERROR:
75         error_count_++;
76         return AidlErrorLog(AidlErrorLog::ERROR, loc, suffix);
77     }
78   }
ErrorCount() const79   size_t ErrorCount() const { return error_count_; }
Suppress(const AidlAnnotatable & a)80   void Suppress(const AidlAnnotatable& a) {
81     const auto& warnings = a.SuppressWarnings();
82     DiagnosticMapping new_mapping = mapping_.top();
83     for (const auto& w : warnings) {
84       auto it = kAllDiagnostics.find(w);
85       if (it == kAllDiagnostics.end()) {
86         Report(a.GetLocation(), DiagnosticID::unknown_warning, DiagnosticSeverity::ERROR)
87             << "unknown warning: " << w;
88         continue;
89       }
90       new_mapping.Severity(it->second.id, DiagnosticSeverity::DISABLED);
91     }
92     mapping_.push(std::move(new_mapping));
93   }
Restore(const AidlAnnotatable &)94   void Restore(const AidlAnnotatable&) {
95     mapping_.pop();
96   }
97  private:
98   std::stack<DiagnosticMapping> mapping_;
99   size_t error_count_ = {};
100 };
101 
102 class DiagnosticsVisitor : public AidlVisitor {
103  public:
DiagnosticsVisitor(DiagnosticsContext & diag)104   DiagnosticsVisitor(DiagnosticsContext& diag) : diag(diag) {}
Check(const AidlDocument & doc)105   void Check(const AidlDocument& doc) {
106     DiagnosticsVisitor* visitor = this;
107     using Fun = std::function<void(const AidlAnnotatable&)>;
108     struct Hook : public AidlVisitor {
109       Fun fun;
110       Hook(Fun fun) : fun(fun) {}
111       void Visit(const AidlInterface& a) override { fun(a); }
112       void Visit(const AidlEnumDeclaration& a) override { fun(a); }
113       void Visit(const AidlStructuredParcelable& a) override { fun(a); }
114       void Visit(const AidlUnionDecl& a) override { fun(a); }
115       void Visit(const AidlParcelable& a) override { fun(a); }
116       void Visit(const AidlMethod& a) override { fun(a.GetType()); }
117     };
118     Hook suppress{std::bind(&DiagnosticsContext::Suppress, &diag, _1)};
119     Hook restore{std::bind(&DiagnosticsContext::Restore, &diag, _1)};
120     std::function<void(const AidlNode&)> top_down = [&top_down, &suppress, &restore,
121                                                      visitor](const AidlNode& a) {
122       a.DispatchVisit(suppress);
123       a.DispatchVisit(*visitor);
124       a.TraverseChildren(top_down);
125       a.DispatchVisit(restore);
126     };
127     top_down(doc);
128   }
129  protected:
130   DiagnosticsContext& diag;
131 };
132 
133 struct DiagnoseInterfaceName : DiagnosticsVisitor {
DiagnoseInterfaceNameandroid::aidl::DiagnoseInterfaceName134   DiagnoseInterfaceName(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseInterfaceName135   void Visit(const AidlInterface& i) override {
136     if (auto name = i.GetName(); name.size() < 1 || name[0] != 'I') {
137       diag.Report(i.GetLocation(), DiagnosticID::interface_name)
138           << "Interface names should start with I.";
139     }
140   }
141 };
142 
143 struct DiagnoseInoutParameter : DiagnosticsVisitor {
DiagnoseInoutParameterandroid::aidl::DiagnoseInoutParameter144   DiagnoseInoutParameter(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseInoutParameter145   void Visit(const AidlArgument& a) override {
146     if (a.GetDirection() == AidlArgument::INOUT_DIR) {
147       diag.Report(a.GetLocation(), DiagnosticID::inout_parameter)
148           << a.GetName()
149           << " is 'inout'. Avoid inout parameters. This is somewhat confusing for clients "
150              "because although the parameters are 'in', they look out 'out' parameters.";
151     }
152   }
153 };
154 
155 struct DiagnoseConstName : DiagnosticsVisitor {
DiagnoseConstNameandroid::aidl::DiagnoseConstName156   DiagnoseConstName(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseConstName157   void Visit(const AidlEnumerator& e) override {
158     if (ToUpper(e.GetName()) != e.GetName()) {
159       diag.Report(e.GetLocation(), DiagnosticID::const_name)
160           << "Enum values should be named in upper case: " << e.GetName();
161     }
162   }
Visitandroid::aidl::DiagnoseConstName163   void Visit(const AidlConstantDeclaration& c) override {
164     if (ToUpper(c.GetName()) != c.GetName()) {
165       diag.Report(c.GetLocation(), DiagnosticID::const_name)
166           << "Constants should be named in upper case: " << c.GetName();
167     }
168   }
169 };
170 
171 struct DiagnoseExplicitDefault : DiagnosticsVisitor {
DiagnoseExplicitDefaultandroid::aidl::DiagnoseExplicitDefault172   DiagnoseExplicitDefault(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseExplicitDefault173   void Visit(const AidlStructuredParcelable& p) override {
174     for (const auto& var : p.GetFields()) {
175       CheckExplicitDefault(*var);
176     }
177   }
Visitandroid::aidl::DiagnoseExplicitDefault178   void Visit(const AidlUnionDecl& u) override {
179     AIDL_FATAL_IF(u.GetFields().empty(), u) << "The union '" << u.GetName() << "' has no fields.";
180     const auto& first = u.GetFields()[0];
181     CheckExplicitDefault(*first);
182   }
CheckExplicitDefaultandroid::aidl::DiagnoseExplicitDefault183   void CheckExplicitDefault(const AidlVariableDeclaration& v) {
184     if (v.IsDefaultUserSpecified()) return;
185     if (v.GetType().IsNullable()) return;
186     if (v.GetType().IsArray()) return;
187     const auto defined_type = v.GetType().GetDefinedType();
188     if (defined_type && defined_type->AsEnumDeclaration()) {
189       diag.Report(v.GetLocation(), DiagnosticID::enum_explicit_default)
190           << "The enum field '" << v.GetName() << "' has no explicit value.";
191       return;
192     }
193   }
194 };
195 
196 struct DiagnoseMixedOneway : DiagnosticsVisitor {
DiagnoseMixedOnewayandroid::aidl::DiagnoseMixedOneway197   DiagnoseMixedOneway(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseMixedOneway198   void Visit(const AidlInterface& i) override {
199     bool has_oneway = false;
200     bool has_twoway = false;
201     for (const auto& m : i.GetMethods()) {
202       if (!m->IsUserDefined()) continue;
203       if (Suppressed(*m)) continue;
204       if (m->IsOneway()) {
205         has_oneway = true;
206       } else {
207         has_twoway = true;
208       }
209     }
210     if (has_oneway && has_twoway) {
211       diag.Report(i.GetLocation(), DiagnosticID::mixed_oneway)
212           << "The interface '" << i.GetName()
213           << "' has both one-way and two-way methods. This makes it hard to reason about threading "
214              "of client code.";
215     }
216   }
Suppressedandroid::aidl::DiagnoseMixedOneway217   bool Suppressed(const AidlMethod& m) const {
218     for (const auto& w : m.GetType().SuppressWarnings()) {
219       if (w == to_string(DiagnosticID::mixed_oneway)) {
220         return true;
221       }
222     }
223     return false;
224   }
225 };
226 
227 struct DiagnoseRedundantOneway : DiagnosticsVisitor {
DiagnoseRedundantOnewayandroid::aidl::DiagnoseRedundantOneway228   DiagnoseRedundantOneway(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseRedundantOneway229   void Visit(const AidlInterface& i) override {
230     if (i.HasOnewayAnnotation()) {
231       for (const auto& m : i.GetMethods()) {
232         if (!m->IsUserDefined()) continue;
233         if (Suppressed(*m)) continue;
234         if (m->HasOnewayAnnotation()) {
235           diag.Report(i.GetLocation(), DiagnosticID::redundant_oneway)
236               << "The interface '" << i.GetName()
237               << "' is oneway. Redundant oneway annotation for method '" << m->GetName() << "'.";
238         }
239       }
240     }
241   }
Suppressedandroid::aidl::DiagnoseRedundantOneway242   bool Suppressed(const AidlMethod& m) const {
243     for (const auto& w : m.GetType().SuppressWarnings()) {
244       if (w == to_string(DiagnosticID::redundant_oneway)) {
245         return true;
246       }
247     }
248     return false;
249   }
250 };
251 
252 struct DiagnoseOutArray : DiagnosticsVisitor {
DiagnoseOutArrayandroid::aidl::DiagnoseOutArray253   DiagnoseOutArray(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseOutArray254   void Visit(const AidlMethod& m) override {
255     for (const auto& a : m.GetArguments()) {
256       if (a->GetType().IsArray() && a->IsOut()) {
257         diag.Report(m.GetLocation(), DiagnosticID::out_array)
258             << "The method '" << m.GetName() << "' an array output parameter '" << a->GetName()
259             << "'. Instead prefer APIs like '" << a->GetType().Signature() << " " << m.GetName()
260             << "(...).";
261       }
262     }
263   }
264 };
265 
266 struct DiagnoseFileDescriptor : DiagnosticsVisitor {
DiagnoseFileDescriptorandroid::aidl::DiagnoseFileDescriptor267   DiagnoseFileDescriptor(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseFileDescriptor268   void Visit(const AidlTypeSpecifier& t) override {
269     if (t.GetName() == "FileDescriptor") {
270       diag.Report(t.GetLocation(), DiagnosticID::file_descriptor)
271           << "Please use ParcelFileDescriptor instead of FileDescriptor.";
272     }
273   }
274 };
275 
276 struct DiagnoseOutNullable : DiagnosticsVisitor {
DiagnoseOutNullableandroid::aidl::DiagnoseOutNullable277   DiagnoseOutNullable(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseOutNullable278   void Visit(const AidlArgument& a) override {
279     if (a.GetType().IsArray()) return;
280     if (a.IsOut() && a.GetType().IsNullable()) {
281       diag.Report(a.GetLocation(), DiagnosticID::out_nullable)
282           << "'" << a.GetName() << "' is an " << a.GetDirectionSpecifier()
283           << " parameter and also nullable. Some backends don't support setting null value to out "
284              "parameters. Please use it as return value or drop @nullable to avoid potential "
285              "errors.";
286     }
287   }
288 };
289 
290 struct DiagnoseImports : DiagnosticsVisitor {
DiagnoseImportsandroid::aidl::DiagnoseImports291   DiagnoseImports(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseImports292   void Visit(const AidlDocument& doc) override {
293     auto collide_with_decls = [&](const auto& import) {
294       for (const auto& type : doc.DefinedTypes()) {
295         if (type->GetCanonicalName() != import && type->GetName() == SimpleName(import)) {
296           return true;
297         }
298       }
299       return false;
300     };
301 
302     std::set<std::string> imported_names;
303     for (const auto& import : doc.Imports()) {
304       if (collide_with_decls(import)) {
305         diag.Report(doc.GetLocation(), DiagnosticID::unique_import)
306             << SimpleName(import) << " is already defined in this file.";
307       }
308       auto [_, inserted] = imported_names.insert(SimpleName(import));
309       if (!inserted) {
310         diag.Report(doc.GetLocation(), DiagnosticID::unique_import)
311             << SimpleName(import) << " is already imported.";
312       }
313     }
314   }
315 };
316 
317 struct DiagnoseUntypedCollection : DiagnosticsVisitor {
DiagnoseUntypedCollectionandroid::aidl::DiagnoseUntypedCollection318   DiagnoseUntypedCollection(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnoseUntypedCollection319   void Visit(const AidlTypeSpecifier& t) override {
320     if (t.GetName() == "List" || t.GetName() == "Map") {
321       if (!t.IsGeneric()) {
322         diag.Report(t.GetLocation(), DiagnosticID::untyped_collection)
323             << "Use List<V> or Map<K,V> instead.";
324       }
325     }
326   }
327 };
328 
329 struct DiagnosePermissionAnnotations : DiagnosticsVisitor {
DiagnosePermissionAnnotationsandroid::aidl::DiagnosePermissionAnnotations330   DiagnosePermissionAnnotations(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
Visitandroid::aidl::DiagnosePermissionAnnotations331   void Visit(const AidlInterface& intf) override {
332     const std::string diag_message =
333         " is not annotated for permissions. Declare which permissions are "
334         "required using @EnforcePermission. If permissions are manually "
335         "verified within the implementation, use @PermissionManuallyEnforced. "
336         "If no permissions are required, use @RequiresNoPermission.";
337     if (intf.IsPermissionAnnotated()) {
338       return;
339     }
340     const auto& methods = intf.GetMethods();
341     std::vector<size_t> methods_without_annotations;
342     size_t num_user_defined_methods = 0;
343     for (size_t i = 0; i < methods.size(); ++i) {
344       auto& m = methods[i];
345       if (!m->IsUserDefined()) continue;
346       num_user_defined_methods++;
347       if (m->GetType().IsPermissionAnnotated()) {
348         continue;
349       }
350       methods_without_annotations.push_back(i);
351     }
352     if (methods_without_annotations.size() == num_user_defined_methods) {
353       diag.Report(intf.GetLocation(), DiagnosticID::missing_permission_annotation)
354           << intf.GetName() << diag_message
355           << " This can be done for the whole interface or for each method.";
356     } else {
357       for (size_t i : methods_without_annotations) {
358         auto& m = methods[i];
359         diag.Report(m->GetLocation(), DiagnosticID::missing_permission_annotation)
360             << m->GetName() << diag_message;
361       }
362     }
363   }
364 };
365 
366 struct DiagnoseRedundantNames : DiagnosticsVisitor {
DiagnoseRedundantNamesandroid::aidl::DiagnoseRedundantNames367   DiagnoseRedundantNames(DiagnosticsContext& diag) : DiagnosticsVisitor(diag) {}
368 
369   // tokenize the name with either capital letters or '_' being the delimiters
TokenizeNameandroid::aidl::DiagnoseRedundantNames370   static std::vector<std::string> TokenizeName(const std::string& name) {
371     // if a name is all capitals with no '_', then we don't want to tokenize it.
372     if (std::all_of(name.begin(), name.end(), [](unsigned char c) { return isupper(c); })) {
373       return {name};
374     }
375     // if a name has an `_` in it, it will be tokenized based on '_',
376     // otherwise based on capital letters
377     if (name.find('_') != std::string::npos) {
378       return base::Tokenize(name, "_");
379     }
380 
381     std::vector<std::string> tokens;
382     size_t size = name.size();
383     std::string tmp{name.front()};
384     // Skip the first character to avoid an empty substring for common cases
385     for (size_t i = 1; i < size; i++) {
386       if (std::isupper(name[i])) {
387         tokens.push_back(tmp);
388         tmp.clear();
389         // This uppercase letter belongs to the next token
390         tmp += name[i];
391       } else {
392         tmp += name[i];
393       }
394     }
395 
396     if (!tmp.empty()) tokens.push_back(tmp);
397 
398     return tokens;
399   }
400 
Visitandroid::aidl::DiagnoseRedundantNames401   void Visit(const AidlEnumDeclaration& e) override {
402     const std::vector<std::string> parent = TokenizeName(e.GetName());
403     for (const auto& enumerator : e.GetEnumerators()) {
404       const std::vector<std::string> child = TokenizeName(enumerator->GetName());
405       for (const auto& parentSubStr : parent) {
406         for (const auto& childSubStr : child) {
407           if (ToUpper(parentSubStr) == ToUpper(childSubStr)) {
408             diag.Report(e.GetLocation(), DiagnosticID::redundant_name)
409                 << "The enumerator '" << enumerator->GetName() << "' has a redundant substring '"
410                 << childSubStr << "' being defined in '" << e.GetName() << "'";
411           }
412         }
413       }
414     }
415   }
416 
CheckConstantDeclarationsandroid::aidl::DiagnoseRedundantNames417   void CheckConstantDeclarations(
418       const std::string& name,
419       const std::vector<std::unique_ptr<AidlConstantDeclaration>>& consts) {
420     const std::vector<std::string> parent = TokenizeName(name);
421     for (const auto& member : consts) {
422       const std::vector<std::string> child = TokenizeName(member->GetName());
423       for (const auto& parentSubStr : parent) {
424         for (const auto& childSubStr : child) {
425           if (ToUpper(parentSubStr) == ToUpper(childSubStr)) {
426             diag.Report(member->GetLocation(), DiagnosticID::redundant_name)
427                 << "The constant '" << member->GetName() << "' has a redundant substring '"
428                 << childSubStr << "' being defined in '" << name << "'";
429           }
430         }
431       }
432     }
433   }
434 
Visitandroid::aidl::DiagnoseRedundantNames435   void Visit(const AidlInterface& t) override {
436     CheckConstantDeclarations(t.GetName(), t.GetConstantDeclarations());
437   }
438 
Visitandroid::aidl::DiagnoseRedundantNames439   void Visit(const AidlUnionDecl& t) override {
440     CheckConstantDeclarations(t.GetName(), t.GetConstantDeclarations());
441   }
442 
Visitandroid::aidl::DiagnoseRedundantNames443   void Visit(const AidlStructuredParcelable& t) override {
444     CheckConstantDeclarations(t.GetName(), t.GetConstantDeclarations());
445   }
446 };
447 
Diagnose(const AidlDocument & doc,const DiagnosticMapping & mapping)448 bool Diagnose(const AidlDocument& doc, const DiagnosticMapping& mapping) {
449   DiagnosticsContext diag(mapping);
450 
451   DiagnoseInterfaceName{diag}.Check(doc);
452   DiagnoseInoutParameter{diag}.Check(doc);
453   DiagnoseConstName{diag}.Check(doc);
454   DiagnoseExplicitDefault{diag}.Check(doc);
455   DiagnoseMixedOneway{diag}.Check(doc);
456   DiagnoseOutArray{diag}.Check(doc);
457   DiagnoseFileDescriptor{diag}.Check(doc);
458   DiagnoseOutNullable{diag}.Check(doc);
459   DiagnoseImports{diag}.Check(doc);
460   DiagnoseUntypedCollection{diag}.Check(doc);
461   DiagnosePermissionAnnotations{diag}.Check(doc);
462   DiagnoseRedundantNames{diag}.Check(doc);
463   DiagnoseRedundantOneway{diag}.Check(doc);
464 
465   return diag.ErrorCount() == 0;
466 }
467 }  // namespace aidl
468 }  // namespace android
469