1 /*
2 * Copyright (C) 2019, 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 "parser.h"
18
19 #include <queue>
20
21 #include "aidl_language_y.h"
22 #include "logging.h"
23
24 void yylex_init(void**);
25 void yylex_destroy(void*);
26 void yyset_in(FILE* f, void*);
27 int yyparse(Parser*);
28 YY_BUFFER_STATE yy_scan_buffer(char*, size_t, void*);
29 void yy_delete_buffer(YY_BUFFER_STATE, void*);
30
31 // For each union, generate nested "Tag" enum type so that "Tag" can be used as a valid type.
32 // union Foo { int a; int b; } => union Foo { ... enum Tag { a, b }}
33 struct UnionTagGenerater : AidlVisitor {
VisitUnionTagGenerater34 void Visit(const AidlUnionDecl& decl) override {
35 std::vector<std::unique_ptr<AidlEnumerator>> enumerators;
36 for (const auto& field : decl.GetFields()) {
37 auto derived = field->GetLocation().ToDerivedLocation();
38 AIDL_FATAL_IF(!derived, field)
39 << "Failed to get a derived location. Is this not an external type?";
40 enumerators.push_back(std::make_unique<AidlEnumerator>(*derived, field->GetName(), nullptr,
41 field->GetComments()));
42 }
43 auto derived = decl.GetLocation().ToDerivedLocation();
44 AIDL_FATAL_IF(!derived, decl)
45 << "Failed to get a derived location. Is this not an external type?";
46 auto tag_enum = std::make_unique<AidlEnumDeclaration>(*derived, "Tag", &enumerators,
47 decl.GetPackage(), Comments{});
48 // Tag for @FixedSize union is limited to "byte" type so that it can be passed via FMQ with
49 // with lower overhead.
50 std::shared_ptr<AidlConstantValue> backing_type{
51 AidlConstantValue::String(AIDL_LOCATION_HERE, decl.IsFixedSize() ? "\"byte\"" : "\"int\"")};
52 std::vector<std::unique_ptr<AidlAnnotation>> annotations;
53 annotations.push_back(
54 AidlAnnotation::Parse(AIDL_LOCATION_HERE, "Backing", {{"type", backing_type}}, Comments{}));
55 tag_enum->Annotate(std::move(annotations));
56 const_cast<AidlUnionDecl&>(decl).AddType(std::move(tag_enum));
57 }
58 };
59
Parse(const std::string & filename,const android::aidl::IoDelegate & io_delegate,AidlTypenames & typenames,bool is_preprocessed)60 const AidlDocument* Parser::Parse(const std::string& filename,
61 const android::aidl::IoDelegate& io_delegate,
62 AidlTypenames& typenames, bool is_preprocessed) {
63 auto clean_path = android::aidl::IoDelegate::CleanPath(filename);
64 // reuse pre-parsed document from typenames
65 for (auto& doc : typenames.AllDocuments()) {
66 if (doc->GetLocation().GetFile() == clean_path) {
67 return doc.get();
68 }
69 }
70 // Make sure we can read the file first, before trashing previous state.
71 unique_ptr<string> raw_buffer = io_delegate.GetFileContents(clean_path);
72 if (raw_buffer == nullptr) {
73 AIDL_ERROR(clean_path) << "Error while opening file for parsing";
74 return nullptr;
75 }
76
77 // We're going to scan this buffer in place, and yacc demands we put two
78 // nulls at the end.
79 raw_buffer->append(2u, '\0');
80
81 Parser parser(clean_path, *raw_buffer, is_preprocessed);
82
83 if (yy::parser(&parser).parse() != 0 || parser.HasError()) {
84 return nullptr;
85 }
86
87 // Preprocess parsed document before adding to typenames.
88 UnionTagGenerater v;
89 VisitTopDown(v, *parser.document_);
90
91 // transfer ownership to AidlTypenames and return the raw pointer
92 const AidlDocument* result = parser.document_.get();
93 if (!typenames.AddDocument(std::move(parser.document_))) {
94 return nullptr;
95 }
96 return result;
97 }
98
SetTypeParameters(AidlTypeSpecifier * type,std::vector<std::unique_ptr<AidlTypeSpecifier>> * type_args)99 void Parser::SetTypeParameters(AidlTypeSpecifier* type,
100 std::vector<std::unique_ptr<AidlTypeSpecifier>>* type_args) {
101 if (type->IsArray()) {
102 AIDL_ERROR(type) << "Must specify type parameters (<>) before array ([]).";
103 AddError();
104 }
105 if (!type->SetTypeParameters(type_args)) {
106 AIDL_ERROR(type) << "Can only specify one set of type parameters.";
107 AddError();
108 delete type_args;
109 }
110 }
111
CheckValidTypeName(const AidlToken & token,const AidlLocation & loc)112 void Parser::CheckValidTypeName(const AidlToken& token, const AidlLocation& loc) {
113 if (!is_preprocessed_ && token.GetText().find('.') != std::string::npos) {
114 AIDL_ERROR(loc) << "Type name can't be qualified. Use `package`.";
115 AddError();
116 }
117 }
118
SetPackage(const std::string & package)119 void Parser::SetPackage(const std::string& package) {
120 if (is_preprocessed_) {
121 AIDL_ERROR(package) << "Preprocessed file can't declare package.";
122 AddError();
123 }
124 package_ = package;
125 }
126
CheckNoRecursiveDefinition(const AidlNode & node)127 bool CheckNoRecursiveDefinition(const AidlNode& node) {
128 struct Visitor : AidlVisitor {
129 enum {
130 NOT_STARTED = 0,
131 STARTED = 1,
132 FINISHED = 2,
133 };
134 std::map<const AidlParcelable*, int> visited;
135 std::vector<std::string> path;
136 bool found_cycle = false;
137
138 void Visit(const AidlStructuredParcelable& t) override { FindCycle(&t); }
139 void Visit(const AidlUnionDecl& t) override { FindCycle(&t); }
140 void Visit(const AidlParcelable& t) override { FindCycle(&t); }
141
142 bool FindCycle(const AidlParcelable* p) {
143 // no need to search further
144 if (found_cycle) {
145 return true;
146 }
147 // we just found a cycle
148 if (visited[p] == STARTED) {
149 path.push_back(p->GetName());
150 AIDL_ERROR(p) << p->GetName()
151 << " is a recursive parcelable: " << android::base::Join(path, "->");
152 return (found_cycle = true);
153 }
154 // we arrived here with a different route.
155 if (visited[p] == FINISHED) {
156 return false;
157 }
158 // start DFS
159 visited[p] = STARTED;
160 path.push_back(p->GetName());
161 for (const auto& f : p->GetFields()) {
162 const auto& ref = f->GetType();
163 if (!ref.IsArray() && !ref.IsHeapNullable()) {
164 const auto& type = ref.GetDefinedType();
165 if (type && type->AsParcelable()) {
166 if (FindCycle(type->AsParcelable())) {
167 return true;
168 }
169 }
170 }
171 }
172 path.pop_back();
173 visited[p] = FINISHED;
174 return false;
175 }
176 } v;
177 VisitTopDown(v, node);
178 return !v.found_cycle;
179 }
180
181 // Each Visit*() method can use Scope() to get its scope(AidlDefinedType)
182 class ScopedVisitor : public AidlVisitor {
183 protected:
Scope() const184 const AidlDefinedType* Scope() const {
185 AIDL_FATAL_IF(scope_.empty(), AIDL_LOCATION_HERE) << "Scope is empty";
186 return scope_.back();
187 }
PushScope(const AidlDefinedType * scope)188 void PushScope(const AidlDefinedType* scope) { scope_.push_back(scope); }
PopScope()189 void PopScope() { scope_.pop_back(); }
190 // Keep user defined type as a defining scope
VisitScopedTopDown(const AidlNode & node)191 void VisitScopedTopDown(const AidlNode& node) {
192 std::function<void(const AidlNode&)> top_down = [&](const AidlNode& a) {
193 a.DispatchVisit(*this);
194 auto defined_type = AidlCast<AidlDefinedType>(a);
195 if (defined_type) PushScope(defined_type);
196 a.TraverseChildren(top_down);
197 if (defined_type) PopScope();
198 };
199 top_down(node);
200 }
201
202 private:
203 std::vector<const AidlDefinedType*> scope_ = {};
204 };
205
206 class TypeReferenceResolver : public ScopedVisitor {
207 public:
TypeReferenceResolver(TypeResolver & resolver)208 TypeReferenceResolver(TypeResolver& resolver) : resolver_(resolver) {}
209
Visit(const AidlTypeSpecifier & t)210 void Visit(const AidlTypeSpecifier& t) override {
211 // We're visiting the same node again. This can happen when two constant references
212 // point to an ancestor of this node.
213 if (t.IsResolved()) {
214 return;
215 }
216 AidlTypeSpecifier& type = const_cast<AidlTypeSpecifier&>(t);
217 if (!resolver_(Scope(), &type)) {
218 AIDL_ERROR(type) << "Failed to resolve '" << type.GetUnresolvedName() << "'";
219 success_ = false;
220 return;
221 }
222
223 // In case a new document is imported for the type reference, enqueue it for type resolution.
224 auto resolved = t.GetDefinedType();
225 if (resolved) {
226 queue_.push(&resolved->GetDocument());
227 }
228 }
229
Resolve(const AidlDocument & document)230 bool Resolve(const AidlDocument& document) {
231 queue_.push(&document);
232 while (!queue_.empty()) {
233 auto doc = queue_.front();
234 queue_.pop();
235 // Skip the doc if it's visited already.
236 if (!visited_.insert(doc).second) {
237 continue;
238 }
239 VisitScopedTopDown(*doc);
240 }
241 return success_;
242 }
243
244 private:
245 TypeResolver& resolver_;
246 bool success_ = true;
247 std::queue<const AidlDocument*> queue_ = {};
248 std::set<const AidlDocument*> visited_ = {};
249 };
250
251 class ConstantReferenceResolver : public ScopedVisitor {
252 public:
253 ConstantReferenceResolver() = default;
254
Visit(const AidlConstantReference & v)255 void Visit(const AidlConstantReference& v) override {
256 if (IsCircularReference(&v)) {
257 success_ = false;
258 return;
259 }
260
261 const AidlConstantValue* resolved = v.Resolve(Scope());
262 if (!resolved) {
263 AIDL_ERROR(v) << "Unknown reference '" << v.Literal() << "'";
264 success_ = false;
265 return;
266 }
267
268 // On error, skip recursive visiting to avoid redundant messages
269 if (!success_) {
270 return;
271 }
272 // resolve recursive references
273 PushConstRef(&v);
274 VisitScopedTopDown(*resolved);
275 PopConstRef();
276 }
277
Resolve(const AidlDocument & document)278 bool Resolve(const AidlDocument& document) {
279 VisitScopedTopDown(document);
280 return success_;
281 }
282
283 private:
PushConstRef(const AidlConstantReference * ref)284 void PushConstRef(const AidlConstantReference* ref) {
285 stack_.push_back(ref);
286 if (ref->GetRefType()) {
287 PushScope(ref->GetRefType()->GetDefinedType());
288 }
289 }
290
PopConstRef()291 void PopConstRef() {
292 if (stack_.back()->GetRefType()) {
293 PopScope();
294 }
295 stack_.pop_back();
296 }
297
IsCircularReference(const AidlConstantReference * ref)298 bool IsCircularReference(const AidlConstantReference* ref) {
299 auto it =
300 std::find_if(stack_.begin(), stack_.end(), [&](const auto& elem) { return elem == ref; });
301 if (it == stack_.end()) {
302 return false;
303 }
304 std::vector<std::string> path;
305 while (it != stack_.end()) {
306 path.push_back((*it)->Literal());
307 ++it;
308 }
309 path.push_back(ref->Literal());
310 AIDL_ERROR(ref) << "Found a circular reference: " << android::base::Join(path, " -> ");
311 return true;
312 }
313
314 bool success_ = true;
315 std::vector<const AidlConstantReference*> stack_ = {};
316 };
317
318 // Resolve references(types/constants) in the "main" document.
ResolveReferences(const AidlDocument & document,TypeResolver & type_resolver)319 bool ResolveReferences(const AidlDocument& document, TypeResolver& type_resolver) {
320 // Types are resolved first before resolving constant references so that every referenced document
321 // gets imported.
322 if (!TypeReferenceResolver(type_resolver).Resolve(document)) {
323 return false;
324 }
325 if (!ConstantReferenceResolver().Resolve(document)) {
326 return false;
327 }
328 if (!CheckNoRecursiveDefinition(document)) {
329 return false;
330 }
331 return true;
332 }
333
Parser(const std::string & filename,std::string & raw_buffer,bool is_preprocessed)334 Parser::Parser(const std::string& filename, std::string& raw_buffer, bool is_preprocessed)
335 : filename_(filename), is_preprocessed_(is_preprocessed) {
336 yylex_init(&scanner_);
337 buffer_ = yy_scan_buffer(&raw_buffer[0], raw_buffer.length(), scanner_);
338 }
339
~Parser()340 Parser::~Parser() {
341 yy_delete_buffer(buffer_, scanner_);
342 yylex_destroy(scanner_);
343 }
344
MakeDocument(const AidlLocation & location,const Comments & comments,std::vector<std::string> imports,std::vector<std::unique_ptr<AidlDefinedType>> defined_types)345 void Parser::MakeDocument(const AidlLocation& location, const Comments& comments,
346 std::vector<std::string> imports,
347 std::vector<std::unique_ptr<AidlDefinedType>> defined_types) {
348 AIDL_FATAL_IF(document_.get(), location);
349 document_ = std::make_unique<AidlDocument>(location, comments, std::move(imports),
350 std::move(defined_types), is_preprocessed_);
351 }
352