summaryrefslogtreecommitdiffstats
blob: 7c55181dc58609a77619dd0ef09e1f694d2cbee3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "VintfObject.h"

#include "CompatibilityMatrix.h"
#include "parse_string.h"
#include "parse_xml.h"
#include "utils.h"

#include <dirent.h>

#include <functional>
#include <memory>
#include <mutex>

#ifdef LIBVINTF_TARGET
#include <android-base/properties.h>
#endif

#include <android-base/logging.h>

using std::placeholders::_1;
using std::placeholders::_2;

namespace android {
namespace vintf {

using namespace details;

template <typename T>
struct LockedSharedPtr {
    std::shared_ptr<T> object;
    std::mutex mutex;
    bool fetchedOnce = false;
};

struct LockedRuntimeInfoCache {
    std::shared_ptr<RuntimeInfo> object;
    std::mutex mutex;
    RuntimeInfo::FetchFlags fetchedFlags = RuntimeInfo::FetchFlag::NONE;
};

template <typename T, typename F>
static std::shared_ptr<const T> Get(
        LockedSharedPtr<T> *ptr,
        bool skipCache,
        const F &fetchAllInformation) {
    std::unique_lock<std::mutex> _lock(ptr->mutex);
    if (skipCache || !ptr->fetchedOnce) {
        ptr->object = std::make_unique<T>();
        std::string error;
        if (fetchAllInformation(ptr->object.get(), &error) != OK) {
            LOG(WARNING) << error;
            ptr->object = nullptr; // frees the old object
        }
        ptr->fetchedOnce = true;
    }
    return ptr->object;
}

// static
std::shared_ptr<const HalManifest> VintfObject::GetDeviceHalManifest(bool skipCache) {
    static LockedSharedPtr<HalManifest> gVendorManifest;
    return Get(&gVendorManifest, skipCache, &VintfObject::FetchDeviceHalManifest);
}

// static
std::shared_ptr<const HalManifest> VintfObject::GetFrameworkHalManifest(bool skipCache) {
    static LockedSharedPtr<HalManifest> gFrameworkManifest;
    return Get(&gFrameworkManifest, skipCache,
               std::bind(&HalManifest::fetchAllInformation, _1, kSystemManifest, _2));
}


// static
std::shared_ptr<const CompatibilityMatrix> VintfObject::GetDeviceCompatibilityMatrix(bool skipCache) {
    static LockedSharedPtr<CompatibilityMatrix> gDeviceMatrix;
    return Get(&gDeviceMatrix, skipCache, &VintfObject::FetchDeviceMatrix);
}

// static
std::shared_ptr<const CompatibilityMatrix> VintfObject::GetFrameworkCompatibilityMatrix(bool skipCache) {
    static LockedSharedPtr<CompatibilityMatrix> gFrameworkMatrix;
    static LockedSharedPtr<CompatibilityMatrix> gCombinedFrameworkMatrix;
    static std::mutex gFrameworkCompatibilityMatrixMutex;

    // To avoid deadlock, get device manifest before any locks.
    auto deviceManifest = GetDeviceHalManifest();

    std::unique_lock<std::mutex> _lock(gFrameworkCompatibilityMatrixMutex);

    auto combined =
        Get(&gCombinedFrameworkMatrix, skipCache,
            std::bind(&VintfObject::GetCombinedFrameworkMatrix, deviceManifest, _1, _2));
    if (combined != nullptr) {
        return combined;
    }

    return Get(&gFrameworkMatrix, skipCache,
               std::bind(&CompatibilityMatrix::fetchAllInformation, _1, kSystemLegacyMatrix, _2));
}

status_t VintfObject::GetCombinedFrameworkMatrix(
    const std::shared_ptr<const HalManifest>& deviceManifest, CompatibilityMatrix* out,
    std::string* error) {
    auto matrixFragments = GetAllFrameworkMatrixLevels(error);
    if (matrixFragments.empty()) {
        return NAME_NOT_FOUND;
    }

    Level deviceLevel = Level::UNSPECIFIED;

    if (deviceManifest != nullptr) {
        deviceLevel = deviceManifest->level();
    }

    // TODO(b/70628538): Do not infer from Shipping API level.
#ifdef LIBVINTF_TARGET
    if (deviceLevel == Level::UNSPECIFIED) {
        auto shippingApi =
            android::base::GetUintProperty<uint64_t>("ro.product.first_api_level", 0u);
        if (shippingApi != 0u) {
            deviceLevel = details::convertFromApiLevel(shippingApi);
        }
    }
#endif

    if (deviceLevel == Level::UNSPECIFIED) {
        // Cannot infer FCM version. Combine all matrices by assuming
        // Shipping FCM Version == min(all supported FCM Versions in the framework)
        for (auto&& pair : matrixFragments) {
            Level fragmentLevel = pair.object.level();
            if (fragmentLevel != Level::UNSPECIFIED && deviceLevel > fragmentLevel) {
                deviceLevel = fragmentLevel;
            }
        }
    }

    if (deviceLevel == Level::UNSPECIFIED) {
        // None of the fragments specify any FCM version. Should never happen except
        // for inconsistent builds.
        if (error) {
            *error = "No framework compatibility matrix files under " + kSystemVintfDir +
                     " declare FCM version.";
        }
        return NAME_NOT_FOUND;
    }

    CompatibilityMatrix* combined =
        CompatibilityMatrix::combine(deviceLevel, &matrixFragments, error);
    if (combined == nullptr) {
        return BAD_VALUE;
    }
    *out = std::move(*combined);
    return OK;
}

// Priority for loading vendor manifest:
// 1. /vendor/etc/vintf/manifest.xml + ODM manifest
// 2. /vendor/etc/vintf/manifest.xml
// 3. ODM manifest
// 4. /vendor/manifest.xml
// where:
// A + B means adding <hal> tags from B to A (so that <hal>s from B can override A)
status_t VintfObject::FetchDeviceHalManifest(HalManifest* out, std::string* error) {
    status_t vendorStatus = FetchOneHalManifest(kVendorManifest, out, error);
    if (vendorStatus != OK && vendorStatus != NAME_NOT_FOUND) {
        return vendorStatus;
    }

    HalManifest odmManifest;
    status_t odmStatus = FetchOdmHalManifest(&odmManifest, error);
    if (odmStatus != OK && odmStatus != NAME_NOT_FOUND) {
        return odmStatus;
    }

    if (vendorStatus == OK) {
        if (odmStatus == OK) {
            out->addAllHals(&odmManifest);
        }
        return OK;
    }

    // vendorStatus != OK, "out" is not changed.
    if (odmStatus == OK) {
        *out = std::move(odmManifest);
        return OK;
    }

    // Use legacy /vendor/manifest.xml
    return out->fetchAllInformation(kVendorLegacyManifest, error);
}

// "out" is written to iff return status is OK.
// Priority:
// 1. if {sku} is defined, /odm/etc/vintf/manifest_{sku}.xml
// 2. /odm/etc/vintf/manifest.xml
// 3. if {sku} is defined, /odm/etc/manifest_{sku}.xml
// 4. /odm/etc/manifest.xml
// where:
// {sku} is the value of ro.boot.product.hardware.sku
status_t VintfObject::FetchOdmHalManifest(HalManifest* out, std::string* error) {
    status_t status;

#ifdef LIBVINTF_TARGET
    std::string productModel;
    productModel = android::base::GetProperty("ro.boot.product.hardware.sku", "");

    if (!productModel.empty()) {
        status =
            FetchOneHalManifest(kOdmVintfDir + "manifest_" + productModel + ".xml", out, error);
        if (status == OK || status != NAME_NOT_FOUND) {
            return status;
        }
    }
#endif

    status = FetchOneHalManifest(kOdmManifest, out, error);
    if (status == OK || status != NAME_NOT_FOUND) {
        return status;
    }

#ifdef LIBVINTF_TARGET
    if (!productModel.empty()) {
        status = FetchOneHalManifest(kOdmLegacyVintfDir + "manifest_" + productModel + ".xml", out,
                                     error);
        if (status == OK || status != NAME_NOT_FOUND) {
            return status;
        }
    }
#endif

    status = FetchOneHalManifest(kOdmLegacyManifest, out, error);
    if (status == OK || status != NAME_NOT_FOUND) {
        return status;
    }

    return NAME_NOT_FOUND;
}

// Fetch one manifest.xml file. "out" is written to iff return status is OK.
// Returns NAME_NOT_FOUND if file is missing.
status_t VintfObject::FetchOneHalManifest(const std::string& path, HalManifest* out,
                                          std::string* error) {
    HalManifest ret;
    status_t status = ret.fetchAllInformation(path, error);
    if (status == OK) {
        *out = std::move(ret);
    }
    return status;
}

status_t VintfObject::FetchDeviceMatrix(CompatibilityMatrix* out, std::string* error) {
    CompatibilityMatrix etcMatrix;
    if (etcMatrix.fetchAllInformation(kVendorMatrix, error) == OK) {
        *out = std::move(etcMatrix);
        return OK;
    }
    return out->fetchAllInformation(kVendorLegacyMatrix, error);
}

std::vector<Named<CompatibilityMatrix>> VintfObject::GetAllFrameworkMatrixLevels(
    std::string* error) {
    std::vector<std::string> fileNames;
    std::vector<Named<CompatibilityMatrix>> results;

    if (details::gFetcher->listFiles(kSystemVintfDir, &fileNames, error) != OK) {
        return {};
    }
    for (const std::string& fileName : fileNames) {
        std::string path = kSystemVintfDir + fileName;

        std::string content;
        std::string fetchError;
        status_t status = details::gFetcher->fetch(path, content, &fetchError);
        if (status != OK) {
            if (error) {
                *error += "Ignore file " + path + ": " + fetchError + "\n";
            }
            continue;
        }

        auto it = results.emplace(results.end());
        if (!gCompatibilityMatrixConverter(&it->object, content)) {
            if (error) {
                // TODO(b/71874788): do not use lastError() because it is not thread-safe.
                *error +=
                    "Ignore file " + path + ": " + gCompatibilityMatrixConverter.lastError() + "\n";
            }
            results.erase(it);
            continue;
        }
    }

    if (results.empty()) {
        if (error) {
            *error = "No framework matrices under " + kSystemVintfDir +
                     " can be fetched or parsed.\n" + *error;
        }
    } else {
        if (error && !error->empty()) {
            LOG(WARNING) << *error;
            *error = "";
        }
    }

    return results;
}

// static
std::shared_ptr<const RuntimeInfo> VintfObject::GetRuntimeInfo(bool skipCache,
                                                               RuntimeInfo::FetchFlags flags) {
    static LockedRuntimeInfoCache gDeviceRuntimeInfo;
    std::unique_lock<std::mutex> _lock(gDeviceRuntimeInfo.mutex);

    if (!skipCache) {
        flags &= (~gDeviceRuntimeInfo.fetchedFlags);
    }

    if (gDeviceRuntimeInfo.object == nullptr) {
        gDeviceRuntimeInfo.object = details::gRuntimeInfoFactory->make_shared();
    }

    status_t status = gDeviceRuntimeInfo.object->fetchAllInformation(flags);
    if (status != OK) {
        gDeviceRuntimeInfo.fetchedFlags &= (~flags);  // mark the fields as "not fetched"
        return nullptr;
    }

    gDeviceRuntimeInfo.fetchedFlags |= flags;
    return gDeviceRuntimeInfo.object;
}

namespace details {

enum class ParseStatus {
    OK,
    PARSE_ERROR,
    DUPLICATED_FWK_ENTRY,
    DUPLICATED_DEV_ENTRY,
};

static std::string toString(ParseStatus status) {
    switch(status) {
        case ParseStatus::OK:                   return "OK";
        case ParseStatus::PARSE_ERROR:          return "parse error";
        case ParseStatus::DUPLICATED_FWK_ENTRY: return "duplicated framework";
        case ParseStatus::DUPLICATED_DEV_ENTRY: return "duplicated device";
    }
    return "";
}

template<typename T>
static ParseStatus tryParse(const std::string &xml, const XmlConverter<T> &parse,
        std::shared_ptr<T> *fwk, std::shared_ptr<T> *dev) {
    std::shared_ptr<T> ret = std::make_shared<T>();
    if (!parse(ret.get(), xml)) {
        return ParseStatus::PARSE_ERROR;
    }
    if (ret->type() == SchemaType::FRAMEWORK) {
        if (fwk->get() != nullptr) {
            return ParseStatus::DUPLICATED_FWK_ENTRY;
        }
        *fwk = std::move(ret);
    } else if (ret->type() == SchemaType::DEVICE) {
        if (dev->get() != nullptr) {
            return ParseStatus::DUPLICATED_DEV_ENTRY;
        }
        *dev = std::move(ret);
    }
    return ParseStatus::OK;
}

template<typename T, typename GetFunction>
static status_t getMissing(const std::shared_ptr<T>& pkg, bool mount,
        std::function<status_t(void)> mountFunction,
        std::shared_ptr<const T>* updated,
        GetFunction getFunction) {
    if (pkg != nullptr) {
        *updated = pkg;
    } else {
        if (mount) {
            (void)mountFunction(); // ignore mount errors
        }
        *updated = getFunction();
    }
    return OK;
}

#define ADD_MESSAGE(__error__)  \
    if (error != nullptr) {     \
        *error += (__error__);  \
    }                           \

struct PackageInfo {
    struct Pair {
        std::shared_ptr<HalManifest>         manifest;
        std::shared_ptr<CompatibilityMatrix> matrix;
    };
    Pair dev;
    Pair fwk;
};

struct UpdatedInfo {
    struct Pair {
        std::shared_ptr<const HalManifest>         manifest;
        std::shared_ptr<const CompatibilityMatrix> matrix;
    };
    Pair dev;
    Pair fwk;
    std::shared_ptr<const RuntimeInfo> runtimeInfo;
};

// Checks given compatibility info against info on the device. If no
// compatability info is given then the device info will be checked against
// itself.
int32_t checkCompatibility(const std::vector<std::string>& xmls, bool mount,
                           const PartitionMounter& mounter, std::string* error,
                           DisabledChecks disabledChecks) {
    status_t status;
    ParseStatus parseStatus;
    PackageInfo pkg; // All information from package.
    UpdatedInfo updated; // All files and runtime info after the update.

    // parse all information from package
    for (const auto &xml : xmls) {
        parseStatus = tryParse(xml, gHalManifestConverter, &pkg.fwk.manifest, &pkg.dev.manifest);
        if (parseStatus == ParseStatus::OK) {
            continue; // work on next one
        }
        if (parseStatus != ParseStatus::PARSE_ERROR) {
            ADD_MESSAGE(toString(parseStatus) + " manifest");
            return ALREADY_EXISTS;
        }
        parseStatus = tryParse(xml, gCompatibilityMatrixConverter, &pkg.fwk.matrix, &pkg.dev.matrix);
        if (parseStatus == ParseStatus::OK) {
            continue; // work on next one
        }
        if (parseStatus != ParseStatus::PARSE_ERROR) {
            ADD_MESSAGE(toString(parseStatus) + " matrix");
            return ALREADY_EXISTS;
        }
        ADD_MESSAGE(toString(parseStatus)); // parse error
        return BAD_VALUE;
    }

    // get missing info from device
    // use functions instead of std::bind because std::bind doesn't work well with mock objects
    auto mountSystem = [&mounter] { return mounter.mountSystem(); };
    auto mountVendor = [&mounter] { return mounter.mountVendor(); };
    if ((status = getMissing(
             pkg.fwk.manifest, mount, mountSystem, &updated.fwk.manifest,
             std::bind(VintfObject::GetFrameworkHalManifest, true /* skipCache */))) != OK) {
        return status;
    }
    if ((status = getMissing(
             pkg.dev.manifest, mount, mountVendor, &updated.dev.manifest,
             std::bind(VintfObject::GetDeviceHalManifest, true /* skipCache */))) != OK) {
        return status;
    }
    if ((status = getMissing(
             pkg.fwk.matrix, mount, mountSystem, &updated.fwk.matrix,
             std::bind(VintfObject::GetFrameworkCompatibilityMatrix, true /* skipCache */))) !=
        OK) {
        return status;
    }
    if ((status = getMissing(
             pkg.dev.matrix, mount, mountVendor, &updated.dev.matrix,
             std::bind(VintfObject::GetDeviceCompatibilityMatrix, true /* skipCache */))) != OK) {
        return status;
    }

    if (mount) {
        (void)mounter.umountSystem(); // ignore errors
        (void)mounter.umountVendor(); // ignore errors
    }

    updated.runtimeInfo = VintfObject::GetRuntimeInfo(true /* skipCache */);

    // null checks for files and runtime info after the update
    // TODO(b/37321309) if a compat mat is missing, it is not matched and considered compatible.
    if (updated.fwk.manifest == nullptr) {
        ADD_MESSAGE("No framework manifest file from device or from update package");
        return NO_INIT;
    }
    if (updated.dev.manifest == nullptr) {
        ADD_MESSAGE("No device manifest file from device or from update package");
        return NO_INIT;
    }
    if (updated.fwk.matrix == nullptr) {
        ADD_MESSAGE("No framework matrix, skipping;");
        // TODO(b/37321309) consider missing matricies as errors.
    }
    if (updated.dev.matrix == nullptr) {
        ADD_MESSAGE("No device matrix, skipping;");
        // TODO(b/37321309) consider missing matricies as errors.
    }
    if (updated.runtimeInfo == nullptr) {
        ADD_MESSAGE("No runtime info from device");
        return NO_INIT;
    }

    // compatiblity check.
    // TODO(b/37321309) outer if checks can be removed if we consider missing matrices as errors.
    if (updated.dev.manifest && updated.fwk.matrix) {
        if (!updated.dev.manifest->checkCompatibility(*updated.fwk.matrix, error)) {
            if (error)
                error->insert(0, "Device manifest and framework compatibility matrix "
                                 "are incompatible: ");
            return INCOMPATIBLE;
        }
    }
    if (updated.fwk.manifest && updated.dev.matrix) {
        if (!updated.fwk.manifest->checkCompatibility(*updated.dev.matrix, error)) {
            if (error)
                error->insert(0, "Framework manifest and device compatibility matrix "
                                 "are incompatible: ");
            return INCOMPATIBLE;
        }
    }
    if (updated.runtimeInfo && updated.fwk.matrix) {
        if (!updated.runtimeInfo->checkCompatibility(*updated.fwk.matrix, error, disabledChecks)) {
            if (error)
                error->insert(0, "Runtime info and framework compatibility matrix "
                                 "are incompatible: ");
            return INCOMPATIBLE;
        }
    }

    return COMPATIBLE;
}

const std::string kSystemVintfDir = "/system/etc/vintf/";
const std::string kVendorVintfDir = "/vendor/etc/vintf/";
const std::string kOdmVintfDir = "/odm/etc/vintf/";

const std::string kVendorManifest = kVendorVintfDir + "manifest.xml";
const std::string kSystemManifest = kSystemVintfDir + "manifest.xml";
const std::string kVendorMatrix = kVendorVintfDir + "compatibility_matrix.xml";
const std::string kOdmManifest = kOdmVintfDir + "manifest.xml";

const std::string kVendorLegacyManifest = "/vendor/manifest.xml";
const std::string kVendorLegacyMatrix = "/vendor/compatibility_matrix.xml";
const std::string kSystemLegacyMatrix = "/system/compatibility_matrix.xml";
const std::string kOdmLegacyVintfDir = "/odm/etc/";
const std::string kOdmLegacyManifest = kOdmLegacyVintfDir + "manifest.xml";

} // namespace details

// static
int32_t VintfObject::CheckCompatibility(const std::vector<std::string>& xmls, std::string* error,
                                        DisabledChecks disabledChecks) {
    return details::checkCompatibility(xmls, false /* mount */, *details::gPartitionMounter, error,
                                       disabledChecks);
}

bool VintfObject::isHalDeprecated(const MatrixHal& oldMatrixHal,
                                  const CompatibilityMatrix& targetMatrix,
                                  const IsInstanceInUse& isInstanceInUse, std::string* error) {
    for (const VersionRange& range : oldMatrixHal.versionRanges) {
        for (const HalInterface& interface : iterateValues(oldMatrixHal.interfaces)) {
            for (const std::string& instance : interface.instances) {
                if (isInstanceDeprecated(oldMatrixHal.name, range.minVer(), interface.name,
                                         instance, targetMatrix, isInstanceInUse, error)) {
                    return true;
                }
            }
        }
    }
    return false;
}

// If isInstanceInUse(package@x.y::interface/instance), return true iff:
// 1. package@x.?::interface/instance is not in targetMatrix; OR
// 2. package@x.z::interface/instance is in targetMatrix but
// !isInstanceInUse(package@x.z::interface/instance)
bool VintfObject::isInstanceDeprecated(const std::string& package, Version version,
                                       const std::string& interface, const std::string& instance,
                                       const CompatibilityMatrix& targetMatrix,
                                       const IsInstanceInUse& isInstanceInUse,
                                       std::string* error) {
    bool oldVersionIsServed;
    Version servedVersion;
    std::tie(oldVersionIsServed, servedVersion) =
        isInstanceInUse(package, version, interface, instance);
    if (oldVersionIsServed) {
        // Find any package@x.? in target matrix, and check if instance is in target matrix.
        const MatrixHal* targetMatrixHal;
        const VersionRange* targetMatrixRange;
        std::tie(targetMatrixHal, targetMatrixRange) =
            targetMatrix.getHalWithMajorVersion(package, version.majorVer);
        if (targetMatrixHal == nullptr || targetMatrixRange == nullptr) {
            if (error) {
                *error = package + "@" + to_string(servedVersion) +
                         "is deprecated in compatibility matrix at FCM Version " +
                         to_string(targetMatrix.level()) + "; it should not be served.";
            }
            return true;
        }

        const auto& targetMatrixInstances = targetMatrixHal->getInstances(interface);
        if (targetMatrixInstances.find(instance) == targetMatrixInstances.end()) {
            if (error) {
                *error += package + "@" + to_string(servedVersion) + "::" + interface + "/" +
                          instance + " is deprecated at FCM version " +
                          to_string(targetMatrix.level()) + "; it should be not be served.\n";
            }
            return true;
        }

        // Assuming that targetMatrix requires @x.u-v, require that at least @x.u is served.
        bool targetVersionServed;
        std::tie(targetVersionServed, std::ignore) =
            isInstanceInUse(package, targetMatrixRange->minVer(), interface, instance);

        if (!targetVersionServed) {
            if (error) {
                *error += package + "@" + to_string(servedVersion) + " is deprecated; " +
                          "require at least " + to_string(targetMatrixRange->minVer()) + "\n";
            }
            return true;
        }
    }
    return false;
}

int32_t VintfObject::CheckDeprecation(const IsInstanceInUse& isInstanceInUse,
                                      std::string* error) {
    auto matrixFragments = GetAllFrameworkMatrixLevels(error);
    if (matrixFragments.empty()) {
        if (error && error->empty())
            *error = "Cannot get framework matrix for each FCM version for unknown error.";
        return NAME_NOT_FOUND;
    }
    auto deviceManifest = GetDeviceHalManifest();
    if (deviceManifest == nullptr) {
        if (error) *error = "No device manifest.";
        return NAME_NOT_FOUND;
    }
    Level deviceLevel = deviceManifest->level();
    if (deviceLevel == Level::UNSPECIFIED) {
        if (error) *error = "Device manifest does not specify Shipping FCM Version.";
        return BAD_VALUE;
    }

    const CompatibilityMatrix* targetMatrix = nullptr;
    for (const auto& namedMatrix : matrixFragments) {
        if (namedMatrix.object.level() == deviceLevel) {
            targetMatrix = &namedMatrix.object;
        }
    }
    if (targetMatrix == nullptr) {
        if (error)
            *error = "Cannot find framework matrix at FCM version " + to_string(deviceLevel) + ".";
        return NAME_NOT_FOUND;
    }

    bool hasDeprecatedHals = false;
    for (const auto& namedMatrix : matrixFragments) {
        if (namedMatrix.object.level() == Level::UNSPECIFIED) continue;
        if (namedMatrix.object.level() >= deviceLevel) continue;

        const auto& oldMatrix = namedMatrix.object;
        for (const MatrixHal& hal : oldMatrix.getHals()) {
            hasDeprecatedHals |= isHalDeprecated(hal, *targetMatrix, isInstanceInUse, error);
        }
    }

    return hasDeprecatedHals ? DEPRECATED : NO_DEPRECATED_HALS;
}

int32_t VintfObject::CheckDeprecation(std::string* error) {
    auto deviceManifest = GetDeviceHalManifest();
    IsInstanceInUse inManifest = [&deviceManifest](const std::string& package, Version version,
                                                    const std::string& interface,
                                                    const std::string& instance) {
        const ManifestHal* hal = deviceManifest->getHal(package, version);
        if (hal == nullptr) {
            return std::make_pair(false, Version{});
        }
        const auto& instances = hal->getInstances(interface);
        if (instances.find(instance) == instances.end()) {
            return std::make_pair(false, Version{});
        }

        for (Version v : hal->versions) {
            if (v.minorAtLeast(version)) {
                return std::make_pair(true, v);
            }
        }
        return std::make_pair(false, Version{});
    };
    return CheckDeprecation(inManifest, error);
}

} // namespace vintf
} // namespace android