rust-apk 1.0.0

Build, align, sign, verify, and inspect Android APKs in pure Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
//! Compiling app resources into a resource table.

use std::borrow::Cow;
use std::cmp::Reverse;
use std::collections::BTreeMap;

use super::table::{self, EntryData, TypeData};
use super::{
    Config, Locale, RawValue, ResourceId, ResourceLookup, ResourceName, ResourceNameError, ResourceRef, ResourceType,
    StringPoolBuilder, TableError, Value, data_type, resolve,
};
use crate::Content;
use crate::types::{ApiLevel, ArchivePath, ArchivePathError, PackageName};
use crate::xml::{Document, XmlError};

/// Why resources could not be added or compiled.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ResourceError {
    #[error(transparent)]
    Name(#[from] ResourceNameError),
    #[error("{ty}/{name} is defined twice for configuration `{config}`")]
    Duplicate { ty: ResourceType, name: ResourceName, config: Config },
    #[error("{ty} resources cannot be files")]
    NotAFileType { ty: ResourceType },
    #[error("{ty} resources cannot be compiled XML")]
    NotAnXmlType { ty: ResourceType },
    #[error("{ty} resources hold bags or IDs, which this compiler does not build")]
    Unsupported { ty: ResourceType },
    #[error("{ty}/{name} cannot hold this kind of value")]
    ValueMismatch { ty: ResourceType, name: ResourceName },
    #[error("file resource name {name:?} must use only lowercase letters, digits, and `_`")]
    InvalidFileName { name: ResourceName },
    #[error("file resource extension {extension:?} is not a lowercase alphanumeric extension")]
    InvalidExtension { extension: String },
    #[error("{ty}/{name}.xml would be stored as text; add XML resources with `Resources::xml`")]
    TextXml { ty: ResourceType, name: ResourceName },
    #[error("{name}.9.png is a nine-patch, which must be compiled by aapt2")]
    NinePatch { name: ResourceName },
    #[error("the path of {ty}/{name} is invalid: {source}")]
    Path { ty: ResourceType, name: ResourceName, source: ArchivePathError },
    #[error("{ty}/{name} has no default value; devices outside its qualifiers would crash")]
    MissingDefault { ty: ResourceType, name: ResourceName },
    #[error("{ty}/{name} refers to {reference}, which does not exist")]
    UnresolvedReference { ty: ResourceType, name: ResourceName, reference: ResourceRef },
    #[error("XML resource {ty}/{name}: {source}")]
    Xml { ty: ResourceType, name: ResourceName, source: Box<XmlError> },
    #[error(transparent)]
    Table(#[from] TableError),
}

impl ResourceType {
    /// Whether resources of this type are files under `res/`.
    pub fn is_file_type(self) -> bool {
        matches!(
            self,
            Self::Anim
                | Self::Animator
                | Self::Drawable
                | Self::Font
                | Self::Interpolator
                | Self::Layout
                | Self::Menu
                | Self::Mipmap
                | Self::Navigation
                | Self::Raw
                | Self::Transition
                | Self::Xml
        )
    }

    /// Whether resources of this type are bags (or IDs), which have no
    /// simple value.
    fn is_bag_type(self) -> bool {
        matches!(self, Self::Array | Self::Attr | Self::Id | Self::Plurals | Self::Style)
    }

    /// Whether `value` is a simple value of this type.
    fn accepts(self, value: &Value) -> bool {
        use {ResourceType as T, Value as V};
        matches!(
            (self, value),
            (_, V::Reference(_))
                | (T::String, V::String(_))
                | (T::Bool, V::Bool(_))
                | (T::Integer, V::Int(_) | V::Hex(_))
                | (T::Color | T::Drawable | T::Mipmap, V::Color(_))
                | (T::Dimen, V::Dimension(_))
                | (T::Fraction, V::Fraction(_))
        )
    }
}

/// The contents of one resource variant.
#[derive(Clone, Debug, PartialEq)]
enum Item {
    Value(Value),
    /// A file stored as is.
    File {
        path: ArchivePath,
        content: Content,
    },
    /// A document compiled to binary XML.
    Xml {
        path: ArchivePath,
        document: Document,
    },
}

/// An application's resources: values, files, and XML documents, each
/// defined for one or more configurations.
///
/// IDs are assigned when compiling, by type and then by name, so adding a
/// resource can change the IDs of others. Like aapt2, the compiler adds the
/// minimum API level a configuration's qualifiers imply (`night` is stored
/// as `night-v8`).
///
/// ```
/// use apk::res::{Config, Density, Resources, ResourceType};
///
/// let mut resources = Resources::new();
/// resources.string("app_name", "Postcard")?;
/// resources.localized_string("app_name", "fr".parse()?, "Carte postale")?;
/// let png = vec![0x89, b'P', b'N', b'G'];
/// resources.file(ResourceType::Mipmap, "ic_launcher", Config::for_density(Density::XHDPI), "png", png)?;
/// # Ok::<(), apk::Error>(())
/// ```
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Resources {
    types: BTreeMap<ResourceType, BTreeMap<ResourceName, BTreeMap<Config, Item>>>,
}

impl Resources {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn is_empty(&self) -> bool {
        self.types.is_empty()
    }

    /// Whether a resource with this type and name exists in any configuration.
    pub fn contains(&self, ty: ResourceType, name: &str) -> bool {
        self.variants(ty, name).is_some()
    }

    /// Whether a resource with this type and name is defined for `config`.
    pub fn contains_variant(&self, ty: ResourceType, name: &str, config: Config) -> bool {
        self.variants(ty, name).is_some_and(|variants| variants.contains_key(&config.with_implied_sdk_version()))
    }

    fn variants(&self, ty: ResourceType, name: &str) -> Option<&BTreeMap<Config, Item>> {
        self.types.get(&ty)?.get(name)
    }

    /// Adds a simple value: a string, bool, integer, color, dimension,
    /// fraction, or a reference to another resource.
    pub fn value(
        &mut self,
        ty: ResourceType,
        name: &str,
        config: Config,
        value: impl Into<Value>,
    ) -> Result<&mut Self, ResourceError> {
        let name = ResourceName::try_new(name)?;
        let value = value.into();
        if ty.is_bag_type() {
            return Err(ResourceError::Unsupported { ty });
        }
        if !ty.accepts(&value) {
            return Err(ResourceError::ValueMismatch { ty, name });
        }
        self.insert(ty, name, config, |_| Ok(Item::Value(value)))
    }

    /// Adds the default value of string resource `name`.
    pub fn string(&mut self, name: &str, value: impl Into<String>) -> Result<&mut Self, ResourceError> {
        self.value(ResourceType::String, name, Config::default(), Value::String(value.into()))
    }

    /// Adds a translation of string resource `name`.
    pub fn localized_string(
        &mut self,
        name: &str,
        locale: Locale,
        value: impl Into<String>,
    ) -> Result<&mut Self, ResourceError> {
        self.value(ResourceType::String, name, Config::for_locale(locale), Value::String(value.into()))
    }

    /// Adds a file stored as is, at `res/<type>[-<qualifiers>]/<name>.<extension>`.
    /// XML (except in raw files) must be added with [`xml`](Self::xml),
    /// which compiles it.
    pub fn file(
        &mut self,
        ty: ResourceType,
        name: &str,
        config: Config,
        extension: &str,
        content: impl Into<Content>,
    ) -> Result<&mut Self, ResourceError> {
        let name = ResourceName::try_new(name)?;
        if !ty.is_file_type() {
            return Err(ResourceError::NotAFileType { ty });
        }
        let valid = |part: &str| !part.is_empty() && part.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit());
        if !extension.split('.').all(valid) {
            return Err(ResourceError::InvalidExtension { extension: extension.to_owned() });
        }
        if extension == "xml" && ty != ResourceType::Raw {
            return Err(ResourceError::TextXml { ty, name });
        }
        if extension == "9.png" {
            return Err(ResourceError::NinePatch { name });
        }
        let content = content.into();
        self.insert(ty, name, config, |slot| Ok(Item::File { path: slot.path(extension)?, content }))
    }

    /// Adds an XML file resource, such as an adaptive icon, a color state
    /// list, or a network security config, compiled to binary XML. Its
    /// references may name other resources in this set.
    pub fn xml(
        &mut self,
        ty: ResourceType,
        name: &str,
        config: Config,
        document: Document,
    ) -> Result<&mut Self, ResourceError> {
        let name = ResourceName::try_new(name)?;
        if !(ty.is_file_type() || ty == ResourceType::Color) || ty == ResourceType::Raw {
            return Err(ResourceError::NotAnXmlType { ty });
        }
        self.insert(ty, name, config, |slot| Ok(Item::Xml { path: slot.path("xml")?, document }))
    }

    /// Adds the item `make` builds for the slot `(ty, name, config)`.
    fn insert(
        &mut self,
        ty: ResourceType,
        name: ResourceName,
        config: Config,
        make: impl FnOnce(&Slot<'_>) -> Result<Item, ResourceError>,
    ) -> Result<&mut Self, ResourceError> {
        let config = config.with_implied_sdk_version();
        if self.variants(ty, &name).is_some_and(|variants| variants.contains_key(&config)) {
            return Err(ResourceError::Duplicate { ty, name, config });
        }
        let item = make(&Slot { ty, name: &name, config })?;
        self.types.entry(ty).or_default().entry(name).or_default().insert(config, item);
        Ok(self)
    }

    /// Assigns IDs and writes the resource table for `package`, for an app
    /// supporting `min_sdk` onwards.
    ///
    /// Like aapt2, version qualifiers the minimum SDK already satisfies are
    /// dropped from the table (`night-v8` becomes `night`); when that makes
    /// variants collide, the one with the highest version is kept.
    pub fn compile(&self, package: &PackageName, min_sdk: ApiLevel) -> Result<CompiledResources<'_>, ResourceError> {
        let ids = Ids(self
            .types
            .iter()
            .enumerate()
            .flat_map(|(type_index, (&ty, entries))| {
                entries.keys().enumerate().map(move |(entry, name)| {
                    // Out-of-range indices are rejected when the table is written.
                    let id = ResourceId::new(ResourceId::APP_PACKAGE, type_index as u8 + 1, entry as u16);
                    (ty, name, id)
                })
            })
            .collect());
        let mut strings = StringPoolBuilder::default();
        let mut files = Vec::new();
        let mut types = Vec::with_capacity(self.types.len());
        for (&ty, entries) in &self.types {
            let mut data = TypeData { ty, entries: Vec::with_capacity(entries.len()) };
            for (name, variants) in entries {
                let mut variants: Vec<(Config, u16, &Item)> = variants
                    .iter()
                    .map(|(&config, item)| {
                        let version = config.sdk_version();
                        let implied = u32::from(version) <= min_sdk.get();
                        (if implied { config.with_sdk_version(0) } else { config }, version, item)
                    })
                    .collect();
                variants.sort_by_key(|&(config, version, _)| (config, Reverse(version)));
                variants.dedup_by_key(|&mut (config, _, _)| config);
                if !ty.is_file_type() && !variants.iter().any(|(config, _, _)| config.is_default()) {
                    return Err(ResourceError::MissingDefault { ty, name: name.clone() });
                }
                let mut values = Vec::with_capacity(variants.len());
                for (config, _, item) in variants {
                    let value = match item {
                        Item::Value(value) => {
                            let unresolved = |reference: &ResourceRef| ResourceError::UnresolvedReference {
                                ty,
                                name: name.clone(),
                                reference: reference.clone(),
                            };
                            let lookup =
                                |reference: &ResourceRef| resolve(reference, &ids).ok_or_else(|| unresolved(reference));
                            value.to_raw(|s| strings.intern(s), lookup)?
                        }
                        Item::File { path, content } => {
                            files.push((path, Cow::Borrowed(content)));
                            RawValue::new(data_type::STRING, strings.intern(path.as_str()))
                        }
                        Item::Xml { path, document } => {
                            let xml = |source| ResourceError::Xml { ty, name: name.clone(), source: Box::new(source) };
                            let bytes = document.encode(&ids).map_err(xml)?;
                            files.push((path, Cow::Owned(Content::from(bytes))));
                            RawValue::new(data_type::STRING, strings.intern(path.as_str()))
                        }
                    };
                    values.push((config, value));
                }
                data.entries.push(EntryData { name: name.as_str(), values });
            }
            types.push(data);
        }
        let table = table::write(ResourceId::APP_PACKAGE, package.as_str(), &strings, &types)?;
        files.sort_by_key(|&(path, _)| path);
        Ok(CompiledResources { table, files, ids })
    }
}

