hal 文件的作用
hal文件用来定义hal层, 对外通信的接口 和 通信数据的格式
处理 hal文件的工具
out/host/linux-x86/bin/hidl-gen 命令会将 hal文件转换为相应的文件, 例:
usage: out/host/linux-x86/bin/hidl-gen [-p <root path>] -o <output path> -L <language> (-r <interface root>)+ [-t] fqname+
-h: Prints this menu.
-L <language>: The following options are available:
check : Parses the interface to see if valid but doesn't write any files.
c++ : (internal) (deprecated) Generates C++ interface files for talking to HIDL interfaces.
c++-headers : (internal) Generates C++ headers for interface files for talking to HIDL interfaces.
c++-sources : (internal) Generates C++ sources for interface files for talking to HIDL interfaces.
export-header : Generates a header file from @export enumerations to help maintain legacy code.
c++-impl : Generates boilerplate implementation of a hidl interface in C++ (for convenience).
c++-impl-headers: c++-impl but headers only
c++-impl-sources: c++-impl but sources only
java : (internal) Generates Java library for talking to HIDL interfaces in Java.
java-constants : (internal) Like export-header but for Java (always created by -Lmakefile if @export exists).
vts : (internal) Generates vts proto files for use in vtsd.
makefile : (internal) Generates makefiles for -Ljava and -Ljava-constants.
androidbp : (internal) Generates Soong bp files for -Lc++-headers and -Lc++-sources.
androidbp-impl : Generates boilerplate bp files for implementation created with -Lc++-impl.
hash : Prints hashes of interface in `current.txt` format to standard out.
-o <output path>: Location to output files.
-p <root path>: Android build root, defaults to $ANDROID_BUILD_TOP or pwd.
-r <package:path root>: E.g., android.hardware:hardware/interfaces.
-t: generate build scripts (Android.bp) for tests.
处理hal文件的流程
./out/host/linux-x86/bin/hidl-gen -o ./demo -Lc++-headers -randroid.hardware:hardware/interfaces -randroid.hidl:system/libhidl/transport android.hardware.automotive.vehicle@2.0
-o: 生成文件的目录
-Lc++-headers: 生成c++ 头文件
-r:指定包号和root路径
android/system/tools/hidl/main.cpp
int main(int argc, char **argv){
OutputHandler *outputFormat = nullptr;
while ((res = getopt(argc, argv, "hp:o:r:L:t")) >= 0) {
switch (res) {
case 'L': {
for (auto &e : formats) {
if (e.name() == optarg) {
//指向 要 执行的配置
outputFormat = &e;
break;
}
}
break;
}
.......
}
Coordinator coordinator(packageRootPaths, packageRoots, rootPath);
coordinator.addDefaultPackagePath("android.hardware", "hardware/interfaces");
coordinator.addDefaultPackagePath("android.hidl", "system/libhidl/transport");
coordinator.addDefaultPackagePath("android.frameworks", "frameworks/hardware/interfaces");
coordinator.addDefaultPackagePath("android.system", "system/hardware/interfaces");
for (int i = 0; i < argc; ++i) {
FQName fqName(argv[i]);
outputFormat->generate(fqName, me, &coordinator, outputPath);
}
}
outputFormat是根据 -L 的参数, 从formats 中获取到的对应配置
outputFormat 对应结构体OutputHandler 的定义为:
struct OutputHandler {
std::string mKey;
std::string mDescription;
enum OutputMode {
NEEDS_DIR,
NEEDS_FILE,
NEEDS_SRC, // for changes inside the source tree itself
NOT_NEEDED
} mOutputMode;
const std::string& name() { return mKey; }
const std::string& description() { return mDescription; }
using ValidationFunction = std::function<bool(const FQName &, const std::string &language)>;
using GenerationFunction = std::function<status_t(const FQName &fqName,
┆ ┆ ┆ ┆ ┆ ┆ ┆ const char *hidl_gen,
┆ ┆ ┆ ┆ ┆ ┆ ┆ Coordinator *coordinator,
┆ ┆ ┆ ┆ ┆ ┆ ┆ const std::string &outputDir)>;
ValidationFunction validate;
GenerationFunction generate;
};
-Lc+±headers 对应的配置为:
static std::vector<OutputHandler> formats = {
{
"c++-headers",
"(internal) Generates C++ headers for interface files for talking to HIDL interfaces.",
OutputHandler::NEEDS_DIR /* mOutputMode */,
validateForSource,
generationFunctionForFileOrPackage("c++-headers")
},
{
"c++-impl", //key---name
"Generates boilerplate implementation of a hidl interface in C++ (for convenience).", //des
OutputHandler::NEEDS_DIR /* mOutputMode */,
validateForSource, //校验文件
generationFunctionForFileOrPackage("c++-impl") //生成 src
},
}
outputFormat->generate(fqName, me, &coordinator, outputPath);
调用的对应方法为:
OutputHandler::GenerationFunction generationFunctionForFileOrPackage(const std::string &language) {
return [language](const FQName &fqName, const char *hidl_gen, Coordinator *coordinator, const std::string &outputDir) -> status_t {
if (fqName.isFullyQualified()) {
return generateSourcesForFile(fqName, hidl_gen, coordinator, outputDir, language);
} else {
return generateSourcesForPackage(fqName, hidl_gen, coordinator, outputDir, language);
}
};
}
此处fqName.isFullyQualified()
is false走的是generateSourcesForPackage
方法:
static status_t generateSourcesForPackage(const FQName &packageFQName, const char *hidl_gen,
Coordinator *coordinator, const std::string &outputDir, const std::string &lang) {
std::vector<FQName> packageInterfaces;
status_t err = coordinator->appendPackageInterfacesToVector(packageFQName, &packageInterfaces);
for (const auto &fqName : packageInterfaces) {
err = generateSourcesForFile( fqName, hidl_gen, coordinator, outputDir, lang);
}
return OK;
}
走的是generateSourcesForFile 去解析文件,生成文件
static status_t generateSourcesForFile( const FQName &fqName, const char *,
Coordinator *coordinator, const std::string &outputDir, const std::string &lang) {
AST *ast;
std::string limitToType;
if (fqName.name().find("types.") == 0) {
limitToType = fqName.name().substr(strlen("types."));
FQName typesName = fqName.getTypesForPackage();
ast = coordinator->parse(typesName);
}
if (lang == "c++") {
return ast->generateCpp(outputDir);
}
if (lang == "c++-headers") {
return ast->generateCppHeaders(outputDir);
}
if (lang == "c++-sources") {
return ast->generateCppSources(outputDir);
}
if (lang == "c++-impl") {
return ast->generateCppImpl(outputDir);
}
if (lang == "c++-impl-headers") {
return ast->generateStubImplHeader(outputDir);
}
if (lang == "c++-impl-sources") {
return ast->generateStubImplSource(outputDir);
}
if (lang == "java") {
return ast->generateJava(outputDir, limitToType);
}
if (lang == "vts") {
return ast->generateVts(outputDir);
}
return UNKNOWN_ERROR;
}
此处分为两个步骤解析 和生成
1. 解析:
android/system/tools/hidl/Coordinator.cpp
AST* Coordinator::parse(const FQName& fqName, std::set<AST*>* parsedASTs,
Enforce enforcement) const {
auto it = mCache.find(fqName);
if (it != mCache.end()) {
AST *ast = (*it).second;
if (ast != nullptr && parsedASTs != nullptr) {
parsedASTs->insert(ast);
}
return ast;
}
mCache[fqName] = nullptr;
AST *typesAST = nullptr;
if (fqName.name() != "types") {
FQName typesName = fqName.getTypesForPackage();
typesAST = parse(typesName, nullptr, Enforce::NONE);
}
std::string path = getAbsolutePackagePath(fqName);
path.append(fqName.name());
path.append(".hal");
AST *ast = new AST(this, path);
if (typesAST != NULL) {
ast->addImportedAST(typesAST);
}
status_t err = parseFile(ast);
...
return ast;
}
android/system/tools/hidl/hidl-gen_l.ll
status_t parseFile(AST *ast) {
FILE *file = fopen(ast->getFilename().c_str(), "rb");
//扫描器
yyscan_t scanner;
//初始化 扫描器
yylex_init(&scanner);
//设置扫描器对应的文件
yyset_in(file, scanner);
Scope* scopeStack = ast->getRootScope();
int res = yy::parser(scanner, ast, &scopeStack).parse();
yylex_destroy(scanner);
fclose(file);
file = nullptr;
return OK;
}
这里用到的是 flex 和 B is o n的技术对hal 文件进行词法分析和语法分析, 生成相应 的cpp文件
//flex 与bison待补充学习
system/tools/hidl/hidl-gen_y.yy
typedef_declaration
: TYPEDEF type valid_type_name
{
std::string errorMsg;
if (!ast->addTypeDef($3, $2, convertYYLoc(@3), &errorMsg, *scope)) {
std::cerr << "ERROR: " << errorMsg << " at " << @3 << "\n";
YYERROR;
}
$$ = nullptr;
}
;
bool AST::addTypeDef(const char* localName, Type* type, const Location& location,
std::string* errorMsg, Scope* scope) {
return addScopedTypeInternal(new TypeDef(localName, location, scope, type), errorMsg, scope);
}
bool AST::addScopedTypeInternal(NamedType* type, std::string* errorMsg, Scope* scope) {
bool success = scope->addType(type, errorMsg);
std::vector<std::string> pathComponents{{type->localName()}};
for (; scope != &mRootScope; scope = scope->parent()) {
pathComponents.push_back(scope->localName());
}
std::reverse(pathComponents.begin(), pathComponents.end());
std::string path = StringHelper::JoinStrings(pathComponents, ".");
FQName fqName(mPackage.package(), mPackage.version(), path);
type->setFullName(fqName);
mDefinedTypesByFullName[fqName] = type;
return true;
}
system/tools/hidl/Scope.cpp
bool Scope::addType(NamedType *type, std::string *errorMsg) {
const std::string &localName = type->localName();
fprintf(stderr,"hecheng addType %s \n", localName.c_str());
auto it = mTypeIndexByName.find(localName);
if (it != mTypeIndexByName.end()) {
*errorMsg = "A type named '";
(*errorMsg) += localName;
(*errorMsg) += "' is already declared in the current scope.";
return false;
}
size_t index = mTypes.size();
mTypes.push_back(type);
mTypeIndexByName[localName] = index;
return true;
}
2. 生成
我们传入的参数为c++-headers
所以生产走的是generateCppHeaders
方法:
android/system/tools/hidl/generateCpp.cpp
status_t AST::generateCppHeaders(const std::string &outputPath) const {
status_t err = generateInterfaceHeader(outputPath);
if (err == OK) {
err = generateStubHeader(outputPath);
}
if (err == OK) {
err = generateHwBinderHeader(outputPath);
}
if (err == OK) {
err = generateProxyHeader(outputPath);
}
if (err == OK) {
err = generatePassthroughHeader(outputPath);
}
return err;
}
status_t AST::generateInterfaceHeader(const std::string &outputPath) const {
const Interface *iface = getInterface();
std::string ifaceName = iface ? iface->localName() : "types";
//输出文件
std::string path = outputPath;
path.append(mCoordinator->convertPackageRootToPath(mPackage));
path.append(mCoordinator->getPackagePath(mPackage, true /* relative */));
path.append(ifaceName);
path.append(".h");
FILE *file = fopen(path.c_str(), "w");
Formatter out(file);
const std::string guard = makeHeaderGuard(ifaceName);
out << "#ifndef " << guard << "\n";
out << "#define " << guard << "\n\n";
//向out中导入include
for (const auto &item : mImportedNames) {
generateCppPackageInclude(out, item, item.name());
}
out << "#include <hidl/HidlSupport.h>\n";
out << "#include <hidl/MQDescriptor.h>\n";
out << "#include <utils/NativeHandle.h>\n";
out << "#include <utils/misc.h>\n\n"; /* for report_sysprop_change() */
//向out中写入name space
enterLeaveNamespace(out, true /* enter */);
out << "\n";
status_t err = emitTypeDeclarations(out);
err = mRootScope.emitGlobalTypeDeclarations(out);
out << "\n";
enterLeaveNamespace(out, false /* enter */);
out << "\n#endif // " << guard << "\n";
return OK;
}
generateCppPackageInclude
将导入的包写入out file
enterLeaveNamespace
将name space 写入out file
emitTypeDeclarations
将type类型写入out file, 在types.hal 中用于 将 定义的所有枚举 等类型写入
status_t AST::emitTypeDeclarations(Formatter &out) const {
return mRootScope.emitTypeDeclarations(out);
}
android/system/tools/hidl/Scope.cpp
status_t Scope::emitTypeDeclarations(Formatter &out) const {
return forEachType([&](Type *type) {
return type->emitTypeDeclarations(out);
});
}
android/system/tools/hidl/EnumType.cpp
status_t EnumType::emitTypeDeclarations(Formatter &out) const {
const ScalarType *scalarType = mStorageType->resolveToScalarType();
const std::string storageType = scalarType->getCppStackType();
out << "enum class " << localName() << " : " << storageType << " {\n";
out.indent();
std::vector<const EnumType *> chain;
getTypeChain(&chain);
for (auto it = chain.rbegin(); it != chain.rend(); ++it) {
const auto &type = *it;
for (const auto &entry : type->values()) {
out << entry->name();
std::string value = entry->cppValue(scalarType->getKind());
out << " = " << value;
out << ",";
std::string comment = entry->comment();
if (!comment.empty() && comment != value) {
out << " // " << comment;
}
out << "\n";
}
}
out.unindent();
out << "};\n\n";
return OK;
}
将type
内的数据遍历写入 out file 内