返回资讯中心
外部精选
软件工程
#开发者实时流

Patching APKs: Smali, DEX, Rebuild, and Resigning

A practical, in-depth tutorial for editing Android app code and producing a

Hacker News 最新noppers2026/10/31 · 18 天前30 分钟阅读

以下正文同步自 Hacker News 最新,版权归原站所有,已转换为易读排版。

A practical, in-depth tutorial for editing Android app code and producing a working, installable APK — plus the theory of why the toolchain looks the way it does.

Legal / ethical note. Only patch APKs you own, that you built yourself, or that you have explicit permission to modify. Repackaging someone else's app breaks its signature, its update path, and usually its terms of service, and can be illegal depending on where you live. This document is about learning how Android packaging works, debugging your own builds, instrumenting test builds, and reverse engineering for interoperability.

An APK is a ZIP file. Inside it are resources, a manifest, native libraries, assets — and one or more classes*.dex files containing all the compiled Kotlin/Java code.

Kotlin/Java source │ kotlinc / javac ▼ JVM .class files (stack-based bytecode, one file per class) │ d8 (or R8 for release builds) ▼ classes.dex (register-based Dalvik bytecode, all classes in one file) │ zip + aapt2 (resources) + apksigner ▼ app.apk

Smali is not a compilation target. It is a textual rendering of an existing DEX file, produced by a disassembler (baksmali) and consumed by an assembler (smali). Editing smali is editing the DEX, just in a form you can read.

classes.dex ──baksmali──▶ smali/ (readable text) ▲ │ └────────smali─────────────┘ (edit in between)

apktool wraps exactly this: apktool d = unzip + decode resources + baksmali; apktool b = smali + aapt2 + zip. That is the whole trick.

app.apk (ZIP) ├── AndroidManifest.xml binary XML (AXML), not text ├── resources.arsc compiled resource table (binary) ├── classes.dex code (classes2.dex, classes3.dex … for multidex) ├── res/ compiled resource files (layouts, drawables…) ├── lib/<abi>/lib*.so native libraries ├── assets/ raw files shipped verbatim └── META-INF/ v1 (JAR) signature files — MANIFEST.MF, *.SF, *.RSA

Two consequences that drive everything else:

apktool d keeps the untouched originals in a folder called original/ (notably original/META-INF and original/AndroidManifest.xml). apktool b -c (--copy-original) can reuse them.

DEX ("Dalvik Executable") is the bytecode container that Android Runtime (ART) loads. It is a single flat file holding every class in the app, with all strings, types, prototypes, fields, and methods interned into shared, indexed tables. Cross-class references become 16-bit/32-bit integer indices instead of names, which is what makes it compact.

It is an instruction set architecture, like x86 or ARM — not a programming language. There is no syntax, no expressions, no scoping. There is only a byte stream plus a documented layout.

Note: DEX is not JVM bytecode. .class files are stack-based; DEX is register-based. d8 performs that translation. This is why a .class file and a .dex file for the same class look nothing alike, and why you cannot just rename one to the other.

The first 0x70 bytes are a fixed header, then six index tables, then a data section:

┌───────────────┬──────────────────────────────────────────────┐ │ header │ 0x00 – 0x6F (112 bytes) │ ├───────────────┼──────────────────────────────────────────────┤ │ string_ids │ offsets to MUTF-8 strings │ │ type_ids │ indices into string_ids (type descriptors) │ │ proto_ids │ method signatures (return type + params) │ │ field_ids │ {class, type, name} triples │ │ method_ids │ {class, proto, name} triples │ │ class_defs │ one per class: where its data lives │ ├───────────────┼──────────────────────────────────────────────┤ │ data │ string bytes, type lists, code items, debug │ │ │ info, annotations, static values, map_list │ └───────────────┴──────────────────────────────────────────────┘

Header fields worth memorizing:

The checksum and signature fields are why a hand-edited DEX is rejected until you recompute them. Everything from 0x0C onward is covered by the checksum, and everything from 0x20 onward is covered by the signature — and the checksum field (at 0x08) is itself inside the signed region, so the order matters: signature first, then checksum.

