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 "VintfObject.h"
18 
19 #include <dirent.h>
20 
21 #include <algorithm>
22 #include <functional>
23 #include <memory>
24 #include <mutex>
25 
26 #include <android-base/logging.h>
27 #include <android-base/result.h>
28 #include <android-base/strings.h>
29 #include <hidl/metadata.h>
30 
31 #include "CompatibilityMatrix.h"
32 #include "parse_string.h"
33 #include "parse_xml.h"
34 #include "utils.h"
35 
36 using std::placeholders::_1;
37 using std::placeholders::_2;
38 
39 namespace android {
40 namespace vintf {
41 
42 using namespace details;
43 
44 #ifdef LIBVINTF_TARGET
45 static constexpr bool kIsTarget = true;
46 #else
47 static constexpr bool kIsTarget = false;
48 #endif
49 
50 template <typename T, typename F>
Get(const char * id,LockedSharedPtr<T> * ptr,const F & fetchAllInformation)51 static std::shared_ptr<const T> Get(const char* id, LockedSharedPtr<T>* ptr,
52                                     const F& fetchAllInformation) {
53     std::unique_lock<std::mutex> _lock(ptr->mutex);
54     if (!ptr->fetchedOnce) {
55         LOG(INFO) << id << ": Reading VINTF information.";
56         ptr->object = std::make_unique<T>();
57         std::string error;
58         status_t status = fetchAllInformation(ptr->object.get(), &error);
59         if (status == OK) {
60             ptr->fetchedOnce = true;
61             LOG(INFO) << id << ": Successfully processed VINTF information";
62         } else {
63             // Doubled because a malformed error std::string might cause us to
64             // lose the status.
65             LOG(ERROR) << id << ": status from fetching VINTF information: " << status;
66             LOG(ERROR) << id << ": " << status << " VINTF parse error: " << error;
67             ptr->object = nullptr; // frees the old object
68         }
69     }
70     return ptr->object;
71 }
72 
createDefaultFileSystem()73 static std::unique_ptr<FileSystem> createDefaultFileSystem() {
74     std::unique_ptr<FileSystem> fileSystem;
75     if (kIsTarget) {
76         fileSystem = std::make_unique<details::FileSystemImpl>();
77     } else {
78         fileSystem = std::make_unique<details::FileSystemNoOp>();
79     }
80     return fileSystem;
81 }
82 
createDefaultPropertyFetcher()83 static std::unique_ptr<PropertyFetcher> createDefaultPropertyFetcher() {
84     std::unique_ptr<PropertyFetcher> propertyFetcher;
85     if (kIsTarget) {
86         propertyFetcher = std::make_unique<details::PropertyFetcherImpl>();
87     } else {
88         propertyFetcher = std::make_unique<details::PropertyFetcherNoOp>();
89     }
90     return propertyFetcher;
91 }
92 
GetInstance()93 std::shared_ptr<VintfObject> VintfObject::GetInstance() {
94     static details::LockedSharedPtr<VintfObject> sInstance{};
95     std::unique_lock<std::mutex> lock(sInstance.mutex);
96     if (sInstance.object == nullptr) {
97         sInstance.object = std::shared_ptr<VintfObject>(VintfObject::Builder().build().release());
98     }
99     return sInstance.object;
100 }
101 
GetDeviceHalManifest()102 std::shared_ptr<const HalManifest> VintfObject::GetDeviceHalManifest() {
103     return GetInstance()->getDeviceHalManifest();
104 }
105 
getDeviceHalManifest()106 std::shared_ptr<const HalManifest> VintfObject::getDeviceHalManifest() {
107     return Get(__func__, &mDeviceManifest,
108                std::bind(&VintfObject::fetchDeviceHalManifest, this, _1, _2));
109 }
110 
GetFrameworkHalManifest()111 std::shared_ptr<const HalManifest> VintfObject::GetFrameworkHalManifest() {
112     return GetInstance()->getFrameworkHalManifest();
113 }
114 
getFrameworkHalManifest()115 std::shared_ptr<const HalManifest> VintfObject::getFrameworkHalManifest() {
116     return Get(__func__, &mFrameworkManifest,
117                std::bind(&VintfObject::fetchFrameworkHalManifest, this, _1, _2));
118 }
119 
GetDeviceCompatibilityMatrix()120 std::shared_ptr<const CompatibilityMatrix> VintfObject::GetDeviceCompatibilityMatrix() {
121     return GetInstance()->getDeviceCompatibilityMatrix();
122 }
123 
getDeviceCompatibilityMatrix()124 std::shared_ptr<const CompatibilityMatrix> VintfObject::getDeviceCompatibilityMatrix() {
125     return Get(__func__, &mDeviceMatrix, std::bind(&VintfObject::fetchDeviceMatrix, this, _1, _2));
126 }
127 
GetFrameworkCompatibilityMatrix()128 std::shared_ptr<const CompatibilityMatrix> VintfObject::GetFrameworkCompatibilityMatrix() {
129     return GetInstance()->getFrameworkCompatibilityMatrix();
130 }
131 
getFrameworkCompatibilityMatrix()132 std::shared_ptr<const CompatibilityMatrix> VintfObject::getFrameworkCompatibilityMatrix() {
133     // To avoid deadlock, get device manifest before any locks.
134     auto deviceManifest = getDeviceHalManifest();
135 
136     std::unique_lock<std::mutex> _lock(mFrameworkCompatibilityMatrixMutex);
137 
138     auto combined =
139         Get(__func__, &mCombinedFrameworkMatrix,
140             std::bind(&VintfObject::getCombinedFrameworkMatrix, this, deviceManifest, _1, _2));
141     if (combined != nullptr) {
142         return combined;
143     }
144 
145     return Get(__func__, &mFrameworkMatrix,
146                std::bind(&CompatibilityMatrix::fetchAllInformation, _1, getFileSystem().get(),
147                          kSystemLegacyMatrix, _2));
148 }
149 
getCombinedFrameworkMatrix(const std::shared_ptr<const HalManifest> & deviceManifest,CompatibilityMatrix * out,std::string * error)150 status_t VintfObject::getCombinedFrameworkMatrix(
151     const std::shared_ptr<const HalManifest>& deviceManifest, CompatibilityMatrix* out,
152     std::string* error) {
153     std::vector<CompatibilityMatrix> matrixFragments;
154     auto matrixFragmentsStatus = getAllFrameworkMatrixLevels(&matrixFragments, error);
155     if (matrixFragmentsStatus != OK) {
156         return matrixFragmentsStatus;
157     }
158     if (matrixFragments.empty()) {
159         if (error && error->empty()) {
160             *error = "Cannot get framework matrix for each FCM version for unknown error.";
161         }
162         return NAME_NOT_FOUND;
163     }
164 
165     Level deviceLevel = Level::UNSPECIFIED;
166 
167     if (deviceManifest != nullptr) {
168         deviceLevel = deviceManifest->level();
169     }
170 
171     // TODO(b/70628538): Do not infer from Shipping API level.
172     if (deviceLevel == Level::UNSPECIFIED) {
173         auto shippingApi = getPropertyFetcher()->getUintProperty("ro.product.first_api_level", 0u);
174         if (shippingApi != 0u) {
175             deviceLevel = details::convertFromApiLevel(shippingApi);
176         }
177     }
178 
179     if (deviceLevel == Level::UNSPECIFIED) {
180         // Cannot infer FCM version. Combine all matrices by assuming
181         // Shipping FCM Version == min(all supported FCM Versions in the framework)
182         for (auto&& fragment : matrixFragments) {
183             Level fragmentLevel = fragment.level();
184             if (fragmentLevel != Level::UNSPECIFIED && deviceLevel > fragmentLevel) {
185                 deviceLevel = fragmentLevel;
186             }
187         }
188     }
189 
190     if (deviceLevel == Level::UNSPECIFIED) {
191         // None of the fragments specify any FCM version. Should never happen except
192         // for inconsistent builds.
193         if (error) {
194             *error = "No framework compatibility matrix files under " + kSystemVintfDir +
195                      " declare FCM version.";
196         }
197         return NAME_NOT_FOUND;
198     }
199 
200     auto combined = CompatibilityMatrix::combine(deviceLevel, &matrixFragments, error);
201     if (combined == nullptr) {
202         return BAD_VALUE;
203     }
204     *out = std::move(*combined);
205     return OK;
206 }
207 
208 // Load and combine all of the manifests in a directory
addDirectoryManifests(const std::string & directory,HalManifest * manifest,std::string * error)209 status_t VintfObject::addDirectoryManifests(const std::string& directory, HalManifest* manifest,
210                                             std::string* error) {
211     std::vector<std::string> fileNames;
212     status_t err = getFileSystem()->listFiles(directory, &fileNames, error);
213     // if the directory isn't there, that's okay
214     if (err == NAME_NOT_FOUND) return OK;
215     if (err != OK) return err;
216 
217     for (const std::string& file : fileNames) {
218         // Only adds HALs because all other things are added by libvintf
219         // itself for now.
220         HalManifest fragmentManifest;
221         err = fetchOneHalManifest(directory + file, &fragmentManifest, error);
222         if (err != OK) return err;
223 
224         if (!manifest->addAll(&fragmentManifest, error)) {
225             if (error) {
226                 error->insert(0, "Cannot add manifest fragment " + directory + file + ": ");
227             }
228             return UNKNOWN_ERROR;
229         }
230     }
231 
232     return OK;
233 }
234 
235 // Priority for loading vendor manifest:
236 // 1. Vendor manifest + device fragments + ODM manifest (optional) + odm fragments
237 // 2. Vendor manifest + device fragments
238 // 3. ODM manifest (optional) + odm fragments
239 // 4. /vendor/manifest.xml (legacy, no fragments)
240 // where:
241 // A + B means unioning <hal> tags from A and B. If B declares an override, then this takes priority
242 // over A.
fetchDeviceHalManifest(HalManifest * out,std::string * error)243 status_t VintfObject::fetchDeviceHalManifest(HalManifest* out, std::string* error) {
244     HalManifest vendorManifest;
245     status_t vendorStatus = fetchVendorHalManifest(&vendorManifest, error);
246     if (vendorStatus != OK && vendorStatus != NAME_NOT_FOUND) {
247         return vendorStatus;
248     }
249 
250     if (vendorStatus == OK) {
251         *out = std::move(vendorManifest);
252         status_t fragmentStatus = addDirectoryManifests(kVendorManifestFragmentDir, out, error);
253         if (fragmentStatus != OK) {
254             return fragmentStatus;
255         }
256     }
257 
258     HalManifest odmManifest;
259     status_t odmStatus = fetchOdmHalManifest(&odmManifest, error);
260     if (odmStatus != OK && odmStatus != NAME_NOT_FOUND) {
261         return odmStatus;
262     }
263 
264     if (vendorStatus == OK) {
265         if (odmStatus == OK) {
266             if (!out->addAll(&odmManifest, error)) {
267                 if (error) {
268                     error->insert(0, "Cannot add ODM manifest :");
269                 }
270                 return UNKNOWN_ERROR;
271             }
272         }
273         return addDirectoryManifests(kOdmManifestFragmentDir, out, error);
274     }
275 
276     // vendorStatus != OK, "out" is not changed.
277     if (odmStatus == OK) {
278         *out = std::move(odmManifest);
279         return addDirectoryManifests(kOdmManifestFragmentDir, out, error);
280     }
281 
282     // Use legacy /vendor/manifest.xml
283     return out->fetchAllInformation(getFileSystem().get(), kVendorLegacyManifest, error);
284 }
285 
286 // Priority:
287 // 1. if {vendorSku} is defined, /vendor/etc/vintf/manifest_{vendorSku}.xml
288 // 2. /vendor/etc/vintf/manifest.xml
289 // where:
290 // {vendorSku} is the value of ro.boot.product.vendor.sku
fetchVendorHalManifest(HalManifest * out,std::string * error)291 status_t VintfObject::fetchVendorHalManifest(HalManifest* out, std::string* error) {
292     status_t status;
293 
294     std::string vendorSku;
295     vendorSku = getPropertyFetcher()->getProperty("ro.boot.product.vendor.sku", "");
296 
297     if (!vendorSku.empty()) {
298         status =
299             fetchOneHalManifest(kVendorVintfDir + "manifest_" + vendorSku + ".xml", out, error);
300         if (status == OK || status != NAME_NOT_FOUND) {
301             return status;
302         }
303     }
304 
305     status = fetchOneHalManifest(kVendorManifest, out, error);
306     if (status == OK || status != NAME_NOT_FOUND) {
307         return status;
308     }
309 
310     return NAME_NOT_FOUND;
311 }
312 
313 // "out" is written to iff return status is OK.
314 // Priority:
315 // 1. if {sku} is defined, /odm/etc/vintf/manifest_{sku}.xml
316 // 2. /odm/etc/vintf/manifest.xml
317 // 3. if {sku} is defined, /odm/etc/manifest_{sku}.xml
318 // 4. /odm/etc/manifest.xml
319 // where:
320 // {sku} is the value of ro.boot.product.hardware.sku
fetchOdmHalManifest(HalManifest * out,std::string * error)321 status_t VintfObject::fetchOdmHalManifest(HalManifest* out, std::string* error) {
322     status_t status;
323 
324     std::string productModel;
325     productModel = getPropertyFetcher()->getProperty("ro.boot.product.hardware.sku", "");
326 
327     if (!productModel.empty()) {
328         status =
329             fetchOneHalManifest(kOdmVintfDir + "manifest_" + productModel + ".xml", out, error);
330         if (status == OK || status != NAME_NOT_FOUND) {
331             return status;
332         }
333     }
334 
335     status = fetchOneHalManifest(kOdmManifest, out, error);
336     if (status == OK || status != NAME_NOT_FOUND) {
337         return status;
338     }
339 
340     if (!productModel.empty()) {
341         status = fetchOneHalManifest(kOdmLegacyVintfDir + "manifest_" + productModel + ".xml", out,
342                                      error);
343         if (status == OK || status != NAME_NOT_FOUND) {
344             return status;
345         }
346     }
347 
348     status = fetchOneHalManifest(kOdmLegacyManifest, out, error);
349     if (status == OK || status != NAME_NOT_FOUND) {
350         return status;
351     }
352 
353     return NAME_NOT_FOUND;
354 }
355 
356 // Fetch one manifest.xml file. "out" is written to iff return status is OK.
357 // Returns NAME_NOT_FOUND if file is missing.
fetchOneHalManifest(const std::string & path,HalManifest * out,std::string * error)358 status_t VintfObject::fetchOneHalManifest(const std::string& path, HalManifest* out,
359                                           std::string* error) {
360     HalManifest ret;
361     status_t status = ret.fetchAllInformation(getFileSystem().get(), path, error);
362     if (status == OK) {
363         *out = std::move(ret);
364     }
365     return status;
366 }
367 
fetchDeviceMatrix(CompatibilityMatrix * out,std::string * error)368 status_t VintfObject::fetchDeviceMatrix(CompatibilityMatrix* out, std::string* error) {
369     CompatibilityMatrix etcMatrix;
370     if (etcMatrix.fetchAllInformation(getFileSystem().get(), kVendorMatrix, error) == OK) {
371         *out = std::move(etcMatrix);
372         return OK;
373     }
374     return out->fetchAllInformation(getFileSystem().get(), kVendorLegacyMatrix, error);
375 }
376 
377 // Priority:
378 // 1. /system/etc/vintf/manifest.xml
379 //    + /system/etc/vintf/manifest/*.xml if they exist
380 //    + /product/etc/vintf/manifest.xml if it exists
381 //    + /product/etc/vintf/manifest/*.xml if they exist
382 // 2. (deprecated) /system/manifest.xml
fetchFrameworkHalManifest(HalManifest * out,std::string * error)383 status_t VintfObject::fetchFrameworkHalManifest(HalManifest* out, std::string* error) {
384     auto systemEtcStatus = fetchOneHalManifest(kSystemManifest, out, error);
385     if (systemEtcStatus == OK) {
386         auto dirStatus = addDirectoryManifests(kSystemManifestFragmentDir, out, error);
387         if (dirStatus != OK) {
388             return dirStatus;
389         }
390 
391         std::vector<std::pair<const std::string&, const std::string&>> extensions{
392             {kProductManifest, kProductManifestFragmentDir},
393             {kSystemExtManifest, kSystemExtManifestFragmentDir},
394         };
395         for (auto&& [manifestPath, frags] : extensions) {
396             HalManifest halManifest;
397             auto status = fetchOneHalManifest(manifestPath, &halManifest, error);
398             if (status != OK && status != NAME_NOT_FOUND) {
399                 return status;
400             }
401             if (status == OK) {
402                 if (!out->addAll(&halManifest, error)) {
403                     if (error) {
404                         error->insert(0, "Cannot add " + manifestPath + ":");
405                     }
406                     return UNKNOWN_ERROR;
407                 }
408             }
409 
410             auto fragmentStatus = addDirectoryManifests(frags, out, error);
411             if (fragmentStatus != OK) {
412                 return fragmentStatus;
413             }
414         }
415         return OK;
416     } else {
417         LOG(WARNING) << "Cannot fetch " << kSystemManifest << ": "
418                      << (error ? *error : strerror(-systemEtcStatus));
419     }
420 
421     return out->fetchAllInformation(getFileSystem().get(), kSystemLegacyManifest, error);
422 }
423 
appendLine(std::string * error,const std::string & message)424 static void appendLine(std::string* error, const std::string& message) {
425     if (error != nullptr) {
426         if (!error->empty()) *error += "\n";
427         *error += message;
428     }
429 }
430 
getOneMatrix(const std::string & path,CompatibilityMatrix * out,std::string * error)431 status_t VintfObject::getOneMatrix(const std::string& path, CompatibilityMatrix* out,
432                                    std::string* error) {
433     std::string content;
434     status_t status = getFileSystem()->fetch(path, &content, error);
435     if (status != OK) {
436         return status;
437     }
438     if (!gCompatibilityMatrixConverter(out, content, error)) {
439         if (error) {
440             error->insert(0, "Cannot parse " + path + ": ");
441         }
442         return BAD_VALUE;
443     }
444     out->setFileName(path);
445     return OK;
446 }
447 
getAllFrameworkMatrixLevels(std::vector<CompatibilityMatrix> * results,std::string * error)448 status_t VintfObject::getAllFrameworkMatrixLevels(std::vector<CompatibilityMatrix>* results,
449                                                   std::string* error) {
450     std::vector<std::string> dirs = {
451         kSystemVintfDir,
452         kSystemExtVintfDir,
453         kProductVintfDir,
454     };
455     for (const auto& dir : dirs) {
456         std::vector<std::string> fileNames;
457         status_t listStatus = getFileSystem()->listFiles(dir, &fileNames, error);
458         if (listStatus == NAME_NOT_FOUND) {
459             continue;
460         }
461         if (listStatus != OK) {
462             return listStatus;
463         }
464         for (const std::string& fileName : fileNames) {
465             std::string path = dir + fileName;
466             CompatibilityMatrix namedMatrix;
467             std::string matrixError;
468             status_t matrixStatus = getOneMatrix(path, &namedMatrix, &matrixError);
469             if (matrixStatus != OK) {
470                 // Manifests and matrices share the same dir. Client may not have enough
471                 // permissions to read system manifests, or may not be able to parse it.
472                 auto logLevel = matrixStatus == BAD_VALUE ? base::DEBUG : base::ERROR;
473                 LOG(logLevel) << "Framework Matrix: Ignore file " << path << ": " << matrixError;
474                 continue;
475             }
476             results->emplace_back(std::move(namedMatrix));
477         }
478 
479         if (dir == kSystemVintfDir && results->empty()) {
480             if (error) {
481                 *error = "No framework matrices under " + dir + " can be fetched or parsed.\n";
482             }
483             return NAME_NOT_FOUND;
484         }
485     }
486 
487     if (results->empty()) {
488         if (error) {
489             *error =
490                 "No framework matrices can be fetched or parsed. "
491                 "The following directories are searched:\n  " +
492                 android::base::Join(dirs, "\n  ");
493         }
494         return NAME_NOT_FOUND;
495     }
496     return OK;
497 }
498 
GetRuntimeInfo(RuntimeInfo::FetchFlags flags)499 std::shared_ptr<const RuntimeInfo> VintfObject::GetRuntimeInfo(RuntimeInfo::FetchFlags flags) {
500     return GetInstance()->getRuntimeInfo(flags);
501 }
getRuntimeInfo(RuntimeInfo::FetchFlags flags)502 std::shared_ptr<const RuntimeInfo> VintfObject::getRuntimeInfo(RuntimeInfo::FetchFlags flags) {
503     std::unique_lock<std::mutex> _lock(mDeviceRuntimeInfo.mutex);
504 
505     // Skip fetching information that has already been fetched previously.
506     flags &= (~mDeviceRuntimeInfo.fetchedFlags);
507 
508     if (mDeviceRuntimeInfo.object == nullptr) {
509         mDeviceRuntimeInfo.object = getRuntimeInfoFactory()->make_shared();
510     }
511 
512     // Fetch kernel FCM version from device HAL manifest and store it in RuntimeInfo too.
513     if ((flags & RuntimeInfo::FetchFlag::KERNEL_FCM) != 0) {
514         auto manifest = getDeviceHalManifest();
515         if (!manifest) {
516             mDeviceRuntimeInfo.fetchedFlags &= ~RuntimeInfo::FetchFlag::KERNEL_FCM;
517             return nullptr;
518         }
519         Level level = Level::UNSPECIFIED;
520         if (manifest->kernel().has_value()) {
521             level = manifest->kernel()->level();
522         }
523         mDeviceRuntimeInfo.object->setKernelLevel(level);
524         flags &= ~RuntimeInfo::FetchFlag::KERNEL_FCM;
525     }
526 
527     status_t status = mDeviceRuntimeInfo.object->fetchAllInformation(flags);
528     if (status != OK) {
529         mDeviceRuntimeInfo.fetchedFlags &= (~flags);  // mark the fields as "not fetched"
530         return nullptr;
531     }
532 
533     mDeviceRuntimeInfo.fetchedFlags |= flags;
534     return mDeviceRuntimeInfo.object;
535 }
536 
checkCompatibility(std::string * error,CheckFlags::Type flags)537 int32_t VintfObject::checkCompatibility(std::string* error, CheckFlags::Type flags) {
538     status_t status = OK;
539     // null checks for files and runtime info
540     if (getFrameworkHalManifest() == nullptr) {
541         appendLine(error, "No framework manifest file from device or from update package");
542         status = NO_INIT;
543     }
544     if (getDeviceHalManifest() == nullptr) {
545         appendLine(error, "No device manifest file from device or from update package");
546         status = NO_INIT;
547     }
548     if (getFrameworkCompatibilityMatrix() == nullptr) {
549         appendLine(error, "No framework matrix file from device or from update package");
550         status = NO_INIT;
551     }
552     if (getDeviceCompatibilityMatrix() == nullptr) {
553         appendLine(error, "No device matrix file from device or from update package");
554         status = NO_INIT;
555     }
556 
557     if (flags.isRuntimeInfoEnabled()) {
558         if (getRuntimeInfo() == nullptr) {
559             appendLine(error, "No runtime info from device");
560             status = NO_INIT;
561         }
562     }
563     if (status != OK) return status;
564 
565     // compatiblity check.
566     if (!getDeviceHalManifest()->checkCompatibility(*getFrameworkCompatibilityMatrix(), error)) {
567         if (error) {
568             error->insert(0,
569                           "Device manifest and framework compatibility matrix are incompatible: ");
570         }
571         return INCOMPATIBLE;
572     }
573     if (!getFrameworkHalManifest()->checkCompatibility(*getDeviceCompatibilityMatrix(), error)) {
574         if (error) {
575             error->insert(0,
576                           "Framework manifest and device compatibility matrix are incompatible: ");
577         }
578         return INCOMPATIBLE;
579     }
580 
581     if (flags.isRuntimeInfoEnabled()) {
582         if (!getRuntimeInfo()->checkCompatibility(*getFrameworkCompatibilityMatrix(), error,
583                                                   flags)) {
584             if (error) {
585                 error->insert(0,
586                               "Runtime info and framework compatibility matrix are incompatible: ");
587             }
588             return INCOMPATIBLE;
589         }
590     }
591 
592     return COMPATIBLE;
593 }
594 
595 namespace details {
596 
597 const std::string kSystemVintfDir = "/system/etc/vintf/";
598 const std::string kVendorVintfDir = "/vendor/etc/vintf/";
599 const std::string kOdmVintfDir = "/odm/etc/vintf/";
600 const std::string kProductVintfDir = "/product/etc/vintf/";
601 const std::string kSystemExtVintfDir = "/system_ext/etc/vintf/";
602 
603 const std::string kVendorManifest = kVendorVintfDir + "manifest.xml";
604 const std::string kSystemManifest = kSystemVintfDir + "manifest.xml";
605 const std::string kVendorMatrix = kVendorVintfDir + "compatibility_matrix.xml";
606 const std::string kOdmManifest = kOdmVintfDir + "manifest.xml";
607 const std::string kProductMatrix = kProductVintfDir + "compatibility_matrix.xml";
608 const std::string kProductManifest = kProductVintfDir + "manifest.xml";
609 const std::string kSystemExtManifest = kSystemExtVintfDir + "manifest.xml";
610 
611 const std::string kVendorManifestFragmentDir = kVendorVintfDir + "manifest/";
612 const std::string kSystemManifestFragmentDir = kSystemVintfDir + "manifest/";
613 const std::string kOdmManifestFragmentDir = kOdmVintfDir + "manifest/";
614 const std::string kProductManifestFragmentDir = kProductVintfDir + "manifest/";
615 const std::string kSystemExtManifestFragmentDir = kSystemExtVintfDir + "manifest/";
616 
617 const std::string kVendorLegacyManifest = "/vendor/manifest.xml";
618 const std::string kVendorLegacyMatrix = "/vendor/compatibility_matrix.xml";
619 const std::string kSystemLegacyManifest = "/system/manifest.xml";
620 const std::string kSystemLegacyMatrix = "/system/compatibility_matrix.xml";
621 const std::string kOdmLegacyVintfDir = "/odm/etc/";
622 const std::string kOdmLegacyManifest = kOdmLegacyVintfDir + "manifest.xml";
623 
dumpFileList()624 std::vector<std::string> dumpFileList() {
625     return {
626         // clang-format off
627         kSystemVintfDir,
628         kVendorVintfDir,
629         kOdmVintfDir,
630         kProductVintfDir,
631         kSystemExtVintfDir,
632         kOdmLegacyVintfDir,
633         kVendorLegacyManifest,
634         kVendorLegacyMatrix,
635         kSystemLegacyManifest,
636         kSystemLegacyMatrix,
637         // clang-format on
638     };
639 }
640 
641 }  // namespace details
642 
IsHalDeprecated(const MatrixHal & oldMatrixHal,const CompatibilityMatrix & targetMatrix,const ListInstances & listInstances,const ChildrenMap & childrenMap,std::string * appendedError)643 bool VintfObject::IsHalDeprecated(const MatrixHal& oldMatrixHal,
644                                   const CompatibilityMatrix& targetMatrix,
645                                   const ListInstances& listInstances,
646                                   const ChildrenMap& childrenMap, std::string* appendedError) {
647     bool isDeprecated = false;
648     oldMatrixHal.forEachInstance([&](const MatrixInstance& oldMatrixInstance) {
649         if (IsInstanceDeprecated(oldMatrixInstance, targetMatrix, listInstances, childrenMap,
650                                  appendedError)) {
651             isDeprecated = true;
652         }
653         return true;  // continue to check next instance
654     });
655     return isDeprecated;
656 }
657 
658 // Let oldMatrixInstance = package@x.y-w::interface/instancePattern.
659 // If any "@servedVersion::interface/servedInstance" in listInstances(package@x.y::interface)
660 // matches instancePattern, return true iff for all child interfaces (from
661 // GetListedInstanceInheritance), IsFqInstanceDeprecated returns false.
IsInstanceDeprecated(const MatrixInstance & oldMatrixInstance,const CompatibilityMatrix & targetMatrix,const ListInstances & listInstances,const ChildrenMap & childrenMap,std::string * appendedError)662 bool VintfObject::IsInstanceDeprecated(const MatrixInstance& oldMatrixInstance,
663                                        const CompatibilityMatrix& targetMatrix,
664                                        const ListInstances& listInstances,
665                                        const ChildrenMap& childrenMap, std::string* appendedError) {
666     const std::string& package = oldMatrixInstance.package();
667     const Version& version = oldMatrixInstance.versionRange().minVer();
668     const std::string& interface = oldMatrixInstance.interface();
669 
670     std::vector<std::string> instanceHint;
671     if (!oldMatrixInstance.isRegex()) {
672         instanceHint.push_back(oldMatrixInstance.exactInstance());
673     }
674 
675     std::vector<std::string> accumulatedErrors;
676     auto list = listInstances(package, version, interface, instanceHint);
677 
678     for (const auto& pair : list) {
679         const std::string& servedInstance = pair.first;
680         Version servedVersion = pair.second;
681         std::string servedFqInstanceString =
682             toFQNameString(package, servedVersion, interface, servedInstance);
683         if (!oldMatrixInstance.matchInstance(servedInstance)) {
684             // ignore unrelated instance
685             continue;
686         }
687 
688         auto inheritance = GetListedInstanceInheritance(package, servedVersion, interface,
689                                                         servedInstance, listInstances, childrenMap);
690         if (!inheritance.has_value()) {
691             accumulatedErrors.push_back(inheritance.error().message());
692             continue;
693         }
694 
695         std::vector<std::string> errors;
696         for (const auto& fqInstance : *inheritance) {
697             auto result = IsFqInstanceDeprecated(targetMatrix, oldMatrixInstance.format(),
698                                                  fqInstance, listInstances);
699             if (result.ok()) {
700                 errors.clear();
701                 break;
702             }
703             errors.push_back(result.error().message());
704         }
705 
706         if (errors.empty()) {
707             continue;
708         }
709         accumulatedErrors.insert(accumulatedErrors.end(), errors.begin(), errors.end());
710     }
711 
712     if (accumulatedErrors.empty()) {
713         return false;
714     }
715     appendLine(appendedError, android::base::Join(accumulatedErrors, "\n"));
716     return true;
717 }
718 
719 // Check if fqInstance is listed in |listInstances|.
IsInstanceListed(const ListInstances & listInstances,const FqInstance & fqInstance)720 bool VintfObject::IsInstanceListed(const ListInstances& listInstances,
721                                    const FqInstance& fqInstance) {
722     auto list =
723         listInstances(fqInstance.getPackage(), fqInstance.getVersion(), fqInstance.getInterface(),
724                       {fqInstance.getInstance()} /* instanceHint*/);
725     return std::any_of(list.begin(), list.end(),
726                        [&](const auto& pair) { return pair.first == fqInstance.getInstance(); });
727 }
728 
729 // Return a list of FqInstance, where each element:
730 // - is listed in |listInstances|; AND
731 // - is, or inherits from, package@version::interface/instance (as specified by |childrenMap|)
GetListedInstanceInheritance(const std::string & package,const Version & version,const std::string & interface,const std::string & instance,const ListInstances & listInstances,const ChildrenMap & childrenMap)732 android::base::Result<std::vector<FqInstance>> VintfObject::GetListedInstanceInheritance(
733     const std::string& package, const Version& version, const std::string& interface,
734     const std::string& instance, const ListInstances& listInstances,
735     const ChildrenMap& childrenMap) {
736     FqInstance fqInstance;
737     if (!fqInstance.setTo(package, version.majorVer, version.minorVer, interface, instance)) {
738         return android::base::Error() << toFQNameString(package, version, interface, instance)
739                                       << " is not a valid FqInstance";
740     }
741 
742     if (!IsInstanceListed(listInstances, fqInstance)) {
743         return {};
744     }
745 
746     const FQName& fqName = fqInstance.getFqName();
747 
748     std::vector<FqInstance> ret;
749     ret.push_back(fqInstance);
750 
751     auto childRange = childrenMap.equal_range(fqName.string());
752     for (auto it = childRange.first; it != childRange.second; ++it) {
753         const auto& childFqNameString = it->second;
754         FQName childFqName;
755         if (!childFqName.setTo(childFqNameString)) {
756             return android::base::Error() << "Cannot parse " << childFqNameString << " as FQName";
757         }
758         FqInstance childFqInstance;
759         if (!childFqInstance.setTo(childFqName, fqInstance.getInstance())) {
760             return android::base::Error() << "Cannot merge " << childFqName.string() << "/"
761                                           << fqInstance.getInstance() << " as FqInstance";
762             continue;
763         }
764         if (!IsInstanceListed(listInstances, childFqInstance)) {
765             continue;
766         }
767         ret.push_back(childFqInstance);
768     }
769     return ret;
770 }
771 
772 // Check if |fqInstance| is in |targetMatrix|; essentially equal to
773 // targetMatrix.matchInstance(fqInstance), but provides richer error message. In details:
774 // 1. package@x.?::interface/servedInstance is not in targetMatrix; OR
775 // 2. package@x.z::interface/servedInstance is in targetMatrix but
776 //    servedInstance is not in listInstances(package@x.z::interface)
IsFqInstanceDeprecated(const CompatibilityMatrix & targetMatrix,HalFormat format,const FqInstance & fqInstance,const ListInstances & listInstances)777 android::base::Result<void> VintfObject::IsFqInstanceDeprecated(
778     const CompatibilityMatrix& targetMatrix, HalFormat format, const FqInstance& fqInstance,
779     const ListInstances& listInstances) {
780     // Find minimum package@x.? in target matrix, and check if instance is in target matrix.
781     bool foundInstance = false;
782     Version targetMatrixMinVer{SIZE_MAX, SIZE_MAX};
783     targetMatrix.forEachInstanceOfPackage(
784         format, fqInstance.getPackage(), [&](const auto& targetMatrixInstance) {
785             if (targetMatrixInstance.versionRange().majorVer == fqInstance.getMajorVersion() &&
786                 targetMatrixInstance.interface() == fqInstance.getInterface() &&
787                 targetMatrixInstance.matchInstance(fqInstance.getInstance())) {
788                 targetMatrixMinVer =
789                     std::min(targetMatrixMinVer, targetMatrixInstance.versionRange().minVer());
790                 foundInstance = true;
791             }
792             return true;
793         });
794     if (!foundInstance) {
795         return android::base::Error()
796                << fqInstance.string() << " is deprecated in compatibility matrix at FCM Version "
797                << targetMatrix.level() << "; it should not be served.";
798     }
799 
800     // Assuming that targetMatrix requires @x.u-v, require that at least @x.u is served.
801     bool targetVersionServed = false;
802     for (const auto& newPair :
803          listInstances(fqInstance.getPackage(), targetMatrixMinVer, fqInstance.getInterface(),
804                        {fqInstance.getInstance()} /* instanceHint */)) {
805         if (newPair.first == fqInstance.getInstance()) {
806             targetVersionServed = true;
807             break;
808         }
809     }
810 
811     if (!targetVersionServed) {
812         return android::base::Error()
813                << fqInstance.string() << " is deprecated; requires at least " << targetMatrixMinVer;
814     }
815     return {};
816 }
817 
checkDeprecation(const ListInstances & listInstances,const std::vector<HidlInterfaceMetadata> & hidlMetadata,std::string * error)818 int32_t VintfObject::checkDeprecation(const ListInstances& listInstances,
819                                       const std::vector<HidlInterfaceMetadata>& hidlMetadata,
820                                       std::string* error) {
821     std::vector<CompatibilityMatrix> matrixFragments;
822     auto matrixFragmentsStatus = getAllFrameworkMatrixLevels(&matrixFragments, error);
823     if (matrixFragmentsStatus != OK) {
824         return matrixFragmentsStatus;
825     }
826     if (matrixFragments.empty()) {
827         if (error && error->empty()) {
828             *error = "Cannot get framework matrix for each FCM version for unknown error.";
829         }
830         return NAME_NOT_FOUND;
831     }
832     auto deviceManifest = getDeviceHalManifest();
833     if (deviceManifest == nullptr) {
834         if (error) *error = "No device manifest.";
835         return NAME_NOT_FOUND;
836     }
837     Level deviceLevel = deviceManifest->level();
838     if (deviceLevel == Level::UNSPECIFIED) {
839         if (error) *error = "Device manifest does not specify Shipping FCM Version.";
840         return BAD_VALUE;
841     }
842 
843     const CompatibilityMatrix* targetMatrix = nullptr;
844     for (const auto& namedMatrix : matrixFragments) {
845         if (namedMatrix.level() == deviceLevel) {
846             targetMatrix = &namedMatrix;
847         }
848     }
849     if (targetMatrix == nullptr) {
850         if (error)
851             *error = "Cannot find framework matrix at FCM version " + to_string(deviceLevel) + ".";
852         return NAME_NOT_FOUND;
853     }
854 
855     std::multimap<std::string, std::string> childrenMap;
856     for (const auto& child : hidlMetadata) {
857         for (const auto& parent : child.inherited) {
858             childrenMap.emplace(parent, child.name);
859         }
860     }
861 
862     // Find a list of possibly deprecated HALs by comparing |listInstances| with older matrices.
863     // Matrices with unspecified level are considered "current".
864     bool isDeprecated = false;
865     for (const auto& namedMatrix : matrixFragments) {
866         if (namedMatrix.level() == Level::UNSPECIFIED) continue;
867         if (namedMatrix.level() >= deviceLevel) continue;
868 
869         for (const MatrixHal& hal : namedMatrix.getHals()) {
870             if (IsHalDeprecated(hal, *targetMatrix, listInstances, childrenMap, error)) {
871                 isDeprecated = true;
872             }
873         }
874     }
875 
876     return isDeprecated ? DEPRECATED : NO_DEPRECATED_HALS;
877 }
878 
checkDeprecation(const std::vector<HidlInterfaceMetadata> & hidlMetadata,std::string * error)879 int32_t VintfObject::checkDeprecation(const std::vector<HidlInterfaceMetadata>& hidlMetadata,
880                                       std::string* error) {
881     using namespace std::placeholders;
882     auto deviceManifest = getDeviceHalManifest();
883     ListInstances inManifest =
884         [&deviceManifest](const std::string& package, Version version, const std::string& interface,
885                           const std::vector<std::string>& /* hintInstances */) {
886             std::vector<std::pair<std::string, Version>> ret;
887             deviceManifest->forEachInstanceOfInterface(
888                 HalFormat::HIDL, package, version, interface,
889                 [&ret](const ManifestInstance& manifestInstance) {
890                     ret.push_back(
891                         std::make_pair(manifestInstance.instance(), manifestInstance.version()));
892                     return true;
893                 });
894             return ret;
895         };
896     return checkDeprecation(inManifest, hidlMetadata, error);
897 }
898 
getKernelLevel(std::string * error)899 Level VintfObject::getKernelLevel(std::string* error) {
900     auto manifest = getDeviceHalManifest();
901     if (!manifest) {
902         if (error) *error = "Cannot retrieve device manifest.";
903         return Level::UNSPECIFIED;
904     }
905     if (manifest->kernel().has_value() && manifest->kernel()->level() != Level::UNSPECIFIED) {
906         return manifest->kernel()->level();
907     }
908     if (error) *error = "Device manifest does not specify kernel FCM version.";
909     return Level::UNSPECIFIED;
910 }
911 
getFileSystem()912 const std::unique_ptr<FileSystem>& VintfObject::getFileSystem() {
913     return mFileSystem;
914 }
915 
getPropertyFetcher()916 const std::unique_ptr<PropertyFetcher>& VintfObject::getPropertyFetcher() {
917     return mPropertyFetcher;
918 }
919 
getRuntimeInfoFactory()920 const std::unique_ptr<ObjectFactory<RuntimeInfo>>& VintfObject::getRuntimeInfoFactory() {
921     return mRuntimeInfoFactory;
922 }
923 
hasFrameworkCompatibilityMatrixExtensions()924 android::base::Result<bool> VintfObject::hasFrameworkCompatibilityMatrixExtensions() {
925     std::vector<CompatibilityMatrix> matrixFragments;
926     std::string error;
927     status_t status = getAllFrameworkMatrixLevels(&matrixFragments, &error);
928     if (status != OK) {
929         return android::base::Error(-status)
930                << "Cannot get all framework matrix fragments: " << error;
931     }
932     for (const auto& namedMatrix : matrixFragments) {
933         // Returns true if product matrix exists.
934         if (android::base::StartsWith(namedMatrix.fileName(), kProductVintfDir)) {
935             return true;
936         }
937         // Returns true if system_ext matrix exists.
938         if (android::base::StartsWith(namedMatrix.fileName(), kSystemExtVintfDir)) {
939             return true;
940         }
941         // Returns true if device system matrix exists.
942         if (android::base::StartsWith(namedMatrix.fileName(), kSystemVintfDir) &&
943             namedMatrix.level() == Level::UNSPECIFIED && !namedMatrix.getHals().empty()) {
944             return true;
945         }
946     }
947     return false;
948 }
949 
checkUnusedHals(const std::vector<HidlInterfaceMetadata> & hidlMetadata)950 android::base::Result<void> VintfObject::checkUnusedHals(
951     const std::vector<HidlInterfaceMetadata>& hidlMetadata) {
952     auto matrix = getFrameworkCompatibilityMatrix();
953     if (matrix == nullptr) {
954         return android::base::Error(-NAME_NOT_FOUND) << "Missing framework matrix.";
955     }
956     auto manifest = getDeviceHalManifest();
957     if (manifest == nullptr) {
958         return android::base::Error(-NAME_NOT_FOUND) << "Missing device manifest.";
959     }
960     auto unused = manifest->checkUnusedHals(*matrix, hidlMetadata);
961     if (!unused.empty()) {
962         return android::base::Error()
963                << "The following instances are in the device manifest but "
964                << "not specified in framework compatibility matrix: \n"
965                << "    " << android::base::Join(unused, "\n    ") << "\n"
966                << "Suggested fix:\n"
967                << "1. Update deprecated HALs to the latest version.\n"
968                << "2. Check for any typos in device manifest or framework compatibility "
969                << "matrices with FCM version >= " << matrix->level() << ".\n"
970                << "3. For new platform HALs, add them to any framework compatibility matrix "
971                << "with FCM version >= " << matrix->level() << " where applicable.\n"
972                << "4. For device-specific HALs, add to DEVICE_FRAMEWORK_COMPATIBILITY_MATRIX_FILE "
973                << "or DEVICE_PRODUCT_COMPATIBILITY_MATRIX_FILE.";
974     }
975     return {};
976 }
977 
978 // make_unique does not work because VintfObject constructor is private.
Builder()979 VintfObject::Builder::Builder() : mObject(std::unique_ptr<VintfObject>(new VintfObject())) {}
980 
setFileSystem(std::unique_ptr<FileSystem> && e)981 VintfObject::Builder& VintfObject::Builder::setFileSystem(std::unique_ptr<FileSystem>&& e) {
982     mObject->mFileSystem = std::move(e);
983     return *this;
984 }
985 
setRuntimeInfoFactory(std::unique_ptr<ObjectFactory<RuntimeInfo>> && e)986 VintfObject::Builder& VintfObject::Builder::setRuntimeInfoFactory(
987     std::unique_ptr<ObjectFactory<RuntimeInfo>>&& e) {
988     mObject->mRuntimeInfoFactory = std::move(e);
989     return *this;
990 }
991 
setPropertyFetcher(std::unique_ptr<PropertyFetcher> && e)992 VintfObject::Builder& VintfObject::Builder::setPropertyFetcher(
993     std::unique_ptr<PropertyFetcher>&& e) {
994     mObject->mPropertyFetcher = std::move(e);
995     return *this;
996 }
997 
build()998 std::unique_ptr<VintfObject> VintfObject::Builder::build() {
999     if (!mObject->mFileSystem) mObject->mFileSystem = createDefaultFileSystem();
1000     if (!mObject->mRuntimeInfoFactory)
1001         mObject->mRuntimeInfoFactory = std::make_unique<ObjectFactory<RuntimeInfo>>();
1002     if (!mObject->mPropertyFetcher) mObject->mPropertyFetcher = createDefaultPropertyFetcher();
1003     return std::move(mObject);
1004 }
1005 
1006 } // namespace vintf
1007 } // namespace android
1008