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