1mod render;
2
3#[cfg(target_family = "wasm")]
4compile_error!("java_asm_cli is a native-only executable");
5
6use clap::{Args, Parser, Subcommand, ValueEnum, ValueHint};
7use java_asm::AsmErr;
8use java_asm::StrRef;
9use java_asm::dex::{ClassDef, DexFile, DexFileAccessor};
10use java_asm::node::element::ClassNode;
11use java_asm_server::fuzzy::FuzzyMatchModel;
12use serde_json::{Map, Value, json};
13use std::fmt::{Display, Formatter};
14use std::fs;
15use std::io::{Cursor, Read};
16use std::path::{Path, PathBuf};
17use std::sync::Arc;
18
19use zip::ZipArchive;
20
21use crate::render::render_jvm_class;
22
23pub const DEFAULT_OUTPUT_DIR: &str = "asm_cli_output";
24const MAX_ARCHIVE_DEPTH: usize = 8;
25
26#[derive(Debug)]
27pub enum CliError {
28 Io {
29 path: PathBuf,
30 source: std::io::Error,
31 },
32 Zip {
33 path: PathBuf,
34 message: String,
35 },
36 Parse {
37 source: String,
38 message: String,
39 },
40 NotFound(String),
41 Ambiguous(String),
42}
43
44impl Display for CliError {
45 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
46 match self {
47 Self::Io { path, source } => write!(f, "{}: {source}", path.display()),
48 Self::Zip { path, message } => write!(f, "{}: {message}", path.display()),
49 Self::Parse { source, message } => write!(f, "{source}: {message}"),
50 Self::NotFound(message) | Self::Ambiguous(message) => write!(f, "{message}"),
51 }
52 }
53}
54
55impl std::error::Error for CliError {}
56
57#[derive(Debug, Parser)]
58#[command(
59 name = "java_asm_cli",
60 version,
61 about = "Find and export classes from Java and Android bytecode",
62 after_help = "Find commands emit JSON. export-class writes Smali to stdout unless --output is provided.\n\nExamples:\n java_asm_cli find-classes app.apks com.example.Main\n java_asm_cli export-class app.apks com.example.Main --internal-path base.apk!classes2.dex\n java_asm_cli export-all app.apk --class-filter com.example --output exported",
63 arg_required_else_help = true,
64 propagate_version = true
65)]
66pub struct Cli {
67 #[command(subcommand)]
68 command: Commands,
69}
70
71#[derive(Debug, Subcommand)]
72enum Commands {
73 #[command(
74 visible_alias = "findClasses",
75 about = "Find all matching classes and return their basic structure"
76 )]
77 FindClasses(FindClassesArgs),
78 #[command(
79 visible_alias = "exportClass",
80 about = "Export one class to stdout or a file"
81 )]
82 ExportClass(ExportClassArgs),
83 #[command(
84 visible_alias = "exportAll",
85 about = "Export all classes matching an optional filter"
86 )]
87 ExportAll(ExportAllArgs),
88}
89
90#[derive(Debug, Args)]
91struct FindClassesArgs {
92 #[arg(value_name = "INPUT", value_hint = ValueHint::FilePath)]
94 input: PathBuf,
95 #[arg(value_name = "QUERY")]
97 query: Option<String>,
98}
99
100#[derive(Debug, Args)]
101struct ExportClassArgs {
102 #[arg(value_name = "INPUT", value_hint = ValueHint::FilePath)]
104 input: PathBuf,
105 #[arg(value_name = "CLASS")]
107 class_name: String,
108 #[arg(long, value_name = "PATH")]
110 internal_path: Option<String>,
111 #[arg(short, long, value_name = "FILE", value_hint = ValueHint::FilePath)]
113 output: Option<PathBuf>,
114 #[arg(long, value_enum, default_value_t = ExportFormat::Smali)]
116 format: ExportFormat,
117}
118
119#[derive(Debug, Args)]
120struct ExportAllArgs {
121 #[arg(value_name = "INPUT", value_hint = ValueHint::FilePath)]
123 input: PathBuf,
124 #[arg(long, alias = "filter", value_name = "QUERY")]
126 class_filter: Option<String>,
127 #[arg(
129 short,
130 long,
131 default_value = "asm_cli_output",
132 value_name = "DIR",
133 value_hint = ValueHint::DirPath
134 )]
135 output: PathBuf,
136 #[arg(long, value_enum, default_value_t = ExportFormat::Smali)]
138 format: ExportFormat,
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
142enum ExportFormat {
143 Smali,
144}
145
146impl ExportFormat {
147 fn as_str(self) -> &'static str {
148 match self {
149 Self::Smali => "smali",
150 }
151 }
152
153 fn extension(self) -> &'static str {
154 self.as_str()
155 }
156}
157
158#[derive(Debug)]
159pub enum CliOutput {
160 Json(Value),
161 Text(String),
162}
163
164enum ClassPayload {
165 Dex {
166 accessor: Arc<DexFileAccessor>,
167 class_def: ClassDef,
168 },
169 Jvm {
170 node: Arc<ClassNode>,
171 },
172}
173
174struct ClassEntry {
175 internal_name: String,
176 descriptor: String,
177 internal_path: Option<String>,
178 payload: ClassPayload,
179}
180
181#[derive(Default)]
182struct InputIndex {
183 classes: Vec<ClassEntry>,
184}
185
186#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
187struct MethodInfo {
188 name: String,
189 signature: String,
190}
191
192#[derive(Debug, Eq, Ord, PartialEq, PartialOrd)]
193struct FieldInfo {
194 name: String,
195 field_type: String,
196}
197
198pub fn execute(cli: Cli) -> Result<CliOutput, CliError> {
199 match cli.command {
200 Commands::FindClasses(args) => execute_find_classes(args),
201 Commands::ExportClass(args) => execute_export_class(args),
202 Commands::ExportAll(args) => execute_export_all(args),
203 }
204}
205
206fn execute_find_classes(args: FindClassesArgs) -> Result<CliOutput, CliError> {
207 let index = InputIndex::load(&args.input, None)?;
208 let query = args.query.unwrap_or_default();
209 let classes = find_matching_classes(&index, &query)
210 .into_iter()
211 .map(|entry| entry.to_json())
212 .collect::<Result<Vec<_>, _>>()?;
213 Ok(CliOutput::Json(json!({
214 "ok": true,
215 "operation": "findClasses",
216 "input": args.input,
217 "query": query,
218 "count": classes.len(),
219 "classes": classes,
220 })))
221}
222
223fn execute_export_class(args: ExportClassArgs) -> Result<CliOutput, CliError> {
224 let index = InputIndex::load(&args.input, args.internal_path.as_deref())?;
225 let expected = normalize_class_name(&args.class_name);
226 let matches: Vec<&ClassEntry> = index
227 .classes
228 .iter()
229 .filter(|entry| entry.internal_name == expected)
230 .collect();
231 let entry = match matches.as_slice() {
232 [] => {
233 return Err(CliError::NotFound(format!(
234 "class not found: {}",
235 args.class_name
236 )));
237 }
238 [entry] => *entry,
239 entries => {
240 let paths = entries
241 .iter()
242 .filter_map(|entry| entry.internal_path.as_deref())
243 .collect::<Vec<_>>()
244 .join(", ");
245 return Err(CliError::Ambiguous(format!(
246 "class {} exists in multiple locations; pass --internal-path with one of: {paths}",
247 args.class_name
248 )));
249 }
250 };
251 let content = entry.render(args.format)?;
252 let Some(output) = args.output else {
253 return Ok(CliOutput::Text(content));
254 };
255 write_file(&output, content.as_bytes())?;
256 let mut result = Map::from_iter([
257 ("ok".to_owned(), Value::Bool(true)),
258 (
259 "operation".to_owned(),
260 Value::String("exportClass".to_owned()),
261 ),
262 ("input".to_owned(), json!(args.input)),
263 (
264 "class_name".to_owned(),
265 Value::String(entry.qualified_name()),
266 ),
267 (
268 "descriptor".to_owned(),
269 Value::String(entry.descriptor.clone()),
270 ),
271 (
272 "format".to_owned(),
273 Value::String(args.format.as_str().to_owned()),
274 ),
275 ("output".to_owned(), json!(output)),
276 ]);
277 insert_internal_path(&mut result, entry.internal_path.as_deref());
278 Ok(CliOutput::Json(Value::Object(result)))
279}
280
281fn execute_export_all(args: ExportAllArgs) -> Result<CliOutput, CliError> {
282 let index = InputIndex::load(&args.input, None)?;
283 let filter = args.class_filter.as_deref().unwrap_or_default();
284 let selected = find_matching_classes(&index, filter);
285 if selected.is_empty() {
286 return Err(CliError::NotFound(format!(
287 "no classes matched filter: {filter}"
288 )));
289 }
290 fs::create_dir_all(&args.output).map_err(|source| CliError::Io {
291 path: args.output.clone(),
292 source,
293 })?;
294 let mut classes = Vec::with_capacity(selected.len());
295 for entry in selected {
296 let output = class_output_path(&args.output, entry, args.format);
297 let content = entry.render(args.format)?;
298 write_file(&output, content.as_bytes())?;
299 let mut class = Map::from_iter([
300 (
301 "class_name".to_owned(),
302 Value::String(entry.qualified_name()),
303 ),
304 (
305 "descriptor".to_owned(),
306 Value::String(entry.descriptor.clone()),
307 ),
308 ("output".to_owned(), json!(output)),
309 ]);
310 insert_internal_path(&mut class, entry.internal_path.as_deref());
311 classes.push(Value::Object(class));
312 }
313 let manifest = json!({
314 "ok": true,
315 "operation": "exportAll",
316 "input": args.input,
317 "class_filter": args.class_filter,
318 "format": args.format.as_str(),
319 "output_dir": args.output,
320 "count": classes.len(),
321 "classes": classes,
322 });
323 let manifest_path = args.output.join("manifest.json");
324 let bytes = serde_json::to_vec_pretty(&manifest).map_err(|error| CliError::Parse {
325 source: "manifest.json".to_owned(),
326 message: format!("serialize manifest: {error}"),
327 })?;
328 write_file(&manifest_path, &bytes)?;
329 Ok(CliOutput::Json(manifest))
330}
331
332impl InputIndex {
333 fn load(path: &Path, internal_path: Option<&str>) -> Result<Self, CliError> {
334 let bytes = fs::read(path).map_err(|source| CliError::Io {
335 path: path.to_owned(),
336 source,
337 })?;
338 let mut index = Self::default();
339 if let Some(internal_path) = internal_path {
340 let bytes = read_internal_entry(path, bytes, internal_path)?;
341 index.collect_embedded(bytes, Some(internal_path.to_owned()), 0)?;
342 } else {
343 index.collect_embedded(bytes, None, 0)?;
344 }
345 if index.classes.is_empty() {
346 return Err(CliError::Parse {
347 source: input_label(path, internal_path),
348 message: "no supported DEX or class files found".to_owned(),
349 });
350 }
351 Ok(index)
352 }
353
354 fn collect_embedded(
355 &mut self,
356 bytes: Vec<u8>,
357 internal_path: Option<String>,
358 depth: usize,
359 ) -> Result<(), CliError> {
360 if is_dex(&bytes) {
361 return self.add_dex(internal_path, bytes);
362 }
363 if is_class(&bytes) {
364 return self.add_class(internal_path, bytes);
365 }
366 if !is_zip(&bytes) {
367 return Ok(());
368 }
369 self.collect_archive(bytes, internal_path.as_deref(), depth)
370 }
371
372 fn collect_archive(
373 &mut self,
374 bytes: Vec<u8>,
375 prefix: Option<&str>,
376 depth: usize,
377 ) -> Result<(), CliError> {
378 if depth >= MAX_ARCHIVE_DEPTH {
379 return Err(CliError::Parse {
380 source: prefix.unwrap_or("input").to_owned(),
381 message: "archive nesting is too deep".to_owned(),
382 });
383 }
384 let archive_label = prefix.unwrap_or("input");
385 let mut archive = ZipArchive::new(Cursor::new(bytes)).map_err(|error| CliError::Zip {
386 path: PathBuf::from(archive_label),
387 message: error.to_string(),
388 })?;
389 for index in 0..archive.len() {
390 let mut entry = archive.by_index(index).map_err(|error| CliError::Zip {
391 path: PathBuf::from(archive_label),
392 message: error.to_string(),
393 })?;
394 if entry.is_dir() || !is_possible_input_entry(entry.name()) || entry.size() < 4 {
395 continue;
396 }
397 let name = entry.name().to_owned();
398 let mut header = [0; 4];
399 entry
400 .read_exact(&mut header)
401 .map_err(|source| CliError::Io {
402 path: PathBuf::from(&name),
403 source,
404 })?;
405 if !is_supported_magic(&header) {
406 continue;
407 }
408 let mut entry_bytes = Vec::with_capacity(entry.size().min(usize::MAX as u64) as usize);
409 entry_bytes.extend_from_slice(&header);
410 entry
411 .read_to_end(&mut entry_bytes)
412 .map_err(|source| CliError::Io {
413 path: PathBuf::from(&name),
414 source,
415 })?;
416 let entry_path = join_internal_path(prefix, &name);
417 drop(entry);
418 self.collect_embedded(entry_bytes, Some(entry_path), depth + 1)?;
419 }
420 Ok(())
421 }
422
423 fn add_dex(&mut self, internal_path: Option<String>, bytes: Vec<u8>) -> Result<(), CliError> {
424 let source = internal_path.as_deref().unwrap_or("input.dex");
425 let file =
426 DexFile::resolve_from_bytes(&bytes).map_err(|error| parse_error(source, error))?;
427 let accessor = Arc::new(DexFileAccessor::new(file, bytes, source.into()));
428 let class_defs = accessor.file.class_defs.clone();
429 for class_def in class_defs {
430 let descriptor = accessor
431 .get_type(class_def.class_idx)
432 .map_err(|error| parse_error(source, error))?;
433 let Some(internal_name) = descriptor_to_internal(&descriptor) else {
434 return Err(CliError::Parse {
435 source: source.to_owned(),
436 message: format!("invalid class descriptor {descriptor}"),
437 });
438 };
439 self.classes.push(ClassEntry {
440 internal_name,
441 descriptor: descriptor.to_string(),
442 internal_path: internal_path.clone(),
443 payload: ClassPayload::Dex {
444 accessor: Arc::clone(&accessor),
445 class_def,
446 },
447 });
448 }
449 Ok(())
450 }
451
452 fn add_class(&mut self, internal_path: Option<String>, bytes: Vec<u8>) -> Result<(), CliError> {
453 let source = internal_path.as_deref().unwrap_or("input.class");
454 let node = ClassNode::from_bytes(&bytes).map_err(|error| parse_error(source, error))?;
455 let internal_name = node.name.to_string();
456 self.classes.push(ClassEntry {
457 descriptor: format!("L{internal_name};"),
458 internal_name,
459 internal_path,
460 payload: ClassPayload::Jvm {
461 node: Arc::new(node),
462 },
463 });
464 Ok(())
465 }
466}
467
468impl ClassEntry {
469 fn qualified_name(&self) -> String {
470 self.internal_name.replace('/', ".")
471 }
472
473 fn members(&self) -> Result<(Vec<MethodInfo>, Vec<FieldInfo>), CliError> {
474 let (mut methods, mut fields) = match &self.payload {
475 ClassPayload::Jvm { node } => (
476 node.methods
477 .iter()
478 .map(|method| MethodInfo {
479 name: method.name.to_string(),
480 signature: method.desc.to_string(),
481 })
482 .collect(),
483 node.fields
484 .iter()
485 .map(|field| FieldInfo {
486 name: field.name.to_string(),
487 field_type: field.desc.to_string(),
488 })
489 .collect(),
490 ),
491 ClassPayload::Dex {
492 accessor,
493 class_def,
494 } => {
495 if class_def.class_data_off == 0 {
496 (Vec::new(), Vec::new())
497 } else {
498 let source = self.internal_path.as_deref().unwrap_or("input.dex");
499 let data = accessor
500 .get_class_element(class_def.class_data_off)
501 .map_err(|error| parse_error(source, error))?;
502 let methods = data
503 .direct_methods
504 .into_iter()
505 .chain(data.virtual_methods)
506 .map(|method| MethodInfo {
507 name: method.name.to_string(),
508 signature: format!(
509 "({}){}",
510 method
511 .parameters
512 .iter()
513 .map(|parameter| parameter.as_ref())
514 .collect::<String>(),
515 method.return_type,
516 ),
517 })
518 .collect();
519 let fields = data
520 .static_fields
521 .into_iter()
522 .chain(data.instance_fields)
523 .map(|field| FieldInfo {
524 name: field.name.to_string(),
525 field_type: field.descriptor.to_string(),
526 })
527 .collect();
528 (methods, fields)
529 }
530 }
531 };
532 methods.sort();
533 fields.sort();
534 Ok((methods, fields))
535 }
536
537 fn to_json(&self) -> Result<Value, CliError> {
538 let (methods, fields) = self.members()?;
539 let mut class = Map::from_iter([
540 (
541 "class_name".to_owned(),
542 Value::String(self.qualified_name()),
543 ),
544 (
545 "descriptor".to_owned(),
546 Value::String(self.descriptor.clone()),
547 ),
548 (
549 "methods".to_owned(),
550 Value::Array(
551 methods
552 .into_iter()
553 .map(|method| {
554 json!({
555 "name": method.name,
556 "signature": method.signature,
557 })
558 })
559 .collect(),
560 ),
561 ),
562 (
563 "fields".to_owned(),
564 Value::Array(
565 fields
566 .into_iter()
567 .map(|field| {
568 json!({
569 "name": field.name,
570 "type": field.field_type,
571 })
572 })
573 .collect(),
574 ),
575 ),
576 ]);
577 insert_internal_path(&mut class, self.internal_path.as_deref());
578 Ok(Value::Object(class))
579 }
580
581 fn render(&self, format: ExportFormat) -> Result<String, CliError> {
582 match format {
583 ExportFormat::Smali => match &self.payload {
584 ClassPayload::Jvm { node } => Ok(render_jvm_class(node)),
585 ClassPayload::Dex {
586 accessor,
587 class_def,
588 } => accessor
589 .get_class_smali(*class_def)
590 .map(|node| node.render(0))
591 .map_err(|error| {
592 parse_error(self.internal_path.as_deref().unwrap_or("input.dex"), error)
593 }),
594 },
595 }
596 }
597}
598
599fn find_matching_classes<'a>(index: &'a InputIndex, query: &str) -> Vec<&'a ClassEntry> {
600 let keys: Vec<StrRef> = index
601 .classes
602 .iter()
603 .map(|entry| entry.descriptor.clone().into())
604 .collect();
605 let mut model = FuzzyMatchModel::new(query.into(), &keys, keys.len());
606 let result = model.full_search();
607
608 result
609 .items
610 .into_iter()
611 .filter_map(|item| index.classes.get(item.index))
612 .collect()
613}
614
615fn read_internal_entry(
616 input: &Path,
617 bytes: Vec<u8>,
618 internal_path: &str,
619) -> Result<Vec<u8>, CliError> {
620 if internal_path.is_empty() {
621 return Err(CliError::Parse {
622 source: input.display().to_string(),
623 message: "internal_path cannot be empty".to_owned(),
624 });
625 }
626 let mut current = bytes;
627 let mut consumed = Vec::new();
628 for segment in internal_path.split('!') {
629 if segment.is_empty() {
630 return Err(CliError::Parse {
631 source: internal_path.to_owned(),
632 message: "internal_path contains an empty segment".to_owned(),
633 });
634 }
635 if !is_zip(¤t) {
636 return Err(CliError::Parse {
637 source: consumed.join("!"),
638 message: format!("cannot descend into non-archive entry {segment}"),
639 });
640 }
641 let mut archive = ZipArchive::new(Cursor::new(current)).map_err(|error| CliError::Zip {
642 path: input.to_owned(),
643 message: error.to_string(),
644 })?;
645 let mut entry = archive.by_name(segment).map_err(|error| CliError::Zip {
646 path: PathBuf::from(internal_path),
647 message: error.to_string(),
648 })?;
649 let mut next = Vec::with_capacity(entry.size().min(usize::MAX as u64) as usize);
650 entry
651 .read_to_end(&mut next)
652 .map_err(|source| CliError::Io {
653 path: PathBuf::from(internal_path),
654 source,
655 })?;
656 consumed.push(segment);
657 current = next;
658 }
659 Ok(current)
660}
661
662fn write_file(path: &Path, bytes: &[u8]) -> Result<(), CliError> {
663 if let Some(parent) = path
664 .parent()
665 .filter(|parent| !parent.as_os_str().is_empty())
666 {
667 fs::create_dir_all(parent).map_err(|source| CliError::Io {
668 path: parent.to_owned(),
669 source,
670 })?;
671 }
672 fs::write(path, bytes).map_err(|source| CliError::Io {
673 path: path.to_owned(),
674 source,
675 })
676}
677
678fn class_output_path(output: &Path, entry: &ClassEntry, format: ExportFormat) -> PathBuf {
679 let mut result = output.to_owned();
680 if matches!(&entry.payload, ClassPayload::Dex { .. }) {
681 if let Some(internal_path) = &entry.internal_path {
682 result.push(safe_component(internal_path));
683 }
684 } else if let Some(internal_path) = &entry.internal_path
685 && let Some((archive_path, _)) = internal_path.rsplit_once('!')
686 {
687 result.push(safe_component(archive_path));
688 }
689 for part in entry.internal_name.split('/') {
690 result.push(safe_component(part));
691 }
692 result.set_extension(format.extension());
693 result
694}
695
696fn insert_internal_path(result: &mut Map<String, Value>, internal_path: Option<&str>) {
697 if let Some(internal_path) = internal_path {
698 result.insert(
699 "internal_path".to_owned(),
700 Value::String(internal_path.to_owned()),
701 );
702 }
703}
704
705fn parse_error(source: &str, error: AsmErr) -> CliError {
706 CliError::Parse {
707 source: source.to_owned(),
708 message: format!("{error:?}"),
709 }
710}
711
712fn input_label(path: &Path, internal_path: Option<&str>) -> String {
713 internal_path.map_or_else(
714 || path.display().to_string(),
715 |internal_path| format!("{}!{internal_path}", path.display()),
716 )
717}
718
719fn join_internal_path(prefix: Option<&str>, entry: &str) -> String {
720 prefix.map_or_else(|| entry.to_owned(), |prefix| format!("{prefix}!{entry}"))
721}
722
723fn descriptor_to_internal(descriptor: &str) -> Option<String> {
724 descriptor
725 .strip_prefix('L')
726 .and_then(|name| name.strip_suffix(';'))
727 .map(ToOwned::to_owned)
728}
729
730fn normalize_class_name(value: &str) -> String {
731 let value = value.trim();
732 let value = value.strip_prefix('L').unwrap_or(value);
733 let value = value.strip_suffix(';').unwrap_or(value);
734 value.replace('.', "/")
735}
736
737fn is_dex(bytes: &[u8]) -> bool {
738 bytes.get(..4) == Some(b"dex\n")
739}
740
741fn is_class(bytes: &[u8]) -> bool {
742 bytes.get(..4) == Some(&[0xCA, 0xFE, 0xBA, 0xBE])
743}
744
745fn is_zip(bytes: &[u8]) -> bool {
746 matches!(
747 bytes.get(..4),
748 Some(b"PK\x03\x04" | b"PK\x05\x06" | b"PK\x07\x08")
749 )
750}
751
752fn is_supported_magic(bytes: &[u8]) -> bool {
753 is_dex(bytes) || is_class(bytes) || is_zip(bytes)
754}
755
756fn is_possible_input_entry(name: &str) -> bool {
757 let Some((_, extension)) = name.rsplit_once('.') else {
758 return true;
759 };
760 ["dex", "class", "apk", "apks", "xapk", "aab", "zip", "jar"]
761 .iter()
762 .any(|candidate| extension.eq_ignore_ascii_case(candidate))
763}
764
765fn safe_component(value: &str) -> String {
766 let result: String = value
767 .chars()
768 .map(|character| {
769 if character.is_ascii_alphanumeric() || matches!(character, '.' | '_' | '-' | '$') {
770 character
771 } else {
772 '_'
773 }
774 })
775 .collect();
776 if result.is_empty() {
777 "input".to_owned()
778 } else {
779 result
780 }
781}
782
783#[cfg(test)]
784mod tests {
785 use super::{
786 Cli, Commands, ExportFormat, InputIndex, class_output_path, normalize_class_name,
787 read_internal_entry,
788 };
789 use clap::Parser;
790 use std::io::{Cursor, Write};
791 use std::path::PathBuf;
792 use zip::ZipWriter;
793 use zip::write::SimpleFileOptions;
794
795 fn zip_file(name: &str, bytes: &[u8]) -> Vec<u8> {
796 let mut writer = ZipWriter::new(Cursor::new(Vec::new()));
797 writer
798 .start_file(name, SimpleFileOptions::default())
799 .unwrap();
800 writer.write_all(bytes).unwrap();
801 writer.finish().unwrap().into_inner()
802 }
803
804 #[test]
805 fn parses_new_command_aliases() {
806 let cli = Cli::try_parse_from([
807 "java_asm_cli",
808 "exportClass",
809 "app.apks",
810 "com.example.Main",
811 "--internal-path",
812 "base.apk!classes2.dex",
813 ])
814 .unwrap();
815 let Commands::ExportClass(args) = cli.command else {
816 panic!("expected export-class command");
817 };
818 assert_eq!(args.input, PathBuf::from("app.apks"));
819 assert_eq!(args.class_name, "com.example.Main");
820 assert_eq!(args.internal_path.as_deref(), Some("base.apk!classes2.dex"));
821 }
822
823 #[test]
824 fn normalizes_java_class_names() {
825 assert_eq!(normalize_class_name("com.example.Main"), "com/example/Main");
826 assert_eq!(
827 normalize_class_name("Lcom/example/Main;"),
828 "com/example/Main"
829 );
830 }
831
832 #[test]
833 fn standalone_class_has_structure_without_internal_path() {
834 let bytes = include_bytes!("../../asm/tests/res/bytecode/CompileTesting.class");
835 let mut index = InputIndex::default();
836 index.collect_embedded(bytes.to_vec(), None, 0).unwrap();
837
838 let class = index.classes[0].to_json().unwrap();
839 assert_eq!(class["class_name"], "CompileTesting");
840 assert!(class.get("internal_path").is_none());
841 assert!(
842 class["methods"]
843 .as_array()
844 .unwrap()
845 .iter()
846 .any(|method| method["name"] == "main"
847 && method["signature"] == "([Ljava/lang/String;)V")
848 );
849 }
850
851 #[test]
852 fn standalone_dex_omits_internal_path() {
853 let dex = include_bytes!("../../asm/tests/res/dex/classes14.dex");
854 let mut index = InputIndex::default();
855 index.collect_embedded(dex.to_vec(), None, 0).unwrap();
856
857 assert!(!index.classes.is_empty());
858 assert!(
859 index
860 .classes
861 .iter()
862 .all(|class| class.internal_path.is_none())
863 );
864 assert!(
865 index.classes[0]
866 .to_json()
867 .unwrap()
868 .get("internal_path")
869 .is_none()
870 );
871 }
872
873 #[test]
874 fn nested_apks_reports_exportable_internal_path() {
875 let dex = include_bytes!("../../asm/tests/res/dex/classes14.dex");
876 let apk = zip_file("classes14.dex", dex);
877 let apks = zip_file("base.apk", &apk);
878 let mut index = InputIndex::default();
879 index.collect_embedded(apks, None, 0).unwrap();
880
881 assert!(!index.classes.is_empty());
882 assert!(
883 index
884 .classes
885 .iter()
886 .all(|class| class.internal_path.as_deref() == Some("base.apk!classes14.dex"))
887 );
888 let output = class_output_path(
889 &PathBuf::from("out"),
890 &index.classes[0],
891 ExportFormat::Smali,
892 );
893 assert!(output.starts_with("out/base.apk_classes14.dex"));
894 assert_eq!(
895 output.extension().and_then(|value| value.to_str()),
896 Some("smali")
897 );
898 }
899
900 #[test]
901 fn internal_path_reads_only_the_requested_nested_dex() {
902 let dex = include_bytes!("../../asm/tests/res/dex/classes14.dex");
903 let apk = zip_file("classes14.dex", dex);
904 let apks = zip_file("base.apk", &apk);
905 let input = PathBuf::from("sample.apks");
906
907 let selected = read_internal_entry(&input, apks, "base.apk!classes14.dex").unwrap();
908 assert_eq!(selected, dex);
909 }
910}