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 kColumnSeperator = "   ";
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     // If the HAL version is in device / framework compatibility matrix, whether it is required
209     // or not.
210     bool required = false;
211 
212     // Return true if:
213     // - not a required HAL version; OR
214     // - required in device matrix and framework manifest;
215     // - required in framework matrix and device manifest.
meetsReqeuirementTableRow216     bool meetsReqeuirement() const {
217         if (!required) return true;
218         if (dcm && !fm) return false;
219         if (fcm && !dm) return false;
220         return true;
221     }
222 };
223 
operator <<(std::ostream & out,const TableRow & row)224 std::ostream& operator<<(std::ostream& out, const TableRow& row) {
225     return out << (row.required ? "R" : " ") << (row.meetsReqeuirement() ? " " : "!")
226                << kColumnSeperator << (row.dm ? "DM" : "  ") << kColumnSeperator
227                << (row.fm ? "FM" : "  ") << kColumnSeperator << (row.fcm ? "FCM" : "   ")
228                << kColumnSeperator << (row.dcm ? "DCM" : "   ");
229 }
230 
231 using RowMutator = std::function<void(TableRow*)>;
232 using Table = std::map<std::string, TableRow>;
233 
234 // Insert each fqInstanceName foo@x.y::IFoo/instance to the table by inserting the key
235 // if it does not exist and setting the corresponding indicator (as specified by "mutate").
insert(const HalManifest * manifest,Table * table,const RowMutator & mutate)236 void insert(const HalManifest* manifest, Table* table, const RowMutator& mutate) {
237     if (manifest == nullptr) return;
238     manifest->forEachInstance([&](const auto& manifestInstance) {
239         std::string key = manifestInstance.description();
240         mutate(&(*table)[key]);
241         return true;
242     });
243 }
244 
insert(const CompatibilityMatrix * matrix,Table * table,const RowMutator & mutate)245 void insert(const CompatibilityMatrix* matrix, Table* table, const RowMutator& mutate) {
246     if (matrix == nullptr) return;
247     matrix->forEachInstance([&](const auto& matrixInstance) {
248         for (auto minorVer = matrixInstance.versionRange().minMinor;
249              minorVer >= matrixInstance.versionRange().minMinor &&
250              minorVer <= matrixInstance.versionRange().maxMinor;
251              ++minorVer) {
252             Version version{matrixInstance.versionRange().majorVer, minorVer};
253             std::string key = matrixInstance.description(version);
254             auto it = table->find(key);
255             if (it == table->end()) {
256                 mutate(&(*table)[key]);
257             } else {
258                 mutate(&it->second);
259                 if (minorVer == matrixInstance.versionRange().minMinor) {
260                     it->second.required = !matrixInstance.optional();
261                 }
262             }
263         }
264         return true;
265     });
266 }
267 
generateHalSummary(const HalManifest * vm,const HalManifest * fm,const CompatibilityMatrix * vcm,const CompatibilityMatrix * fcm)268 Table generateHalSummary(const HalManifest* vm, const HalManifest* fm,
269                          const CompatibilityMatrix* vcm, const CompatibilityMatrix* fcm) {
270     Table table;
271     insert(vm, &table, [](auto* row) { row->dm = true; });
272     insert(fm, &table, [](auto* row) { row->fm = true; });
273     insert(vcm, &table, [](auto* row) { row->dcm = true; });
274     insert(fcm, &table, [](auto* row) { row->fcm = true; });
275 
276     return table;
277 }
278 
279 static const std::vector<Option> gAvailableOptions{
__anon07d375560702() 280     {'h', "help", "Print help message.", [](auto) { return USAGE; }},
__anon07d375560802() 281     {'v', "verbose", "Dump detailed and raw content, including kernel configurations", [](auto o) {
282          o->verbose = true;
283          return OK;
284      }}};
285 // A convenience binary to dump information available through libvintf.
main(int argc,char ** argv)286 int main(int argc, char** argv) {
287     ParsedOptions options;
288     Status status = parseOptions(argc, argv, gAvailableOptions, &options);
289     if (status == USAGE) usage(argv[0], gAvailableOptions);
290     if (status != OK) return status;
291 
292     options.fn(options);
293 }
294 
dumpLegacy(const ParsedOptions & options)295 void dumpLegacy(const ParsedOptions& options) {
296     auto vm = VintfObject::GetDeviceHalManifest();
297     auto fm = VintfObject::GetFrameworkHalManifest();
298     auto vcm = VintfObject::GetDeviceCompatibilityMatrix();
299     auto fcm = VintfObject::GetFrameworkCompatibilityMatrix();
300     auto ki = VintfObject::GetRuntimeInfo();
301 
302     if (!options.verbose) {
303         std::cout << "======== HALs =========" << std::endl
304                   << "R: required. (empty): optional or missing from matrices. "
305                   << "!: required and not in manifest." << std::endl
306                   << "DM: device manifest. FM: framework manifest." << std::endl
307                   << "FCM: framework compatibility matrix. DCM: device compatibility matrix."
308                   << std::endl
309                   << std::endl;
310         auto table = generateHalSummary(vm.get(), fm.get(), vcm.get(), fcm.get());
311 
312         for (const auto& pair : table)
313             std::cout << pair.second << kColumnSeperator << pair.first << std::endl;
314 
315         std::cout << std::endl;
316     }
317 
318     SerializeFlags::Type flags = SerializeFlags::EVERYTHING;
319     if (!options.verbose) {
320         flags = flags.disableHals().disableKernel();
321     }
322     std::cout << "======== Device HAL Manifest =========" << std::endl;
323     if (vm != nullptr) std::cout << toXml(*vm, flags);
324     std::cout << "======== Framework HAL Manifest =========" << std::endl;
325     if (fm != nullptr) std::cout << toXml(*fm, flags);
326     std::cout << "======== Device Compatibility Matrix =========" << std::endl;
327     if (vcm != nullptr) std::cout << toXml(*vcm, flags);
328     std::cout << "======== Framework Compatibility Matrix =========" << std::endl;
329     if (fcm != nullptr) std::cout << toXml(*fcm, flags);
330 
331     std::cout << "======== Runtime Info =========" << std::endl;
332     if (ki != nullptr) std::cout << dump(*ki, options.verbose);
333 
334     std::cout << std::endl;
335 
336     std::cout << "======== Summary =========" << std::endl;
337     std::cout << "Device Manifest?    " << existString(vm != nullptr) << std::endl
338               << "Device Matrix?      " << existString(vcm != nullptr) << std::endl
339               << "Framework Manifest? " << existString(fm != nullptr) << std::endl
340               << "Framework Matrix?   " << existString(fcm != nullptr) << std::endl;
341     std::string error;
342     if (vm && fcm) {
343         bool compatible = vm->checkCompatibility(*fcm, &error);
344         std::cout << "Device HAL Manifest <==> Framework Compatibility Matrix? "
345                   << boolCompatString(compatible);
346         if (!compatible)
347             std::cout << ", " << error;
348         std::cout << std::endl;
349     }
350     if (fm && vcm) {
351         bool compatible = fm->checkCompatibility(*vcm, &error);
352         std::cout << "Framework HAL Manifest <==> Device Compatibility Matrix? "
353                   << boolCompatString(compatible);
354         if (!compatible)
355             std::cout << ", " << error;
356         std::cout << std::endl;
357     }
358     if (ki && fcm) {
359         bool compatible = ki->checkCompatibility(*fcm, &error);
360         std::cout << "Runtime info <==> Framework Compatibility Matrix?        "
361                   << boolCompatString(compatible);
362         if (!compatible) std::cout << ", " << error;
363         std::cout << std::endl;
364     }
365 
366     {
367         auto compatible = VintfObject::GetInstance()->checkCompatibility(&error);
368         std::cout << "VintfObject::checkCompatibility?                         "
369                   << compatibleString(compatible);
370         if (compatible != COMPATIBLE) std::cout << ", " << error;
371         std::cout << std::endl;
372     }
373 
374     if (vm && fcm) {
375         // TODO(b/131717099): Use correct information from libhidlmetadata
376         auto deprecate = VintfObject::GetInstance()->checkDeprecation({}, &error);
377         std::cout << "VintfObject::CheckDeprecation (against device manifest) (w/o hidlmetadata)? "
378                   << deprecateString(deprecate);
379         if (deprecate != NO_DEPRECATED_HALS) std::cout << ", " << error;
380         std::cout << std::endl;
381     }
382 }
383 
dumpDm(const ParsedOptions &)384 void dumpDm(const ParsedOptions&) {
385     auto dm = VintfObject::GetDeviceHalManifest();
386     if (dm != nullptr) std::cout << toXml(*dm);
387 }
388 
dumpFm(const ParsedOptions &)389 void dumpFm(const ParsedOptions&) {
390     auto fm = VintfObject::GetFrameworkHalManifest();
391     if (fm != nullptr) std::cout << toXml(*fm);
392 }
393 
dumpDcm(const ParsedOptions &)394 void dumpDcm(const ParsedOptions&) {
395     auto dcm = VintfObject::GetDeviceCompatibilityMatrix();
396     if (dcm != nullptr) std::cout << toXml(*dcm);
397 }
398 
dumpFcm(const ParsedOptions &)399 void dumpFcm(const ParsedOptions&) {
400     auto fcm = VintfObject::GetFrameworkCompatibilityMatrix();
401     if (fcm != nullptr) std::cout << toXml(*fcm);
402 }
403 
404 // Keep field names in sync with VintfDeviceInfo's usage
dumpRi(const ParsedOptions &)405 void dumpRi(const ParsedOptions&) {
406     const RuntimeInfo::FetchFlags flags = RuntimeInfo::FetchFlag::CPU_INFO |
407                                           RuntimeInfo::FetchFlag::CPU_VERSION |
408                                           RuntimeInfo::FetchFlag::POLICYVERS;
409 
410     auto ri = VintfObject::GetRuntimeInfo(flags);
411     if (ri != nullptr) {
412         Json::Value root;
413         root["cpu_info"] = ri->cpuInfo();
414         root["os_name"] = ri->osName();
415         root["node_name"] = ri->nodeName();
416         root["os_release"] = ri->osRelease();
417         root["os_version"] = ri->osVersion();
418         root["hardware_id"] = ri->hardwareId();
419         root["kernel_version"] = to_string(ri->kernelVersion());
420         std::cout << root << '\n';
421     }
422 }
423