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