• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 
hasVariantFile(const FQName & fqName,const Coordinator * coordinator,const std::string & fileName,bool * isVariant)525 status_t hasVariantFile(const FQName& fqName, const Coordinator* coordinator,
526                         const std::string& fileName, bool* isVariant) {
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 =
534             coordinator->getFilepath(fqName, Coordinator::Location::PACKAGE_ROOT, fileName, &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     *isVariant = exists;
544     return OK;
545 }
546 
isSystemExtPackage(const FQName & fqName,const Coordinator * coordinator,bool * isSystemExt)547 status_t isSystemExtPackage(const FQName& fqName, const Coordinator* coordinator,
548                             bool* isSystemExt) {
549     return hasVariantFile(fqName, coordinator, ".hidl_for_system_ext", isSystemExt);
550 }
551 
isOdmPackage(const FQName & fqName,const Coordinator * coordinator,bool * isOdm)552 status_t isOdmPackage(const FQName& fqName, const Coordinator* coordinator, bool* isOdm) {
553     return hasVariantFile(fqName, coordinator, ".hidl_for_odm", isOdm);
554 }
555 
generateAndroidBpForPackage(const FQName & packageFQName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)556 static status_t generateAndroidBpForPackage(const FQName& packageFQName,
557                                             const Coordinator* coordinator,
558                                             const FileGenerator::GetFormatter& getFormatter) {
559     CHECK(!packageFQName.isFullyQualified() && packageFQName.name().empty());
560 
561     std::vector<FQName> packageInterfaces;
562 
563     status_t err = coordinator->appendPackageInterfacesToVector(packageFQName, &packageInterfaces);
564 
565     if (err != OK) {
566         return err;
567     }
568 
569     std::set<FQName> importedPackagesHierarchy;
570     std::vector<const Type *> exportedTypes;
571     AST* typesAST = nullptr;
572 
573     for (const auto& fqName : packageInterfaces) {
574         AST* ast = coordinator->parse(fqName);
575 
576         if (ast == nullptr) {
577             fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
578 
579             return UNKNOWN_ERROR;
580         }
581 
582         if (fqName.name() == "types") {
583             typesAST = ast;
584         }
585 
586         ast->getImportedPackagesHierarchy(&importedPackagesHierarchy);
587         ast->appendToExportedTypesVector(&exportedTypes);
588     }
589 
590     bool needsJavaCode = packageNeedsJavaCode(packageInterfaces, typesAST);
591 
592     bool genJavaConstants = needsJavaCode && !exportedTypes.empty();
593 
594     bool isJavaCompatible;
595     err = isPackageJavaCompatible(packageFQName, coordinator, &isJavaCompatible);
596     if (err != OK) return err;
597     bool genJavaLibrary = needsJavaCode && isJavaCompatible;
598 
599     bool isCoreAndroid = isCoreAndroidPackage(packageFQName);
600 
601     bool isVndkCore = isVndkCoreLib(packageFQName);
602     bool isVndkSp = isSystemProcessSupportedPackage(packageFQName);
603 
604     bool isSystemExtHidl;
605     err = isSystemExtPackage(packageFQName, coordinator, &isSystemExtHidl);
606     if (err != OK) return err;
607     bool isSystemExt = isSystemExtHidl || !isCoreAndroid;
608 
609     bool isForOdm;
610     err = isOdmPackage(packageFQName, coordinator, &isForOdm);
611     if (err != OK) return err;
612 
613     std::string packageRoot;
614     err = coordinator->getPackageRoot(packageFQName, &packageRoot);
615     if (err != OK) return err;
616 
617     Formatter out = getFormatter();
618     if (!out.isValid()) {
619         return UNKNOWN_ERROR;
620     }
621 
622     out << "// This file is autogenerated by hidl-gen -Landroidbp.\n\n";
623 
624     out << "hidl_interface ";
625     out.block([&] {
626         out << "name: \"" << makeLibraryName(packageFQName) << "\",\n";
627         if (!coordinator->getOwner().empty()) {
628             out << "owner: \"" << coordinator->getOwner() << "\",\n";
629         }
630         out << "root: \"" << packageRoot << "\",\n";
631         if (isVndkCore || isVndkSp) {
632             out << "vndk: ";
633             out.block([&]() {
634                 out << "enabled: true,\n";
635                 if (isVndkSp) {
636                     out << "support_system_process: true,\n";
637                 }
638             }) << ",\n";
639         }
640         if (isSystemExt) {
641             out << "system_ext_specific: true,\n";
642         }
643         if (isForOdm) {
644             out << "odm_available: true,\n";
645         }
646         (out << "srcs: [\n").indent([&] {
647            for (const auto& fqName : packageInterfaces) {
648                out << "\"" << fqName.name() << ".hal\",\n";
649            }
650         }) << "],\n";
651         if (!importedPackagesHierarchy.empty()) {
652             (out << "interfaces: [\n").indent([&] {
653                for (const auto& fqName : importedPackagesHierarchy) {
654                    out << "\"" << fqName.string() << "\",\n";
655                }
656             }) << "],\n";
657         }
658         // Explicity call this out for developers.
659         out << "gen_java: " << (genJavaLibrary ? "true" : "false") << ",\n";
660         if (genJavaConstants) {
661             out << "gen_java_constants: true,\n";
662         }
663    }).endl();
664 
665     return OK;
666 }
667 
generateAndroidBpImplForPackage(const FQName & packageFQName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)668 static status_t generateAndroidBpImplForPackage(const FQName& packageFQName,
669                                                 const Coordinator* coordinator,
670                                                 const FileGenerator::GetFormatter& getFormatter) {
671     const std::string libraryName = makeLibraryName(packageFQName) + "-impl";
672 
673     std::vector<FQName> packageInterfaces;
674 
675     status_t err =
676         coordinator->appendPackageInterfacesToVector(packageFQName,
677                                                      &packageInterfaces);
678 
679     if (err != OK) {
680         return err;
681     }
682 
683     std::set<FQName> importedPackages;
684 
685     for (const auto &fqName : packageInterfaces) {
686         AST *ast = coordinator->parse(fqName);
687 
688         if (ast == nullptr) {
689             fprintf(stderr,
690                     "ERROR: Could not parse %s. Aborting.\n",
691                     fqName.string().c_str());
692 
693             return UNKNOWN_ERROR;
694         }
695 
696         ast->getImportedPackages(&importedPackages);
697     }
698 
699     Formatter out = getFormatter();
700     if (!out.isValid()) {
701         return UNKNOWN_ERROR;
702     }
703 
704     out << "// FIXME: your file license if you have one\n\n";
705     out << "cc_library_shared {\n";
706     out.indent([&] {
707         out << "// FIXME: this should only be -impl for a passthrough hal.\n"
708             << "// In most cases, to convert this to a binderized implementation, you should:\n"
709             << "// - change '-impl' to '-service' here and make it a cc_binary instead of a\n"
710             << "//   cc_library_shared.\n"
711             << "// - add a *.rc file for this module.\n"
712             << "// - delete HIDL_FETCH_I* functions.\n"
713             << "// - call configureRpcThreadpool and registerAsService on the instance.\n"
714             << "// You may also want to append '-impl/-service' with a specific identifier like\n"
715             << "// '-vendor' or '-<hardware identifier>' etc to distinguish it.\n";
716         out << "name: \"" << libraryName << "\",\n";
717         if (!coordinator->getOwner().empty()) {
718             out << "owner: \"" << coordinator->getOwner() << "\",\n";
719         }
720         out << "relative_install_path: \"hw\",\n";
721         if (coordinator->getOwner().empty()) {
722             out << "// FIXME: this should be 'vendor: true' for modules that will eventually be\n"
723                    "// on AOSP.\n";
724         }
725         out << "proprietary: true,\n";
726         out << "srcs: [\n";
727         out.indent([&] {
728             for (const auto &fqName : packageInterfaces) {
729                 if (fqName.name() == "types") {
730                     continue;
731                 }
732                 out << "\"" << fqName.getInterfaceBaseName() << ".cpp\",\n";
733             }
734         });
735         out << "],\n"
736             << "shared_libs: [\n";
737         out.indent([&] {
738             out << "\"libhidlbase\",\n"
739                 << "\"libutils\",\n"
740                 << "\"" << makeLibraryName(packageFQName) << "\",\n";
741 
742             for (const auto &importedPackage : importedPackages) {
743                 if (isHidlTransportPackage(importedPackage)) {
744                     continue;
745                 }
746 
747                 out << "\"" << makeLibraryName(importedPackage) << "\",\n";
748             }
749         });
750         out << "],\n";
751     });
752     out << "}\n";
753 
754     return OK;
755 }
756 
validateForSource(const FQName & fqName,const Coordinator * coordinator,const std::string & language)757 bool validateForSource(const FQName& fqName, const Coordinator* coordinator,
758                        const std::string& language) {
759     if (fqName.package().empty()) {
760         fprintf(stderr, "ERROR: Expecting package name\n");
761         return false;
762     }
763 
764     if (fqName.version().empty()) {
765         fprintf(stderr, "ERROR: Expecting package version\n");
766         return false;
767     }
768 
769     const std::string &name = fqName.name();
770     if (!name.empty()) {
771         if (name.find('.') == std::string::npos) {
772             return true;
773         }
774 
775         if (language != "java" || name.find("types.") != 0) {
776             // When generating java sources for "types.hal", output can be
777             // constrained to just one of the top-level types declared
778             // by using the extended syntax
779             // android.hardware.Foo@1.0::types.TopLevelTypeName.
780             // In all other cases (different language, not 'types') the dot
781             // notation in the name is illegal in this context.
782             return false;
783         }
784 
785         return true;
786     }
787 
788     if (language == "java") {
789         bool isJavaCompatible;
790         status_t err = isPackageJavaCompatible(fqName, coordinator, &isJavaCompatible);
791         if (err != OK) return false;
792 
793         if (!isJavaCompatible) {
794             fprintf(stderr,
795                     "ERROR: %s is not Java compatible. The Java backend does NOT support union "
796                     "types. In addition, vectors of arrays are limited to at most one-dimensional "
797                     "arrays and vectors of {vectors,interfaces,memory} are not supported.\n",
798                     fqName.string().c_str());
799             return false;
800         }
801     }
802 
803     return true;
804 }
805 
validateForFormat(const FQName & fqName,const Coordinator * coordinator,const std::string & format)806 bool validateForFormat(const FQName& fqName, const Coordinator* coordinator,
807                        const std::string& format) {
808     CHECK_EQ(format, "format");
809 
810     if (!validateForSource(fqName, coordinator, format)) return false;
811 
812     std::vector<FQName> packageInterfaces;
813 
814     if (fqName.isFullyQualified()) {
815         packageInterfaces.push_back(fqName);
816     } else {
817         status_t err = coordinator->appendPackageInterfacesToVector(fqName, &packageInterfaces);
818         if (err != OK) return err;
819     }
820 
821     bool destroysInformation = false;
822 
823     for (const auto& fqName : packageInterfaces) {
824         AST* ast = coordinator->parse(fqName);
825 
826         if (ast->getUnhandledComments().size() > 0) {
827             destroysInformation = true;
828             for (const auto& i : ast->getUnhandledComments()) {
829                 std::cerr << "Unrecognized comment at " << i->location() << std::endl;
830                 Formatter err(stderr);
831                 err.indent();
832                 i->emit(err);
833                 err.unindent();
834                 err.endl();
835             }
836         }
837     }
838 
839     if (destroysInformation) {
840         std::cerr << "\nhidl-gen does not support comments at these locations, and formatting "
841                      "the file would destroy them. HIDL doc comments need to be multiline comments "
842                      "(/*...*/) before specific elements. This will also cause them to be emitted "
843                      "in output files in the correct locations so that IDE users or people "
844                      "inspecting generated source can see them in the correct location. Formatting "
845                      "the file would destroy these comments.\n";
846         return false;
847     }
848 
849     return true;
850 }
851 
generateExportHeaderForPackage(bool forJava)852 FileGenerator::GenerationFunction generateExportHeaderForPackage(bool forJava) {
853     return [forJava](const FQName& packageFQName, const Coordinator* coordinator,
854                      const FileGenerator::GetFormatter& getFormatter) -> status_t {
855         CHECK(!packageFQName.package().empty() && !packageFQName.version().empty() &&
856               packageFQName.name().empty());
857 
858         std::vector<FQName> packageInterfaces;
859 
860         status_t err = coordinator->appendPackageInterfacesToVector(
861                 packageFQName, &packageInterfaces);
862 
863         if (err != OK) {
864             return err;
865         }
866 
867         std::vector<const Type *> exportedTypes;
868 
869         for (const auto &fqName : packageInterfaces) {
870             AST *ast = coordinator->parse(fqName);
871 
872             if (ast == nullptr) {
873                 fprintf(stderr,
874                         "ERROR: Could not parse %s. Aborting.\n",
875                         fqName.string().c_str());
876 
877                 return UNKNOWN_ERROR;
878             }
879 
880             ast->appendToExportedTypesVector(&exportedTypes);
881         }
882 
883         if (exportedTypes.empty()) {
884             fprintf(stderr,
885                     "ERROR: -Ljava-constants (Android.bp: gen_java_constants) requested for %s, "
886                     "but no types declare @export.",
887                     packageFQName.string().c_str());
888             return UNKNOWN_ERROR;
889         }
890 
891         Formatter out = getFormatter();
892         if (!out.isValid()) {
893             return UNKNOWN_ERROR;
894         }
895 
896         std::string packagePath;
897         err = coordinator->getPackagePath(packageFQName, false /* relative */,
898                                           false /* sanitized */, &packagePath);
899         if (err != OK) return err;
900 
901         out << "// This file is autogenerated by hidl-gen. Do not edit manually.\n"
902             << "// Source: " << packageFQName.string() << "\n"
903             << "// Location: " << packagePath << "\n\n";
904 
905         std::string guard;
906         if (forJava) {
907             out << "package " << packageFQName.javaPackage() << ";\n\n";
908             out << "public class Constants {\n";
909             out.indent();
910         } else {
911             guard = "HIDL_GENERATED_";
912             guard += StringHelper::Uppercase(packageFQName.tokenName());
913             guard += "_";
914             guard += "EXPORTED_CONSTANTS_H_";
915 
916             out << "#ifndef "
917                 << guard
918                 << "\n#define "
919                 << guard
920                 << "\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n";
921         }
922 
923         for (const auto &type : exportedTypes) {
924             type->emitExportedHeader(out, forJava);
925         }
926 
927         if (forJava) {
928             out.unindent();
929             out << "}\n";
930         } else {
931             out << "#ifdef __cplusplus\n}\n#endif\n\n#endif  // "
932                 << guard
933                 << "\n";
934         }
935 
936         return OK;
937     };
938 }
939 
generateHashOutput(const FQName & fqName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)940 static status_t generateHashOutput(const FQName& fqName, const Coordinator* coordinator,
941                                    const FileGenerator::GetFormatter& getFormatter) {
942     CHECK(fqName.isFullyQualified());
943 
944     AST* ast = coordinator->parse(fqName, {} /* parsed */,
945                                   Coordinator::Enforce::NO_HASH /* enforcement */);
946 
947     if (ast == nullptr) {
948         fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
949 
950         return UNKNOWN_ERROR;
951     }
952 
953     Formatter out = getFormatter();
954     if (!out.isValid()) {
955         return UNKNOWN_ERROR;
956     }
957 
958     out << Hash::getHash(ast->getFilename()).hexString() << " " << fqName.string() << "\n";
959 
960     return OK;
961 }
962 
generateFunctionCount(const FQName & fqName,const Coordinator * coordinator,const FileGenerator::GetFormatter & getFormatter)963 static status_t generateFunctionCount(const FQName& fqName, const Coordinator* coordinator,
964                                       const FileGenerator::GetFormatter& getFormatter) {
965     CHECK(fqName.isFullyQualified());
966 
967     AST* ast = coordinator->parse(fqName, {} /* parsed */,
968                                   Coordinator::Enforce::NO_HASH /* enforcement */);
969 
970     if (ast == nullptr) {
971         fprintf(stderr, "ERROR: Could not parse %s. Aborting.\n", fqName.string().c_str());
972         return UNKNOWN_ERROR;
973     }
974 
975     const Interface* interface = ast->getInterface();
976     if (interface == nullptr) {
977         fprintf(stderr, "ERROR: Function count requires interface: %s.\n", fqName.string().c_str());
978         return UNKNOWN_ERROR;
979     }
980 
981     Formatter out = getFormatter();
982     if (!out.isValid()) {
983         return UNKNOWN_ERROR;
984     }
985 
986     // This is wrong for android.hidl.base@1.0::IBase, but in that case, it doesn't matter.
987     // This is just the number of APIs that are added.
988     out << fqName.string() << " " << interface->userDefinedMethods().size() << "\n";
989 
990     return OK;
991 }
992 
993 template <typename T>
operator +(const std::vector<T> & lhs,const std::vector<T> & rhs)994 std::vector<T> operator+(const std::vector<T>& lhs, const std::vector<T>& rhs) {
995     std::vector<T> ret;
996     ret.reserve(lhs.size() + rhs.size());
997     ret.insert(ret.begin(), lhs.begin(), lhs.end());
998     ret.insert(ret.end(), rhs.begin(), rhs.end());
999     return ret;
1000 }
1001 
1002 // clang-format off
1003 static const std::vector<FileGenerator> kCppHeaderFormats = {
1004     {
1005         FileGenerator::alwaysGenerate,
__anoncf1ffabe0d02() 1006         [](const FQName& fqName) { return fqName.name() + ".h"; },
1007         astGenerationFunction(&AST::generateInterfaceHeader),
1008     },
1009     {
1010         FileGenerator::alwaysGenerate,
__anoncf1ffabe0e02() 1011         [](const FQName& fqName) {
1012             return fqName.isInterfaceName() ? fqName.getInterfaceHwName() + ".h" : "hwtypes.h";
1013         },
1014         astGenerationFunction(&AST::generateHwBinderHeader),
1015     },
1016     {
1017         FileGenerator::generateForInterfaces,
__anoncf1ffabe0f02() 1018         [](const FQName& fqName) { return fqName.getInterfaceStubName() + ".h"; },
1019         astGenerationFunction(&AST::generateStubHeader),
1020     },
1021     {
1022         FileGenerator::generateForInterfaces,
__anoncf1ffabe1002() 1023         [](const FQName& fqName) { return fqName.getInterfaceProxyName() + ".h"; },
1024         astGenerationFunction(&AST::generateProxyHeader),
1025     },
1026     {
1027         FileGenerator::generateForInterfaces,
__anoncf1ffabe1102() 1028         [](const FQName& fqName) { return fqName.getInterfacePassthroughName() + ".h"; },
1029         astGenerationFunction(&AST::generatePassthroughHeader),
1030     },
1031 };
1032 
1033 static const std::vector<FileGenerator> kCppSourceFormats = {
1034     {
1035         FileGenerator::alwaysGenerate,
__anoncf1ffabe1202() 1036         [](const FQName& fqName) {
1037             return fqName.isInterfaceName() ? fqName.getInterfaceBaseName() + "All.cpp" : "types.cpp";
1038         },
1039         astGenerationFunction(&AST::generateCppSource),
1040     },
1041 };
1042 
1043 static const std::vector<FileGenerator> kCppImplHeaderFormats = {
1044     {
1045         FileGenerator::generateForInterfaces,
__anoncf1ffabe1302() 1046         [](const FQName& fqName) { return fqName.getInterfaceBaseName() + ".h"; },
1047         astGenerationFunction(&AST::generateCppImplHeader),
1048     },
1049 };
1050 
1051 static const std::vector<FileGenerator> kCppImplSourceFormats = {
1052     {
1053         FileGenerator::generateForInterfaces,
__anoncf1ffabe1402() 1054         [](const FQName& fqName) { return fqName.getInterfaceBaseName() + ".cpp"; },
1055         astGenerationFunction(&AST::generateCppImplSource),
1056     },
1057 };
1058 
1059 static const std::vector<OutputHandler> kFormats = {
1060     {
1061         "check",
1062         "Parses the interface to see if valid but doesn't write any files.",
1063         OutputMode::NOT_NEEDED,
1064         Coordinator::Location::STANDARD_OUT,
1065         GenerationGranularity::PER_FILE,
1066         validateForSource,
1067         {
1068             {
1069                 FileGenerator::alwaysGenerate,
1070                 nullptr /* filename for fqname */,
1071                 astGenerationFunction(),
1072             },
1073         },
1074     },
1075     {
1076         "c++",
1077         "(internal) (deprecated) Generates C++ interface files for talking to HIDL interfaces.",
1078         OutputMode::NEEDS_DIR,
1079         Coordinator::Location::GEN_OUTPUT,
1080         GenerationGranularity::PER_FILE,
1081         validateForSource,
1082         kCppHeaderFormats + kCppSourceFormats,
1083     },
1084     {
1085         "c++-headers",
1086         "(internal) Generates C++ headers for interface files for talking to HIDL interfaces.",
1087         OutputMode::NEEDS_DIR,
1088         Coordinator::Location::GEN_OUTPUT,
1089         GenerationGranularity::PER_FILE,
1090         validateForSource,
1091         kCppHeaderFormats,
1092     },
1093     {
1094         "c++-sources",
1095         "(internal) Generates C++ sources for interface files for talking to HIDL interfaces.",
1096         OutputMode::NEEDS_DIR,
1097         Coordinator::Location::GEN_OUTPUT,
1098         GenerationGranularity::PER_FILE,
1099         validateForSource,
1100         kCppSourceFormats,
1101     },
1102     {
1103         "export-header",
1104         "Generates a header file from @export enumerations to help maintain legacy code.",
1105         OutputMode::NEEDS_FILE,
1106         Coordinator::Location::DIRECT,
1107         GenerationGranularity::PER_PACKAGE,
1108         validateIsPackage,
1109         {singleFileGenerator("", generateExportHeaderForPackage(false /* forJava */))}
1110     },
1111     {
1112         "c++-impl",
1113         "Generates boilerplate implementation of a hidl interface in C++ (for convenience).",
1114         OutputMode::NEEDS_DIR,
1115         Coordinator::Location::DIRECT,
1116         GenerationGranularity::PER_FILE,
1117         validateForSource,
1118         kCppImplHeaderFormats + kCppImplSourceFormats,
1119     },
1120     {
1121         "c++-impl-headers",
1122         "c++-impl but headers only.",
1123         OutputMode::NEEDS_DIR,
1124         Coordinator::Location::DIRECT,
1125         GenerationGranularity::PER_FILE,
1126         validateForSource,
1127         kCppImplHeaderFormats,
1128     },
1129     {
1130         "c++-impl-sources",
1131         "c++-impl but sources only.",
1132         OutputMode::NEEDS_DIR,
1133         Coordinator::Location::DIRECT,
1134         GenerationGranularity::PER_FILE,
1135         validateForSource,
1136         kCppImplSourceFormats,
1137     },
1138     {
1139         "java",
1140         "(internal) Generates Java library for talking to HIDL interfaces in Java.",
1141         OutputMode::NEEDS_DIR,
1142         Coordinator::Location::GEN_SANITIZED,
1143         GenerationGranularity::PER_TYPE,
1144         validateForSource,
1145         {
1146             {
1147                 FileGenerator::alwaysGenerate,
__anoncf1ffabe1502() 1148                 [](const FQName& fqName) {
1149                     return StringHelper::LTrim(fqName.name(), "types.") + ".java";
1150                 },
1151                 generateJavaForPackage,
1152             },
1153         }
1154     },
1155     {
1156         "java-impl",
1157         "Generates boilerplate implementation of a hidl interface in Java (for convenience).",
1158         OutputMode::NEEDS_DIR,
1159         Coordinator::Location::DIRECT,
1160         GenerationGranularity::PER_FILE,
1161         validateForSource,
1162         {
1163             {
1164                 FileGenerator::generateForInterfaces,
__anoncf1ffabe1602() 1165                 [](const FQName& fqName) { return fqName.getInterfaceBaseName() + ".java"; },
1166                 astGenerationFunction(&AST::generateJavaImpl),
1167             },
1168         }
1169     },
1170     {
1171         "java-constants",
1172         "(internal) Like export-header but for Java (always created by -Lmakefile if @export exists).",
1173         OutputMode::NEEDS_DIR,
1174         Coordinator::Location::GEN_SANITIZED,
1175         GenerationGranularity::PER_PACKAGE,
1176         validateIsPackage,
1177         {singleFileGenerator("Constants.java", generateExportHeaderForPackage(true /* forJava */))}
1178     },
1179     {
1180         "vts",
1181         "(internal) Generates vts proto files for use in vtsd.",
1182         OutputMode::NEEDS_DIR,
1183         Coordinator::Location::GEN_OUTPUT,
1184         GenerationGranularity::PER_FILE,
1185         validateForSource,
1186         {
1187             {
1188                 FileGenerator::alwaysGenerate,
__anoncf1ffabe1702() 1189                 [](const FQName& fqName) {
1190                     return fqName.isInterfaceName() ? fqName.getInterfaceBaseName() + ".vts" : "types.vts";
1191                 },
1192                 astGenerationFunction(&AST::generateVts),
1193             },
1194         }
1195     },
1196     {
1197         "makefile",
1198         "(removed) Used to generate makefiles for -Ljava and -Ljava-constants.",
1199         OutputMode::NEEDS_SRC,
1200         Coordinator::Location::PACKAGE_ROOT,
1201         GenerationGranularity::PER_PACKAGE,
__anoncf1ffabe1802() 1202         [](const FQName &, const Coordinator*, const std::string &) {
1203            fprintf(stderr, "ERROR: makefile output is not supported. Use -Landroidbp for all build file generation.\n");
1204            return false;
1205         },
__anoncf1ffabe1902() 1206         {},
1207     },
1208     {
1209         "androidbp",
1210         "(internal) Generates Soong bp files for -Lc++-headers, -Lc++-sources, -Ljava, and -Ljava-constants",
1211         OutputMode::NEEDS_SRC,
1212         Coordinator::Location::PACKAGE_ROOT,
1213         GenerationGranularity::PER_PACKAGE,
1214         validateIsPackage,
1215         {singleFileGenerator("Android.bp", generateAndroidBpForPackage)},
1216     },
1217     {
1218         "androidbp-impl",
1219         "Generates boilerplate bp files for implementation created with -Lc++-impl.",
1220         OutputMode::NEEDS_DIR,
1221         Coordinator::Location::DIRECT,
1222         GenerationGranularity::PER_PACKAGE,
1223         validateIsPackage,
1224         {singleFileGenerator("Android.bp", generateAndroidBpImplForPackage)},
1225     },
1226     {
1227         "hash",
1228         "Prints hashes of interface in `current.txt` format to standard out.",
1229         OutputMode::NOT_NEEDED,
1230         Coordinator::Location::STANDARD_OUT,
1231         GenerationGranularity::PER_FILE,
1232         validateForSource,
1233         {
1234             {
1235                 FileGenerator::alwaysGenerate,
1236                 nullptr /* file name for fqName */,
1237                 generateHashOutput,
1238             },
1239         }
1240     },
1241     {
1242         "function-count",
1243         "Prints the total number of functions added by the package or interface.",
1244         OutputMode::NOT_NEEDED,
1245         Coordinator::Location::STANDARD_OUT,
1246         GenerationGranularity::PER_FILE,
1247         validateForSource,
1248         {
1249             {
1250                 FileGenerator::generateForInterfaces,
1251                 nullptr /* file name for fqName */,
1252                 generateFunctionCount,
1253             },
1254         }
1255     },
1256     {
1257         "dependencies",
1258         "Prints all depended types.",
1259         OutputMode::NOT_NEEDED,
1260         Coordinator::Location::STANDARD_OUT,
1261         GenerationGranularity::PER_FILE,
1262         validateForSource,
1263         {
1264             {
1265                 FileGenerator::alwaysGenerate,
1266                 nullptr /* file name for fqName */,
1267                 astGenerationFunction(&AST::generateDependencies),
1268             },
1269         },
1270     },
1271     {
1272         "inheritance-hierarchy",
1273         "Prints the hierarchy of inherited types as a JSON object.",
1274         OutputMode::NOT_NEEDED,
1275         Coordinator::Location::STANDARD_OUT,
1276         GenerationGranularity::PER_FILE,
1277         validateForSource,
1278         {
1279             {
1280                 FileGenerator::alwaysGenerate,
1281                 nullptr /* file name for fqName */,
1282                 astGenerationFunction(&AST::generateInheritanceHierarchy),
1283             },
1284         },
1285     },
1286     {
1287         "format",
1288         "Reformats the .hal files",
1289         OutputMode::NEEDS_SRC,
1290         Coordinator::Location::PACKAGE_ROOT,
1291         GenerationGranularity::PER_FILE,
1292         validateForFormat,
1293         {
1294             {
1295                 FileGenerator::alwaysGenerate,
__anoncf1ffabe1a02() 1296                 [](const FQName& fqName) { return fqName.name() + ".hal"; },
1297                 astGenerationFunction(&AST::generateFormattedHidl),
1298             },
1299         }
1300     },
1301 };
1302 // clang-format on
1303 
usage(const char * me)1304 static void usage(const char* me) {
1305     Formatter out(stderr);
1306 
1307     out << "Usage: " << me << " -o <output path> -L <language> [-O <owner>] ";
1308     Coordinator::emitOptionsUsageString(out);
1309     out << " FQNAME...\n\n";
1310 
1311     out << "Process FQNAME, PACKAGE(.SUBPACKAGE)*@[0-9]+.[0-9]+(::TYPE)?, to create output.\n\n";
1312 
1313     out.indent();
1314     out.indent();
1315 
1316     out << "-h: Prints this menu.\n";
1317     out << "-L <language>: The following options are available:\n";
1318     out.indent([&] {
1319         for (auto& e : kFormats) {
1320             std::stringstream sstream;
1321             sstream.fill(' ');
1322             sstream.width(16);
1323             sstream << std::left << e.name();
1324 
1325             out << sstream.str() << ": " << e.description() << "\n";
1326         }
1327     });
1328     out << "-O <owner>: The owner of the module for -Landroidbp(-impl)?.\n";
1329     out << "-o <output path>: Location to output files.\n";
1330     Coordinator::emitOptionsDetailString(out);
1331 
1332     out.unindent();
1333     out.unindent();
1334 }
1335 
1336 // hidl is intentionally leaky. Turn off LeakSanitizer by default.
__asan_default_options()1337 extern "C" const char *__asan_default_options() {
1338     return "detect_leaks=0";
1339 }
1340 
main(int argc,char ** argv)1341 int main(int argc, char **argv) {
1342     const char *me = argv[0];
1343     if (argc == 1) {
1344         usage(me);
1345         exit(1);
1346     }
1347 
1348     const OutputHandler* outputFormat = nullptr;
1349     Coordinator coordinator;
1350     std::string outputPath;
1351 
1352     coordinator.parseOptions(argc, argv, "ho:O:L:", [&](int res, char* arg) {
1353         switch (res) {
1354             case 'o': {
1355                 if (!outputPath.empty()) {
1356                     fprintf(stderr, "ERROR: -o <output path> can only be specified once.\n");
1357                     exit(1);
1358                 }
1359                 outputPath = arg;
1360                 break;
1361             }
1362 
1363             case 'O': {
1364                 if (!coordinator.getOwner().empty()) {
1365                     fprintf(stderr, "ERROR: -O <owner> can only be specified once.\n");
1366                     exit(1);
1367                 }
1368                 coordinator.setOwner(arg);
1369                 break;
1370             }
1371 
1372             case 'L': {
1373                 if (outputFormat != nullptr) {
1374                     fprintf(stderr,
1375                             "ERROR: only one -L option allowed. \"%s\" already specified.\n",
1376                             outputFormat->name().c_str());
1377                     exit(1);
1378                 }
1379                 for (auto& e : kFormats) {
1380                     if (e.name() == arg) {
1381                         outputFormat = &e;
1382                         break;
1383                     }
1384                 }
1385                 if (outputFormat == nullptr) {
1386                     fprintf(stderr, "ERROR: unrecognized -L option: \"%s\".\n", arg);
1387                     exit(1);
1388                 }
1389                 break;
1390             }
1391 
1392             case '?':
1393             case 'h':
1394             default: {
1395                 usage(me);
1396                 exit(1);
1397                 break;
1398             }
1399         }
1400     });
1401 
1402     if (outputFormat == nullptr) {
1403         fprintf(stderr,
1404             "ERROR: no -L option provided.\n");
1405         exit(1);
1406     }
1407 
1408     argc -= optind;
1409     argv += optind;
1410 
1411     if (argc == 0) {
1412         fprintf(stderr, "ERROR: no fqname specified.\n");
1413         usage(me);
1414         exit(1);
1415     }
1416 
1417     // Valid options are now in argv[0] .. argv[argc - 1].
1418 
1419     switch (outputFormat->mOutputMode) {
1420         case OutputMode::NEEDS_DIR:
1421         case OutputMode::NEEDS_FILE: {
1422             if (outputPath.empty()) {
1423                 usage(me);
1424                 exit(1);
1425             }
1426 
1427             if (outputFormat->mOutputMode == OutputMode::NEEDS_DIR) {
1428                 if (outputPath.back() != '/') {
1429                     outputPath += "/";
1430                 }
1431             }
1432             break;
1433         }
1434         case OutputMode::NEEDS_SRC: {
1435             if (outputPath.empty()) {
1436                 outputPath = coordinator.getRootPath();
1437             }
1438             if (outputPath.back() != '/') {
1439                 outputPath += "/";
1440             }
1441 
1442             break;
1443         }
1444 
1445         default:
1446             outputPath.clear();  // Unused.
1447             break;
1448     }
1449 
1450     coordinator.setOutputPath(outputPath);
1451 
1452     for (int i = 0; i < argc; ++i) {
1453         const char* arg = argv[i];
1454 
1455         FQName fqName;
1456         if (!FQName::parse(arg, &fqName)) {
1457             fprintf(stderr, "ERROR: Invalid fully-qualified name as argument: %s.\n", arg);
1458             exit(1);
1459         }
1460 
1461         if (coordinator.getPackageInterfaceFiles(fqName, nullptr /*fileNames*/) != OK) {
1462             fprintf(stderr, "ERROR: Could not get sources for %s.\n", arg);
1463             exit(1);
1464         }
1465 
1466         // Dump extra verbose output
1467         if (coordinator.isVerbose()) {
1468             status_t err =
1469                 dumpDefinedButUnreferencedTypeNames(fqName.getPackageAndVersion(), &coordinator);
1470             if (err != OK) return err;
1471         }
1472 
1473         if (!outputFormat->validate(fqName, &coordinator, outputFormat->name())) {
1474             fprintf(stderr, "ERROR: Validation failed.\n");
1475             exit(1);
1476         }
1477 
1478         status_t err = outputFormat->generate(fqName, &coordinator);
1479         if (err != OK) exit(1);
1480 
1481         err = outputFormat->writeDepFile(fqName, &coordinator);
1482         if (err != OK) exit(1);
1483     }
1484 
1485     return 0;
1486 }
1487