ndk-build2 1.3.7

Utilities for building Android binaries
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
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use {
    crate::{
        error::NdkError,
        manifest::AndroidManifest,
        ndk::{Key, Ndk},
        target::Target,
    },
    serde::{Deserialize, Serialize},
    std::{
        collections::{HashMap, HashSet},
        ffi::OsStr,
        fs::{copy, create_dir_all, read_dir, remove_dir_all, remove_file, rename},
        io::Error as IoError,
        path::{Path, PathBuf},
        process::Command,
        str::from_utf8,
    },
};

//noinspection SpellCheckingInspection
/// 如何处理添加到 APK 的任何 `.so` 文件中的调试符号的选项。
///
/// 在您的货物清单中使用
/// [`strip`](https://doc.rust-lang.org/cargo/reference/profiles.html#strip)
/// 或 [`split-debuginfo`](https://doc.rust-lang.org/cargo/reference/profiles.html#split-debuginfo)
/// 可能会导致调试符号不存在于 `.so` 中,从而导致这些选项不执行任何操作。
#[derive(Debug, Copy, Clone, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum StripConfig {
    /// 不对调试符号进行特殊处理
    #[default]
    Default,
    /// 在将库复制到 APK 之前,从库中删除调试符号
    Strip,
    /// 将库拆分为 ELF(`.so`)和 DWARF(`.dwarf`)。只有 `.so` 会被复制到 APK 中
    Split,
}

pub struct ApkConfig {
    pub ndk: Ndk,
    pub build_dir: PathBuf,
    pub apk_name: String,
    pub use_aapt2: bool,
    pub assets: Option<PathBuf>,
    pub resources: Option<PathBuf>,
    pub manifest: AndroidManifest,
    pub disable_aapt_compression: bool,
    pub strip: StripConfig,
    pub reverse_port_forward: HashMap<String, String>,
}

impl ApkConfig {
    fn build_tool(&self, tool: &'static str) -> Result<Command, NdkError> {
        let mut cmd = self.ndk.build_tool(tool)?;
        cmd.current_dir(&self.build_dir);

        Ok(cmd)
    }

    fn build_tool_utf8(&self, tool: &'static str) -> Result<Command, NdkError> {
        let mut cmd = self.ndk.build_tool_utf8(tool)?;
        cmd.current_dir(&self.build_dir);

        Ok(cmd)
    }

    fn unaligned_apk(&self) -> PathBuf {
        self.build_dir
            .join(format!("{}-unaligned.apk", self.apk_name))
    }

    /// 调用 [`UnsignedApk::sign`] 时将写入的 APK 的路径
    #[inline]
    pub fn apk(&self) -> PathBuf {
        self.build_dir.join(format!("{}.apk", self.apk_name))
    }

    pub fn create_apk<P>(&self, gen_java_dir: P) -> Result<UnalignedApk<'_>, NdkError>
    where
        P: AsRef<Path>,
    {
        create_dir_all(&self.build_dir)?;
        self.manifest.write_to(&self.build_dir)?;

        let target_sdk_version = self
            .manifest
            .sdk
            .target_sdk_version
            .unwrap_or_else(|| self.ndk.default_target_platform());

        if self.use_aapt2 {
            let out_dir = self.build_dir.join("resources");
            self.aapt2_compile(&out_dir)?;
            self.aapt2_link(
                &out_dir,
                &gen_java_dir.as_ref().to_path_buf(),
                target_sdk_version,
            )?;
            if !self.manifest.application.debuggable.unwrap_or(false) {
                self.aapt2_optimize()?;
            }
        } else {
            self.aapt_package(&gen_java_dir, target_sdk_version)?;
        }

        Ok(UnalignedApk {
            config: self,
            pending_libs: HashSet::default(),
        })
    }

    fn aapt_package<P>(&self, gen_java_dir: P, target_sdk_version: u32) -> Result<(), NdkError>
    where
        P: AsRef<Path>,
    {
        if self.resources.is_some() {
            create_dir_all(&gen_java_dir)?;
        }

        let mut aapt = self.build_tool(bin!("aapt"))?;
        println!("Packing apk resources......");
        aapt.arg("package")
            .arg("-f")
            .arg("-F")
            .arg(self.unaligned_apk())
            .arg("-M")
            .arg("AndroidManifest.xml")
            .arg("-J")
            .arg(gen_java_dir.as_ref())
            .arg("--generate-dependencies")
            .arg("--auto-add-overlay")
            .arg("-I")
            .arg(self.ndk.android_jar(target_sdk_version)?);

        if self.disable_aapt_compression {
            aapt.arg("-0").arg("");
        }

        if let Some(res) = &self.resources {
            aapt.arg("-S").arg(res);
        }

        if let Some(assets) = &self.assets {
            aapt.arg("-A").arg(assets);
        }

        if !aapt.status()?.success() {
            return Err(NdkError::CmdFailed(Box::new(aapt)));
        }

        Ok(())
    }

