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 // This needs to be on top of the file to work.
18 #include "gmock-logging-compat.h"
19 
20 #include <stdio.h>
21 #include <optional>
22 
23 #include <android-base/file.h>
24 #include <android-base/logging.h>
25 #include <android-base/result-gmock.h>
26 #include <android-base/stringprintf.h>
27 #include <android-base/strings.h>
28 #include <gtest/gtest.h>
29 
30 #include <vintf/VintfObject.h>
31 #include <vintf/parse_string.h>
32 #include <vintf/parse_xml.h>
33 #include "constants-private.h"
34 #include "parse_xml_internal.h"
35 #include "test_constants.h"
36 #include "utils-fake.h"
37 
38 using namespace ::testing;
39 using namespace std::literals;
40 
41 using android::base::testing::HasError;
42 using android::base::testing::HasValue;
43 using android::base::testing::Ok;
44 using android::base::testing::WithCode;
45 using android::base::testing::WithMessage;
46 using android::vintf::FqInstance;
47 
48 #define EXPECT_IN(sub, str) EXPECT_THAT(str, HasSubstr(sub))
49 #define EXPECT_NOT_IN(sub, str) EXPECT_THAT(str, Not(HasSubstr(sub)))
50 
51 namespace android {
52 namespace vintf {
53 namespace testing {
54 
55 using namespace ::android::vintf::details;
56 
57 // clang-format off
58 
59 //
60 // Set of Xml1 metadata compatible with each other.
61 //
62 
63 const std::string systemMatrixXml1 =
64     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\">\n"
65     "    <hal format=\"hidl\" optional=\"false\">\n"
66     "        <name>android.hardware.camera</name>\n"
67     "        <version>2.0-5</version>\n"
68     "        <version>3.4-16</version>\n"
69     "    </hal>\n"
70     "    <hal format=\"hidl\" optional=\"false\">\n"
71     "        <name>android.hardware.nfc</name>\n"
72     "        <version>1.0</version>\n"
73     "        <version>2.0</version>\n"
74     "    </hal>\n"
75     "    <hal format=\"hidl\" optional=\"true\">\n"
76     "        <name>android.hardware.foo</name>\n"
77     "        <version>1.0</version>\n"
78     "    </hal>\n"
79     "    <kernel version=\"3.18.31\"></kernel>\n"
80     "    <sepolicy>\n"
81     "        <kernel-sepolicy-version>30</kernel-sepolicy-version>\n"
82     "        <sepolicy-version>25.5</sepolicy-version>\n"
83     "        <sepolicy-version>26.0-3</sepolicy-version>\n"
84     "    </sepolicy>\n"
85     "    <avb>\n"
86     "        <vbmeta-version>0.0</vbmeta-version>\n"
87     "    </avb>\n"
88     "</compatibility-matrix>\n";
89 
90 const std::string vendorManifestXml1 =
91     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
92     "    <hal format=\"hidl\">\n"
93     "        <name>android.hardware.camera</name>\n"
94     "        <transport>hwbinder</transport>\n"
95     "        <version>3.5</version>\n"
96     "        <interface>\n"
97     "            <name>IBetterCamera</name>\n"
98     "            <instance>camera</instance>\n"
99     "        </interface>\n"
100     "        <interface>\n"
101     "            <name>ICamera</name>\n"
102     "            <instance>default</instance>\n"
103     "            <instance>legacy/0</instance>\n"
104     "        </interface>\n"
105     "    </hal>\n"
106     "    <hal format=\"hidl\">\n"
107     "        <name>android.hardware.nfc</name>\n"
108     "        <transport>hwbinder</transport>\n"
109     "        <version>1.0</version>\n"
110     "        <interface>\n"
111     "            <name>INfc</name>\n"
112     "            <instance>nfc_nci</instance>\n"
113     "        </interface>\n"
114     "    </hal>\n"
115     "    <hal format=\"hidl\">\n"
116     "        <name>android.hardware.nfc</name>\n"
117     "        <transport>hwbinder</transport>\n"
118     "        <version>2.0</version>\n"
119     "        <interface>\n"
120     "            <name>INfc</name>\n"
121     "            <instance>default</instance>\n"
122     "            <instance>nfc_nci</instance>\n"
123     "        </interface>\n"
124     "    </hal>\n"
125     "    <sepolicy>\n"
126     "        <version>25.5</version>\n"
127     "    </sepolicy>\n"
128     "</manifest>\n";
129 
130 const std::string systemManifestXml1 =
131     "<manifest " + kMetaVersionStr + " type=\"framework\">\n"
132     "    <hal format=\"hidl\">\n"
133     "        <name>android.hidl.manager</name>\n"
134     "        <transport>hwbinder</transport>\n"
135     "        <version>1.0</version>\n"
136     "        <interface>\n"
137     "            <name>IServiceManager</name>\n"
138     "            <instance>default</instance>\n"
139     "        </interface>\n"
140     "    </hal>\n"
141     "    <vndk>\n"
142     "        <version>25.0.5</version>\n"
143     "        <library>libbase.so</library>\n"
144     "        <library>libjpeg.so</library>\n"
145     "    </vndk>\n"
146     "</manifest>\n";
147 
148 const std::string vendorMatrixXml1 =
149     "<compatibility-matrix " + kMetaVersionStr + " type=\"device\">\n"
150     "    <hal format=\"hidl\" optional=\"false\">\n"
151     "        <name>android.hidl.manager</name>\n"
152     "        <version>1.0</version>\n"
153     "    </hal>\n"
154     "    <vndk>\n"
155     "        <version>25.0.1-5</version>\n"
156     "        <library>libbase.so</library>\n"
157     "        <library>libjpeg.so</library>\n"
158     "    </vndk>\n"
159     "</compatibility-matrix>\n";
160 
161 //
162 // Set of Xml2 metadata compatible with each other.
163 //
164 
165 const std::string systemMatrixXml2 =
166     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\">\n"
167     "    <hal format=\"hidl\" optional=\"false\">\n"
168     "        <name>android.hardware.foo</name>\n"
169     "        <version>1.0</version>\n"
170     "    </hal>\n"
171     "    <kernel version=\"3.18.31\"></kernel>\n"
172     "    <sepolicy>\n"
173     "        <kernel-sepolicy-version>30</kernel-sepolicy-version>\n"
174     "        <sepolicy-version>25.5</sepolicy-version>\n"
175     "        <sepolicy-version>26.0-3</sepolicy-version>\n"
176     "    </sepolicy>\n"
177     "    <avb>\n"
178     "        <vbmeta-version>0.0</vbmeta-version>\n"
179     "    </avb>\n"
180     "</compatibility-matrix>\n";
181 
182 const std::string vendorManifestXml2 =
183     "<manifest " + kMetaVersionStr + " type=\"device\">"
184     "    <hal>"
185     "        <name>android.hardware.foo</name>"
186     "        <transport>hwbinder</transport>"
187     "        <version>1.0</version>"
188     "    </hal>"
189     "    <sepolicy>\n"
190     "        <version>25.5</version>\n"
191     "    </sepolicy>\n"
192     "</manifest>";
193 
194 //
195 // Set of framework matrices of different FCM version.
196 //
197 
198 const std::string systemMatrixLevel1 =
199     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
200     "    <hal format=\"hidl\" optional=\"true\">\n"
201     "        <name>android.hardware.major</name>\n"
202     "        <version>1.0</version>\n"
203     "        <interface>\n"
204     "            <name>IMajor</name>\n"
205     "            <instance>default</instance>\n"
206     "        </interface>\n"
207     "    </hal>\n"
208     "    <hal format=\"hidl\" optional=\"true\">\n"
209     "        <name>android.hardware.removed</name>\n"
210     "        <version>1.0</version>\n"
211     "        <interface>\n"
212     "            <name>IRemoved</name>\n"
213     "            <instance>default</instance>\n"
214     "        </interface>\n"
215     "    </hal>\n"
216     "    <hal format=\"hidl\" optional=\"true\">\n"
217     "        <name>android.hardware.minor</name>\n"
218     "        <version>1.0</version>\n"
219     "        <interface>\n"
220     "            <name>IMinor</name>\n"
221     "            <instance>default</instance>\n"
222     "            <instance>legacy</instance>\n"
223     "        </interface>\n"
224     "    </hal>\n"
225     "    <hal format=\"aidl\" optional=\"true\">\n"
226     "        <name>android.hardware.minor</name>\n"
227     "        <version>101</version>\n"
228     "        <interface>\n"
229     "            <name>IMinor</name>\n"
230     "            <instance>default</instance>\n"
231     "        </interface>\n"
232     "    </hal>\n"
233     "    <hal format=\"aidl\" optional=\"true\">\n"
234     "        <name>android.hardware.removed</name>\n"
235     "        <version>101</version>\n"
236     "        <interface>\n"
237     "            <name>IRemoved</name>\n"
238     "            <instance>default</instance>\n"
239     "        </interface>\n"
240     "    </hal>\n"
241     "</compatibility-matrix>\n";
242 
243 const std::string systemMatrixLevel2 =
244     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
245     "    <hal format=\"hidl\" optional=\"true\">\n"
246     "        <name>android.hardware.major</name>\n"
247     "        <version>2.0</version>\n"
248     "        <interface>\n"
249     "            <name>IMajor</name>\n"
250     "            <instance>default</instance>\n"
251     "        </interface>\n"
252     "    </hal>\n"
253     "    <hal format=\"hidl\" optional=\"true\">\n"
254     "        <name>android.hardware.minor</name>\n"
255     "        <version>1.1</version>\n"
256     "        <interface>\n"
257     "            <name>IMinor</name>\n"
258     "            <instance>default</instance>\n"
259     "        </interface>\n"
260     "    </hal>\n"
261     "    <hal format=\"aidl\" optional=\"true\">\n"
262     "        <name>android.hardware.minor</name>\n"
263     "        <version>102</version>\n"
264     "        <interface>\n"
265     "            <name>IMinor</name>\n"
266     "            <instance>default</instance>\n"
267     "        </interface>\n"
268     "    </hal>\n"
269     "</compatibility-matrix>\n";
270 
271 //
272 // Smaller product FCMs at different levels to test that framework and product
273 // FCMs are combined when checking deprecation.
274 //
275 
276 const std::string productMatrixLevel1 =
277     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
278     "    <hal format=\"hidl\" optional=\"true\">\n"
279     "        <name>product.removed</name>\n"
280     "        <version>1.0</version>\n"
281     "        <interface>\n"
282     "            <name>IRemoved</name>\n"
283     "            <instance>default</instance>\n"
284     "        </interface>\n"
285     "    </hal>\n"
286     "    <hal format=\"hidl\" optional=\"true\">\n"
287     "        <name>product.minor</name>\n"
288     "        <version>1.0</version>\n"
289     "        <interface>\n"
290     "            <name>IMinor</name>\n"
291     "            <instance>default</instance>\n"
292     "        </interface>\n"
293     "    </hal>\n"
294     "</compatibility-matrix>\n";
295 
296 const std::string productMatrixLevel2 =
297     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
298     "    <hal format=\"hidl\" optional=\"true\">\n"
299     "        <name>product.minor</name>\n"
300     "        <version>1.1</version>\n"
301     "        <interface>\n"
302     "            <name>IMinor</name>\n"
303     "            <instance>default</instance>\n"
304     "        </interface>\n"
305     "    </hal>\n"
306     "</compatibility-matrix>\n";
307 
308 //
309 // Set of framework matrices of different FCM version with regex.
310 //
311 
312 const static std::vector<std::string> systemMatrixRegexXmls = {
313     // 1.xml
314     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
315     "    <hal format=\"hidl\" optional=\"false\">\n"
316     "        <name>android.hardware.regex</name>\n"
317     "        <version>1.0-1</version>\n"
318     "        <interface>\n"
319     "            <name>IRegex</name>\n"
320     "            <instance>default</instance>\n"
321     "            <instance>special/1.0</instance>\n"
322     "            <regex-instance>regex/1.0/[0-9]+</regex-instance>\n"
323     "            <regex-instance>regex_common/[0-9]+</regex-instance>\n"
324     "        </interface>\n"
325     "    </hal>\n"
326     "</compatibility-matrix>\n",
327     // 2.xml
328     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
329     "    <hal format=\"hidl\" optional=\"false\">\n"
330     "        <name>android.hardware.regex</name>\n"
331     "        <version>1.1-2</version>\n"
332     "        <interface>\n"
333     "            <name>IRegex</name>\n"
334     "            <instance>default</instance>\n"
335     "            <instance>special/1.1</instance>\n"
336     "            <regex-instance>regex/1.1/[0-9]+</regex-instance>\n"
337     "            <regex-instance>[a-z]+_[a-z]+/[0-9]+</regex-instance>\n"
338     "        </interface>\n"
339     "    </hal>\n"
340     "</compatibility-matrix>\n",
341     // 3.xml
342     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"3\">\n"
343     "    <hal format=\"hidl\" optional=\"false\">\n"
344     "        <name>android.hardware.regex</name>\n"
345     "        <version>2.0</version>\n"
346     "        <interface>\n"
347     "            <name>IRegex</name>\n"
348     "            <instance>default</instance>\n"
349     "            <instance>special/2.0</instance>\n"
350     "            <regex-instance>regex/2.0/[0-9]+</regex-instance>\n"
351     "            <regex-instance>regex_[a-z]+/[0-9]+</regex-instance>\n"
352     "        </interface>\n"
353     "    </hal>\n"
354     "</compatibility-matrix>\n"};
355 
356 //
357 // Set of metadata at different FCM version that has requirements
358 //
359 
360 const std::vector<std::string> systemMatrixRequire = {
361     // 1.xml
362     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
363     "    <hal format=\"hidl\" optional=\"false\">\n"
364     "        <name>android.hardware.foo</name>\n"
365     "        <version>1.0</version>\n"
366     "        <interface>\n"
367     "            <name>IFoo</name>\n"
368     "            <instance>default</instance>\n"
369     "        </interface>\n"
370     "    </hal>\n"
371     "</compatibility-matrix>\n",
372     // 2.xml
373     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
374     "    <hal format=\"hidl\" optional=\"false\">\n"
375     "        <name>android.hardware.bar</name>\n"
376     "        <version>1.0</version>\n"
377     "        <interface>\n"
378     "            <name>IBar</name>\n"
379     "            <instance>default</instance>\n"
380     "        </interface>\n"
381     "    </hal>\n"
382     "</compatibility-matrix>\n"};
383 
384 const std::string vendorManifestRequire1 =
385     "<manifest " + kMetaVersionStr + " type=\"device\" target-level=\"1\">\n"
386     "    <hal format=\"hidl\">\n"
387     "        <name>android.hardware.foo</name>\n"
388     "        <transport>hwbinder</transport>\n"
389     "        <fqname>@1.0::IFoo/default</fqname>\n"
390     "    </hal>\n"
391     "</manifest>\n";
392 
393 const std::string vendorManifestRequire2 =
394     "<manifest " + kMetaVersionStr + " type=\"device\" target-level=\"2\">\n"
395     "    <hal format=\"hidl\">\n"
396     "        <name>android.hardware.bar</name>\n"
397     "        <transport>hwbinder</transport>\n"
398     "        <fqname>@1.0::IBar/default</fqname>\n"
399     "    </hal>\n"
400     "</manifest>\n";
401 
402 //
403 // Set of metadata for kernel requirements
404 //
405 
406 const std::string vendorManifestKernel318 =
407     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
408     "    <kernel version=\"3.18.999\" />\n"
409     "    <sepolicy>\n"
410     "        <version>25.5</version>\n"
411     "    </sepolicy>\n"
412     "</manifest>\n";
413 
414 const std::string systemMatrixKernel318 =
415     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\">\n"
416     "    <kernel version=\"3.18.999\"></kernel>\n"
417     "    <sepolicy>\n"
418     "        <kernel-sepolicy-version>30</kernel-sepolicy-version>\n"
419     "        <sepolicy-version>25.5</sepolicy-version>\n"
420     "    </sepolicy>\n"
421     "</compatibility-matrix>\n";
422 
423 const std::string apexHalName = "android.hardware.apex.foo";
424 const std::string apexHalManifest =
425     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
426     "    <hal format=\"aidl\">\n"
427     "        <name>" + apexHalName + "</name>\n"
428     "        <fqname>IApex/default</fqname>\n"
429     "    </hal>\n"
430     "</manifest>\n";
431 
432 class VintfObjectTestBase : public ::testing::Test {
433    protected:
fetcher()434     MockFileSystem& fetcher() {
435         return static_cast<MockFileSystem&>(*vintfObject->getFileSystem());
436     }
propertyFetcher()437     MockPropertyFetcher& propertyFetcher() {
438         return static_cast<MockPropertyFetcher&>(*vintfObject->getPropertyFetcher());
439     }
440 
setCheckAidlFCM(bool check)441     void setCheckAidlFCM(bool check) { vintfObject->setFakeCheckAidlCompatMatrix(check); }
useEmptyFileSystem()442     void useEmptyFileSystem() {
443         // By default, no files exist in the file system.
444         // Use EXPECT_CALL because more specific expectation of fetch and listFiles will come along.
445         EXPECT_CALL(fetcher(), listFiles(_, _, _)).Times(AnyNumber())
446             .WillRepeatedly(Return(::android::NAME_NOT_FOUND));
447         EXPECT_CALL(fetcher(), fetch(_, _)).Times(AnyNumber())
448             .WillRepeatedly(Return(::android::NAME_NOT_FOUND));
449     }
450 
451     // Setup the MockFileSystem used by the fetchAllInformation template
452     // so it returns the given metadata info instead of fetching from device.
setupMockFetcher(const std::string & vendorManifestXml,const std::string & systemMatrixXml,const std::string & systemManifestXml,const std::string & vendorMatrixXml)453     void setupMockFetcher(const std::string& vendorManifestXml, const std::string& systemMatrixXml,
454                           const std::string& systemManifestXml, const std::string& vendorMatrixXml) {
455 
456         useEmptyFileSystem();
457 
458         ON_CALL(fetcher(), fetch(StrEq(kVendorLegacyManifest), _))
459             .WillByDefault(
460                 Invoke([vendorManifestXml](const std::string& path, std::string& fetched) {
461                     (void)path;
462                     fetched = vendorManifestXml;
463                     return 0;
464                 }));
465         ON_CALL(fetcher(), fetch(StrEq(kSystemManifest), _))
466             .WillByDefault(
467                 Invoke([systemManifestXml](const std::string& path, std::string& fetched) {
468                     (void)path;
469                     fetched = systemManifestXml;
470                     return 0;
471                 }));
472         ON_CALL(fetcher(), fetch(StrEq(kVendorLegacyMatrix), _))
473             .WillByDefault(Invoke([vendorMatrixXml](const std::string& path, std::string& fetched) {
474                 (void)path;
475                 fetched = vendorMatrixXml;
476                 return 0;
477             }));
478         ON_CALL(fetcher(), fetch(StrEq(kSystemLegacyMatrix), _))
479             .WillByDefault(Invoke([systemMatrixXml](const std::string& path, std::string& fetched) {
480                 (void)path;
481                 fetched = systemMatrixXml;
482                 return 0;
483             }));
484     }
SetUp()485     virtual void SetUp() {
486         vintfObject = VintfObject::Builder()
487                           .setFileSystem(std::make_unique<NiceMock<MockFileSystem>>())
488                           .setRuntimeInfoFactory(std::make_unique<NiceMock<MockRuntimeInfoFactory>>(
489                               std::make_shared<NiceMock<MockRuntimeInfo>>()))
490                           .setPropertyFetcher(std::make_unique<NiceMock<MockPropertyFetcher>>())
491                           .build();
492 
493         ON_CALL(propertyFetcher(), getBoolProperty("apex.all.ready", _))
494             .WillByDefault(Return(true));
495     }
TearDown()496     virtual void TearDown() {
497         Mock::VerifyAndClear(&fetcher());
498     }
499 
expectVendorManifest(size_t times=1)500     void expectVendorManifest(size_t times = 1) {
501         EXPECT_CALL(fetcher(), fetch(StrEq(kVendorLegacyManifest), _)).Times(times);
502     }
503 
expectSystemManifest(size_t times=1)504     void expectSystemManifest(size_t times = 1) {
505         EXPECT_CALL(fetcher(), fetch(StrEq(kSystemManifest), _)).Times(times);
506     }
507 
expectVendorMatrix(size_t times=1)508     void expectVendorMatrix(size_t times = 1) {
509         EXPECT_CALL(fetcher(), fetch(StrEq(kVendorLegacyMatrix), _)).Times(times);
510     }
511 
expectSystemMatrix(size_t times=1)512     void expectSystemMatrix(size_t times = 1) {
513         EXPECT_CALL(fetcher(), fetch(StrEq(kSystemLegacyMatrix), _)).Times(times);
514     }
515 
516     // Expect that a file exist and should be fetched once.
expectFetch(const std::string & path,const std::string & content)517     void expectFetch(const std::string& path, const std::string& content) {
518         EXPECT_CALL(fetcher(), fetch(StrEq(path), _))
519             .WillOnce(Invoke([content](const auto&, auto& out) {
520                 out = content;
521                 return ::android::OK;
522             }));
523     }
524 
525     // Expect that a file exist and can be fetched 0 or more times.
expectFetchRepeatedly(const std::string & path,const std::string & content)526     void expectFetchRepeatedly(const std::string& path, const std::string& content) {
527         EXPECT_CALL(fetcher(), fetch(StrEq(path), _))
528             .Times(AnyNumber())
529             .WillRepeatedly(Invoke([content](const auto&, auto& out) {
530                 out = content;
531                 return ::android::OK;
532             }));
533     }
534 
535     // Expect that the file should never be fetched (whether it exists or not).
expectNeverFetch(const std::string & path)536     void expectNeverFetch(const std::string& path) {
537         EXPECT_CALL(fetcher(), fetch(StrEq(path), _)).Times(0);
538     }
539 
540     // Expect that the file does not exist, and can be fetched 0 or more times.
541     template <typename Matcher>
expectFileNotExist(const Matcher & matcher)542     void expectFileNotExist(const Matcher& matcher) {
543         EXPECT_CALL(fetcher(), fetch(matcher, _))
544             .Times(AnyNumber())
545             .WillRepeatedly(Return(::android::NAME_NOT_FOUND));
546     }
547 
548     // clang-format on
expectVendorManifest(Level level,const std::vector<std::string> & fqInstances,const std::vector<FqInstance> & aidlInstances={})549     void expectVendorManifest(Level level, const std::vector<std::string>& fqInstances,
550                               const std::vector<FqInstance>& aidlInstances = {}) {
551         std::string xml =
552             android::base::StringPrintf(R"(<manifest %s type="device" target-level="%s">)",
553                                         kMetaVersionStr.c_str(), to_string(level).c_str());
554         for (const auto& fqInstanceString : fqInstances) {
555             auto fqInstance = FqInstance::from(fqInstanceString);
556             ASSERT_TRUE(fqInstance.has_value());
557             xml += android::base::StringPrintf(
558                 R"(
559                     <hal format="hidl">
560                         <name>%s</name>
561                         <transport>hwbinder</transport>
562                         <fqname>%s</fqname>
563                     </hal>
564                 )",
565                 fqInstance->getPackage().c_str(),
566                 toFQNameString(fqInstance->getVersion(), fqInstance->getInterface(),
567                                fqInstance->getInstance())
568                     .c_str());
569         }
570         for (const auto& fqInstance : aidlInstances) {
571             xml += android::base::StringPrintf(
572                 R"(
573                     <hal format="aidl">
574                         <name>%s</name>
575                         <version>%zu</version>
576                         <fqname>%s</fqname>
577                     </hal>
578                 )",
579                 fqInstance.getPackage().c_str(), fqInstance.getMinorVersion(),
580                 toFQNameString(fqInstance.getInterface(), fqInstance.getInstance()).c_str());
581         }
582         xml += "</manifest>";
583         expectFetchRepeatedly(kVendorManifest, xml);
584     }
585     // clang-format off
586 
runtimeInfoFactory()587     MockRuntimeInfoFactory& runtimeInfoFactory() {
588         return static_cast<MockRuntimeInfoFactory&>(*vintfObject->getRuntimeInfoFactory());
589     }
590 
noApex()591     void noApex() {
592         expectFileNotExist(StartsWith("/apex/"));
593     }
594 
595     std::unique_ptr<VintfObject> vintfObject;
596 };
597 
598 // Test fixture that provides compatible metadata from the mock device.
599 class VintfObjectCompatibleTest : public VintfObjectTestBase {
600    protected:
SetUp()601     virtual void SetUp() {
602         VintfObjectTestBase::SetUp();
603         setupMockFetcher(vendorManifestXml1, systemMatrixXml1, systemManifestXml1, vendorMatrixXml1);
604         noApex();
605     }
606 };
607 
608 // Tests that local info is checked.
TEST_F(VintfObjectCompatibleTest,TestDeviceCompatibility)609 TEST_F(VintfObjectCompatibleTest, TestDeviceCompatibility) {
610     std::string error;
611 
612     expectVendorManifest();
613     expectSystemManifest();
614     expectVendorMatrix();
615     expectSystemMatrix();
616 
617     int result = vintfObject->checkCompatibility(&error);
618 
619     ASSERT_EQ(result, 0) << "Fail message:" << error.c_str();
620     // Check that nothing was ignored.
621     ASSERT_STREQ(error.c_str(), "");
622 }
623 
624 // Test fixture that provides incompatible metadata from the mock device.
625 class VintfObjectIncompatibleTest : public VintfObjectTestBase {
626    protected:
SetUp()627     virtual void SetUp() {
628         VintfObjectTestBase::SetUp();
629         setupMockFetcher(vendorManifestXml1, systemMatrixXml2, systemManifestXml1, vendorMatrixXml1);
630     }
631 };
632 
633 // Fetch all metadata from device and ensure that it fails.
TEST_F(VintfObjectIncompatibleTest,TestDeviceCompatibility)634 TEST_F(VintfObjectIncompatibleTest, TestDeviceCompatibility) {
635     std::string error;
636 
637     expectVendorManifest();
638     expectSystemManifest();
639     expectVendorMatrix();
640     expectSystemMatrix();
641 
642     int result = vintfObject->checkCompatibility(&error);
643 
644     ASSERT_EQ(result, 1) << "Should have failed:" << error.c_str();
645 }
646 
647 const std::string vendorManifestKernelFcm =
648         "<manifest " + kMetaVersionStr + " type=\"device\">\n"
649         "    <kernel version=\"3.18.999\" target-level=\"8\"/>\n"
650         "</manifest>\n";
651 
652 // Test fixture that provides compatible metadata from the mock device.
653 class VintfObjectRuntimeInfoTest : public VintfObjectTestBase {
654    protected:
SetUp()655     virtual void SetUp() {
656         VintfObjectTestBase::SetUp();
657     }
TearDown()658     virtual void TearDown() {
659         Mock::VerifyAndClear(&runtimeInfoFactory());
660         Mock::VerifyAndClear(runtimeInfoFactory().getInfo().get());
661     }
662 };
663 
TEST_F(VintfObjectRuntimeInfoTest,GetRuntimeInfo)664 TEST_F(VintfObjectRuntimeInfoTest, GetRuntimeInfo) {
665     setupMockFetcher(vendorManifestKernelFcm, "", "", "");
666     expectVendorManifest();
667     InSequence s;
668 
669     EXPECT_CALL(*runtimeInfoFactory().getInfo(),
670                 fetchAllInformation(RuntimeInfo::FetchFlag::CPU_VERSION));
671     EXPECT_CALL(*runtimeInfoFactory().getInfo(), fetchAllInformation(RuntimeInfo::FetchFlag::NONE));
672     EXPECT_CALL(
673         *runtimeInfoFactory().getInfo(),
674         fetchAllInformation(RuntimeInfo::FetchFlag::ALL & ~RuntimeInfo::FetchFlag::CPU_VERSION));
675     EXPECT_CALL(*runtimeInfoFactory().getInfo(), fetchAllInformation(RuntimeInfo::FetchFlag::NONE));
676 
677     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(
678                                                    RuntimeInfo::FetchFlag::CPU_VERSION));
679     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(
680                                                    RuntimeInfo::FetchFlag::CPU_VERSION));
681     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(
682                                                    RuntimeInfo::FetchFlag::ALL));
683     EXPECT_NE(nullptr, vintfObject->getRuntimeInfo(
684                                                    RuntimeInfo::FetchFlag::ALL));
685 }
686 
TEST_F(VintfObjectRuntimeInfoTest,GetRuntimeInfoHost)687 TEST_F(VintfObjectRuntimeInfoTest, GetRuntimeInfoHost) {
688     runtimeInfoFactory().getInfo()->failNextFetch();
689     EXPECT_EQ(nullptr, vintfObject->getRuntimeInfo(RuntimeInfo::FetchFlag::ALL));
690 }
691 
692 class VintfObjectKernelFcmTest : public VintfObjectTestBase,
693                                  public WithParamInterface<std::tuple<bool, bool>> {
694    protected:
SetUp()695     virtual void SetUp() {
696         VintfObjectTestBase::SetUp();
697         auto [isHost, hasDeviceManifest] = GetParam();
698         if (hasDeviceManifest) {
699             setupMockFetcher(vendorManifestKernelFcm, "", "", "");
700             expectVendorManifest();
701         }
702 
703         if (isHost) {
704             runtimeInfoFactory().getInfo()->failNextFetch();
705         } else {
706             runtimeInfoFactory().getInfo()->setNextFetchKernelLevel(Level{8});
707         }
708     }
709 
expectedKernelFcm()710     Level expectedKernelFcm() {
711         auto [isHost, hasDeviceManifest] = GetParam();
712         return !isHost || hasDeviceManifest ? Level{8} : Level::UNSPECIFIED;
713     }
714 };
715 
TEST_P(VintfObjectKernelFcmTest,GetKernelLevel)716 TEST_P(VintfObjectKernelFcmTest, GetKernelLevel) {
717     ASSERT_EQ(expectedKernelFcm(), vintfObject->getKernelLevel());
718 }
719 
720 INSTANTIATE_TEST_SUITE_P(KernelFcm, VintfObjectKernelFcmTest,
721     ::testing::Combine(::testing::Bool(), ::testing::Bool()));
722 
723 // Test fixture that provides incompatible metadata from the mock device.
724 class VintfObjectTest : public VintfObjectTestBase {
725    protected:
SetUp()726     virtual void SetUp() {
727         VintfObjectTestBase::SetUp();
728         useEmptyFileSystem();
729     }
730 };
731 
732 // Test framework compatibility matrix is combined at runtime
TEST_F(VintfObjectTest,FrameworkCompatibilityMatrixCombine)733 TEST_F(VintfObjectTest, FrameworkCompatibilityMatrixCombine) {
734     EXPECT_CALL(fetcher(), listFiles(StrEq(kSystemVintfDir), _, _))
735         .WillOnce(Invoke([](const auto&, auto* out, auto*) {
736             *out = {
737                 "compatibility_matrix.1.xml",
738                 "compatibility_matrix.empty.xml",
739             };
740             return ::android::OK;
741         }));
742     expectFetch(kSystemVintfDir + "compatibility_matrix.1.xml"s,
743                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\"/>");
744     expectFetch(kSystemVintfDir + "compatibility_matrix.empty.xml"s,
745                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\"/>");
746     expectFileNotExist(StrEq(kProductMatrix));
747     expectFetch(kVendorManifest, "<manifest " + kMetaVersionStr + " type=\"device\" />\n");
748     expectNeverFetch(kSystemLegacyMatrix);
749 
750     EXPECT_NE(nullptr, vintfObject->getFrameworkCompatibilityMatrix());
751 }
752 
753 // Test product compatibility matrix is fetched
TEST_F(VintfObjectTest,ProductCompatibilityMatrix)754 TEST_F(VintfObjectTest, ProductCompatibilityMatrix) {
755     EXPECT_CALL(fetcher(), listFiles(StrEq(kSystemVintfDir), _, _))
756         .WillOnce(Invoke([](const auto&, auto* out, auto*) {
757             *out = {
758                 "compatibility_matrix.1.xml",
759                 "compatibility_matrix.empty.xml",
760             };
761             return ::android::OK;
762         }));
763     EXPECT_CALL(fetcher(), listFiles(StrEq(kProductVintfDir), _, _))
764         .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
765             *out = {android::base::Basename(kProductMatrix)};
766             return ::android::OK;
767         }));
768     expectFetch(kSystemVintfDir + "compatibility_matrix.1.xml"s,
769                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\"/>");
770     expectFetch(kSystemVintfDir + "compatibility_matrix.empty.xml"s,
771                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\"/>");
772     expectFetch(kProductMatrix,
773                 "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\">\n"
774                 "    <hal format=\"hidl\" optional=\"true\">\n"
775                 "        <name>android.hardware.foo</name>\n"
776                 "        <version>1.0</version>\n"
777                 "        <interface>\n"
778                 "            <name>IFoo</name>\n"
779                 "            <instance>default</instance>\n"
780                 "        </interface>\n"
781                 "    </hal>\n"
782                 "</compatibility-matrix>\n");
783     expectFetch(kVendorManifest, "<manifest " + kMetaVersionStr + " type=\"device\" />\n");
784     expectNeverFetch(kSystemLegacyMatrix);
785 
786     auto fcm = vintfObject->getFrameworkCompatibilityMatrix();
787     ASSERT_NE(nullptr, fcm);
788 
789     FqInstance expectInstance;
790     EXPECT_TRUE(expectInstance.setTo("android.hardware.foo@1.0::IFoo/default"));
791     bool found = false;
792     fcm->forEachHidlInstance([&found, &expectInstance](const auto& matrixInstance) {
793         found |= matrixInstance.isSatisfiedBy(expectInstance);
794         return !found;  // continue if not found
795     });
796     EXPECT_TRUE(found) << "android.hardware.foo@1.0::IFoo/default should be found in matrix:\n"
797                        << toXml(*fcm);
798 }
799 
800 const std::string vendorEtcManifest =
801     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
802     "    <hal format=\"hidl\">\n"
803     "        <name>android.hardware.foo</name>\n"
804     "        <transport>hwbinder</transport>\n"
805     "        <version>1.0</version>\n"
806     "        <version>2.0</version>\n"
807     "        <interface>\n"
808     "            <name>IVendorEtc</name>\n"
809     "            <instance>default</instance>\n"
810     "        </interface>\n"
811     "    </hal>\n"
812     "</manifest>\n";
813 
814 const std::string vendorManifest =
815     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
816     "    <hal format=\"hidl\">\n"
817     "        <name>android.hardware.foo</name>\n"
818     "        <transport>hwbinder</transport>\n"
819     "        <version>1.0</version>\n"
820     "        <interface>\n"
821     "            <name>IVendor</name>\n"
822     "            <instance>default</instance>\n"
823     "        </interface>\n"
824     "    </hal>\n"
825     "</manifest>\n";
826 
827 const std::string odmProductManifest =
828     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
829     "    <hal format=\"hidl\" override=\"true\">\n"
830     "        <name>android.hardware.foo</name>\n"
831     "        <transport>hwbinder</transport>\n"
832     "        <version>1.1</version>\n"
833     "        <interface>\n"
834     "            <name>IOdmProduct</name>\n"
835     "            <instance>default</instance>\n"
836     "        </interface>\n"
837     "    </hal>\n"
838     "</manifest>\n";
839 
840 const std::string odmManifest =
841     "<manifest " + kMetaVersionStr + " type=\"device\">\n"
842     "    <hal format=\"hidl\" override=\"true\">\n"
843     "        <name>android.hardware.foo</name>\n"
844     "        <transport>hwbinder</transport>\n"
845     "        <version>1.1</version>\n"
846     "        <interface>\n"
847     "            <name>IOdm</name>\n"
848     "            <instance>default</instance>\n"
849     "        </interface>\n"
850     "    </hal>\n"
851     "</manifest>\n";
852 
containsVendorManifest(const std::shared_ptr<const HalManifest> & p)853 bool containsVendorManifest(const std::shared_ptr<const HalManifest>& p) {
854     return !p->getHidlInstances("android.hardware.foo", {1, 0}, "IVendor").empty();
855 }
856 
containsVendorEtcManifest(const std::shared_ptr<const HalManifest> & p)857 bool containsVendorEtcManifest(const std::shared_ptr<const HalManifest>& p) {
858     return !p->getHidlInstances("android.hardware.foo", {2, 0}, "IVendorEtc").empty();
859 }
860 
vendorEtcManifestOverridden(const std::shared_ptr<const HalManifest> & p)861 bool vendorEtcManifestOverridden(const std::shared_ptr<const HalManifest>& p) {
862     return p->getHidlInstances("android.hardware.foo", {1, 0}, "IVendorEtc").empty();
863 }
864 
containsOdmManifest(const std::shared_ptr<const HalManifest> & p)865 bool containsOdmManifest(const std::shared_ptr<const HalManifest>& p) {
866     return !p->getHidlInstances("android.hardware.foo", {1, 1}, "IOdm").empty();
867 }
868 
containsOdmProductManifest(const std::shared_ptr<const HalManifest> & p)869 bool containsOdmProductManifest(const std::shared_ptr<const HalManifest>& p) {
870     return !p->getHidlInstances("android.hardware.foo", {1, 1}, "IOdmProduct").empty();
871 }
872 
containsApexManifest(const std::shared_ptr<const HalManifest> & p)873 bool containsApexManifest(const std::shared_ptr<const HalManifest>& p) {
874     return !p->getAidlInstances(apexHalName, "IApex").empty();
875 }
876 
877 class DeviceManifestTest : public VintfObjectTestBase {
878    protected:
expectApex(const std::string & halManifest=apexHalManifest)879     void expectApex(const std::string& halManifest = apexHalManifest) {
880         expectFetchRepeatedly(kApexInfoFile, R"(<apex-info-list>
881             <apex-info moduleName="com.test"
882                 preinstalledModulePath="/vendor/apex/com.test.apex" isActive="true"/>
883             <apex-info moduleName="com.novintf"
884                 preinstalledModulePath="/vendor/apex/com.novintf.apex" isActive="true"/>
885         </apex-info-list>)");
886         EXPECT_CALL(fetcher(), modifiedTime(kApexInfoFile, _, _))
887             .WillOnce(Invoke([](auto, timespec* out, auto){
888                 *out = {};
889                 return ::android::OK;
890             }))
891             // Update once, but no more.
892             .WillRepeatedly(Invoke([](auto, timespec* out, auto){
893                 *out = {1,};
894                 return ::android::OK;
895             }))
896             ;
897         ON_CALL(fetcher(), listFiles("/apex/com.test/etc/vintf/", _, _))
898             .WillByDefault(Invoke([](auto, std::vector<std::string>* out, auto){
899                 *out = {"manifest.xml"};
900                 return ::android::OK;
901             }));
902         expectFetchRepeatedly("/apex/com.test/etc/vintf/manifest.xml", halManifest);
903     }
904 
905     // Expect that /vendor/etc/vintf/manifest.xml is fetched.
expectVendorManifest()906     void expectVendorManifest() {
907         expectFetchRepeatedly(kVendorManifest, vendorEtcManifest);
908     }
909     // /vendor/etc/vintf/manifest.xml does not exist.
noVendorManifest()910     void noVendorManifest() { expectFileNotExist(StrEq(kVendorManifest)); }
911     // Expect some ODM manifest is fetched.
expectOdmManifest()912     void expectOdmManifest() {
913         expectFetchRepeatedly(kOdmManifest, odmManifest);
914     }
noOdmManifest()915     void noOdmManifest() { expectFileNotExist(StartsWith("/odm/")); }
get()916     std::shared_ptr<const HalManifest> get() {
917         return vintfObject->getDeviceHalManifest();
918     }
919 };
920 
921 // Test /vendor/etc/vintf/manifest.xml + ODM manifest
TEST_F(DeviceManifestTest,Combine1)922 TEST_F(DeviceManifestTest, Combine1) {
923     expectVendorManifest();
924     expectOdmManifest();
925     noApex();
926     auto p = get();
927     ASSERT_NE(nullptr, p);
928     EXPECT_TRUE(containsVendorEtcManifest(p));
929     EXPECT_TRUE(vendorEtcManifestOverridden(p));
930     EXPECT_TRUE(containsOdmManifest(p));
931     EXPECT_FALSE(containsVendorManifest(p));
932 }
933 
934 // Test /vendor/etc/vintf/manifest.xml
TEST_F(DeviceManifestTest,Combine2)935 TEST_F(DeviceManifestTest, Combine2) {
936     expectVendorManifest();
937     noOdmManifest();
938     noApex();
939     auto p = get();
940     ASSERT_NE(nullptr, p);
941     EXPECT_TRUE(containsVendorEtcManifest(p));
942     EXPECT_FALSE(vendorEtcManifestOverridden(p));
943     EXPECT_FALSE(containsOdmManifest(p));
944     EXPECT_FALSE(containsVendorManifest(p));
945 }
946 
947 // Test ODM manifest
TEST_F(DeviceManifestTest,Combine3)948 TEST_F(DeviceManifestTest, Combine3) {
949     noVendorManifest();
950     expectOdmManifest();
951     noApex();
952     auto p = get();
953     ASSERT_NE(nullptr, p);
954     EXPECT_FALSE(containsVendorEtcManifest(p));
955     EXPECT_TRUE(vendorEtcManifestOverridden(p));
956     EXPECT_TRUE(containsOdmManifest(p));
957     EXPECT_FALSE(containsVendorManifest(p));
958 }
959 
960 // Test /vendor/manifest.xml
TEST_F(DeviceManifestTest,Combine4)961 TEST_F(DeviceManifestTest, Combine4) {
962     noVendorManifest();
963     noOdmManifest();
964     noApex();
965     expectFetch(kVendorLegacyManifest, vendorManifest);
966     auto p = get();
967     ASSERT_NE(nullptr, p);
968     EXPECT_FALSE(containsVendorEtcManifest(p));
969     EXPECT_TRUE(vendorEtcManifestOverridden(p));
970     EXPECT_FALSE(containsOdmManifest(p));
971     EXPECT_TRUE(containsVendorManifest(p));
972 }
973 
974 // Run the same tests as above (Combine1,2,3,4) including APEX data.
975 
976 // Test /vendor/etc/vintf/manifest.xml + ODM manifest + APEX
TEST_F(DeviceManifestTest,Combine5)977 TEST_F(DeviceManifestTest, Combine5) {
978     expectVendorManifest();
979     expectOdmManifest();
980     expectApex();
981     auto p = get();
982     ASSERT_NE(nullptr, p);
983     EXPECT_TRUE(containsVendorEtcManifest(p));
984     EXPECT_TRUE(vendorEtcManifestOverridden(p));
985     EXPECT_TRUE(containsOdmManifest(p));
986     EXPECT_FALSE(containsVendorManifest(p));
987     EXPECT_TRUE(containsApexManifest(p));
988 
989     // Second call should create new maninfest containing APEX info.
990     auto p2 = get();
991     ASSERT_NE(nullptr, p2);
992     ASSERT_NE(p, p2);
993 
994     // Third call expect no update and no call to DeviceVintfDirs.
995     auto p3 = get();
996     ASSERT_EQ(p2,p3);
997 }
998 
999 // Tests for valid/invalid APEX defined HAL
1000 // For a HAL to be defined within an APEX it must not have
1001 // the update-via-apex attribute defined in the HAL manifest
1002 
1003 // Valid APEX HAL definition
TEST_F(DeviceManifestTest,ValidApexHal)1004 TEST_F(DeviceManifestTest, ValidApexHal) {
1005     expectVendorManifest();
1006     noOdmManifest();
1007     expectApex();
1008     auto p = get();
1009     ASSERT_NE(nullptr, p);
1010     // HALs defined in APEX should set updatable-via-apex
1011     bool found = false;
1012     p->forEachInstance([&found](const ManifestInstance& instance){
1013         if (instance.package() == apexHalName) {
1014             std::optional<std::string> apexName = "com.test";
1015             EXPECT_EQ(apexName, instance.updatableViaApex());
1016             found = true;
1017         }
1018         return true;
1019     });
1020     ASSERT_TRUE(found) << "should found android.apex.foo";
1021 }
1022 // Invalid APEX HAL definition
TEST_F(DeviceManifestTest,InvalidApexHal)1023 TEST_F(DeviceManifestTest, InvalidApexHal) {
1024     const std::string apexInvalidManifest =
1025         "<manifest " + kMetaVersionStr + " type=\"device\">\n"
1026         "    <hal format=\"aidl\" updatable-via-apex=\"com.android.apex.foo\">\n"
1027         "        <name>android.apex.foo</name>\n"
1028         "        <fqname>IApex/default</fqname>\n"
1029         "    </hal>\n"
1030         "</manifest>\n";
1031     expectVendorManifest();
1032     noOdmManifest();
1033     expectApex(apexInvalidManifest);
1034     auto p = get();
1035     ASSERT_EQ(nullptr, p);
1036 }
1037 
1038 struct VendorApexTest : DeviceManifestTest {
SetUpandroid::vintf::testing::VendorApexTest1039     virtual void SetUp() override {
1040         // Use actual Apex implementation
1041         vintfObject = VintfObject::Builder()
1042                           .setFileSystem(std::make_unique<NiceMock<MockFileSystem>>())
1043                           .setRuntimeInfoFactory(std::make_unique<NiceMock<MockRuntimeInfoFactory>>(
1044                               std::make_shared<NiceMock<MockRuntimeInfo>>()))
1045                           .setPropertyFetcher(std::make_unique<NiceMock<MockPropertyFetcher>>())
1046                           .build();
1047         expectVendorManifest();
1048         noOdmManifest();
1049 
1050         EXPECT_CALL(fetcher(), listFiles(_, _, _))
1051             .WillRepeatedly(Invoke([](const auto&, auto*, auto*) {
1052                 return ::android::OK;
1053             }));
1054         EXPECT_CALL(fetcher(), modifiedTime(_, _, _))
1055             .WillRepeatedly(Invoke([](const auto&, auto*, auto*) {
1056                 return ::android::OK;
1057             }));
1058     }
1059 };
1060 
TEST_F(VendorApexTest,ReadBootstrapApexBeforeApexReady)1061 TEST_F(VendorApexTest, ReadBootstrapApexBeforeApexReady) {
1062     // When APEXes are not ready,
1063     ON_CALL(propertyFetcher(), getBoolProperty("apex.all.ready", _))
1064         .WillByDefault(Return(false));
1065     // Should read bootstrap APEXes from /bootstrap-apex
1066     EXPECT_CALL(fetcher(), fetch(kBootstrapApexInfoFile, _))
1067         .WillOnce(Invoke([](const auto&, auto& out) {
1068             out = R"(<?xml version="1.0" encoding="utf-8"?>
1069                 <apex-info-list>
1070                     <apex-info moduleName="com.vendor.foo"
1071                             preinstalledModulePath="/vendor/apex/foo.apex"
1072                             isActive="true" />
1073                 </apex-info-list>)";
1074             return ::android::OK;
1075         }));
1076     // ... and read VINTF directory in it.
1077     EXPECT_CALL(fetcher(), listFiles("/bootstrap-apex/com.vendor.foo/etc/vintf/", _, _))
1078         .WillOnce(Invoke([](const auto&, auto*, auto*) {
1079             return ::android::OK;
1080         }));
1081     auto p = get();
1082     (void) p;
1083 }
1084 
TEST_F(VendorApexTest,OkayIfBootstrapApexDirDoesntExist)1085 TEST_F(VendorApexTest, OkayIfBootstrapApexDirDoesntExist) {
1086     // When APEXes are not ready,
1087     ON_CALL(propertyFetcher(), getBoolProperty("apex.all.ready", _))
1088         .WillByDefault(Return(false));
1089     // Should try to read bootstrap APEXes from /bootstrap-apex
1090     EXPECT_CALL(fetcher(), fetch(kBootstrapApexInfoFile, _))
1091         .WillOnce(Invoke([](const auto&, auto&) {
1092             return NAME_NOT_FOUND;
1093         }));
1094     // Doesn't fallback to normal APEX if APEXes are not ready.
1095     EXPECT_CALL(fetcher(), fetch(kApexInfoFile, _)).Times(0);
1096     auto p = get();
1097     (void) p;
1098 }
1099 
TEST_F(VendorApexTest,DoNotReadBootstrapApexWhenApexesAreReady)1100 TEST_F(VendorApexTest, DoNotReadBootstrapApexWhenApexesAreReady) {
1101     // When APEXes are ready,
1102     ON_CALL(propertyFetcher(), getBoolProperty("apex.all.ready", _))
1103         .WillByDefault(Return(true));
1104     // Should NOT read bootstrap APEXes
1105     EXPECT_CALL(fetcher(), fetch(kBootstrapApexInfoFile, _))
1106         .Times(0);
1107     // Instead, read /apex/apex-info-list.xml
1108     EXPECT_CALL(fetcher(), fetch(kApexInfoFile, _));
1109     auto p = get();
1110     (void) p;
1111 }
1112 
1113 class OdmManifestTest : public VintfObjectTestBase,
1114                          public ::testing::WithParamInterface<const char*> {
1115    protected:
SetUp()1116     virtual void SetUp() override {
1117         VintfObjectTestBase::SetUp();
1118         // Assume /vendor/etc/vintf/manifest.xml does not exist to simplify
1119         // testing logic.
1120         expectFileNotExist(StrEq(kVendorManifest));
1121         // Expect that the legacy /vendor/manifest.xml is never fetched.
1122         expectNeverFetch(kVendorLegacyManifest);
1123         // Assume no files exist under /odm/ unless otherwise specified.
1124         expectFileNotExist(StartsWith("/odm/"));
1125         noApex();
1126         // set SKU
1127         productModel = GetParam();
1128         ON_CALL(propertyFetcher(), getProperty("ro.boot.product.hardware.sku", _))
1129             .WillByDefault(Return(productModel));
1130     }
get()1131     std::shared_ptr<const HalManifest> get() {
1132         return vintfObject->getDeviceHalManifest();
1133     }
1134     std::string productModel;
1135 };
1136 
TEST_P(OdmManifestTest,OdmProductManifest)1137 TEST_P(OdmManifestTest, OdmProductManifest) {
1138     if (productModel.empty()) return;
1139     expectFetch(kOdmVintfDir + "manifest_"s + productModel + ".xml", odmProductManifest);
1140     // /odm/etc/vintf/manifest.xml should not be fetched when the product variant exists.
1141     expectNeverFetch(kOdmManifest);
1142     auto p = get();
1143     ASSERT_NE(nullptr, p);
1144     EXPECT_TRUE(containsOdmProductManifest(p));
1145 }
1146 
TEST_P(OdmManifestTest,OdmManifest)1147 TEST_P(OdmManifestTest, OdmManifest) {
1148     expectFetch(kOdmManifest, odmManifest);
1149     auto p = get();
1150     ASSERT_NE(nullptr, p);
1151     EXPECT_TRUE(containsOdmManifest(p));
1152 }
1153 
TEST_P(OdmManifestTest,OdmLegacyProductManifest)1154 TEST_P(OdmManifestTest, OdmLegacyProductManifest) {
1155     if (productModel.empty()) return;
1156     expectFetch(kOdmLegacyVintfDir + "manifest_"s + productModel + ".xml", odmProductManifest);
1157     // /odm/manifest.xml should not be fetched when the product variant exists.
1158     expectNeverFetch(kOdmLegacyManifest);
1159     auto p = get();
1160     ASSERT_NE(nullptr, p);
1161     EXPECT_TRUE(containsOdmProductManifest(p));
1162 }
1163 
TEST_P(OdmManifestTest,OdmLegacyManifest)1164 TEST_P(OdmManifestTest, OdmLegacyManifest) {
1165     expectFetch(kOdmLegacyManifest, odmManifest);
1166     auto p = get();
1167     ASSERT_NE(nullptr, p);
1168     EXPECT_TRUE(containsOdmManifest(p));
1169 }
1170 
1171 INSTANTIATE_TEST_SUITE_P(OdmManifest, OdmManifestTest, ::testing::Values("", "fake_sku"));
1172 
1173 struct ManifestOverrideTest : public VintfObjectTestBase {
1174   protected:
SetUpandroid::vintf::testing::ManifestOverrideTest1175     void SetUp() override {
1176         VintfObjectTestBase::SetUp();
1177         ON_CALL(fetcher(), fetch(_, _))
1178             .WillByDefault(Invoke([&](auto path, std::string& out) {
1179                 auto dirIt = dirs_.find(base::Dirname(path) + "/");
1180                 if (dirIt != dirs_.end()) {
1181                     auto fileIt = dirIt->second.find(base::Basename(path));
1182                     if (fileIt != dirIt->second.end()) {
1183                         out = fileIt->second;
1184                         return OK;
1185                     }
1186                 }
1187                 return NAME_NOT_FOUND;
1188             }));
1189         ON_CALL(fetcher(), listFiles(_, _, _))
1190             .WillByDefault(Invoke([&](auto path, std::vector<std::string>* out, auto) {
1191                 auto dirIt = dirs_.find(path);
1192                 if (dirIt != dirs_.end()) {
1193                     for (const auto& [f, _]: dirIt->second) {
1194                         out->push_back(f);
1195                     }
1196                     return OK;
1197                 }
1198                 return NAME_NOT_FOUND;
1199             }));
1200     }
expectandroid::vintf::testing::ManifestOverrideTest1201     void expect(std::string path, std::string content) {
1202         dirs_[base::Dirname(path) + "/"][base::Basename(path)] = content;
1203     }
1204   private:
1205     std::map<std::string, std::map<std::string, std::string>> dirs_;
1206 };
1207 
TEST_F(ManifestOverrideTest,NoOverrideForVendor)1208 TEST_F(ManifestOverrideTest, NoOverrideForVendor) {
1209     expect(kVendorManifest,
1210         "<manifest " + kMetaVersionStr + " type=\"device\">"
1211         "  <hal format=\"aidl\">"
1212         "    <name>android.hardware.foo</name>"
1213         "    <fqname>IFoo/default</fqname>"
1214         "  </hal>"
1215         "</manifest>");
1216     auto p = vintfObject->getDeviceHalManifest();
1217     ASSERT_NE(nullptr, p);
1218     ASSERT_EQ(p->getAidlInstances("android.hardware.foo", "IFoo"),
1219         std::set<std::string>({"default"}));
1220 }
1221 
TEST_F(ManifestOverrideTest,OdmOverridesVendor)1222 TEST_F(ManifestOverrideTest, OdmOverridesVendor) {
1223     expect(kVendorManifest, "<manifest " + kMetaVersionStr + " type=\"device\">"
1224         "  <hal format=\"aidl\">"
1225         "    <name>android.hardware.foo</name>"
1226         "    <fqname>IFoo/default</fqname>"
1227         "  </hal>"
1228         "</manifest>");
1229     // ODM overrides(disables) HAL in Vendor
1230     expect(kOdmManifest, "<manifest " + kMetaVersionStr + " type=\"device\">"
1231         "  <hal override=\"true\" format=\"aidl\">"
1232         "    <name>android.hardware.foo</name>"
1233         "  </hal>"
1234         "</manifest>");
1235     auto p = vintfObject->getDeviceHalManifest();
1236     ASSERT_NE(nullptr, p);
1237     ASSERT_EQ(p->getAidlInstances("android.hardware.foo", "IFoo"), std::set<std::string>({}));
1238 }
1239 
TEST_F(ManifestOverrideTest,NoOverrideForVendorApex)1240 TEST_F(ManifestOverrideTest, NoOverrideForVendorApex) {
1241     expect(kVendorManifest,
1242         "<manifest " + kMetaVersionStr + " type=\"device\" />");
1243     expect(kApexInfoFile,
1244         R"(<apex-info-list>
1245           <apex-info
1246             moduleName="com.android.foo"
1247             preinstalledModulePath="/vendor/apex/com.android.foo.apex"
1248             isActive="true"/>
1249         </apex-info-list>)");
1250     expect("/apex/com.android.foo/etc/vintf/foo.xml",
1251         "<manifest " + kMetaVersionStr + "type=\"device\">"
1252         "  <hal format=\"aidl\">"
1253         "    <name>android.hardware.foo</name>"
1254         "    <fqname>IFoo/default</fqname>"
1255         "  </hal>"
1256         "</manifest>");
1257     auto p = vintfObject->getDeviceHalManifest();
1258     ASSERT_NE(nullptr, p);
1259     ASSERT_EQ(p->getAidlInstances("android.hardware.foo", "IFoo"),
1260         std::set<std::string>({"default"}));
1261 }
1262 
TEST_F(ManifestOverrideTest,OdmOverridesVendorApex)1263 TEST_F(ManifestOverrideTest, OdmOverridesVendorApex) {
1264     expect(kVendorManifest,
1265         "<manifest " + kMetaVersionStr + " type=\"device\" />");
1266     expect(kApexInfoFile,
1267         R"(<apex-info-list>
1268             <apex-info
1269                 moduleName="com.android.foo"
1270                 preinstalledModulePath="/vendor/apex/com.android.foo.apex"
1271                 isActive="true"/>
1272             </apex-info-list>)");
1273     expect("/apex/com.android.foo/etc/vintf/foo.xml",
1274         "<manifest " + kMetaVersionStr + "type=\"device\">"
1275         "  <hal format=\"aidl\">"
1276         "    <name>android.hardware.foo</name>"
1277         "    <fqname>IFoo/default</fqname>"
1278         "  </hal>"
1279         "</manifest>");
1280     // ODM overrides(disables) HAL in Vendor APEX
1281     expect(kOdmManifest, "<manifest " + kMetaVersionStr + " type=\"device\">"
1282         "  <hal override=\"true\" format=\"aidl\">"
1283         "    <name>android.hardware.foo</name>"
1284         "  </hal>"
1285         "</manifest>");
1286     auto p = vintfObject->getDeviceHalManifest();
1287     ASSERT_NE(nullptr, p);
1288     ASSERT_EQ(p->getAidlInstances("android.hardware.foo", "IFoo"),
1289         std::set<std::string>({}));
1290 }
1291 
1292 struct CheckedFqInstance : FqInstance {
CheckedFqInstanceandroid::vintf::testing::CheckedFqInstance1293     CheckedFqInstance(const char* s) : CheckedFqInstance(std::string(s)) {}
CheckedFqInstanceandroid::vintf::testing::CheckedFqInstance1294     CheckedFqInstance(const std::string& s) { CHECK(setTo(s)) << s; }
1295 
getVersionandroid::vintf::testing::CheckedFqInstance1296     Version getVersion() const { return FqInstance::getVersion(); }
1297 };
1298 
1299 class DeprecateTest : public VintfObjectTestBase {
1300    protected:
SetUp()1301     virtual void SetUp() override {
1302         VintfObjectTestBase::SetUp();
1303         useEmptyFileSystem();
1304         EXPECT_CALL(fetcher(), listFiles(StrEq(kSystemVintfDir), _, _))
1305             .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
1306                 *out = {
1307                     "compatibility_matrix.1.xml",
1308                     "compatibility_matrix.2.xml",
1309                 };
1310                 return ::android::OK;
1311             }));
1312         expectFetchRepeatedly(kSystemVintfDir + "compatibility_matrix.1.xml"s, systemMatrixLevel1);
1313         expectFetchRepeatedly(kSystemVintfDir + "compatibility_matrix.2.xml"s, systemMatrixLevel2);
1314         EXPECT_CALL(fetcher(), listFiles(StrEq(kProductVintfDir), _, _))
1315             .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
1316                 *out = {
1317                     "compatibility_matrix.1.xml",
1318                     "compatibility_matrix.2.xml",
1319                 };
1320                 return ::android::OK;
1321             }));
1322         expectFetchRepeatedly(kProductVintfDir + "compatibility_matrix.1.xml"s,
1323                               productMatrixLevel1);
1324         expectFetchRepeatedly(kProductVintfDir + "compatibility_matrix.2.xml"s,
1325                               productMatrixLevel2);
1326         expectFileNotExist(StrEq(kProductMatrix));
1327         expectNeverFetch(kSystemLegacyMatrix);
1328 
1329         expectFileNotExist(StartsWith("/odm/"));
1330     }
1331 };
1332 
1333 // clang-format on
1334 
aidlFqInstance(const std::string & package,size_t version,const std::string & interface,const std::string & instance)1335 FqInstance aidlFqInstance(const std::string& package, size_t version, const std::string& interface,
1336                           const std::string& instance) {
1337     auto ret = FqInstance::from(package, kFakeAidlMajorVersion, version, interface, instance);
1338     EXPECT_TRUE(ret.has_value());
1339     return ret.value_or(FqInstance());
1340 }
1341 
1342 // clang-format off
1343 
TEST_F(DeprecateTest,CheckNoDeprecate)1344 TEST_F(DeprecateTest, CheckNoDeprecate) {
1345     expectVendorManifest(Level{2}, {
1346         "android.hardware.minor@1.1::IMinor/default",
1347         "android.hardware.major@2.0::IMajor/default",
1348         "product.minor@1.1::IMinor/default",
1349     }, {
1350         aidlFqInstance("android.hardware.minor", 102, "IMinor", "default"),
1351     });
1352     std::string error;
1353     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation({}, &error)) << error;
1354 }
1355 
TEST_F(DeprecateTest,CheckRemovedSystem)1356 TEST_F(DeprecateTest, CheckRemovedSystem) {
1357     expectVendorManifest(Level{2}, {
1358         "android.hardware.removed@1.0::IRemoved/default",
1359         "android.hardware.minor@1.1::IMinor/default",
1360         "android.hardware.major@2.0::IMajor/default",
1361     });
1362     std::string error;
1363     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1364         << "removed@1.0 should be deprecated. " << error;
1365 }
1366 
TEST_F(DeprecateTest,CheckRemovedSystemAidl)1367 TEST_F(DeprecateTest, CheckRemovedSystemAidl) {
1368     expectVendorManifest(Level{2}, {}, {
1369         aidlFqInstance("android.hardware.removed", 101, "IRemoved", "default"),
1370     });
1371     std::string error;
1372     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1373         << "removed@101 should be deprecated. " << error;
1374 }
1375 
TEST_F(DeprecateTest,CheckRemovedProduct)1376 TEST_F(DeprecateTest, CheckRemovedProduct) {
1377     expectVendorManifest(Level{2}, {
1378         "product.removed@1.0::IRemoved/default",
1379         "product.minor@1.1::IMinor/default",
1380     });
1381     std::string error;
1382     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1383         << "removed@1.0 should be deprecated. " << error;
1384 }
1385 
TEST_F(DeprecateTest,CheckMinorSystem)1386 TEST_F(DeprecateTest, CheckMinorSystem) {
1387     expectVendorManifest(Level{2}, {
1388         "android.hardware.minor@1.0::IMinor/default",
1389         "android.hardware.major@2.0::IMajor/default",
1390     });
1391     std::string error;
1392     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1393         << "minor@1.0 should be deprecated. " << error;
1394 }
1395 
TEST_F(DeprecateTest,CheckMinorSystemAidl)1396 TEST_F(DeprecateTest, CheckMinorSystemAidl) {
1397     expectVendorManifest(Level{2}, {}, {
1398         aidlFqInstance("android.hardware.minor", 101, "IMinor", "default"),
1399     });
1400     std::string error;
1401     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1402         << "minor@101 should be deprecated. " << error;
1403 }
1404 
TEST_F(DeprecateTest,CheckMinorProduct)1405 TEST_F(DeprecateTest, CheckMinorProduct) {
1406     expectVendorManifest(Level{2}, {
1407         "product.minor@1.0::IMinor/default",
1408     });
1409     std::string error;
1410     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1411         << "minor@1.0 should be deprecated. " << error;
1412 }
1413 
TEST_F(DeprecateTest,CheckMinorDeprecatedInstance1)1414 TEST_F(DeprecateTest, CheckMinorDeprecatedInstance1) {
1415     expectVendorManifest(Level{2}, {
1416         "android.hardware.minor@1.0::IMinor/legacy",
1417         "android.hardware.minor@1.1::IMinor/default",
1418         "android.hardware.major@2.0::IMajor/default",
1419     });
1420     std::string error;
1421     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1422         << "minor@1.0::IMinor/legacy should be deprecated. " << error;
1423 }
1424 
TEST_F(DeprecateTest,CheckMinorDeprecatedInstance2)1425 TEST_F(DeprecateTest, CheckMinorDeprecatedInstance2) {
1426     expectVendorManifest(Level{2}, {
1427         "android.hardware.minor@1.1::IMinor/default",
1428         "android.hardware.minor@1.1::IMinor/legacy",
1429         "android.hardware.major@2.0::IMajor/default",
1430     });
1431     std::string error;
1432     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1433         << "minor@1.1::IMinor/legacy should be deprecated. " << error;
1434 }
1435 
TEST_F(DeprecateTest,CheckMajor1)1436 TEST_F(DeprecateTest, CheckMajor1) {
1437     expectVendorManifest(Level{2}, {
1438         "android.hardware.minor@1.1::IMinor/default",
1439         "android.hardware.major@1.0::IMajor/default",
1440         "android.hardware.major@2.0::IMajor/default",
1441     });
1442     std::string error;
1443     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1444         << "major@1.0 should be deprecated. " << error;
1445 }
1446 
TEST_F(DeprecateTest,CheckMajor2)1447 TEST_F(DeprecateTest, CheckMajor2) {
1448     expectVendorManifest(Level{2}, {
1449         "android.hardware.minor@1.1::IMinor/default",
1450         "android.hardware.major@1.0::IMajor/default",
1451     });
1452     std::string error;
1453     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1454         << "major@1.0 should be deprecated. " << error;
1455 }
1456 
TEST_F(DeprecateTest,HidlMetadataNotDeprecate)1457 TEST_F(DeprecateTest, HidlMetadataNotDeprecate) {
1458     expectVendorManifest(Level{2}, {
1459         "android.hardware.major@1.0::IMajor/default",
1460         "android.hardware.major@2.0::IMajor/default",
1461     });
1462     std::string error;
1463     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1464         << "major@1.0 should be deprecated. " << error;
1465     std::vector<HidlInterfaceMetadata> hidlMetadata{
1466       {"android.hardware.major@2.0::IMajor", {"android.hardware.major@1.0::IMajor"}},
1467     };
1468     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation(hidlMetadata, &error))
1469         << "major@1.0 should not be deprecated because it extends from 2.0: " << error;
1470 }
1471 
TEST_F(DeprecateTest,HidlMetadataDeprecate)1472 TEST_F(DeprecateTest, HidlMetadataDeprecate) {
1473     expectVendorManifest(Level{2}, {
1474         "android.hardware.major@1.0::IMajor/default",
1475     });
1476     std::string error;
1477     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1478         << "major@1.0 should be deprecated. " << error;
1479     std::vector<HidlInterfaceMetadata> hidlMetadata{
1480       {"android.hardware.major@2.0::IMajor", {"android.hardware.major@1.0::IMajor"}},
1481     };
1482     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation(hidlMetadata, &error))
1483         << "major@1.0 should be deprecated. " << error;
1484 }
1485 
1486 class RegexInstanceDeprecateTest : public VintfObjectTestBase {
1487    protected:
SetUp()1488     virtual void SetUp() override {
1489         VintfObjectTestBase::SetUp();
1490         useEmptyFileSystem();
1491         EXPECT_CALL(fetcher(), listFiles(StrEq(kSystemVintfDir), _, _))
1492             .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
1493                 *out = {
1494                     "compatibility_matrix.1.xml",
1495                     "compatibility_matrix.2.xml",
1496                 };
1497                 return ::android::OK;
1498             }));
1499         expectFetchRepeatedly(kSystemVintfDir + "compatibility_matrix.1.xml"s,
1500             "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
1501             "    <hal format=\"hidl\" optional=\"true\">\n"
1502             "        <name>android.hardware.minor</name>\n"
1503             "        <version>1.1</version>\n"
1504             "        <interface>\n"
1505             "            <name>IMinor</name>\n"
1506             "            <regex-instance>instance.*</regex-instance>\n"
1507             "        </interface>\n"
1508             "    </hal>\n"
1509             "    <hal format=\"aidl\" optional=\"true\">\n"
1510             "        <name>android.hardware.minor</name>\n"
1511             "        <version>101</version>\n"
1512             "        <interface>\n"
1513             "            <name>IMinor</name>\n"
1514             "            <regex-instance>instance.*</regex-instance>\n"
1515             "        </interface>\n"
1516             "    </hal>\n"
1517             "</compatibility-matrix>\n"
1518         );
1519         expectFetchRepeatedly(kSystemVintfDir + "compatibility_matrix.2.xml"s,
1520             "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
1521             "    <hal format=\"hidl\" optional=\"true\">\n"
1522             "        <name>android.hardware.minor</name>\n"
1523             "        <version>1.2</version>\n"
1524             "        <interface>\n"
1525             "            <name>IMinor</name>\n"
1526             "            <regex-instance>instance.*</regex-instance>\n"
1527             "        </interface>\n"
1528             "    </hal>\n"
1529             "    <hal format=\"aidl\" optional=\"true\">\n"
1530             "        <name>android.hardware.minor</name>\n"
1531             "        <version>102</version>\n"
1532             "        <interface>\n"
1533             "            <name>IMinor</name>\n"
1534             "            <regex-instance>instance.*</regex-instance>\n"
1535             "        </interface>\n"
1536             "    </hal>\n"
1537             "</compatibility-matrix>\n");
1538         expectFileNotExist(StrEq(kProductMatrix));
1539         expectNeverFetch(kSystemLegacyMatrix);
1540 
1541         expectFileNotExist(StartsWith("/odm/"));
1542     }
1543 };
1544 
TEST_F(RegexInstanceDeprecateTest,HidlNoDeprecate)1545 TEST_F(RegexInstanceDeprecateTest, HidlNoDeprecate) {
1546     expectVendorManifest(Level{2}, {
1547         "android.hardware.minor@1.2::IMinor/instance1",
1548     }, {
1549         aidlFqInstance("android.hardware.minor", 102, "IMinor", "instance1"),
1550     });
1551     std::string error;
1552     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation({}, &error)) << error;
1553 }
1554 
TEST_F(RegexInstanceDeprecateTest,HidlDeprecate)1555 TEST_F(RegexInstanceDeprecateTest, HidlDeprecate) {
1556     expectVendorManifest(Level{2}, {
1557         "android.hardware.minor@1.2::IMinor/instance1",
1558         "android.hardware.minor@1.1::IMinor/instance2",
1559     }, {});
1560     std::string error;
1561     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1562         << "minor@1.1::IMinor/instance2 is deprecated";
1563 }
1564 
TEST_F(RegexInstanceDeprecateTest,AidlDeprecate)1565 TEST_F(RegexInstanceDeprecateTest, AidlDeprecate) {
1566     expectVendorManifest(Level{2}, {}, {
1567         aidlFqInstance("android.hardware.minor", 102, "IMinor", "instance1"),
1568         aidlFqInstance("android.hardware.minor", 101, "IMinor", "instance2"),
1569     });
1570     std::string error;
1571     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1572         << "minor@101::IMinor/instance2 is deprecated";
1573 }
1574 
1575 class MultiMatrixTest : public VintfObjectTestBase {
1576    protected:
SetUp()1577     void SetUp() override {
1578         VintfObjectTestBase::SetUp();
1579         useEmptyFileSystem();
1580     }
getFileName(size_t i)1581     static std::string getFileName(size_t i) {
1582         return "compatibility_matrix." + to_string(static_cast<Level>(i)) + ".xml";
1583     }
SetUpMockSystemMatrices(const std::vector<std::string> & xmls)1584     void SetUpMockSystemMatrices(const std::vector<std::string>& xmls) {
1585         SetUpMockMatrices(kSystemVintfDir, xmls);
1586     }
SetUpMockMatrices(const std::string & dir,const std::vector<std::string> & xmls)1587     void SetUpMockMatrices(const std::string& dir, const std::vector<std::string>& xmls) {
1588         EXPECT_CALL(fetcher(), listFiles(StrEq(dir), _, _))
1589             .WillRepeatedly(Invoke([=](const auto&, auto* out, auto*) {
1590                 size_t i = 1;
1591                 for (const auto& content : xmls) {
1592                     (void)content;
1593                     out->push_back(getFileName(i));
1594                     ++i;
1595                 }
1596                 return ::android::OK;
1597             }));
1598         size_t i = 1;
1599         for (const auto& content : xmls) {
1600             expectFetchRepeatedly(dir + getFileName(i), content);
1601             ++i;
1602         }
1603     }
expectTargetFcmVersion(size_t level)1604     void expectTargetFcmVersion(size_t level) {
1605         expectVendorManifest(Level{level}, {});
1606     }
1607 };
1608 
1609 class RegexTest : public MultiMatrixTest {
1610    protected:
SetUp()1611     virtual void SetUp() {
1612         MultiMatrixTest::SetUp();
1613         SetUpMockSystemMatrices(systemMatrixRegexXmls);
1614     }
1615 };
1616 
TEST_F(RegexTest,CombineLevel1)1617 TEST_F(RegexTest, CombineLevel1) {
1618     expectTargetFcmVersion(1);
1619     auto matrix = vintfObject->getFrameworkCompatibilityMatrix();
1620     ASSERT_NE(nullptr, matrix);
1621     std::string xml = toXml(*matrix);
1622 
1623     EXPECT_IN(
1624         "    <hal format=\"hidl\" optional=\"false\">\n"
1625         "        <name>android.hardware.regex</name>\n"
1626         "        <version>1.0-2</version>\n"
1627         "        <version>2.0</version>\n"
1628         "        <interface>\n"
1629         "            <name>IRegex</name>\n"
1630         "            <instance>default</instance>\n"
1631         "        </interface>\n"
1632         "    </hal>\n",
1633         xml);
1634     EXPECT_IN(
1635         "    <hal format=\"hidl\" optional=\"false\">\n"
1636         "        <name>android.hardware.regex</name>\n"
1637         "        <version>1.0-1</version>\n"
1638         "        <interface>\n"
1639         "            <name>IRegex</name>\n"
1640         "            <instance>special/1.0</instance>\n"
1641         "            <regex-instance>regex/1.0/[0-9]+</regex-instance>\n"
1642         "            <regex-instance>regex_common/[0-9]+</regex-instance>\n"
1643         "        </interface>\n"
1644         "    </hal>\n",
1645         xml);
1646     EXPECT_IN(
1647         "    <hal format=\"hidl\" optional=\"true\">\n"
1648         "        <name>android.hardware.regex</name>\n"
1649         "        <version>1.1-2</version>\n"
1650         "        <interface>\n"
1651         "            <name>IRegex</name>\n"
1652         "            <instance>special/1.1</instance>\n"
1653         "            <regex-instance>[a-z]+_[a-z]+/[0-9]+</regex-instance>\n"
1654         "            <regex-instance>regex/1.1/[0-9]+</regex-instance>\n"
1655         "        </interface>\n"
1656         "    </hal>\n",
1657         xml);
1658     EXPECT_IN(
1659         "    <hal format=\"hidl\" optional=\"true\">\n"
1660         "        <name>android.hardware.regex</name>\n"
1661         "        <version>2.0</version>\n"
1662         "        <interface>\n"
1663         "            <name>IRegex</name>\n"
1664         "            <instance>special/2.0</instance>\n"
1665         "            <regex-instance>regex/2.0/[0-9]+</regex-instance>\n"
1666         "            <regex-instance>regex_[a-z]+/[0-9]+</regex-instance>\n"
1667         "        </interface>\n"
1668         "    </hal>\n",
1669         xml);
1670 }
1671 
TEST_F(RegexTest,CombineLevel2)1672 TEST_F(RegexTest, CombineLevel2) {
1673     expectTargetFcmVersion(2);
1674     auto matrix = vintfObject->getFrameworkCompatibilityMatrix();
1675     ASSERT_NE(nullptr, matrix);
1676     std::string xml = toXml(*matrix);
1677 
1678     EXPECT_IN(
1679         "    <hal format=\"hidl\" optional=\"false\">\n"
1680         "        <name>android.hardware.regex</name>\n"
1681         "        <version>1.1-2</version>\n"
1682         "        <version>2.0</version>\n"
1683         "        <interface>\n"
1684         "            <name>IRegex</name>\n"
1685         "            <instance>default</instance>\n"
1686         "        </interface>\n"
1687         "    </hal>\n",
1688         xml);
1689     EXPECT_IN(
1690         "    <hal format=\"hidl\" optional=\"false\">\n"
1691         "        <name>android.hardware.regex</name>\n"
1692         "        <version>1.1-2</version>\n"
1693         "        <interface>\n"
1694         "            <name>IRegex</name>\n"
1695         "            <instance>special/1.1</instance>\n"
1696         "            <regex-instance>[a-z]+_[a-z]+/[0-9]+</regex-instance>\n"
1697         "            <regex-instance>regex/1.1/[0-9]+</regex-instance>\n"
1698         "        </interface>\n"
1699         "    </hal>\n",
1700         xml);
1701     EXPECT_IN(
1702         "    <hal format=\"hidl\" optional=\"true\">\n"
1703         "        <name>android.hardware.regex</name>\n"
1704         "        <version>2.0</version>\n"
1705         "        <interface>\n"
1706         "            <name>IRegex</name>\n"
1707         "            <instance>special/2.0</instance>\n"
1708         "            <regex-instance>regex/2.0/[0-9]+</regex-instance>\n"
1709         "            <regex-instance>regex_[a-z]+/[0-9]+</regex-instance>\n"
1710         "        </interface>\n"
1711         "    </hal>\n",
1712         xml);
1713 }
1714 
1715 // clang-format on
1716 
TEST_F(RegexTest,DeprecateLevel2)1717 TEST_F(RegexTest, DeprecateLevel2) {
1718     std::string error;
1719     expectVendorManifest(Level{2}, {
1720                                        "android.hardware.regex@1.1::IRegex/default",
1721                                        "android.hardware.regex@1.1::IRegex/special/1.1",
1722                                        "android.hardware.regex@1.1::IRegex/regex/1.1/1",
1723                                        "android.hardware.regex@1.1::IRegex/regex_common/0",
1724                                        "android.hardware.regex@2.0::IRegex/default",
1725                                    });
1726     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation({}, &error)) << error;
1727 }
1728 
1729 class RegexTestDeprecateLevel2P : public RegexTest, public WithParamInterface<const char*> {};
TEST_P(RegexTestDeprecateLevel2P,Test)1730 TEST_P(RegexTestDeprecateLevel2P, Test) {
1731     auto deprecated = GetParam();
1732     std::string error;
1733     // 2.0/default ensures compatibility.
1734     expectVendorManifest(Level{2}, {
1735                                        deprecated,
1736                                        "android.hardware.regex@2.0::IRegex/default",
1737                                    });
1738     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1739         << deprecated << " should be deprecated. " << error;
1740 }
1741 
1742 INSTANTIATE_TEST_SUITE_P(RegexTest, RegexTestDeprecateLevel2P,
1743                          ::testing::Values("android.hardware.regex@1.0::IRegex/default",
1744                                            "android.hardware.regex@1.0::IRegex/special/1.0",
1745                                            "android.hardware.regex@1.0::IRegex/regex/1.0/1",
1746                                            "android.hardware.regex@1.0::IRegex/regex_common/0",
1747                                            "android.hardware.regex@1.1::IRegex/special/1.0",
1748                                            "android.hardware.regex@1.1::IRegex/regex/1.0/1"));
1749 
TEST_F(RegexTest,DeprecateLevel3)1750 TEST_F(RegexTest, DeprecateLevel3) {
1751     std::string error;
1752     expectVendorManifest(Level{3}, {
1753                                        "android.hardware.regex@2.0::IRegex/special/2.0",
1754                                        "android.hardware.regex@2.0::IRegex/regex/2.0/1",
1755                                        "android.hardware.regex@2.0::IRegex/default",
1756                                    });
1757     EXPECT_EQ(NO_DEPRECATED_HALS, vintfObject->checkDeprecation({}, &error)) << error;
1758 }
1759 
1760 class RegexTestDeprecateLevel3P : public RegexTest, public WithParamInterface<const char*> {};
TEST_P(RegexTestDeprecateLevel3P,Test)1761 TEST_P(RegexTestDeprecateLevel3P, Test) {
1762     auto deprecated = GetParam();
1763     std::string error;
1764     // 2.0/default ensures compatibility.
1765     expectVendorManifest(Level{3}, {
1766                                        deprecated,
1767                                        "android.hardware.regex@2.0::IRegex/default",
1768                                    });
1769     EXPECT_EQ(DEPRECATED, vintfObject->checkDeprecation({}, &error))
1770         << deprecated << " should be deprecated.";
1771 }
1772 
1773 INSTANTIATE_TEST_SUITE_P(RegexTest, RegexTestDeprecateLevel3P,
1774                          ::testing::Values("android.hardware.regex@1.0::IRegex/default",
1775                                            "android.hardware.regex@1.0::IRegex/special/1.0",
1776                                            "android.hardware.regex@1.0::IRegex/regex/1.0/1",
1777                                            "android.hardware.regex@1.0::IRegex/regex_common/0",
1778                                            "android.hardware.regex@1.1::IRegex/special/1.0",
1779                                            "android.hardware.regex@1.1::IRegex/regex/1.0/1",
1780                                            "android.hardware.regex@1.1::IRegex/special/1.1",
1781                                            "android.hardware.regex@1.1::IRegex/regex/1.1/1",
1782                                            "android.hardware.regex@1.1::IRegex/regex_common/0"));
1783 
1784 // clang-format off
1785 
1786 //
1787 // Set of framework matrices of different FCM version with <kernel>.
1788 //
1789 
1790 #define FAKE_KERNEL(__version__, __key__, __level__)                   \
1791     "    <kernel version=\"" __version__ "\" level=\"" #__level__ "\">\n"            \
1792     "        <config>\n"                                    \
1793     "            <key>CONFIG_" __key__ "</key>\n"           \
1794     "            <value type=\"tristate\">y</value>\n"      \
1795     "        </config>\n"                                   \
1796     "    </kernel>\n"
1797 
1798 const static std::vector<std::string> systemMatrixKernelXmls = {
1799     // 1.xml
1800     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
1801     FAKE_KERNEL("1.0.0", "A1", 1)
1802     FAKE_KERNEL("2.0.0", "B1", 1)
1803     "</compatibility-matrix>\n",
1804     // 2.xml
1805     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
1806     FAKE_KERNEL("2.0.0", "B2", 2)
1807     FAKE_KERNEL("3.0.0", "C2", 2)
1808     FAKE_KERNEL("4.0.0", "D2", 2)
1809     "</compatibility-matrix>\n",
1810     // 3.xml
1811     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"3\">\n"
1812     FAKE_KERNEL("4.0.0", "D3", 3)
1813     FAKE_KERNEL("5.0.0", "E3", 3)
1814     "</compatibility-matrix>\n",
1815     // 4.xml
1816     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"4\">\n"
1817     FAKE_KERNEL("5.0.0", "E4", 4)
1818     FAKE_KERNEL("6.0.0", "F4", 4)
1819     "</compatibility-matrix>\n",
1820     // 5.xml
1821     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"5\">\n"
1822     FAKE_KERNEL("6.0.0", "F5", 5)
1823     FAKE_KERNEL("7.0.0", "G5", 5)
1824     "</compatibility-matrix>\n",
1825 };
1826 
1827 const static std::vector<std::string> systemMatrixKernelXmlsGki = {
1828     // 5.xml
1829     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"5\">\n"
1830     FAKE_KERNEL("4.14.0", "R_4_14", 5)
1831     FAKE_KERNEL("4.19.0", "R_4_19", 5)
1832     FAKE_KERNEL("5.4.0", "R_5_4", 5)
1833     "</compatibility-matrix>\n",
1834     // 6.xml
1835     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"6\">\n"
1836     FAKE_KERNEL("4.19.0", "S_4_19", 6)
1837     FAKE_KERNEL("5.4.0", "S_5_4", 6)
1838     FAKE_KERNEL("5.10.0", "S_5_10", 6)
1839     "</compatibility-matrix>\n",
1840     // 7.xml
1841     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"7\">\n"
1842     FAKE_KERNEL("5.10.0", "T_5_10", 7)
1843     FAKE_KERNEL("5.15.0", "T_5_15", 7)
1844     "</compatibility-matrix>\n",
1845     // 8.xml
1846     "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"8\">\n"
1847     FAKE_KERNEL("5.15.0", "U_5_15", 8)
1848     FAKE_KERNEL("6.1.0", "U_6_1", 8)
1849     "</compatibility-matrix>\n",
1850 };
1851 
1852 class KernelTest : public MultiMatrixTest {
1853    public:
expectKernelFcmVersion(size_t targetFcm,Level kernelFcm)1854     void expectKernelFcmVersion(size_t targetFcm, Level kernelFcm) {
1855         std::string xml = "<manifest " + kMetaVersionStr + " type=\"device\" target-level=\"" +
1856                           to_string(static_cast<Level>(targetFcm)) + "\">\n";
1857         if (kernelFcm != Level::UNSPECIFIED) {
1858             xml += "    <kernel target-level=\"" + to_string(kernelFcm) + "\"/>\n";
1859         }
1860         xml += "</manifest>";
1861         expectFetch(kVendorManifest, xml);
1862     }
1863 };
1864 
1865 // Assume that we are developing level 2. Test that old <kernel> requirements should
1866 // not change and new <kernel> versions are added.
TEST_F(KernelTest,Level1AndLevel2)1867 TEST_F(KernelTest, Level1AndLevel2) {
1868     SetUpMockSystemMatrices({systemMatrixKernelXmls[0], systemMatrixKernelXmls[1]});
1869 
1870     expectTargetFcmVersion(1);
1871     auto matrix = vintfObject->getFrameworkCompatibilityMatrix();
1872     ASSERT_NE(nullptr, matrix);
1873     std::string xml = toXml(*matrix);
1874 
1875     EXPECT_IN(FAKE_KERNEL("1.0.0", "A1", 1), xml) << "\nOld requirements must not change.";
1876     EXPECT_IN(FAKE_KERNEL("2.0.0", "B1", 1), xml) << "\nOld requirements must not change.";
1877     EXPECT_IN(FAKE_KERNEL("3.0.0", "C2", 2), xml) << "\nShould see <kernel> from new matrices";
1878     EXPECT_IN(FAKE_KERNEL("4.0.0", "D2", 2), xml) << "\nShould see <kernel> from new matrices";
1879 
1880     EXPECT_IN(FAKE_KERNEL("2.0.0", "B2", 2), xml) << "\nShould see <kernel> from new matrices";
1881 }
1882 
1883 // Assume that we are developing level 3. Test that old <kernel> requirements should
1884 // not change and new <kernel> versions are added.
TEST_F(KernelTest,Level1AndMore)1885 TEST_F(KernelTest, Level1AndMore) {
1886     SetUpMockSystemMatrices({systemMatrixKernelXmls});
1887 
1888     expectTargetFcmVersion(1);
1889     auto matrix = vintfObject->getFrameworkCompatibilityMatrix();
1890     ASSERT_NE(nullptr, matrix);
1891     std::string xml = toXml(*matrix);
1892 
1893     EXPECT_IN(FAKE_KERNEL("1.0.0", "A1", 1), xml) << "\nOld requirements must not change.";
1894     EXPECT_IN(FAKE_KERNEL("2.0.0", "B1", 1), xml) << "\nOld requirements must not change.";
1895     EXPECT_IN(FAKE_KERNEL("3.0.0", "C2", 2), xml) << "\nOld requirements must not change.";
1896     EXPECT_IN(FAKE_KERNEL("4.0.0", "D2", 2), xml) << "\nOld requirements must not change.";
1897     EXPECT_IN(FAKE_KERNEL("5.0.0", "E3", 3), xml) << "\nShould see <kernel> from new matrices";
1898 
1899     EXPECT_IN(FAKE_KERNEL("2.0.0", "B2", 2), xml) << "\nShould see <kernel> from new matrices";
1900     EXPECT_IN(FAKE_KERNEL("4.0.0", "D3", 3), xml) << "\nShould see <kernel> from new matrices";
1901 }
1902 
MakeKernelInfo(const std::string & version,const std::string & key)1903 KernelInfo MakeKernelInfo(const std::string& version, const std::string& key) {
1904     KernelInfo info;
1905     CHECK(fromXml(&info,
1906                                "    <kernel version=\"" + version + "\">\n"
1907                                "        <config>\n"
1908                                "            <key>CONFIG_" + key + "</key>\n"
1909                                "            <value type=\"tristate\">y</value>\n"
1910                                "        </config>\n"
1911                                "    </kernel>\n"));
1912     return info;
1913 }
1914 
TEST_F(KernelTest,Compatible)1915 TEST_F(KernelTest, Compatible) {
1916     setupMockFetcher(vendorManifestXml1, systemMatrixXml1, systemManifestXml1, vendorMatrixXml1);
1917 
1918     SetUpMockSystemMatrices({
1919         "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
1920         FAKE_KERNEL("1.0.0", "A1", 1)
1921         FAKE_KERNEL("2.0.0", "B1", 1)
1922         "    <sepolicy>\n"
1923         "        <kernel-sepolicy-version>0</kernel-sepolicy-version>\n"
1924         "        <sepolicy-version>0</sepolicy-version>\n"
1925         "    </sepolicy>\n"
1926         "</compatibility-matrix>\n"});
1927     expectKernelFcmVersion(1, Level{1});
1928     expectSystemManifest();
1929     expectVendorMatrix();
1930 
1931     auto info = MakeKernelInfo("1.0.0", "A1");
1932     runtimeInfoFactory().getInfo()->setNextFetchKernelInfo(info.version(), info.configs());
1933     std::string error;
1934     ASSERT_EQ(COMPATIBLE, vintfObject->checkCompatibility(&error)) << error;
1935 }
1936 
TEST_F(KernelTest,Level)1937 TEST_F(KernelTest, Level) {
1938     expectKernelFcmVersion(1, Level{8});
1939     EXPECT_EQ(Level{8}, vintfObject->getKernelLevel());
1940 }
1941 
TEST_F(KernelTest,LevelUnspecified)1942 TEST_F(KernelTest, LevelUnspecified) {
1943     expectKernelFcmVersion(1, Level::UNSPECIFIED);
1944     EXPECT_EQ(Level::UNSPECIFIED, vintfObject->getKernelLevel());
1945 }
1946 
1947 class KernelTestP : public KernelTest, public WithParamInterface<
1948     std::tuple<std::vector<std::string>, KernelInfo, Level, Level, bool>> {};
1949 // Assume that we are developing level 2. Test that old <kernel> requirements should
1950 // not change and new <kernel> versions are added.
TEST_P(KernelTestP,Test)1951 TEST_P(KernelTestP, Test) {
1952     auto&& [matrices, info, targetFcm, kernelFcm, pass] = GetParam();
1953 
1954     SetUpMockSystemMatrices(matrices);
1955     expectKernelFcmVersion(static_cast<size_t>(targetFcm), kernelFcm);
1956     runtimeInfoFactory().getInfo()->setNextFetchKernelInfo(info.version(), info.configs());
1957     auto matrix = vintfObject->getFrameworkCompatibilityMatrix();
1958     auto runtime = vintfObject->getRuntimeInfo();
1959     ASSERT_NE(nullptr, matrix);
1960     ASSERT_NE(nullptr, runtime);
1961     std::string fallbackError = "Matrix is compatible with kernel info, but it shouldn't. Matrix:\n"
1962         + toXml(*matrix) + "\nKernelInfo:\n" + toXml(info);
1963     std::string error;
1964     ASSERT_EQ(pass, runtime->checkCompatibility(*matrix, &error))
1965             << (pass ? error : fallbackError);
1966 }
1967 
1968 
KernelTestParamValues()1969 std::vector<KernelTestP::ParamType> KernelTestParamValues() {
1970     std::vector<KernelTestP::ParamType> ret;
1971     std::vector<std::string> matrices = {systemMatrixKernelXmls[0], systemMatrixKernelXmls[1]};
1972     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{1}, Level::UNSPECIFIED, true);
1973     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{1}, Level::UNSPECIFIED, true);
1974     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{1}, Level::UNSPECIFIED, true);
1975     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{1}, Level::UNSPECIFIED, true);
1976     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{1}, Level::UNSPECIFIED, false);
1977 
1978     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{1}, Level{1}, true);
1979     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{1}, Level{1}, true);
1980     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{1}, Level{1}, false);
1981     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{1}, Level{1}, false);
1982     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{1}, Level{1}, true);
1983 
1984     // Kernel FCM lower than target FCM
1985     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{2}, Level{1}, true);
1986     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{2}, Level{1}, true);
1987     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{2}, Level{1}, true);
1988 
1989     matrices = systemMatrixKernelXmls;
1990     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{1}, Level::UNSPECIFIED, true);
1991     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{1}, Level::UNSPECIFIED, true);
1992     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{1}, Level::UNSPECIFIED, true);
1993     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{1}, Level::UNSPECIFIED, true);
1994     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E3"), Level{1}, Level::UNSPECIFIED, true);
1995     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{1}, Level::UNSPECIFIED, true);
1996     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{1}, Level::UNSPECIFIED, false);
1997     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D3"), Level{1}, Level::UNSPECIFIED, false);
1998     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E4"), Level{1}, Level::UNSPECIFIED, false);
1999     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F5"), Level{1}, Level::UNSPECIFIED, false);
2000 
2001     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{2}, Level::UNSPECIFIED, true);
2002     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{3}, Level::UNSPECIFIED, true);
2003     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{4}, Level::UNSPECIFIED, true);
2004     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{5}, Level::UNSPECIFIED, false);
2005 
2006     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{1}, Level{1}, true);
2007     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{1}, Level{1}, true);
2008     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{1}, Level{1}, true);
2009     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{1}, Level{1}, false);
2010     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C3"), Level{1}, Level{1}, false);
2011     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{1}, Level{1}, false);
2012     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D3"), Level{1}, Level{1}, false);
2013     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E3"), Level{1}, Level{1}, false);
2014     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E4"), Level{1}, Level{1}, false);
2015     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{1}, Level{1}, false);
2016     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F5"), Level{1}, Level{1}, false);
2017     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{1}, Level{1}, false);
2018 
2019     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{2}, Level{2}, false);
2020     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{3}, Level{3}, false);
2021     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{4}, Level{4}, true);
2022     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{5}, Level{5}, false);
2023 
2024     // Kernel FCM lower than target FCM
2025     ret.emplace_back(matrices, MakeKernelInfo("1.0.0", "A1"), Level{2}, Level{1}, true);
2026     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B1"), Level{2}, Level{1}, true);
2027     ret.emplace_back(matrices, MakeKernelInfo("2.0.0", "B2"), Level{2}, Level{1}, true);
2028     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C2"), Level{2}, Level{1}, false);
2029     ret.emplace_back(matrices, MakeKernelInfo("3.0.0", "C3"), Level{2}, Level{1}, false);
2030     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D2"), Level{2}, Level{1}, false);
2031     ret.emplace_back(matrices, MakeKernelInfo("4.0.0", "D3"), Level{2}, Level{1}, false);
2032     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E3"), Level{2}, Level{1}, false);
2033     ret.emplace_back(matrices, MakeKernelInfo("5.0.0", "E4"), Level{2}, Level{1}, false);
2034     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{2}, Level{1}, false);
2035     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F5"), Level{2}, Level{1}, false);
2036     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{2}, Level{1}, false);
2037 
2038     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{3}, Level{2}, false);
2039     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{4}, Level{3}, false);
2040     ret.emplace_back(matrices, MakeKernelInfo("6.0.0", "F4"), Level{5}, Level{4}, true);
2041     // We don't have device FCM 6 in systemMatrixKernelXmls, skip
2042 
2043     return ret;
2044 }
2045 
RKernelTestParamValues()2046 std::vector<KernelTestP::ParamType> RKernelTestParamValues() {
2047     std::vector<KernelTestP::ParamType> ret;
2048     std::vector<std::string> matrices = systemMatrixKernelXmls;
2049 
2050     // Devices launching O~Q: Must not use *-r+ kernels without specifying kernel FCM version
2051     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{1}, Level::UNSPECIFIED, false);
2052     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{2}, Level::UNSPECIFIED, false);
2053     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{3}, Level::UNSPECIFIED, false);
2054     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{4}, Level::UNSPECIFIED, false);
2055 
2056     // Devices launching R: may use r kernel without specifying kernel FCM version because
2057     // assemble_vintf does not insert <kernel> tags to device manifest any more.
2058     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{5}, Level::UNSPECIFIED, true);
2059 
2060     // May use *-r+ kernels with kernel FCM version
2061     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{1}, Level{5}, true);
2062     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{2}, Level{5}, true);
2063     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{3}, Level{5}, true);
2064     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{4}, Level{5}, true);
2065     ret.emplace_back(matrices, MakeKernelInfo("7.0.0", "G5"), Level{5}, Level{5}, true);
2066 
2067     return ret;
2068 }
2069 
PrintKernelTestParam(const TestParamInfo<KernelTestP::ParamType> & info)2070 std::string PrintKernelTestParam(const TestParamInfo<KernelTestP::ParamType>& info) {
2071     const auto& [matrices, kernelInfo, targetFcm, kernelFcm, pass] = info.param;
2072     return (matrices.size() == 2 ? "Level1AndLevel2_" : "Level1AndMore_") +
2073            android::base::StringReplace(to_string(kernelInfo.version()), ".", "_", true) + "_" +
2074            android::base::StringReplace(kernelInfo.configs().begin()->first, "CONFIG_", "", false) +
2075            "_TargetFcm" +
2076            (targetFcm == Level::UNSPECIFIED ? "Unspecified" : to_string(targetFcm)) +
2077            "_KernelFcm" +
2078            (kernelFcm == Level::UNSPECIFIED ? "Unspecified" : to_string(kernelFcm)) +
2079            "_Should" + (pass ? "Pass" : "Fail");
2080 }
2081 
2082 INSTANTIATE_TEST_SUITE_P(KernelTest, KernelTestP, ValuesIn(KernelTestParamValues()),
2083                          &PrintKernelTestParam);
2084 INSTANTIATE_TEST_SUITE_P(NoRKernelWithoutFcm, KernelTestP, ValuesIn(RKernelTestParamValues()),
2085                          &PrintKernelTestParam);
2086 
2087 // clang-format on
2088 
GkiKernelTestParamValues()2089 std::vector<KernelTestP::ParamType> GkiKernelTestParamValues() {
2090     std::vector<KernelTestP::ParamType> ret;
2091     std::vector<std::string> matrices = systemMatrixKernelXmlsGki;
2092 
2093     // Kernel FCM version R: may use 4.19-stable and android12-5.4
2094     ret.emplace_back(matrices, MakeKernelInfo("4.19.0", "R_4_19"), Level::R, Level::R, true);
2095     ret.emplace_back(matrices, MakeKernelInfo("4.19.0", "S_4_19"), Level::R, Level::R, true);
2096     ret.emplace_back(matrices, MakeKernelInfo("5.4.0", "R_5_4"), Level::R, Level::R, true);
2097     ret.emplace_back(matrices, MakeKernelInfo("5.4.0", "S_5_4"), Level::R, Level::R, true);
2098 
2099     // Kernel FCM version S: may not use android13-5.10.
2100     ret.emplace_back(matrices, MakeKernelInfo("5.4.0", "S_5_4"), Level::S, Level::S, true);
2101     ret.emplace_back(matrices, MakeKernelInfo("5.10.0", "S_5_10"), Level::S, Level::S, true);
2102     ret.emplace_back(matrices, MakeKernelInfo("5.10.0", "T_5_10"), Level::S, Level::S, false);
2103 
2104     // Kernel FCM version T: may not use android14-5.15.
2105     ret.emplace_back(matrices, MakeKernelInfo("5.10.0", "T_5_10"), Level::T, Level::T, true);
2106     ret.emplace_back(matrices, MakeKernelInfo("5.15.0", "T_5_15"), Level::T, Level::T, true);
2107     ret.emplace_back(matrices, MakeKernelInfo("5.15.0", "U_5_15"), Level::T, Level::T, false);
2108 
2109     return ret;
2110 }
2111 
GkiPrintKernelTestParam(const TestParamInfo<KernelTestP::ParamType> & info)2112 std::string GkiPrintKernelTestParam(const TestParamInfo<KernelTestP::ParamType>& info) {
2113     const auto& [matrices, kernelInfo, targetFcm, kernelFcm, pass] = info.param;
2114     std::string ret = kernelInfo.configs().begin()->first;
2115     ret += "_TargetFcm" + (targetFcm == Level::UNSPECIFIED ? "Unspecified" : to_string(targetFcm));
2116     ret += "_KernelFcm" + (kernelFcm == Level::UNSPECIFIED ? "Unspecified" : to_string(kernelFcm));
2117     ret += "_Should"s + (pass ? "Pass" : "Fail");
2118     return ret;
2119 }
2120 
2121 INSTANTIATE_TEST_SUITE_P(GkiNoCheckFutureKmi, KernelTestP, ValuesIn(GkiKernelTestParamValues()),
2122                          &GkiPrintKernelTestParam);
2123 
2124 // clang-format off
2125 
2126 class VintfObjectPartialUpdateTest : public MultiMatrixTest {
2127    protected:
SetUp()2128     void SetUp() override {
2129         MultiMatrixTest::SetUp();
2130     }
2131 };
2132 
TEST_F(VintfObjectPartialUpdateTest,DeviceCompatibility)2133 TEST_F(VintfObjectPartialUpdateTest, DeviceCompatibility) {
2134     setupMockFetcher(vendorManifestRequire1, "", systemManifestXml1, vendorMatrixXml1);
2135     SetUpMockSystemMatrices(systemMatrixRequire);
2136 
2137     expectSystemManifest();
2138     expectVendorMatrix();
2139     expectVendorManifest();
2140 
2141     std::string error;
2142     EXPECT_TRUE(vintfObject->checkCompatibility(&error)) << error;
2143 }
2144 
CreateFrameworkManifestFrag(const std::string & interface)2145 std::string CreateFrameworkManifestFrag(const std::string& interface) {
2146     return "<manifest " + kMetaVersionStr + " type=\"framework\">\n"
2147            "    <hal format=\"hidl\">\n"
2148            "        <name>android.hardware.foo</name>\n"
2149            "        <transport>hwbinder</transport>\n"
2150            "        <fqname>@1.0::" + interface + "/default</fqname>\n"
2151            "    </hal>\n"
2152            "</manifest>\n";
2153 }
2154 
2155 using FrameworkManifestTestParam =
2156     std::tuple<bool /* Existence of /system/etc/vintf/manifest.xml */,
2157                bool /* Existence of /system/etc/vintf/manifest/fragment.xml */,
2158                bool /* Existence of /product/etc/vintf/manifest.xml */,
2159                bool /* Existence of /product/etc/vintf/manifest/fragment.xml */,
2160                bool /* Existence of /system_ext/etc/vintf/manifest.xml */,
2161                bool /* Existence of /system_ext/etc/vintf/manifest/fragment.xml */,
2162                bool /* Existence of /apex/com.system/etc/vintf/manifest.xml */>;
2163 class FrameworkManifestTest : public VintfObjectTestBase,
2164                               public ::testing::WithParamInterface<FrameworkManifestTestParam> {
2165    protected:
2166     // Set the existence of |path|.
expectManifest(const std::string & path,const std::string & interface,bool exists)2167     void expectManifest(const std::string& path, const std::string& interface, bool exists) {
2168         if (exists) {
2169             expectFetchRepeatedly(path, CreateFrameworkManifestFrag(interface));
2170         } else {
2171             expectFileNotExist(StrEq(path));
2172         }
2173     }
2174 
2175     // Set the existence of |path| as a fragment dir
expectFragment(const std::string & path,const std::string & interface,bool exists)2176     void expectFragment(const std::string& path, const std::string& interface, bool exists) {
2177         if (exists) {
2178             EXPECT_CALL(fetcher(), listFiles(StrEq(path), _, _))
2179                 .Times(AnyNumber())
2180                 .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
2181                     *out = {"fragment.xml"};
2182                     return ::android::OK;
2183                 }));
2184             expectFetchRepeatedly(path + "fragment.xml",
2185                                   CreateFrameworkManifestFrag(interface));
2186         } else {
2187             EXPECT_CALL(fetcher(), listFiles(StrEq(path), _, _))
2188                 .Times(AnyNumber())
2189                 .WillRepeatedly(Return(::android::OK));
2190             expectFileNotExist(path + "fragment.xml");
2191         }
2192     }
2193 
expectContainsInterface(const std::string & interface,bool contains=true)2194     void expectContainsInterface(const std::string& interface, bool contains = true) {
2195         auto manifest = vintfObject->getFrameworkHalManifest();
2196         ASSERT_NE(nullptr, manifest);
2197         EXPECT_NE(manifest->getHidlInstances("android.hardware.foo", {1, 0}, interface).empty(),
2198                   contains)
2199             << interface << " should " << (contains ? "" : "not ") << "exist.";
2200     }
2201 
expectApex()2202     void expectApex() {
2203         expectFetchRepeatedly(kApexInfoFile, R"(
2204             <apex-info-list>
2205                 <apex-info
2206                     moduleName="com.system"
2207                     preinstalledModulePath="/system/apex/com.system.apex"
2208                     isActive="true"/>
2209             </apex-info-list>)");
2210         EXPECT_CALL(fetcher(), modifiedTime(kApexInfoFile, _, _))
2211             .WillRepeatedly(Invoke([](auto, timespec* out, auto){
2212                 *out = {};
2213                 return ::android::OK;
2214             }))
2215             ;
2216         EXPECT_CALL(fetcher(), listFiles("/apex/com.system/etc/vintf/", _, _))
2217             .WillRepeatedly(Invoke([](auto, std::vector<std::string>* out, auto){
2218                 *out = {"manifest.xml"};
2219                 return ::android::OK;
2220             }));
2221         expectManifest("/apex/com.system/etc/vintf/manifest.xml", "ISystemApex", true);
2222     }
2223 };
2224 
TEST_P(FrameworkManifestTest,Existence)2225 TEST_P(FrameworkManifestTest, Existence) {
2226     useEmptyFileSystem();
2227 
2228     expectFileNotExist(StrEq(kSystemLegacyManifest));
2229 
2230     expectManifest(kSystemManifest, "ISystemEtc", std::get<0>(GetParam()));
2231     expectFragment(kSystemManifestFragmentDir, "ISystemEtcFragment", std::get<1>(GetParam()));
2232     expectManifest(kProductManifest, "IProductEtc", std::get<2>(GetParam()));
2233     expectFragment(kProductManifestFragmentDir, "IProductEtcFragment", std::get<3>(GetParam()));
2234     expectManifest(kSystemExtManifest, "ISystemExtEtc", std::get<4>(GetParam()));
2235     expectFragment(kSystemExtManifestFragmentDir, "ISystemExtEtcFragment", std::get<5>(GetParam()));
2236     if (std::get<6>(GetParam())) {
2237         expectApex();
2238     }
2239 
2240     if (!std::get<0>(GetParam())) {
2241         EXPECT_EQ(nullptr, vintfObject->getFrameworkHalManifest())
2242             << "getFrameworkHalManifest must return nullptr if " << kSystemManifest
2243             << " does not exist";
2244     } else {
2245         expectContainsInterface("ISystemEtc", std::get<0>(GetParam()));
2246         expectContainsInterface("ISystemEtcFragment", std::get<1>(GetParam()));
2247         expectContainsInterface("IProductEtc", std::get<2>(GetParam()));
2248         expectContainsInterface("IProductEtcFragment", std::get<3>(GetParam()));
2249         expectContainsInterface("ISystemExtEtc", std::get<4>(GetParam()));
2250         expectContainsInterface("ISystemExtEtcFragment", std::get<5>(GetParam()));
2251         expectContainsInterface("ISystemApex", std::get<6>(GetParam()));
2252     }
2253 }
2254 INSTANTIATE_TEST_SUITE_P(Vintf, FrameworkManifestTest,
2255                          ::testing::Combine(Bool(), Bool(), Bool(), Bool(), Bool(), Bool(), Bool()));
2256 
2257 // clang-format on
2258 
2259 class FrameworkManifestLevelTest : public VintfObjectTestBase {
2260    protected:
SetUp()2261     void SetUp() override {
2262         VintfObjectTestBase::SetUp();
2263         useEmptyFileSystem();
2264 
2265         auto head = "<manifest " + kMetaVersionStr + R"( type="framework">)";
2266         auto tail = "</manifest>";
2267 
2268         auto systemManifest =
2269             head + getFragment(HalFormat::HIDL, Level::UNSPECIFIED, Level{6}, "@3.0::ISystemEtc") +
2270             getFragment(HalFormat::AIDL, Level{6}, Level{7}, "ISystemEtc4") + tail;
2271         expectFetch(kSystemManifest, systemManifest);
2272 
2273         auto hidlFragment =
2274             head +
2275             getFragment(HalFormat::HIDL, Level::UNSPECIFIED, Level{7}, "@4.0::ISystemEtcFragment") +
2276             tail;
2277         expectFetch(kSystemManifestFragmentDir + "hidl.xml"s, hidlFragment);
2278 
2279         auto aidlFragment =
2280             head + getFragment(HalFormat::AIDL, Level{5}, Level{6}, "ISystemEtcFragment3") + tail;
2281         expectFetch(kSystemManifestFragmentDir + "aidl.xml"s, aidlFragment);
2282 
2283         EXPECT_CALL(fetcher(), listFiles(StrEq(kSystemManifestFragmentDir), _, _))
2284             .Times(AnyNumber())
2285             .WillRepeatedly(Invoke([](const auto&, auto* out, auto*) {
2286                 *out = {"hidl.xml", "aidl.xml"};
2287                 return ::android::OK;
2288             }));
2289     }
2290 
expectTargetFcmVersion(size_t level)2291     void expectTargetFcmVersion(size_t level) {
2292         std::string xml = android::base::StringPrintf(
2293             R"(<manifest %s type="device" target-level="%s"/>)", kMetaVersionStr.c_str(),
2294             to_string(static_cast<Level>(level)).c_str());
2295         expectFetch(kVendorManifest, xml);
2296         (void)vintfObject->getDeviceHalManifest();
2297     }
2298 
expectContainsHidl(const Version & version,const std::string & interfaceName,bool exists=true)2299     void expectContainsHidl(const Version& version, const std::string& interfaceName,
2300                             bool exists = true) {
2301         auto manifest = vintfObject->getFrameworkHalManifest();
2302         ASSERT_NE(nullptr, manifest);
2303         EXPECT_NE(
2304             manifest->getHidlInstances("android.frameworks.foo", version, interfaceName).empty(),
2305             exists)
2306             << "@" << version << "::" << interfaceName << " should " << (exists ? "" : "not ")
2307             << "exist.";
2308     }
2309 
expectContainsAidl(const std::string & interfaceName,bool exists=true)2310     void expectContainsAidl(const std::string& interfaceName, bool exists = true) {
2311         auto manifest = vintfObject->getFrameworkHalManifest();
2312         ASSERT_NE(nullptr, manifest);
2313         EXPECT_NE(manifest->getAidlInstances("android.frameworks.foo", interfaceName).empty(),
2314                   exists)
2315             << interfaceName << " should " << (exists ? "" : "not ") << "exist.";
2316     }
2317 
2318    private:
getFragment(HalFormat halFormat,Level minLevel,Level maxLevel,const char * versionedInterface)2319     std::string getFragment(HalFormat halFormat, Level minLevel, Level maxLevel,
2320                             const char* versionedInterface) {
2321         auto format = R"(<hal format="%s"%s>
2322                              <name>android.frameworks.foo</name>
2323                              %s
2324                              <fqname>%s/default</fqname>
2325                          </hal>)";
2326         std::string halAttrs;
2327         if (minLevel != Level::UNSPECIFIED) {
2328             halAttrs +=
2329                 android::base::StringPrintf(R"( min-level="%s")", to_string(minLevel).c_str());
2330         }
2331         if (maxLevel != Level::UNSPECIFIED) {
2332             halAttrs +=
2333                 android::base::StringPrintf(R"( max-level="%s")", to_string(maxLevel).c_str());
2334         }
2335         const char* transport = "";
2336         if (halFormat == HalFormat::HIDL) {
2337             transport = "<transport>hwbinder</transport>";
2338         }
2339         return android::base::StringPrintf(format, to_string(halFormat).c_str(), halAttrs.c_str(),
2340                                            transport, versionedInterface);
2341     }
2342 };
2343 
TEST_F(FrameworkManifestLevelTest,NoTargetFcmVersion)2344 TEST_F(FrameworkManifestLevelTest, NoTargetFcmVersion) {
2345     auto xml =
2346         android::base::StringPrintf(R"(<manifest %s type="device"/> )", kMetaVersionStr.c_str());
2347     expectFetch(kVendorManifest, xml);
2348 
2349     // If no target FCM version, it is treated as an infinitely old device
2350     expectContainsHidl({3, 0}, "ISystemEtc");
2351     expectContainsHidl({4, 0}, "ISystemEtcFragment");
2352     expectContainsAidl("ISystemEtcFragment3", false);
2353     expectContainsAidl("ISystemEtc4", false);
2354 }
2355 
TEST_F(FrameworkManifestLevelTest,TargetFcmVersion4)2356 TEST_F(FrameworkManifestLevelTest, TargetFcmVersion4) {
2357     expectTargetFcmVersion(4);
2358     expectContainsHidl({3, 0}, "ISystemEtc");
2359     expectContainsHidl({4, 0}, "ISystemEtcFragment");
2360     expectContainsAidl("ISystemEtcFragment3", false);
2361     expectContainsAidl("ISystemEtc4", false);
2362 }
2363 
TEST_F(FrameworkManifestLevelTest,TargetFcmVersion5)2364 TEST_F(FrameworkManifestLevelTest, TargetFcmVersion5) {
2365     expectTargetFcmVersion(5);
2366     expectContainsHidl({3, 0}, "ISystemEtc");
2367     expectContainsHidl({4, 0}, "ISystemEtcFragment");
2368     expectContainsAidl("ISystemEtcFragment3");
2369     expectContainsAidl("ISystemEtc4", false);
2370 }
2371 
TEST_F(FrameworkManifestLevelTest,TargetFcmVersion6)2372 TEST_F(FrameworkManifestLevelTest, TargetFcmVersion6) {
2373     expectTargetFcmVersion(6);
2374     expectContainsHidl({3, 0}, "ISystemEtc");
2375     expectContainsHidl({4, 0}, "ISystemEtcFragment");
2376     expectContainsAidl("ISystemEtcFragment3");
2377     expectContainsAidl("ISystemEtc4");
2378 }
2379 
TEST_F(FrameworkManifestLevelTest,TargetFcmVersion7)2380 TEST_F(FrameworkManifestLevelTest, TargetFcmVersion7) {
2381     expectTargetFcmVersion(7);
2382     expectContainsHidl({3, 0}, "ISystemEtc", false);
2383     expectContainsHidl({4, 0}, "ISystemEtcFragment");
2384     expectContainsAidl("ISystemEtcFragment3", false);
2385     expectContainsAidl("ISystemEtc4");
2386 }
2387 
TEST_F(FrameworkManifestLevelTest,TargetFcmVersion8)2388 TEST_F(FrameworkManifestLevelTest, TargetFcmVersion8) {
2389     expectTargetFcmVersion(8);
2390     expectContainsHidl({3, 0}, "ISystemEtc", false);
2391     expectContainsHidl({4, 0}, "ISystemEtcFragment", false);
2392     expectContainsAidl("ISystemEtcFragment3", false);
2393     expectContainsAidl("ISystemEtc4", false);
2394 }
2395 
2396 // clang-format off
2397 
2398 //
2399 // Set of OEM FCM matrices at different FCM version.
2400 //
2401 
GetOemFcmMatrixLevels(const std::string & name)2402 std::vector<std::string> GetOemFcmMatrixLevels(const std::string& name) {
2403     return {
2404         // 1.xml
2405         "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
2406         "    <hal format=\"hidl\" optional=\"true\">\n"
2407         "        <name>vendor.foo." + name + "</name>\n"
2408         "        <version>1.0</version>\n"
2409         "        <interface>\n"
2410         "            <name>IExtra</name>\n"
2411         "            <instance>default</instance>\n"
2412         "        </interface>\n"
2413         "    </hal>\n"
2414         "</compatibility-matrix>\n",
2415         // 2.xml
2416         "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"2\">\n"
2417         "    <hal format=\"hidl\" optional=\"true\">\n"
2418         "        <name>vendor.foo." + name + "</name>\n"
2419         "        <version>2.0</version>\n"
2420         "        <interface>\n"
2421         "            <name>IExtra</name>\n"
2422         "            <instance>default</instance>\n"
2423         "        </interface>\n"
2424         "    </hal>\n"
2425         "</compatibility-matrix>\n",
2426     };
2427 }
2428 
2429 class OemFcmLevelTest : public MultiMatrixTest,
2430                         public WithParamInterface<std::tuple<size_t, bool, bool>> {
2431    protected:
SetUp()2432     virtual void SetUp() override {
2433         MultiMatrixTest::SetUp();
2434         SetUpMockSystemMatrices({systemMatrixLevel1, systemMatrixLevel2});
2435     }
2436     using Instances = std::set<std::string>;
GetInstances(const CompatibilityMatrix * fcm)2437     Instances GetInstances(const CompatibilityMatrix* fcm) {
2438         Instances instances;
2439         fcm->forEachHidlInstance([&instances](const auto& matrixInstance) {
2440             instances.insert(matrixInstance.description(matrixInstance.versionRange().minVer()));
2441             return true; // continue
2442         });
2443         return instances;
2444     }
2445 };
2446 
TEST_P(OemFcmLevelTest,Test)2447 TEST_P(OemFcmLevelTest, Test) {
2448     auto&& [level, hasProduct, hasSystemExt] = GetParam();
2449 
2450     expectTargetFcmVersion(level);
2451     if (hasProduct) {
2452         SetUpMockMatrices(kProductVintfDir, GetOemFcmMatrixLevels("product"));
2453     }
2454     if (hasSystemExt) {
2455         SetUpMockMatrices(kSystemExtVintfDir, GetOemFcmMatrixLevels("systemext"));
2456     }
2457 
2458     auto fcm = vintfObject->getFrameworkCompatibilityMatrix();
2459     ASSERT_NE(nullptr, fcm);
2460     auto instances = GetInstances(fcm.get());
2461 
2462     auto containsOrNot = [](bool contains, const std::string& e) {
2463         return contains ? SafeMatcherCast<Instances>(Contains(e))
2464                         : SafeMatcherCast<Instances>(Not(Contains(e)));
2465     };
2466 
2467     EXPECT_THAT(instances, containsOrNot(level == 1,
2468                                          "android.hardware.major@1.0::IMajor/default"));
2469     EXPECT_THAT(instances, containsOrNot(level == 1 && hasProduct,
2470                                          "vendor.foo.product@1.0::IExtra/default"));
2471     EXPECT_THAT(instances, containsOrNot(level == 1 && hasSystemExt,
2472                                          "vendor.foo.systemext@1.0::IExtra/default"));
2473     EXPECT_THAT(instances, Contains("android.hardware.major@2.0::IMajor/default"));
2474     EXPECT_THAT(instances, containsOrNot(hasProduct,
2475                                          "vendor.foo.product@2.0::IExtra/default"));
2476     EXPECT_THAT(instances, containsOrNot(hasSystemExt,
2477                                          "vendor.foo.systemext@2.0::IExtra/default"));
2478 }
2479 
OemFcmLevelTestParamToString(const TestParamInfo<OemFcmLevelTest::ParamType> & info)2480 static std::string OemFcmLevelTestParamToString(
2481         const TestParamInfo<OemFcmLevelTest::ParamType>& info) {
2482     auto&& [level, hasProduct, hasSystemExt] = info.param;
2483     auto name = "Level" + std::to_string(level);
2484     name += "With"s + (hasProduct ? "" : "out") + "Product";
2485     name += "With"s + (hasSystemExt ? "" : "out") + "SystemExt";
2486     return name;
2487 }
2488 INSTANTIATE_TEST_SUITE_P(OemFcmLevel, OemFcmLevelTest, Combine(Values(1, 2), Bool(), Bool()),
2489     OemFcmLevelTestParamToString);
2490 // clang-format on
2491 
2492 // Common test set up for checking matrices against lib*idlmetadata.
2493 class CheckMatricesWithHalDefTestBase : public MultiMatrixTest {
SetUp()2494     void SetUp() override {
2495         MultiMatrixTest::SetUp();
2496 
2497         // clang-format off
2498         std::vector<std::string> matrices{
2499             "<compatibility-matrix " + kMetaVersionStr + " type=\"framework\" level=\"1\">\n"
2500             "    <hal format=\"hidl\" optional=\"false\">\n"
2501             "        <name>android.hardware.hidl</name>\n"
2502             "        <version>1.0</version>\n"
2503             "        <interface>\n"
2504             "            <name>IHidl</name>\n"
2505             "            <instance>default</instance>\n"
2506             "        </interface>\n"
2507             "    </hal>\n"
2508             "    <hal format=\"aidl\" optional=\"false\">\n"
2509             "        <name>android.hardware.aidl</name>\n"
2510             "        <interface>\n"
2511             "            <name>IAidl</name>\n"
2512             "            <instance>default</instance>\n"
2513             "        </interface>\n"
2514             "    </hal>\n"
2515             "</compatibility-matrix>\n",
2516         };
2517         // clang-format on
2518 
2519         SetUpMockSystemMatrices(matrices);
2520     }
2521 };
2522 
2523 // A set of tests on VintfObject::checkMissingHalsInMatrices
2524 class CheckMissingHalsTest : public CheckMatricesWithHalDefTestBase {
2525    public:
defaultPred(const std::string &)2526     static bool defaultPred(const std::string&) { return true; }
2527 };
2528 
TEST_F(CheckMissingHalsTest,Empty)2529 TEST_F(CheckMissingHalsTest, Empty) {
2530     EXPECT_THAT(vintfObject->checkMissingHalsInMatrices({}, {}, defaultPred, defaultPred), Ok());
2531 }
2532 
TEST_F(CheckMissingHalsTest,Pass)2533 TEST_F(CheckMissingHalsTest, Pass) {
2534     std::vector<HidlInterfaceMetadata> hidl{{.name = "android.hardware.hidl@1.0::IHidl"}};
2535     std::vector<AidlInterfaceMetadata> aidl{
2536         {.types = {"android.hardware.aidl.IAidl"}, .stability = "vintf", .versions = {1}}};
2537     EXPECT_THAT(vintfObject->checkMissingHalsInMatrices(hidl, {}, defaultPred, defaultPred), Ok());
2538     EXPECT_THAT(vintfObject->checkMissingHalsInMatrices({}, aidl, defaultPred, defaultPred), Ok());
2539     EXPECT_THAT(vintfObject->checkMissingHalsInMatrices(hidl, aidl, defaultPred, defaultPred),
2540                 Ok());
2541 }
2542 
TEST_F(CheckMissingHalsTest,FailVendor)2543 TEST_F(CheckMissingHalsTest, FailVendor) {
2544     std::vector<HidlInterfaceMetadata> hidl{{.name = "vendor.foo.hidl@1.0"}};
2545     std::vector<AidlInterfaceMetadata> aidl{
2546         {.types = {"vendor.foo.aidl.IAidl"}, .stability = "vintf", .versions = {1}}};
2547 
2548     auto res = vintfObject->checkMissingHalsInMatrices(hidl, {}, defaultPred, defaultPred);
2549     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("vendor.foo.hidl@1.0"))));
2550 
2551     setCheckAidlFCM(true);
2552     res = vintfObject->checkMissingHalsInMatrices({}, aidl, defaultPred, defaultPred);
2553     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("vendor.foo.aidl"))));
2554 
2555     res = vintfObject->checkMissingHalsInMatrices(hidl, aidl, defaultPred, defaultPred);
2556     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("vendor.foo.hidl@1.0"))));
2557     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("vendor.foo.aidl"))));
2558 
2559     auto predicate = [](const auto& interfaceName) {
2560         return android::base::StartsWith(interfaceName, "android.hardware");
2561     };
2562     EXPECT_THAT(vintfObject->checkMissingHalsInMatrices(hidl, {}, predicate, predicate), Ok());
2563     EXPECT_THAT(vintfObject->checkMissingHalsInMatrices({}, aidl, predicate, predicate), Ok());
2564     EXPECT_THAT(vintfObject->checkMissingHalsInMatrices(hidl, aidl, predicate, predicate), Ok());
2565 }
2566 
TEST_F(CheckMissingHalsTest,FailMajorVersion)2567 TEST_F(CheckMissingHalsTest, FailMajorVersion) {
2568     std::vector<HidlInterfaceMetadata> hidl{{.name = "android.hardware.hidl@2.0"}};
2569     std::vector<AidlInterfaceMetadata> aidl{
2570         {.types = {"android.hardware.aidl2.IAidl"}, .stability = "vintf", .versions = {1}}};
2571 
2572     setCheckAidlFCM(true);
2573     auto res = vintfObject->checkMissingHalsInMatrices(hidl, {}, defaultPred, defaultPred);
2574     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@2.0"))));
2575 
2576     res = vintfObject->checkMissingHalsInMatrices({}, aidl, defaultPred, defaultPred);
2577     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl2"))));
2578 
2579     res = vintfObject->checkMissingHalsInMatrices(hidl, aidl, defaultPred, defaultPred);
2580     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@2.0"))));
2581     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl2"))));
2582 
2583     auto predicate = [](const auto& interfaceName) {
2584         return android::base::StartsWith(interfaceName, "android.hardware");
2585     };
2586 
2587     res = vintfObject->checkMissingHalsInMatrices(hidl, {}, predicate, predicate);
2588     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@2.0"))));
2589 
2590     res = vintfObject->checkMissingHalsInMatrices({}, aidl, predicate, predicate);
2591     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl2"))));
2592 
2593     res = vintfObject->checkMissingHalsInMatrices(hidl, aidl, predicate, predicate);
2594     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@2.0"))));
2595     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl2"))));
2596 }
2597 
TEST_F(CheckMissingHalsTest,FailMinorVersion)2598 TEST_F(CheckMissingHalsTest, FailMinorVersion) {
2599     std::vector<HidlInterfaceMetadata> hidl{{.name = "android.hardware.hidl@1.1"}};
2600     std::vector<AidlInterfaceMetadata> aidl{
2601         {.types = {"android.hardware.aidl.IAidl"}, .stability = "vintf", .versions = {1, 2}}};
2602 
2603     auto res = vintfObject->checkMissingHalsInMatrices(hidl, {}, defaultPred, defaultPred);
2604     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@1.1"))));
2605 
2606     setCheckAidlFCM(true);
2607     res = vintfObject->checkMissingHalsInMatrices({}, aidl, defaultPred, defaultPred);
2608     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl@2"))));
2609 
2610     res = vintfObject->checkMissingHalsInMatrices(hidl, aidl, defaultPred, defaultPred);
2611     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@1.1"))));
2612     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl@2"))));
2613 }
2614 
TEST_F(CheckMissingHalsTest,SkipFcmCheckForAidl)2615 TEST_F(CheckMissingHalsTest, SkipFcmCheckForAidl) {
2616     std::vector<HidlInterfaceMetadata> hidl{{.name = "android.hardware.hidl@1.1"}};
2617     std::vector<AidlInterfaceMetadata> aidl{
2618         {.types = {"android.hardware.aidl.IAidl"}, .stability = "vintf", .versions = {1, 2}}};
2619 
2620     auto res = vintfObject->checkMissingHalsInMatrices(hidl, {}, defaultPred, defaultPred);
2621     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@1.1"))));
2622 
2623     setCheckAidlFCM(false);
2624     res = vintfObject->checkMissingHalsInMatrices({}, aidl, defaultPred, defaultPred);
2625     EXPECT_THAT(res, Ok());
2626 
2627     setCheckAidlFCM(true);
2628     res = vintfObject->checkMissingHalsInMatrices(hidl, aidl, defaultPred, defaultPred);
2629     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@1.1"))));
2630     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl@2"))));
2631 }
2632 
TEST_F(CheckMissingHalsTest,PassAidlInDevelopment)2633 TEST_F(CheckMissingHalsTest, PassAidlInDevelopment) {
2634     std::vector<AidlInterfaceMetadata> aidl{{.types = {"android.hardware.aidl.IAidl"},
2635                                              .stability = "vintf",
2636                                              .versions = {},
2637                                              .has_development = true}};
2638 
2639     auto res = vintfObject->checkMissingHalsInMatrices({}, aidl, defaultPred, defaultPred);
2640     EXPECT_THAT(res, Ok());
2641 }
2642 
TEST_F(CheckMissingHalsTest,FailAidlInDevelopment)2643 TEST_F(CheckMissingHalsTest, FailAidlInDevelopment) {
2644     std::vector<AidlInterfaceMetadata> aidl{{.types = {"android.hardware.aidl.IAidl"},
2645                                              .stability = "vintf",
2646                                              .versions = {1},
2647                                              .has_development = true}};
2648 
2649     setCheckAidlFCM(true);
2650     auto res = vintfObject->checkMissingHalsInMatrices({}, aidl, defaultPred, defaultPred);
2651     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl@2"))));
2652 }
2653 
2654 // A set of tests on VintfObject::checkMatrixHalsHasDefinition
2655 class CheckMatrixHalsHasDefinitionTest : public CheckMatricesWithHalDefTestBase {};
2656 
TEST_F(CheckMatrixHalsHasDefinitionTest,Pass)2657 TEST_F(CheckMatrixHalsHasDefinitionTest, Pass) {
2658     std::vector<HidlInterfaceMetadata> hidl{{.name = "android.hardware.hidl@1.0::IHidl"}};
2659     std::vector<AidlInterfaceMetadata> aidl{
2660         {.types = {"android.hardware.aidl.IAidl"}, .stability = "vintf"}};
2661     EXPECT_THAT(vintfObject->checkMatrixHalsHasDefinition(hidl, aidl), Ok());
2662 }
2663 
TEST_F(CheckMatrixHalsHasDefinitionTest,FailMissingHidl)2664 TEST_F(CheckMatrixHalsHasDefinitionTest, FailMissingHidl) {
2665     std::vector<AidlInterfaceMetadata> aidl{
2666         {.types = {"android.hardware.aidl.IAidl"}, .stability = "vintf"}};
2667     auto res = vintfObject->checkMatrixHalsHasDefinition({}, aidl);
2668     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@1.0::IHidl"))));
2669 }
2670 
TEST_F(CheckMatrixHalsHasDefinitionTest,FailMissingAidl)2671 TEST_F(CheckMatrixHalsHasDefinitionTest, FailMissingAidl) {
2672     std::vector<HidlInterfaceMetadata> hidl{{.name = "android.hardware.hidl@1.0::IHidl"}};
2673     auto res = vintfObject->checkMatrixHalsHasDefinition(hidl, {});
2674     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl.IAidl"))));
2675 }
2676 
TEST_F(CheckMatrixHalsHasDefinitionTest,FailMissingBoth)2677 TEST_F(CheckMatrixHalsHasDefinitionTest, FailMissingBoth) {
2678     auto res = vintfObject->checkMatrixHalsHasDefinition({}, {});
2679     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.hidl@1.0::IHidl"))));
2680     EXPECT_THAT(res, HasError(WithMessage(HasSubstr("android.hardware.aidl.IAidl"))));
2681 }
2682 
2683 constexpr const char* systemMatrixHealthFormat = R"(
2684 <compatibility-matrix %s type="framework" level="%s">
2685     <hal format="%s" optional="%s">
2686         <name>android.hardware.health</name>
2687         <version>%s</version>
2688         <interface>
2689             <name>IHealth</name>
2690             <instance>default</instance>
2691         </interface>
2692     </hal>
2693 </compatibility-matrix>
2694 )";
2695 
2696 constexpr const char* vendorManifestHealthHidlFormat = R"(
2697 <manifest %s type="device" target-level="%s">
2698     <hal format="hidl">
2699         <name>android.hardware.health</name>
2700         <transport>hwbinder</transport>
2701         <fqname>@%s::IHealth/default</fqname>
2702     </hal>
2703 </manifest>
2704 )";
2705 
2706 constexpr const char* vendorManifestHealthAidlFormat = R"(
2707 <manifest %s type="device" target-level="%s">
2708     <hal format="aidl">
2709         <name>android.hardware.health</name>
2710         <version>%s</version>
2711         <fqname>IHealth/default</fqname>
2712     </hal>
2713 </manifest>
2714 )";
2715 
2716 using HealthHalVersion = std::variant<Version /* HIDL */, size_t /* AIDL */>;
2717 struct VintfObjectHealthHalTestParam {
2718     Level targetLevel;
2719     HealthHalVersion halVersion;
2720     bool expected;
2721 
getHalFormatandroid::vintf::testing::VintfObjectHealthHalTestParam2722     HalFormat getHalFormat() const {
2723         if (std::holds_alternative<Version>(halVersion)) return HalFormat::HIDL;
2724         if (std::holds_alternative<size_t>(halVersion)) return HalFormat::AIDL;
2725         __builtin_unreachable();
2726     }
2727 };
operator <<(std::ostream & os,const VintfObjectHealthHalTestParam & param)2728 std::ostream& operator<<(std::ostream& os, const VintfObjectHealthHalTestParam& param) {
2729     os << param.targetLevel << "_" << param.getHalFormat() << "_";
2730     switch (param.getHalFormat()) {
2731         case HalFormat::HIDL: {
2732             const auto& v = std::get<Version>(param.halVersion);
2733             os << "v" << v.majorVer << "_" << v.minorVer;
2734         } break;
2735         case HalFormat::AIDL: {
2736             os << "v" << std::get<size_t>(param.halVersion);
2737         } break;
2738         default:
2739             __builtin_unreachable();
2740     }
2741     return os << "_" << (param.expected ? "ok" : "not_ok");
2742 }
2743 
2744 // Test fixture that provides compatible metadata from the mock device.
2745 class VintfObjectHealthHalTest : public MultiMatrixTest,
2746                                  public WithParamInterface<VintfObjectHealthHalTestParam> {
2747    public:
SetUp()2748     virtual void SetUp() {
2749         MultiMatrixTest::SetUp();
2750         SetUpMockSystemMatrices({
2751             android::base::StringPrintf(
2752                 systemMatrixHealthFormat, kMetaVersionStr.c_str(), to_string(Level::P).c_str(),
2753                 to_string(HalFormat::HIDL).c_str(), "true", to_string(Version{2, 0}).c_str()),
2754             android::base::StringPrintf(
2755                 systemMatrixHealthFormat, kMetaVersionStr.c_str(), to_string(Level::Q).c_str(),
2756                 to_string(HalFormat::HIDL).c_str(), "true", to_string(Version{2, 0}).c_str()),
2757             android::base::StringPrintf(
2758                 systemMatrixHealthFormat, kMetaVersionStr.c_str(), to_string(Level::R).c_str(),
2759                 to_string(HalFormat::HIDL).c_str(), "true", to_string(Version{2, 1}).c_str()),
2760             android::base::StringPrintf(
2761                 systemMatrixHealthFormat, kMetaVersionStr.c_str(), to_string(Level::S).c_str(),
2762                 to_string(HalFormat::HIDL).c_str(), "true", to_string(Version{2, 1}).c_str()),
2763             android::base::StringPrintf(
2764                 systemMatrixHealthFormat, kMetaVersionStr.c_str(), to_string(Level::T).c_str(),
2765                 to_string(HalFormat::AIDL).c_str(), "false", to_string(1).c_str()),
2766         });
2767         switch (GetParam().getHalFormat()) {
2768             case HalFormat::HIDL:
2769                 expectFetchRepeatedly(
2770                     kVendorManifest,
2771                     android::base::StringPrintf(
2772                         vendorManifestHealthHidlFormat, kMetaVersionStr.c_str(),
2773                         to_string(GetParam().targetLevel).c_str(),
2774                         to_string(std::get<Version>(GetParam().halVersion)).c_str()));
2775                 break;
2776             case HalFormat::AIDL:
2777                 expectFetchRepeatedly(
2778                     kVendorManifest,
2779                     android::base::StringPrintf(
2780                         vendorManifestHealthAidlFormat, kMetaVersionStr.c_str(),
2781                         to_string(GetParam().targetLevel).c_str(),
2782                         to_string(std::get<size_t>(GetParam().halVersion)).c_str()));
2783                 break;
2784             default:
2785                 __builtin_unreachable();
2786         }
2787     }
GetParams()2788     static std::vector<VintfObjectHealthHalTestParam> GetParams() {
2789         std::vector<VintfObjectHealthHalTestParam> ret;
2790         for (auto level : {Level::P, Level::Q, Level::R, Level::S, Level::T}) {
2791             ret.push_back({level, Version{2, 0}, level < Level::R});
2792             ret.push_back({level, Version{2, 1}, level < Level::T});
2793             ret.push_back({level, 1u, true});
2794         }
2795         return ret;
2796     }
2797 };
2798 
TEST_P(VintfObjectHealthHalTest,Test)2799 TEST_P(VintfObjectHealthHalTest, Test) {
2800     auto manifest = vintfObject->getDeviceHalManifest();
2801     ASSERT_NE(nullptr, manifest);
2802     std::string deprecatedError;
2803     auto deprecation = vintfObject->checkDeprecation({}, &deprecatedError);
2804     bool hasHidl =
2805         manifest->hasHidlInstance("android.hardware.health", {2, 0}, "IHealth", "default");
2806     bool hasAidl = manifest->hasAidlInstance("android.hardware.health", 1, "IHealth", "default");
2807     bool hasHal = hasHidl || hasAidl;
2808     EXPECT_EQ(GetParam().expected, deprecation == NO_DEPRECATED_HALS && hasHal)
2809         << "checkDeprecation() returns " << deprecation << "; hasHidl = " << hasHidl
2810         << ", hasAidl = " << hasAidl;
2811 }
2812 
2813 INSTANTIATE_TEST_SUITE_P(VintfObjectHealthHalTest, VintfObjectHealthHalTest,
2814                          ::testing::ValuesIn(VintfObjectHealthHalTest::GetParams()),
__anon5aab1a0f2202(const auto& info) 2815                          [](const auto& info) { return to_string(info.param); });
2816 
2817 constexpr const char* systemMatrixComposerFormat = R"(
2818 <compatibility-matrix %s type="framework" level="%s">
2819     %s
2820 </compatibility-matrix>
2821 )";
2822 
2823 constexpr const char* systemMatrixComposerHalFragmentFormat = R"(
2824     <hal format="%s" optional="%s">
2825         <name>%s</name>
2826         <version>%s</version>
2827         <interface>
2828             <name>IComposer</name>
2829             <instance>default</instance>
2830         </interface>
2831     </hal>
2832 )";
2833 
2834 constexpr const char* vendorManifestComposerHidlFormat = R"(
2835 <manifest %s type="device" target-level="%s">
2836     %s
2837 </manifest>
2838 )";
2839 
2840 constexpr const char* vendorManifestComposerHidlFragmentFormat = R"(
2841     <hal format="hidl">
2842         <name>android.hardware.graphics.composer</name>
2843         <version>%s</version>
2844         <transport>hwbinder</transport>
2845         <interface>
2846             <name>IComposer</name>
2847             <instance>default</instance>
2848         </interface>
2849     </hal>
2850 )";
2851 
2852 constexpr const char* vendorManifestComposerAidlFragmentFormat = R"(
2853     <hal format="aidl">
2854         <name>android.hardware.graphics.composer3</name>
2855         <version>%s</version>
2856         <interface>
2857             <name>IComposer</name>
2858             <instance>default</instance>
2859         </interface>
2860     </hal>
2861 )";
2862 
2863 constexpr const char* composerHidlHalName = "android.hardware.graphics.composer";
2864 constexpr const char* composerAidlHalName = "android.hardware.graphics.composer3";
2865 
2866 using ComposerHalVersion = std::variant<Version /* HIDL */, size_t /* AIDL */>;
2867 struct VintfObjectComposerHalTestParam {
2868     Level targetLevel;
2869     std::optional<ComposerHalVersion> halVersion;
2870     bool expected;
2871 
hasHalandroid::vintf::testing::VintfObjectComposerHalTestParam2872     bool hasHal() const { return halVersion.has_value(); }
2873 
getHalFormatandroid::vintf::testing::VintfObjectComposerHalTestParam2874     HalFormat getHalFormat() const {
2875         if (std::holds_alternative<Version>(*halVersion)) return HalFormat::HIDL;
2876         if (std::holds_alternative<size_t>(*halVersion)) return HalFormat::AIDL;
2877         __builtin_unreachable();
2878     }
2879 };
operator <<(std::ostream & os,const VintfObjectComposerHalTestParam & param)2880 std::ostream& operator<<(std::ostream& os, const VintfObjectComposerHalTestParam& param) {
2881     os << param.targetLevel << "_";
2882     if (param.hasHal()) {
2883         os << param.getHalFormat() << "_";
2884         switch (param.getHalFormat()) {
2885             case HalFormat::HIDL: {
2886                 const auto& v = std::get<Version>(*param.halVersion);
2887                 os << "v" << v.majorVer << "_" << v.minorVer;
2888             } break;
2889             case HalFormat::AIDL: {
2890                 os << "v" << std::get<size_t>(*param.halVersion);
2891             } break;
2892             default:
2893                 __builtin_unreachable();
2894         }
2895     } else {
2896         os << "no_hal";
2897     }
2898     return os << "_" << (param.expected ? "ok" : "not_ok");
2899 }
2900 
2901 // Test fixture that provides compatible metadata from the mock device.
2902 class VintfObjectComposerHalTest : public MultiMatrixTest,
2903                                    public WithParamInterface<VintfObjectComposerHalTestParam> {
2904    public:
SetUp()2905     virtual void SetUp() {
2906         MultiMatrixTest::SetUp();
2907 
2908         const std::string requiresHidl2_1To2_2 = android::base::StringPrintf(
2909             systemMatrixComposerHalFragmentFormat, to_string(HalFormat::HIDL).c_str(), "false",
2910             composerHidlHalName, to_string(VersionRange{2, 1, 2}).c_str());
2911         const std::string requiresHidl2_1To2_3 = android::base::StringPrintf(
2912             systemMatrixComposerHalFragmentFormat, to_string(HalFormat::HIDL).c_str(), "false",
2913             composerHidlHalName, to_string(VersionRange{2, 1, 3}).c_str());
2914         const std::string requiresHidl2_1To2_4 = android::base::StringPrintf(
2915             systemMatrixComposerHalFragmentFormat, to_string(HalFormat::HIDL).c_str(), "false",
2916             composerHidlHalName, to_string(VersionRange{2, 1, 4}).c_str());
2917         const std::string optionalHidl2_1To2_4 = android::base::StringPrintf(
2918             systemMatrixComposerHalFragmentFormat, to_string(HalFormat::HIDL).c_str(), "true",
2919             composerHidlHalName, to_string(VersionRange{2, 1, 4}).c_str());
2920         const std::string optionalAidl1 = android::base::StringPrintf(
2921             systemMatrixComposerHalFragmentFormat, to_string(HalFormat::AIDL).c_str(), "true",
2922             composerAidlHalName, "1");
2923         const std::string optionalHidl2_1To2_4OrAidl1 = optionalHidl2_1To2_4 + optionalAidl1;
2924 
2925         SetUpMockSystemMatrices({
2926             android::base::StringPrintf(systemMatrixComposerFormat, kMetaVersionStr.c_str(),
2927                                         to_string(Level::P).c_str(), requiresHidl2_1To2_2.c_str()),
2928             android::base::StringPrintf(systemMatrixComposerFormat, kMetaVersionStr.c_str(),
2929                                         to_string(Level::Q).c_str(), requiresHidl2_1To2_3.c_str()),
2930             android::base::StringPrintf(systemMatrixComposerFormat, kMetaVersionStr.c_str(),
2931                                         to_string(Level::R).c_str(), requiresHidl2_1To2_4.c_str()),
2932             android::base::StringPrintf(systemMatrixComposerFormat, kMetaVersionStr.c_str(),
2933                                         to_string(Level::S).c_str(), requiresHidl2_1To2_4.c_str()),
2934             android::base::StringPrintf(systemMatrixComposerFormat, kMetaVersionStr.c_str(),
2935                                         to_string(Level::T).c_str(),
2936                                         optionalHidl2_1To2_4OrAidl1.c_str()),
2937         });
2938 
2939         const auto param = GetParam();
2940 
2941         std::string vendorHalFragment;
2942         if (param.hasHal()) {
2943             switch (param.getHalFormat()) {
2944                 case HalFormat::HIDL:
2945                     vendorHalFragment = android::base::StringPrintf(
2946                         vendorManifestComposerHidlFragmentFormat,
2947                         to_string(std::get<Version>(*param.halVersion)).c_str());
2948                     break;
2949                 case HalFormat::AIDL:
2950                     vendorHalFragment = android::base::StringPrintf(
2951                         vendorManifestComposerAidlFragmentFormat,
2952                         to_string(std::get<size_t>(*param.halVersion)).c_str());
2953                     break;
2954                 default:
2955                     __builtin_unreachable();
2956             }
2957         } else {
2958             vendorHalFragment = "";
2959         }
2960         expectFetchRepeatedly(kVendorManifest,
2961                               android::base::StringPrintf(
2962                                   vendorManifestComposerHidlFormat, kMetaVersionStr.c_str(),
2963                                   to_string(param.targetLevel).c_str(), vendorHalFragment.c_str()));
2964     }
GetParams()2965     static std::vector<VintfObjectComposerHalTestParam> GetParams() {
2966         std::vector<VintfObjectComposerHalTestParam> ret;
2967         for (auto level : {Level::P, Level::Q, Level::R, Level::S, Level::T}) {
2968             ret.push_back({level, std::nullopt, false});
2969             ret.push_back({level, ComposerHalVersion{Version{2, 1}}, true});
2970             ret.push_back({level, ComposerHalVersion{Version{2, 2}}, true});
2971             ret.push_back({level, ComposerHalVersion{Version{2, 3}}, true});
2972             ret.push_back({level, ComposerHalVersion{Version{2, 4}}, true});
2973             ret.push_back({level, ComposerHalVersion{1u}, true});
2974         }
2975         return ret;
2976     }
2977 };
2978 
TEST_P(VintfObjectComposerHalTest,Test)2979 TEST_P(VintfObjectComposerHalTest, Test) {
2980     auto manifest = vintfObject->getDeviceHalManifest();
2981     ASSERT_NE(nullptr, manifest);
2982     std::string deprecatedError;
2983     auto deprecation = vintfObject->checkDeprecation({}, &deprecatedError);
2984     bool hasHidl = manifest->hasHidlInstance(composerHidlHalName, {2, 1}, "IComposer", "default");
2985     bool hasAidl = manifest->hasAidlInstance(composerAidlHalName, 1, "IComposer", "default");
2986     bool hasHal = hasHidl || hasAidl;
2987     EXPECT_EQ(GetParam().expected, deprecation == NO_DEPRECATED_HALS && hasHal)
2988         << "checkDeprecation() returns " << deprecation << "; hasHidl = " << hasHidl
2989         << ", hasAidl = " << hasAidl;
2990 }
2991 
2992 INSTANTIATE_TEST_SUITE_P(VintfObjectComposerHalTest, VintfObjectComposerHalTest,
2993                          ::testing::ValuesIn(VintfObjectComposerHalTest::GetParams()),
__anon5aab1a0f2302(const auto& info) 2994                          [](const auto& info) { return to_string(info.param); });
2995 
2996 constexpr const char* systemMatrixLatestMinLtsFormat = R"(
2997 <compatibility-matrix %s type="framework" level="%s">
2998     <kernel version="%s" />
2999     <kernel version="%s" />
3000     <kernel version="%s" />
3001 </compatibility-matrix>
3002 )";
3003 
3004 class VintfObjectLatestMinLtsTest : public MultiMatrixTest {};
3005 
TEST_F(VintfObjectLatestMinLtsTest,TestEmpty)3006 TEST_F(VintfObjectLatestMinLtsTest, TestEmpty) {
3007     SetUpMockSystemMatrices({});
3008     EXPECT_THAT(vintfObject->getLatestMinLtsAtFcmVersion(Level::S),
3009                 HasError(WithCode(-NAME_NOT_FOUND)));
3010 }
3011 
TEST_F(VintfObjectLatestMinLtsTest,TestMissing)3012 TEST_F(VintfObjectLatestMinLtsTest, TestMissing) {
3013     SetUpMockSystemMatrices({
3014         android::base::StringPrintf(systemMatrixLatestMinLtsFormat, kMetaVersionStr.c_str(),
3015                                     to_string(Level::S).c_str(), "4.19.191", "5.4.86", "5.10.43"),
3016     });
3017     EXPECT_THAT(
3018         vintfObject->getLatestMinLtsAtFcmVersion(Level::T),
3019         HasError(WithMessage(HasSubstr("Can't find compatibility matrix fragment for level 7"))));
3020 }
3021 
TEST_F(VintfObjectLatestMinLtsTest,TestSimple)3022 TEST_F(VintfObjectLatestMinLtsTest, TestSimple) {
3023     SetUpMockSystemMatrices({
3024         android::base::StringPrintf(systemMatrixLatestMinLtsFormat, kMetaVersionStr.c_str(),
3025                                     to_string(Level::S).c_str(), "4.19.191", "5.4.86", "5.10.43"),
3026         android::base::StringPrintf(systemMatrixLatestMinLtsFormat, kMetaVersionStr.c_str(),
3027                                     to_string(Level::T).c_str(), "5.4.86", "5.10.107", "5.15.41"),
3028     });
3029     EXPECT_THAT(vintfObject->getLatestMinLtsAtFcmVersion(Level::S),
3030                 HasValue(KernelVersion{5, 10, 43}));
3031     EXPECT_THAT(vintfObject->getLatestMinLtsAtFcmVersion(Level::T),
3032                 HasValue(KernelVersion{5, 15, 41}));
3033 }
3034 
TEST_F(VintfObjectLatestMinLtsTest,TestMultipleFragment)3035 TEST_F(VintfObjectLatestMinLtsTest, TestMultipleFragment) {
3036     SetUpMockSystemMatrices({
3037         android::base::StringPrintf(systemMatrixLatestMinLtsFormat, kMetaVersionStr.c_str(),
3038                                     to_string(Level::S).c_str(), "4.19.191", "5.4.86", "5.10.43"),
3039         android::base::StringPrintf(systemMatrixLatestMinLtsFormat, kMetaVersionStr.c_str(),
3040                                     to_string(Level::S).c_str(), "5.4.86", "5.10.107", "5.15.41"),
3041     });
3042     EXPECT_THAT(vintfObject->getLatestMinLtsAtFcmVersion(Level::S),
3043                 HasValue(KernelVersion{5, 15, 41}));
3044 }
3045 
3046 }  // namespace testing
3047 }  // namespace vintf
3048 }  // namespace android
3049 
main(int argc,char ** argv)3050 int main(int argc, char** argv) {
3051 #ifndef LIBVINTF_TARGET
3052     // Silence logs on host because they pollute the gtest output. Negative tests writes a lot
3053     // of warning and error logs.
3054     android::base::SetMinimumLogSeverity(android::base::LogSeverity::FATAL);
3055 #endif
3056 
3057     ::testing::InitGoogleMock(&argc, argv);
3058     return RUN_ALL_TESTS();
3059 }
3060