1pub mod cfg;
9pub mod classdec;
10
11pub use classdec::ClassOptions;
12pub mod ctx;
13pub mod lift;
14pub mod method;
15pub mod passes;
16pub mod platform;
17
18use jdc_core::FxHashMap as HashMap;
19
20use ddc_dex::annotations::{self, EncodedValue};
21
22#[derive(Debug, Clone)]
24pub enum StaticValue {
25 Int(i64),
26 Float(f32),
27 Double(f64),
28 Str(String),
29 Type(String),
30 Boolean(bool),
31 Null,
32 Field(String, String),
34 Other,
35}
36use ddc_dex::{ClassDef, DexFile};
37use jdc_core::types::{
38 parse_field_descriptor, parse_method_descriptor, JavaType, MethodDescriptor,
39};
40
41pub mod access {
45 pub const ACC_PUBLIC: u32 = 0x1;
46 pub const ACC_PRIVATE: u32 = 0x2;
47 pub const ACC_PROTECTED: u32 = 0x4;
48 pub const ACC_STATIC: u32 = 0x8;
49 pub const ACC_FINAL: u32 = 0x10;
50 pub const ACC_SYNCHRONIZED: u32 = 0x20;
51 pub const ACC_BRIDGE: u32 = 0x40;
52 pub const ACC_VARARGS: u32 = 0x80;
53 pub const ACC_NATIVE: u32 = 0x100;
54 pub const ACC_INTERFACE: u32 = 0x200;
55 pub const ACC_ABSTRACT: u32 = 0x400;
56 pub const ACC_STRICT: u32 = 0x800;
57 pub const ACC_SYNTHETIC: u32 = 0x1000;
58 pub const ACC_ANNOTATION: u32 = 0x2000;
59 pub const ACC_ENUM: u32 = 0x4000;
60 pub const ACC_CONSTRUCTOR: u32 = 0x1_0000;
61 pub const ACC_DECLARED_SYNCHRONIZED: u32 = 0x2_0000;
62}
63
64#[derive(Debug, Clone)]
66pub struct PoolField {
67 pub name: String,
68 pub desc: String,
70 pub access: u32,
71 pub is_static: bool,
72}
73
74#[derive(Debug, Clone)]
76pub struct PoolMethod {
77 pub name: std::sync::Arc<str>,
79 pub desc: std::sync::Arc<str>,
83 pub access: u32,
84 pub code_off: u32,
85 pub debug_info_off: u32,
86 pub dex_idx: usize,
88}
89
90impl PoolMethod {
91 pub fn parsed_desc(&self) -> Option<MethodDescriptor> {
92 parse_method_descriptor(&self.desc)
93 }
94 pub fn is_static(&self) -> bool {
95 self.access & access::ACC_STATIC != 0
96 }
97 pub fn is_abstract_or_native(&self) -> bool {
98 self.access & (access::ACC_ABSTRACT | access::ACC_NATIVE) != 0
99 }
100}
101
102enum ClassEntry {
105 Eager(PoolClass),
106 Lazy {
107 at: (usize, usize),
108 pc: std::sync::OnceLock<PoolClass>,
109 },
110}
111
112#[derive(Debug, Clone)]
115pub struct PoolClass {
116 pub name: String,
117 pub access: u32,
118 pub super_name: Option<String>,
120 pub interfaces: Vec<String>,
121 pub source_file: Option<String>,
122 pub static_fields: Vec<PoolField>,
123 pub instance_fields: Vec<PoolField>,
124 pub direct_methods: Vec<PoolMethod>,
125 pub virtual_methods: Vec<PoolMethod>,
126 pub static_values: Vec<StaticValue>,
128 pub nesting: ResolvedNesting,
130 pub dex_idx: usize,
132}
133
134#[derive(Debug, Clone, Default)]
136pub struct ResolvedNesting {
137 pub enclosing_class: Option<String>,
138 pub enclosing_method: Option<(String, String)>,
140 pub member_classes: Vec<String>,
141}
142
143impl PoolClass {
144 pub fn is_interface(&self) -> bool {
145 self.access & access::ACC_INTERFACE != 0
146 }
147
148 pub fn is_enum(&self) -> bool {
149 self.access & access::ACC_ENUM != 0
150 }
151
152 pub fn is_synthetic(&self) -> bool {
153 self.access & access::ACC_SYNTHETIC != 0
154 }
155
156 pub fn is_static_nested(&self) -> bool {
157 self.access & access::ACC_STATIC != 0
158 }
159
160 pub fn all_methods(&self) -> impl Iterator<Item = &PoolMethod> {
162 self.direct_methods
163 .iter()
164 .chain(self.virtual_methods.iter())
165 }
166
167 pub fn find_method(&self, name: &str, desc: &str) -> Option<&PoolMethod> {
169 self.all_methods()
170 .find(|m| &*m.name == name && &*m.desc == desc)
171 }
172
173 pub fn ctors_by_arity(&self, arity: usize) -> Vec<&PoolMethod> {
175 self.all_methods()
176 .filter(|m| &*m.name == "<init>")
177 .filter(|m| {
178 m.parsed_desc()
179 .map(|d| d.args.len() == arity)
180 .unwrap_or(false)
181 })
182 .collect()
183 }
184
185 pub fn field_flags_of(&self, name: &str) -> Option<u32> {
186 self.static_fields
187 .iter()
188 .chain(self.instance_fields.iter())
189 .find(|f| f.name == name)
190 .map(|f| f.access)
191 }
192}
193
194pub struct DexPool {
196 dexes: Vec<std::sync::Arc<DexFile>>,
202 pub dex_labels: Vec<String>,
205 classes: HashMap<String, ClassEntry>,
210 pub order: Vec<String>,
212 retire_counts: std::sync::Mutex<Vec<u64>>,
214 retire_armed: std::sync::atomic::AtomicBool,
215 outers: std::sync::OnceLock<HashMap<String, Option<String>>>,
217 children: std::sync::OnceLock<HashMap<String, Vec<String>>>,
219 ref_caches: Vec<DexRefCache>,
221}
222
223pub(crate) struct DexRefCache {
233 proto_descs: Box<[std::sync::OnceLock<std::sync::Arc<jdc_core::types::MethodDescriptor>>]>,
234 type_names: Box<[std::sync::OnceLock<std::sync::Arc<str>>]>,
235 type_javas: Box<[std::sync::OnceLock<std::sync::Arc<jdc_core::types::JavaType>>]>,
236}
237
238impl DexRefCache {
239 fn new(protos: usize, types: usize) -> Self {
240 DexRefCache {
241 proto_descs: (0..protos).map(|_| std::sync::OnceLock::new()).collect(),
242 type_names: (0..types).map(|_| std::sync::OnceLock::new()).collect(),
243 type_javas: (0..types).map(|_| std::sync::OnceLock::new()).collect(),
244 }
245 }
246}
247
248impl DexPool {
249 pub fn new() -> Self {
250 DexPool {
251 dexes: Vec::new(),
252 retire_armed: std::sync::atomic::AtomicBool::new(false),
253 dex_labels: Vec::new(),
254 classes: HashMap::default(),
255 order: Vec::new(),
256 retire_counts: std::sync::Mutex::new(Vec::new()),
257 outers: std::sync::OnceLock::new(),
258 children: std::sync::OnceLock::new(),
259 ref_caches: Vec::new(),
260 }
261 }
262
263 pub fn proto_desc_parsed(
265 &self,
266 di: usize,
267 proto_idx: u32,
268 ) -> std::sync::Arc<jdc_core::types::MethodDescriptor> {
269 let Some(dex) = self.dexes.get(di) else {
270 return std::sync::Arc::new(jdc_core::types::MethodDescriptor {
271 args: Vec::new(),
272 ret: jdc_core::types::JavaType::Void,
273 });
274 };
275 let build = || {
276 std::sync::Arc::new(parse_proto_desc(dex, proto_idx))
277 };
278 match self
279 .ref_caches
280 .get(di)
281 .and_then(|c| c.proto_descs.get(proto_idx as usize))
282 {
283 Some(slot) => slot.get_or_init(build).clone(),
284 None => build(),
285 }
286 }
287
288 pub fn type_name_arc(&self, di: usize, type_idx: u32) -> std::sync::Arc<str> {
290 let Some(dex) = self.dexes.get(di) else {
291 return std::sync::Arc::from("");
292 };
293 let build = || std::sync::Arc::from(dex.class_name(type_idx).as_str());
294 match self
295 .ref_caches
296 .get(di)
297 .and_then(|c| c.type_names.get(type_idx as usize))
298 {
299 Some(slot) => slot.get_or_init(build).clone(),
300 None => build(),
301 }
302 }
303
304 pub fn type_java(&self, di: usize, type_idx: u32) -> std::sync::Arc<jdc_core::types::JavaType> {
306 let Some(dex) = self.dexes.get(di) else {
307 return std::sync::Arc::new(jdc_core::types::JavaType::Object(
308 std::sync::Arc::from("java/lang/Object"),
309 ));
310 };
311 let build = || std::sync::Arc::new(desc_type(dex.type_name(type_idx)));
312 match self
313 .ref_caches
314 .get(di)
315 .and_then(|c| c.type_javas.get(type_idx as usize))
316 {
317 Some(slot) => slot.get_or_init(build).clone(),
318 None => build(),
319 }
320 }
321
322 fn outer_map(&self) -> &HashMap<String, Option<String>> {
324 self.outers.get_or_init(|| {
325 self.order
326 .iter()
327 .map(|n| (n.clone(), find_outer_name(self, n)))
328 .collect()
329 })
330 }
331
332 pub fn outer_of(&self, name: &str) -> Option<&str> {
334 self.outer_map().get(name).and_then(|o| o.as_deref())
335 }
336
337 pub fn children_of(&self, internal: &str) -> &[String] {
341 if self.children.get().is_none() {
342 let mut idx: HashMap<String, Vec<String>> = HashMap::default();
350 for name in &self.order {
351 if let Some(outer) = self.outer_of(name).map(str::to_string) {
352 idx.entry(outer).or_default().push(name.clone());
353 }
354 }
355 let _ = self.children.set(idx);
358 }
359 self.children
360 .get()
361 .and_then(|m| m.get(internal))
362 .map(|v| v.as_slice())
363 .unwrap_or(&[])
364 }
365
366 pub fn add_dex(&mut self, dex: DexFile) -> usize {
370 let dex_idx = self.dexes.len();
371 self.classes.reserve(dex.class_defs.len());
374 for cd in &dex.class_defs {
377 let name = dex.class_name(cd.class_idx);
378 if self.classes.contains_key(&name) {
379 continue;
380 }
381 let pc = pool_class_of(&dex, dex.raw(), cd, dex_idx);
382 self.classes.insert(name.clone(), ClassEntry::Eager(pc));
383 self.order.push(name);
384 }
385 self.ref_caches
386 .push(DexRefCache::new(dex.proto_count(), dex.type_count()));
387 self.dexes.push(std::sync::Arc::new(dex));
388 self.retire_counts.lock().unwrap().push(0);
389 self.dex_labels.push(format!("dex {}", dex_idx));
390 dex_idx
391 }
392
393 pub fn add_dex_lazy(&mut self, dex: DexFile) -> usize {
397 let dex_idx = self.dexes.len();
398 self.classes.reserve(dex.class_defs.len());
399 for (ci, cd) in dex.class_defs.iter().enumerate() {
400 let name = dex.class_name(cd.class_idx);
401 if self.classes.contains_key(&name) {
402 continue;
403 }
404 self.classes.insert(
405 name.clone(),
406 ClassEntry::Lazy {
407 at: (dex_idx, ci),
408 pc: std::sync::OnceLock::new(),
409 },
410 );
411 self.order.push(name);
412 }
413 self.ref_caches
414 .push(DexRefCache::new(dex.proto_count(), dex.type_count()));
415 self.dexes.push(std::sync::Arc::new(dex));
416 self.retire_counts.lock().unwrap().push(0);
417 self.dex_labels.push(format!("dex {}", dex_idx));
418 dex_idx
419 }
420
421 pub fn set_dex_label(&mut self, idx: usize, label: impl Into<String>) {
423 if let Some(slot) = self.dex_labels.get_mut(idx) {
424 *slot = label.into();
425 }
426 }
427
428 pub fn len(&self) -> usize {
429 self.classes.len()
430 }
431
432 pub fn is_empty(&self) -> bool {
433 self.classes.is_empty()
434 }
435
436 pub fn get(&self, internal: &str) -> Option<&PoolClass> {
437 self.get_inner(internal, None)
438 }
439
440 fn get_inner(&self, internal: &str, raws: Option<&[&[u8]]>) -> Option<&PoolClass> {
445 match self.classes.get(internal)? {
446 ClassEntry::Eager(pc) => Some(pc),
447 ClassEntry::Lazy { at, pc } => {
448 if let Some(built) = pc.get() {
449 return Some(built);
450 }
451 let (di, ci) = *at;
452 let dex = self.dexes.get(di)?;
453 let cd = dex.class_defs.get(ci)?;
454 let raw = match raws {
455 Some(r) => r.get(di).copied().unwrap_or(&[]),
456 None => dex.raw(),
457 };
458 let built = pool_class_of(dex, raw, cd, di);
459 Some(pc.get_or_init(move || built))
460 }
461 }
462 }
463
464 pub fn materialize_all(&self, threads: usize) {
470 let keys: Vec<String> = self
471 .classes
472 .iter()
473 .filter(|(_, e)| matches!(e, ClassEntry::Lazy { .. }))
474 .map(|(k, _)| k.clone())
475 .collect();
476 if keys.is_empty() {
477 return;
478 }
479 let raws: Vec<&[u8]> = self.dexes.iter().map(|d| d.raw()).collect();
484 let threads = threads.max(1);
485 let next = std::sync::atomic::AtomicUsize::new(0);
486 std::thread::scope(|scope| {
487 for _ in 0..threads {
488 scope.spawn(|| loop {
489 let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
490 let Some(k) = keys.get(i) else { break };
491 let _ = self.get_inner(k, Some(&raws));
492 });
493 }
494 });
495 }
496
497 fn get_if_materialized(&self, internal: &str) -> Option<&PoolClass> {
499 match self.classes.get(internal)? {
500 ClassEntry::Eager(pc) => Some(pc),
501 ClassEntry::Lazy { pc, .. } => pc.get(),
502 }
503 }
504
505 pub fn has_name(&self, internal: &str) -> bool {
507 self.classes.contains_key(internal)
508 }
509
510 pub fn dex(&self, idx: usize) -> Option<std::sync::Arc<DexFile>> {
513 self.dexes.get(idx).cloned()
514 }
515
516 pub fn dex_count(&self) -> usize {
517 self.dexes.len()
518 }
519
520 pub fn class_names(&self) -> impl Iterator<Item = &str> {
521 self.order.iter().map(|s| s.as_str())
522 }
523
524 pub fn is_subtype(&self, sub: &str, sup: &str) -> bool {
527 if sub == sup {
528 return true;
529 }
530 if let (Some(sub_elem), Some(sup_elem)) = (array_elem(sub), array_elem(sup)) {
532 if sub_elem.starts_with('L')
533 && sup_elem.starts_with('L')
534 && sub_elem.ends_with(';')
535 && sup_elem.ends_with(';')
536 {
537 return self.is_subtype(
538 &sub_elem[1..sub_elem.len() - 1],
539 &sup_elem[1..sup_elem.len() - 1],
540 );
541 }
542 return sub_elem == sup_elem;
543 }
544 let mut cur = self.get(sub);
545 let mut hops = 0;
546 while let Some(c) = cur {
547 hops += 1;
548 if hops > 64 {
549 return false;
550 }
551 for i in &c.interfaces {
552 if i == sup || self.is_subtype(i, sup) {
553 return true;
554 }
555 }
556 match &c.super_name {
557 Some(s) if s == sup => return true,
558 Some(s) if s != "java/lang/Object" => {
559 cur = self.get(s);
560 }
561 _ => return false,
562 }
563 }
564 false
565 }
566}
567
568impl Default for DexPool {
569 fn default() -> Self {
570 Self::new()
571 }
572}
573
574fn array_elem(desc: &str) -> Option<&str> {
575 desc.strip_prefix('[')
576}
577
578fn resolve_static_value(v: &EncodedValue, dex: &DexFile) -> StaticValue {
579 match v {
580 EncodedValue::Byte(x) => StaticValue::Int(*x as i64),
581 EncodedValue::Short(x) => StaticValue::Int(*x as i64),
582 EncodedValue::Char(x) => StaticValue::Int(*x as i64),
583 EncodedValue::Int(x) => StaticValue::Int(*x as i64),
584 EncodedValue::Long(x) => StaticValue::Int(*x),
585 EncodedValue::Float(x) => StaticValue::Float(*x),
586 EncodedValue::Double(x) => StaticValue::Double(*x),
587 EncodedValue::String(i) => StaticValue::Str(dex.string(*i).to_string()),
588 EncodedValue::Type(i) => StaticValue::Type(dex.class_name(*i)),
589 EncodedValue::Boolean(b) => StaticValue::Boolean(*b),
590 EncodedValue::Null => StaticValue::Null,
591 EncodedValue::Enum(i) | EncodedValue::Field(i) => {
592 let f = dex.field(*i);
593 StaticValue::Field(
594 dex.class_name(f.class_idx),
595 dex.string(f.name_idx).to_string(),
596 )
597 }
598 _ => StaticValue::Other,
599 }
600}
601
602fn pool_class_of(dex: &DexFile, raw: &[u8], cd: &ClassDef, dex_idx: usize) -> PoolClass {
603 let name = dex.class_name(cd.class_idx);
604 let super_name = if cd.superclass_idx == ddc_dex::NO_INDEX {
605 None
606 } else {
607 let s = dex.class_name(cd.superclass_idx);
608 if s.is_empty() || s == "java/lang/Object" {
609 None
610 } else {
611 Some(s)
612 }
613 };
614 let interfaces = dex
615 .interfaces_of(cd)
616 .into_iter()
617 .map(|t| dex.class_name(t))
618 .collect();
619 let source_file = if cd.source_file_idx == ddc_dex::NO_INDEX {
620 None
621 } else {
622 Some(dex.string(cd.source_file_idx).to_string())
623 };
624
625 let data = dex.class_data(cd);
626 let mk_field = |ef: &ddc_dex::EncodedField, is_static: bool| {
627 let f = dex.field(ef.field_idx);
628 PoolField {
629 name: dex.string(f.name_idx).to_string(),
630 desc: dex.type_name(f.type_idx).to_string(),
631 access: ef.access_flags,
632 is_static,
633 }
634 };
635 let static_fields: Vec<PoolField> = data
636 .static_fields
637 .iter()
638 .map(|f| mk_field(f, true))
639 .collect();
640 let instance_fields: Vec<PoolField> = data
641 .instance_fields
642 .iter()
643 .map(|f| mk_field(f, false))
644 .collect();
645 let mk_method = |em: &ddc_dex::EncodedMethod| {
646 let m = dex.method(em.method_idx);
647 let (code_off, debug_info_off) = match dex.debug_info_off_at(em.code_off) {
648 Some(d) => (em.code_off, d),
649 None => (0, 0),
650 };
651 PoolMethod {
652 name: dex.string_arc(m.name_idx),
653 desc: dex.proto_desc(m.proto_idx),
654 access: em.access_flags,
655 code_off,
656 debug_info_off,
657 dex_idx,
658 }
659 };
660 let direct_methods: Vec<PoolMethod> = data.direct_methods.iter().map(&mk_method).collect();
661 let virtual_methods: Vec<PoolMethod> = data.virtual_methods.iter().map(&mk_method).collect();
662
663 let static_values: Vec<StaticValue> = dex
664 .static_values(cd.static_values_off)
665 .into_iter()
666 .map(|v| resolve_static_value(&v, dex))
667 .collect();
668 let anns = if cd.annotations_off != 0 {
669 annotations::read_class_annotations(raw, cd.annotations_off)
670 } else {
671 Vec::new()
672 };
673 let raw = annotations::nesting_from(&anns, &|t: u32| dex.type_name(t).to_string());
674 let nesting = ResolvedNesting {
675 enclosing_class: raw.enclosing_class.map(|t| dex.class_name(t)),
676 enclosing_method: raw.enclosing_method.map(|m| {
677 let mid = dex.method(m);
678 (
679 dex.class_name(mid.class_idx),
680 dex.string(mid.name_idx).to_string(),
681 )
682 }),
683 member_classes: raw
684 .member_classes
685 .into_iter()
686 .map(|t| dex.class_name(t))
687 .collect(),
688 };
689
690 PoolClass {
691 name,
692 access: cd.access_flags,
693 super_name,
694 interfaces,
695 source_file,
696 static_fields,
697 instance_fields,
698 direct_methods,
699 virtual_methods,
700 static_values,
701 nesting,
702 dex_idx,
703 }
704}
705
706fn parse_proto_desc(
710 dex: &ddc_dex::DexFile,
711 proto_idx: u32,
712) -> jdc_core::types::MethodDescriptor {
713 let proto = dex.proto(proto_idx);
714 let args = dex
715 .proto_params(proto_idx)
716 .iter()
717 .map(|&t| desc_type(dex.type_name(t)))
718 .collect();
719 jdc_core::types::MethodDescriptor {
720 args,
721 ret: desc_type(dex.type_name(proto.return_type_idx)),
722 }
723}
724
725pub fn desc_type(desc: &str) -> JavaType {
726 parse_field_descriptor(desc).unwrap_or(JavaType::Object("java/lang/Object".into()))
727}
728
729pub fn find_outer_name(pool: &DexPool, internal: &str) -> Option<String> {
732 if let Some(pc) = pool.get_if_materialized(internal) {
737 if let Some(enc) = &pc.nesting.enclosing_class {
738 return Some(enc.clone());
739 }
740 }
741 let mut rest = internal;
742 while let Some(d) = rest.rfind('$') {
743 let cand = &rest[..d];
744 if pool.has_name(cand) {
745 return Some(cand.to_string());
746 }
747 rest = cand;
748 }
749 None
750}
751
752fn clean_member_tail(rest: &str) -> bool {
755 if rest.starts_with('-') {
756 return false;
757 }
758 let tail = rest.rsplit('$').next().unwrap_or(rest);
759 if tail.is_empty() || tail.starts_with(|c: char| c.is_ascii_digit()) {
760 return false;
761 }
762 true
763}
764
765impl DexPool {
768 pub fn arm_retirement(&self) {
771 self.retire_armed
772 .store(true, std::sync::atomic::Ordering::Release);
773 let mut counts = self.retire_counts.lock().unwrap();
774 for c in counts.iter_mut() {
775 *c = 0;
776 }
777 for entry in self.classes.values() {
778 let di = match entry {
779 ClassEntry::Eager(pc) => pc.dex_idx,
780 ClassEntry::Lazy { at, .. } => at.0,
781 };
782 if let Some(c) = counts.get_mut(di) {
783 *c += 1;
784 }
785 }
786 }
787
788 pub fn report_class_done(&self, class_name: &str) -> Option<usize> {
791 if !self.retire_armed.load(std::sync::atomic::Ordering::Acquire) {
792 return None;
793 }
794 let entry = self.classes.get(class_name)?;
795 let di = match entry {
796 ClassEntry::Eager(pc) => pc.dex_idx,
797 ClassEntry::Lazy { at, .. } => at.0,
798 };
799 let mut counts = self.retire_counts.lock().unwrap();
800 match counts.get_mut(di) {
801 Some(c) => {
802 *c = c.saturating_sub(1);
803 if *c == 0 {
804 Some(di)
805 } else {
806 None
807 }
808 }
809 None => None,
810 }
811 }
812
813 pub fn release_images(&self, indexes: &[usize]) {
817 let mut counts = self.retire_counts.lock().unwrap();
818 for &i in indexes {
819 if let Some(dex) = self.dexes.get(i) {
820 dex.mark_released();
824 }
825 if let Some(c) = counts.get_mut(i) {
826 *c = u64::MAX; }
828 }
829 }
830}
831
832pub fn top_level_classes(pool: &DexPool) -> Vec<String> {
833 pool.class_names()
834 .filter(|name| match pool.outer_of(name) {
835 None => true,
836 Some(outer) => {
837 if pool.get(outer).is_none() {
838 return true;
839 }
840 let rest = name
847 .strip_prefix(outer)
848 .and_then(|t| t.strip_prefix('$'))
849 .unwrap_or("");
850 !clean_member_tail(rest)
851 }
852 })
853 .map(|n| n.to_string())
854 .collect()
855}
856
857pub fn case_rename_map(pool: &DexPool) -> HashMap<String, String> {
864 use std::collections::HashMap;
865 let mut groups: HashMap<String, Vec<String>> = HashMap::default();
866 for t in top_level_classes(pool) {
867 groups.entry(t.to_lowercase()).or_default().push(t);
868 }
869 let folds: std::collections::HashSet<String> = groups.keys().cloned().collect();
870 let mut map = HashMap::default();
871 for (_, mut members) in groups {
872 members.sort();
873 for (i, m) in members.iter().enumerate() {
874 if i == 0 {
875 map.insert(m.clone(), m.clone());
876 continue;
877 }
878 let cut = m.rfind('/').map(|x| x + 1).unwrap_or(0);
881 let mut n = i + 1;
882 loop {
883 let cand = format!("{}{}_{}", &m[..cut], &m[cut..], n);
884 let fold = cand.to_lowercase();
885 if !folds.contains(&fold) {
886 map.insert(m.clone(), cand);
887 break;
888 }
889 n += 1;
890 }
891 }
892 }
893 map
894}
895
896fn nested_collision_renames(pool: &DexPool, map: &mut HashMap<String, String>) {
933 let mut names: Vec<&String> = pool.order.iter().collect();
936 names.sort_by_key(|n| n.matches('$').count());
937 let mut assigned: jdc_core::FxHashSet<String> = jdc_core::FxHashSet::default();
938 for name in names {
939 if !name.contains('$') || map.contains_key(name) {
940 continue;
941 }
942 let Some(parent) = find_outer_name(pool, name) else {
943 continue;
944 };
945 let Some(rest) = name
948 .strip_prefix(parent.as_str())
949 .and_then(|t| t.strip_prefix('$'))
950 else {
951 continue;
952 };
953 if !clean_member_tail(rest) {
954 continue;
955 }
956 let mut chain: Vec<String> = Vec::new();
958 let mut cur = parent.clone();
959 loop {
960 let disp = map.get(&cur).cloned().unwrap_or_else(|| cur.clone());
961 let simple = disp.rsplit('/').next().unwrap_or(&disp);
962 chain.push(simple.rsplit('$').next().unwrap_or(simple).to_string());
963 match find_outer_name(pool, &cur) {
964 Some(o) if o != cur => cur = o,
965 _ => break,
966 }
967 }
968 let disp_parent = map
969 .get(&parent)
970 .cloned()
971 .unwrap_or_else(|| parent.clone());
972 let tail = rest.rsplit('$').next().unwrap_or(rest);
973 let orphan = rest.contains('$');
974 let clash = chain.iter().any(|c| c == tail);
975 if !orphan && !clash {
976 continue;
977 }
978 let mut k = 0u32;
979 loop {
980 k += 1;
981 let cand_tail = if k == 1 {
982 tail.to_string()
983 } else {
984 format!("{tail}{k}")
985 };
986 if chain.contains(&cand_tail) {
990 continue;
991 }
992 let cand = format!("{disp_parent}${cand_tail}");
993 if pool.has_name(&cand) || assigned.contains(&cand) {
994 continue;
995 }
996 assigned.insert(cand.clone());
997 map.insert(name.clone(), cand);
998 break;
999 }
1000 }
1001}
1002
1003pub fn install_case_renames(pool: &DexPool) {
1005 let mut map = case_rename_map(pool);
1006 pkg_leaf_shadow_renames(pool, &mut map);
1011 nested_collision_renames(pool, &mut map);
1012 jdc_core::rename::set_class_renames(map);
1013 jdc_core::rename::set_field_renames(member_collision_renames(pool));
1014}
1015
1016fn pkg_leaf_shadow_renames(pool: &DexPool, map: &mut HashMap<String, String>) {
1024 let taken: jdc_core::FxHashSet<String> = pool.order.iter().cloned().collect();
1025 for name in &pool.order {
1026 let Some((pkg, simple)) = name.rsplit_once('/') else {
1027 continue;
1028 };
1029 if simple.is_empty() || pkg.is_empty() {
1030 continue;
1031 }
1032 let leaf = pkg.rsplit('/').next().unwrap_or(pkg);
1033 if simple != leaf {
1036 continue;
1037 }
1038 let prefix = format!("{pkg}/");
1039 let siblings = pool
1040 .order
1041 .iter()
1042 .filter(|n| n.starts_with(&prefix) && **n != *name)
1043 .count();
1044 if siblings == 0 || map.get(name).is_some_and(|v| v != name) {
1045 continue; }
1047 let mut k = 1u32;
1048 loop {
1049 k += 1;
1050 let cand = format!("{pkg}/{simple}{k}");
1051 if !taken.contains(&cand) && !map.values().any(|v| *v == cand) {
1052 map.insert(name.clone(), cand);
1053 break;
1054 }
1055 }
1056 }
1057}
1058
1059fn member_collision_renames(
1072 pool: &DexPool,
1073) -> HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> {
1074 let mut out: HashMap<std::sync::Arc<str>, Vec<jdc_core::rename::FieldRename>> =
1075 HashMap::default();
1076 for name in &pool.order {
1077 let Some(pc) = pool.get_if_materialized(name) else {
1078 continue;
1079 };
1080 let outer_ref_desc = find_outer_name(pool, name)
1081 .filter(|o| o != name)
1082 .map(|o| format!("L{o};"));
1083 let fields: Vec<&PoolField> = pc
1085 .static_fields
1086 .iter()
1087 .chain(pc.instance_fields.iter())
1088 .collect();
1089 let fgroups: HashMap<String, Vec<&PoolField>> = HashMap::default();
1090 let mut fgroups = fgroups;
1091 for f in &fields {
1092 let disp = crate::classdec::java_ident(&f.name).into_owned();
1093 fgroups.entry(disp).or_default().push(f);
1094 }
1095 let f_taken: jdc_core::FxHashSet<String> = fields
1096 .iter()
1097 .map(|f| crate::classdec::java_ident(&f.name).into_owned())
1098 .collect();
1099 let mut f_taken = f_taken;
1100 for group in fgroups.values() {
1101 if group.len() < 2 {
1102 continue;
1103 }
1104 let keeper_pos = group
1105 .iter()
1106 .position(|f| f.access & crate::access::ACC_SYNTHETIC == 0)
1107 .unwrap_or(0);
1108 for (gi, f) in group.iter().enumerate() {
1109 if gi == keeper_pos {
1110 continue;
1111 }
1112 let base = crate::classdec::java_ident(&f.name).into_owned();
1113 let display: String = match &outer_ref_desc {
1114 Some(ord)
1115 if f.access & crate::access::ACC_SYNTHETIC != 0
1116 && !f.is_static
1117 && *ord == f.desc =>
1118 {
1119 let mut k = 0u32;
1120 loop {
1121 let cand = if k == 0 {
1122 "this$0".to_string()
1123 } else {
1124 format!("this$0{k}")
1125 };
1126 if f_taken.insert(cand.clone()) {
1127 break cand;
1128 }
1129 k += 1;
1130 }
1131 }
1132 _ => suffix_unique(&base, &mut f_taken),
1133 };
1134 out.entry(std::sync::Arc::from(name.as_str()))
1135 .or_default()
1136 .push(jdc_core::rename::FieldRename {
1137 name: std::sync::Arc::from(f.name.as_str()),
1138 desc: std::sync::Arc::from(f.desc.as_str()),
1139 display: std::sync::Arc::from(display.as_str()),
1140 });
1141 }
1142 }
1143 let methods: Vec<&PoolMethod> = pc.all_methods().collect();
1145 let mut m_taken: jdc_core::FxHashSet<String> = methods
1146 .iter()
1147 .map(|m| crate::classdec::java_ident(&m.name).into_owned())
1148 .collect();
1149 let mut mgroups: HashMap<(String, String), Vec<&PoolMethod>> = HashMap::default();
1150 for m in &methods {
1151 let d: &str = &m.desc;
1152 let lo = d.find('(').map(|i| i + 1).unwrap_or(0);
1153 let hi = d.find(')').unwrap_or(d.len());
1154 let key = (
1155 crate::classdec::java_ident(&m.name).into_owned(),
1156 d[lo..hi].to_string(),
1157 );
1158 mgroups.entry(key).or_default().push(m);
1159 }
1160 for ((base, _), group) in &mgroups {
1161 if group.len() < 2 {
1162 continue;
1163 }
1164 let covariant = group
1172 .iter()
1173 .any(|m| group.iter().any(|o| o.name == m.name && o.desc != m.desc));
1174 if covariant {
1175 continue;
1176 }
1177 let mut base = base.clone();
1182 let mut seen_orig: jdc_core::FxHashSet<(&str, &str)> =
1183 jdc_core::FxHashSet::default();
1184 for m in group {
1185 if !seen_orig.insert((&m.name, &m.desc)) {
1186 continue; }
1188 let display = suffix_unique(&base, &mut m_taken);
1189 out.entry(std::sync::Arc::from(name.as_str()))
1190 .or_default()
1191 .push(jdc_core::rename::FieldRename {
1192 name: m.name.clone(),
1193 desc: m.desc.clone(),
1194 display: std::sync::Arc::from(display.as_str()),
1195 });
1196 let _ = &mut base;
1199 }
1200 }
1201 }
1202 out
1203}
1204
1205fn suffix_unique(base: &str, taken: &mut jdc_core::FxHashSet<String>) -> String {
1206 let mut k = 1u32;
1207 loop {
1208 k += 1;
1209 let cand = format!("{base}{k}");
1210 if taken.insert(cand.clone()) {
1211 return cand;
1212 }
1213 }
1214}
1215
1216pub fn install_field_renames(pool: &DexPool) {
1219 jdc_core::rename::set_field_renames(member_collision_renames(pool));
1220}
1221pub use jdc_core::rename::apply_class_rename;