Each method body is a code_item: register count, in/out argument sizes, try blocks, debug info offset, instruction count in 16-bit code units, and the instruction stream. Instructions are 1–5 code units long, variable length, and operate on registers named v0, v1, …:

const/4 v0, 0x1 # 1 code unit (2 bytes) invoke-virtual {v0}, Ljava/lang/Object;->toString()Ljava/lang/String; # 3 code units

Because instruction length depends on the encoded value (const/4 vs const/16 vs const), inserting or growing code changes byte offsets everywhere after it. That is the central difficulty of editing DEX directly, and the reason a textual assembler exists.

classes.dex, classes2.dex, … each have their own 64K budget. apktool decodes them to smali/, smali_classes2/, smali_classes3/, … and reassembles each directory back into the matching DEX name.

Smali is the assembly syntax for DEX. Every DEX instruction has a smali mnemonic with the same name (invoke-virtual, iget-object, const-string), and every reference is written symbolically instead of as an index:

invoke-virtual {v0, v1}, Ljava/lang/StringBuilder;->append(Ljava/lang/String;)Ljava/lang/StringBuilder;

Same instruction, but now you can read the class, the method, the parameter type, and the return type. That is the entire value proposition.

Smali is lossless in the forward direction: baksmali → text → smali gives you a semantically equivalent DEX. It is not guaranteed byte-identical (the string pool and code-item ordering can be rearranged), but the class structure and behaviour are preserved. This round-trip property is why apktool can rebuild real apps at all.

You must be able to read these; they appear everywhere:

.class public final Lcom/example/Checker; .super Ljava/lang/Object; .source "Checker.java"

static field with a constant value

.field private static final TAG:Ljava/lang/String; = "Checker"

instance field

.field private licenseKey:Ljava/lang/String;

.method public constructor <init>()V .registers 1 .line 12 invoke-direct {p0}, Ljava/lang/Object;-><init>()V return-void .end method

.method public isLicensed()Z .registers 2 .line 20 iget-object v0, p0, Lcom/example/Checker;->licenseKey:Ljava/lang/String;

if-nez v0, :cond_0 const/4 v0, 0x0 return v0

:cond_0 const/4 v0, 0x1 return v0 .end method

.method public static log(Ljava/lang/String;)V .registers 2 .param p0, "msg" # Ljava/lang/String; const-string v0, "Checker" invoke-static {v0, p0}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I return-void .end method

Line by line:

if-eqz v0, :cond_next goto :goto_0

:cond_next packed-switch v1, :pswitch_data_0

:pswitch_0

case 0 body

.catch Ljava/lang/Exception; {:try_start_0 .. :try_end_0} :catch_0

:try_start_0 invoke-static {}, Lcom/example/Native;->init()V :try_end_0

goto :goto_1

:catch_0 move-exception v0 invoke-static {v0}, Landroid/util/Log;->getStackTraceString(Ljava/lang/Throwable;)Ljava/lang/String;

:goto_0 return-void

:pswitch_data_0 .packed-switch 0x0 :pswitch_0 .end packed-switch

Notes:

.annotation runtime Ljava/lang/Deprecated; .end annotation

.annotation system Ldalvik/annotation/InnerClass; accessFlags = 0x8 name = "Builder" .end annotation

These appear as .annotation blocks before fields/methods/classes or at the end of the class. @Override, @Nullable, and Kotlin metadata are all annotations here — the Kotlin metadata blob is how decompilers recover Kotlin constructs.

The relationship is exactly like .o/ELF versus .s assembly: one is what the machine runs, one is what humans and patch tools manipulate. DEX is the canonical form; smali is a projection of it.

So: smali is the easiest thing to edit; Java is the easiest thing to read; DEX is the only thing that actually runs. A good workflow uses all three: jadx to understand, smali to change, DEX (via the assembler) to ship.

java -version apktool --version apksigner version zipalign -h | head -3

Version gotchas:

