1 /*
2  * Copyright (C) 2018, 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 
17 #include "aidl.h"
18 
19 #include <map>
20 #include <string>
21 #include <vector>
22 
23 #include <android-base/result.h>
24 #include <android-base/strings.h>
25 #include <gtest/gtest.h>
26 
27 #include "aidl_dumpapi.h"
28 #include "aidl_language.h"
29 #include "import_resolver.h"
30 #include "logging.h"
31 #include "options.h"
32 
33 namespace android {
34 namespace aidl {
35 
36 using android::base::Error;
37 using android::base::Result;
38 using android::base::StartsWith;
39 using std::map;
40 using std::set;
41 using std::string;
42 using std::vector;
43 
44 struct DumpForEqualityVisitor : DumpVisitor {
DumpForEqualityVisitorandroid::aidl::DumpForEqualityVisitor45   DumpForEqualityVisitor(CodeWriter& out) : DumpVisitor(out) {}
46 
DumpConstantValueandroid::aidl::DumpForEqualityVisitor47   void DumpConstantValue(const AidlTypeSpecifier&, const AidlConstantValue& c) {
48     out << c.Literal();
49   }
50 };
51 
Dump(const AidlDefinedType & type)52 static std::string Dump(const AidlDefinedType& type) {
53   string code;
54   CodeWriterPtr out = CodeWriter::ForString(&code);
55   DumpForEqualityVisitor visitor(*out);
56   type.DispatchVisit(visitor);
57   out->Close();
58   return code;
59 }
60 
61 // Uses each type's Dump() and GTest utility(EqHelper).
CheckEquality(const AidlDefinedType & older,const AidlDefinedType & newer)62 static bool CheckEquality(const AidlDefinedType& older, const AidlDefinedType& newer) {
63   using testing::internal::EqHelper;
64   auto older_file = older.GetLocation().GetFile();
65   auto newer_file = newer.GetLocation().GetFile();
66   auto result = EqHelper::Compare(older_file.data(), newer_file.data(), Dump(older), Dump(newer));
67   if (!result) {
68     AIDL_ERROR(newer) << result.failure_message();
69   }
70   return result;
71 }
72 
get_strict_annotations(const AidlAnnotatable & node)73 static vector<string> get_strict_annotations(const AidlAnnotatable& node) {
74   // This must be symmetrical (if you can add something, you must be able to
75   // remove it). The reason is that we have no way of knowing which interface a
76   // server serves and which interface a client serves (e.g. a callback
77   // interface). Note that this is being overly lenient. It makes sense for
78   // newer code to start accepting nullable things. However, here, we don't know
79   // if the client of an interface or the server of an interface is newer.
80   //
81   // Here are two examples to demonstrate this:
82   // - a new implementation might change so that it no longer returns null
83   // values (remove @nullable)
84   // - a new implementation might start accepting null values (add @nullable)
85   static const set<AidlAnnotation::Type> kIgnoreAnnotations{
86       AidlAnnotation::Type::NULLABLE,
87       // @JavaDerive doesn't affect read/write
88       AidlAnnotation::Type::JAVA_DERIVE,
89       AidlAnnotation::Type::JAVA_ONLY_IMMUTABLE,
90       // @Backing for a enum type is checked by the enum checker
91       AidlAnnotation::Type::BACKING,
92       // @RustDerive doesn't affect read/write
93       AidlAnnotation::Type::RUST_DERIVE,
94       AidlAnnotation::Type::SUPPRESS_WARNINGS,
95   };
96   vector<string> annotations;
97   for (const AidlAnnotation& annotation : node.GetAnnotations()) {
98     if (kIgnoreAnnotations.find(annotation.GetType()) != kIgnoreAnnotations.end()) {
99       continue;
100     }
101     auto annotation_string = annotation.ToString();
102     // adding @Deprecated (with optional args) is okay
103     if (StartsWith(annotation_string, "@JavaPassthrough(annotation=\"@Deprecated")) {
104       continue;
105     }
106     annotations.push_back(annotation_string);
107   }
108   return annotations;
109 }
110 
have_compatible_annotations(const AidlAnnotatable & older,const AidlAnnotatable & newer)111 static bool have_compatible_annotations(const AidlAnnotatable& older,
112                                         const AidlAnnotatable& newer) {
113   vector<string> olderAnnotations = get_strict_annotations(older);
114   vector<string> newerAnnotations = get_strict_annotations(newer);
115   sort(olderAnnotations.begin(), olderAnnotations.end());
116   sort(newerAnnotations.begin(), newerAnnotations.end());
117   if (olderAnnotations != newerAnnotations) {
118     const string from = older.ToString().empty() ? "(empty)" : older.ToString();
119     const string to = newer.ToString().empty() ? "(empty)" : newer.ToString();
120     AIDL_ERROR(newer) << "Changed annotations: " << from << " to " << to;
121     return false;
122   }
123   return true;
124 }
125 
are_compatible_types(const AidlTypeSpecifier & older,const AidlTypeSpecifier & newer)126 static bool are_compatible_types(const AidlTypeSpecifier& older, const AidlTypeSpecifier& newer) {
127   bool compatible = true;
128   if (older.Signature() != newer.Signature()) {
129     AIDL_ERROR(newer) << "Type changed: " << older.Signature() << " to " << newer.Signature()
130                       << ".";
131     compatible = false;
132   }
133   compatible &= have_compatible_annotations(older, newer);
134   return compatible;
135 }
136 
are_compatible_constants(const AidlDefinedType & older,const AidlDefinedType & newer)137 static bool are_compatible_constants(const AidlDefinedType& older, const AidlDefinedType& newer) {
138   bool compatible = true;
139 
140   map<string, AidlConstantDeclaration*> new_constdecls;
141   for (const auto& c : newer.GetConstantDeclarations()) {
142     new_constdecls[c->GetName()] = &*c;
143   }
144 
145   for (const auto& old_c : older.GetConstantDeclarations()) {
146     const auto found = new_constdecls.find(old_c->GetName());
147     if (found == new_constdecls.end()) {
148       AIDL_ERROR(old_c) << "Removed constant declaration: " << older.GetCanonicalName() << "."
149                         << old_c->GetName();
150       compatible = false;
151       continue;
152     }
153 
154     const auto new_c = found->second;
155     compatible &= are_compatible_types(old_c->GetType(), new_c->GetType());
156 
157     const string old_value = old_c->GetValue().Literal();
158     const string new_value = new_c->GetValue().Literal();
159     if (old_value != new_value) {
160       AIDL_ERROR(newer) << "Changed constant value: " << older.GetCanonicalName() << "."
161                         << old_c->GetName() << " from " << old_value << " to " << new_value << ".";
162       compatible = false;
163     }
164   }
165   return compatible;
166 }
167 
are_compatible_interfaces(const AidlInterface & older,const AidlInterface & newer)168 static bool are_compatible_interfaces(const AidlInterface& older, const AidlInterface& newer) {
169   bool compatible = true;
170 
171   map<string, AidlMethod*> new_methods;
172   for (const auto& m : newer.AsInterface()->GetMethods()) {
173     new_methods.emplace(m->Signature(), m.get());
174   }
175 
176   for (const auto& old_m : older.AsInterface()->GetMethods()) {
177     const auto found = new_methods.find(old_m->Signature());
178     if (found == new_methods.end()) {
179       AIDL_ERROR(old_m) << "Removed or changed method: " << older.GetCanonicalName() << "."
180                         << old_m->Signature();
181       compatible = false;
182       continue;
183     }
184 
185     // Compare IDs to detect method reordering. IDs are assigned by their
186     // textual order, so if there is an ID mismatch, that means reordering
187     // has happened.
188     const auto new_m = found->second;
189 
190     if (old_m->IsOneway() != new_m->IsOneway()) {
191       AIDL_ERROR(new_m) << "Oneway attribute " << (old_m->IsOneway() ? "removed" : "added") << ": "
192                         << older.GetCanonicalName() << "." << old_m->Signature();
193       compatible = false;
194     }
195 
196     if (old_m->GetId() != new_m->GetId()) {
197       AIDL_ERROR(new_m) << "Transaction ID changed: " << older.GetCanonicalName() << "."
198                         << old_m->Signature() << " is changed from " << old_m->GetId() << " to "
199                         << new_m->GetId() << ".";
200       compatible = false;
201     }
202 
203     compatible &= are_compatible_types(old_m->GetType(), new_m->GetType());
204 
205     const auto& old_args = old_m->GetArguments();
206     const auto& new_args = new_m->GetArguments();
207     // this is guaranteed because arguments are part of AidlMethod::Signature()
208     AIDL_FATAL_IF(old_args.size() != new_args.size(), old_m);
209     for (size_t i = 0; i < old_args.size(); i++) {
210       const AidlArgument& old_a = *(old_args.at(i));
211       const AidlArgument& new_a = *(new_args.at(i));
212       compatible &= are_compatible_types(old_a.GetType(), new_a.GetType());
213 
214       if (old_a.GetDirection() != new_a.GetDirection()) {
215         AIDL_ERROR(new_m) << "Direction changed: " << old_a.GetDirectionSpecifier() << " to "
216                           << new_a.GetDirectionSpecifier() << ".";
217         compatible = false;
218       }
219     }
220   }
221 
222   compatible = are_compatible_constants(older, newer) && compatible;
223 
224   return compatible;
225 }
226 
HasZeroEnumerator(const AidlEnumDeclaration & enum_decl)227 static bool HasZeroEnumerator(const AidlEnumDeclaration& enum_decl) {
228   return std::any_of(enum_decl.GetEnumerators().begin(), enum_decl.GetEnumerators().end(),
229                      [&](const unique_ptr<AidlEnumerator>& enumerator) {
230                        return enumerator->GetValue()->Literal() == "0";
231                      });
232 }
233 
EvaluatesToZero(const AidlEnumDeclaration & enum_decl,const std::string & value)234 static bool EvaluatesToZero(const AidlEnumDeclaration& enum_decl, const std::string& value) {
235   if (value == "") return true;
236   // Because --check_api runs with "valid" AIDL definitions, we can safely assume that
237   // the value is formatted as <scope>.<enumerator>.
238   auto enumerator_name = value.substr(value.find_last_of('.') + 1);
239   for (const auto& enumerator : enum_decl.GetEnumerators()) {
240     if (enumerator->GetName() == enumerator_name) {
241       return enumerator->GetValue()->Literal() == "0";
242     }
243   }
244   AIDL_FATAL(enum_decl) << "Can't find " << enumerator_name << " in " << enum_decl.GetName();
245 }
246 
are_compatible_parcelables(const AidlDefinedType & older,const AidlTypenames &,const AidlDefinedType & newer,const AidlTypenames & new_types)247 static bool are_compatible_parcelables(const AidlDefinedType& older, const AidlTypenames&,
248                                        const AidlDefinedType& newer,
249                                        const AidlTypenames& new_types) {
250   const auto& old_fields = older.GetFields();
251   const auto& new_fields = newer.GetFields();
252   if (old_fields.size() > new_fields.size()) {
253     // you can add new fields only at the end
254     AIDL_ERROR(newer) << "Number of fields in " << older.GetCanonicalName() << " is reduced from "
255                       << old_fields.size() << " to " << new_fields.size() << ".";
256     return false;
257   }
258   if (newer.IsFixedSize() && old_fields.size() != new_fields.size()) {
259     AIDL_ERROR(newer) << "Number of fields in " << older.GetCanonicalName() << " is changed from "
260                       << old_fields.size() << " to " << new_fields.size()
261                       << ". This is an incompatible change for FixedSize types.";
262     return false;
263   }
264 
265   // android.net.UidRangeParcel should be frozen to prevent breakage in legacy (b/186720556)
266   if (older.GetCanonicalName() == "android.net.UidRangeParcel" &&
267       old_fields.size() != new_fields.size()) {
268     AIDL_ERROR(newer) << "Number of fields in " << older.GetCanonicalName() << " is changed from "
269                       << old_fields.size() << " to " << new_fields.size()
270                       << ". But it is forbidden because of legacy support.";
271     return false;
272   }
273 
274   bool compatible = true;
275   for (size_t i = 0; i < old_fields.size(); i++) {
276     const auto& old_field = old_fields.at(i);
277     const auto& new_field = new_fields.at(i);
278     compatible &= are_compatible_types(old_field->GetType(), new_field->GetType());
279 
280     string old_value = old_field->GetDefaultValue() ? old_field->GetDefaultValue()->Literal() : "";
281     string new_value = new_field->GetDefaultValue() ? new_field->GetDefaultValue()->Literal() : "";
282 
283     if (old_value == new_value) {
284       continue;
285     }
286     // For enum type fields, we accept setting explicit default value which is "zero"
287     auto enum_decl = new_types.GetEnumDeclaration(new_field->GetType());
288     if (old_value == "" && enum_decl && EvaluatesToZero(*enum_decl, new_value)) {
289       continue;
290     }
291 
292     AIDL_ERROR(new_field) << "Changed default value: " << old_value << " to " << new_value << ".";
293     compatible = false;
294   }
295 
296   // Reordering of fields is an incompatible change.
297   for (size_t i = 0; i < new_fields.size(); i++) {
298     const auto& new_field = new_fields.at(i);
299     auto found = std::find_if(old_fields.begin(), old_fields.end(), [&new_field](const auto& f) {
300       return new_field->GetName() == f->GetName();
301     });
302     if (found != old_fields.end()) {
303       size_t old_index = std::distance(old_fields.begin(), found);
304       if (old_index != i) {
305         AIDL_ERROR(new_field) << "Reordered " << new_field->GetName() << " from " << old_index
306                               << " to " << i << ".";
307         compatible = false;
308       }
309     }
310   }
311 
312   for (size_t i = old_fields.size(); i < new_fields.size(); i++) {
313     const auto& new_field = new_fields.at(i);
314     if (new_field->HasUsefulDefaultValue()) {
315       continue;
316     }
317 
318     // enum can't be nullable, but it's okay if it has 0 as a valid enumerator.
319     if (const auto& enum_decl = new_types.GetEnumDeclaration(new_field->GetType());
320         enum_decl != nullptr) {
321       if (HasZeroEnumerator(*enum_decl)) {
322         continue;
323       }
324 
325       // TODO(b/142893595): Rephrase the message: "provide a default value or make sure ..."
326       AIDL_ERROR(new_field) << "Field '" << new_field->GetName() << "' of enum '"
327                             << enum_decl->GetName()
328                             << "' can't be initialized as '0'. Please make sure '"
329                             << enum_decl->GetName() << "' has '0' as a valid value.";
330       compatible = false;
331       continue;
332     }
333 
334     // Old API versions may suffer from the issue presented here. There is
335     // only a finite number in Android, which we must allow indefinitely.
336     struct HistoricalException {
337       std::string canonical;
338       std::string field;
339     };
340     static std::vector<HistoricalException> exceptions = {
341         {"android.net.DhcpResultsParcelable", "serverHostName"},
342         {"android.net.ResolverParamsParcel", "resolverOptions"},
343     };
344     bool excepted = false;
345     for (const HistoricalException& exception : exceptions) {
346       if (older.GetCanonicalName() == exception.canonical &&
347           new_field->GetName() == exception.field) {
348         excepted = true;
349         break;
350       }
351     }
352     if (excepted) continue;
353 
354     AIDL_ERROR(new_field)
355         << "Field '" << new_field->GetName()
356         << "' does not have a useful default in some backends. Please either provide a default "
357            "value for this field or mark the field as @nullable. This value or a null value will "
358            "be used automatically when an old version of this parcelable is sent to a process "
359            "which understands a new version of this parcelable. In order to make sure your code "
360            "continues to be backwards compatible, make sure the default or null value does not "
361            "cause a semantic change to this parcelable.";
362     compatible = false;
363   }
364 
365   compatible = are_compatible_constants(older, newer) && compatible;
366 
367   return compatible;
368 }
369 
are_compatible_enums(const AidlEnumDeclaration & older,const AidlEnumDeclaration & newer)370 static bool are_compatible_enums(const AidlEnumDeclaration& older,
371                                  const AidlEnumDeclaration& newer) {
372   if (!are_compatible_types(older.GetBackingType(), newer.GetBackingType())) {
373     AIDL_ERROR(newer) << "Changed backing types.";
374     return false;
375   }
376 
377   std::map<std::string, const AidlConstantValue*> old_enum_map;
378   for (const auto& enumerator : older.GetEnumerators()) {
379     old_enum_map[enumerator->GetName()] = enumerator->GetValue();
380   }
381   std::map<std::string, const AidlConstantValue*> new_enum_map;
382   for (const auto& enumerator : newer.GetEnumerators()) {
383     new_enum_map[enumerator->GetName()] = enumerator->GetValue();
384   }
385 
386   bool compatible = true;
387   for (const auto& [name, value] : old_enum_map) {
388     if (new_enum_map.find(name) == new_enum_map.end()) {
389       AIDL_ERROR(newer) << "Removed enumerator from " << older.GetCanonicalName() << ": " << name;
390       compatible = false;
391       continue;
392     }
393     const string old_value = old_enum_map[name]->Literal();
394     const string new_value = new_enum_map[name]->Literal();
395     if (old_value != new_value) {
396       AIDL_ERROR(newer) << "Changed enumerator value: " << older.GetCanonicalName() << "::" << name
397                         << " from " << old_value << " to " << new_value << ".";
398       compatible = false;
399     }
400   }
401   return compatible;
402 }
403 
load_from_dir(const Options & options,const IoDelegate & io_delegate,const std::string & dir)404 static Result<AidlTypenames> load_from_dir(const Options& options, const IoDelegate& io_delegate,
405                                            const std::string& dir) {
406   Result<std::vector<std::string>> dir_files = io_delegate.ListFiles(dir);
407   if (!dir_files.ok()) {
408     AIDL_ERROR(dir) << dir_files.error();
409     return Error();
410   }
411 
412   AidlTypenames typenames;
413   for (const auto& file : *dir_files) {
414     if (!android::base::EndsWith(file, ".aidl")) continue;
415     if (internals::load_and_validate_aidl(file, options, io_delegate, &typenames,
416                                           nullptr /* imported_files */) != AidlError::OK) {
417       AIDL_ERROR(file) << "Failed to read.";
418       return Error();
419     }
420   }
421 
422   return typenames;
423 }
424 
check_api(const Options & options,const IoDelegate & io_delegate)425 bool check_api(const Options& options, const IoDelegate& io_delegate) {
426   AIDL_FATAL_IF(!options.IsStructured(), AIDL_LOCATION_HERE);
427   AIDL_FATAL_IF(options.InputFiles().size() != 2, AIDL_LOCATION_HERE)
428       << "--checkapi requires two inputs "
429       << "but got " << options.InputFiles().size();
430   auto old_tns = load_from_dir(options, io_delegate, options.InputFiles().at(0));
431   if (!old_tns.ok()) {
432     return false;
433   }
434   auto new_tns = load_from_dir(options, io_delegate, options.InputFiles().at(1));
435   if (!new_tns.ok()) {
436     return false;
437   }
438 
439   const Options::CheckApiLevel level = options.GetCheckApiLevel();
440 
441   std::vector<AidlDefinedType*> old_types = old_tns->AllDefinedTypes();
442   std::vector<AidlDefinedType*> new_types = new_tns->AllDefinedTypes();
443 
444   bool compatible = true;
445 
446   if (level == Options::CheckApiLevel::EQUAL) {
447     std::set<string> old_type_names;
448     for (const auto t : old_types) {
449       old_type_names.insert(t->GetCanonicalName());
450     }
451     for (const auto new_type : new_types) {
452       const auto found = old_type_names.find(new_type->GetCanonicalName());
453       if (found == old_type_names.end()) {
454         AIDL_ERROR(new_type) << "Added type: " << new_type->GetCanonicalName();
455         compatible = false;
456         continue;
457       }
458     }
459   }
460 
461   map<string, AidlDefinedType*> new_map;
462   for (const auto t : new_types) {
463     new_map.emplace(t->GetCanonicalName(), t);
464   }
465 
466   for (const auto old_type : old_types) {
467     const auto found = new_map.find(old_type->GetCanonicalName());
468     if (found == new_map.end()) {
469       AIDL_ERROR(old_type) << "Removed type: " << old_type->GetCanonicalName();
470       compatible = false;
471       continue;
472     }
473     const auto new_type = found->second;
474 
475     if (level == Options::CheckApiLevel::EQUAL) {
476       if (!CheckEquality(*old_type, *new_type)) {
477         compatible = false;
478       }
479       continue;
480     }
481 
482     if (!have_compatible_annotations(*old_type, *new_type)) {
483       compatible = false;
484     }
485     if (old_type->AsInterface() != nullptr) {
486       if (new_type->AsInterface() == nullptr) {
487         AIDL_ERROR(new_type) << "Type mismatch: " << old_type->GetCanonicalName()
488                              << " is changed from " << old_type->GetPreprocessDeclarationName()
489                              << " to " << new_type->GetPreprocessDeclarationName();
490         compatible = false;
491         continue;
492       }
493       compatible &=
494           are_compatible_interfaces(*(old_type->AsInterface()), *(new_type->AsInterface()));
495     } else if (old_type->AsStructuredParcelable() != nullptr) {
496       if (new_type->AsStructuredParcelable() == nullptr) {
497         AIDL_ERROR(new_type) << "Parcelable" << new_type->GetCanonicalName()
498                              << " is not structured. ";
499         compatible = false;
500         continue;
501       }
502       compatible &= are_compatible_parcelables(*(old_type->AsStructuredParcelable()), *old_tns,
503                                                *(new_type->AsStructuredParcelable()), *new_tns);
504     } else if (old_type->AsUnionDeclaration() != nullptr) {
505       if (new_type->AsUnionDeclaration() == nullptr) {
506         AIDL_ERROR(new_type) << "Type mismatch: " << old_type->GetCanonicalName()
507                              << " is changed from " << old_type->GetPreprocessDeclarationName()
508                              << " to " << new_type->GetPreprocessDeclarationName();
509         compatible = false;
510         continue;
511       }
512       compatible &= are_compatible_parcelables(*(old_type->AsUnionDeclaration()), *old_tns,
513                                                *(new_type->AsUnionDeclaration()), *new_tns);
514     } else if (old_type->AsEnumDeclaration() != nullptr) {
515       if (new_type->AsEnumDeclaration() == nullptr) {
516         AIDL_ERROR(new_type) << "Type mismatch: " << old_type->GetCanonicalName()
517                              << " is changed from " << old_type->GetPreprocessDeclarationName()
518                              << " to " << new_type->GetPreprocessDeclarationName();
519         compatible = false;
520         continue;
521       }
522       compatible &=
523           are_compatible_enums(*(old_type->AsEnumDeclaration()), *(new_type->AsEnumDeclaration()));
524     } else {
525       AIDL_ERROR(old_type) << "Unsupported type " << old_type->GetPreprocessDeclarationName()
526                            << " for " << old_type->GetCanonicalName();
527       compatible = false;
528     }
529   }
530 
531   return compatible;
532 }
533 
534 }  // namespace aidl
535 }  // namespace android
536