AAPT2: Insert <uses-sdk> element before <application>

PackageParser on the device uses the targetSdkVersion of the
app while it parses <application>. That means that if the
<uses-sdk> tag comes after <application>, the targetSdkVersion
is assumed to be 0.

Test: make libaapt2_tests
Change-Id: I60f2179a7ff44e7419217afb53f3d24f8c030f6e
diff --git a/tools/aapt2/link/ManifestFixer.cpp b/tools/aapt2/link/ManifestFixer.cpp
index a418fc8..36a3494 100644
--- a/tools/aapt2/link/ManifestFixer.cpp
+++ b/tools/aapt2/link/ManifestFixer.cpp
@@ -309,10 +309,12 @@
   if ((options_.min_sdk_version_default ||
        options_.target_sdk_version_default) &&
       root->FindChild({}, "uses-sdk") == nullptr) {
-    // Auto insert a <uses-sdk> element.
+    // Auto insert a <uses-sdk> element. This must be inserted before the
+    // <application> tag. The device runtime PackageParser will make SDK version
+    // decisions while parsing <application>.
     std::unique_ptr<xml::Element> uses_sdk = util::make_unique<xml::Element>();
     uses_sdk->name = "uses-sdk";
-    root->AddChild(std::move(uses_sdk));
+    root->InsertChild(0, std::move(uses_sdk));
   }
 
   xml::XmlActionExecutor executor;
@@ -327,7 +329,8 @@
 
   if (options_.rename_manifest_package) {
     // Rename manifest package outside of the XmlActionExecutor.
-    // We need to extract the old package name and FullyQualify all class names.
+    // We need to extract the old package name and FullyQualify all class
+    // names.
     if (!RenameManifestPackage(options_.rename_manifest_package.value(),
                                root)) {
       return false;