Locate the SDK tools if they are not on PATH:

export ANDROID_HOME="$HOME/Android/Sdk" export PATH="$ANDROID_HOME/build-tools/35.0.0:$ANDROID_HOME/platform-tools:$PATH"

Working directory convention used below:

mkdir -p ~/work/patch && cd ~/work/patch cp ~/Downloads/app.apk .

  1. Workflow A — the standard apktool loop, step by step

This is the normal, safest path. It rebuilds resources and code, and it is what you want 90% of the time.

apktool d app.apk -o decoded ──▶ decoded/ (edit smali in decoded/smali*) │ apktool b ▼ unsigned.apk │ zipalign ▼ aligned.apk │ apksigner ▼ signed.apk │ adb install ▼ device

Step 0 — Keep a pristine copy

cp app.apk app.original.apk sha256sum app.apk app.original.apk

You will compare against this when something breaks. Never debug on your only copy.

apktool d app.apk -o decoded

Useful flags:

decoded/ ├── AndroidManifest.xml now readable XML ├── apktool.yml metadata: versions, DEX names, flags ├── res/ decoded resources ├── smali/ classes.dex ├── smali_classes2/ classes2.dex ├── smali_classes3/ classes3.dex ├── assets/ ├── lib/ └── original/ untouched META-INF + manifest

If decoding fails on an OEM/system APK, install its framework first:

apktool if framework-res.apk

Step 2 — Find the code to patch

Three complementary approaches:

1. Search strings in smali (fast, exact)

grep -rn "isLicensed|license" decoded/smali*/ | head -50

2. Search the decompiled Java for intent (jadx is read-only)

jadx -d jadx-out app.apk grep -rn "isLicensed" jadx-out/ | head

3. Inspect the manifest for entry points and permissions

sed -n '1,80p' decoded/AndroidManifest.xml

Use jadx to understand, smali to locate the exact instructions. jadx-gui is better for browsing; note that when jadx fails to decompile a method it prints the smali instead — that is your bridge.

Open the file and find the method. Typical patterns to look for:

.method public isLicensed()Z .registers 2 iget-object v0, p0, Lcom/example/Checker;->licenseKey:Ljava/lang/String; invoke-virtual {v0}, Ljava/lang/String;->isEmpty()Z move-result v0 xor-int/lit8 v0, v0, 0x1 return v0 .end method

Before editing, note: register count, which registers are inputs, whether there are try/catch blocks, and whether the method returns a value or V. Write down the original (or rely on git — see Step 4).

cd decoded && git init && git add -A && git commit -m "pristine decode" && cd ..

Now every patch is a reviewable diff, and reverting is trivial. This is the single biggest quality-of-life improvement in this workflow.

Minimal, surgical changes win. Common patterns:

.method public isLicensed()Z .registers 2 const/4 v0, 0x1 return v0 .end method

Force false: identical with 0x0.

.method public onCreate(Landroid/os/Bundle;)V .registers 3 invoke-super {p0, p1}, Landroid/app/Activity;->onCreate(Landroid/os/Bundle;)V return-void .end method

Neutralise one instruction — replace with nops, matching the original instruction's code-unit count, or you will corrupt the following bytes when assembling by hand (the assembler handles it, but the semantics of labels and try ranges still matter):

before: invoke-static {}, Lcom/example/Analytics;->ping()V (3 code units)

nop nop nop

Add logging (bump .registers if you need a new register):

.method public isLicensed()Z .registers 2 const-string v0, "PATCH" const-string v1, "isLicensed() called" invoke-static {v0, v1}, Landroid/util/Log;->d(Ljava/lang/String;Ljava/lang/String;)I const/4 v0, 0x1 return v0 .end method

Rules of thumb while editing:

apktool b decoded -o unsigned.apk

Notes:

unzip -l unsigned.apk | grep -E 'classes.*dex|resources.arsc' unzip -p unsigned.apk classes.dex > /tmp/check.dex dexdump -f /tmp/check.

正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。

打开原文
去社区讨论 →