-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathapk.rs
More file actions
332 lines (281 loc) · 9.99 KB
/
Copy pathapk.rs
File metadata and controls
332 lines (281 loc) · 9.99 KB
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
use crate::error::NdkError;
use crate::manifest::AndroidManifest;
use crate::ndk::{Key, Ndk};
use crate::target::Target;
use std::collections::HashMap;
use std::collections::HashSet;
use std::ffi::OsStr;
use std::fs;
#[cfg(target_family = "unix")]
use std::os::unix::prelude::PermissionsExt;
use std::path::{Path, PathBuf};
use std::process::Command;
/// The options for how to treat debug symbols that are present in any `.so`
/// files that are added to the APK.
///
/// Using [`strip`](https://doc.rust-lang.org/cargo/reference/profiles.html#strip)
/// or [`split-debuginfo`](https://doc.rust-lang.org/cargo/reference/profiles.html#split-debuginfo)
/// in your cargo manifest(s) may cause debug symbols to not be present in a
/// `.so`, which would cause these options to do nothing.
#[derive(Debug, Copy, Clone, PartialEq, Eq, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StripConfig {
/// Does not treat debug symbols specially
Default,
/// Removes debug symbols from the library before copying it into the APK
Strip,
/// Splits the library into into an ELF (`.so`) and DWARF (`.dwarf`). Only the
/// `.so` is copied into the APK
Split,
}
impl Default for StripConfig {
fn default() -> Self {
Self::Default
}
}
pub struct ApkConfig {
pub ndk: Ndk,
pub build_dir: PathBuf,
pub apk_name: String,
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 unaligned_apk(&self) -> PathBuf {
self.build_dir
.join(format!("{}-unaligned.apk", self.apk_name))
}
/// Retrieves the path of the APK that will be written when [`UnsignedApk::sign`]
/// is invoked
#[inline]
pub fn apk(&self) -> PathBuf {
self.build_dir.join(format!("{}.apk", self.apk_name))
}
pub fn create_apk(&self) -> Result<UnalignedApk, NdkError> {
fs::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());
let mut aapt = self.build_tool(bin!("aapt"))?;
aapt.arg("package")
.arg("-f")
.arg("-F")
.arg(self.unaligned_apk())
.arg("-M")
.arg("AndroidManifest.xml")
.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(aapt));
}
Ok(UnalignedApk {
config: self,
pending_libs: HashSet::default(),
})
}
}
pub struct UnalignedApk<'a> {
config: &'a ApkConfig,
pending_libs: HashSet<String>,
}
impl<'a> UnalignedApk<'a> {
pub fn config(&self) -> &ApkConfig {
self.config
}
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);
fs::create_dir_all(out.parent().unwrap())?;
match self.config.strip {
StripConfig::Default => {
fs::copy(path, out.clone())?;
#[cfg(target_family = "unix")]
fs::set_permissions(out, fs::Permissions::from_mode(0o644))?;
}
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(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(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(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 fs::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(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(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(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(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(adb));
}
Ok(())
}
pub fn start(&self, device_serial: Option<&str>) -> Result<u32, NdkError> {
let mut am_start = self.ndk.adb(device_serial)?;
am_start
.arg("shell")
.arg("am")
.arg("start")
.arg("-W")
.arg("-a")
.arg("android.intent.action.MAIN")
.arg("-n")
.arg(format!("{}/android.app.NativeActivity", &self.package_name));
if !am_start.status()?.success() {
return Err(NdkError::CmdFailed(am_start));
}
let pid_vec = self
.ndk
.adb(device_serial)?
.arg("shell")
.arg("pidof")
.arg(&self.package_name)
.output()?
.stdout;
let pid = std::str::from_utf8(&pid_vec).unwrap().trim();
let pid: u32 = pid
.parse()
.map_err(|e| NdkError::NotAPid(e, pid.to_owned()))?;
println!("Launched with PID {}", pid);
Ok(pid)
}
}