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_typenames.h"
18 #include "aidl_language.h"
19 #include "logging.h"
20 
21 #include <android-base/strings.h>
22 
23 #include <map>
24 #include <memory>
25 #include <set>
26 #include <string>
27 #include <utility>
28 #include <vector>
29 
30 using android::base::Split;
31 
32 using std::make_pair;
33 using std::map;
34 using std::pair;
35 using std::set;
36 using std::string;
37 using std::unique_ptr;
38 using std::vector;
39 
40 namespace android {
41 namespace aidl {
42 
43 // The built-in AIDL types..
44 static const set<string> kBuiltinTypes = {"void",
45                                           "boolean",
46                                           "byte",
47                                           "char",
48                                           "int",
49                                           "long",
50                                           "float",
51                                           "double",
52                                           "String",
53                                           "List",
54                                           "Map",
55                                           "IBinder",
56                                           "FileDescriptor",
57                                           "CharSequence",
58                                           "ParcelFileDescriptor",
59                                           "ParcelableHolder"};
60 
61 static const set<string> kPrimitiveTypes = {"void", "boolean", "byte",  "char",
62                                             "int",  "long",    "float", "double"};
63 
64 // Note: these types may look wrong because they look like Java
65 // types, but they have long been supported from the time when Java
66 // was the only target language of this compiler. They are added here for
67 // backwards compatibility, but we internally treat them as List and Map,
68 // respectively.
69 static const map<string, string> kJavaLikeTypeToAidlType = {
70     {"java.util.List", "List"},
71     {"java.util.Map", "Map"},
72     {"android.os.ParcelFileDescriptor", "ParcelFileDescriptor"},
73 };
74 
75 // Package name and type name can't be one of these as they are keywords
76 // in Java and C++. Using these names will eventually cause compilation error,
77 // so checking this here is not a must have, but early detection of errors
78 // is always better.
79 static const set<string> kCppOrJavaReservedWord = {
80     "break",  "case",   "catch", "char",     "class",  "continue", "default",
81     "do",     "double", "else",  "enum",     "false",  "float",    "for",
82     "goto",   "if",     "int",   "long",     "new",    "private",  "protected",
83     "public", "return", "short", "static",   "switch", "this",     "throw",
84     "true",   "try",    "void",  "volatile", "while"};
85 
HasValidNameComponents(const AidlDefinedType & defined)86 static bool HasValidNameComponents(const AidlDefinedType& defined) {
87   bool success = true;
88   vector<string> pieces = Split(defined.GetCanonicalName(), ".");
89   for (const string& piece : pieces) {
90     if (kCppOrJavaReservedWord.find(piece) != kCppOrJavaReservedWord.end()) {
91       AIDL_ERROR(defined) << defined.GetCanonicalName() << " is an invalid name because '" << piece
92                           << "' is a Java or C++ identifier.";
93       success = false;
94     }
95     // not checking kJavaLikeTypeToAidl, since that wouldn't make sense here
96     if (kBuiltinTypes.find(piece) != kBuiltinTypes.end()) {
97       AIDL_ERROR(defined) << defined.GetCanonicalName() << " is an invalid name because '" << piece
98                           << "' is a built-in AIDL type.";
99       success = false;
100     }
101   }
102   return success;
103 }
104 
IsIgnorableImport(const string & import) const105 bool AidlTypenames::IsIgnorableImport(const string& import) const {
106   static set<string> ignore_import = {"android.os.IInterface",   "android.os.IBinder",
107                                       "android.os.Parcelable",   "android.os.Parcel",
108                                       "android.content.Context", "java.lang.String"};
109   // these known built-in types don't need to be imported
110   const bool in_ignore_import = ignore_import.find(import) != ignore_import.end();
111   // an already defined type doesn't need to be imported again unless it is from
112   // the preprocessed file
113   auto ret = TryGetDefinedTypeImpl(import);
114   const bool defined_type_not_from_preprocessed = ret.type != nullptr && !ret.from_preprocessed;
115   return in_ignore_import || defined_type_not_from_preprocessed;
116 }
117 
AddDocument(std::unique_ptr<AidlDocument> doc)118 bool AidlTypenames::AddDocument(std::unique_ptr<AidlDocument> doc) {
119   for (const auto& type : doc->DefinedTypes()) {
120     if (defined_types_.find(type->GetCanonicalName()) != defined_types_.end()) {
121       return false;
122     }
123     if (!HasValidNameComponents(*type)) {
124       return false;
125     }
126   }
127   documents_.push_back(std::move(doc));
128   for (const auto& type : documents_.back()->DefinedTypes()) {
129     defined_types_.emplace(type->GetCanonicalName(), type.get());
130   }
131   return true;
132 }
133 
MainDocument() const134 const AidlDocument& AidlTypenames::MainDocument() const {
135   CHECK(documents_.size() != 0) << "Main document doesn't exist";
136   return *(documents_[0]);
137 }
138 
AddPreprocessedType(unique_ptr<AidlDefinedType> type)139 bool AidlTypenames::AddPreprocessedType(unique_ptr<AidlDefinedType> type) {
140   const string name = type->GetCanonicalName();
141   if (preprocessed_types_.find(name) != preprocessed_types_.end()) {
142     return false;
143   }
144   if (!HasValidNameComponents(*type)) {
145     return false;
146   }
147   preprocessed_types_.insert(make_pair(name, std::move(type)));
148   return true;
149 }
150 
IsBuiltinTypename(const string & type_name)151 bool AidlTypenames::IsBuiltinTypename(const string& type_name) {
152   return kBuiltinTypes.find(type_name) != kBuiltinTypes.end() ||
153       kJavaLikeTypeToAidlType.find(type_name) != kJavaLikeTypeToAidlType.end();
154 }
155 
IsPrimitiveTypename(const string & type_name)156 bool AidlTypenames::IsPrimitiveTypename(const string& type_name) {
157   return kPrimitiveTypes.find(type_name) != kPrimitiveTypes.end();
158 }
159 
TryGetDefinedType(const string & type_name) const160 const AidlDefinedType* AidlTypenames::TryGetDefinedType(const string& type_name) const {
161   return TryGetDefinedTypeImpl(type_name).type;
162 }
163 
TryGetDefinedTypeImpl(const string & type_name) const164 AidlTypenames::DefinedImplResult AidlTypenames::TryGetDefinedTypeImpl(
165     const string& type_name) const {
166   // Do the exact match first.
167   auto found_def = defined_types_.find(type_name);
168   if (found_def != defined_types_.end()) {
169     return DefinedImplResult(found_def->second, false);
170   }
171 
172   auto found_prep = preprocessed_types_.find(type_name);
173   if (found_prep != preprocessed_types_.end()) {
174     return DefinedImplResult(found_prep->second.get(), true);
175   }
176 
177   // Then match with the class name. Defined types has higher priority than
178   // types from the preprocessed file.
179   for (auto it = defined_types_.begin(); it != defined_types_.end(); it++) {
180     if (it->second->GetName() == type_name) {
181       return DefinedImplResult(it->second, false);
182     }
183   }
184 
185   for (auto it = preprocessed_types_.begin(); it != preprocessed_types_.end(); it++) {
186     if (it->second->GetName() == type_name) {
187       return DefinedImplResult(it->second.get(), true);
188     }
189   }
190 
191   return DefinedImplResult(nullptr, false);
192 }
193 
AllDefinedTypes() const194 std::vector<AidlDefinedType*> AidlTypenames::AllDefinedTypes() const {
195   std::vector<AidlDefinedType*> res;
196   for (const auto& d : AllDocuments()) {
197     for (const auto& t : d->DefinedTypes()) {
198       res.push_back(t.get());
199     }
200   }
201   return res;
202 }
203 
ResolveTypename(const string & type_name) const204 AidlTypenames::ResolvedTypename AidlTypenames::ResolveTypename(const string& type_name) const {
205   if (IsBuiltinTypename(type_name)) {
206     auto found = kJavaLikeTypeToAidlType.find(type_name);
207     if (found != kJavaLikeTypeToAidlType.end()) {
208       return {found->second, true};
209     }
210     return {type_name, true};
211   }
212   const AidlDefinedType* defined_type = TryGetDefinedType(type_name);
213   if (defined_type != nullptr) {
214     return {defined_type->GetCanonicalName(), true};
215   } else {
216     return {type_name, false};
217   }
218 }
219 
220 // Only immutable Parcelable, primitive type, and String, and List, Map, array of the types can be
221 // immutable.
CanBeImmutable(const AidlTypeSpecifier & type) const222 bool AidlTypenames::CanBeImmutable(const AidlTypeSpecifier& type) const {
223   const string& name = type.GetName();
224   if (type.IsGeneric()) {
225     if (type.GetName() == "List" || type.GetName() == "Map") {
226       const auto& types = type.GetTypeParameters();
227       return std::all_of(types.begin(), types.end(),
228                          [this](const auto& t) { return CanBeImmutable(*t); });
229     }
230     AIDL_ERROR(type) << "For a generic type, an immutable parcelable can contain only List or Map.";
231     return false;
232   }
233   if (IsPrimitiveTypename(name) || name == "String") {
234     return true;
235   }
236   const AidlDefinedType* t = TryGetDefinedType(type.GetName());
237   if (t == nullptr) {
238     AIDL_ERROR(type) << "An immutable parcelable can contain only immutable Parcelable, primitive "
239                         "type, and String.";
240     return false;
241   }
242   return t->IsImmutable();
243 }
244 
245 // Only T[], List, Map, ParcelFileDescriptor and mutable Parcelable can be an out parameter.
CanBeOutParameter(const AidlTypeSpecifier & type) const246 bool AidlTypenames::CanBeOutParameter(const AidlTypeSpecifier& type) const {
247   const string& name = type.GetName();
248   if (IsBuiltinTypename(name) || GetEnumDeclaration(type)) {
249     return type.IsArray() || type.GetName() == "List" || type.GetName() == "Map" ||
250            type.GetName() == "ParcelFileDescriptor";
251   }
252   const AidlDefinedType* t = TryGetDefinedType(type.GetName());
253   CHECK(t != nullptr) << "Unrecognized type: '" << type.GetName() << "'";
254   // An 'out' field is passed as an argument, so it doesn't make sense if it is immutable.
255   return t->AsParcelable() != nullptr && !t->IsImmutable();
256 }
257 
GetEnumDeclaration(const AidlTypeSpecifier & type) const258 const AidlEnumDeclaration* AidlTypenames::GetEnumDeclaration(const AidlTypeSpecifier& type) const {
259   if (auto defined_type = TryGetDefinedType(type.GetName()); defined_type != nullptr) {
260     if (auto enum_decl = defined_type->AsEnumDeclaration(); enum_decl != nullptr) {
261       return enum_decl;
262     }
263   }
264   return nullptr;
265 }
266 
GetInterface(const AidlTypeSpecifier & type) const267 const AidlInterface* AidlTypenames::GetInterface(const AidlTypeSpecifier& type) const {
268   if (auto defined_type = TryGetDefinedType(type.GetName()); defined_type != nullptr) {
269     if (auto intf = defined_type->AsInterface(); intf != nullptr) {
270       return intf;
271     }
272   }
273   return nullptr;
274 }
275 
IterateTypes(const std::function<void (const AidlDefinedType &)> & body) const276 void AidlTypenames::IterateTypes(const std::function<void(const AidlDefinedType&)>& body) const {
277   for (const auto& kv : defined_types_) {
278     body(*kv.second);
279   }
280   for (const auto& kv : preprocessed_types_) {
281     body(*kv.second);
282   }
283 }
284 
285 }  // namespace aidl
286 }  // namespace android
287