AAPT2: GetBag infinite recursion fix

Style resources with circular parental dependencies caused infinite
recursion when calling AssetManager2::GetBag. This fix allows recursion
to cease when a circular dependency is found.

Bug: 77928512
Change-Id: Ib900c36ab1aef5da5b03234a9484c4dad3b63c02
Test: Manual test of b/77928512 and duplicates of 74493983
diff --git a/libs/androidfw/tests/AssetManager2_test.cpp b/libs/androidfw/tests/AssetManager2_test.cpp
index 7cac2b3..3118009 100644
--- a/libs/androidfw/tests/AssetManager2_test.cpp
+++ b/libs/androidfw/tests/AssetManager2_test.cpp
@@ -329,6 +329,17 @@
   EXPECT_EQ(0, bag_two->entries[5].cookie);
 }
 
+TEST_F(AssetManager2Test, MergeStylesCircularDependency) {
+  AssetManager2 assetmanager;
+  assetmanager.SetApkAssets({style_assets_.get()});
+
+  // GetBag should stop traversing the parents of styles when a circular
+  // dependency is detected
+  const ResolvedBag* bag_one = assetmanager.GetBag(app::R::style::StyleFour);
+  ASSERT_NE(nullptr, bag_one);
+  ASSERT_EQ(3u, bag_one->entry_count);
+}
+
 TEST_F(AssetManager2Test, ResolveReferenceToResource) {
   AssetManager2 assetmanager;
   assetmanager.SetApkAssets({basic_assets_.get()});
diff --git a/libs/androidfw/tests/data/styles/R.h b/libs/androidfw/tests/data/styles/R.h
index 05073a8..538a847 100644
--- a/libs/androidfw/tests/data/styles/R.h
+++ b/libs/androidfw/tests/data/styles/R.h
@@ -48,6 +48,9 @@
       StyleOne = 0x7f020000u,
       StyleTwo = 0x7f020001u,
       StyleThree = 0x7f020002u,
+      StyleFour = 0x7f020003u,
+      StyleFive = 0x7f020004u,
+      StyleSix = 0x7f020005u,
     };
   };
 };
diff --git a/libs/androidfw/tests/data/styles/res/values/styles.xml b/libs/androidfw/tests/data/styles/res/values/styles.xml
index 3c90317..1a23176 100644
--- a/libs/androidfw/tests/data/styles/res/values/styles.xml
+++ b/libs/androidfw/tests/data/styles/res/values/styles.xml
@@ -63,4 +63,20 @@
         <item name="attr_five">5</item>
     </style>
 
+    <!-- Circular parental dependency -->
+    <public type="style" name="StyleFour" id="0x7f020003" />
+    <style name="StyleFour" parent="StyleFive">
+        <item name="attr_one">1</item>
+    </style>
+
+    <public type="style" name="StyleFive" id="0x7f020004" />
+    <style name="StyleFive" parent="StyleSix">
+        <item name="attr_two">2</item>
+    </style>
+
+    <public type="style" name="StyleSix" id="0x7f020005" />
+    <style name="StyleSix" parent="StyleFour">
+        <item name="attr_three">3</item>
+    </style>
+
 </resources>
diff --git a/libs/androidfw/tests/data/styles/styles.apk b/libs/androidfw/tests/data/styles/styles.apk
index 72abf8f..cd5c7a1 100644
--- a/libs/androidfw/tests/data/styles/styles.apk
+++ b/libs/androidfw/tests/data/styles/styles.apk
Binary files differ