2 * Copyright (C) 2014 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
20 #include "aapt/AaptUtil.h"
24 #include "RuleGenerator.h"
25 #include "SplitDescription.h"
26 #include "SplitSelector.h"
28 #include <androidfw/AssetManager.h>
29 #include <androidfw/ResourceTypes.h>
30 #include <utils/KeyedVector.h>
31 #include <utils/Vector.h>
33 using namespace android;
39 "split-select --help\n"
40 "split-select --target <config> --base <path/to/apk> [--split <path/to/apk> [...]]\n"
41 "split-select --generate --base <path/to/apk> [--split <path/to/apk> [...]]\n"
43 " --help Displays more information about this program.\n"
44 " --target <config> Performs the Split APK selection on the given configuration.\n"
45 " --generate Generates the logic for selecting the Split APK, in JSON format.\n"
46 " --base <path/to/apk> Specifies the base APK, from which all Split APKs must be based off.\n"
47 " --split <path/to/apk> Includes a Split APK in the selection process.\n"
49 " Where <config> is an extended AAPT resource qualifier of the form\n"
50 " 'resource-qualifiers:extended-qualifiers', where 'resource-qualifiers' is an AAPT resource\n"
51 " qualifier (ex: en-rUS-sw600dp-xhdpi), and 'extended-qualifiers' is an ordered list of one\n"
52 " qualifier (or none) from each category:\n"
53 " Architecture: armeabi, armeabi-v7a, arm64-v8a, x86, x86_64, mips\n");
59 " Generates the logic for selecting a Split APK given some target Android device configuration.\n"
60 " Using the flag --generate will emit a JSON encoded tree of rules that must be satisfied in order\n"
61 " to install the given Split APK. Using the flag --target along with the device configuration\n"
62 " will emit the set of Split APKs to install, following the same logic that would have been emitted\n"
66 Vector<SplitDescription> select(const SplitDescription& target, const Vector<SplitDescription>& splits) {
67 const SplitSelector selector(splits);
68 return selector.getBestSplits(target);
71 void generate(const KeyedVector<String8, Vector<SplitDescription> >& splits, const String8& base) {
72 Vector<SplitDescription> allSplits;
73 const size_t apkSplitCount = splits.size();
74 for (size_t i = 0; i < apkSplitCount; i++) {
75 allSplits.appendVector(splits[i]);
77 const SplitSelector selector(allSplits);
78 KeyedVector<SplitDescription, sp<Rule> > rules(selector.getRules());
81 fprintf(stdout, "[\n");
82 for (size_t i = 0; i < apkSplitCount; i++) {
83 if (splits.keyAt(i) == base) {
89 fprintf(stdout, ",\n");
93 sp<Rule> masterRule = new Rule();
94 masterRule->op = Rule::OR_SUBRULES;
95 const Vector<SplitDescription>& splitDescriptions = splits[i];
96 const size_t splitDescriptionCount = splitDescriptions.size();
97 for (size_t j = 0; j < splitDescriptionCount; j++) {
98 masterRule->subrules.add(rules.valueFor(splitDescriptions[j]));
100 masterRule = Rule::simplify(masterRule);
101 fprintf(stdout, " {\n \"path\": \"%s\",\n \"rules\": %s\n }",
102 splits.keyAt(i).string(),
103 masterRule->toJson(2).string());
105 fprintf(stdout, "\n]\n");
108 static void removeRuntimeQualifiers(ConfigDescription* outConfig) {
110 outConfig->orientation = ResTable_config::ORIENTATION_ANY;
111 outConfig->screenWidth = ResTable_config::SCREENWIDTH_ANY;
112 outConfig->screenHeight = ResTable_config::SCREENHEIGHT_ANY;
113 outConfig->uiMode &= ResTable_config::UI_MODE_NIGHT_ANY;
122 static bool getAppInfo(const String8& path, AppInfo& outInfo) {
123 memset(&outInfo, 0, sizeof(outInfo));
125 AssetManager assetManager;
127 if (!assetManager.addAssetPath(path, &cookie)) {
131 Asset* asset = assetManager.openNonAsset(cookie, "AndroidManifest.xml", Asset::ACCESS_BUFFER);
137 if (xml.setTo(asset->getBuffer(true), asset->getLength(), false) != NO_ERROR) {
142 const String16 kAndroidNamespace("http://schemas.android.com/apk/res/android");
143 const String16 kManifestTag("manifest");
144 const String16 kApplicationTag("application");
145 const String16 kUsesSdkTag("uses-sdk");
146 const String16 kVersionCodeAttr("versionCode");
147 const String16 kMultiArchAttr("multiArch");
148 const String16 kMinSdkVersionAttr("minSdkVersion");
150 ResXMLParser::event_code_t event;
151 while ((event = xml.next()) != ResXMLParser::BAD_DOCUMENT &&
152 event != ResXMLParser::END_DOCUMENT) {
153 if (event != ResXMLParser::START_TAG) {
158 const char16_t* name = xml.getElementName(&len);
159 String16 name16(name, len);
160 if (name16 == kManifestTag) {
161 ssize_t idx = xml.indexOfAttribute(
162 kAndroidNamespace.string(), kAndroidNamespace.size(),
163 kVersionCodeAttr.string(), kVersionCodeAttr.size());
165 outInfo.versionCode = xml.getAttributeData(idx);
168 } else if (name16 == kApplicationTag) {
169 ssize_t idx = xml.indexOfAttribute(
170 kAndroidNamespace.string(), kAndroidNamespace.size(),
171 kMultiArchAttr.string(), kMultiArchAttr.size());
173 outInfo.multiArch = xml.getAttributeData(idx) != 0;
176 } else if (name16 == kUsesSdkTag) {
177 ssize_t idx = xml.indexOfAttribute(
178 kAndroidNamespace.string(), kAndroidNamespace.size(),
179 kMinSdkVersionAttr.string(), kMinSdkVersionAttr.size());
181 uint16_t type = xml.getAttributeDataType(idx);
182 if (type >= Res_value::TYPE_FIRST_INT && type <= Res_value::TYPE_LAST_INT) {
183 outInfo.minSdkVersion = xml.getAttributeData(idx);
184 } else if (type == Res_value::TYPE_STRING) {
185 String8 minSdk8(xml.getStrings().string8ObjectAt(idx));
187 int minSdk = strtol(minSdk8.string(), &endPtr, 10);
188 if (endPtr != minSdk8.string() + minSdk8.size()) {
189 fprintf(stderr, "warning: failed to parse android:minSdkVersion '%s'\n",
192 outInfo.minSdkVersion = minSdk;
195 fprintf(stderr, "warning: unrecognized value for android:minSdkVersion.\n");
205 static Vector<SplitDescription> extractSplitDescriptionsFromApk(const String8& path) {
206 AssetManager assetManager;
207 Vector<SplitDescription> splits;
209 if (!assetManager.addAssetPath(path, &cookie)) {
213 const ResTable& res = assetManager.getResources(false);
214 if (res.getError() == NO_ERROR) {
215 Vector<ResTable_config> configs;
216 res.getConfigurations(&configs, true);
217 const size_t configCount = configs.size();
218 for (size_t i = 0; i < configCount; i++) {
220 splits.editTop().config = configs[i];
224 AssetDir* dir = assetManager.openNonAssetDir(cookie, "lib");
226 const size_t fileCount = dir->getFileCount();
227 for (size_t i = 0; i < fileCount; i++) {
229 Vector<String8> parts = AaptUtil::splitAndLowerCase(dir->getFileName(i), '-');
230 if (parseAbi(parts, 0, &splits.editTop()) < 0) {
231 fprintf(stderr, "Malformed library %s\n", dir->getFileName(i).string());
240 static int main(int argc, char** argv) {
241 // Skip over the first argument.
245 bool generateFlag = false;
246 String8 targetConfigStr;
247 Vector<String8> splitApkPaths;
250 const String8 arg(*argv);
251 if (arg == "--target") {
255 fprintf(stderr, "error: missing parameter for --target.\n");
259 targetConfigStr.setTo(*argv);
260 } else if (arg == "--split") {
264 fprintf(stderr, "error: missing parameter for --split.\n");
268 splitApkPaths.add(String8(*argv));
269 } else if (arg == "--base") {
273 fprintf(stderr, "error: missing parameter for --base.\n");
278 if (baseApkPath.size() > 0) {
279 fprintf(stderr, "error: multiple --base flags not allowed.\n");
283 baseApkPath.setTo(*argv);
284 } else if (arg == "--generate") {
286 } else if (arg == "--help") {
290 fprintf(stderr, "error: unknown argument '%s'.\n", arg.string());
298 if (!generateFlag && targetConfigStr == "") {
303 if (baseApkPath.size() == 0) {
304 fprintf(stderr, "error: missing --base argument.\n");
309 // Find out some details about the base APK.
311 if (!getAppInfo(baseApkPath, baseAppInfo)) {
312 fprintf(stderr, "error: unable to read base APK: '%s'.\n", baseApkPath.string());
316 SplitDescription targetSplit;
318 if (!SplitDescription::parse(targetConfigStr, &targetSplit)) {
319 fprintf(stderr, "error: invalid --target config: '%s'.\n",
320 targetConfigStr.string());
325 // We don't want to match on things that will change at run-time
326 // (orientation, w/h, etc.).
327 removeRuntimeQualifiers(&targetSplit.config);
330 splitApkPaths.add(baseApkPath);
332 KeyedVector<String8, Vector<SplitDescription> > apkPathSplitMap;
333 KeyedVector<SplitDescription, String8> splitApkPathMap;
334 Vector<SplitDescription> splitConfigs;
335 const size_t splitCount = splitApkPaths.size();
336 for (size_t i = 0; i < splitCount; i++) {
337 Vector<SplitDescription> splits = extractSplitDescriptionsFromApk(splitApkPaths[i]);
338 if (splits.isEmpty()) {
339 fprintf(stderr, "error: invalid --split path: '%s'. No splits found.\n",
340 splitApkPaths[i].string());
344 apkPathSplitMap.replaceValueFor(splitApkPaths[i], splits);
345 const size_t apkSplitDescriptionCount = splits.size();
346 for (size_t j = 0; j < apkSplitDescriptionCount; j++) {
347 splitApkPathMap.replaceValueFor(splits[j], splitApkPaths[i]);
349 splitConfigs.appendVector(splits);
353 Vector<SplitDescription> matchingConfigs = select(targetSplit, splitConfigs);
354 const size_t matchingConfigCount = matchingConfigs.size();
355 SortedVector<String8> matchingSplitPaths;
356 for (size_t i = 0; i < matchingConfigCount; i++) {
357 matchingSplitPaths.add(splitApkPathMap.valueFor(matchingConfigs[i]));
360 const size_t matchingSplitApkPathCount = matchingSplitPaths.size();
361 for (size_t i = 0; i < matchingSplitApkPathCount; i++) {
362 if (matchingSplitPaths[i] != baseApkPath) {
363 fprintf(stdout, "%s\n", matchingSplitPaths[i].string());
367 generate(apkPathSplitMap, baseApkPath);
374 int main(int argc, char** argv) {
375 return split::main(argc, argv);