|
| 1 | +"""Base class for framework modifier with utility methods.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import re |
| 6 | +import shutil |
| 7 | +from pathlib import Path |
| 8 | +from typing import TYPE_CHECKING |
| 9 | + |
| 10 | +from src.utils.shell import ShellRunner |
| 11 | +from src.core.modifiers.base_modifier import BaseModifier |
| 12 | +from src.core.modifiers.smali_args import SmaliArgs |
| 13 | +from src.utils.smalikit import SmaliKit |
| 14 | + |
| 15 | +if TYPE_CHECKING: |
| 16 | + from src.core.context import PortingContext |
| 17 | + |
| 18 | + |
| 19 | +class FrameworkModifierBase(BaseModifier): |
| 20 | + """Base class for framework-level modifications with utility methods.""" |
| 21 | + |
| 22 | + def __init__(self, context: PortingContext) -> None: |
| 23 | + super().__init__(context, "FrameworkModifier") |
| 24 | + self.shell = ShellRunner() |
| 25 | + self.bin_dir = Path("bin").resolve() |
| 26 | + |
| 27 | + self.apktool_path = self.bin_dir / "apktool" / "apktool" |
| 28 | + self.apkeditor_path = self.bin_dir / "APKEditor.jar" |
| 29 | + self.baksmali_path = self.bin_dir / "baksmali.jar" |
| 30 | + |
| 31 | + self.temp_dir = self.ctx.target_dir.parent / "temp_modifier" |
| 32 | + |
| 33 | + def _run_smalikit(self, **kwargs) -> None: |
| 34 | + """Run SmaliKit with given arguments.""" |
| 35 | + args = SmaliArgs(**kwargs) |
| 36 | + patcher = SmaliKit(args, logger=self.logger) |
| 37 | + target = args.file_path if args.file_path else args.path |
| 38 | + if target: |
| 39 | + patcher.walk_and_patch(target) |
| 40 | + |
| 41 | + def _apkeditor_decode(self, jar_path: Path, out_dir: Path) -> None: |
| 42 | + """Decode JAR/APK using APKEditor.""" |
| 43 | + self.shell.run_java_jar( |
| 44 | + self.apkeditor_path, ["d", "-f", "-i", str(jar_path), "-o", str(out_dir)] |
| 45 | + ) |
| 46 | + |
| 47 | + def _apkeditor_build(self, src_dir: Path, out_jar: Path) -> None: |
| 48 | + """Build JAR/APK using APKEditor.""" |
| 49 | + self.shell.run_java_jar( |
| 50 | + self.apkeditor_path, ["b", "-f", "-i", str(src_dir), "-o", str(out_jar)] |
| 51 | + ) |
| 52 | + |
| 53 | + def _find_file(self, root: Path, name_pattern: str) -> Path | None: |
| 54 | + """Find file by name pattern recursively.""" |
| 55 | + for p in Path(root).rglob(name_pattern): |
| 56 | + if p.is_file(): |
| 57 | + return p |
| 58 | + return None |
| 59 | + |
| 60 | + def _find_file_recursive(self, root: Path, name_pattern: str) -> Path | None: |
| 61 | + """Alias for _find_file for backward compatibility.""" |
| 62 | + return self._find_file(root, name_pattern) |
| 63 | + |
| 64 | + def _replace_text_in_file(self, file_path: Path | None, old: str, new: str) -> None: |
| 65 | + """Replace text in file if it exists.""" |
| 66 | + if not file_path or not file_path.exists(): |
| 67 | + return |
| 68 | + content = file_path.read_text(encoding="utf-8", errors="ignore") |
| 69 | + if old in content: |
| 70 | + new_content = content.replace(old, new) |
| 71 | + file_path.write_text(new_content, encoding="utf-8") |
| 72 | + self.logger.info(f"Patched {file_path.name}: {old[:20]}... -> {new[:20]}...") |
| 73 | + |
| 74 | + def _copy_to_next_classes(self, work_dir: Path, source_dir: Path) -> None: |
| 75 | + """Copy smali classes to next available classes directory.""" |
| 76 | + max_num = 1 |
| 77 | + for d in work_dir.glob("smali/classes*"): |
| 78 | + name = d.name |
| 79 | + if name == "classes": |
| 80 | + num = 1 |
| 81 | + else: |
| 82 | + try: |
| 83 | + num = int(name.replace("classes", "")) |
| 84 | + except ValueError: |
| 85 | + num = 1 |
| 86 | + if num > max_num: |
| 87 | + max_num = num |
| 88 | + |
| 89 | + target = work_dir / "smali" / f"classes{max_num + 1}" |
| 90 | + shutil.copytree(source_dir, target, dirs_exist_ok=True) |
| 91 | + self.logger.info(f"Copied classes to {target.name}") |
| 92 | + |
| 93 | + def _extract_register_from_invoke( |
| 94 | + self, content: str, method_signature: str, invoke_signature: str, arg_index: int = 1 |
| 95 | + ) -> str | None: |
| 96 | + """Extract register name from invoke instruction in method.""" |
| 97 | + method_pattern = re.compile( |
| 98 | + rf"\.method[^\n]*?{re.escape(method_signature)}(.*?)\.end method", re.DOTALL |
| 99 | + ) |
| 100 | + method_match = method_pattern.search(content) |
| 101 | + |
| 102 | + if not method_match: |
| 103 | + self.logger.warning(f"Target method not found: {method_signature}") |
| 104 | + return None |
| 105 | + |
| 106 | + method_body = method_match.group(1) |
| 107 | + |
| 108 | + invoke_pattern = re.compile(rf"invoke-\w+\s+{{(.*?)}}\s*,\s+{re.escape(invoke_signature)}") |
| 109 | + invoke_match = invoke_pattern.search(method_body) |
| 110 | + |
| 111 | + if not invoke_match: |
| 112 | + self.logger.warning(f"Invoke signature not found in method body: {invoke_signature}") |
| 113 | + return None |
| 114 | + |
| 115 | + matched_regs_str = invoke_match.group(1) |
| 116 | + reg_list = [r.strip() for r in matched_regs_str.split(",") if r.strip()] |
| 117 | + |
| 118 | + if arg_index < len(reg_list): |
| 119 | + extracted_reg = reg_list[arg_index] |
| 120 | + self.logger.debug(f"Extracted register {extracted_reg} from {method_signature}") |
| 121 | + return extracted_reg |
| 122 | + else: |
| 123 | + self.logger.warning(f"arg_index {arg_index} out of bounds for registers: {reg_list}") |
| 124 | + return None |
| 125 | + |
| 126 | + def _extract_register_from_local( |
| 127 | + self, content: str, method_signature: str, local_name: str |
| 128 | + ) -> str | None: |
| 129 | + """Extract register name from .local declaration or move-object instructions.""" |
| 130 | + method_pattern = re.compile( |
| 131 | + rf"\.method[^\n]*?{re.escape(method_signature)}(.*?)\.end method", re.DOTALL |
| 132 | + ) |
| 133 | + method_match = method_pattern.search(content) |
| 134 | + if not method_match: |
| 135 | + return None |
| 136 | + |
| 137 | + body = method_match.group(1) |
| 138 | + |
| 139 | + local_pattern = re.compile(rf"\.local\s+([vp]\d+),\s+{re.escape(local_name)}[;:,]") |
| 140 | + match = local_pattern.search(body) |
| 141 | + if match: |
| 142 | + return match.group(1) |
| 143 | + |
| 144 | + if local_name == '"descriptor"': |
| 145 | + move_match = re.search(r"move-object(?:\/from16)?\s+([vp]\d+),\s+p1", body) |
| 146 | + if move_match: |
| 147 | + return move_match.group(1) |
| 148 | + elif local_name == '"args"': |
| 149 | + move_match = re.search(r"move-object(?:\/from16)?\s+([vp]\d+),\s+p3", body) |
| 150 | + if move_match: |
| 151 | + return move_match.group(1) |
| 152 | + |
| 153 | + return None |
0 commit comments