    fn aapt2_compile<P>(&self, out_dir: P) -> Result<(), NdkError>
    where
        P: AsRef<Path>,
    {
        let _ = remove_dir_all(&out_dir);
        create_dir_all(&out_dir)?;

        let mut aapt = self.build_tool_utf8(bin!("aapt2"))?;
        println!("Compiling apk resources...");
        aapt.arg("compile").arg("-o").arg(out_dir.as_ref());

        if self.disable_aapt_compression {
            aapt.arg("--no-crunch");
        }

        if let Some(res) = &self.resources {
            aapt.arg("--dir").arg(res);
        }

        if !aapt.status()?.success() {
            return Err(NdkError::CmdFailed(Box::new(aapt)));
        }

        Ok(())
    }

    fn aapt2_link<P>(
        &self,
        compiled_dir: P,
        gen_java_dir: P,
        target_sdk_version: u32,
    ) -> Result<(), NdkError>
    where
        P: AsRef<Path>,
    {
        let mut aapt = self.build_tool_utf8(bin!("aapt2"))?;
        println!("Linking apk resources...");
        aapt.arg("link")
            .arg("-o")
            .arg(self.unaligned_apk())
            .arg("--manifest")
            .arg("AndroidManifest.xml")
            .arg("-I")
            .arg(self.ndk.android_jar(target_sdk_version)?)
            .arg("--java")
            .arg(gen_java_dir.as_ref());

        if self.disable_aapt_compression {
            aapt.arg("--no-compress");
        }

        if let Some(assets) = &self.assets {
            aapt.arg("-A").arg(assets);
        }

        if compiled_dir.as_ref().exists()
            && let Ok(files) = read_dir(compiled_dir)
        {
            for file in files {
                aapt.arg(file?.path());
            }
        }

        if !aapt.status()?.success() {
            return Err(NdkError::CmdFailed(Box::new(aapt)));
        }

        Ok(())
    }

    fn aapt2_optimize(&self) -> Result<(), NdkError> {
        let mut aapt = self.build_tool_utf8(bin!("aapt2"))?;
        println!("Optimizing apk resources...");
        let path = self.unaligned_apk();
        let input_path = path.parent().unwrap().join(&self.manifest.package);
        rename(&path, &input_path)?;
        aapt.arg("optimize")
            .arg("-o")
            .arg(path)
            .arg(&input_path)
            .arg("--enable-sparse-encoding");

        if !aapt.status()?.success() {
            remove_file(input_path)?;
            return Err(NdkError::CmdFailed(Box::new(aapt)));
        }
        remove_file(input_path)?;
        Ok(())
    }
}

pub struct UnalignedApk<'a> {
    config: &'a ApkConfig,
    pending_libs: HashSet<String>,
}

impl<'a> UnalignedApk<'a> {
    pub fn config(&self) -> &ApkConfig {
        self.config
    }