/// Where a file resource of a given type, name, and configuration is stored.
struct Slot<'a> {
    ty: ResourceType,
    name: &'a ResourceName,
    config: Config,
}

impl Slot<'_> {
    /// `res/<type>[-<qualifiers>]/<name>.<extension>`.
    fn path(&self, extension: &str) -> Result<ArchivePath, ResourceError> {
        let Self { ty, name, config } = *self;
        if !name.is_file_name() {
            return Err(ResourceError::InvalidFileName { name: name.clone() });
        }
        let path = match config.is_default() {
            true => format!("res/{ty}/{name}.{extension}"),
            false => format!("res/{ty}-{config}/{name}.{extension}"),
        };
        ArchivePath::try_new(path).map_err(|source| ResourceError::Path { ty, name: name.clone(), source })
    }
}

/// The IDs assigned by [`Resources::compile`], ordered by type and name.
#[derive(Clone, Debug, PartialEq)]
struct Ids<'a>(Vec<(ResourceType, &'a ResourceName, ResourceId)>);

impl Ids<'_> {
    fn get(&self, ty: ResourceType, name: &str) -> Option<ResourceId> {
        let index = self.0.binary_search_by(|&(t, n, _)| (t, n.as_str()).cmp(&(ty, name))).ok()?;
        Some(self.0[index].2)
    }
}

