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 <gmock/gmock.h>
18 #include <gtest/gtest.h>
19 #include <stdio.h>
20 #include <unistd.h>
21 
22 #include <android-base/file.h>
23 #include <android-base/logging.h>
24 #include <android-base/strings.h>
25 #include <hidl-util/FQName.h>
26 
27 #include <vintf/VintfObject.h>
28 #include <vintf/parse_string.h>
29 #include <vintf/parse_xml.h>
30 #include "test_constants.h"
31 #include "utils-fake.h"
32 
33 using namespace ::testing;
34 using namespace std::literals;
35 
36 using android::FqInstance;
37 
38 static AssertionResult In(const std::string& sub, const std::string& str) {
39     return (str.find(sub) != std::string::npos ? AssertionSuccess() : AssertionFailure())
40            << "Value is " << str;
41 }
42 #define EXPECT_IN(sub, str) EXPECT_TRUE(In((sub), (str)))
43 #define EXPECT_NOT_IN(sub, str) EXPECT_FALSE(In((sub), (str)))
44 
45 namespace android {
46 namespace vintf {
47 
48 extern XmlConverter<KernelInfo>& gKernelInfoConverter;
49 
50 namespace testing {
51 
52 using namespace ::android::vintf::details;
53 
54 // clang-format off
55 
56 //
57 // Set of Xml1 metadata compatible with each other.
58 //
59 
60 const std::string systemMatrixXml1 =
61     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\">\n"
62     "    <hal format=\"hidl\" optional=\"false\">\n"
63     "        <name>android.hardware.camera</name>\n"
64     "        <version>2.0-5</version>\n"
65     "        <version>3.4-16</version>\n"
66     "    </hal>\n"
67     "    <hal format=\"hidl\" optional=\"false\">\n"
68     "        <name>android.hardware.nfc</name>\n"
69     "        <version>1.0</version>\n"
70     "        <version>2.0</version>\n"
71     "    </hal>\n"
72     "    <hal format=\"hidl\" optional=\"true\">\n"
73     "        <name>android.hardware.foo</name>\n"
74     "        <version>1.0</version>\n"
75     "    </hal>\n"
76     "    <kernel version=\"3.18.31\"></kernel>\n"
77     "    <sepolicy>\n"
78     "        <kernel-sepolicy-version>30</kernel-sepolicy-version>\n"
79     "        <sepolicy-version>25.5</sepolicy-version>\n"
80     "        <sepolicy-version>26.0-3</sepolicy-version>\n"
81     "    </sepolicy>\n"
82     "    <avb>\n"
83     "        <vbmeta-version>0.0</vbmeta-version>\n"
84     "    </avb>\n"
85     "</compatibility-matrix>\n";
86 
87 const std::string vendorManifestXml1 =
88     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
89     "    <hal format=\"hidl\">\n"
90     "        <name>android.hardware.camera</name>\n"
91     "        <transport>hwbinder</transport>\n"
92     "        <version>3.5</version>\n"
93     "        <interface>\n"
94     "            <name>IBetterCamera</name>\n"
95     "            <instance>camera</instance>\n"
96     "        </interface>\n"
97     "        <interface>\n"
98     "            <name>ICamera</name>\n"
99     "            <instance>default</instance>\n"
100     "            <instance>legacy/0</instance>\n"
101     "        </interface>\n"
102     "    </hal>\n"
103     "    <hal format=\"hidl\">\n"
104     "        <name>android.hardware.nfc</name>\n"
105     "        <transport>hwbinder</transport>\n"
106     "        <version>1.0</version>\n"
107     "        <interface>\n"
108     "            <name>INfc</name>\n"
109     "            <instance>nfc_nci</instance>\n"
110     "        </interface>\n"
111     "    </hal>\n"
112     "    <hal format=\"hidl\">\n"
113     "        <name>android.hardware.nfc</name>\n"
114     "        <transport>hwbinder</transport>\n"
115     "        <version>2.0</version>\n"
116     "        <interface>\n"
117     "            <name>INfc</name>\n"
118     "            <instance>default</instance>\n"
119     "            <instance>nfc_nci</instance>\n"
120     "        </interface>\n"
121     "    </hal>\n"
122     "    <sepolicy>\n"
123     "        <version>25.5</version>\n"
124     "    </sepolicy>\n"
125     "</manifest>\n";
126 
127 const std::string systemManifestXml1 =
128     "<manifest " + kMetaVersionStr + " type=\"framework\">\n"
129     "    <hal format=\"hidl\">\n"
130     "        <name>android.hidl.manager</name>\n"
131     "        <transport>hwbinder</transport>\n"
132     "        <version>1.0</version>\n"
133     "        <interface>\n"
134     "            <name>IServiceManager</name>\n"
135     "            <instance>default</instance>\n"
136     "        </interface>\n"
137     "    </hal>\n"
138     "    <vndk>\n"
139     "        <version>25.0.5</version>\n"
140     "        <library>libbase.so</library>\n"
141     "        <library>libjpeg.so</library>\n"
142     "    </vndk>\n"
143     "</manifest>\n";
144 
145 const std::string vendorMatrixXml1 =
146     "<compatibility-matrix " + kMetaVersionStr + " type=\"device\">\n"
147     "    <hal format=\"hidl\" optional=\"false\">\n"
148     "        <name>android.hidl.manager</name>\n"
149     "        <version>1.0</version>\n"
150     "    </hal>\n"
151     "    <vndk>\n"
152     "        <version>25.0.1-5</version>\n"
153     "        <library>libbase.so</library>\n"
154     "        <library>libjpeg.so</library>\n"
155     "    </vndk>\n"
156     "</compatibility-matrix>\n";
157 
158 //
159 // Set of Xml2 metadata compatible with each other.
160 //
161 
162 const std::string systemMatrixXml2 =
163     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\">\n"
164     "    <hal format=\"hidl\">\n"
165     "        <name>android.hardware.foo</name>\n"
166     "        <version>1.0</version>\n"
167     "    </hal>\n"
168     "    <kernel version=\"3.18.31\"></kernel>\n"
169     "    <sepolicy>\n"
170     "        <kernel-sepolicy-version>30</kernel-sepolicy-version>\n"
171     "        <sepolicy-version>25.5</sepolicy-version>\n"
172     "        <sepolicy-version>26.0-3</sepolicy-version>\n"
173     "    </sepolicy>\n"
174     "    <avb>\n"
175     "        <vbmeta-version>0.0</vbmeta-version>\n"
176     "    </avb>\n"
177     "</compatibility-matrix>\n";
178 
179 const std::string vendorManifestXml2 =
180     "<manifest " + kMetaVersionStr + " type=\"device\">"
181     "    <hal>"
182     "        <name>android.hardware.foo</name>"
183     "        <transport>hwbinder</transport>"
184     "        <version>1.0</version>"
185     "    </hal>"
186     "    <sepolicy>\n"
187     "        <version>25.5</version>\n"
188     "    </sepolicy>\n"
189     "</manifest>";
190 
191 //
192 // Set of framework matrices of different FCM version.
193 //
194 
195 const std::string systemMatrixLevel1 =
196     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
197     "    <hal format=\"hidl\" optional=\"true\">\n"
198     "        <name>android.hardware.major</name>\n"
199     "        <version>1.0</version>\n"
200     "        <interface>\n"
201     "            <name>IMajor</name>\n"
202     "            <instance>default</instance>\n"
203     "        </interface>\n"
204     "    </hal>\n"
205     "    <hal format=\"hidl\" optional=\"true\">\n"
206     "        <name>android.hardware.removed</name>\n"
207     "        <version>1.0</version>\n"
208     "        <interface>\n"
209     "            <name>IRemoved</name>\n"
210     "            <instance>default</instance>\n"
211     "        </interface>\n"
212     "    </hal>\n"
213     "    <hal format=\"hidl\" optional=\"true\">\n"
214     "        <name>android.hardware.minor</name>\n"
215     "        <version>1.0</version>\n"
216     "        <interface>\n"
217     "            <name>IMinor</name>\n"
218     "            <instance>default</instance>\n"
219     "            <instance>legacy</instance>\n"
220     "        </interface>\n"
221     "    </hal>\n"
222     "</compatibility-matrix>\n";
223 
224 const std::string systemMatrixLevel2 =
225     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
226     "    <hal format=\"hidl\" optional=\"true\">\n"
227     "        <name>android.hardware.major</name>\n"
228     "        <version>2.0</version>\n"
229     "        <interface>\n"
230     "            <name>IMajor</name>\n"
231     "            <instance>default</instance>\n"
232     "        </interface>\n"
233     "    </hal>\n"
234     "    <hal format=\"hidl\" optional=\"true\">\n"
235     "        <name>android.hardware.minor</name>\n"
236     "        <version>1.1</version>\n"
237     "        <interface>\n"
238     "            <name>IMinor</name>\n"
239     "            <instance>default</instance>\n"
240     "        </interface>\n"
241     "    </hal>\n"
242     "</compatibility-matrix>\n";
243 
244 //
245 // Set of framework matrices of different FCM version with regex.
246 //
247 
248 const static std::vector<std::string> systemMatrixRegexXmls = {
249     // 1.xml
250     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
251     "    <hal format=\"hidl\" optional=\"false\">\n"
252     "        <name>android.hardware.regex</name>\n"
253     "        <version>1.0-1</version>\n"
254     "        <interface>\n"
255     "            <name>IRegex</name>\n"
256     "            <instance>default</instance>\n"
257     "            <instance>special/1.0</instance>\n"
258     "            <regex-instance>regex/1.0/[0-9]+</regex-instance>\n"
259     "            <regex-instance>regex_common/[0-9]+</regex-instance>\n"
260     "        </interface>\n"
261     "    </hal>\n"
262     "</compatibility-matrix>\n",
263     // 2.xml
264     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
265     "    <hal format=\"hidl\" optional=\"false\">\n"
266     "        <name>android.hardware.regex</name>\n"
267     "        <version>1.1-2</version>\n"
268     "        <interface>\n"
269     "            <name>IRegex</name>\n"
270     "            <instance>default</instance>\n"
271     "            <instance>special/1.1</instance>\n"
272     "            <regex-instance>regex/1.1/[0-9]+</regex-instance>\n"
273     "            <regex-instance>[a-z]+_[a-z]+/[0-9]+</regex-instance>\n"
274     "        </interface>\n"
275     "    </hal>\n"
276     "</compatibility-matrix>\n",
277     // 3.xml
278     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"3\">\n"
279     "    <hal format=\"hidl\" optional=\"false\">\n"
280     "        <name>android.hardware.regex</name>\n"
281     "        <version>2.0</version>\n"
282     "        <interface>\n"
283     "            <name>IRegex</name>\n"
284     "            <instance>default</instance>\n"
285     "            <instance>special/2.0</instance>\n"
286     "            <regex-instance>regex/2.0/[0-9]+</regex-instance>\n"
287     "            <regex-instance>regex_[a-z]+/[0-9]+</regex-instance>\n"
288     "        </interface>\n"
289     "    </hal>\n"
290     "</compatibility-matrix>\n"};
291 
292 //
293 // Set of metadata at different FCM version that has requirements
294 //
295 
296 const std::vector<std::string> systemMatrixRequire = {
297     // 1.xml
298     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
299     "    <hal format=\"hidl\" optional=\"false\">\n"
300     "        <name>android.hardware.foo</name>\n"
301     "        <version>1.0</version>\n"
302     "        <interface>\n"
303     "            <name>IFoo</name>\n"
304     "            <instance>default</instance>\n"
305     "        </interface>\n"
306     "    </hal>\n"
307     "</compatibility-matrix>\n",
308     // 2.xml
309     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
310     "    <hal format=\"hidl\" optional=\"false\">\n"
311     "        <name>android.hardware.bar</name>\n"
312     "        <version>1.0</version>\n"
313     "        <interface>\n"
314     "            <name>IBar</name>\n"
315     "            <instance>default</instance>\n"
316     "        </interface>\n"
317     "    </hal>\n"
318     "</compatibility-matrix>\n"};
319 
320 const std::string vendorManifestRequire1 =
321     "<manifest " + kMetaVersionStr + " type=\"device\" target-level=\"1\">\n"
322     "    <hal format=\"hidl\">\n"
323     "        <name>android.hardware.foo</name>\n"
324     "        <transport>hwbinder</transport>\n"
325     "        <fqname>@1.0::IFoo/default</fqname>\n"
326     "    </hal>\n"
327     "</manifest>\n";
328 
329 const std::string vendorManifestRequire2 =
330     "<manifest " + kMetaVersionStr + " type=\"device\" target-level=\"2\">\n"
331     "    <hal format=\"hidl\">\n"
332     "        <name>android.hardware.bar</name>\n"
333     "        <transport>hwbinder</transport>\n"
334     "        <fqname>@1.0::IBar/default</fqname>\n"
335     "    </hal>\n"
336     "</manifest>\n";
337 
338 //
339 // Set of metadata for kernel requirements
340 //
341 
342 const std::string vendorManifestKernel318 =
343     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
344     "    <kernel version=\"3.18.999\" />\n"
345     "    <sepolicy>\n"
346     "        <version>25.5</version>\n"
347     "    </sepolicy>\n"
348     "</manifest>\n";
349 
350 const std::string systemMatrixKernel318 =
351     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\">\n"
352     "    <kernel version=\"3.18.999\"></kernel>\n"
353     "    <sepolicy>\n"
354     "        <kernel-sepolicy-version>30</kernel-sepolicy-version>\n"
355     "        <sepolicy-version>25.5</sepolicy-version>\n"
356     "    </sepolicy>\n"
357     "</compatibility-matrix>\n";
358 
359 class VintfObjectTestBase : public ::testing::Test {
360    protected:
361     MockFileSystem& fetcher() {
362         return static_cast<MockFileSystem&>(*vintfObject->getFileSystem());
363     }
364     MockPropertyFetcher& propertyFetcher() {
365         return static_cast<MockPropertyFetcher&>(*vintfObject->getPropertyFetcher());
366     }
367 
368     void useEmptyFileSystem() {
369         // By default, no files exist in the file system.
370         // Use EXPECT_CALL because more specific expectation of fetch and listFiles will come along.
371         EXPECT_CALL(fetcher(), listFiles(_, _, _)).Times(AnyNumber())
372             .WillRepeatedly(Return(::android::NAME_NOT_FOUND));
373         EXPECT_CALL(fetcher(), fetch(_, _)).Times(AnyNumber())
374             .WillRepeatedly(Return(::android::NAME_NOT_FOUND));
375     }
376 
377     // Setup the MockFileSystem used by the fetchAllInformation template
378     // so it returns the given metadata info instead of fetching from device.
379     void setupMockFetcher(const std::string& vendorManifestXml, const std::string& systemMatrixXml,
380                           const std::string& systemManifestXml, const std::string& vendorMatrixXml) {
381 
382         useEmptyFileSystem();
383 
384         ON_CALL(fetcher(), fetch(StrEq(kVendorLegacyManifest), _))
385             .WillByDefault(
386                 Invoke([vendorManifestXml](const std::string& path, std::string& fetched) {
387                     (void)path;
388                     fetched = vendorManifestXml;
389                     return 0;
390                 }));
391         ON_CALL(fetcher(), fetch(StrEq(kSystemManifest), _))
392             .WillByDefault(
393                 Invoke([systemManifestXml](const std::string& path, std::string& fetched) {
394                     (void)path;
395                     fetched = systemManifestXml;
396                     return 0;
397                 }));
398         ON_CALL(fetcher(), fetch(StrEq(kVendorLegacyMatrix), _))
399             .WillByDefault(Invoke([vendorMatrixXml](const std::string& path, std::string& fetched) {
400                 (void)path;
401                 fetched = vendorMatrixXml;
402                 return 0;
403             }));
404         ON_CALL(fetcher(), fetch(StrEq(kSystemLegacyMatrix), _))
405             .WillByDefault(Invoke([systemMatrixXml](const std::string& path, std::string& fetched) {
406                 (void)path;
407                 fetched = systemMatrixXml;
408                 return 0;
409             }));
410     }
411 
412     virtual void SetUp() {
413         vintfObject = VintfObject::Builder()
414                           .setFileSystem(std::make_unique<NiceMock<MockFileSystem>>())
415                           .setRuntimeInfoFactory(std::make_unique<NiceMock<MockRuntimeInfoFactory>>(
416                               std::make_shared<NiceMock<MockRuntimeInfo>>()))
417                           .setPropertyFetcher(std::make_unique<NiceMock<MockPropertyFetcher>>())
418                           .build();
419     }
420     virtual void TearDown() {
421         Mock::VerifyAndClear(&fetcher());
422     }
423 
424     void expectVendorManifest(size_t times = 1) {
425         EXPECT_CALL(fetcher(), fetch(StrEq(kVendorLegacyManifest), _)).Times(times);
426     }
427 
428     void expectSystemManifest(size_t times = 1) {
429         EXPECT_CALL(fetcher(), fetch(StrEq(kSystemManifest), _)).Times(times);
430     }
431 
432     void expectVendorMatrix(size_t times = 1) {
433         EXPECT_CALL(fetcher(), fetch(StrEq(kVendorLegacyMatrix), _)).Times(times);
434     }
435 
436     void expectSystemMatrix(size_t times = 1) {
437         EXPECT_CALL(fetcher(), fetch(StrEq(kSystemLegacyMatrix), _)).Times(times);
438     }
439 
440     // Expect that a file exist and should be fetched once.
441     void expectFetch(const std::string& path, const std::string& content) {
442         EXPECT_CALL(fetcher(), fetch(StrEq(path), _))
443             .WillOnce(Invoke([content](const auto&, auto& out) {
444                 out = content;
445                 return ::android::OK;
446             }));
447     }
448 
449     // Expect that a file exist and can be fetched 0 or more times.
450     void expectFetchRepeatedly(const std::string& path, const std::string& content) {
451         EXPECT_CALL(fetcher(), fetch(StrEq(path), _))
452             .Times(AnyNumber())
453             .WillRepeatedly(Invoke([content](const auto&, auto& out) {
454                 out = content;
455                 return ::android::OK;
456             }));
457     }
458 
459     // Expect that the file should never be fetched (whether it exists or not).
460     void expectNeverFetch(const std::string& path) {
461         EXPECT_CALL(fetcher(), fetch(StrEq(path), _)).Times(0);
462     }
463 
464     // Expect that the file does not exist, and can be fetched 0 or more times.
465     template <typename Matcher>
466     void expectFileNotExist(const Matcher& matcher) {
467         EXPECT_CALL(fetcher(), fetch(matcher, _))
468             .Times(AnyNumber())
469             .WillRepeatedly(Return(::android::NAME_NOT_FOUND));
470     }
471 
472     MockRuntimeInfoFactory& runtimeInfoFactory() {
473         return static_cast<MockRuntimeInfoFactory&>(*vintfObject->getRuntimeInfoFactory());
474     }
475 
476     std::unique_ptr<VintfObject> vintfObject;
477 };
478 
479 // Test fixture that provides compatible metadata from the mock device.
480 class VintfObjectCompatibleTest : public VintfObjectTestBase {
481    protected:
482     virtual void SetUp() {
483         VintfObjectTestBase::SetUp();
484         setupMockFetcher(vendorManifestXml1, systemMatrixXml1, systemManifestXml1, vendorMatrixXml1);
485     }
486 };
487 
488 // Tests that local info is checked.
489 TEST_F(VintfObjectCompatibleTest, TestDeviceCompatibility) {
490     std::string error;
491 
492     expectVendorManifest();
493     expectSystemManifest();
494     expectVendorMatrix();
495     expectSystemMatrix();
496 
497     int result = vintfObject->checkCompatibility(&error);
498 
499     ASSERT_EQ(result, 0) << "Fail message:" << error.c_str();
500     // Check that nothing was ignored.
501     ASSERT_STREQ(error.c_str(), "");
502 }
503 
504 // Test fixture that provides incompatible metadata from the mock device.
505 class VintfObjectIncompatibleTest : public VintfObjectTestBase {
506    protected:
507     virtual void SetUp() {
508         VintfObjectTestBase::SetUp();
509         setupMockFetcher(vendorManifestXml1, systemMatrixXml2, systemManifestXml1, vendorMatrixXml1);
510     }
511 };
512 
513 // Fetch all metadata from device and ensure that it fails.
514 TEST_F(VintfObjectIncompatibleTest, TestDeviceCompatibility) {
515     std::string error;
516 
517     expectVendorManifest();
518     expectSystemManifest();
519     expectVendorMatrix();
520     expectSystemMatrix();
521 
522     int result = vintfObject->checkCompatibility(&error);
523 
524     ASSERT_EQ(result, 1) << "Should have failed:" << error.c_str();
525 }
526 
527 const std::string vendorManifestKernelFcm =
528         "<manifest " + kMetaVersionStr + " type=\"device\">\n"
529         "    <kernel version=\"3.18.999\" target-level=\"92\"/>\n"
530         "</manifest>\n";
531 
532 // Test fixture that provides compatible metadata from the mock device.
533 class VintfObjectRuntimeInfoTest : public VintfObjectTestBase {
534    protected:
535     virtual void SetUp() {
536         VintfObjectTestBase::SetUp();
537         setupMockFetcher(vendorManifestKernelFcm, "", "", "");
538         expectVendorManifest();
539     }
540     virtual void TearDown() {
541         Mock::VerifyAndClear(&runtimeInfoFactory());
542         Mock::VerifyAndClear(runtimeInfoFactory().getInfo().get());
543     }
544 };
545 
546 TEST_F(VintfObjectRuntimeInfoTest, GetRuntimeInfo) {
547     // RuntimeInfo.fetchAllInformation is never called with KERNEL_FCM set.
548     auto allExceptKernelFcm = RuntimeInfo::FetchFlag::ALL & ~RuntimeInfo::FetchFlag::KERNEL_FCM;
549 
550     InSequence s;
551 
552     EXPECT_CALL(*runtimeInfoFactory().getInfo(),
553                 fetchAllInformation(RuntimeInfo::FetchFlag::CPU_VERSION));
554     EXPECT_CALL(*runtimeInfoFactory().getInfo(), fetchAllInformation(RuntimeInfo::FetchFlag::NONE));
555     EXPECT_CALL(*runtimeInfoFactory().getInfo(),
556                 fetchAllInformation(RuntimeInfo::FetchFlag::CPU_VERSION));
557     EXPECT_CALL(
558         *runtimeInfoFactory().getInfo(),
559         fetchAllInformation(allExceptKernelFcm & ~RuntimeInfo::FetchFlag::CPU_VERSION));
560     EXPECT_CALL(*runtimeInfoFactory().getInfo(), fetchAllInformation(allExceptKernelFcm));
561     EXPECT_CALL(*runtimeInfoFactory().getInfo(), fetchAllInformation(RuntimeInfo::FetchFlag::NONE));
562 
563     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(false /* skipCache */,
564                                                    RuntimeInfo::FetchFlag::CPU_VERSION));
565     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(false /* skipCache */,
566                                                    RuntimeInfo::FetchFlag::CPU_VERSION));
567     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(true /* skipCache */,
568                                                    RuntimeInfo::FetchFlag::CPU_VERSION));
569     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(false /* skipCache */,
570                                                    RuntimeInfo::FetchFlag::ALL));
571     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(true /* skipCache */,
572                                                    RuntimeInfo::FetchFlag::ALL));
573     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(false /* skipCache */,
574                                                    RuntimeInfo::FetchFlag::ALL));
575 }
576 
577 TEST_F(VintfObjectRuntimeInfoTest, GetRuntimeInfoKernelFcm) {
578     ASSERT_EQ(Level{92}, vintfObject->getKernelLevel());
579 }
580 
581 // Test fixture that provides incompatible metadata from the mock device.
582 class VintfObjectTest : public VintfObjectTestBase {
583    protected:
584     virtual void SetUp() {
585         VintfObjectTestBase::SetUp();
586         useEmptyFileSystem();
587     }
588 };
589 
590 // Test framework compatibility matrix is combined at runtime
591 TEST_F(VintfObjectTest, FrameworkCompatibilityMatrixCombine) {
592     EXPECT_CALL(fetcher(), listFiles(StrEq(kSystemVintfDir), _, _))
593         .WillOnce(Invoke([](const auto&, auto* out, auto*) {
594             *out = {
595                 "compatibility_matrix.1.xml",
596                 "compatibility_matrix.empty.xml",
597             };
598             return ::android::OK;
599         }));
600     expectFetch(kSystemVintfDir + "compatibility_matrix.1.xml",
601                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\"/>");
602     expectFetch(kSystemVintfDir + "compatibility_matrix.empty.xml",
603                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\"/>");
604     expectFileNotExist(StrEq(kProductMatrix));
605     expectFetch(kVendorManifest, "<manifest " + kMetaVersionStr + " type=\"device\" />\n");
606     expectNeverFetch(kSystemLegacyMatrix);
607 
608     EXPECT_NE(nullptr, vintfObject->getFrameworkCompatibilityMatrix(true /* skipCache */));
609 }
610 
611 // Test product compatibility matrix is fetched
612 TEST_F(VintfObjectTest, ProductCompatibilityMatrix) {
613     EXPECT_CALL(fetcher(), listFiles(StrEq(kSystemVintfDir), _, _))
614         .WillOnce(Invoke([](const auto&, auto* out, auto*) {
615             *out = {
616                 "compatibility_matrix.1.xml",
617                 "compatibility_matrix.empty.xml",
618             };
619             return ::android::OK;
620         }));
621     EXPECT_CALL(fetcher(), listFiles(StrEq(kProductVintfDir), _, _))
622         .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
623             *out = {android::base::Basename(kProductMatrix)};
624             return ::android::OK;
625         }));
626     expectFetch(kSystemVintfDir + "compatibility_matrix.1.xml",
627                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\"/>");
628     expectFetch(kSystemVintfDir + "compatibility_matrix.empty.xml",
629                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\"/>");
630     expectFetch(kProductMatrix,
631                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\">\n"
632                 "    <hal format=\"hidl\" optional=\"true\">\n"
633                 "        <name>android.hardware.foo</name>\n"
634                 "        <version>1.0</version>\n"
635                 "        <interface>\n"
636                 "            <name>IFoo</name>\n"
637                 "            <instance>default</instance>\n"
638                 "        </interface>\n"
639                 "    </hal>\n"
640                 "</compatibility-matrix>\n");
641     expectFetch(kVendorManifest, "<manifest " + kMetaVersionStr + " type=\"device\" />\n");
642     expectNeverFetch(kSystemLegacyMatrix);
643 
644     auto fcm = vintfObject->getFrameworkCompatibilityMatrix(true /* skipCache */);
645     ASSERT_NE(nullptr, fcm);
646 
647     FqInstance expectInstance;
648     EXPECT_TRUE(expectInstance.setTo("[email protected]::IFoo/default"));
649     bool found = false;
650     fcm->forEachHidlInstance([&found, &expectInstance](const auto& matrixInstance) {
651         found |= matrixInstance.isSatisfiedBy(expectInstance);
652         return !found;  // continue if not found
653     });
654     EXPECT_TRUE(found) << "[email protected]::IFoo/default should be found in matrix:\n"
655                        << gCompatibilityMatrixConverter(*fcm);
656 }
657 
658 const std::string vendorEtcManifest =
659     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
660     "    <hal format=\"hidl\">\n"
661     "        <name>android.hardware.foo</name>\n"
662     "        <transport>hwbinder</transport>\n"
663     "        <version>1.0</version>\n"
664     "        <version>2.0</version>\n"
665     "        <interface>\n"
666     "            <name>IVendorEtc</name>\n"
667     "            <instance>default</instance>\n"
668     "        </interface>\n"
669     "    </hal>\n"
670     "</manifest>\n";
671 
672 const std::string vendorManifest =
673     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
674     "    <hal format=\"hidl\">\n"
675     "        <name>android.hardware.foo</name>\n"
676     "        <transport>hwbinder</transport>\n"
677     "        <version>1.0</version>\n"
678     "        <interface>\n"
679     "            <name>IVendor</name>\n"
680     "            <instance>default</instance>\n"
681     "        </interface>\n"
682     "    </hal>\n"
683     "</manifest>\n";
684 
685 const std::string odmProductManifest =
686     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
687     "    <hal format=\"hidl\" override=\"true\">\n"
688     "        <name>android.hardware.foo</name>\n"
689     "        <transport>hwbinder</transport>\n"
690     "        <version>1.1</version>\n"
691     "        <interface>\n"
692     "            <name>IOdmProduct</name>\n"
693     "            <instance>default</instance>\n"
694     "        </interface>\n"
695     "    </hal>\n"
696     "</manifest>\n";
697 
698 const std::string odmManifest =
699     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
700     "    <hal format=\"hidl\" override=\"true\">\n"
701     "        <name>android.hardware.foo</name>\n"
702     "        <transport>hwbinder</transport>\n"
703     "        <version>1.1</version>\n"
704     "        <interface>\n"
705     "            <name>IOdm</name>\n"
706     "            <instance>default</instance>\n"
707     "        </interface>\n"
708     "    </hal>\n"
709     "</manifest>\n";
710 
711 bool containsVendorManifest(const std::shared_ptr<const HalManifest>& p) {
712     return !p->getHidlInstances("android.hardware.foo", {1, 0}, "IVendor").empty();
713 }
714 
715 bool containsVendorEtcManifest(const std::shared_ptr<const HalManifest>& p) {
716     return !p->getHidlInstances("android.hardware.foo", {2, 0}, "IVendorEtc").empty();
717 }
718 
719 bool vendorEtcManifestOverridden(const std::shared_ptr<const HalManifest>& p) {
720     return p->getHidlInstances("android.hardware.foo", {1, 0}, "IVendorEtc").empty();
721 }
722 
723 bool containsOdmManifest(const std::shared_ptr<const HalManifest>& p) {
724     return !p->getHidlInstances("android.hardware.foo", {1, 1}, "IOdm").empty();
725 }
726 
727 bool containsOdmProductManifest(const std::shared_ptr<const HalManifest>& p) {
728     return !p->getHidlInstances("android.hardware.foo", {1, 1}, "IOdmProduct").empty();
729 }
730 
731 class DeviceManifestTest : public VintfObjectTestBase {
732    protected:
733     // Expect that /vendor/etc/vintf/manifest.xml is fetched.
734     void expectVendorManifest() { expectFetch(kVendorManifest, vendorEtcManifest); }
735     // /vendor/etc/vintf/manifest.xml does not exist.
736     void noVendorManifest() { expectFileNotExist(StrEq(kVendorManifest)); }
737     // Expect some ODM manifest is fetched.
738     void expectOdmManifest() {
739         expectFetch(kOdmManifest, odmManifest);
740     }
741     void noOdmManifest() { expectFileNotExist(StartsWith("/odm/")); }
742     std::shared_ptr<const HalManifest> get() {
743         return vintfObject->getDeviceHalManifest(true /* skipCache */);
744     }
745 };
746 
747 // Test /vendor/etc/vintf/manifest.xml + ODM manifest
748 TEST_F(DeviceManifestTest, Combine1) {
749     expectVendorManifest();
750     expectOdmManifest();
751     auto p = get();
752     ASSERT_NE(nullptr, p);
753     EXPECT_TRUE(containsVendorEtcManifest(p));
754     EXPECT_TRUE(vendorEtcManifestOverridden(p));
755     EXPECT_TRUE(containsOdmManifest(p));
756     EXPECT_FALSE(containsVendorManifest(p));
757 }
758 
759 // Test /vendor/etc/vintf/manifest.xml
760 TEST_F(DeviceManifestTest, Combine2) {
761     expectVendorManifest();
762     noOdmManifest();
763     auto p = get();
764     ASSERT_NE(nullptr, p);
765     EXPECT_TRUE(containsVendorEtcManifest(p));
766     EXPECT_FALSE(vendorEtcManifestOverridden(p));
767     EXPECT_FALSE(containsOdmManifest(p));
768     EXPECT_FALSE(containsVendorManifest(p));
769 }
770 
771 // Test ODM manifest
772 TEST_F(DeviceManifestTest, Combine3) {
773     noVendorManifest();
774     expectOdmManifest();
775     auto p = get();
776     ASSERT_NE(nullptr, p);
777     EXPECT_FALSE(containsVendorEtcManifest(p));
778     EXPECT_TRUE(vendorEtcManifestOverridden(p));
779     EXPECT_TRUE(containsOdmManifest(p));
780     EXPECT_FALSE(containsVendorManifest(p));
781 }
782 
783 // Test /vendor/manifest.xml
784 TEST_F(DeviceManifestTest, Combine4) {
785     noVendorManifest();
786     noOdmManifest();
787     expectFetch(kVendorLegacyManifest, vendorManifest);
788     auto p = get();
789     ASSERT_NE(nullptr, p);
790     EXPECT_FALSE(containsVendorEtcManifest(p));
791     EXPECT_TRUE(vendorEtcManifestOverridden(p));
792     EXPECT_FALSE(containsOdmManifest(p));
793     EXPECT_TRUE(containsVendorManifest(p));
794 }
795 
796 class OdmManifestTest : public VintfObjectTestBase,
797                          public ::testing::WithParamInterface<const char*> {
798    protected:
799     virtual void SetUp() override {
800         VintfObjectTestBase::SetUp();
801         // Assume /vendor/etc/vintf/manifest.xml does not exist to simplify
802         // testing logic.
803         expectFileNotExist(StrEq(kVendorManifest));
804         // Expect that the legacy /vendor/manifest.xml is never fetched.
805         expectNeverFetch(kVendorLegacyManifest);
806         // Assume no files exist under /odm/ unless otherwise specified.
807         expectFileNotExist(StartsWith("/odm/"));
808 
809         // set SKU
810         productModel = GetParam();
811         ON_CALL(propertyFetcher(), getProperty("ro.boot.product.hardware.sku", _))
812             .WillByDefault(Return(productModel));
813     }
814     std::shared_ptr<const HalManifest> get() {
815         return vintfObject->getDeviceHalManifest(true /* skipCache */);
816     }
817     std::string productModel;
818 };
819 
820 TEST_P(OdmManifestTest, OdmProductManifest) {
821     if (productModel.empty()) return;
822     expectFetch(kOdmVintfDir + "manifest_" + productModel + ".xml", odmProductManifest);
823     // /odm/etc/vintf/manifest.xml should not be fetched when the product variant exists.
824     expectNeverFetch(kOdmManifest);
825     auto p = get();
826     ASSERT_NE(nullptr, p);
827     EXPECT_TRUE(containsOdmProductManifest(p));
828 }
829 
830 TEST_P(OdmManifestTest, OdmManifest) {
831     expectFetch(kOdmManifest, odmManifest);
832     auto p = get();
833     ASSERT_NE(nullptr, p);
834     EXPECT_TRUE(containsOdmManifest(p));
835 }
836 
837 TEST_P(OdmManifestTest, OdmLegacyProductManifest) {
838     if (productModel.empty()) return;
839     expectFetch(kOdmLegacyVintfDir + "manifest_" + productModel + ".xml", odmProductManifest);
840     // /odm/manifest.xml should not be fetched when the product variant exists.
841     expectNeverFetch(kOdmLegacyManifest);
842     auto p = get();
843     ASSERT_NE(nullptr, p);
844     EXPECT_TRUE(containsOdmProductManifest(p));
845 }
846 
847 TEST_P(OdmManifestTest, OdmLegacyManifest) {
848     expectFetch(kOdmLegacyManifest, odmManifest);
849     auto p = get();
850     ASSERT_NE(nullptr, p);
851     EXPECT_TRUE(containsOdmManifest(p));
852 }
853 
854 INSTANTIATE_TEST_SUITE_P(OdmManifest, OdmManifestTest, ::testing::Values("", "fake_sku"));
855 
856 struct CheckedFqInstance : FqInstance {
857     CheckedFqInstance(const char* s) : CheckedFqInstance(std::string(s)) {}
858     CheckedFqInstance(const std::string& s) { CHECK(setTo(s)) << s; }
859 
860     Version getVersion() const { return FqInstance::getVersion(); }
861 };
862 
863 static VintfObject::ListInstances getInstanceListFunc(
864     const std::vector<CheckedFqInstance>& instances) {
865     return [instances](const std::string& package, Version version, const std::string& interface,
866                        const auto& /* instanceHint */) {
867         std::vector<std::pair<std::string, Version>> ret;
868         for (auto&& existing : instances) {
869             if (existing.getPackage() == package && existing.getVersion().minorAtLeast(version) &&
870                 existing.getInterface() == interface) {
871                 ret.push_back(std::make_pair(existing.getInstance(), existing.getVersion()));
872             }
873         }
874 
875         return ret;
876     };
877 }
878 
879 class DeprecateTest : public VintfObjectTestBase {
880    protected:
881     virtual void SetUp() override {
882         VintfObjectTestBase::SetUp();
883         useEmptyFileSystem();
884         EXPECT_CALL(fetcher(), listFiles(StrEq(kSystemVintfDir), _, _))
885             .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
886                 *out = {
887                     "compatibility_matrix.1.xml",
888                     "compatibility_matrix.2.xml",
889                 };
890                 return ::android::OK;
891             }));
892         expectFetchRepeatedly(kSystemVintfDir + "compatibility_matrix.1.xml", systemMatrixLevel1);
893         expectFetchRepeatedly(kSystemVintfDir + "compatibility_matrix.2.xml", systemMatrixLevel2);
894         expectFileNotExist(StrEq(kProductMatrix));
895         expectNeverFetch(kSystemLegacyMatrix);
896 
897         expectFetchRepeatedly(kVendorManifest,
898                     "<manifest " + kMetaVersionStr + " type=\"device\" target-level=\"2\"/>");
899         expectFileNotExist(StartsWith("/odm/"));
900 
901         // Update the device manifest cache because CheckDeprecate does not fetch
902         // device manifest again if cache exist.
903         vintfObject->getDeviceHalManifest(true /* skipCache */);
904     }
905 
906 };
907 
908 TEST_F(DeprecateTest, CheckNoDeprecate) {
909     auto pred = getInstanceListFunc({
910         "[email protected]::IMinor/default",
911         "[email protected]::IMajor/default",
912     });
913     std::string error;
914     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation(pred, {}, &error)) << error;
915 }
916 
917 TEST_F(DeprecateTest, CheckRemoved) {
918     auto pred = getInstanceListFunc({
919         "[email protected]::IRemoved/default",
920         "[email protected]::IMinor/default",
921         "[email protected]::IMajor/default",
922     });
923     std::string error;
924     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
925         << "[email protected] should be deprecated. " << error;
926 }
927 
928 TEST_F(DeprecateTest, CheckMinor) {
929     auto pred = getInstanceListFunc({
930         "[email protected]::IMinor/default",
931         "[email protected]::IMajor/default",
932     });
933     std::string error;
934     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
935         << "[email protected] should be deprecated. " << error;
936 }
937 
938 TEST_F(DeprecateTest, CheckMinorDeprecatedInstance1) {
939     auto pred = getInstanceListFunc({
940         "[email protected]::IMinor/legacy",
941         "[email protected]::IMinor/default",
942         "[email protected]::IMajor/default",
943     });
944     std::string error;
945     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
946         << "[email protected]::IMinor/legacy should be deprecated. " << error;
947 }
948 
949 TEST_F(DeprecateTest, CheckMinorDeprecatedInstance2) {
950     auto pred = getInstanceListFunc({
951         "[email protected]::IMinor/default",
952         "[email protected]::IMinor/legacy",
953         "[email protected]::IMajor/default",
954     });
955     std::string error;
956     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
957         << "[email protected]::IMinor/legacy should be deprecated. " << error;
958 }
959 
960 TEST_F(DeprecateTest, CheckMajor1) {
961     auto pred = getInstanceListFunc({
962         "[email protected]::IMinor/default",
963         "[email protected]::IMajor/default",
964         "[email protected]::IMajor/default",
965     });
966     std::string error;
967     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
968         << "[email protected] should be deprecated. " << error;
969 }
970 
971 TEST_F(DeprecateTest, CheckMajor2) {
972     auto pred = getInstanceListFunc({
973         "[email protected]::IMinor/default",
974         "[email protected]::IMajor/default",
975     });
976     std::string error;
977     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
978         << "[email protected] should be deprecated. " << error;
979 }
980 
981 TEST_F(DeprecateTest, HidlMetadataNotDeprecate) {
982     auto pred = getInstanceListFunc({
983         "[email protected]::IMajor/default",
984         "[email protected]::IMajor/default",
985     });
986     std::string error;
987     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
988         << "[email protected] should be deprecated. " << error;
989     std::vector<HidlInterfaceMetadata> hidlMetadata{
990       {"[email protected]::IMajor", {"[email protected]::IMajor"}},
991     };
992     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation(pred, hidlMetadata, &error))
993         << "[email protected] should not be deprecated because it extends from 2.0: " << error;
994 }
995 
996 TEST_F(DeprecateTest, HidlMetadataDeprecate) {
997     auto pred = getInstanceListFunc({
998         "[email protected]::IMajor/default",
999     });
1000     std::string error;
1001     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
1002         << "[email protected] should be deprecated. " << error;
1003     std::vector<HidlInterfaceMetadata> hidlMetadata{
1004       {"[email protected]::IMajor", {"[email protected]::IMajor"}},
1005     };
1006     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, hidlMetadata, &error))
1007         << "[email protected] should be deprecated. " << error;
1008 }
1009 
1010 class MultiMatrixTest : public VintfObjectTestBase {
1011    protected:
1012     void SetUp() override {
1013         VintfObjectTestBase::SetUp();
1014         useEmptyFileSystem();
1015     }
1016     static std::string getFileName(size_t i) {
1017         return "compatibility_matrix." + std::to_string(static_cast<Level>(i)) + ".xml";
1018     }
1019     void SetUpMockSystemMatrices(const std::vector<std::string>& xmls) {
1020         SetUpMockMatrices(kSystemVintfDir, xmls);
1021     }
1022     void SetUpMockMatrices(const std::string& dir, const std::vector<std::string>& xmls) {
1023         EXPECT_CALL(fetcher(), listFiles(StrEq(dir), _, _))
1024             .WillRepeatedly(Invoke([=](const auto&, auto* out, auto*) {
1025                 size_t i = 1;
1026                 for (const auto& content : xmls) {
1027                     (void)content;
1028                     out->push_back(getFileName(i));
1029                     ++i;
1030                 }
1031                 return ::android::OK;
1032             }));
1033         size_t i = 1;
1034         for (const auto& content : xmls) {
1035             expectFetchRepeatedly(dir + getFileName(i), content);
1036             ++i;
1037         }
1038     }
1039     void expectTargetFcmVersion(size_t level) {
1040         expectFetch(kVendorManifest, "<manifest " + kMetaVersionStr + " type=\"device\" target-level=\"" +
1041                                          to_string(static_cast<Level>(level)) + "\"/>");
1042         vintfObject->getDeviceHalManifest(true /* skipCache */);
1043     }
1044 };
1045 
1046 class RegexTest : public MultiMatrixTest {
1047    protected:
1048     virtual void SetUp() {
1049         MultiMatrixTest::SetUp();
1050         SetUpMockSystemMatrices(systemMatrixRegexXmls);
1051     }
1052 };
1053 
1054 TEST_F(RegexTest, CombineLevel1) {
1055     expectTargetFcmVersion(1);
1056     auto matrix = vintfObject->getFrameworkCompatibilityMatrix(true /* skipCache */);
1057     ASSERT_NE(nullptr, matrix);
1058     std::string xml = gCompatibilityMatrixConverter(*matrix);
1059 
1060     EXPECT_IN(
1061         "    <hal format=\"hidl\" optional=\"false\">\n"
1062         "        <name>android.hardware.regex</name>\n"
1063         "        <version>1.0-2</version>\n"
1064         "        <version>2.0</version>\n"
1065         "        <interface>\n"
1066         "            <name>IRegex</name>\n"
1067         "            <instance>default</instance>\n"
1068         "        </interface>\n"
1069         "    </hal>\n",
1070         xml);
1071     EXPECT_IN(
1072         "    <hal format=\"hidl\" optional=\"false\">\n"
1073         "        <name>android.hardware.regex</name>\n"
1074         "        <version>1.0-1</version>\n"
1075         "        <interface>\n"
1076         "            <name>IRegex</name>\n"
1077         "            <instance>special/1.0</instance>\n"
1078         "            <regex-instance>regex/1.0/[0-9]+</regex-instance>\n"
1079         "            <regex-instance>regex_common/[0-9]+</regex-instance>\n"
1080         "        </interface>\n"
1081         "    </hal>\n",
1082         xml);
1083     EXPECT_IN(
1084         "    <hal format=\"hidl\" optional=\"true\">\n"
1085         "        <name>android.hardware.regex</name>\n"
1086         "        <version>1.1-2</version>\n"
1087         "        <interface>\n"
1088         "            <name>IRegex</name>\n"
1089         "            <instance>special/1.1</instance>\n"
1090         "            <regex-instance>[a-z]+_[a-z]+/[0-9]+</regex-instance>\n"
1091         "            <regex-instance>regex/1.1/[0-9]+</regex-instance>\n"
1092         "        </interface>\n"
1093         "    </hal>\n",
1094         xml);
1095     EXPECT_IN(
1096         "    <hal format=\"hidl\" optional=\"true\">\n"
1097         "        <name>android.hardware.regex</name>\n"
1098         "        <version>2.0</version>\n"
1099         "        <interface>\n"
1100         "            <name>IRegex</name>\n"
1101         "            <instance>special/2.0</instance>\n"
1102         "            <regex-instance>regex/2.0/[0-9]+</regex-instance>\n"
1103         "            <regex-instance>regex_[a-z]+/[0-9]+</regex-instance>\n"
1104         "        </interface>\n"
1105         "    </hal>\n",
1106         xml);
1107 }
1108 
1109 TEST_F(RegexTest, CombineLevel2) {
1110     expectTargetFcmVersion(2);
1111     auto matrix = vintfObject->getFrameworkCompatibilityMatrix(true /* skipCache */);
1112     ASSERT_NE(nullptr, matrix);
1113     std::string xml = gCompatibilityMatrixConverter(*matrix);
1114 
1115     EXPECT_IN(
1116         "    <hal format=\"hidl\" optional=\"false\">\n"
1117         "        <name>android.hardware.regex</name>\n"
1118         "        <version>1.1-2</version>\n"
1119         "        <version>2.0</version>\n"
1120         "        <interface>\n"
1121         "            <name>IRegex</name>\n"
1122         "            <instance>default</instance>\n"
1123         "        </interface>\n"
1124         "    </hal>\n",
1125         xml);
1126     EXPECT_IN(
1127         "    <hal format=\"hidl\" optional=\"false\">\n"
1128         "        <name>android.hardware.regex</name>\n"
1129         "        <version>1.1-2</version>\n"
1130         "        <interface>\n"
1131         "            <name>IRegex</name>\n"
1132         "            <instance>special/1.1</instance>\n"
1133         "            <regex-instance>[a-z]+_[a-z]+/[0-9]+</regex-instance>\n"
1134         "            <regex-instance>regex/1.1/[0-9]+</regex-instance>\n"
1135         "        </interface>\n"
1136         "    </hal>\n",
1137         xml);
1138     EXPECT_IN(
1139         "    <hal format=\"hidl\" optional=\"true\">\n"
1140         "        <name>android.hardware.regex</name>\n"
1141         "        <version>2.0</version>\n"
1142         "        <interface>\n"
1143         "            <name>IRegex</name>\n"
1144         "            <instance>special/2.0</instance>\n"
1145         "            <regex-instance>regex/2.0/[0-9]+</regex-instance>\n"
1146         "            <regex-instance>regex_[a-z]+/[0-9]+</regex-instance>\n"
1147         "        </interface>\n"
1148         "    </hal>\n",
1149         xml);
1150 }
1151 
1152 TEST_F(RegexTest, DeprecateLevel2) {
1153     std::string error;
1154     expectTargetFcmVersion(2);
1155 
1156     auto pred = getInstanceListFunc({
1157         "[email protected]::IRegex/default",
1158         "[email protected]::IRegex/special/1.1",
1159         "[email protected]::IRegex/regex/1.1/1",
1160         "[email protected]::IRegex/regex_common/0",
1161         "[email protected]::IRegex/default",
1162     });
1163     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation(pred, {}, &error)) << error;
1164 
1165     for (const auto& deprecated : {
1166              "[email protected]::IRegex/default",
1167              "[email protected]::IRegex/special/1.0",
1168              "[email protected]::IRegex/regex/1.0/1",
1169              "[email protected]::IRegex/regex_common/0",
1170              "[email protected]::IRegex/special/1.0",
1171              "[email protected]::IRegex/regex/1.0/1",
1172          }) {
1173         // 2.0/default ensures compatibility.
1174         pred = getInstanceListFunc({
1175             deprecated,
1176             "[email protected]::IRegex/default",
1177         });
1178         error.clear();
1179         EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
1180             << deprecated << " should be deprecated. " << error;
1181     }
1182 }
1183 
1184 TEST_F(RegexTest, DeprecateLevel3) {
1185     std::string error;
1186     expectTargetFcmVersion(3);
1187 
1188     auto pred = getInstanceListFunc({
1189         "[email protected]::IRegex/special/2.0",
1190         "[email protected]::IRegex/regex/2.0/1",
1191         "[email protected]::IRegex/default",
1192     });
1193     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation(pred, {}, &error)) << error;
1194 
1195     for (const auto& deprecated : {
1196              "[email protected]::IRegex/default",
1197              "[email protected]::IRegex/special/1.0",
1198              "[email protected]::IRegex/regex/1.0/1",
1199              "[email protected]::IRegex/regex_common/0",
1200              "[email protected]::IRegex/special/1.0",
1201              "[email protected]::IRegex/regex/1.0/1",
1202              "[email protected]::IRegex/special/1.1",
1203              "[email protected]::IRegex/regex/1.1/1",
1204              "[email protected]::IRegex/regex_common/0",
1205          }) {
1206         // 2.0/default ensures compatibility.
1207         pred = getInstanceListFunc({
1208             deprecated,
1209             "[email protected]::IRegex/default",
1210         });
1211 
1212         error.clear();
1213         EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(pred, {}, &error))
1214             << deprecated << " should be deprecated.";
1215     }
1216 }
1217 
1218 //
1219 // Set of framework matrices of different FCM version with <kernel>.
1220 //
1221 
1222 #define FAKE_KERNEL(__version__, __key__, __level__)                   \
1223     "    <kernel version=\"" __version__ "\" level=\"" #__level__ "\">\n"            \
1224     "        <config>\n"                                    \
1225     "            <key>CONFIG_" __key__ "</key>\n"           \
1226     "            <value type=\"tristate\">y</value>\n"      \
1227     "        </config>\n"                                   \
1228     "    </kernel>\n"
1229 
1230 const static std::vector<std::string> systemMatrixKernelXmls = {
1231     // 1.xml
1232     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
1233     FAKE_KERNEL("1.0.0", "A1", 1)
1234     FAKE_KERNEL("2.0.0", "B1", 1)
1235     "</compatibility-matrix>\n",
1236     // 2.xml
1237     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
1238     FAKE_KERNEL("2.0.0", "B2", 2)
1239     FAKE_KERNEL("3.0.0", "C2", 2)
1240     FAKE_KERNEL("4.0.0", "D2", 2)
1241     "</compatibility-matrix>\n",
1242     // 3.xml
1243     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"3\">\n"
1244     FAKE_KERNEL("4.0.0", "D3", 3)
1245     FAKE_KERNEL("5.0.0", "E3", 3)
1246     "</compatibility-matrix>\n",
1247     // 4.xml
1248     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"4\">\n"
1249     FAKE_KERNEL("5.0.0", "E4", 4)
1250     FAKE_KERNEL("6.0.0", "F4", 4)
1251     "</compatibility-matrix>\n",
1252     // 5.xml
1253     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"5\">\n"
1254     FAKE_KERNEL("6.0.0", "F5", 5)
1255     FAKE_KERNEL("7.0.0", "G5", 5)
1256     "</compatibility-matrix>\n",
1257 };
1258 
1259 class KernelTest : public MultiMatrixTest {
1260    public:
1261     void expectKernelFcmVersion(size_t targetFcm, Level kernelFcm) {
1262         std::string xml = "<manifest " + kMetaVersionStr + " type=\"device\" target-level=\"" +
1263                           to_string(static_cast<Level>(targetFcm)) + "\">\n";
1264         if (kernelFcm != Level::UNSPECIFIED) {
1265             xml += "    <kernel target-level=\"" + to_string(kernelFcm) + "\"/>\n";
1266         }
1267         xml += "</manifest>";
1268         expectFetch(kVendorManifest, xml);
1269     }
1270 };
1271 
1272 // Assume that we are developing level 2. Test that old <kernel> requirements should
1273 // not change and new <kernel> versions are added.
1274 TEST_F(KernelTest, Level1AndLevel2) {
1275     SetUpMockSystemMatrices({systemMatrixKernelXmls[0], systemMatrixKernelXmls[1]});
1276 
1277     expectTargetFcmVersion(1);
1278     auto matrix = vintfObject->getFrameworkCompatibilityMatrix(true /* skipCache */);
1279     ASSERT_NE(nullptr, matrix);
1280     std::string xml = gCompatibilityMatrixConverter(*matrix);
1281 
1282     EXPECT_IN(FAKE_KERNEL("1.0.0", "A1", 1), xml) << "\nOld requirements must not change.";
1283     EXPECT_IN(FAKE_KERNEL("2.0.0", "B1", 1), xml) << "\nOld requirements must not change.";
1284     EXPECT_IN(FAKE_KERNEL("3.0.0", "C2", 2), xml) << "\nShould see <kernel> from new matrices";
1285     EXPECT_IN(FAKE_KERNEL("4.0.0", "D2", 2), xml) << "\nShould see <kernel> from new matrices";
1286 
1287     EXPECT_IN(FAKE_KERNEL("2.0.0", "B2", 2), xml) << "\nShould see <kernel> from new matrices";
1288 }
1289 
1290 // Assume that we are developing level 3. Test that old <kernel> requirements should
1291 // not change and new <kernel> versions are added.
1292 TEST_F(KernelTest, Level1AndMore) {
1293     SetUpMockSystemMatrices({systemMatrixKernelXmls});
1294 
1295     expectTargetFcmVersion(1);
1296     auto matrix = vintfObject->getFrameworkCompatibilityMatrix(true /* skipCache */);
1297     ASSERT_NE(nullptr, matrix);
1298     std::string xml = gCompatibilityMatrixConverter(*matrix);
1299 
1300     EXPECT_IN(FAKE_KERNEL("1.0.0", "A1", 1), xml) << "\nOld requirements must not change.";
1301     EXPECT_IN(FAKE_KERNEL("2.0.0", "B1", 1), xml) << "\nOld requirements must not change.";
1302     EXPECT_IN(FAKE_KERNEL("3.0.0", "C2", 2), xml) << "\nOld requirements must not change.";
1303     EXPECT_IN(FAKE_KERNEL("4.0.0", "D2", 2), xml) << "\nOld requirements must not change.";
1304     EXPECT_IN(FAKE_KERNEL("5.0.0", "E3", 3), xml) << "\nShould see <kernel> from new matrices";
1305 
1306     EXPECT_IN(FAKE_KERNEL("2.0.0", "B2", 2), xml) << "\nShould see <kernel> from new matrices";
1307     EXPECT_IN(FAKE_KERNEL("4.0.0", "D3", 3), xml) << "\nShould see <kernel> from new matrices";
1308 }
1309 
1310 KernelInfo MakeKernelInfo(const std::string& version, const std::string& key) {
1311     KernelInfo info;
1312     CHECK(gKernelInfoConverter(&info,
1313                                "    <kernel version=\"" + version + "\">\n"
1314                                "        <config>\n"
1315                                "            <key>CONFIG_" + key + "</key>\n"
1316                                "            <value type=\"tristate\">y</value>\n"
1317                                "        </config>\n"
1318                                "    </kernel>\n"));
1319     return info;
1320 }
1321 
1322 TEST_F(KernelTest, Compatible) {
1323     setupMockFetcher(vendorManifestXml1, systemMatrixXml1, systemManifestXml1, vendorMatrixXml1);
1324 
1325     SetUpMockSystemMatrices({
1326         "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
1327         FAKE_KERNEL("1.0.0", "A1", 1)
1328         FAKE_KERNEL("2.0.0", "B1", 1)
1329         "    <sepolicy>\n"
1330         "        <kernel-sepolicy-version>0</kernel-sepolicy-version>\n"
1331         "        <sepolicy-version>0.0</sepolicy-version>\n"
1332         "    </sepolicy>\n"
1333         "</compatibility-matrix>\n"});
1334     expectKernelFcmVersion(Level{1}, Level{1});
1335     expectSystemManifest();
1336     expectVendorMatrix();
1337 
1338     auto info = MakeKernelInfo("1.0.0", "A1");
1339     runtimeInfoFactory().getInfo()->setNextFetchKernelInfo(info.version(), info.configs());
1340     std::string error;
1341     ASSERT_EQ(COMPATIBLE, vintfObject->checkCompatibility(&error)) << error;
1342 }
1343 
1344 TEST_F(KernelTest, Level) {
1345     expectKernelFcmVersion(1, Level{10});
1346     EXPECT_EQ(Level{10}, vintfObject->getKernelLevel());
1347 }
1348 
1349 TEST_F(KernelTest, LevelUnspecified) {
1350     expectKernelFcmVersion(1, Level::UNSPECIFIED);
1351     EXPECT_EQ(Level::UNSPECIFIED, vintfObject->getKernelLevel());
1352 }
1353 
1354 class KernelTestP : public KernelTest, public WithParamInterface<
1355     std::tuple<std::vector<std::string>, KernelInfo, Level, Level, bool>> {};
1356 // Assume that we are developing level 2. Test that old <kernel> requirements should
1357 // not change and new <kernel> versions are added.
1358 TEST_P(KernelTestP, Test) {
1359     auto&& [matrices, info, targetFcm, kernelFcm, pass] = GetParam();
1360 
1361     SetUpMockSystemMatrices(matrices);
1362     expectKernelFcmVersion(targetFcm, kernelFcm);
1363     runtimeInfoFactory().getInfo()->setNextFetchKernelInfo(info.version(), info.configs());
1364     auto matrix = vintfObject->getFrameworkCompatibilityMatrix();
1365     auto runtime = vintfObject->getRuntimeInfo();
1366     ASSERT_NE(nullptr, matrix);
1367     ASSERT_NE(nullptr, runtime);
1368     std::string fallbackError = kernelFcm == Level::UNSPECIFIED
1369         ? "\nOld requirements must not change"
1370         : "\nMust not pull unnecessary requirements from new matrices";
1371     std::string error;
1372     ASSERT_EQ(pass, runtime->checkCompatibility(*matrix, &error))
1373             << (pass ? error : fallbackError);
1374 }
1375 
1376 
1377 std::vector<KernelTestP::ParamType> KernelTestParamValues() {
1378     std::vector<KernelTestP::ParamType> ret;
1379     std::vector<std::string> matrices = {systemMatrixKernelXmls[0], systemMatrixKernelXmls[1]};
1380     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{1}, Level::UNSPECIFIED, true);
1381     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{1}, Level::UNSPECIFIED, true);
1382     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{1}, Level::UNSPECIFIED, true);
1383     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{1}, Level::UNSPECIFIED, true);
1384     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{1}, Level::UNSPECIFIED, false);
1385 
1386     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{1}, Level{1}, true);
1387     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{1}, Level{1}, true);
1388     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{1}, Level{1}, false);
1389     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{1}, Level{1}, false);
1390     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{1}, Level{1}, true);
1391 
1392     matrices = systemMatrixKernelXmls;
1393     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{1}, Level::UNSPECIFIED, true);
1394     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{1}, Level::UNSPECIFIED, true);
1395     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{1}, Level::UNSPECIFIED, true);
1396     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{1}, Level::UNSPECIFIED, true);
1397     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E3"), Level{1}, Level::UNSPECIFIED, true);
1398     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{1}, Level::UNSPECIFIED, true);
1399     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{1}, Level::UNSPECIFIED, false);
1400     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D3"), Level{1}, Level::UNSPECIFIED, false);
1401     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E4"), Level{1}, Level::UNSPECIFIED, false);
1402     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F5"), Level{1}, Level::UNSPECIFIED, false);
1403 
1404     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{2}, Level::UNSPECIFIED, true);
1405     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{3}, Level::UNSPECIFIED, true);
1406     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{4}, Level::UNSPECIFIED, true);
1407     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{5}, Level::UNSPECIFIED, false);
1408 
1409     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{1}, Level{1}, true);
1410     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{1}, Level{1}, true);
1411     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{1}, Level{1}, true);
1412     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{1}, Level{1}, false);
1413     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C3"), Level{1}, Level{1}, false);
1414     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{1}, Level{1}, false);
1415     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D3"), Level{1}, Level{1}, false);
1416     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E3"), Level{1}, Level{1}, false);
1417     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E4"), Level{1}, Level{1}, false);
1418     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{1}, Level{1}, false);
1419     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F5"), Level{1}, Level{1}, false);
1420     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{1}, Level{1}, false);
1421 
1422     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{2}, Level{2}, false);
1423     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{3}, Level{3}, false);
1424     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{4}, Level{4}, true);
1425     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{5}, Level{5}, false);
1426 
1427     return ret;
1428 }
1429 
1430 std::vector<KernelTestP::ParamType> RKernelTestParamValues() {
1431     std::vector<KernelTestP::ParamType> ret;
1432     std::vector<std::string> matrices = systemMatrixKernelXmls;
1433 
1434     // Must not use *-r+ kernels without specifying kernel FCM version
1435     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{1}, Level::UNSPECIFIED, false);
1436     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{2}, Level::UNSPECIFIED, false);
1437     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{3}, Level::UNSPECIFIED, false);
1438     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{4}, Level::UNSPECIFIED, false);
1439     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{5}, Level::UNSPECIFIED, false);
1440 
1441     // May use *-r+ kernels with kernel FCM version
1442     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{1}, Level{5}, true);
1443     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{2}, Level{5}, true);
1444     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{3}, Level{5}, true);
1445     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{4}, Level{5}, true);
1446     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{5}, Level{5}, true);
1447 
1448     return ret;
1449 }
1450 
1451 std::string PrintKernelTestParam(const TestParamInfo<KernelTestP::ParamType>& info) {
1452     const auto& [matrices, kernelInfo, targetFcm, kernelFcm, pass] = info.param;
1453     return (matrices.size() == 2 ? "Level1AndLevel2_" : "Level1AndMore_") +
1454            android::base::StringReplace(to_string(kernelInfo.version()), ".", "_", true) + "_" +
1455            android::base::StringReplace(kernelInfo.configs().begin()->first, "CONFIG_", "", false) +
1456            "_TargetFcm" +
1457            (targetFcm == Level::UNSPECIFIED ? "Unspecified" : to_string(targetFcm)) +
1458            "_KernelFcm" +
1459            (kernelFcm == Level::UNSPECIFIED ? "Unspecified" : to_string(kernelFcm)) +
1460            "_Should" + (pass ? "Pass" : "Fail");
1461 }
1462 
1463 INSTANTIATE_TEST_SUITE_P(KernelTest, KernelTestP, ValuesIn(KernelTestParamValues()),
1464                          &PrintKernelTestParam);
1465 INSTANTIATE_TEST_SUITE_P(NoRKernelWithoutFcm, KernelTestP, ValuesIn(RKernelTestParamValues()),
1466                          &PrintKernelTestParam);
1467 
1468 class VintfObjectPartialUpdateTest : public MultiMatrixTest {
1469    protected:
1470     void SetUp() override {
1471         MultiMatrixTest::SetUp();
1472     }
1473 };
1474 
1475 TEST_F(VintfObjectPartialUpdateTest, DeviceCompatibility) {
1476     setupMockFetcher(vendorManifestRequire1, "", systemManifestXml1, vendorMatrixXml1);
1477     SetUpMockSystemMatrices(systemMatrixRequire);
1478 
1479     expectSystemManifest();
1480     expectVendorMatrix();
1481     expectVendorManifest();
1482 
1483     std::string error;
1484     EXPECT_TRUE(vintfObject->checkCompatibility(&error)) << error;
1485 }
1486 
1487 std::string CreateFrameworkManifestFrag(const std::string& interface) {
1488     return "<manifest " + kMetaVersionStr + " type=\"framework\">\n"
1489            "    <hal format=\"hidl\">\n"
1490            "        <name>android.hardware.foo</name>\n"
1491            "        <transport>hwbinder</transport>\n"
1492            "        <fqname>@1.0::" + interface + "/default</fqname>\n"
1493            "    </hal>\n"
1494            "</manifest>\n";
1495 }
1496 
1497 using FrameworkManifestTestParam =
1498     std::tuple<bool /* Existence of /system/etc/vintf/manifest.xml */,
1499                bool /* Existence of /system/etc/vintf/manifest/fragment.xml */,
1500                bool /* Existence of /product/etc/vintf/manifest.xml */,
1501                bool /* Existence of /product/etc/vintf/manifest/fragment.xml */,
1502                bool /* Existence of /system_ext/etc/vintf/manifest.xml */,
1503                bool /* Existence of /system_ext/etc/vintf/manifest/fragment.xml */>;
1504 class FrameworkManifestTest : public VintfObjectTestBase,
1505                               public ::testing::WithParamInterface<FrameworkManifestTestParam> {
1506    protected:
1507     // Set the existence of |path|.
1508     void expectManifest(const std::string& path, const std::string& interface, bool exists) {
1509         if (exists) {
1510             expectFetchRepeatedly(path, CreateFrameworkManifestFrag(interface));
1511         } else {
1512             expectFileNotExist(StrEq(path));
1513         }
1514     }
1515 
1516     // Set the existence of |path| as a fragment dir
1517     void expectFragment(const std::string& path, const std::string& interface, bool exists) {
1518         if (exists) {
1519             EXPECT_CALL(fetcher(), listFiles(StrEq(path), _, _))
1520                 .Times(AnyNumber())
1521                 .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
1522                     *out = {"fragment.xml"};
1523                     return ::android::OK;
1524                 }));
1525             expectFetchRepeatedly(path + "fragment.xml",
1526                                   CreateFrameworkManifestFrag(interface));
1527         } else {
1528             EXPECT_CALL(fetcher(), listFiles(StrEq(path), _, _))
1529                 .Times(AnyNumber())
1530                 .WillRepeatedly(Return(::android::OK));
1531             expectFileNotExist(path + "fragment.xml");
1532         }
1533     }
1534 
1535     void expectContainsInterface(const std::string& interface, bool contains = true) {
1536         auto manifest = vintfObject->getFrameworkHalManifest();
1537         ASSERT_NE(nullptr, manifest);
1538         EXPECT_NE(manifest->getHidlInstances("android.hardware.foo", {1, 0}, interface).empty(),
1539                   contains)
1540             << interface << " is missing.";
1541     }
1542 };
1543 
1544 TEST_P(FrameworkManifestTest, Existence) {
1545     expectFileNotExist(StrEq(kSystemLegacyManifest));
1546 
1547     expectManifest(kSystemManifest, "ISystemEtc", std::get<0>(GetParam()));
1548     expectFragment(kSystemManifestFragmentDir, "ISystemEtcFragment", std::get<1>(GetParam()));
1549     expectManifest(kProductManifest, "IProductEtc", std::get<2>(GetParam()));
1550     expectFragment(kProductManifestFragmentDir, "IProductEtcFragment", std::get<3>(GetParam()));
1551     expectManifest(kSystemExtManifest, "ISystemExtEtc", std::get<4>(GetParam()));
1552     expectFragment(kSystemExtManifestFragmentDir, "ISystemExtEtcFragment", std::get<5>(GetParam()));
1553 
1554     if (!std::get<0>(GetParam())) {
1555         EXPECT_EQ(nullptr, vintfObject->getFrameworkHalManifest())
1556             << "getFrameworkHalManifest must return nullptr if " << kSystemManifest
1557             << " does not exist";
1558     } else {
1559         expectContainsInterface("ISystemEtc", std::get<0>(GetParam()));
1560         expectContainsInterface("ISystemEtcFragment", std::get<1>(GetParam()));
1561         expectContainsInterface("IProductEtc", std::get<2>(GetParam()));
1562         expectContainsInterface("IProductEtcFragment", std::get<3>(GetParam()));
1563         expectContainsInterface("ISystemExtEtc", std::get<4>(GetParam()));
1564         expectContainsInterface("ISystemExtEtcFragment", std::get<5>(GetParam()));
1565     }
1566 }
1567 INSTANTIATE_TEST_SUITE_P(Vintf, FrameworkManifestTest,
1568                          ::testing::Combine(Bool(), Bool(), Bool(), Bool(), Bool(), Bool()));
1569 
1570 
1571 //
1572 // Set of OEM FCM matrices at different FCM version.
1573 //
1574 
1575 std::vector<std::string> GetOemFcmMatrixLevels(const std::string& name) {
1576     return {
1577         // 1.xml
1578         "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
1579         "    <hal format=\"hidl\" optional=\"true\">\n"
1580         "        <name>vendor.foo." + name + "</name>\n"
1581         "        <version>1.0</version>\n"
1582         "        <interface>\n"
1583         "            <name>IExtra</name>\n"
1584         "            <instance>default</instance>\n"
1585         "        </interface>\n"
1586         "    </hal>\n"
1587         "</compatibility-matrix>\n",
1588         // 2.xml
1589         "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
1590         "    <hal format=\"hidl\" optional=\"true\">\n"
1591         "        <name>vendor.foo." + name + "</name>\n"
1592         "        <version>2.0</version>\n"
1593         "        <interface>\n"
1594         "            <name>IExtra</name>\n"
1595         "            <instance>default</instance>\n"
1596         "        </interface>\n"
1597         "    </hal>\n"
1598         "</compatibility-matrix>\n",
1599     };
1600 }
1601 
1602 class OemFcmLevelTest : public MultiMatrixTest,
1603                         public WithParamInterface<std::tuple<size_t, bool, bool>> {
1604    protected:
1605     virtual void SetUp() override {
1606         MultiMatrixTest::SetUp();
1607         SetUpMockSystemMatrices({systemMatrixLevel1, systemMatrixLevel2});
1608     }
1609     using Instances = std::set<std::string>;
1610     Instances GetInstances(const CompatibilityMatrix* fcm) {
1611         Instances instances;
1612         fcm->forEachHidlInstance([&instances](const auto& matrixInstance) {
1613             instances.insert(matrixInstance.description(matrixInstance.versionRange().minVer()));
1614             return true; // continue
1615         });
1616         return instances;
1617     }
1618 };
1619 
1620 TEST_P(OemFcmLevelTest, Test) {
1621     auto&& [level, hasProduct, hasSystemExt] = GetParam();
1622 
1623     expectTargetFcmVersion(level);
1624     if (hasProduct) {
1625         SetUpMockMatrices(kProductVintfDir, GetOemFcmMatrixLevels("product"));
1626     }
1627     if (hasSystemExt) {
1628         SetUpMockMatrices(kSystemExtVintfDir, GetOemFcmMatrixLevels("systemext"));
1629     }
1630 
1631     auto fcm = vintfObject->getFrameworkCompatibilityMatrix();
1632     ASSERT_NE(nullptr, fcm);
1633     auto instances = GetInstances(fcm.get());
1634 
1635     auto containsOrNot = [](bool contains, const std::string& e) {
1636         return contains ? SafeMatcherCast<Instances>(Contains(e))
1637                         : SafeMatcherCast<Instances>(Not(Contains(e)));
1638     };
1639 
1640     EXPECT_THAT(instances, containsOrNot(level == 1,
1641                                          "[email protected]::IMajor/default"));
1642     EXPECT_THAT(instances, containsOrNot(level == 1 && hasProduct,
1643                                          "[email protected]::IExtra/default"));
1644     EXPECT_THAT(instances, containsOrNot(level == 1 && hasSystemExt,
1645                                          "[email protected]::IExtra/default"));
1646     EXPECT_THAT(instances, Contains("[email protected]::IMajor/default"));
1647     EXPECT_THAT(instances, containsOrNot(hasProduct,
1648                                          "[email protected]::IExtra/default"));
1649     EXPECT_THAT(instances, containsOrNot(hasSystemExt,
1650                                          "[email protected]::IExtra/default"));
1651 }
1652 
1653 static std::string OemFcmLevelTestParamToString(
1654         const TestParamInfo<OemFcmLevelTest::ParamType>& info) {
1655     auto&& [level, hasProduct, hasSystemExt] = info.param;
1656     auto name = "Level" + std::to_string(level);
1657     name += "With"s + (hasProduct ? "" : "out") + "Product";
1658     name += "With"s + (hasSystemExt ? "" : "out") + "SystemExt";
1659     return name;
1660 }
1661 INSTANTIATE_TEST_SUITE_P(OemFcmLevel, OemFcmLevelTest, Combine(Values(1, 2), Bool(), Bool()),
1662     OemFcmLevelTestParamToString);
1663 // clang-format on
1664 
1665 }  // namespace testing
1666 }  // namespace vintf
1667 }  // namespace android
1668 
1669 int main(int argc, char** argv) {
1670     ::testing::InitGoogleMock(&argc, argv);
1671     return RUN_ALL_TESTS();
1672 }
1673