    /// 将jar文件转换为dex并添加到APK中
    pub fn put_jar(&mut self, jar_file: &Path) -> Result<(), NdkError> {
        if !jar_file.exists() {
            return Ok(());
        }

        // 尝试使用d8工具(Android SDK新版本)
        let target_sdk_version = self
            .config
            .manifest
            .sdk
            .target_sdk_version
            .unwrap_or_else(|| self.config.ndk.default_target_platform());
        let min_sdk_version = self
            .config
            .manifest
            .sdk
            .min_sdk_version
            .unwrap_or_else(|| self.config.ndk.default_target_platform());

        let mut d8 = self
            .config()
            .build_tool(if cfg!(windows) { "d8.bat" } else { "d8" })?;
        d8.arg("--output")
            .arg(&self.config.build_dir)
            .arg("--intermediate")
            .arg("--min-api")
            .arg(min_sdk_version.to_string())
            .arg("--lib")
            .arg(&self.config.ndk.android_jar(target_sdk_version)?)
            .arg(jar_file);

        let dex_file = self.config.build_dir.join("classes.dex");
        let d8_result = d8.status();
        let success = match d8_result {
            Ok(status) => status.success(),
            Err(_) => {
                // 如果d8不可用,尝试使用dx工具(旧版本)
                println!("d8 not found, trying dx...");
                let mut dx = Command::new("dx");
                dx.arg("--dex").arg("--output").arg(&dex_file).arg(jar_file);

                dx.status()?.success()
            }
        };

        if !success {
            return Err(IoError::other("Failed to convert jar to dex").into());
        }

        // 将classes.dex/classesN.dex文件添加到APK中
        let mut dex_entries = Vec::new();
        for entry in read_dir(&self.config.build_dir)? {
            let entry = entry?;
            let path = entry.path();
            let Some(file_name) = path.file_name().and_then(|value| value.to_str()) else {
                continue;
            };
            if file_name == "classes.dex"
                || (file_name.starts_with("classes")
                    && file_name.ends_with(".dex")
                    && file_name[7..file_name.len() - 4]
                        .chars()
                        .all(|ch| ch.is_ascii_digit()))
            {
                dex_entries.push(file_name.to_string());
            }
        }
        dex_entries.sort();

        if !dex_entries.is_empty() {
            let mut aapt = self.config.build_tool(bin!("aapt"))?;
            aapt.arg("add").arg(self.config.unaligned_apk());
            for dex_entry in &dex_entries {
                aapt.arg(dex_entry);
            }

            if !aapt.status()?.success() {
                return Err(NdkError::CmdFailed(Box::new(aapt)));
            }
        }

        Ok(())
    }

    //noinspection SpellCheckingInspection
    pub fn add_lib(&mut self, path: &Path, target: Target) -> Result<(), NdkError> {
        if !path.exists() {
            return Err(NdkError::PathNotFound(path.into()));
        }
        let abi = target.android_abi();
        let lib_path = Path::new("lib").join(abi).join(path.file_name().unwrap());
        let out = self.config.build_dir.join(&lib_path);
        create_dir_all(out.parent().unwrap())?;

        match self.config.strip {
            StripConfig::Default => {
                copy(path, out)?;
            }
            StripConfig::Strip | StripConfig::Split => {
                let obj_copy = self.config.ndk.toolchain_bin("objcopy", target)?;

                {
                    let mut cmd = Command::new(&obj_copy);
                    cmd.arg("--strip-debug");
                    cmd.arg(path);
                    cmd.arg(&out);

                    if !cmd.status()?.success() {
                        return Err(NdkError::CmdFailed(Box::new(cmd)));
                    }
                }

                if self.config.strip == StripConfig::Split {
                    let dwarf_path = out.with_extension("dwarf");

                    {
                        let mut cmd = Command::new(&obj_copy);
                        cmd.arg("--only-keep-debug");
                        cmd.arg(path);
                        cmd.arg(&dwarf_path);

                        if !cmd.status()?.success() {
                            return Err(NdkError::CmdFailed(Box::new(cmd)));
                        }
                    }

                    let mut cmd = Command::new(obj_copy);
                    cmd.arg(format!("--add-gnu-debuglink={}", dwarf_path.display()));
                    cmd.arg(out);

                    if !cmd.status()?.success() {
                        return Err(NdkError::CmdFailed(Box::new(cmd)));
                    }
                }
            }
        }

        // Pass UNIX path separators to `aapt` on non-UNIX systems, ensuring the resulting separator
        // is compatible with the target device instead of the host platform.
        // Otherwise, it results in a runtime error when loading the \NativeActivity `.so` library.
        let lib_path_unix = lib_path.to_str().unwrap().replace('\\', "/");

        self.pending_libs.insert(lib_path_unix);

        Ok(())
    }

    pub fn add_runtime_libs(
        &mut self,
        path: &Path,
        target: Target,
        search_paths: &[&Path],
    ) -> Result<(), NdkError> {
        let abi_dir = path.join(target.android_abi());
        for entry in read_dir(&abi_dir).map_err(|e| NdkError::IoPathError(abi_dir, e))? {
            let entry = entry?;
            let path = entry.path();
            if path.extension() == Some(OsStr::new("so")) {
                self.add_lib_recursively(&path, target, search_paths)?;
            }
        }
        Ok(())
    }

    pub fn add_pending_libs_and_align(self) -> Result<UnsignedApk<'a>, NdkError> {
        let mut aapt = self.config.build_tool(bin!("aapt"))?;
        aapt.arg("add");

        if self.config.disable_aapt_compression {
            aapt.arg("-0").arg("");
        }

        aapt.arg(self.config.unaligned_apk());