impl ResourceLookup for Ids<'_> {
    fn lookup(&self, ty: ResourceType, name: &ResourceName) -> Option<ResourceId> {
        self.get(ty, name)
    }
}

/// The output of [`Resources::compile`], borrowing the resources' files.
#[derive(Clone, Debug, PartialEq)]
pub struct CompiledResources<'a> {
    /// The encoded `resources.arsc`.
    pub table: Vec<u8>,
    /// Files to store in the APK, by path.
    pub files: Vec<(&'a ArchivePath, Cow<'a, Content>)>,
    ids: Ids<'a>,
}

impl CompiledResources<'_> {
    /// The ID assigned to resource `name` of type `ty`.
    pub fn id(&self, ty: ResourceType, name: &str) -> Option<ResourceId> {
        self.ids.get(ty, name)
    }
}

impl ResourceLookup for CompiledResources<'_> {
    fn lookup(&self, ty: ResourceType, name: &ResourceName) -> Option<ResourceId> {
        self.ids.lookup(ty, name)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::android::attr;
    use crate::res::{Color, Density, EntryValue, ResourceTable};
    use crate::xml::Element;

    fn package() -> PackageName {
        PackageName::try_new("org.example.app").unwrap()
    }

    #[test]
    fn assigns_ids_and_writes_the_table() {
        let mut resources = Resources::new();
        resources.string("app_name", "Hello").unwrap();
        resources.localized_string("app_name", "fr".parse().unwrap(), "Bonjour").unwrap();
        resources.string("about", "About").unwrap();
        resources
            .file(ResourceType::Mipmap, "ic_launcher", Config::for_density(Density::XHDPI), "png", b"png")
            .unwrap();
        let compiled = resources.compile(&package(), ApiLevel::N).unwrap();

        // Types are numbered in `ResourceType` order, entries by name.
        assert_eq!(compiled.id(ResourceType::Mipmap, "ic_launcher"), Some(ResourceId(0x7f01_0000)));
        assert_eq!(compiled.id(ResourceType::String, "about"), Some(ResourceId(0x7f02_0000)));
        assert_eq!(compiled.id(ResourceType::String, "app_name"), Some(ResourceId(0x7f02_0001)));
        assert_eq!(compiled.files[0].0.as_str(), "res/mipmap-xhdpi-v4/ic_launcher.png");

        let table = ResourceTable::parse(&compiled.table).unwrap();
        let app_name = table.get(ResourceId(0x7f02_0001)).unwrap();
        assert_eq!(app_name.value(&"fr".parse().unwrap()), Some(EntryValue::Simple("Bonjour".into())));
        assert_eq!(table.find(0x7f, ResourceType::Mipmap, "ic_launcher"), Some(ResourceId(0x7f01_0000)));
    }

    #[test]
    fn compiles_xml_resources_against_app_ids() {
        let mut resources = Resources::new();
        resources.value(ResourceType::Color, "background", Config::default(), Color::rgb(0x112233)).unwrap();
        resources.file(ResourceType::Mipmap, "foreground", Config::default(), "png", b"png").unwrap();
        let reference = |text: &str| text.parse::<ResourceRef>().unwrap();
        let icon = Element::new("adaptive-icon")
            .with_android_namespace()
            .with_child(Element::new("background").with_attr(attr::DRAWABLE, reference("@color/background")))
            .with_child(Element::new("foreground").with_attr(attr::DRAWABLE, reference("@mipmap/foreground")));
        resources.xml(ResourceType::Mipmap, "ic_launcher", "anydpi-v26".parse().unwrap(), Document::new(icon)).unwrap();
        let compiled = resources.compile(&package(), ApiLevel::N).unwrap();
        let (path, content) = compiled.files.iter().find(|(p, _)| p.extension() == Some("xml")).unwrap();
        assert_eq!(path.as_str(), "res/mipmap-anydpi-v26/ic_launcher.xml");
        let Content::Bytes(bytes) = content.as_ref() else { panic!("compiled XML is in memory") };
        let decoded = Document::decode(bytes).unwrap();
        let background = decoded.root.element("background").unwrap().android_attr(attr::DRAWABLE).unwrap();
        let id = compiled.id(ResourceType::Color, "background").unwrap();
        assert_eq!(background, &Value::Reference(id.into()));
    }

    #[test]
    fn versions_the_minimum_sdk_implies_are_collapsed() {
        let mut resources = Resources::new();
        let color = |rgb| Color::rgb(rgb);
        resources
            .value(ResourceType::Color, "tint", Config::default(), color(0x000000))
            .unwrap()
            .value(ResourceType::Color, "tint", "night".parse().unwrap(), color(0x111111))
            .unwrap()
            .value(ResourceType::Color, "tint", "v21".parse().unwrap(), color(0x222222))
            .unwrap()
            .value(ResourceType::Color, "tint", "v23".parse().unwrap(), color(0x333333))
            .unwrap()
            .value(ResourceType::Color, "tint", "v26".parse().unwrap(), color(0x444444))
            .unwrap();
        let compiled = resources.compile(&package(), ApiLevel::N).unwrap();
        let table = ResourceTable::parse(&compiled.table).unwrap();
        let tint = table.get(compiled.id(ResourceType::Color, "tint").unwrap()).unwrap();
        let values: Vec<(String, String)> = tint.values().map(|(c, v)| (c.to_string(), v.to_string())).collect();
        // `v23` outranks `v21` and the unversioned default once API 24 is assumed.
        assert_eq!(
            values,
            [("", "#333333"), ("night", "#111111"), ("v26", "#444444")].map(|(c, v)| (c.into(), v.into()))
        );
    }

    #[test]
    fn rejects_inconsistent_definitions() {
        let mut resources = Resources::new();
        resources.string("title", "A").unwrap();
        assert!(matches!(resources.string("title", "B"), Err(ResourceError::Duplicate { .. })));
        assert!(matches!(
            resources.value(ResourceType::Bool, "flag", Config::default(), "yes"),
            Err(ResourceError::ValueMismatch { .. })
        ));
        assert!(matches!(
            resources.file(ResourceType::Mipmap, "Icon", Config::default(), "png", b""),
            Err(ResourceError::InvalidFileName { .. })
        ));
        assert!(matches!(
            resources.file(ResourceType::String, "x", Config::default(), "txt", b""),
            Err(ResourceError::NotAFileType { .. })
        ));
        let mut untranslated = Resources::new();
        untranslated.localized_string("greeting", "de".parse().unwrap(), "Hallo").unwrap();
        assert!(matches!(untranslated.compile(&package(), ApiLevel::N), Err(ResourceError::MissingDefault { .. })));
    }

    #[test]
    fn rejects_resources_it_cannot_build() {
        let mut resources = Resources::new();
        let document = || Document::new(Element::new("selector"));
        assert!(matches!(
            resources.value(ResourceType::Style, "Theme", Config::default(), Value::Null),
            Err(ResourceError::Unsupported { ty: ResourceType::Style })
        ));
        assert!(matches!(
            resources.file(ResourceType::Drawable, "shape", Config::default(), "xml", b"<shape/>"),
            Err(ResourceError::TextXml { .. })
        ));
        assert!(matches!(
            resources.file(ResourceType::Drawable, "button", Config::default(), "9.png", b""),
            Err(ResourceError::NinePatch { .. })
        ));
        assert!(matches!(
            resources.xml(ResourceType::Raw, "config", Config::default(), document()),
            Err(ResourceError::NotAnXmlType { ty: ResourceType::Raw })
        ));
        // Color state lists are XML; raw XML is stored as is.
        resources.xml(ResourceType::Color, "tint", Config::default(), document()).unwrap();
        resources.file(ResourceType::Raw, "config", Config::default(), "xml", b"<config/>").unwrap();
    }

    #[test]
    fn overlong_paths_are_errors_not_panics() {
        let (name, extension) = ("a".repeat(30_000), "b".repeat(40_000));
        let mut resources = Resources::new();
        let result = resources.file(ResourceType::Raw, &name, Config::default(), &extension, b"");
        assert!(matches!(result, Err(ResourceError::Path { .. })));
    }
}