• 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 #include "MultiApkGenerator.h"
18 
19 #include <algorithm>
20 #include <regex>
21 #include <string>
22 
23 #include "androidfw/ConfigDescription.h"
24 #include "androidfw/StringPiece.h"
25 
26 #include "LoadedApk.h"
27 #include "ResourceUtils.h"
28 #include "ValueVisitor.h"
29 #include "configuration/ConfigurationParser.h"
30 #include "cmd/Util.h"
31 #include "filter/AbiFilter.h"
32 #include "filter/Filter.h"
33 #include "format/Archive.h"
34 #include "format/binary/XmlFlattener.h"
35 #include "optimize/VersionCollapser.h"
36 #include "process/IResourceTableConsumer.h"
37 #include "split/TableSplitter.h"
38 #include "util/Files.h"
39 #include "xml/XmlDom.h"
40 #include "xml/XmlUtil.h"
41 
42 namespace aapt {
43 
44 using ::aapt::configuration::AndroidSdk;
45 using ::aapt::configuration::OutputArtifact;
46 using ::aapt::xml::kSchemaAndroid;
47 using ::aapt::xml::XmlResource;
48 using ::android::ConfigDescription;
49 using ::android::StringPiece;
50 
51 /**
52  * Context wrapper that allows the min Android SDK value to be overridden.
53  */
54 class ContextWrapper : public IAaptContext {
55  public:
ContextWrapper(IAaptContext * context)56   explicit ContextWrapper(IAaptContext* context)
57       : context_(context), min_sdk_(context_->GetMinSdkVersion()) {
58   }
59 
GetPackageType()60   PackageType GetPackageType() override {
61     return context_->GetPackageType();
62   }
63 
GetExternalSymbols()64   SymbolTable* GetExternalSymbols() override {
65     return context_->GetExternalSymbols();
66   }
67 
GetDiagnostics()68   IDiagnostics* GetDiagnostics() override {
69     if (source_diag_) {
70       return source_diag_.get();
71     }
72     return context_->GetDiagnostics();
73   }
74 
GetCompilationPackage()75   const std::string& GetCompilationPackage() override {
76     return context_->GetCompilationPackage();
77   }
78 
GetPackageId()79   uint8_t GetPackageId() override {
80     return context_->GetPackageId();
81   }
82 
GetNameMangler()83   NameMangler* GetNameMangler() override {
84     return context_->GetNameMangler();
85   }
86 
IsVerbose()87   bool IsVerbose() override {
88     return context_->IsVerbose();
89   }
90 
GetMinSdkVersion()91   int GetMinSdkVersion() override {
92     return min_sdk_;
93   }
94 
SetMinSdkVersion(int min_sdk)95   void SetMinSdkVersion(int min_sdk) {
96     min_sdk_ = min_sdk;
97   }
98 
SetSource(const std::string & source)99   void SetSource(const std::string& source) {
100     source_diag_ =
101         util::make_unique<SourcePathDiagnostics>(Source{source}, context_->GetDiagnostics());
102   }
103 
GetSplitNameDependencies()104   const std::set<std::string>& GetSplitNameDependencies() override {
105     return context_->GetSplitNameDependencies();
106   }
107 
108  private:
109   IAaptContext* context_;
110   std::unique_ptr<SourcePathDiagnostics> source_diag_;
111 
112   int min_sdk_ = -1;
113 };
114 
115 class SignatureFilter : public IPathFilter {
Keep(const std::string & path)116   bool Keep(const std::string& path) override {
117     static std::regex signature_regex(R"regex(^META-INF/.*\.(RSA|DSA|EC|SF)$)regex");
118     if (std::regex_search(path, signature_regex)) {
119       return false;
120     }
121     return !(path == "META-INF/MANIFEST.MF");
122   }
123 };
124 
MultiApkGenerator(LoadedApk * apk,IAaptContext * context)125 MultiApkGenerator::MultiApkGenerator(LoadedApk* apk, IAaptContext* context)
126     : apk_(apk), context_(context) {
127 }
128 
FromBaseApk(const MultiApkGeneratorOptions & options)129 bool MultiApkGenerator::FromBaseApk(const MultiApkGeneratorOptions& options) {
130   std::unordered_set<std::string> artifacts_to_keep = options.kept_artifacts;
131   std::unordered_set<std::string> filtered_artifacts;
132   std::unordered_set<std::string> kept_artifacts;
133 
134   // For now, just write out the stripped APK since ABI splitting doesn't modify anything else.
135   for (const OutputArtifact& artifact : options.apk_artifacts) {
136     FilterChain filters;
137 
138     ContextWrapper wrapped_context{context_};
139     wrapped_context.SetSource(artifact.name);
140 
141     if (!options.kept_artifacts.empty()) {
142       const auto& it = artifacts_to_keep.find(artifact.name);
143       if (it == artifacts_to_keep.end()) {
144         filtered_artifacts.insert(artifact.name);
145         if (context_->IsVerbose()) {
146           context_->GetDiagnostics()->Note(DiagMessage(artifact.name) << "skipping artifact");
147         }
148         continue;
149       } else {
150         artifacts_to_keep.erase(it);
151         kept_artifacts.insert(artifact.name);
152       }
153     }
154 
155     std::unique_ptr<ResourceTable> table =
156         FilterTable(context_, artifact, *apk_->GetResourceTable(), &filters);
157     if (!table) {
158       return false;
159     }
160 
161     IDiagnostics* diag = wrapped_context.GetDiagnostics();
162 
163     std::unique_ptr<XmlResource> manifest;
164     if (!UpdateManifest(artifact, &manifest, diag)) {
165       diag->Error(DiagMessage() << "could not update AndroidManifest.xml for output artifact");
166       return false;
167     }
168 
169     std::string out = options.out_dir;
170     if (!file::mkdirs(out)) {
171       diag->Warn(DiagMessage() << "could not create out dir: " << out);
172     }
173     file::AppendPath(&out, artifact.name);
174 
175     if (context_->IsVerbose()) {
176       diag->Note(DiagMessage() << "Generating split: " << out);
177     }
178 
179     std::unique_ptr<IArchiveWriter> writer = CreateZipFileArchiveWriter(diag, out);
180 
181     if (context_->IsVerbose()) {
182       diag->Note(DiagMessage() << "Writing output: " << out);
183     }
184 
185     filters.AddFilter(util::make_unique<SignatureFilter>());
186     if (!apk_->WriteToArchive(&wrapped_context, table.get(), options.table_flattener_options,
187                               &filters, writer.get(), manifest.get())) {
188       return false;
189     }
190   }
191 
192   // Make sure all of the requested artifacts were valid. If there are any kept artifacts left,
193   // either the config or the command line was wrong.
194   if (!artifacts_to_keep.empty()) {
195     context_->GetDiagnostics()->Error(
196         DiagMessage() << "The configuration and command line to filter artifacts do not match");
197 
198     context_->GetDiagnostics()->Error(DiagMessage() << kept_artifacts.size() << " kept:");
199     for (const auto& artifact : kept_artifacts) {
200       context_->GetDiagnostics()->Error(DiagMessage() << "  " << artifact);
201     }
202 
203     context_->GetDiagnostics()->Error(DiagMessage() << filtered_artifacts.size() << " filtered:");
204     for (const auto& artifact : filtered_artifacts) {
205       context_->GetDiagnostics()->Error(DiagMessage() << "  " << artifact);
206     }
207 
208     context_->GetDiagnostics()->Error(DiagMessage() << artifacts_to_keep.size() << " missing:");
209     for (const auto& artifact : artifacts_to_keep) {
210       context_->GetDiagnostics()->Error(DiagMessage() << "  " << artifact);
211     }
212 
213     return false;
214   }
215 
216   return true;
217 }
218 
FilterTable(IAaptContext * context,const OutputArtifact & artifact,const ResourceTable & old_table,FilterChain * filters)219 std::unique_ptr<ResourceTable> MultiApkGenerator::FilterTable(IAaptContext* context,
220                                                               const OutputArtifact& artifact,
221                                                               const ResourceTable& old_table,
222                                                               FilterChain* filters) {
223   TableSplitterOptions splits;
224   AxisConfigFilter axis_filter;
225   ContextWrapper wrapped_context{context};
226   wrapped_context.SetSource(artifact.name);
227 
228   if (!artifact.abis.empty()) {
229     filters->AddFilter(AbiFilter::FromAbiList(artifact.abis));
230   }
231 
232   if (!artifact.screen_densities.empty()) {
233     for (const auto& density_config : artifact.screen_densities) {
234       splits.preferred_densities.push_back(density_config.density);
235     }
236   }
237 
238   if (!artifact.locales.empty()) {
239     for (const auto& locale : artifact.locales) {
240       axis_filter.AddConfig(locale);
241     }
242     splits.config_filter = &axis_filter;
243   }
244 
245   if (artifact.android_sdk) {
246     wrapped_context.SetMinSdkVersion(artifact.android_sdk.value().min_sdk_version);
247   }
248 
249   std::unique_ptr<ResourceTable> table = old_table.Clone();
250 
251   VersionCollapser collapser;
252   if (!collapser.Consume(&wrapped_context, table.get())) {
253     context->GetDiagnostics()->Error(DiagMessage() << "Failed to strip versioned resources");
254     return {};
255   }
256 
257   TableSplitter splitter{{}, splits};
258   splitter.SplitTable(table.get());
259   return table;
260 }
261 
UpdateManifest(const OutputArtifact & artifact,std::unique_ptr<XmlResource> * updated_manifest,IDiagnostics * diag)262 bool MultiApkGenerator::UpdateManifest(const OutputArtifact& artifact,
263                                        std::unique_ptr<XmlResource>* updated_manifest,
264                                        IDiagnostics* diag) {
265   const xml::XmlResource* apk_manifest = apk_->GetManifest();
266   if (apk_manifest == nullptr) {
267     return false;
268   }
269 
270   *updated_manifest = apk_manifest->Clone();
271   XmlResource* manifest = updated_manifest->get();
272 
273   // Make sure the first element is <manifest> with package attribute.
274   xml::Element* manifest_el = manifest->root.get();
275   if (!manifest_el) {
276     return false;
277   }
278 
279   if (!manifest_el->namespace_uri.empty() || manifest_el->name != "manifest") {
280     diag->Error(DiagMessage(manifest->file.source) << "root tag must be <manifest>");
281     return false;
282   }
283 
284   // Retrieve the versionCode attribute.
285   auto version_code = manifest_el->FindAttribute(kSchemaAndroid, "versionCode");
286   if (!version_code) {
287     diag->Error(DiagMessage(manifest->file.source) << "manifest must have a versionCode attribute");
288     return false;
289   }
290 
291   auto version_code_value = ValueCast<BinaryPrimitive>(version_code->compiled_value.get());
292   if (!version_code_value) {
293     diag->Error(DiagMessage(manifest->file.source) << "versionCode is invalid");
294     return false;
295   }
296 
297   // Retrieve the versionCodeMajor attribute.
298   auto version_code_major = manifest_el->FindAttribute(kSchemaAndroid, "versionCodeMajor");
299   BinaryPrimitive* version_code_major_value = nullptr;
300   if (version_code_major) {
301     version_code_major_value = ValueCast<BinaryPrimitive>(version_code_major->compiled_value.get());
302     if (!version_code_major_value) {
303       diag->Error(DiagMessage(manifest->file.source) << "versionCodeMajor is invalid");
304       return false;
305     }
306   }
307 
308   // Calculate and set the updated version code
309   uint64_t major = (version_code_major_value)
310                   ? ((uint64_t) version_code_major_value->value.data) << 32 : 0;
311   uint64_t new_version = (major | version_code_value->value.data) + artifact.version;
312   SetLongVersionCode(manifest_el, new_version);
313 
314   // Check to see if the minSdkVersion needs to be updated.
315   if (artifact.android_sdk) {
316     // TODO(safarmer): Handle the rest of the Android SDK.
317     const AndroidSdk& android_sdk = artifact.android_sdk.value();
318 
319     if (xml::Element* uses_sdk_el = manifest_el->FindChild({}, "uses-sdk")) {
320       if (xml::Attribute* min_sdk_attr =
321               uses_sdk_el->FindAttribute(xml::kSchemaAndroid, "minSdkVersion")) {
322         // Populate with a pre-compiles attribute to we don't need to relink etc.
323         const std::string& min_sdk_str = std::to_string(android_sdk.min_sdk_version);
324         min_sdk_attr->compiled_value = ResourceUtils::TryParseInt(min_sdk_str);
325       } else {
326         // There was no minSdkVersion. This is strange since at this point we should have been
327         // through the manifest fixer which sets the default minSdkVersion.
328         diag->Error(DiagMessage(manifest->file.source) << "missing minSdkVersion from <uses-sdk>");
329         return false;
330       }
331     } else {
332       // No uses-sdk present. This is strange since at this point we should have been
333       // through the manifest fixer which should have added it.
334       diag->Error(DiagMessage(manifest->file.source) << "missing <uses-sdk> from <manifest>");
335       return false;
336     }
337   }
338 
339   if (!artifact.screen_densities.empty()) {
340     xml::Element* screens_el = manifest_el->FindChild({}, "compatible-screens");
341     if (!screens_el) {
342       // create a new element.
343       std::unique_ptr<xml::Element> new_screens_el = util::make_unique<xml::Element>();
344       new_screens_el->name = "compatible-screens";
345       screens_el = new_screens_el.get();
346       manifest_el->AppendChild(std::move(new_screens_el));
347     } else {
348       // clear out the old element.
349       screens_el->GetChildElements().clear();
350     }
351 
352     for (const auto& density : artifact.screen_densities) {
353       AddScreens(density, screens_el);
354     }
355   }
356 
357   return true;
358 }
359 
360 /**
361  * Adds a screen element with both screenSize and screenDensity set. Since we only know the density
362  * we add it for all screen sizes.
363  *
364  * This requires the resource IDs for the attributes from the framework library. Since these IDs are
365  * a part of the public API (and in public.xml) we hard code the values.
366  *
367  * The excert from the framework is as follows:
368  *    <public type="attr" name="screenSize" id="0x010102ca" />
369  *    <public type="attr" name="screenDensity" id="0x010102cb" />
370  */
AddScreens(const ConfigDescription & config,xml::Element * parent)371 void MultiApkGenerator::AddScreens(const ConfigDescription& config, xml::Element* parent) {
372   // Hard coded integer representation of the supported screen sizes:
373   //  small   = 200
374   //  normal  = 300
375   //  large   = 400
376   //  xlarge  = 500
377   constexpr const uint32_t kScreenSizes[4] = {200, 300, 400, 500,};
378   constexpr const uint32_t kScreenSizeResourceId = 0x010102ca;
379   constexpr const uint32_t kScreenDensityResourceId = 0x010102cb;
380 
381   for (uint32_t screen_size : kScreenSizes) {
382     std::unique_ptr<xml::Element> screen = util::make_unique<xml::Element>();
383     screen->name = "screen";
384 
385     xml::Attribute* size = screen->FindOrCreateAttribute(kSchemaAndroid, "screenSize");
386     size->compiled_attribute = xml::AaptAttribute(Attribute(), {kScreenSizeResourceId});
387     size->compiled_value = ResourceUtils::MakeInt(screen_size);
388 
389     xml::Attribute* density = screen->FindOrCreateAttribute(kSchemaAndroid, "screenDensity");
390     density->compiled_attribute = xml::AaptAttribute(Attribute(), {kScreenDensityResourceId});
391     density->compiled_value = ResourceUtils::MakeInt(config.density);
392 
393 
394     parent->AppendChild(std::move(screen));
395   }
396 }
397 
398 }  // namespace aapt
399