1 /*
2  * Copyright (C) 2016 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 "AST.h"
18 #include "Coordinator.h"
19 #include "Interface.h"
20 #include "Scope.h"
21 
22 #include <android-base/logging.h>
23 #include <hidl-hash/Hash.h>
24 #include <hidl-util/FQName.h>
25 #include <hidl-util/Formatter.h>
26 #include <hidl-util/StringHelper.h>
27 #include <stdio.h>
28 #include <sys/stat.h>
29 #include <unistd.h>
30 #include <iostream>
31 #include <set>
32 #include <sstream>
33 #include <string>
34 #include <vector>
35 
36 using namespace android;
37 
38 enum class OutputMode {
39     NEEDS_DIR,   // -o output option expects a directory
40     NEEDS_FILE,  // -o output option expects a file
41     NEEDS_SRC,   // for changes inside the source tree itself
42     NOT_NEEDED   // does not create files
43 };
44 
45 enum class GenerationGranularity {
46     PER_PACKAGE,  // Files generated for each package
47     PER_FILE,     // Files generated for each hal file
48     PER_TYPE,     // Files generated for each hal file + each type in HAL files
49 };
50 
51 // Represents a file that is generated by an -L option for an FQName
52 struct FileGenerator {
53     using ShouldGenerateFunction = std::function<bool(const FQName& fqName)>;
54     using FileNameForFQName = std::function<std::string(const FQName& fqName)>;
55     using GetFormatter = std::function<Formatter(void)>;
56     using GenerationFunction =
57             std::function<status_t(const FQName& fqName, const Coordinator* coordinator,
58                                    const GetFormatter& getFormatter)>;
59 
60     ShouldGenerateFunction mShouldGenerateForFqName;  // If generate function applies to this target
61     FileNameForFQName mFileNameForFqName;             // Target -> filename
62     GenerationFunction mGenerationFunction;           // Function to generate output for file
63 
getFileNameFileGenerator64     std::string getFileName(const FQName& fqName) const {
65         return mFileNameForFqName ? mFileNameForFqName(fqName) : "";
66     }
67 
getOutputFileFileGenerator68     status_t getOutputFile(const FQName& fqName, const Coordinator* coordinator,
69                            Coordinator::Location location, std::string* file) const {
70         if (!mShouldGenerateForFqName(fqName)) {
71             return OK;
72         }
73 
74         return coordinator->getFilepath(fqName, location, getFileName(fqName), file);
75     }
76 
appendOutputFilesFileGenerator77     status_t appendOutputFiles(const FQName& fqName, const Coordinator* coordinator,
78                                Coordinator::Location location,
79                                std::vector<std::string>* outputFiles) const {
80         if (location == Coordinator::Location::STANDARD_OUT) {
81             return OK;
82         }
83 
84         if (mShouldGenerateForFqName(fqName)) {
85             std::string fileName;
86             status_t err = getOutputFile(fqName, coordinator, location, &fileName);
87             if (err != OK) return err;
88 
89             if (!fileName.empty()) {
90                 outputFiles->push_back(fileName);
91             }
92         }
93         return OK;
94     }
95 
generateFileGenerator96     status_t generate(const FQName& fqName, const Coordinator* coordinator,
97                       Coordinator::Location location) const {
98         CHECK(mShouldGenerateForFqName != nullptr);
99         CHECK(mGenerationFunction != nullptr);
100 
101         if (!mShouldGenerateForFqName(fqName)) {
102             return OK;
103         }
104 
105         return mGenerationFunction(fqName, coordinator, [&] {
106             return coordinator->getFormatter(fqName, location, getFileName(fqName));
107         });
108     }
109 
110     // Helper methods for filling out this struct
generateForTypesFileGenerator111     static bool generateForTypes(const FQName& fqName) {
112         const auto names = fqName.names();
113         return names.size() > 0 && names[0] == "types";
114     }
generateForInterfacesFileGenerator115     static bool generateForInterfaces(const FQName& fqName) { return !generateForTypes(fqName); }
alwaysGenerateFileGenerator116     static bool alwaysGenerate(const FQName&) { return true; }
117 };
118 
119 // Represents a -L option, takes a fqName and generates files
120 struct OutputHandler {
121     using ValidationFunction = std::function<bool(
122         const FQName& fqName, const Coordinator* coordinator, const std::string& language)>;
123 
124     std::string mKey;                 // -L in Android.bp
125     std::string mDescription;         // for display in help menu
126     OutputMode mOutputMode;           // how this option interacts with -o
127     Coordinator::Location mLocation;  // how to compute location relative to the output directory
128     GenerationGranularity mGenerationGranularity;   // what to run generate function on
129     ValidationFunction mValidate;                   // if a given fqName is allowed for this option
130     std::vector<FileGenerator> mGenerateFunctions;  // run for each target at this granularity
131 
nameOutputHandler132     const std::string& name() const { return mKey; }
descriptionOutputHandler133     const std::string& description() const { return mDescription; }
134 
135     status_t generate(const FQName& fqName, const Coordinator* coordinator) const;
validateOutputHandler136     status_t validate(const FQName& fqName, const Coordinator* coordinator,
137                       const std::string& language) const {
138         return mValidate(fqName, coordinator, language);
139     }
140 
141     status_t writeDepFile(const FQName& fqName, const Coordinator* coordinator) const;
142 
143    private:
144     status_t appendTargets(const FQName& fqName, const Coordinator* coordinator,
145                            std::vector<FQName>* targets) const;
146     status_t appendOutputFiles(const FQName& fqName, const Coordinator* coordinator,
147                                std::vector<std::string>* outputFiles) const;
148 };
149 
150 // Helper method for GenerationGranularity::PER_TYPE
151 // IFoo -> IFoo, types.hal (containing Bar, Baz) -> types.Bar, types.Baz
appendPerTypeTargets(const FQName & fqName,const Coordinator * coordinator,std::vector<FQName> * exportedPackageInterfaces)152 static status_t appendPerTypeTargets(const FQName& fqName, const Coordinator* coordinator,
153                                      std::vector<FQName>* exportedPackageInterfaces) {
154     CHECK(fqName.isFullyQualified());
155     if (fqName.name() != "types") {
156         exportedPackageInterfaces->push_back(fqName);
157         return OK;
158     }
159 
160     AST* typesAST = coordinator->parse(fqName);
161     if (typesAST == nullptr) {
162         fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
163         return UNKNOWN_ERROR;
164     }
165 
166     std::vector<NamedType*> rootTypes = typesAST->getRootScope().getSubTypes();
167     for (const NamedType* rootType : rootTypes) {
168         if (rootType->isTypeDef()) continue;
169 
170         FQName rootTypeName(fqName.package(), fqName.version(), "types." + rootType->definedName());
171         exportedPackageInterfaces->push_back(rootTypeName);
172     }
173     return OK;
174 }
175 
appendTargets(const FQName & fqName,const Coordinator * coordinator,std::vector<FQName> * targets) const176 status_t OutputHandler::appendTargets(const FQName& fqName, const Coordinator* coordinator,
177                                       std::vector<FQName>* targets) const {
178     switch (mGenerationGranularity) {
179         case GenerationGranularity::PER_PACKAGE: {
180             targets->push_back(fqName.getPackageAndVersion());
181         } break;
182         case GenerationGranularity::PER_FILE: {
183             if (fqName.isFullyQualified()) {
184                 targets->push_back(fqName);
185                 break;
186             }
187             status_t err = coordinator->appendPackageInterfacesToVector(fqName, targets);
188             if (err != OK) return err;
189         } break;
190         case GenerationGranularity::PER_TYPE: {
191             if (fqName.isFullyQualified()) {
192                 status_t err = appendPerTypeTargets(fqName, coordinator, targets);
193                 if (err != OK) return err;
194                 break;
195             }
196 
197             std::vector<FQName> packageInterfaces;
198             status_t err = coordinator->appendPackageInterfacesToVector(fqName, &packageInterfaces);
199             if (err != OK) return err;
200             for (const FQName& packageInterface : packageInterfaces) {
201                 err = appendPerTypeTargets(packageInterface, coordinator, targets);
202                 if (err != OK) return err;
203             }
204         } break;
205         default:
206             CHECK(!"Should be here");
207     }
208 
209     return OK;
210 }
211 
generate(const FQName & fqName,const Coordinator * coordinator) const212 status_t OutputHandler::generate(const FQName& fqName, const Coordinator* coordinator) const {
213     std::vector<FQName> targets;
214     status_t err = appendTargets(fqName, coordinator, &targets);
215     if (err != OK) return err;
216 
217     for (const FQName& fqName : targets) {
218         for (const FileGenerator& file : mGenerateFunctions) {
219             status_t err = file.generate(fqName, coordinator, mLocation);
220             if (err != OK) return err;
221         }
222     }
223 
224     return OK;
225 }
226 
appendOutputFiles(const FQName & fqName,const Coordinator * coordinator,std::vector<std::string> * outputFiles) const227 status_t OutputHandler::appendOutputFiles(const FQName& fqName, const Coordinator* coordinator,
228                                           std::vector<std::string>* outputFiles) const {
229     std::vector<FQName> targets;
230     status_t err = appendTargets(fqName, coordinator, &targets);
231     if (err != OK) return err;
232 
233     for (const FQName& fqName : targets) {
234         for (const FileGenerator& file : mGenerateFunctions) {
235             err = file.appendOutputFiles(fqName, coordinator, mLocation, outputFiles);
236             if (err != OK) return err;
237         }
238     }
239 
240     return OK;
241 }
242 
writeDepFile(const FQName & fqName,const Coordinator * coordinator) const243 status_t OutputHandler::writeDepFile(const FQName& fqName, const Coordinator* coordinator) const {
244     std::vector<std::string> outputFiles;
245     status_t err = appendOutputFiles(fqName, coordinator, &outputFiles);
246     if (err != OK) return err;
247 
248     // No need for dep files
249     if (outputFiles.empty()) {
250         return OK;
251     }
252 
253     // Depfiles in Android for genrules should be for the 'main file'. Because hidl-gen doesn't have
254     // a main file for most targets, we are just outputting a depfile for one single file only.
255     const std::string forFile = outputFiles[0];
256 
257     return coordinator->writeDepFile(forFile);
258 }
259 
260 // Use an AST function as a OutputHandler GenerationFunction
astGenerationFunction(void (AST::* generate)(Formatter &)const=nullptr)261 static FileGenerator::GenerationFunction astGenerationFunction(void (AST::*generate)(Formatter&)
262                                                                    const = nullptr) {
263     return [generate](const FQName& fqName, const Coordinator* coordinator,
264                       const FileGenerator::GetFormatter& getFormatter) -> status_t {
265         AST* ast = coordinator->parse(fqName);
266         if (ast == nullptr) {
267             fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
268             return UNKNOWN_ERROR;
269         }
270 
271         if (generate == nullptr) return OK;  // just parsing AST
272 
273         Formatter out = getFormatter();
274         if (!out.isValid()) {
275             return UNKNOWN_ERROR;
276         }
277 
278         (ast->*generate)(out);
279 
280         return OK;
281     };
282 }
283 
284 // Common pattern: single file for package or standard out
singleFileGenerator(const std::string & fileName,const FileGenerator::GenerationFunction & generationFunction)285 static FileGenerator singleFileGenerator(
286     const std::string& fileName, const FileGenerator::GenerationFunction& generationFunction) {
287     return {
288         FileGenerator::alwaysGenerate, [fileName](const FQName&) { return fileName; },
289         generationFunction,
290     };
291 }
292 
generateJavaForPackage(const FQName & fqName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)293 static status_t generateJavaForPackage(const FQName& fqName, const Coordinator* coordinator,
294                                        const FileGenerator::GetFormatter& getFormatter) {
295     AST* ast;
296     std::string limitToType;
297     FQName typeName;
298 
299     // See appendPerTypeTargets.
300     // 'a.b.c@1.0::types.Foo' is used to compile 'Foo' for Java even though in
301     // the rest of the compiler, this type is simply called 'a.b.c@1.0::Foo'.
302     // However, here, we need to disambiguate an interface name and a type in
303     // types.hal in order to figure out what to parse, so this legacy behavior
304     // is kept.
305     if (fqName.name().find("types.") == 0) {
306         limitToType = fqName.name().substr(strlen("types."));
307 
308         ast = coordinator->parse(fqName.getTypesForPackage());
309 
310         const auto& names = fqName.names();
311         CHECK(names.size() == 2 && names[0] == "types") << fqName.string();
312         typeName = FQName(fqName.package(), fqName.version(), names[1]);
313     } else {
314         ast = coordinator->parse(fqName);
315         typeName = fqName;
316     }
317     if (ast == nullptr) {
318         fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
319         return UNKNOWN_ERROR;
320     }
321 
322     Type* type = ast->lookupType(typeName, &ast->getRootScope());
323     CHECK(type != nullptr) << typeName.string();
324     if (!type->isJavaCompatible()) {
325         return OK;
326     }
327 
328     Formatter out = getFormatter();
329     if (!out.isValid()) {
330         return UNKNOWN_ERROR;
331     }
332 
333     ast->generateJava(out, limitToType);
334     return OK;
335 };
336 
dumpDefinedButUnreferencedTypeNames(const FQName & packageFQName,const Coordinator * coordinator)337 static status_t dumpDefinedButUnreferencedTypeNames(const FQName& packageFQName,
338                                                     const Coordinator* coordinator) {
339     std::vector<FQName> packageInterfaces;
340     status_t err = coordinator->appendPackageInterfacesToVector(packageFQName, &packageInterfaces);
341     if (err != OK) return err;
342 
343     std::set<FQName> unreferencedDefinitions;
344     std::set<FQName> unreferencedImports;
345     err = coordinator->addUnreferencedTypes(packageInterfaces, &unreferencedDefinitions,
346                                             &unreferencedImports);
347     if (err != OK) return err;
348 
349     for (const auto& fqName : unreferencedDefinitions) {
350         std::cerr
351             << "VERBOSE: DEFINED-BUT-NOT-REFERENCED "
352             << fqName.string()
353             << std::endl;
354     }
355 
356     for (const auto& fqName : unreferencedImports) {
357         std::cerr
358             << "VERBOSE: IMPORTED-BUT-NOT-REFERENCED "
359             << fqName.string()
360             << std::endl;
361     }
362 
363     return OK;
364 }
365 
makeLibraryName(const FQName & packageFQName)366 static std::string makeLibraryName(const FQName &packageFQName) {
367     return packageFQName.string();
368 }
369 
isPackageJavaCompatible(const FQName & packageFQName,const Coordinator * coordinator,bool * compatible)370 static status_t isPackageJavaCompatible(const FQName& packageFQName, const Coordinator* coordinator,
371                                         bool* compatible) {
372     std::vector<FQName> todo;
373     status_t err =
374         coordinator->appendPackageInterfacesToVector(packageFQName, &todo);
375 
376     if (err != OK) {
377         return err;
378     }
379 
380     std::set<FQName> seen;
381     for (const auto &iface : todo) {
382         seen.insert(iface);
383     }
384 
385     // Form the transitive closure of all imported interfaces (and types.hal-s)
386     // If any one of them is not java compatible, this package isn't either.
387     while (!todo.empty()) {
388         const FQName fqName = todo.back();
389         todo.pop_back();
390 
391         AST *ast = coordinator->parse(fqName);
392 
393         if (ast == nullptr) {
394             return UNKNOWN_ERROR;
395         }
396 
397         if (!ast->isJavaCompatible()) {
398             *compatible = false;
399             return OK;
400         }
401 
402         std::set<FQName> importedPackages;
403         ast->getImportedPackages(&importedPackages);
404 
405         for (const auto &package : importedPackages) {
406             std::vector<FQName> packageInterfaces;
407             status_t err = coordinator->appendPackageInterfacesToVector(
408                     package, &packageInterfaces);
409 
410             if (err != OK) {
411                 return err;
412             }
413 
414             for (const auto &iface : packageInterfaces) {
415                 if (seen.find(iface) != seen.end()) {
416                     continue;
417                 }
418 
419                 todo.push_back(iface);
420                 seen.insert(iface);
421             }
422         }
423     }
424 
425     *compatible = true;
426     return OK;
427 }
428 
packageNeedsJavaCode(const std::vector<FQName> & packageInterfaces,AST * typesAST)429 static bool packageNeedsJavaCode(
430         const std::vector<FQName> &packageInterfaces, AST *typesAST) {
431     if (packageInterfaces.size() == 0) {
432         return false;
433     }
434 
435     // If there is more than just a types.hal file to this package we'll
436     // definitely need to generate Java code.
437     if (packageInterfaces.size() > 1
438             || packageInterfaces[0].name() != "types") {
439         return true;
440     }
441 
442     CHECK(typesAST != nullptr);
443 
444     // We'll have to generate Java code if types.hal contains any non-typedef
445     // type declarations.
446 
447     std::vector<NamedType*> subTypes = typesAST->getRootScope().getSubTypes();
448     for (const auto &subType : subTypes) {
449         if (!subType->isTypeDef()) {
450             return true;
451         }
452     }
453 
454     return false;
455 }
456 
validateIsPackage(const FQName & fqName,const Coordinator *,const std::string &)457 bool validateIsPackage(const FQName& fqName, const Coordinator*,
458                        const std::string& /* language */) {
459     if (fqName.package().empty()) {
460         fprintf(stderr, "ERROR: Expecting package name\n");
461         return false;
462     }
463 
464     if (fqName.version().empty()) {
465         fprintf(stderr, "ERROR: Expecting package version\n");
466         return false;
467     }
468 
469     if (!fqName.name().empty()) {
470         fprintf(stderr,
471                 "ERROR: Expecting only package name and version.\n");
472         return false;
473     }
474 
475     return true;
476 }
477 
isHidlTransportPackage(const FQName & fqName)478 bool isHidlTransportPackage(const FQName& fqName) {
479     return fqName.package() == gIBaseFqName.package() ||
480            fqName.package() == gIManagerFqName.package();
481 }
482 
isSystemProcessSupportedPackage(const FQName & fqName)483 bool isSystemProcessSupportedPackage(const FQName& fqName) {
484     // Technically, so is hidl IBase + IServiceManager, but
485     // these are part of libhidlbase.
486     return fqName.inPackage("android.hardware.graphics.common") ||
487            fqName.inPackage("android.hardware.graphics.mapper") ||
488            fqName.string() == "android.hardware.renderscript@1.0" ||
489            fqName.string() == "android.hidl.memory.token@1.0" ||
490            fqName.string() == "android.hidl.memory@1.0" ||
491            fqName.string() == "android.hidl.safe_union@1.0";
492 }
493 
isCoreAndroidPackage(const FQName & package)494 bool isCoreAndroidPackage(const FQName& package) {
495     return package.inPackage("android.hidl") ||
496            package.inPackage("android.system") ||
497            package.inPackage("android.frameworks") ||
498            package.inPackage("android.hardware");
499 }
500 
501 // Keep the list of libs which are used by VNDK core libs and should be part of
502 // VNDK libs
503 static const std::vector<std::string> vndkLibs = {
504         "android.hardware.audio.common@2.0",
505         "android.hardware.configstore@1.0",
506         "android.hardware.configstore@1.1",
507         "android.hardware.graphics.allocator@2.0",
508         "android.hardware.graphics.allocator@3.0",
509         "android.hardware.graphics.allocator@4.0",
510         "android.hardware.graphics.bufferqueue@1.0",
511         "android.hardware.graphics.bufferqueue@2.0",
512         "android.hardware.media.bufferpool@2.0",
513         "android.hardware.media.omx@1.0",
514         "android.hardware.media@1.0",
515         "android.hardware.memtrack@1.0",
516         "android.hardware.soundtrigger@2.0",
517         "android.hidl.token@1.0",
518         "android.system.suspend@1.0",
519 };
520 
isVndkCoreLib(const FQName & fqName)521 bool isVndkCoreLib(const FQName& fqName) {
522     return std::find(vndkLibs.begin(), vndkLibs.end(), fqName.string()) != vndkLibs.end();
523 }
524 
isSystemExtPackage(const FQName & fqName,const Coordinator * coordinator,bool * isSystemExt)525 status_t isSystemExtPackage(const FQName& fqName, const Coordinator* coordinator,
526                             bool* isSystemExt) {
527     const auto fileExists = [](const std::string& file) {
528         struct stat buf;
529         return stat(file.c_str(), &buf) == 0;
530     };
531 
532     std::string path;
533     status_t err = coordinator->getFilepath(fqName, Coordinator::Location::PACKAGE_ROOT,
534                                             ".hidl_for_system_ext", &path);
535     if (err != OK) return err;
536 
537     const bool exists = fileExists(path);
538 
539     if (exists) {
540         coordinator->onFileAccess(path, "r");
541     }
542 
543     *isSystemExt = exists;
544     return OK;
545 }
546 
generateAdapterMainSource(const FQName & packageFQName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)547 static status_t generateAdapterMainSource(const FQName& packageFQName,
548                                           const Coordinator* coordinator,
549                                           const FileGenerator::GetFormatter& getFormatter) {
550     std::vector<FQName> packageInterfaces;
551     status_t err =
552         coordinator->appendPackageInterfacesToVector(packageFQName,
553                                                      &packageInterfaces);
554     if (err != OK) {
555         return err;
556     }
557 
558     // b/146223994: parse all interfaces
559     // - causes files to get read (filling out dep file)
560     // - avoid creating successful output for broken files
561     for (const FQName& fqName : packageInterfaces) {
562         AST* ast = coordinator->parse(fqName);
563         if (ast == nullptr) {
564             fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
565             return UNKNOWN_ERROR;
566         }
567     }
568 
569     Formatter out = getFormatter();
570     if (!out.isValid()) {
571         return UNKNOWN_ERROR;
572     }
573 
574     out << "#include <hidladapter/HidlBinderAdapter.h>\n";
575 
576     for (auto &interface : packageInterfaces) {
577         if (interface.name() == "types") {
578             continue;
579         }
580         AST::generateCppPackageInclude(out, interface, interface.getInterfaceAdapterName());
581     }
582 
583     out << "int main(int argc, char** argv) ";
584     out.block([&] {
585         out << "return ::android::hardware::adapterMain<\n";
586         out.indent();
587         for (auto &interface : packageInterfaces) {
588             if (interface.name() == "types") {
589                 continue;
590             }
591             out << interface.getInterfaceAdapterFqName().cppName();
592 
593             if (&interface != &packageInterfaces.back()) {
594                 out << ",\n";
595             }
596         }
597         out << ">(\"" << packageFQName.string() << "\", argc, argv);\n";
598         out.unindent();
599     }).endl();
600     return OK;
601 }
602 
generateAndroidBpForPackage(const FQName & packageFQName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)603 static status_t generateAndroidBpForPackage(const FQName& packageFQName,
604                                             const Coordinator* coordinator,
605                                             const FileGenerator::GetFormatter& getFormatter) {
606     CHECK(!packageFQName.isFullyQualified() && packageFQName.name().empty());
607 
608     std::vector<FQName> packageInterfaces;
609 
610     status_t err = coordinator->appendPackageInterfacesToVector(packageFQName, &packageInterfaces);
611 
612     if (err != OK) {
613         return err;
614     }
615 
616     std::set<FQName> importedPackagesHierarchy;
617     std::vector<const Type *> exportedTypes;
618     AST* typesAST = nullptr;
619 
620     for (const auto& fqName : packageInterfaces) {
621         AST* ast = coordinator->parse(fqName);
622 
623         if (ast == nullptr) {
624             fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
625 
626             return UNKNOWN_ERROR;
627         }
628 
629         if (fqName.name() == "types") {
630             typesAST = ast;
631         }
632 
633         ast->getImportedPackagesHierarchy(&importedPackagesHierarchy);
634         ast->appendToExportedTypesVector(&exportedTypes);
635     }
636 
637     bool needsJavaCode = packageNeedsJavaCode(packageInterfaces, typesAST);
638 
639     bool genJavaConstants = needsJavaCode && !exportedTypes.empty();
640 
641     bool isJavaCompatible;
642     err = isPackageJavaCompatible(packageFQName, coordinator, &isJavaCompatible);
643     if (err != OK) return err;
644     bool genJavaLibrary = needsJavaCode && isJavaCompatible;
645 
646     bool isCoreAndroid = isCoreAndroidPackage(packageFQName);
647 
648     bool isVndkCore = isVndkCoreLib(packageFQName);
649     bool isVndkSp = isSystemProcessSupportedPackage(packageFQName);
650 
651     bool isSystemExtHidl;
652     err = isSystemExtPackage(packageFQName, coordinator, &isSystemExtHidl);
653     if (err != OK) return err;
654     bool isSystemExt = isSystemExtHidl || !isCoreAndroid;
655 
656     std::string packageRoot;
657     err = coordinator->getPackageRoot(packageFQName, &packageRoot);
658     if (err != OK) return err;
659 
660     Formatter out = getFormatter();
661     if (!out.isValid()) {
662         return UNKNOWN_ERROR;
663     }
664 
665     out << "// This file is autogenerated by hidl-gen -Landroidbp.\n\n";
666 
667     out << "hidl_interface ";
668     out.block([&] {
669         out << "name: \"" << makeLibraryName(packageFQName) << "\",\n";
670         if (!coordinator->getOwner().empty()) {
671             out << "owner: \"" << coordinator->getOwner() << "\",\n";
672         }
673         out << "root: \"" << packageRoot << "\",\n";
674         if (isVndkCore || isVndkSp) {
675             out << "vndk: ";
676             out.block([&]() {
677                 out << "enabled: true,\n";
678                 if (isVndkSp) {
679                     out << "support_system_process: true,\n";
680                 }
681             }) << ",\n";
682         }
683         if (isSystemExt) {
684             out << "system_ext_specific: true,\n";
685         }
686         (out << "srcs: [\n").indent([&] {
687            for (const auto& fqName : packageInterfaces) {
688                out << "\"" << fqName.name() << ".hal\",\n";
689            }
690         }) << "],\n";
691         if (!importedPackagesHierarchy.empty()) {
692             (out << "interfaces: [\n").indent([&] {
693                for (const auto& fqName : importedPackagesHierarchy) {
694                    out << "\"" << fqName.string() << "\",\n";
695                }
696             }) << "],\n";
697         }
698         // Explicity call this out for developers.
699         out << "gen_java: " << (genJavaLibrary ? "true" : "false") << ",\n";
700         if (genJavaConstants) {
701             out << "gen_java_constants: true,\n";
702         }
703    }).endl();
704 
705     return OK;
706 }
707 
generateAndroidBpImplForPackage(const FQName & packageFQName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)708 static status_t generateAndroidBpImplForPackage(const FQName& packageFQName,
709                                                 const Coordinator* coordinator,
710                                                 const FileGenerator::GetFormatter& getFormatter) {
711     const std::string libraryName = makeLibraryName(packageFQName) + "-impl";
712 
713     std::vector<FQName> packageInterfaces;
714 
715     status_t err =
716         coordinator->appendPackageInterfacesToVector(packageFQName,
717                                                      &packageInterfaces);
718 
719     if (err != OK) {
720         return err;
721     }
722 
723     std::set<FQName> importedPackages;
724 
725     for (const auto &fqName : packageInterfaces) {
726         AST *ast = coordinator->parse(fqName);
727 
728         if (ast == nullptr) {
729             fprintf(stderr,
730                     "ERROR: Could not parse %s. Aborting.\n",
731                     fqName.string().c_str());
732 
733             return UNKNOWN_ERROR;
734         }
735 
736         ast->getImportedPackages(&importedPackages);
737     }
738 
739     Formatter out = getFormatter();
740     if (!out.isValid()) {
741         return UNKNOWN_ERROR;
742     }
743 
744     out << "// FIXME: your file license if you have one\n\n";
745     out << "cc_library_shared {\n";
746     out.indent([&] {
747         out << "// FIXME: this should only be -impl for a passthrough hal.\n"
748             << "// In most cases, to convert this to a binderized implementation, you should:\n"
749             << "// - change '-impl' to '-service' here and make it a cc_binary instead of a\n"
750             << "//   cc_library_shared.\n"
751             << "// - add a *.rc file for this module.\n"
752             << "// - delete HIDL_FETCH_I* functions.\n"
753             << "// - call configureRpcThreadpool and registerAsService on the instance.\n"
754             << "// You may also want to append '-impl/-service' with a specific identifier like\n"
755             << "// '-vendor' or '-<hardware identifier>' etc to distinguish it.\n";
756         out << "name: \"" << libraryName << "\",\n";
757         if (!coordinator->getOwner().empty()) {
758             out << "owner: \"" << coordinator->getOwner() << "\",\n";
759         }
760         out << "relative_install_path: \"hw\",\n";
761         if (coordinator->getOwner().empty()) {
762             out << "// FIXME: this should be 'vendor: true' for modules that will eventually be\n"
763                    "// on AOSP.\n";
764         }
765         out << "proprietary: true,\n";
766         out << "srcs: [\n";
767         out.indent([&] {
768             for (const auto &fqName : packageInterfaces) {
769                 if (fqName.name() == "types") {
770                     continue;
771                 }
772                 out << "\"" << fqName.getInterfaceBaseName() << ".cpp\",\n";
773             }
774         });
775         out << "],\n"
776             << "shared_libs: [\n";
777         out.indent([&] {
778             out << "\"libhidlbase\",\n"
779                 << "\"libutils\",\n"
780                 << "\"" << makeLibraryName(packageFQName) << "\",\n";
781 
782             for (const auto &importedPackage : importedPackages) {
783                 if (isHidlTransportPackage(importedPackage)) {
784                     continue;
785                 }
786 
787                 out << "\"" << makeLibraryName(importedPackage) << "\",\n";
788             }
789         });
790         out << "],\n";
791     });
792     out << "}\n";
793 
794     return OK;
795 }
796 
validateForSource(const FQName & fqName,const Coordinator * coordinator,const std::string & language)797 bool validateForSource(const FQName& fqName, const Coordinator* coordinator,
798                        const std::string& language) {
799     if (fqName.package().empty()) {
800         fprintf(stderr, "ERROR: Expecting package name\n");
801         return false;
802     }
803 
804     if (fqName.version().empty()) {
805         fprintf(stderr, "ERROR: Expecting package version\n");
806         return false;
807     }
808 
809     const std::string &name = fqName.name();
810     if (!name.empty()) {
811         if (name.find('.') == std::string::npos) {
812             return true;
813         }
814 
815         if (language != "java" || name.find("types.") != 0) {
816             // When generating java sources for "types.hal", output can be
817             // constrained to just one of the top-level types declared
818             // by using the extended syntax
819             // android.hardware.Foo@1.0::types.TopLevelTypeName.
820             // In all other cases (different language, not 'types') the dot
821             // notation in the name is illegal in this context.
822             return false;
823         }
824 
825         return true;
826     }
827 
828     if (language == "java") {
829         bool isJavaCompatible;
830         status_t err = isPackageJavaCompatible(fqName, coordinator, &isJavaCompatible);
831         if (err != OK) return false;
832 
833         if (!isJavaCompatible) {
834             fprintf(stderr,
835                     "ERROR: %s is not Java compatible. The Java backend does NOT support union "
836                     "types. In addition, vectors of arrays are limited to at most one-dimensional "
837                     "arrays and vectors of {vectors,interfaces,memory} are not supported.\n",
838                     fqName.string().c_str());
839             return false;
840         }
841     }
842 
843     return true;
844 }
845 
generateExportHeaderForPackage(bool forJava)846 FileGenerator::GenerationFunction generateExportHeaderForPackage(bool forJava) {
847     return [forJava](const FQName& packageFQName, const Coordinator* coordinator,
848                      const FileGenerator::GetFormatter& getFormatter) -> status_t {
849         CHECK(!packageFQName.package().empty() && !packageFQName.version().empty() &&
850               packageFQName.name().empty());
851 
852         std::vector<FQName> packageInterfaces;
853 
854         status_t err = coordinator->appendPackageInterfacesToVector(
855                 packageFQName, &packageInterfaces);
856 
857         if (err != OK) {
858             return err;
859         }
860 
861         std::vector<const Type *> exportedTypes;
862 
863         for (const auto &fqName : packageInterfaces) {
864             AST *ast = coordinator->parse(fqName);
865 
866             if (ast == nullptr) {
867                 fprintf(stderr,
868                         "ERROR: Could not parse %s. Aborting.\n",
869                         fqName.string().c_str());
870 
871                 return UNKNOWN_ERROR;
872             }
873 
874             ast->appendToExportedTypesVector(&exportedTypes);
875         }
876 
877         if (exportedTypes.empty()) {
878             return OK;
879         }
880 
881         Formatter out = getFormatter();
882         if (!out.isValid()) {
883             return UNKNOWN_ERROR;
884         }
885 
886         std::string packagePath;
887         err = coordinator->getPackagePath(packageFQName, false /* relative */,
888                                           false /* sanitized */, &packagePath);
889         if (err != OK) return err;
890 
891         out << "// This file is autogenerated by hidl-gen. Do not edit manually.\n"
892             << "// Source: " << packageFQName.string() << "\n"
893             << "// Location: " << packagePath << "\n\n";
894 
895         std::string guard;
896         if (forJava) {
897             out << "package " << packageFQName.javaPackage() << ";\n\n";
898             out << "public class Constants {\n";
899             out.indent();
900         } else {
901             guard = "HIDL_GENERATED_";
902             guard += StringHelper::Uppercase(packageFQName.tokenName());
903             guard += "_";
904             guard += "EXPORTED_CONSTANTS_H_";
905 
906             out << "#ifndef "
907                 << guard
908                 << "\n#define "
909                 << guard
910                 << "\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n";
911         }
912 
913         for (const auto &type : exportedTypes) {
914             type->emitExportedHeader(out, forJava);
915         }
916 
917         if (forJava) {
918             out.unindent();
919             out << "}\n";
920         } else {
921             out << "#ifdef __cplusplus\n}\n#endif\n\n#endif  // "
922                 << guard
923                 << "\n";
924         }
925 
926         return OK;
927     };
928 }
929 
generateHashOutput(const FQName & fqName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)930 static status_t generateHashOutput(const FQName& fqName, const Coordinator* coordinator,
931                                    const FileGenerator::GetFormatter& getFormatter) {
932     CHECK(fqName.isFullyQualified());
933 
934     AST* ast = coordinator->parse(fqName, {} /* parsed */,
935                                   Coordinator::Enforce::NO_HASH /* enforcement */);
936 
937     if (ast == nullptr) {
938         fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
939 
940         return UNKNOWN_ERROR;
941     }
942 
943     Formatter out = getFormatter();
944     if (!out.isValid()) {
945         return UNKNOWN_ERROR;
946     }
947 
948     out << Hash::getHash(ast->getFilename()).hexString() << " " << fqName.string() << "\n";
949 
950     return OK;
951 }
952 
generateFunctionCount(const FQName & fqName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)953 static status_t generateFunctionCount(const FQName& fqName, const Coordinator* coordinator,
954                                       const FileGenerator::GetFormatter& getFormatter) {
955     CHECK(fqName.isFullyQualified());
956 
957     AST* ast = coordinator->parse(fqName, {} /* parsed */,
958                                   Coordinator::Enforce::NO_HASH /* enforcement */);
959 
960     if (ast == nullptr) {
961         fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
962         return UNKNOWN_ERROR;
963     }
964 
965     const Interface* interface = ast->getInterface();
966     if (interface == nullptr) {
967         fprintf(stderr, "ERROR: Function count requires interface: %s.\n", fqName.string().c_str());
968         return UNKNOWN_ERROR;
969     }
970 
971     Formatter out = getFormatter();
972     if (!out.isValid()) {
973         return UNKNOWN_ERROR;
974     }
975 
976     // This is wrong for android.hidl.base@1.0::IBase, but in that case, it doesn't matter.
977     // This is just the number of APIs that are added.
978     out << fqName.string() << " " << interface->userDefinedMethods().size() << "\n";
979 
980     return OK;
981 }
982 
983 template <typename T>
operator +(const std::vector<T> & lhs,const std::vector<T> & rhs)984 std::vector<T> operator+(const std::vector<T>& lhs, const std::vector<T>& rhs) {
985     std::vector<T> ret;
986     ret.reserve(lhs.size() + rhs.size());
987     ret.insert(ret.begin(), lhs.begin(), lhs.end());
988     ret.insert(ret.end(), rhs.begin(), rhs.end());
989     return ret;
990 }
991 
992 // clang-format off
993 static const std::vector<FileGenerator> kCppHeaderFormats = {
994     {
995         FileGenerator::alwaysGenerate,
__anon31ab13f90e02() 996         [](const FQName& fqName) { return fqName.name() + ".h"; },
997         astGenerationFunction(&AST::generateInterfaceHeader),
998     },
999     {
1000         FileGenerator::alwaysGenerate,
__anon31ab13f90f02() 1001         [](const FQName& fqName) {
1002             return fqName.isInterfaceName() ? fqName.getInterfaceHwName() + ".h" : "hwtypes.h";
1003         },
1004         astGenerationFunction(&AST::generateHwBinderHeader),
1005     },
1006     {
1007         FileGenerator::generateForInterfaces,
__anon31ab13f91002() 1008         [](const FQName& fqName) { return fqName.getInterfaceStubName() + ".h"; },
1009         astGenerationFunction(&AST::generateStubHeader),
1010     },
1011     {
1012         FileGenerator::generateForInterfaces,
__anon31ab13f91102() 1013         [](const FQName& fqName) { return fqName.getInterfaceProxyName() + ".h"; },
1014         astGenerationFunction(&AST::generateProxyHeader),
1015     },
1016     {
1017         FileGenerator::generateForInterfaces,
__anon31ab13f91202() 1018         [](const FQName& fqName) { return fqName.getInterfacePassthroughName() + ".h"; },
1019         astGenerationFunction(&AST::generatePassthroughHeader),
1020     },
1021 };
1022 
1023 static const std::vector<FileGenerator> kCppSourceFormats = {
1024     {
1025         FileGenerator::alwaysGenerate,
__anon31ab13f91302() 1026         [](const FQName& fqName) {
1027             return fqName.isInterfaceName() ? fqName.getInterfaceBaseName() + "All.cpp" : "types.cpp";
1028         },
1029         astGenerationFunction(&AST::generateCppSource),
1030     },
1031 };
1032 
1033 static const std::vector<FileGenerator> kCppImplHeaderFormats = {
1034     {
1035         FileGenerator::generateForInterfaces,
__anon31ab13f91402() 1036         [](const FQName& fqName) { return fqName.getInterfaceBaseName() + ".h"; },
1037         astGenerationFunction(&AST::generateCppImplHeader),
1038     },
1039 };
1040 
1041 static const std::vector<FileGenerator> kCppImplSourceFormats = {
1042     {
1043         FileGenerator::generateForInterfaces,
__anon31ab13f91502() 1044         [](const FQName& fqName) { return fqName.getInterfaceBaseName() + ".cpp"; },
1045         astGenerationFunction(&AST::generateCppImplSource),
1046     },
1047 };
1048 
1049 static const std::vector<FileGenerator> kCppAdapterHeaderFormats = {
1050     {
1051         FileGenerator::alwaysGenerate,
__anon31ab13f91602() 1052         [](const FQName& fqName) {
1053             return fqName.isInterfaceName() ? fqName.getInterfaceAdapterName() + ".h" : "Atypes.h";
1054         },
1055         astGenerationFunction(&AST::generateCppAdapterHeader),
1056     },
1057 };
1058 
1059 static const std::vector<FileGenerator> kCppAdapterSourceFormats = {
1060     {
1061         FileGenerator::alwaysGenerate,
__anon31ab13f91702() 1062         [](const FQName& fqName) {
1063             return fqName.isInterfaceName() ? fqName.getInterfaceAdapterName() + ".cpp" : "Atypes.cpp";
1064         },
1065         astGenerationFunction(&AST::generateCppAdapterSource),
1066     },
1067 };
1068 
1069 static const std::vector<OutputHandler> kFormats = {
1070     {
1071         "check",
1072         "Parses the interface to see if valid but doesn't write any files.",
1073         OutputMode::NOT_NEEDED,
1074         Coordinator::Location::STANDARD_OUT,
1075         GenerationGranularity::PER_FILE,
1076         validateForSource,
1077         {
1078             {
1079                 FileGenerator::alwaysGenerate,
1080                 nullptr /* filename for fqname */,
1081                 astGenerationFunction(),
1082             },
1083         },
1084     },
1085     {
1086         "c++",
1087         "(internal) (deprecated) Generates C++ interface files for talking to HIDL interfaces.",
1088         OutputMode::NEEDS_DIR,
1089         Coordinator::Location::GEN_OUTPUT,
1090         GenerationGranularity::PER_FILE,
1091         validateForSource,
1092         kCppHeaderFormats + kCppSourceFormats,
1093     },
1094     {
1095         "c++-headers",
1096         "(internal) Generates C++ headers for interface files for talking to HIDL interfaces.",
1097         OutputMode::NEEDS_DIR,
1098         Coordinator::Location::GEN_OUTPUT,
1099         GenerationGranularity::PER_FILE,
1100         validateForSource,
1101         kCppHeaderFormats,
1102     },
1103     {
1104         "c++-sources",
1105         "(internal) Generates C++ sources for interface files for talking to HIDL interfaces.",
1106         OutputMode::NEEDS_DIR,
1107         Coordinator::Location::GEN_OUTPUT,
1108         GenerationGranularity::PER_FILE,
1109         validateForSource,
1110         kCppSourceFormats,
1111     },
1112     {
1113         "export-header",
1114         "Generates a header file from @export enumerations to help maintain legacy code.",
1115         OutputMode::NEEDS_FILE,
1116         Coordinator::Location::DIRECT,
1117         GenerationGranularity::PER_PACKAGE,
1118         validateIsPackage,
1119         {singleFileGenerator("", generateExportHeaderForPackage(false /* forJava */))}
1120     },
1121     {
1122         "c++-impl",
1123         "Generates boilerplate implementation of a hidl interface in C++ (for convenience).",
1124         OutputMode::NEEDS_DIR,
1125         Coordinator::Location::DIRECT,
1126         GenerationGranularity::PER_FILE,
1127         validateForSource,
1128         kCppImplHeaderFormats + kCppImplSourceFormats,
1129     },
1130     {
1131         "c++-impl-headers",
1132         "c++-impl but headers only.",
1133         OutputMode::NEEDS_DIR,
1134         Coordinator::Location::DIRECT,
1135         GenerationGranularity::PER_FILE,
1136         validateForSource,
1137         kCppImplHeaderFormats,
1138     },
1139     {
1140         "c++-impl-sources",
1141         "c++-impl but sources only.",
1142         OutputMode::NEEDS_DIR,
1143         Coordinator::Location::DIRECT,
1144         GenerationGranularity::PER_FILE,
1145         validateForSource,
1146         kCppImplSourceFormats,
1147     },
1148     {
1149         "c++-adapter",
1150         "Takes a x.(y+n) interface and mocks an x.y interface.",
1151         OutputMode::NEEDS_DIR,
1152         Coordinator::Location::GEN_OUTPUT,
1153         GenerationGranularity::PER_FILE,
1154         validateForSource,
1155         kCppAdapterHeaderFormats + kCppAdapterSourceFormats,
1156     },
1157     {
1158         "c++-adapter-headers",
1159         "c++-adapter but helper headers only.",
1160         OutputMode::NEEDS_DIR,
1161         Coordinator::Location::GEN_OUTPUT,
1162         GenerationGranularity::PER_FILE,
1163         validateForSource,
1164         kCppAdapterHeaderFormats,
1165     },
1166     {
1167         "c++-adapter-sources",
1168         "c++-adapter but helper sources only.",
1169         OutputMode::NEEDS_DIR,
1170         Coordinator::Location::GEN_OUTPUT,
1171         GenerationGranularity::PER_FILE,
1172         validateForSource,
1173         kCppAdapterSourceFormats,
1174     },
1175     {
1176         "c++-adapter-main",
1177         "c++-adapter but the adapter binary source only.",
1178         OutputMode::NEEDS_DIR,
1179         Coordinator::Location::DIRECT,
1180         GenerationGranularity::PER_PACKAGE,
1181         validateIsPackage,
1182         {singleFileGenerator("main.cpp", generateAdapterMainSource)},
1183     },
1184     {
1185         "java",
1186         "(internal) Generates Java library for talking to HIDL interfaces in Java.",
1187         OutputMode::NEEDS_DIR,
1188         Coordinator::Location::GEN_SANITIZED,
1189         GenerationGranularity::PER_TYPE,
1190         validateForSource,
1191         {
1192             {
1193                 FileGenerator::alwaysGenerate,
__anon31ab13f91802() 1194                 [](const FQName& fqName) {
1195                     return StringHelper::LTrim(fqName.name(), "types.") + ".java";
1196                 },
1197                 generateJavaForPackage,
1198             },
1199         }
1200     },
1201     {
1202         "java-impl",
1203         "Generates boilerplate implementation of a hidl interface in Java (for convenience).",
1204         OutputMode::NEEDS_DIR,
1205         Coordinator::Location::DIRECT,
1206         GenerationGranularity::PER_FILE,
1207         validateForSource,
1208         {
1209             {
1210                 FileGenerator::generateForInterfaces,
__anon31ab13f91902() 1211                 [](const FQName& fqName) { return fqName.getInterfaceBaseName() + ".java"; },
1212                 astGenerationFunction(&AST::generateJavaImpl),
1213             },
1214         }
1215     },
1216     {
1217         "java-constants",
1218         "(internal) Like export-header but for Java (always created by -Lmakefile if @export exists).",
1219         OutputMode::NEEDS_DIR,
1220         Coordinator::Location::GEN_SANITIZED,
1221         GenerationGranularity::PER_PACKAGE,
1222         validateIsPackage,
1223         {singleFileGenerator("Constants.java", generateExportHeaderForPackage(true /* forJava */))}
1224     },
1225     {
1226         "vts",
1227         "(internal) Generates vts proto files for use in vtsd.",
1228         OutputMode::NEEDS_DIR,
1229         Coordinator::Location::GEN_OUTPUT,
1230         GenerationGranularity::PER_FILE,
1231         validateForSource,
1232         {
1233             {
1234                 FileGenerator::alwaysGenerate,
__anon31ab13f91a02() 1235                 [](const FQName& fqName) {
1236                     return fqName.isInterfaceName() ? fqName.getInterfaceBaseName() + ".vts" : "types.vts";
1237                 },
1238                 astGenerationFunction(&AST::generateVts),
1239             },
1240         }
1241     },
1242     {
1243         "makefile",
1244         "(removed) Used to generate makefiles for -Ljava and -Ljava-constants.",
1245         OutputMode::NEEDS_SRC,
1246         Coordinator::Location::PACKAGE_ROOT,
1247         GenerationGranularity::PER_PACKAGE,
__anon31ab13f91b02() 1248         [](const FQName &, const Coordinator*, const std::string &) {
1249            fprintf(stderr, "ERROR: makefile output is not supported. Use -Landroidbp for all build file generation.\n");
1250            return false;
1251         },
__anon31ab13f91c02() 1252         {},
1253     },
1254     {
1255         "androidbp",
1256         "(internal) Generates Soong bp files for -Lc++-headers, -Lc++-sources, -Ljava, -Ljava-constants, and -Lc++-adapter.",
1257         OutputMode::NEEDS_SRC,
1258         Coordinator::Location::PACKAGE_ROOT,
1259         GenerationGranularity::PER_PACKAGE,
1260         validateIsPackage,
1261         {singleFileGenerator("Android.bp", generateAndroidBpForPackage)},
1262     },
1263     {
1264         "androidbp-impl",
1265         "Generates boilerplate bp files for implementation created with -Lc++-impl.",
1266         OutputMode::NEEDS_DIR,
1267         Coordinator::Location::DIRECT,
1268         GenerationGranularity::PER_PACKAGE,
1269         validateIsPackage,
1270         {singleFileGenerator("Android.bp", generateAndroidBpImplForPackage)},
1271     },
1272     {
1273         "hash",
1274         "Prints hashes of interface in `current.txt` format to standard out.",
1275         OutputMode::NOT_NEEDED,
1276         Coordinator::Location::STANDARD_OUT,
1277         GenerationGranularity::PER_FILE,
1278         validateForSource,
1279         {
1280             {
1281                 FileGenerator::alwaysGenerate,
1282                 nullptr /* file name for fqName */,
1283                 generateHashOutput,
1284             },
1285         }
1286     },
1287     {
1288         "function-count",
1289         "Prints the total number of functions added by the package or interface.",
1290         OutputMode::NOT_NEEDED,
1291         Coordinator::Location::STANDARD_OUT,
1292         GenerationGranularity::PER_FILE,
1293         validateForSource,
1294         {
1295             {
1296                 FileGenerator::generateForInterfaces,
1297                 nullptr /* file name for fqName */,
1298                 generateFunctionCount,
1299             },
1300         }
1301     },
1302     {
1303         "dependencies",
1304         "Prints all depended types.",
1305         OutputMode::NOT_NEEDED,
1306         Coordinator::Location::STANDARD_OUT,
1307         GenerationGranularity::PER_FILE,
1308         validateForSource,
1309         {
1310             {
1311                 FileGenerator::alwaysGenerate,
1312                 nullptr /* file name for fqName */,
1313                 astGenerationFunction(&AST::generateDependencies),
1314             },
1315         },
1316     },
1317     {
1318         "inheritance-hierarchy",
1319         "Prints the hierarchy of inherited types as a JSON object.",
1320         OutputMode::NOT_NEEDED,
1321         Coordinator::Location::STANDARD_OUT,
1322         GenerationGranularity::PER_FILE,
1323         validateForSource,
1324         {
1325             {
1326                 FileGenerator::alwaysGenerate,
1327                 nullptr /* file name for fqName */,
1328                 astGenerationFunction(&AST::generateInheritanceHierarchy),
1329             },
1330         },
1331     },
1332     {
1333         "format",
1334         "Reformats the .hal files",
1335         OutputMode::NEEDS_SRC,
1336         Coordinator::Location::PACKAGE_ROOT,
1337         GenerationGranularity::PER_FILE,
1338         validateForSource,
1339         {
1340             {
1341                 FileGenerator::alwaysGenerate,
__anon31ab13f91d02() 1342                 [](const FQName& fqName) { return fqName.name() + ".hal"; },
1343                 astGenerationFunction(&AST::generateFormattedHidl),
1344             },
1345         }
1346     },
1347 };
1348 // clang-format on
1349 
usage(const char * me)1350 static void usage(const char* me) {
1351     Formatter out(stderr);
1352 
1353     out << "Usage: " << me << " -o <output path> -L <language> [-O <owner>] ";
1354     Coordinator::emitOptionsUsageString(out);
1355     out << " FQNAME...\n\n";
1356 
1357     out << "Process FQNAME, PACKAGE(.SUBPACKAGE)*@[0-9]+.[0-9]+(::TYPE)?, to create output.\n\n";
1358 
1359     out.indent();
1360     out.indent();
1361 
1362     out << "-h: Prints this menu.\n";
1363     out << "-L <language>: The following options are available:\n";
1364     out.indent([&] {
1365         for (auto& e : kFormats) {
1366             std::stringstream sstream;
1367             sstream.fill(' ');
1368             sstream.width(16);
1369             sstream << std::left << e.name();
1370 
1371             out << sstream.str() << ": " << e.description() << "\n";
1372         }
1373     });
1374     out << "-O <owner>: The owner of the module for -Landroidbp(-impl)?.\n";
1375     out << "-o <output path>: Location to output files.\n";
1376     Coordinator::emitOptionsDetailString(out);
1377 
1378     out.unindent();
1379     out.unindent();
1380 }
1381 
1382 // hidl is intentionally leaky. Turn off LeakSanitizer by default.
__asan_default_options()1383 extern "C" const char *__asan_default_options() {
1384     return "detect_leaks=0";
1385 }
1386 
main(int argc,char ** argv)1387 int main(int argc, char **argv) {
1388     const char *me = argv[0];
1389     if (argc == 1) {
1390         usage(me);
1391         exit(1);
1392     }
1393 
1394     const OutputHandler* outputFormat = nullptr;
1395     Coordinator coordinator;
1396     std::string outputPath;
1397 
1398     coordinator.parseOptions(argc, argv, "ho:O:L:", [&](int res, char* arg) {
1399         switch (res) {
1400             case 'o': {
1401                 if (!outputPath.empty()) {
1402                     fprintf(stderr, "ERROR: -o <output path> can only be specified once.\n");
1403                     exit(1);
1404                 }
1405                 outputPath = arg;
1406                 break;
1407             }
1408 
1409             case 'O': {
1410                 if (!coordinator.getOwner().empty()) {
1411                     fprintf(stderr, "ERROR: -O <owner> can only be specified once.\n");
1412                     exit(1);
1413                 }
1414                 coordinator.setOwner(arg);
1415                 break;
1416             }
1417 
1418             case 'L': {
1419                 if (outputFormat != nullptr) {
1420                     fprintf(stderr,
1421                             "ERROR: only one -L option allowed. \"%s\" already specified.\n",
1422                             outputFormat->name().c_str());
1423                     exit(1);
1424                 }
1425                 for (auto& e : kFormats) {
1426                     if (e.name() == arg) {
1427                         outputFormat = &e;
1428                         break;
1429                     }
1430                 }
1431                 if (outputFormat == nullptr) {
1432                     fprintf(stderr, "ERROR: unrecognized -L option: \"%s\".\n", arg);
1433                     exit(1);
1434                 }
1435                 break;
1436             }
1437 
1438             case '?':
1439             case 'h':
1440             default: {
1441                 usage(me);
1442                 exit(1);
1443                 break;
1444             }
1445         }
1446     });
1447 
1448     if (outputFormat == nullptr) {
1449         fprintf(stderr,
1450             "ERROR: no -L option provided.\n");
1451         exit(1);
1452     }
1453 
1454     argc -= optind;
1455     argv += optind;
1456 
1457     if (argc == 0) {
1458         fprintf(stderr, "ERROR: no fqname specified.\n");
1459         usage(me);
1460         exit(1);
1461     }
1462 
1463     // Valid options are now in argv[0] .. argv[argc - 1].
1464 
1465     switch (outputFormat->mOutputMode) {
1466         case OutputMode::NEEDS_DIR:
1467         case OutputMode::NEEDS_FILE: {
1468             if (outputPath.empty()) {
1469                 usage(me);
1470                 exit(1);
1471             }
1472 
1473             if (outputFormat->mOutputMode == OutputMode::NEEDS_DIR) {
1474                 if (outputPath.back() != '/') {
1475                     outputPath += "/";
1476                 }
1477             }
1478             break;
1479         }
1480         case OutputMode::NEEDS_SRC: {
1481             if (outputPath.empty()) {
1482                 outputPath = coordinator.getRootPath();
1483             }
1484             if (outputPath.back() != '/') {
1485                 outputPath += "/";
1486             }
1487 
1488             break;
1489         }
1490 
1491         default:
1492             outputPath.clear();  // Unused.
1493             break;
1494     }
1495 
1496     coordinator.setOutputPath(outputPath);
1497 
1498     for (int i = 0; i < argc; ++i) {
1499         const char* arg = argv[i];
1500 
1501         FQName fqName;
1502         if (!FQName::parse(arg, &fqName)) {
1503             fprintf(stderr, "ERROR: Invalid fully-qualified name as argument: %s.\n", arg);
1504             exit(1);
1505         }
1506 
1507         if (coordinator.getPackageInterfaceFiles(fqName, nullptr /*fileNames*/) != OK) {
1508             fprintf(stderr, "ERROR: Could not get sources for %s.\n", arg);
1509             exit(1);
1510         }
1511 
1512         // Dump extra verbose output
1513         if (coordinator.isVerbose()) {
1514             status_t err =
1515                 dumpDefinedButUnreferencedTypeNames(fqName.getPackageAndVersion(), &coordinator);
1516             if (err != OK) return err;
1517         }
1518 
1519         if (!outputFormat->validate(fqName, &coordinator, outputFormat->name())) {
1520             fprintf(stderr,
1521                     "ERROR: output handler failed.\n");
1522             exit(1);
1523         }
1524 
1525         status_t err = outputFormat->generate(fqName, &coordinator);
1526         if (err != OK) exit(1);
1527 
1528         err = outputFormat->writeDepFile(fqName, &coordinator);
1529         if (err != OK) exit(1);
1530     }
1531 
1532     return 0;
1533 }
1534