        for lib_path_unix in self.pending_libs {
            aapt.arg(lib_path_unix);
        }

        if !aapt.status()?.success() {
            return Err(NdkError::CmdFailed(Box::new(aapt)));
        }

        let mut zipalign = self.config.build_tool(bin!("zipalign"))?;
        zipalign
            .arg("-f")
            .arg("-v")
            .arg("4")
            .arg(self.config.unaligned_apk())
            .arg(self.config.apk());

        if !zipalign.status()?.success() {
            return Err(NdkError::CmdFailed(Box::new(zipalign)));
        }

        Ok(UnsignedApk(self.config))
    }
}

pub struct UnsignedApk<'a>(&'a ApkConfig);

impl<'a> UnsignedApk<'a> {
    pub fn sign(self, key: Key) -> Result<Apk, NdkError> {
        let mut apksigner = self.0.build_tool(bat!("apksigner"))?;
        apksigner
            .arg("sign")
            .arg("--ks")
            .arg(&key.path)
            .arg("--ks-pass")
            .arg(format!("pass:{}", &key.password))
            .arg(self.0.apk());
        if !apksigner.status()?.success() {
            return Err(NdkError::CmdFailed(Box::new(apksigner)));
        }
        Ok(Apk::from_config(self.0))
    }
}

pub struct Apk {
    path: PathBuf,
    package_name: String,
    ndk: Ndk,
    reverse_port_forward: HashMap<String, String>,
}

impl Apk {
    pub fn from_config(config: &ApkConfig) -> Self {
        let ndk = config.ndk.clone();
        Self {
            path: config.apk(),
            package_name: config.manifest.package.clone(),
            ndk,
            reverse_port_forward: config.reverse_port_forward.clone(),
        }
    }

    pub fn reverse_port_forwarding(&self, device_serial: Option<&str>) -> Result<(), NdkError> {
        for (from, to) in &self.reverse_port_forward {
            println!("Reverse port forwarding from {} to {}", from, to);
            let mut adb = self.ndk.adb(device_serial)?;

            adb.arg("reverse").arg(from).arg(to);

            if !adb.status()?.success() {
                return Err(NdkError::CmdFailed(Box::new(adb)));
            }
        }

        Ok(())
    }

    pub fn install(&self, device_serial: Option<&str>) -> Result<(), NdkError> {
        let mut adb = self.ndk.adb(device_serial)?;

        adb.arg("install").arg("-r").arg(&self.path);
        if !adb.status()?.success() {
            return Err(NdkError::CmdFailed(Box::new(adb)));
        }
        Ok(())
    }

    pub fn start(
        &self,
        device_serial: Option<&str>,
        activity: Option<&str>,
    ) -> Result<(), NdkError> {
        let mut adb = self.ndk.adb(device_serial)?;
        adb.arg("shell")
            .arg("am")
            .arg("start")
            .arg("-a")
            .arg("android.intent.action.MAIN")
            .arg("-n");

        // 使用提供的activity参数,如果没有提供,则使用默认的NativeActivity
        let activity_name = activity.unwrap_or("android.app.NativeActivity");

        adb.arg(format!("{}/{}", self.package_name, activity_name));

        if !adb.status()?.success() {
            return Err(NdkError::CmdFailed(Box::new(adb)));
        }

        Ok(())
    }

    //noinspection SpellCheckingInspection
    pub fn uidof(&self, device_serial: Option<&str>) -> Result<u32, NdkError> {
        let mut adb = self.ndk.adb(device_serial)?;
        adb.arg("shell")
            .arg("pm")
            .arg("list")
            .arg("package")
            .arg("-U")
            .arg(&self.package_name);
        let output = adb.output()?;

        if !output.status.success() {
            return Err(NdkError::CmdFailed(Box::new(adb)));
        }

        let output = from_utf8(&output.stdout)?;
        let (_package, uid) = output
            .lines()
            .filter_map(|line| line.split_once(' '))
            // `pm list package` uses the id as a substring filter; make sure
            // we select the right package in case it returns multiple matches:
            .find(|(package, _uid)| package.strip_prefix("package:") == Some(&self.package_name))
            .ok_or(NdkError::PackageNotInOutput {
                package: self.package_name.clone(),
                output: output.to_owned(),
            })?;
        let uid = uid
            .strip_prefix("uid:")
            .ok_or(NdkError::UidNotInOutput(output.to_owned()))?;
        uid.parse()
            .map_err(|e| NdkError::NotAUid(e, uid.to_owned()))
    }
}