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       // @JavaDerive doesn't affect read/write
86       AidlAnnotation::Type::JAVA_DERIVE,
87       AidlAnnotation::Type::JAVA_DEFAULT,
88       AidlAnnotation::Type::JAVA_DELEGATOR,
89       AidlAnnotation::Type::JAVA_ONLY_IMMUTABLE,
90       AidlAnnotation::Type::JAVA_PASSTHROUGH,
91       AidlAnnotation::Type::JAVA_SUPPRESS_LINT,
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 auto& 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->ValueString(AidlConstantValueDecorator);
158     const string new_value = new_c->ValueString(AidlConstantValueDecorator);
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()->ValueString(
231                                   enum_decl.GetBackingType(), AidlConstantValueDecorator) == "0";
232                      });
233 }
234 
EvaluatesToZero(const AidlEnumDeclaration & enum_decl,const AidlConstantValue * value)235 static bool EvaluatesToZero(const AidlEnumDeclaration& enum_decl, const AidlConstantValue* value) {
236   if (value == nullptr) return true;
237   return value->ValueString(enum_decl.GetBackingType(), AidlConstantValueDecorator) == "0";
238 }
239 
are_compatible_parcelables(const AidlDefinedType & older,const AidlTypenames &,const AidlDefinedType & newer,const AidlTypenames & new_types)240 static bool are_compatible_parcelables(const AidlDefinedType& older, const AidlTypenames&,
241                                        const AidlDefinedType& newer,
242                                        const AidlTypenames& new_types) {
243   const auto& old_fields = older.GetFields();
244   const auto& new_fields = newer.GetFields();
245   if (old_fields.size() > new_fields.size()) {
246     // you can add new fields only at the end
247     AIDL_ERROR(newer) << "Number of fields in " << older.GetCanonicalName() << " is reduced from "
248                       << old_fields.size() << " to " << new_fields.size() << ".";
249     return false;
250   }
251   if (newer.IsFixedSize() && old_fields.size() != new_fields.size()) {
252     AIDL_ERROR(newer) << "Number of fields in " << older.GetCanonicalName() << " is changed from "
253                       << old_fields.size() << " to " << new_fields.size()
254                       << ". This is an incompatible change for FixedSize types.";
255     return false;
256   }
257 
258   // android.net.UidRangeParcel should be frozen to prevent breakage in legacy (b/186720556)
259   if (older.GetCanonicalName() == "android.net.UidRangeParcel" &&
260       old_fields.size() != new_fields.size()) {
261     AIDL_ERROR(newer) << "Number of fields in " << older.GetCanonicalName() << " is changed from "
262                       << old_fields.size() << " to " << new_fields.size()
263                       << ". But it is forbidden because of legacy support.";
264     return false;
265   }
266 
267   bool compatible = true;
268   for (size_t i = 0; i < old_fields.size(); i++) {
269     const auto& old_field = old_fields.at(i);
270     const auto& new_field = new_fields.at(i);
271     compatible &= are_compatible_types(old_field->GetType(), new_field->GetType());
272 
273     const string old_value = old_field->ValueString(AidlConstantValueDecorator);
274     const string new_value = new_field->ValueString(AidlConstantValueDecorator);
275     if (old_value == new_value) {
276       continue;
277     }
278     // For enum type fields, we accept setting explicit default value which is "zero"
279     auto enum_decl = new_types.GetEnumDeclaration(new_field->GetType());
280     if (old_value == "" && enum_decl && EvaluatesToZero(*enum_decl, new_field->GetDefaultValue())) {
281       continue;
282     }
283 
284     AIDL_ERROR(new_field) << "Changed default value: " << old_value << " to " << new_value << ".";
285     compatible = false;
286   }
287 
288   // Reordering of fields is an incompatible change.
289   for (size_t i = 0; i < new_fields.size(); i++) {
290     const auto& new_field = new_fields.at(i);
291     auto found = std::find_if(old_fields.begin(), old_fields.end(), [&new_field](const auto& f) {
292       return new_field->GetName() == f->GetName();
293     });
294     if (found != old_fields.end()) {
295       size_t old_index = std::distance(old_fields.begin(), found);
296       if (old_index != i) {
297         AIDL_ERROR(new_field) << "Reordered " << new_field->GetName() << " from " << old_index
298                               << " to " << i << ".";
299         compatible = false;
300       }
301     }
302   }
303 
304   // New fields must have default values.
305   if (older.AsUnionDeclaration() == nullptr) {
306     for (size_t i = old_fields.size(); i < new_fields.size(); i++) {
307       const auto& new_field = new_fields.at(i);
308       if (new_field->HasUsefulDefaultValue()) {
309         continue;
310       }
311 
312       // enum can't be nullable, but it's okay if it has 0 as a valid enumerator.
313       if (const auto& enum_decl = new_types.GetEnumDeclaration(new_field->GetType());
314           enum_decl != nullptr) {
315         if (HasZeroEnumerator(*enum_decl)) {
316           continue;
317         }
318 
319         // TODO(b/142893595): Rephrase the message: "provide a default value or make sure ..."
320         AIDL_ERROR(new_field) << "Field '" << new_field->GetName() << "' of enum '"
321                               << enum_decl->GetName()
322                               << "' can't be initialized as '0'. Please make sure '"
323                               << enum_decl->GetName() << "' has '0' as a valid value.";
324         compatible = false;
325         continue;
326       }
327 
328       // Old API versions may suffer from the issue presented here. There is
329       // only a finite number in Android, which we must allow indefinitely.
330       struct HistoricalException {
331         std::string canonical;
332         std::string field;
333       };
334       static std::vector<HistoricalException> exceptions = {
335           {"android.net.DhcpResultsParcelable", "serverHostName"},
336           {"android.net.ResolverParamsParcel", "resolverOptions"},
337       };
338       bool excepted = false;
339       for (const HistoricalException& exception : exceptions) {
340         if (older.GetCanonicalName() == exception.canonical &&
341             new_field->GetName() == exception.field) {
342           excepted = true;
343           break;
344         }
345       }
346       if (excepted) continue;
347 
348       AIDL_ERROR(new_field)
349           << "Field '" << new_field->GetName()
350           << "' does not have a useful default in some backends. Please either provide a default "
351              "value for this field or mark the field as @nullable. This value or a null value will "
352              "be used automatically when an old version of this parcelable is sent to a process "
353              "which understands a new version of this parcelable. In order to make sure your code "
354              "continues to be backwards compatible, make sure the default or null value does not "
355              "cause a semantic change to this parcelable.";
356       compatible = false;
357     }
358   }
359 
360   compatible = are_compatible_constants(older, newer) && compatible;
361 
362   return compatible;
363 }
364 
are_compatible_enums(const AidlEnumDeclaration & older,const AidlEnumDeclaration & newer)365 static bool are_compatible_enums(const AidlEnumDeclaration& older,
366                                  const AidlEnumDeclaration& newer) {
367   std::map<std::string, const AidlConstantValue*> old_enum_map;
368   for (const auto& enumerator : older.GetEnumerators()) {
369     old_enum_map[enumerator->GetName()] = enumerator->GetValue();
370   }
371   std::map<std::string, const AidlConstantValue*> new_enum_map;
372   for (const auto& enumerator : newer.GetEnumerators()) {
373     new_enum_map[enumerator->GetName()] = enumerator->GetValue();
374   }
375 
376   bool compatible = true;
377   for (const auto& [name, value] : old_enum_map) {
378     if (new_enum_map.find(name) == new_enum_map.end()) {
379       AIDL_ERROR(newer) << "Removed enumerator from " << older.GetCanonicalName() << ": " << name;
380       compatible = false;
381       continue;
382     }
383     const string old_value =
384         old_enum_map[name]->ValueString(older.GetBackingType(), AidlConstantValueDecorator);
385     const string new_value =
386         new_enum_map[name]->ValueString(newer.GetBackingType(), AidlConstantValueDecorator);
387     if (old_value != new_value) {
388       AIDL_ERROR(newer) << "Changed enumerator value: " << older.GetCanonicalName() << "::" << name
389                         << " from " << old_value << " to " << new_value << ".";
390       compatible = false;
391     }
392   }
393   return compatible;
394 }
395 
LoadApiDump(const Options & options,const IoDelegate & io_delegate,const std::string & dir)396 Result<AidlTypenames> LoadApiDump(const Options& options, const IoDelegate& io_delegate,
397                                   const std::string& dir) {
398   Result<std::vector<std::string>> dir_files = io_delegate.ListFiles(dir);
399   if (!dir_files.ok()) {
400     AIDL_ERROR(dir) << dir_files.error();
401     return Error();
402   }
403 
404   AidlTypenames typenames;
405   for (const auto& file : *dir_files) {
406     if (!android::base::EndsWith(file, ".aidl")) continue;
407     // current "dir" is added to "imports" so that referenced.aidl files in the current
408     // module are available when resolving references.
409     if (internals::load_and_validate_aidl(file, options.PlusImportDir(dir), io_delegate, &typenames,
410                                           nullptr /* imported_files */) != AidlError::OK) {
411       AIDL_ERROR(file) << "Failed to read.";
412       return Error();
413     }
414   }
415 
416   return typenames;
417 }
418 
check_api(const Options & options,const IoDelegate & io_delegate)419 bool check_api(const Options& options, const IoDelegate& io_delegate) {
420   AIDL_FATAL_IF(!options.IsStructured(), AIDL_LOCATION_HERE);
421   AIDL_FATAL_IF(options.InputFiles().size() != 2, AIDL_LOCATION_HERE)
422       << "--checkapi requires two inputs "
423       << "but got " << options.InputFiles().size();
424   auto old_tns = LoadApiDump(options, io_delegate, options.InputFiles().at(0));
425   if (!old_tns.ok()) {
426     return false;
427   }
428   auto new_tns = LoadApiDump(options, io_delegate, options.InputFiles().at(1));
429   if (!new_tns.ok()) {
430     return false;
431   }
432 
433   const Options::CheckApiLevel level = options.GetCheckApiLevel();
434 
435   // We don't check impoted types.
436   auto get_types_in = [](const AidlTypenames& tns, const std::string& location) {
437     std::vector<const AidlDefinedType*> types;
438     for (const auto& type : tns.AllDefinedTypes()) {
439       if (StartsWith(type->GetLocation().GetFile(), location)) {
440         types.push_back(type);
441       }
442     }
443     return types;
444   };
445   std::vector<const AidlDefinedType*> old_types =
446       get_types_in(*old_tns, options.InputFiles().at(0));
447   std::vector<const AidlDefinedType*> new_types =
448       get_types_in(*new_tns, options.InputFiles().at(1));
449 
450   bool compatible = true;
451 
452   if (level == Options::CheckApiLevel::EQUAL) {
453     std::set<string> old_type_names;
454     for (const auto t : old_types) {
455       old_type_names.insert(t->GetCanonicalName());
456     }
457     for (const auto new_type : new_types) {
458       const auto found = old_type_names.find(new_type->GetCanonicalName());
459       if (found == old_type_names.end()) {
460         AIDL_ERROR(new_type) << "Added type: " << new_type->GetCanonicalName();
461         compatible = false;
462         continue;
463       }
464     }
465   }
466 
467   map<string, const AidlDefinedType*> new_map;
468   for (const auto t : new_types) {
469     new_map.emplace(t->GetCanonicalName(), t);
470   }
471 
472   for (const auto old_type : old_types) {
473     const auto found = new_map.find(old_type->GetCanonicalName());
474     if (found == new_map.end()) {
475       AIDL_ERROR(old_type) << "Removed type: " << old_type->GetCanonicalName();
476       compatible = false;
477       continue;
478     }
479     const auto new_type = found->second;
480 
481     if (level == Options::CheckApiLevel::EQUAL) {
482       if (!CheckEquality(*old_type, *new_type)) {
483         compatible = false;
484       }
485       continue;
486     }
487 
488     if (!have_compatible_annotations(*old_type, *new_type)) {
489       compatible = false;
490     }
491     if (old_type->AsInterface() != nullptr) {
492       if (new_type->AsInterface() == nullptr) {
493         AIDL_ERROR(new_type) << "Type mismatch: " << old_type->GetCanonicalName()
494                              << " is changed from " << old_type->GetPreprocessDeclarationName()
495                              << " to " << new_type->GetPreprocessDeclarationName();
496         compatible = false;
497         continue;
498       }
499       compatible &=
500           are_compatible_interfaces(*(old_type->AsInterface()), *(new_type->AsInterface()));
501     } else if (old_type->AsStructuredParcelable() != nullptr) {
502       if (new_type->AsStructuredParcelable() == nullptr) {
503         AIDL_ERROR(new_type) << "Parcelable" << new_type->GetCanonicalName()
504                              << " is not structured. ";
505         compatible = false;
506         continue;
507       }
508       compatible &= are_compatible_parcelables(*(old_type->AsStructuredParcelable()), *old_tns,
509                                                *(new_type->AsStructuredParcelable()), *new_tns);
510     } else if (old_type->AsUnstructuredParcelable() != nullptr) {
511       // We could compare annotations or cpp_header/ndk_header here, but all these changes
512       // can be safe, and it's really up to the person making these changes to make sure
513       // they are safe. This is originally added for Android Studio. In the platform build
514       // system, this can never be reached because we build with '-b'
515 
516       // ignore, do nothing
517     } else if (old_type->AsUnionDeclaration() != nullptr) {
518       if (new_type->AsUnionDeclaration() == nullptr) {
519         AIDL_ERROR(new_type) << "Type mismatch: " << old_type->GetCanonicalName()
520                              << " is changed from " << old_type->GetPreprocessDeclarationName()
521                              << " to " << new_type->GetPreprocessDeclarationName();
522         compatible = false;
523         continue;
524       }
525       compatible &= are_compatible_parcelables(*(old_type->AsUnionDeclaration()), *old_tns,
526                                                *(new_type->AsUnionDeclaration()), *new_tns);
527     } else if (old_type->AsEnumDeclaration() != nullptr) {
528       if (new_type->AsEnumDeclaration() == nullptr) {
529         AIDL_ERROR(new_type) << "Type mismatch: " << old_type->GetCanonicalName()
530                              << " is changed from " << old_type->GetPreprocessDeclarationName()
531                              << " to " << new_type->GetPreprocessDeclarationName();
532         compatible = false;
533         continue;
534       }
535       compatible &=
536           are_compatible_enums(*(old_type->AsEnumDeclaration()), *(new_type->AsEnumDeclaration()));
537     } else {
538       AIDL_ERROR(old_type) << "Unsupported declaration type "
539                            << old_type->GetPreprocessDeclarationName() << " for "
540                            << old_type->GetCanonicalName() << " API dump comparison";
541       compatible = false;
542     }
543   }
544 
545   return compatible;
546 }
547 
548 }  // namespace aidl
549 }  // namespace android
550