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 <stdlib.h>
18 #include <unistd.h>
19
20 #include <fstream>
21 #include <iostream>
22 #include <sstream>
23 #include <string>
24 #include <unordered_map>
25
26 #include <android-base/file.h>
27 #include <android-base/parseint.h>
28 #include <android-base/strings.h>
29
30 #include <vintf/AssembleVintf.h>
31 #include <vintf/KernelConfigParser.h>
32 #include <vintf/parse_string.h>
33 #include <vintf/parse_xml.h>
34 #include "utils.h"
35
36 #define BUFFER_SIZE sysconf(_SC_PAGESIZE)
37
38 namespace android {
39 namespace vintf {
40
41 static const std::string gConfigPrefix = "android-base-";
42 static const std::string gConfigSuffix = ".config";
43 static const std::string gBaseConfig = "android-base.config";
44
45 // An input stream with a name.
46 // The input stream may be an actual file, or a stringstream for testing.
47 // It takes ownership on the istream.
48 class NamedIstream {
49 public:
NamedIstream(const std::string & name,std::unique_ptr<std::istream> && stream)50 NamedIstream(const std::string& name, std::unique_ptr<std::istream>&& stream)
51 : mName(name), mStream(std::move(stream)) {}
name() const52 const std::string& name() const { return mName; }
stream()53 std::istream& stream() { return *mStream; }
54
55 private:
56 std::string mName;
57 std::unique_ptr<std::istream> mStream;
58 };
59
60 /**
61 * Slurps the device manifest file and add build time flag to it.
62 */
63 class AssembleVintfImpl : public AssembleVintf {
64 using Condition = std::unique_ptr<KernelConfig>;
65 using ConditionedConfig = std::pair<Condition, std::vector<KernelConfig> /* configs */>;
66
67 public:
setFakeEnv(const std::string & key,const std::string & value)68 void setFakeEnv(const std::string& key, const std::string& value) { mFakeEnv[key] = value; }
69
getEnv(const std::string & key) const70 std::string getEnv(const std::string& key) const {
71 auto it = mFakeEnv.find(key);
72 if (it != mFakeEnv.end()) {
73 return it->second;
74 }
75 const char* envValue = getenv(key.c_str());
76 return envValue != nullptr ? std::string(envValue) : std::string();
77 }
78
79 // Get environment variable and split with space.
getEnvList(const std::string & key) const80 std::vector<std::string> getEnvList(const std::string& key) const {
81 std::vector<std::string> ret;
82 for (auto&& v : base::Split(getEnv(key), " ")) {
83 v = base::Trim(v);
84 if (!v.empty()) {
85 ret.push_back(v);
86 }
87 }
88 return ret;
89 }
90
91 template <typename T>
getFlag(const std::string & key,T * value,bool log=true) const92 bool getFlag(const std::string& key, T* value, bool log = true) const {
93 std::string envValue = getEnv(key);
94 if (envValue.empty()) {
95 if (log) {
96 std::cerr << "Warning: " << key << " is missing, defaulted to " << (*value) << "."
97 << std::endl;
98 }
99 return true;
100 }
101
102 if (!parse(envValue, value)) {
103 std::cerr << "Cannot parse " << envValue << "." << std::endl;
104 return false;
105 }
106 return true;
107 }
108
109 /**
110 * Set *out to environment variable only if *out is a dummy value (i.e. default constructed).
111 * Return true if *out is set to environment variable, otherwise false.
112 */
113 template <typename T>
getFlagIfUnset(const std::string & envKey,T * out,bool log=true) const114 bool getFlagIfUnset(const std::string& envKey, T* out, bool log = true) const {
115 bool hasExistingValue = !(*out == T{});
116
117 bool hasEnvValue = false;
118 T envValue;
119 std::string envStrValue = getEnv(envKey);
120 if (!envStrValue.empty()) {
121 if (!parse(envStrValue, &envValue)) {
122 if (log) {
123 std::cerr << "Cannot parse " << envValue << "." << std::endl;
124 }
125 return false;
126 }
127 hasEnvValue = true;
128 }
129
130 if (hasExistingValue) {
131 if (hasEnvValue && log) {
132 std::cerr << "Warning: cannot override existing value " << *out << " with "
133 << envKey << " (which is " << envValue << ")." << std::endl;
134 }
135 return false;
136 }
137 if (!hasEnvValue) {
138 if (log) {
139 std::cerr << "Warning: " << envKey << " is not specified. Default to " << T{} << "."
140 << std::endl;
141 }
142 return false;
143 }
144 *out = envValue;
145 return true;
146 }
147
getBooleanFlag(const std::string & key) const148 bool getBooleanFlag(const std::string& key) const { return getEnv(key) == std::string("true"); }
149
getIntegerFlag(const std::string & key,size_t defaultValue=0) const150 size_t getIntegerFlag(const std::string& key, size_t defaultValue = 0) const {
151 std::string envValue = getEnv(key);
152 if (envValue.empty()) {
153 return defaultValue;
154 }
155 size_t value;
156 if (!base::ParseUint(envValue, &value)) {
157 std::cerr << "Error: " << key << " must be a number." << std::endl;
158 return defaultValue;
159 }
160 return value;
161 }
162
read(std::basic_istream<char> & is)163 static std::string read(std::basic_istream<char>& is) {
164 std::stringstream ss;
165 ss << is.rdbuf();
166 return ss.str();
167 }
168
isCommonConfig(const std::string & path)169 static bool isCommonConfig(const std::string& path) {
170 return ::android::base::Basename(path) == gBaseConfig;
171 }
172
173 // nullptr on any error, otherwise the condition.
generateCondition(const std::string & path)174 static Condition generateCondition(const std::string& path) {
175 std::string fname = ::android::base::Basename(path);
176 if (fname.size() <= gConfigPrefix.size() + gConfigSuffix.size() ||
177 !std::equal(gConfigPrefix.begin(), gConfigPrefix.end(), fname.begin()) ||
178 !std::equal(gConfigSuffix.rbegin(), gConfigSuffix.rend(), fname.rbegin())) {
179 return nullptr;
180 }
181
182 std::string sub = fname.substr(gConfigPrefix.size(),
183 fname.size() - gConfigPrefix.size() - gConfigSuffix.size());
184 if (sub.empty()) {
185 return nullptr; // should not happen
186 }
187 for (size_t i = 0; i < sub.size(); ++i) {
188 if (sub[i] == '-') {
189 sub[i] = '_';
190 continue;
191 }
192 if (isalnum(sub[i])) {
193 sub[i] = toupper(sub[i]);
194 continue;
195 }
196 std::cerr << "'" << fname << "' (in " << path
197 << ") is not a valid kernel config file name. Must match regex: "
198 << "android-base(-[0-9a-zA-Z-]+)?\\" << gConfigSuffix
199 << std::endl;
200 return nullptr;
201 }
202 sub.insert(0, "CONFIG_");
203 return std::make_unique<KernelConfig>(std::move(sub), Tristate::YES);
204 }
205
parseFileForKernelConfigs(std::basic_istream<char> & stream,std::vector<KernelConfig> * out)206 static bool parseFileForKernelConfigs(std::basic_istream<char>& stream,
207 std::vector<KernelConfig>* out) {
208 KernelConfigParser parser(true /* processComments */, true /* relaxedFormat */);
209 status_t err = parser.processAndFinish(read(stream));
210 if (err != OK) {
211 std::cerr << parser.error();
212 return false;
213 }
214
215 for (auto& configPair : parser.configs()) {
216 out->push_back({});
217 KernelConfig& config = out->back();
218 config.first = std::move(configPair.first);
219 if (!parseKernelConfigTypedValue(configPair.second, &config.second)) {
220 std::cerr << "Unknown value type for key = '" << config.first << "', value = '"
221 << configPair.second << "'\n";
222 return false;
223 }
224 }
225 return true;
226 }
227
parseFilesForKernelConfigs(std::vector<NamedIstream> * streams,std::vector<ConditionedConfig> * out)228 static bool parseFilesForKernelConfigs(std::vector<NamedIstream>* streams,
229 std::vector<ConditionedConfig>* out) {
230 out->clear();
231 ConditionedConfig commonConfig;
232 bool foundCommonConfig = false;
233 bool ret = true;
234
235 for (auto& namedStream : *streams) {
236 if (isCommonConfig(namedStream.name())) {
237 ret &= parseFileForKernelConfigs(namedStream.stream(), &commonConfig.second);
238 foundCommonConfig = true;
239 } else {
240 Condition condition = generateCondition(namedStream.name());
241 ret &= (condition != nullptr);
242
243 std::vector<KernelConfig> kernelConfigs;
244 if ((ret &= parseFileForKernelConfigs(namedStream.stream(), &kernelConfigs)))
245 out->emplace_back(std::move(condition), std::move(kernelConfigs));
246 }
247 }
248
249 if (!foundCommonConfig) {
250 std::cerr << "No " << gBaseConfig << " is found in these paths:" << std::endl;
251 for (auto& namedStream : *streams) {
252 std::cerr << " " << namedStream.name() << std::endl;
253 }
254 }
255 ret &= foundCommonConfig;
256 // first element is always common configs (no conditions).
257 out->insert(out->begin(), std::move(commonConfig));
258 return ret;
259 }
260
out() const261 std::basic_ostream<char>& out() const { return mOutRef == nullptr ? std::cout : *mOutRef; }
262
263 // If -c is provided, check it.
checkDualFile(const HalManifest & manifest,const CompatibilityMatrix & matrix)264 bool checkDualFile(const HalManifest& manifest, const CompatibilityMatrix& matrix) {
265 if (getBooleanFlag("PRODUCT_ENFORCE_VINTF_MANIFEST")) {
266 std::string error;
267 if (!manifest.checkCompatibility(matrix, &error)) {
268 std::cerr << "Not compatible: " << error << std::endl;
269 return false;
270 }
271 }
272
273 // Check HALs in device manifest that are not in framework matrix.
274 if (getBooleanFlag("VINTF_ENFORCE_NO_UNUSED_HALS")) {
275 auto unused = manifest.checkUnusedHals(matrix);
276 if (!unused.empty()) {
277 std::cerr << "Error: The following instances are in the device manifest but "
278 << "not specified in framework compatibility matrix: " << std::endl
279 << " " << android::base::Join(unused, "\n ") << std::endl
280 << "Suggested fix:" << std::endl
281 << "1. Check for any typos in device manifest or framework compatibility "
282 << "matrices with FCM version >= " << matrix.level() << "." << std::endl
283 << "2. Add them to any framework compatibility matrix with FCM "
284 << "version >= " << matrix.level() << " where applicable." << std::endl
285 << "3. Add them to DEVICE_FRAMEWORK_COMPATIBILITY_MATRIX_FILE "
286 << "or DEVICE_PRODUCT_COMPATIBILITY_MATRIX_FILE." << std::endl;
287
288 return false;
289 }
290 }
291 return true;
292 }
293
294 template <typename S>
295 using Schemas = std::vector<Named<S>>;
296 using HalManifests = Schemas<HalManifest>;
297 using CompatibilityMatrices = Schemas<CompatibilityMatrix>;
298
299 template <typename M>
outputInputs(const Schemas<M> & inputs)300 void outputInputs(const Schemas<M>& inputs) {
301 out() << "<!--" << std::endl;
302 out() << " Input:" << std::endl;
303 for (const auto& e : inputs) {
304 if (!e.name.empty()) {
305 out() << " " << base::Basename(e.name) << std::endl;
306 }
307 }
308 out() << "-->" << std::endl;
309 }
310
311 // Parse --kernel arguments and write to output manifest.
setDeviceManifestKernel(HalManifest * manifest)312 bool setDeviceManifestKernel(HalManifest* manifest) {
313 if (mKernels.empty()) {
314 return true;
315 }
316 if (mKernels.size() > 1) {
317 std::cerr << "Warning: multiple --kernel is specified when building device manifest. "
318 << "Only the first one will be used." << std::endl;
319 }
320 auto& kernelArg = *mKernels.begin();
321 const auto& kernelVer = kernelArg.first;
322 auto& kernelConfigFiles = kernelArg.second;
323 // addKernel() guarantees that !kernelConfigFiles.empty().
324 if (kernelConfigFiles.size() > 1) {
325 std::cerr << "Warning: multiple config files are specified in --kernel when building "
326 << "device manfiest. Only the first one will be used." << std::endl;
327 }
328
329 KernelConfigParser parser(true /* processComments */, false /* relaxedFormat */);
330 status_t err = parser.processAndFinish(read(kernelConfigFiles[0].stream()));
331 if (err != OK) {
332 std::cerr << parser.error();
333 return false;
334 }
335 manifest->device.mKernel = std::make_optional<KernelInfo>();
336 manifest->device.mKernel->mVersion = kernelVer;
337 manifest->device.mKernel->mConfigs = parser.configs();
338 return true;
339 }
340
assembleHalManifest(HalManifests * halManifests)341 bool assembleHalManifest(HalManifests* halManifests) {
342 std::string error;
343 HalManifest* halManifest = &halManifests->front().object;
344 for (auto it = halManifests->begin() + 1; it != halManifests->end(); ++it) {
345 const std::string& path = it->name;
346 HalManifest& manifestToAdd = it->object;
347
348 if (manifestToAdd.level() != Level::UNSPECIFIED) {
349 if (halManifest->level() == Level::UNSPECIFIED) {
350 halManifest->mLevel = manifestToAdd.level();
351 } else if (halManifest->level() != manifestToAdd.level()) {
352 std::cerr << "Inconsistent FCM Version in HAL manifests:" << std::endl
353 << " File '" << halManifests->front().name << "' has level "
354 << halManifest->level() << std::endl
355 << " File '" << path << "' has level " << manifestToAdd.level()
356 << std::endl;
357 return false;
358 }
359 }
360
361 if (!halManifest->addAll(&manifestToAdd, &error)) {
362 std::cerr << "File \"" << path << "\" cannot be added: " << error << std::endl;
363 return false;
364 }
365 }
366
367 if (halManifest->mType == SchemaType::DEVICE) {
368 (void)getFlagIfUnset("BOARD_SEPOLICY_VERS", &halManifest->device.mSepolicyVersion);
369
370 if (!setDeviceFcmVersion(halManifest)) {
371 return false;
372 }
373
374 if (!setDeviceManifestKernel(halManifest)) {
375 return false;
376 }
377 }
378
379 if (halManifest->mType == SchemaType::FRAMEWORK) {
380 for (auto&& v : getEnvList("PROVIDED_VNDK_VERSIONS")) {
381 halManifest->framework.mVendorNdks.emplace_back(std::move(v));
382 }
383
384 for (auto&& v : getEnvList("PLATFORM_SYSTEMSDK_VERSIONS")) {
385 halManifest->framework.mSystemSdk.mVersions.emplace(std::move(v));
386 }
387 }
388
389 outputInputs(*halManifests);
390
391 if (mOutputMatrix) {
392 CompatibilityMatrix generatedMatrix = halManifest->generateCompatibleMatrix();
393 if (!halManifest->checkCompatibility(generatedMatrix, &error)) {
394 std::cerr << "FATAL ERROR: cannot generate a compatible matrix: " << error
395 << std::endl;
396 }
397 out() << "<!-- \n"
398 " Autogenerated skeleton compatibility matrix. \n"
399 " Use with caution. Modify it to suit your needs.\n"
400 " All HALs are set to optional.\n"
401 " Many entries other than HALs are zero-filled and\n"
402 " require human attention. \n"
403 "-->\n"
404 << gCompatibilityMatrixConverter(generatedMatrix, mSerializeFlags);
405 } else {
406 out() << gHalManifestConverter(*halManifest, mSerializeFlags);
407 }
408 out().flush();
409
410 if (mCheckFile != nullptr) {
411 CompatibilityMatrix checkMatrix;
412 if (!gCompatibilityMatrixConverter(&checkMatrix, read(*mCheckFile), &error)) {
413 std::cerr << "Cannot parse check file as a compatibility matrix: " << error
414 << std::endl;
415 return false;
416 }
417 if (!checkDualFile(*halManifest, checkMatrix)) {
418 return false;
419 }
420 }
421
422 return true;
423 }
424
425 // Parse --kernel arguments and write to output matrix.
assembleFrameworkCompatibilityMatrixKernels(CompatibilityMatrix * matrix)426 bool assembleFrameworkCompatibilityMatrixKernels(CompatibilityMatrix* matrix) {
427 for (auto& pair : mKernels) {
428 std::vector<ConditionedConfig> conditionedConfigs;
429 if (!parseFilesForKernelConfigs(&pair.second, &conditionedConfigs)) {
430 return false;
431 }
432 for (ConditionedConfig& conditionedConfig : conditionedConfigs) {
433 MatrixKernel kernel(KernelVersion{pair.first}, std::move(conditionedConfig.second));
434 if (conditionedConfig.first != nullptr)
435 kernel.mConditions.push_back(std::move(*conditionedConfig.first));
436 std::string error;
437 if (!matrix->addKernel(std::move(kernel), &error)) {
438 std::cerr << "Error:" << error << std::endl;
439 return false;
440 };
441 }
442 }
443 return true;
444 }
445
setDeviceFcmVersion(HalManifest * manifest)446 bool setDeviceFcmVersion(HalManifest* manifest) {
447 // Not needed for generating empty manifest for DEVICE_FRAMEWORK_COMPATIBILITY_MATRIX_FILE.
448 if (getBooleanFlag("VINTF_IGNORE_TARGET_FCM_VERSION")) {
449 return true;
450 }
451
452 size_t shippingApiLevel = getIntegerFlag("PRODUCT_SHIPPING_API_LEVEL");
453
454 if (manifest->level() != Level::UNSPECIFIED) {
455 return true;
456 }
457 if (!getBooleanFlag("PRODUCT_ENFORCE_VINTF_MANIFEST")) {
458 manifest->mLevel = Level::LEGACY;
459 return true;
460 }
461 // TODO(b/70628538): Do not infer from Shipping API level.
462 if (shippingApiLevel) {
463 std::cerr << "Warning: Shipping FCM Version is inferred from Shipping API level. "
464 << "Declare Shipping FCM Version in device manifest directly." << std::endl;
465 manifest->mLevel = details::convertFromApiLevel(shippingApiLevel);
466 if (manifest->mLevel == Level::UNSPECIFIED) {
467 std::cerr << "Error: Shipping FCM Version cannot be inferred from Shipping API "
468 << "level " << shippingApiLevel << "."
469 << "Declare Shipping FCM Version in device manifest directly."
470 << std::endl;
471 return false;
472 }
473 return true;
474 }
475 // TODO(b/69638851): should be an error if Shipping API level is not defined.
476 // For now, just leave it empty; when framework compatibility matrix is built,
477 // lowest FCM Version is assumed.
478 std::cerr << "Warning: Shipping FCM Version cannot be inferred, because:" << std::endl
479 << " (1) It is not explicitly declared in device manifest;" << std::endl
480 << " (2) PRODUCT_ENFORCE_VINTF_MANIFEST is set to true;" << std::endl
481 << " (3) PRODUCT_SHIPPING_API_LEVEL is undefined." << std::endl
482 << "Assuming 'unspecified' Shipping FCM Version. " << std::endl
483 << "To remove this warning, define 'level' attribute in device manifest."
484 << std::endl;
485 return true;
486 }
487
getLowestFcmVersion(const CompatibilityMatrices & matrices)488 Level getLowestFcmVersion(const CompatibilityMatrices& matrices) {
489 Level ret = Level::UNSPECIFIED;
490 for (const auto& e : matrices) {
491 if (ret == Level::UNSPECIFIED || ret > e.object.level()) {
492 ret = e.object.level();
493 }
494 }
495 return ret;
496 }
497
assembleCompatibilityMatrix(CompatibilityMatrices * matrices)498 bool assembleCompatibilityMatrix(CompatibilityMatrices* matrices) {
499 std::string error;
500 CompatibilityMatrix* matrix = nullptr;
501 std::unique_ptr<HalManifest> checkManifest;
502 std::unique_ptr<CompatibilityMatrix> builtMatrix;
503
504 if (mCheckFile != nullptr) {
505 checkManifest = std::make_unique<HalManifest>();
506 if (!gHalManifestConverter(checkManifest.get(), read(*mCheckFile), &error)) {
507 std::cerr << "Cannot parse check file as a HAL manifest: " << error << std::endl;
508 return false;
509 }
510 }
511
512 if (matrices->front().object.mType == SchemaType::DEVICE) {
513 builtMatrix = CompatibilityMatrix::combineDeviceMatrices(matrices, &error);
514 matrix = builtMatrix.get();
515
516 if (matrix == nullptr) {
517 std::cerr << error << std::endl;
518 return false;
519 }
520
521 auto vndkVersion = base::Trim(getEnv("REQUIRED_VNDK_VERSION"));
522 if (!vndkVersion.empty()) {
523 auto& valueInMatrix = matrix->device.mVendorNdk;
524 if (!valueInMatrix.version().empty() && valueInMatrix.version() != vndkVersion) {
525 std::cerr << "Hard-coded <vendor-ndk> version in device compatibility matrix ("
526 << matrices->front().name << "), '" << valueInMatrix.version()
527 << "', does not match value inferred "
528 << "from BOARD_VNDK_VERSION '" << vndkVersion << "'" << std::endl;
529 return false;
530 }
531 valueInMatrix = VendorNdk{std::move(vndkVersion)};
532 }
533
534 for (auto&& v : getEnvList("BOARD_SYSTEMSDK_VERSIONS")) {
535 matrix->device.mSystemSdk.mVersions.emplace(std::move(v));
536 }
537 }
538
539 if (matrices->front().object.mType == SchemaType::FRAMEWORK) {
540 Level deviceLevel =
541 checkManifest != nullptr ? checkManifest->level() : Level::UNSPECIFIED;
542 if (deviceLevel == Level::UNSPECIFIED) {
543 deviceLevel = getLowestFcmVersion(*matrices);
544 if (checkManifest != nullptr && deviceLevel != Level::UNSPECIFIED) {
545 std::cerr << "Warning: No Target FCM Version for device. Assuming \""
546 << to_string(deviceLevel)
547 << "\" when building final framework compatibility matrix."
548 << std::endl;
549 }
550 }
551 builtMatrix = CompatibilityMatrix::combine(deviceLevel, matrices, &error);
552 matrix = builtMatrix.get();
553
554 if (matrix == nullptr) {
555 std::cerr << error << std::endl;
556 return false;
557 }
558
559 if (!assembleFrameworkCompatibilityMatrixKernels(matrix)) {
560 return false;
561 }
562
563 // Add PLATFORM_SEPOLICY_* to sepolicy.sepolicy-version. Remove dupes.
564 std::set<Version> sepolicyVersions;
565 auto sepolicyVersionStrings = getEnvList("PLATFORM_SEPOLICY_COMPAT_VERSIONS");
566 auto currentSepolicyVersionString = getEnv("PLATFORM_SEPOLICY_VERSION");
567 if (!currentSepolicyVersionString.empty()) {
568 sepolicyVersionStrings.push_back(currentSepolicyVersionString);
569 }
570 for (auto&& s : sepolicyVersionStrings) {
571 Version v;
572 if (!parse(s, &v)) {
573 std::cerr << "Error: unknown sepolicy version '" << s << "' specified by "
574 << (s == currentSepolicyVersionString
575 ? "PLATFORM_SEPOLICY_VERSION"
576 : "PLATFORM_SEPOLICY_COMPAT_VERSIONS")
577 << ".";
578 return false;
579 }
580 sepolicyVersions.insert(v);
581 }
582 for (auto&& v : sepolicyVersions) {
583 matrix->framework.mSepolicy.mSepolicyVersionRanges.emplace_back(v.majorVer,
584 v.minorVer);
585 }
586
587 getFlagIfUnset("POLICYVERS", &matrix->framework.mSepolicy.mKernelSepolicyVersion,
588 false /* log */);
589 getFlagIfUnset("FRAMEWORK_VBMETA_VERSION", &matrix->framework.mAvbMetaVersion,
590 false /* log */);
591 // Hard-override existing AVB version
592 getFlag("FRAMEWORK_VBMETA_VERSION_OVERRIDE", &matrix->framework.mAvbMetaVersion,
593 false /* log */);
594 }
595 outputInputs(*matrices);
596 out() << gCompatibilityMatrixConverter(*matrix, mSerializeFlags);
597 out().flush();
598
599 if (checkManifest != nullptr && !checkDualFile(*checkManifest, *matrix)) {
600 return false;
601 }
602
603 return true;
604 }
605
606 enum AssembleStatus { SUCCESS, FAIL_AND_EXIT, TRY_NEXT };
607 template <typename Schema, typename AssembleFunc>
tryAssemble(const XmlConverter<Schema> & converter,const std::string & schemaName,AssembleFunc assemble,std::string * error)608 AssembleStatus tryAssemble(const XmlConverter<Schema>& converter, const std::string& schemaName,
609 AssembleFunc assemble, std::string* error) {
610 Schemas<Schema> schemas;
611 Schema schema;
612 if (!converter(&schema, read(mInFiles.front().stream()), error)) {
613 return TRY_NEXT;
614 }
615 auto firstType = schema.type();
616 schemas.emplace_back(mInFiles.front().name(), std::move(schema));
617
618 for (auto it = mInFiles.begin() + 1; it != mInFiles.end(); ++it) {
619 Schema additionalSchema;
620 const std::string& fileName = it->name();
621 if (!converter(&additionalSchema, read(it->stream()), error)) {
622 std::cerr << "File \"" << fileName << "\" is not a valid " << firstType << " "
623 << schemaName << " (but the first file is a valid " << firstType << " "
624 << schemaName << "). Error: " << *error << std::endl;
625 return FAIL_AND_EXIT;
626 }
627 if (additionalSchema.type() != firstType) {
628 std::cerr << "File \"" << fileName << "\" is a " << additionalSchema.type() << " "
629 << schemaName << " (but a " << firstType << " " << schemaName
630 << " is expected)." << std::endl;
631 return FAIL_AND_EXIT;
632 }
633
634 schemas.emplace_back(fileName, std::move(additionalSchema));
635 }
636 return assemble(&schemas) ? SUCCESS : FAIL_AND_EXIT;
637 }
638
assemble()639 bool assemble() override {
640 using std::placeholders::_1;
641 if (mInFiles.empty()) {
642 std::cerr << "Missing input file." << std::endl;
643 return false;
644 }
645
646 std::string manifestError;
647 auto status = tryAssemble(gHalManifestConverter, "manifest",
648 std::bind(&AssembleVintfImpl::assembleHalManifest, this, _1),
649 &manifestError);
650 if (status == SUCCESS) return true;
651 if (status == FAIL_AND_EXIT) return false;
652
653 resetInFiles();
654
655 std::string matrixError;
656 status = tryAssemble(gCompatibilityMatrixConverter, "compatibility matrix",
657 std::bind(&AssembleVintfImpl::assembleCompatibilityMatrix, this, _1),
658 &matrixError);
659 if (status == SUCCESS) return true;
660 if (status == FAIL_AND_EXIT) return false;
661
662 std::cerr << "Input file has unknown format." << std::endl
663 << "Error when attempting to convert to manifest: " << manifestError << std::endl
664 << "Error when attempting to convert to compatibility matrix: " << matrixError
665 << std::endl;
666 return false;
667 }
668
setOutputStream(Ostream && out)669 std::ostream& setOutputStream(Ostream&& out) override {
670 mOutRef = std::move(out);
671 return *mOutRef;
672 }
673
addInputStream(const std::string & name,Istream && in)674 std::istream& addInputStream(const std::string& name, Istream&& in) override {
675 auto it = mInFiles.emplace(mInFiles.end(), name, std::move(in));
676 return it->stream();
677 }
678
setCheckInputStream(Istream && in)679 std::istream& setCheckInputStream(Istream&& in) override {
680 mCheckFile = std::move(in);
681 return *mCheckFile;
682 }
683
hasKernelVersion(const KernelVersion & kernelVer) const684 bool hasKernelVersion(const KernelVersion& kernelVer) const override {
685 return mKernels.find(kernelVer) != mKernels.end();
686 }
687
addKernelConfigInputStream(const KernelVersion & kernelVer,const std::string & name,Istream && in)688 std::istream& addKernelConfigInputStream(const KernelVersion& kernelVer,
689 const std::string& name, Istream&& in) override {
690 auto&& kernel = mKernels[kernelVer];
691 auto it = kernel.emplace(kernel.end(), name, std::move(in));
692 return it->stream();
693 }
694
resetInFiles()695 void resetInFiles() {
696 for (auto& inFile : mInFiles) {
697 inFile.stream().clear();
698 inFile.stream().seekg(0);
699 }
700 }
701
setOutputMatrix()702 void setOutputMatrix() override { mOutputMatrix = true; }
703
setHalsOnly()704 bool setHalsOnly() override {
705 if (mHasSetHalsOnlyFlag) {
706 std::cerr << "Error: Cannot set --hals-only with --no-hals." << std::endl;
707 return false;
708 }
709 // Just override it with HALS_ONLY because other flags that modify mSerializeFlags
710 // does not interfere with this (except --no-hals).
711 mSerializeFlags = SerializeFlags::HALS_ONLY;
712 mHasSetHalsOnlyFlag = true;
713 return true;
714 }
715
setNoHals()716 bool setNoHals() override {
717 if (mHasSetHalsOnlyFlag) {
718 std::cerr << "Error: Cannot set --hals-only with --no-hals." << std::endl;
719 return false;
720 }
721 mSerializeFlags = mSerializeFlags.disableHals();
722 mHasSetHalsOnlyFlag = true;
723 return true;
724 }
725
setNoKernelRequirements()726 bool setNoKernelRequirements() override {
727 mSerializeFlags = mSerializeFlags.disableKernelConfigs().disableKernelMinorRevision();
728 return true;
729 }
730
731 private:
732 std::vector<NamedIstream> mInFiles;
733 Ostream mOutRef;
734 Istream mCheckFile;
735 bool mOutputMatrix = false;
736 bool mHasSetHalsOnlyFlag = false;
737 SerializeFlags::Type mSerializeFlags = SerializeFlags::EVERYTHING;
738 std::map<KernelVersion, std::vector<NamedIstream>> mKernels;
739 std::map<std::string, std::string> mFakeEnv;
740 };
741
openOutFile(const std::string & path)742 bool AssembleVintf::openOutFile(const std::string& path) {
743 return static_cast<std::ofstream&>(setOutputStream(std::make_unique<std::ofstream>(path)))
744 .is_open();
745 }
746
openInFile(const std::string & path)747 bool AssembleVintf::openInFile(const std::string& path) {
748 return static_cast<std::ifstream&>(addInputStream(path, std::make_unique<std::ifstream>(path)))
749 .is_open();
750 }
751
openCheckFile(const std::string & path)752 bool AssembleVintf::openCheckFile(const std::string& path) {
753 return static_cast<std::ifstream&>(setCheckInputStream(std::make_unique<std::ifstream>(path)))
754 .is_open();
755 }
756
addKernel(const std::string & kernelArg)757 bool AssembleVintf::addKernel(const std::string& kernelArg) {
758 auto tokens = base::Split(kernelArg, ":");
759 if (tokens.size() <= 1) {
760 std::cerr << "Unrecognized --kernel option '" << kernelArg << "'" << std::endl;
761 return false;
762 }
763 KernelVersion kernelVer;
764 if (!parse(tokens.front(), &kernelVer)) {
765 std::cerr << "Unrecognized kernel version '" << tokens.front() << "'" << std::endl;
766 return false;
767 }
768 if (hasKernelVersion(kernelVer)) {
769 std::cerr << "Multiple --kernel for " << kernelVer << " is specified." << std::endl;
770 return false;
771 }
772 for (auto it = tokens.begin() + 1; it != tokens.end(); ++it) {
773 bool opened =
774 static_cast<std::ifstream&>(
775 addKernelConfigInputStream(kernelVer, *it, std::make_unique<std::ifstream>(*it)))
776 .is_open();
777 if (!opened) {
778 std::cerr << "Cannot open file '" << *it << "'." << std::endl;
779 return false;
780 }
781 }
782 return true;
783 }
784
newInstance()785 std::unique_ptr<AssembleVintf> AssembleVintf::newInstance() {
786 return std::make_unique<AssembleVintfImpl>();
787 }
788
789 } // namespace vintf
790 } // namespace android
791