Debian Codegraph @

resources.go

raw symbols SCIP
1 package apkparser
2
3 import (
4 "bytes"
5 "encoding/binary"
6 "errors"
7 "fmt"
8 "io"
9 "io/ioutil"
10 "math"
11 "strings"
12 "unicode/utf16"
13 )
14
15 var ErrUnknownResourceDataType = errors.New("Unknown resource data type")
16
17 // Contains parsed resources.arsc file.
18 type ResourceTable struct {
19 mainStrings stringTable
20 nextPackageId uint32
21 packages map[uint32]*packageGroup
22 }
23
24 type packageGroup struct {
25 Name string
26 Id uint32
27 Packages []*resourcePackage
28
29 table *ResourceTable
30 largestTypeId uint8
31 types map[uint8][]resourceTypeSpec
32 }
33
34 type resourcePackage struct {
35 Id uint32
36 Name string
37
38 typeIdOffset uint32
39 typeStrings stringTable
40 keyStrings stringTable
41 }
42
43 type resourceTypeSpec struct {
44 Id uint8
45 Entries []uint32
46 Package *resourcePackage
47
48 Configs []*resourceType
49 }
50
51 type resourceType struct {
52 chunkData []byte
53 entryCount uint32
54 entriesStart uint32
55 indexesStart uint32
56
57 // ResTable_config config;
58 }
59
60 const (
61 tableEntryComplex = 0x0001
62 tableEntryPublic = 0x0002
63 tableEntryWeak = 0x0004
64 )
65
66 // Describes one resource entry, for example @drawable/icon in the original XML, in one particular config option.
67 type ResourceEntry struct {
68 size uint16
69 flags uint16
70
71 ResourceType string
72 Key string
73 Package string
74
75 value ResourceValue
76 }
77
78 // Handle to the resource's actual value.
79 type ResourceValue struct {
80 dataType AttrType
81 data uint32
82
83 globalStringTable *stringTable
84 convertedData interface{}
85 }
86
87 // Resource config option to pick from options - when @drawable/icon is referenced,
88 // use /res/drawable-xhdpi/icon.png or use /res/drawable-mdpi/icon.png?
89 //
90 // This is not fully implemented, so you can pick only first seen or last seen option.
91 type ResourceConfigOption int
92
93 const (
94 ConfigFirst ResourceConfigOption = iota // Usually the smallest
95 ConfigLast // Usually the biggest
96 ConfigPngIcon // Try to find the biggest png icon, otherwise same as ConfigLast
97 )
98
99 // Parses the resources.arsc file
100 func ParseResourceTable(r io.Reader) (*ResourceTable, error) {
101 res := ResourceTable{
102 nextPackageId: 2,
103 packages: make(map[uint32]*packageGroup),
104 }
105
106 id, hdrLen, totalLen, err := parseChunkHeader(r)
107 if err != nil {
108 return nil, err
109 }
110
111 // Android doesn't care.
112 /*if id != chunkTable {
113 return fmt.Errorf("Invalid top chunk id: 0x%08x", id)
114 }*/
115
116 var packageCurrent, packagesCnt uint32
117 if err = binary.Read(r, binary.LittleEndian, &packagesCnt); err != nil {
118 return nil, err
119 }
120
121 if hdrLen < chunkHeaderSize+4 {
122 return nil, fmt.Errorf("Invalid header length: %d", hdrLen)
123 }
124
125 totalLen -= uint32(hdrLen)
126 hdrLen -= chunkHeaderSize + 4
127
128 if _, err = io.CopyN(ioutil.Discard, r, int64(hdrLen)); err != nil {
129 return nil, fmt.Errorf("Failed to read header padding: %s", err.Error())
130 }
131
132 var len uint32
133 var lastId uint16
134 for i := uint32(0); i < totalLen; i += len {
135 id, hdrLen, len, err = parseChunkHeader(r)
136 if err != nil {
137 return nil, fmt.Errorf("Error parsing header at 0x%08x of 0x%08x %08x: %s", i, totalLen, lastId, err.Error())
138 }
139
140 lastId = id
141
142 lm := &io.LimitedReader{R: r, N: int64(len) - chunkHeaderSize}
143
144 switch id {
145 case chunkStringTable:
146 if res.mainStrings.isEmpty() {
147 res.mainStrings, err = parseStringTable(lm)
148 }
149 case chunkTablePackage:
150 if packageCurrent >= packagesCnt {
151 return nil, fmt.Errorf("Chunk: 0x%08x: Too many package chunks", id)
152 }
153
154 err = res.parsePackage(lm, hdrLen)
155 packageCurrent++
156 default:
157 err = fmt.Errorf("Unknown chunk: 0x%08x at %d.", id, i+chunkHeaderSize+4)
158 //_, err = io.CopyN(ioutil.Discard, lm, lm.N)
159 }
160
161 if err != nil {
162 return nil, fmt.Errorf("Chunk: 0x%08x: %s", id, err.Error())
163 } else if lm.N != 0 {
164 return nil, fmt.Errorf("Chunk: 0x%08x: was not fully read", id)
165 }
166 }
167 return &res, nil
168 }
169
170 func (x *ResourceTable) parsePackage(r *io.LimitedReader, hdrLen uint16) error {
171 pkgBlock, err := ioutil.ReadAll(r)
172 if err != nil {
173 return fmt.Errorf("error reading package block: %s", err.Error())
174 }
175
176 pkgReader := bytes.NewReader(pkgBlock)
177
178 const valsSize = chunkHeaderSize + 4 + 2*128 + 4*5
179 vals := struct {
180 Id uint32
181 Name [128]uint16
182 TypeStrings uint32
183 LastPublicType uint32
184 KeyStrings uint32
185 LastPublicKey uint32
186 TypeIdOffset uint32
187 }{}
188
189 if err := binary.Read(pkgReader, binary.LittleEndian, &vals); err != nil {
190 return fmt.Errorf("error reading values: %s", err.Error())
191 }
192
193 if vals.Id >= 256 {
194 return fmt.Errorf("package id out of range: %d", vals.Id)
195 }
196
197 if vals.Id == 0 {
198 vals.Id = x.nextPackageId
199 x.nextPackageId++
200 }
201
202 pkg := &resourcePackage{
203 Id: vals.Id,
204 }
205
206 // TypeIdOffset was added later and may not be present (frameworks/base@f90f2f8dc36e7243b85e0b6a7fd5a590893c827e)
207 if hdrLen >= valsSize {
208 pkg.typeIdOffset = vals.TypeIdOffset
209 }
210
211 pkg.Name = string(utf16.Decode(vals.Name[:]))
212 if idx := strings.IndexRune(pkg.Name, 0); idx != -1 {
213 pkg.Name = pkg.Name[:idx]
214 }
215
216 if vals.TypeStrings < chunkHeaderSize || vals.KeyStrings <= chunkHeaderSize {
217 return fmt.Errorf("Invalid strings offset: %d %d", vals.TypeStrings, vals.KeyStrings)
218 }
219
220 vals.TypeStrings -= chunkHeaderSize
221 vals.KeyStrings -= chunkHeaderSize
222
223 if _, err := pkgReader.Seek(int64(vals.TypeStrings), io.SeekStart); err != nil {
224 return err
225 }
226
227 if pkg.typeStrings, err = parseStringTableWithChunk(pkgReader); err != nil {
228 return err
229 }
230
231 if _, err := pkgReader.Seek(int64(vals.KeyStrings), io.SeekStart); err != nil {
232 return err
233 }
234
235 if pkg.keyStrings, err = parseStringTableWithChunk(pkgReader); err != nil {
236 return err
237 }
238
239 group, prs := x.packages[pkg.Id]
240 if !prs {
241 group = &packageGroup{
242 Id: pkg.Id,
243 Name: pkg.Name,
244 table: x,
245 types: make(map[uint8][]resourceTypeSpec),
246 }
247 x.packages[pkg.Id] = group
248
249 /*
250 // Find all packages that reference this package
251 size_t N = mpackageGroups.size();
252 for (size_t i = 0; i < N; i++) {
253 mpackageGroups[i]->dynamicRefTable.addMapping(
254 group->name, static_cast<uint8_t>(group->id));
255 }
256 */
257 }
258
259 group.Packages = append(group.Packages, pkg)
260
261 if _, err := pkgReader.Seek(int64(hdrLen-chunkHeaderSize), io.SeekStart); err != nil {
262 return err
263 }
264
265 for {
266 chunkStartOffset, _ := pkgReader.Seek(0, io.SeekCurrent)
267
268 id, hdrLen, totalLen, err := parseChunkHeader(pkgReader)
269 if err == io.EOF {
270 break
271 } else if err != nil {
272 return fmt.Errorf("Error parsing package internal header: %s", err.Error())
273 }
274
275 // Sample: 7e97541191621e72bd794b5b2d60eb2f68669ea8782421e54ec719ccda06c8a4
276 if chunkStartOffset+int64(totalLen) >= int64(len(pkgBlock)) {
277 totalLen = uint32(int64(len(pkgBlock)) - chunkStartOffset)
278 }
279
280 lm := &io.LimitedReader{R: pkgReader, N: int64(totalLen) - chunkHeaderSize}
281
282 switch id {
283 case chunkTableTypeSpec:
284 err = x.parseTypeSpec(lm, pkg, group)
285 case chunkTableType:
286 block := pkgBlock[chunkStartOffset : chunkStartOffset+int64(totalLen)]
287 if err = x.parseType(lm, pkg, group, block, hdrLen); err != nil {
288 break
289 }
290 fallthrough
291 default:
292 _, err = io.CopyN(ioutil.Discard, lm, lm.N)
293 }
294
295 if err != nil {
296 return fmt.Errorf("Chunk: 0x%08x: %s", id, err.Error())
297 } else if lm.N != 0 {
298 return fmt.Errorf("Chunk: 0x%08x: was not fully read", id)
299 }
300 }
301
302 return nil
303 }
304
305 func (x *ResourceTable) parseTypeSpec(r io.Reader, pkg *resourcePackage, group *packageGroup) error {
306 var id uint8
307 if err := binary.Read(r, binary.LittleEndian, &id); err != nil {
308 return fmt.Errorf("Failed to read type spec id: %s", err.Error())
309 }
310
311 if id == 0 {
312 return fmt.Errorf("Invalid type spec id: %d", id)
313 }
314
315 if _, err := io.CopyN(ioutil.Discard, r, 1+2); err != nil {
316 return fmt.Errorf("Failed to skip padding: %s", err.Error())
317 }
318
319 var entryCount uint32
320 if err := binary.Read(r, binary.LittleEndian, &entryCount); err != nil {
321 return fmt.Errorf("Failed to read entryCount: %s", err.Error())
322 }
323
324 if entryCount > 0 {
325 var entries []uint32
326 for i := uint32(0); i < entryCount; i++ {
327 var e uint32
328 if err := binary.Read(r, binary.LittleEndian, &e); err != nil {
329 return fmt.Errorf("Failed to read type spec entry: %s", err.Error())
330 }
331 entries = append(entries, e)
332 }
333
334 group.types[id] = append(group.types[id], resourceTypeSpec{
335 Id: id,
336 Entries: entries,
337 Package: pkg,
338 })
339
340 if id > group.largestTypeId {
341 group.largestTypeId = id
342 }
343 }
344 return nil
345 }
346
347 func (x *ResourceTable) parseType(r io.Reader, pkg *resourcePackage, group *packageGroup, chunkData []byte, hdrLen uint16) error {
348 vals := struct {
349 Id uint8
350 Res0 uint8
351 Res1 uint16
352
353 EntryCount uint32
354 EntriesStart uint32
355
356 //ResTable_config config;
357 }{}
358
359 if err := binary.Read(r, binary.LittleEndian, &vals); err != nil {
360 return fmt.Errorf("error reading values: %s", err.Error())
361 }
362
363 if vals.Id == 0 {
364 return fmt.Errorf("Invalid type id: %d", vals.Id)
365 }
366
367 if vals.EntryCount > 0 {
368 typeList := group.types[vals.Id]
369 if len(typeList) == 0 {
370 return fmt.Errorf("No spec entry for type %d", vals.Id)
371 }
372
373 i := len(typeList) - 1
374 typeList[i].Configs = append(typeList[i].Configs, &resourceType{
375 chunkData: chunkData,
376 entryCount: vals.EntryCount,
377 entriesStart: vals.EntriesStart,
378 indexesStart: uint32(hdrLen),
379 })
380 }
381 return nil
382 }
383
384 // Converts the resource id to readable name including the package name like "@drawable:com.example.app.icon".
385 func (x *ResourceTable) GetResourceName(resId uint32) (string, error) {
386 pkgId := (resId >> 24)
387 typ := ((resId >> 16) & 0xFF) - 1
388 entryId := (resId & 0xFFFF)
389
390 group := x.packages[pkgId]
391 if group == nil {
392 return "", fmt.Errorf("Invalid package identifier.")
393 }
394
395 entry, err := x.getEntry(group, typ, entryId, ConfigFirst)
396 if err != nil {
397 return "", err
398 }
399
400 return fmt.Sprintf("@%s:%s.%s", entry.ResourceType, group.Name, entry.Key), nil
401 }
402
403 // Returns the resource entry for resId and the first configuration option it finds.
404 func (x *ResourceTable) GetResourceEntry(resId uint32) (*ResourceEntry, error) {
405 return x.GetResourceEntryEx(resId, ConfigFirst)
406 }
407
408 // Returns the resource entry for resId and config configuration option.
409 func (x *ResourceTable) GetResourceEntryEx(resId uint32, config ResourceConfigOption) (*ResourceEntry, error) {
410 pkgId := (resId >> 24)
411 typ := ((resId >> 16) & 0xFF) - 1
412 entryId := (resId & 0xFFFF)
413
414 group := x.packages[pkgId]
415 if group == nil {
416 return nil, fmt.Errorf("Invalid package identifier.")
417 }
418
419 return x.getEntry(group, typ, entryId, config)
420 }
421
422 func (x *ResourceTable) getEntry(group *packageGroup, typeId, entry uint32, config ResourceConfigOption) (*ResourceEntry, error) {
423 limit := 1024
424 if config == ConfigFirst {
425 limit = 1
426 }
427
428 entries, err := x.getEntryConfigs(group, typeId, entry, limit)
429 if len(entries) == 0 {
430 return nil, err
431 }
432
433 res := entries[len(entries)-1]
434
435 if config == ConfigPngIcon {
436 for _, e := range entries {
437 if val, _ := e.value.String(); strings.HasSuffix(val, ".png") {
438 res = e
439 }
440 }
441 }
442 return res, err
443 }
444
445 func (x *ResourceTable) getEntryConfigs(group *packageGroup, typeId, entry uint32, limit int) ([]*ResourceEntry, error) {
446 typeList := group.types[uint8(typeId+1)]
447 if len(typeList) == 0 {
448 return nil, fmt.Errorf("Invalid type: %d", typeId)
449 }
450
451 var lastErr error
452 var entries []*ResourceEntry
453 for _, typ := range typeList {
454 for _, thisType := range typ.Configs {
455 if entry >= thisType.entryCount {
456 continue
457 }
458
459 r := bytes.NewReader(thisType.chunkData)
460 if _, err := r.Seek(int64(thisType.indexesStart+entry*4), io.SeekStart); err != nil {
461 return nil, err
462 }
463
464 var thisOffset uint32
465 if err := binary.Read(r, binary.LittleEndian, &thisOffset); err != nil {
466 return nil, fmt.Errorf("Failed to read this type offset: %s", err.Error())
467 }
468
469 if thisOffset == math.MaxUint32 {
470 continue
471 }
472
473 offset := thisType.entriesStart + thisOffset
474
475 if int(offset) >= len(thisType.chunkData) || ((offset & 0x03) != 0) {
476 return nil, fmt.Errorf("Invalid entry 0x%04x offset: %d!", entry, offset)
477 }
478
479 if _, err := r.Seek(int64(offset), io.SeekStart); err != nil {
480 return nil, err
481 }
482
483 res, err := x.parseEntry(r, typ.Package, typeId)
484 if err != nil {
485 lastErr = err
486 } else {
487 entries = append(entries, res)
488 }
489
490 if len(entries) >= limit {
491 goto exit
492 }
493 }
494 }
495
496 if len(entries) == 0 {
497 return nil, fmt.Errorf("No entry found.")
498 }
499 exit:
500 return entries, lastErr
501 }
502
503 func (x *ResourceTable) parseEntry(r io.Reader, pkg *resourcePackage, typeId uint32) (*ResourceEntry, error) {
504 var err error
505 var res ResourceEntry
506 var keyIndex uint32
507
508 if err := binary.Read(r, binary.LittleEndian, &res.size); err != nil {
509 return nil, fmt.Errorf("Failed to read entry size: %s", err.Error())
510 }
511
512 if err := binary.Read(r, binary.LittleEndian, &res.flags); err != nil {
513 return nil, fmt.Errorf("Failed to read entry flags: %s", err.Error())
514 }
515
516 if err := binary.Read(r, binary.LittleEndian, &keyIndex); err != nil {
517 return nil, fmt.Errorf("Failed to read entry key index: %s", err.Error())
518 }
519
520 res.Package = pkg.Name
521
522 res.ResourceType, err = pkg.typeStrings.get(typeId - pkg.typeIdOffset)
523 if err != nil {
524 return nil, fmt.Errorf("Invalid typeString: %s", err.Error())
525 }
526
527 res.Key, err = pkg.keyStrings.get(keyIndex)
528 if err != nil {
529 return nil, fmt.Errorf("Invalid keyString: %s", err.Error())
530 }
531
532 if !res.IsComplex() {
533 var size uint16
534 if err := binary.Read(r, binary.LittleEndian, &size); err != nil {
535 return nil, fmt.Errorf("Failed to read entry value size: %s", err.Error())
536 }
537
538 if size < 8 {
539 return nil, fmt.Errorf("Invalid Res_value size: %d!", size)
540 }
541
542 if _, err := io.CopyN(ioutil.Discard, r, 1); err != nil {
543 return nil, fmt.Errorf("Failed to read entry value res0: %s", err.Error())
544 }
545
546 if err := binary.Read(r, binary.LittleEndian, &res.value.dataType); err != nil {
547 return nil, fmt.Errorf("Failed to read entry value data type: %s", err.Error())
548 }
549
550 if err := binary.Read(r, binary.LittleEndian, &res.value.data); err != nil {
551 return nil, fmt.Errorf("Failed to read entry value data: %s", err.Error())
552 }
553
554 res.value.globalStringTable = &x.mainStrings
555
556 } else {
557 // NYI
558 }
559
560 return &res, nil
561 }
562
563 // Returns true if the resource entry is complex (for example arrays, string plural arrays...).
564 //
565 // Complex ResourceEntries are not yet supported.
566 func (e *ResourceEntry) IsComplex() bool {
567 return (e.flags & tableEntryComplex) != 0
568 }
569
570 // Returns the resource value handle
571 func (e *ResourceEntry) GetValue() *ResourceValue {
572 return &e.value
573 }
574
575 // Returns the resource data type
576 func (v *ResourceValue) Type() AttrType {
577 return v.dataType
578 }
579
580 // Returns the raw data of the resource
581 func (v *ResourceValue) RawData() uint32 {
582 return v.data
583 }
584
585 // Returns the data converted to their native type (e.g. AttrTypeString to string).
586 //
587 // Returns ErrUnknownResourceDataType if the type is not handled by this library
588 func (v *ResourceValue) Data() (interface{}, error) {
589 if v.convertedData != nil {
590 return v.convertedData, nil
591 }
592
593 var val interface{}
594 var err error
595
596 switch v.dataType {
597 case AttrTypeNull:
598 case AttrTypeString:
599 val, err = v.globalStringTable.get(v.data)
600 if err != nil {
601 return nil, err
602 }
603 case AttrTypeIntDec, AttrTypeIntHex, AttrTypeIntBool,
604 AttrTypeIntColorArgb8, AttrTypeIntColorRgb8,
605 AttrTypeIntColorArgb4, AttrTypeIntColorRgb4,
606 AttrTypeReference:
607 val = v.data
608 default:
609 return nil, ErrUnknownResourceDataType
610 }
611
612 v.convertedData = val
613 return val, nil
614 }
615
616 // Returns the data converted to a readable string, to the format it was likely in the original AndroidManifest.xml.
617 //
618 // Unknown data types are returned as the string from ErrUnknownResourceDataType.Error().
619 func (v *ResourceValue) String() (res string, err error) {
620 switch v.dataType {
621 case AttrTypeNull:
622 res = "null"
623 case AttrTypeIntHex:
624 res = fmt.Sprintf("0x%x", v.data)
625 case AttrTypeIntBool:
626 if v.data != 0 {
627 res = "true"
628 } else {
629 res = "false"
630 }
631 case AttrTypeIntColorArgb8:
632 res = fmt.Sprintf("#%08x", v.data)
633 case AttrTypeIntColorRgb8:
634 res = fmt.Sprintf("#%06x", v.data)
635 case AttrTypeIntColorArgb4:
636 res = fmt.Sprintf("#%04x", v.data)
637 case AttrTypeIntColorRgb4:
638 res = fmt.Sprintf("#%03x", v.data)
639 case AttrTypeReference:
640 res = fmt.Sprintf("@%x", v.data)
641 default:
642 var val interface{}
643 val, err = v.Data()
644 if err == nil {
645 res = fmt.Sprintf("%v", val)
646 }
647 }
648 return
649 }