• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 <getopt.h>
18 
19 #include <android-base/strings.h>
20 #include <json/json.h>
21 #include <vintf/VintfObject.h>
22 #include <vintf/parse_string.h>
23 #include <vintf/parse_xml.h>
24 
25 #include <iomanip>
26 #include <iostream>
27 #include <string>
28 #include <vector>
29 
30 using namespace ::android::vintf;
31 
32 static const std::string kColumnSeparator = "   ";
33 
existString(bool value)34 std::string existString(bool value) {
35     return value ? "GOOD" : "DOES NOT EXIST";
36 }
37 
compatibleString(int32_t value)38 std::string compatibleString(int32_t value) {
39     switch (value) {
40         case COMPATIBLE:
41             return "GOOD";
42         case INCOMPATIBLE:
43             return "INCOMPATIBLE";
44         default:
45             return strerror(-value);
46     }
47 }
48 
boolCompatString(bool value)49 std::string boolCompatString(bool value) {
50     return compatibleString(value ? COMPATIBLE : INCOMPATIBLE);
51 }
52 
deprecateString(int32_t value)53 std::string deprecateString(int32_t value) {
54     switch (value) {
55         case NO_DEPRECATED_HALS:
56             return "GOOD";
57         case DEPRECATED:
58             return "DEPRECATED";
59         default:
60             return strerror(-value);
61     }
62 }
63 
64 enum Status : int {
65     OK = 0,
66     USAGE,
67 };
68 
69 struct ParsedOptions;
70 
71 void dumpLegacy(const ParsedOptions&);
72 void dumpDm(const ParsedOptions&);
73 void dumpFm(const ParsedOptions&);
74 void dumpDcm(const ParsedOptions&);
75 void dumpFcm(const ParsedOptions&);
76 void dumpRi(const ParsedOptions&);
77 
78 struct DumpTargetOption {
79     std::string name;
80     std::function<void(const ParsedOptions&)> fn;
81     std::string help;
82 };
83 
84 std::vector<DumpTargetOption> gTargetOptions = {
85     {"legacy", &dumpLegacy, "Print VINTF metadata."},
86     {"dm", &dumpDm, "Print Device HAL Manifest."},
87     {"fm", &dumpFm, "Print Framework HAL Manifest."},
88     {"dcm", &dumpDcm, "Print Device Compatibility Matrix."},
89     {"fcm", &dumpFcm, "Print Framework Compatibility Matrix."},
90     {"ri", &dumpRi, "Print Runtime Information."},
91 };
92 
93 struct ParsedOptions {
94     bool verbose = false;
95     std::function<void(const ParsedOptions&)> fn = &dumpLegacy;
96 };
97 
98 struct Option {
99     char shortOption = '\0';
100     std::string longOption;
101     std::string help;
102     std::function<Status(ParsedOptions*)> op;
103 };
104 
getShortOptions(const std::vector<Option> & options)105 std::string getShortOptions(const std::vector<Option>& options) {
106     std::stringstream ret;
107     for (const auto& e : options)
108         if (e.shortOption != '\0') ret << e.shortOption;
109     return ret.str();
110 }
111 
getLongOptions(const std::vector<Option> & options,int * longOptFlag)112 std::unique_ptr<struct option[]> getLongOptions(const std::vector<Option>& options,
113                                                 int* longOptFlag) {
114     std::unique_ptr<struct option[]> ret{new struct option[options.size() + 1]};
115     int i = 0;
116     for (const auto& e : options) {
117         ret[i].name = e.longOption.c_str();
118         ret[i].has_arg = no_argument;
119         ret[i].flag = longOptFlag;
120         ret[i].val = i;
121 
122         i++;
123     }
124     // getopt_long last option has all zeros
125     ret[i].name = NULL;
126     ret[i].has_arg = 0;
127     ret[i].flag = NULL;
128     ret[i].val = 0;
129 
130     return ret;
131 }
132 
parseOptions(int argc,char ** argv,const std::vector<Option> & options,ParsedOptions * out)133 Status parseOptions(int argc, char** argv, const std::vector<Option>& options, ParsedOptions* out) {
134     int longOptFlag;
135     std::unique_ptr<struct option[]> longOptions = getLongOptions(options, &longOptFlag);
136     std::string shortOptions = getShortOptions(options);
137     int optionIndex;
138     for (;;) {
139         int c = getopt_long(argc, argv, shortOptions.c_str(), longOptions.get(), &optionIndex);
140         if (c == -1) {
141             break;
142         }
143         const Option* found = nullptr;
144         for (size_t i = 0; i < options.size(); ++i)
145             if ((c == 0 && longOptFlag == static_cast<int>(i)) ||
146                 (c != 0 && c == options[i].shortOption))
147 
148                 found = &options[i];
149 
150         if (found == nullptr) {
151             // see unrecognized options
152             std::cerr << "unrecognized option `" << argv[optind - 1] << "'" << std::endl;
153             return USAGE;
154         }
155 
156         Status status = found->op(out);
157         if (status != OK) return status;
158     }
159     // optional/positional/enum
160     if (optind < argc) {
161         for (const auto& o : gTargetOptions) {
162             if (o.name == argv[optind]) {
163                 out->fn = o.fn;
164                 optind++;
165                 break;
166             }
167         }
168     }
169     if (optind < argc) {
170         // see non option
171         std::cerr << "unrecognized option `" << argv[optind] << "'" << std::endl;
172         return USAGE;
173     }
174     return OK;
175 }
176 
usage(char * me,const std::vector<Option> & options)177 void usage(char* me, const std::vector<Option>& options) {
178     std::cerr << me << ": dump VINTF metadata via libvintf." << std::endl;
179     for (const auto& e : options) {
180         if (e.help.empty()) continue;
181         std::cerr << "        ";
182         if (e.shortOption != '\0') std::cerr << "-" << e.shortOption;
183         if (e.shortOption != '\0' && !e.longOption.empty()) std::cerr << ", ";
184         if (!e.longOption.empty()) std::cerr << "--" << e.longOption;
185         std::cerr << ": "
186                   << android::base::Join(android::base::Split(e.help, "\n"), "\n            ")
187                   << std::endl;
188     }
189     // optional/positional/enum
190     std::cerr << "        ";
191     std::vector<std::string> enumValues;
192     for (const auto& o : gTargetOptions) {
193         enumValues.push_back(o.name);
194     }
195     std::cerr << "[" << android::base::Join(enumValues, "|") << "]:\n";
196     for (const auto& o : gTargetOptions) {
197         std::cerr << "            " << o.name << ": " << o.help << "\n";
198     }
199 }
200 
201 struct TableRow {
202     // Whether the HAL version is in device manifest, framework manifest, device compatibility
203     // matrix, framework compatibility matrix, respectively.
204     bool dm = false;
205     bool fm = false;
206     bool dcm = false;
207     bool fcm = false;
208 };
209 
operator <<(std::ostream & out,const TableRow & row)210 std::ostream& operator<<(std::ostream& out, const TableRow& row) {
211     return out << kColumnSeparator << (row.dm ? "DM" : "  ") << kColumnSeparator
212                << (row.fm ? "FM" : "  ") << kColumnSeparator << (row.fcm ? "FCM" : "   ")
213                << kColumnSeparator << (row.dcm ? "DCM" : "   ");
214 }
215 
216 using RowMutator = std::function<void(TableRow*)>;
217 using Table = std::map<std::string, TableRow>;
218 
219 // Insert each fqInstanceName foo@x.y::IFoo/instance to the table by inserting the key
220 // if it does not exist and setting the corresponding indicator (as specified by "mutate").
insert(const HalManifest * manifest,Table * table,const RowMutator & mutate)221 void insert(const HalManifest* manifest, Table* table, const RowMutator& mutate) {
222     if (manifest == nullptr) return;
223     manifest->forEachInstance([&](const auto& manifestInstance) {
224         std::string key = manifestInstance.description();
225         mutate(&(*table)[key]);
226         return true;
227     });
228 }
229 
insert(const CompatibilityMatrix * matrix,Table * table,const RowMutator & mutate)230 void insert(const CompatibilityMatrix* matrix, Table* table, const RowMutator& mutate) {
231     if (matrix == nullptr) return;
232     matrix->forEachInstance([&](const auto& matrixInstance) {
233         for (auto minorVer = matrixInstance.versionRange().minMinor;
234              minorVer >= matrixInstance.versionRange().minMinor &&
235              minorVer <= matrixInstance.versionRange().maxMinor;
236              ++minorVer) {
237             Version version{matrixInstance.versionRange().majorVer, minorVer};
238             std::string key = matrixInstance.description(version);
239             auto it = table->find(key);
240             if (it == table->end()) {
241                 mutate(&(*table)[key]);
242             } else {
243                 mutate(&it->second);
244             }
245         }
246         return true;
247     });
248 }
249 
generateHalSummary(const HalManifest * vm,const HalManifest * fm,const CompatibilityMatrix * vcm,const CompatibilityMatrix * fcm)250 Table generateHalSummary(const HalManifest* vm, const HalManifest* fm,
251                          const CompatibilityMatrix* vcm, const CompatibilityMatrix* fcm) {
252     Table table;
253     insert(vm, &table, [](auto* row) { row->dm = true; });
254     insert(fm, &table, [](auto* row) { row->fm = true; });
255     insert(vcm, &table, [](auto* row) { row->dcm = true; });
256     insert(fcm, &table, [](auto* row) { row->fcm = true; });
257 
258     return table;
259 }
260 
261 static const std::vector<Option> gAvailableOptions{
__anon292d6d0c0702() 262     {'h', "help", "Print help message.", [](auto) { return USAGE; }},
__anon292d6d0c0802() 263     {'v', "verbose", "Dump detailed and raw content, including kernel configurations", [](auto o) {
264          o->verbose = true;
265          return OK;
266      }}};
267 // A convenience binary to dump information available through libvintf.
main(int argc,char ** argv)268 int main(int argc, char** argv) {
269     ParsedOptions options;
270     Status status = parseOptions(argc, argv, gAvailableOptions, &options);
271     if (status == USAGE) usage(argv[0], gAvailableOptions);
272     if (status != OK) return status;
273 
274     options.fn(options);
275 }
276 
dumpLegacy(const ParsedOptions & options)277 void dumpLegacy(const ParsedOptions& options) {
278     auto vm = VintfObject::GetDeviceHalManifest();
279     auto fm = VintfObject::GetFrameworkHalManifest();
280     auto vcm = VintfObject::GetDeviceCompatibilityMatrix();
281     auto fcm = VintfObject::GetFrameworkCompatibilityMatrix();
282     auto ki = VintfObject::GetRuntimeInfo();
283 
284     if (!options.verbose) {
285         std::cout << "======== HALs =========" << std::endl
286                   << "DM: device manifest. FM: framework manifest." << std::endl
287                   << "FCM: framework compatibility matrix. DCM: device compatibility matrix."
288                   << std::endl
289                   << std::endl;
290         auto table = generateHalSummary(vm.get(), fm.get(), vcm.get(), fcm.get());
291 
292         for (const auto& pair : table)
293             std::cout << pair.second << kColumnSeparator << pair.first << std::endl;
294 
295         std::cout << std::endl;
296     }
297 
298     SerializeFlags::Type flags = SerializeFlags::EVERYTHING;
299     if (!options.verbose) {
300         flags = flags.disableHals().disableKernel();
301     }
302     std::cout << "======== Device HAL Manifest =========" << std::endl;
303     if (vm != nullptr) std::cout << toXml(*vm, flags);
304     std::cout << "======== Framework HAL Manifest =========" << std::endl;
305     if (fm != nullptr) std::cout << toXml(*fm, flags);
306     std::cout << "======== Device Compatibility Matrix =========" << std::endl;
307     if (vcm != nullptr) std::cout << toXml(*vcm, flags);
308     std::cout << "======== Framework Compatibility Matrix =========" << std::endl;
309     if (fcm != nullptr) std::cout << toXml(*fcm, flags);
310 
311     std::cout << "======== Runtime Info =========" << std::endl;
312     if (ki != nullptr) std::cout << dump(*ki, options.verbose);
313 
314     std::cout << std::endl;
315 
316     std::cout << "======== Summary =========" << std::endl;
317     std::cout << "Device Manifest?    " << existString(vm != nullptr) << std::endl
318               << "Device Matrix?      " << existString(vcm != nullptr) << std::endl
319               << "Framework Manifest? " << existString(fm != nullptr) << std::endl
320               << "Framework Matrix?   " << existString(fcm != nullptr) << std::endl;
321     std::string error;
322     if (vm && fcm) {
323         bool compatible = vm->checkCompatibility(*fcm, &error);
324         std::cout << "Device HAL Manifest <==> Framework Compatibility Matrix? "
325                   << boolCompatString(compatible);
326         if (!compatible)
327             std::cout << ", " << error;
328         std::cout << std::endl;
329     }
330     if (fm && vcm) {
331         bool compatible = fm->checkCompatibility(*vcm, &error);
332         std::cout << "Framework HAL Manifest <==> Device Compatibility Matrix? "
333                   << boolCompatString(compatible);
334         if (!compatible)
335             std::cout << ", " << error;
336         std::cout << std::endl;
337     }
338     if (ki && fcm) {
339         bool compatible = ki->checkCompatibility(*fcm, &error);
340         std::cout << "Runtime info <==> Framework Compatibility Matrix?        "
341                   << boolCompatString(compatible);
342         if (!compatible) std::cout << ", " << error;
343         std::cout << std::endl;
344     }
345 
346     {
347         auto compatible = VintfObject::GetInstance()->checkCompatibility(&error);
348         std::cout << "VintfObject::checkCompatibility?                         "
349                   << compatibleString(compatible);
350         if (compatible != COMPATIBLE) std::cout << ", " << error;
351         std::cout << std::endl;
352     }
353 
354     if (vm && fcm) {
355         // TODO(b/131717099): Use correct information from libhidlmetadata
356         auto deprecate = VintfObject::GetInstance()->checkDeprecation({}, &error);
357         std::cout << "VintfObject::CheckDeprecation (against device manifest) (w/o hidlmetadata)? "
358                   << deprecateString(deprecate);
359         if (deprecate != NO_DEPRECATED_HALS) std::cout << ", " << error;
360         std::cout << std::endl;
361     }
362 }
363 
dumpDm(const ParsedOptions &)364 void dumpDm(const ParsedOptions&) {
365     auto dm = VintfObject::GetDeviceHalManifest();
366     if (dm != nullptr) std::cout << toXml(*dm);
367 }
368 
dumpFm(const ParsedOptions &)369 void dumpFm(const ParsedOptions&) {
370     auto fm = VintfObject::GetFrameworkHalManifest();
371     if (fm != nullptr) std::cout << toXml(*fm);
372 }
373 
dumpDcm(const ParsedOptions &)374 void dumpDcm(const ParsedOptions&) {
375     auto dcm = VintfObject::GetDeviceCompatibilityMatrix();
376     if (dcm != nullptr) std::cout << toXml(*dcm);
377 }
378 
dumpFcm(const ParsedOptions &)379 void dumpFcm(const ParsedOptions&) {
380     auto fcm = VintfObject::GetFrameworkCompatibilityMatrix();
381     if (fcm != nullptr) std::cout << toXml(*fcm);
382 }
383 
384 // Keep field names in sync with VintfDeviceInfo's usage
dumpRi(const ParsedOptions &)385 void dumpRi(const ParsedOptions&) {
386     const RuntimeInfo::FetchFlags flags = RuntimeInfo::FetchFlag::CPU_INFO |
387                                           RuntimeInfo::FetchFlag::CPU_VERSION |
388                                           RuntimeInfo::FetchFlag::POLICYVERS;
389 
390     auto ri = VintfObject::GetRuntimeInfo(flags);
391     if (ri != nullptr) {
392         Json::Value root;
393         root["cpu_info"] = ri->cpuInfo();
394         root["os_name"] = ri->osName();
395         root["node_name"] = ri->nodeName();
396         root["os_release"] = ri->osRelease();
397         root["os_version"] = ri->osVersion();
398         root["hardware_id"] = ri->hardwareId();
399         root["kernel_version"] = to_string(ri->kernelVersion());
400         std::cout << root << '\n';
401     }
402 }
403