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