Repository navigation
Expand file tree
/
Copy pathapktool
More file actions
executable file
·409 lines (368 loc) · 12.3 KB
/
Copy pathapktool
File metadata and controls
executable file
·409 lines (368 loc) · 12.3 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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
#!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
import os
import sys
import glob
# import zipfile
from atool import zipfile
# fix sys path to include our lib
DIR_PATH = os.path.abspath(os.path.dirname(os.path.realpath(__file__)))
sys.path.insert(0, DIR_PATH)
from atool.apk import sysresource
from atool.apk.axml import AXMLParser
from atool.apk.axml import ResourceParser
from atool.apk.axml import ResObject
TOOL_NAME = 'apktool'
COMMANDS = ['dumpapk', 'dumpxml', 'cat', 'resolve', 'catr']
usage = '''usage: apktool <command> [args]
Type 'apktool <command> -h' for help of specific command.
Available commands:
dumpxml dump android binary xml
dumpapk dump all xml files in given apk file to current directory
cat dump specified xml from given apk file
catr dump R.java
resolve resolve resource name of given numeric id
'''
def get_cmd_path(cmd):
'''Get absolute path of given command with PATH environment'''
if cmd == "":
return None
path = os.environ.get("PATH")
if path == None:
path = os.environ.get("path")
if path == None:
return None
for p in path.split(':'):
f = p + "/" + cmd
if os.access(f, os.X_OK):
return f
return None
def cmp_version(v1, v2):
if v1 == v2:
return 0
a1 = v1.split(".")
a2 = v2.split(".")
while a1 or a2:
if not a1:
return -1
if not a2:
return 1
c1 = a1.pop(0)
c2 = a2.pop(0)
if c1.isdigit() and c2.isdigit():
return cmp(int(c1), int(c2))
else:
return cmp(c1, c2)
def get_android_jar(sdk_dir):
'''Get android system resource file (android.jar)'''
if not (os.path.isdir(sdk_dir + "/platforms")
and os.path.isfile(sdk_dir + "/tools/android")):
return None
prefix = sdk_dir + "/platforms/android-"
i = len(prefix)
platforms = glob.glob(prefix + "*")
if not platforms:
return None
vs = [item[i:] for item in platforms]
vs.sort(cmp=cmp_version)
jar = prefix + vs[-1] + "/android.jar"
if os.path.isfile(jar):
return jar
else:
return None
def get_android_resource():
android = get_cmd_path("android")
if android:
android = os.path.realpath(android)
jar = None
if android:
sdk_dir = os.path.dirname(os.path.dirname(android))
jar = get_android_jar(sdk_dir)
if jar == None:
sdk_dir = os.environ.get("ANDROID_HOME")
if sdk_dir:
jar = get_android_jar(sdk_dir)
return jar
def dump_xml(cmd, argv):
usage = 'usage: %s %s <binary-xml> [<resources.arsc-or-.apk>]' % (TOOL_NAME, cmd)
detail = '''
Dump given xml file to stdout.
If resources file (typically resources.arsc extracted from the
same apk file) not specified, most xml attributes will be dumped
as numeric value.
System resources will be auto loaded (android sdk directory is
resolved by path of command 'android', then try environment
variable 'ANDROID_HOME'). If system resources can not be found,
most xml attributes will be dumped as numeric value.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print usage
print detail
sys.exit(0)
if len(argv) < 1 or len(argv) > 2:
print >> sys.stderr, usage
sys.exit(1)
restable = ResObject()
androidjar = get_android_resource()
if androidjar:
res = get_archived_resource(androidjar)
if res:
restable.update(res)
if len(argv) > 1:
try:
infile = open(argv[1], "rb")
indata = infile.read()
infile.close()
if len(indata) > 4 and indata[0:4] == '\x50\x4b\x03\x04':
res = get_archived_resource(argv[1])
if res:
restable.update(res)
else:
parser = ResourceParser(indata)
res = parser.parse_resources()
if res:
restable.update(res)
except Exception as e:
print >> sys.stderr, "failed to process resource: ", e
infile = open(argv[0], "rb")
indata = infile.read()
infile.close()
parser = AXMLParser(indata)
parser.set_restable(restable)
(xml, ns) = parser.parsexml()
xml.dump(sys.stdout, ns)
def get_archived_resource(archive):
zfile = None
try:
try:
zfile = zipfile.ZipFile(archive, "r")
except Exception as e1:
print >> sys.stderr, "failed to open zip archive:", archive, e1
return None
data = zfile.read("resources.arsc")
zfile.close()
zfile = None
parser = ResourceParser(data)
return parser.parse_resources()
except Exception as e:
if zfile:
zfile.close()
print >> sys.stderr, "failed to process resources.arsc:", e
return None
def make_res_id(pkgid, typeid, entryid):
return ((0xff000000 & (pkgid << 24)) |
(0x00ff0000 & ((typeid) << 16)) |
(0x0000ffff & (entryid)) )
def dump_r(pkg, outfile=sys.stdout):
print >> outfile, "package %s\n" % (pkg.name)
print >> outfile, "public final class R {"
for tname in sorted(pkg.name_map.keys()):
t = pkg.name_map[tname]
print >> outfile, " public static final class %s {" % (t.name)
for k in sorted(t.id_map.keys()):
e = t.id_map[k]
eid = make_res_id(pkg.id, t.id, e.id)
print >> outfile, " public static final int %s = 0x%08x; // %d" % (e.name, eid, eid)
print >> outfile, " }\n"
print >> outfile, "}"
def cat_r(cmd, argv):
usage = 'usage: %s %s <resources.arsc-or-.apk>' % (TOOL_NAME, cmd)
detail = '''
Dump R.java to stdout.
resources file or apk file must specified.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print usage
print detail
sys.exit(0)
if len(argv) != 1:
print >> sys.stderr, usage
sys.exit(1)
res = None
try:
infile = open(argv[0], "rb")
indata = infile.read()
infile.close()
if len(indata) > 4 and indata[0:4] == '\x50\x4b\x03\x04':
res = get_archived_resource(argv[1])
else:
parser = ResourceParser(indata)
res = parser.parse_resources()
if res == None or len(res.id_map) < 1:
print >> std.err, "no package in restable"
return
if len(res.id_map) != 1:
print >> std.err, "multiple package in restable"
return
ids = res.id_map.keys()
pkg = res.id_map[ids[0]]
dump_r(pkg)
except Exception as e:
print >> sys.stderr, "failed to process resource: ", e
def dump_apk(cmd, argv):
usage = 'usage: %s %s <file.apk>' % (TOOL_NAME, cmd)
detail = '''
Dump all xml files in given apk file into current directory.
System resources will be auto loaded (android sdk directory is
resolved by path of command 'android', then try environment
variable 'ANDROID_HOME'). If system resources can not be found,
most xml attributes will be dumped as numeric value.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print usage
print detail
sys.exit(0)
if len(argv) != 1:
print >> sys.stderr, usage
sys.exit(1)
apkfile = argv[0]
restable = ResObject()
androidjar = get_android_resource()
if androidjar:
# print >> sys.stderr, androidjar
res = get_archived_resource(androidjar)
if res:
restable.update(res)
infile = open(apkfile, "rb")
indata = infile.read(4)
infile.close()
if len(indata) < 4 or indata[0:4] != "\x50\x4b\x03\x04":
print >> sys.stderr, "not a apk file: %s" % (apkfile)
sys.exit(1)
res = get_archived_resource(apkfile)
if res:
restable.update(res)
zfile = zipfile.ZipFile(apkfile, "r")
zfile.getinfo("resources.arsc")
flist = zfile.namelist()
for fname in flist:
if not fname.endswith(".xml"):
continue
if not (fname == 'AndroidManifest.xml' or fname.startswith("res/")):
continue
data = zfile.read(fname)
fname = fname.lstrip("/")
print "processing", fname
try:
parser = AXMLParser(data)
parser.set_restable(restable)
(xml, ns) = parser.parsexml()
dirname = os.path.dirname(fname)
if dirname and not os.path.exists(dirname):
os.makedirs(dirname, 0755)
outfile = open(fname, "wb")
xml.dump(outfile, ns)
outfile.close()
except Exception as e:
print >> sys.stderr, " Error:", e
zfile.close()
def cat_xml(cmd, argv):
usage = 'usage: %s %s <file.apk> <name.xml>' % (TOOL_NAME, cmd)
detail = '''
Dump specified xml file from given apk file.
System resources will be auto loaded (android sdk directory is
resolved by path of command 'android', then try environment
variable 'ANDROID_HOME'). If system resources can not be found,
most xml attributes will be dumped as numeric value.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print usage
print detail
sys.exit(0)
if len(argv) != 2:
print >> sys.stderr, usage
sys.exit(1)
apkfile = argv[0]
zfile = zipfile.ZipFile(apkfile, "r")
xmlfile = argv[1]
data = zfile.read(xmlfile)
zfile.close()
if not data:
sys.exit(0)
restable = ResObject()
androidjar = get_android_resource()
if androidjar:
res = get_archived_resource(androidjar)
if res:
restable.update(res)
res = get_archived_resource(apkfile)
if res:
restable.update(res)
parser = AXMLParser(data)
parser.set_restable(restable)
(xml, ns) = parser.parsexml()
xml.dump(sys.stdout, ns)
def resolve_name(cmd, argv):
usage = 'usage: %s %s <numeric_id> [<apk_or_arsc>]' % (TOOL_NAME, cmd)
detail = '''
Resolve resource name of given id.
System resources will be auto loaded, optional apk file or resource file
will also be searched.
'''
if len(argv) > 0 and argv[0] in ['-h', '--help']:
print usage
print detail
sys.exit(0)
if len(argv) < 1 or len(argv) > 2:
print >> sys.stderr, usage
sys.exit(1)
idstr = argv[0]
radix = 10
if idstr.startswith("0x") or idstr.startswith("0X"):
radix = 16
rid = 0
try:
rid = int(idstr, radix)
except:
print >> sys.stderr, "invalid id, not a number: ", idstr
sys.exit(1)
if rid <= 0 or rid >= 0xffffffff:
print >> sys.stderr, "invalid id: ", idstr
sys.exit(1)
restable = ResObject()
androidjar = get_android_resource()
if androidjar:
res = get_archived_resource(androidjar)
if res:
restable.update(res)
if len(argv) > 1:
try:
infile = open(argv[1], "rb")
indata = infile.read()
infile.close()
if len(indata) > 4 and indata[0:4] == "\x50\x4b\x03\x04":
m = get_archived_resource(argv[1])
else:
parser = ResourceParser(indata)
m = parser.parse_resources()
restable.update(m)
except Exception as e:
print >> sys.stderr, "failed to process resource: ", e
parser = ResourceParser("")
parser.set_restable(restable)
result = parser.dereference_resource(rid)
if result == None:
print >> sys.stderr, "can not resolve given id: 0x%08x" % (rid)
sys.exit(1)
print "0x%08x %s %s %s" % (rid, result[0], result[1], result[2])
if __name__ == '__main__':
if len(sys.argv) < 2:
print >> sys.stderr, "no command specified, type 'apktool help' for usage."
sys.exit(1)
command = sys.argv[1]
argv = sys.argv[2:]
if command in ['-h', '-help', '--help', 'help']:
print usage,
sys.exit(0)
if command not in COMMANDS:
print >> sys.stderr, "apktool: unknown command '%s'. See 'apktool help'." % (command)
elif command == 'dumpxml':
dump_xml(command, argv)
elif command == 'dumpapk':
dump_apk(command, argv)
elif command == 'resolve':
resolve_name(command, argv)
elif command == 'cat':
cat_xml(command, argv)
elif command == 'catr':
cat_r(command, argv)