blob: 46a4c3262b66471d359560a22223a4bf871e2b93 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001//
2// Copyright 2006 The Android Open Source Project
3//
4// Build resource files from raw assets.
5//
6
7#include "StringPool.h"
Dianne Hackborn6c997a92012-01-31 11:27:43 -08008#include "ResourceTable.h"
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08009
10#include <utils/ByteOrder.h>
Dianne Hackborn6c997a92012-01-31 11:27:43 -080011#include <utils/SortedVector.h>
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080012
Raphaelf51125d2011-10-27 17:01:31 -070013#if HAVE_PRINTF_ZD
14# define ZD "%zd"
15# define ZD_TYPE ssize_t
16#else
17# define ZD "%ld"
18# define ZD_TYPE long
19#endif
20
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080021#define NOISY(x) //x
22
23void strcpy16_htod(uint16_t* dst, const uint16_t* src)
24{
25 while (*src) {
26 char16_t s = htods(*src);
27 *dst++ = s;
28 src++;
29 }
30 *dst = 0;
31}
32
33void printStringPool(const ResStringPool* pool)
34{
Dianne Hackborn6c997a92012-01-31 11:27:43 -080035 SortedVector<const void*> uniqueStrings;
36 const size_t N = pool->size();
37 for (size_t i=0; i<N; i++) {
38 size_t len;
39 if (pool->isUTF8()) {
40 uniqueStrings.add(pool->string8At(i, &len));
41 } else {
42 uniqueStrings.add(pool->stringAt(i, &len));
43 }
44 }
45
46 printf("String pool of " ZD " unique %s %s strings, " ZD " entries and "
47 ZD " styles using " ZD " bytes:\n",
48 (ZD_TYPE)uniqueStrings.size(), pool->isUTF8() ? "UTF-8" : "UTF-16",
49 pool->isSorted() ? "sorted" : "non-sorted",
50 (ZD_TYPE)N, (ZD_TYPE)pool->styleCount(), (ZD_TYPE)pool->bytes());
51
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052 const size_t NS = pool->size();
53 for (size_t s=0; s<NS; s++) {
Dianne Hackborn6c997a92012-01-31 11:27:43 -080054 String8 str = pool->string8ObjectAt(s);
55 printf("String #" ZD ": %s\n", (ZD_TYPE) s, str.string());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056 }
57}
58
Dianne Hackborn6c997a92012-01-31 11:27:43 -080059String8 StringPool::entry::makeConfigsString() const {
60 String8 configStr(configTypeName);
61 if (configStr.size() > 0) configStr.append(" ");
62 if (configs.size() > 0) {
63 for (size_t j=0; j<configs.size(); j++) {
64 if (j > 0) configStr.append(", ");
65 configStr.append(configs[j].toString());
66 }
67 } else {
68 configStr = "(none)";
69 }
70 return configStr;
71}
72
73int StringPool::entry::compare(const entry& o) const {
74 // Strings with styles go first, to reduce the size of the
75 // styles array.
76 if (hasStyles) {
77 return o.hasStyles ? 0 : -1;
78 }
79 if (o.hasStyles) {
80 return 1;
81 }
82 int comp = configTypeName.compare(o.configTypeName);
83 if (comp != 0) {
84 return comp;
85 }
86 const size_t LHN = configs.size();
87 const size_t RHN = o.configs.size();
88 size_t i=0;
89 while (i < LHN && i < RHN) {
90 comp = configs[i].compareLogical(o.configs[i]);
91 if (comp != 0) {
92 return comp;
93 }
94 i++;
95 }
96 if (LHN < RHN) return -1;
97 else if (LHN > RHN) return 1;
98 return 0;
99}
100
Jeff Brown345b7eb2012-03-16 15:25:17 -0700101StringPool::StringPool(bool utf8) :
102 mUTF8(utf8), mValues(-1)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103{
104}
105
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800106ssize_t StringPool::add(const String16& value, const Vector<entry_style_span>& spans,
107 const String8* configTypeName, const ResTable_config* config)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800108{
Jeff Brown345b7eb2012-03-16 15:25:17 -0700109 ssize_t res = add(value, false, configTypeName, config);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800110 if (res >= 0) {
111 addStyleSpans(res, spans);
112 }
113 return res;
114}
115
Jeff Brown345b7eb2012-03-16 15:25:17 -0700116ssize_t StringPool::add(const String16& value,
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800117 bool mergeDuplicates, const String8* configTypeName, const ResTable_config* config)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119 ssize_t vidx = mValues.indexOfKey(value);
120 ssize_t pos = vidx >= 0 ? mValues.valueAt(vidx) : -1;
121 ssize_t eidx = pos >= 0 ? mEntryArray.itemAt(pos) : -1;
122 if (eidx < 0) {
123 eidx = mEntries.add(entry(value));
124 if (eidx < 0) {
125 fprintf(stderr, "Failure adding string %s\n", String8(value).string());
126 return eidx;
127 }
128 }
129
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800130 if (configTypeName != NULL) {
131 entry& ent = mEntries.editItemAt(eidx);
132 NOISY(printf("*** adding config type name %s, was %s\n",
133 configTypeName->string(), ent.configTypeName.string()));
134 if (ent.configTypeName.size() <= 0) {
135 ent.configTypeName = *configTypeName;
136 } else if (ent.configTypeName != *configTypeName) {
137 ent.configTypeName = " ";
138 }
139 }
140
141 if (config != NULL) {
142 // Add this to the set of configs associated with the string.
143 entry& ent = mEntries.editItemAt(eidx);
144 size_t addPos;
145 for (addPos=0; addPos<ent.configs.size(); addPos++) {
146 int cmp = ent.configs.itemAt(addPos).compareLogical(*config);
147 if (cmp >= 0) {
148 if (cmp > 0) {
149 NOISY(printf("*** inserting config: %s\n", config->toString().string()));
150 ent.configs.insertAt(*config, addPos);
151 }
152 break;
153 }
154 }
155 if (addPos >= ent.configs.size()) {
156 NOISY(printf("*** adding config: %s\n", config->toString().string()));
157 ent.configs.add(*config);
158 }
159 }
160
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 const bool first = vidx < 0;
Ben Gruverdb6e67d2012-03-07 21:19:16 -0800162 const bool styled = (pos >= 0 && (size_t)pos < mEntryStyleArray.size()) ?
163 mEntryStyleArray[pos].spans.size() : 0;
164 if (first || styled || !mergeDuplicates) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165 pos = mEntryArray.add(eidx);
166 if (first) {
167 vidx = mValues.add(value, pos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800168 }
Jeff Brown345b7eb2012-03-16 15:25:17 -0700169 entry& ent = mEntries.editItemAt(eidx);
170 ent.indices.add(pos);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800171 }
172
173 NOISY(printf("Adding string %s to pool: pos=%d eidx=%d vidx=%d\n",
174 String8(value).string(), pos, eidx, vidx));
175
176 return pos;
177}
178
179status_t StringPool::addStyleSpan(size_t idx, const String16& name,
180 uint32_t start, uint32_t end)
181{
182 entry_style_span span;
183 span.name = name;
184 span.span.firstChar = start;
185 span.span.lastChar = end;
186 return addStyleSpan(idx, span);
187}
188
189status_t StringPool::addStyleSpans(size_t idx, const Vector<entry_style_span>& spans)
190{
191 const size_t N=spans.size();
192 for (size_t i=0; i<N; i++) {
193 status_t err = addStyleSpan(idx, spans[i]);
194 if (err != NO_ERROR) {
195 return err;
196 }
197 }
198 return NO_ERROR;
199}
200
201status_t StringPool::addStyleSpan(size_t idx, const entry_style_span& span)
202{
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203 // Place blank entries in the span array up to this index.
204 while (mEntryStyleArray.size() <= idx) {
205 mEntryStyleArray.add();
206 }
207
208 entry_style& style = mEntryStyleArray.editItemAt(idx);
209 style.spans.add(span);
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800210 mEntries.editItemAt(mEntryArray[idx]).hasStyles = true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 return NO_ERROR;
212}
213
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800214int StringPool::config_sort(const size_t* lhs, const size_t* rhs, void* state)
215{
216 StringPool* pool = (StringPool*)state;
217 const entry& lhe = pool->mEntries[pool->mEntryArray[*lhs]];
218 const entry& rhe = pool->mEntries[pool->mEntryArray[*rhs]];
219 return lhe.compare(rhe);
220}
221
222void StringPool::sortByConfig()
223{
Dianne Hackborn6c997a92012-01-31 11:27:43 -0800224 LOG_ALWAYS_FATAL_IF(mOriginalPosToNewPos.size() > 0, "Can't sort string pool after already sorted.");
225
226 const size_t N = mEntryArray.size();
227
228 // This is a vector that starts out with a 1:1 mapping to entries
229 // in the array, which we will sort to come up with the desired order.
230 // At that point it maps from the new position in the array to the
231 // original position the entry appeared.
232 Vector<size_t> newPosToOriginalPos;
233 for (size_t i=0; i<mEntryArray.size(); i++) {
234 newPosToOriginalPos.add(i);
235 }
236
237 // Sort the array.
238 NOISY(printf("SORTING STRINGS BY CONFIGURATION...\n"));
239 newPosToOriginalPos.sort(config_sort, this);
240 NOISY(printf("DONE SORTING STRINGS BY CONFIGURATION.\n"));
241
242 // Create the reverse mapping from the original position in the array
243 // to the new position where it appears in the sorted array. This is
244 // so that clients can re-map any positions they had previously stored.
245 mOriginalPosToNewPos = newPosToOriginalPos;
246 for (size_t i=0; i<N; i++) {
247 mOriginalPosToNewPos.editItemAt(newPosToOriginalPos[i]) = i;
248 }
249
250#if 0
251 SortedVector<entry> entries;
252
253 for (size_t i=0; i<N; i++) {
254 printf("#%d was %d: %s\n", i, newPosToOriginalPos[i],
255 mEntries[mEntryArray[newPosToOriginalPos[i]]].makeConfigsString().string());
256 entries.add(mEntries[mEntryArray[i]]);
257 }
258
259 for (size_t i=0; i<entries.size(); i++) {
260 printf("Sorted config #%d: %s\n", i,
261 entries[i].makeConfigsString().string());
262 }
263#endif
264
265 // Now we rebuild the arrays.
266 Vector<entry> newEntries;
267 Vector<size_t> newEntryArray;
268 Vector<entry_style> newEntryStyleArray;
269 DefaultKeyedVector<size_t, size_t> origOffsetToNewOffset;
270
271 for (size_t i=0; i<N; i++) {
272 // We are filling in new offset 'i'; oldI is where we can find it
273 // in the original data structure.
274 size_t oldI = newPosToOriginalPos[i];
275 // This is the actual entry associated with the old offset.
276 const entry& oldEnt = mEntries[mEntryArray[oldI]];
277 // This is the same entry the last time we added it to the
278 // new entry array, if any.
279 ssize_t newIndexOfOffset = origOffsetToNewOffset.indexOfKey(oldI);
280 size_t newOffset;
281 if (newIndexOfOffset < 0) {
282 // This is the first time we have seen the entry, so add
283 // it.
284 newOffset = newEntries.add(oldEnt);
285 newEntries.editItemAt(newOffset).indices.clear();
286 } else {
287 // We have seen this entry before, use the existing one
288 // instead of adding it again.
289 newOffset = origOffsetToNewOffset.valueAt(newIndexOfOffset);
290 }
291 // Update the indices to include this new position.
292 newEntries.editItemAt(newOffset).indices.add(i);
293 // And add the offset of the entry to the new entry array.
294 newEntryArray.add(newOffset);
295 // Add any old style to the new style array.
296 if (mEntryStyleArray.size() > 0) {
297 if (oldI < mEntryStyleArray.size()) {
298 newEntryStyleArray.add(mEntryStyleArray[oldI]);
299 } else {
300 newEntryStyleArray.add(entry_style());
301 }
302 }
303 }
304
305 // Now trim any entries at the end of the new style array that are
306 // not needed.
307 for (ssize_t i=newEntryStyleArray.size()-1; i>=0; i--) {
308 const entry_style& style = newEntryStyleArray[i];
309 if (style.spans.size() > 0) {
310 // That's it.
311 break;
312 }
313 // This one is not needed; remove.
314 newEntryStyleArray.removeAt(i);
315 }
316
317 // All done, install the new data structures and upate mValues with
318 // the new positions.
319 mEntries = newEntries;
320 mEntryArray = newEntryArray;
321 mEntryStyleArray = newEntryStyleArray;
322 mValues.clear();
323 for (size_t i=0; i<mEntries.size(); i++) {
324 const entry& ent = mEntries[i];
325 mValues.add(ent.value, ent.indices[0]);
326 }
327
328#if 0
329 printf("FINAL SORTED STRING CONFIGS:\n");
330 for (size_t i=0; i<mEntries.size(); i++) {
331 const entry& ent = mEntries[i];
332 printf("#" ZD " %s: %s\n", (ZD_TYPE)i, ent.makeConfigsString().string(),
333 String8(ent.value).string());
334 }
335#endif
336}
337
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800338sp<AaptFile> StringPool::createStringBlock()
339{
340 sp<AaptFile> pool = new AaptFile(String8(), AaptGroupEntry(),
341 String8());
342 status_t err = writeStringBlock(pool);
343 return err == NO_ERROR ? pool : NULL;
344}
345
Kenny Root19138462009-12-04 09:38:48 -0800346#define ENCODE_LENGTH(str, chrsz, strSize) \
347{ \
348 size_t maxMask = 1 << ((chrsz*8)-1); \
349 size_t maxSize = maxMask-1; \
350 if (strSize > maxSize) { \
351 *str++ = maxMask | ((strSize>>(chrsz*8))&maxSize); \
352 } \
353 *str++ = strSize; \
354}
355
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800356status_t StringPool::writeStringBlock(const sp<AaptFile>& pool)
357{
358 // Allow appending. Sorry this is a little wacky.
359 if (pool->getSize() > 0) {
360 sp<AaptFile> block = createStringBlock();
361 if (block == NULL) {
362 return UNKNOWN_ERROR;
363 }
364 ssize_t res = pool->writeData(block->getData(), block->getSize());
365 return (res >= 0) ? (status_t)NO_ERROR : res;
366 }
367
368 // First we need to add all style span names to the string pool.
369 // We do this now (instead of when the span is added) so that these
370 // will appear at the end of the pool, not disrupting the order
371 // our client placed their own strings in it.
372
373 const size_t STYLES = mEntryStyleArray.size();
374 size_t i;
375
376 for (i=0; i<STYLES; i++) {
377 entry_style& style = mEntryStyleArray.editItemAt(i);
378 const size_t N = style.spans.size();
379 for (size_t i=0; i<N; i++) {
380 entry_style_span& span = style.spans.editItemAt(i);
381 ssize_t idx = add(span.name, true);
382 if (idx < 0) {
383 fprintf(stderr, "Error adding span for style tag '%s'\n",
384 String8(span.name).string());
385 return idx;
386 }
387 span.span.name.index = (uint32_t)idx;
388 }
389 }
390
Jeff Brown345b7eb2012-03-16 15:25:17 -0700391 const size_t ENTRIES = mEntryArray.size();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800392
393 // Now build the pool of unique strings.
394
395 const size_t STRINGS = mEntries.size();
396 const size_t preSize = sizeof(ResStringPool_header)
397 + (sizeof(uint32_t)*ENTRIES)
398 + (sizeof(uint32_t)*STYLES);
399 if (pool->editData(preSize) == NULL) {
400 fprintf(stderr, "ERROR: Out of memory for string pool\n");
401 return NO_MEMORY;
402 }
403
Kenny Root19138462009-12-04 09:38:48 -0800404 const size_t charSize = mUTF8 ? sizeof(uint8_t) : sizeof(char16_t);
405
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800406 size_t strPos = 0;
407 for (i=0; i<STRINGS; i++) {
408 entry& ent = mEntries.editItemAt(i);
409 const size_t strSize = (ent.value.size());
Kenny Root19138462009-12-04 09:38:48 -0800410 const size_t lenSize = strSize > (size_t)(1<<((charSize*8)-1))-1 ?
411 charSize*2 : charSize;
412
413 String8 encStr;
414 if (mUTF8) {
415 encStr = String8(ent.value);
416 }
417
418 const size_t encSize = mUTF8 ? encStr.size() : 0;
419 const size_t encLenSize = mUTF8 ?
420 (encSize > (size_t)(1<<((charSize*8)-1))-1 ?
421 charSize*2 : charSize) : 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800422
423 ent.offset = strPos;
Kenny Root19138462009-12-04 09:38:48 -0800424
425 const size_t totalSize = lenSize + encLenSize +
426 ((mUTF8 ? encSize : strSize)+1)*charSize;
427
428 void* dat = (void*)pool->editData(preSize + strPos + totalSize);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800429 if (dat == NULL) {
430 fprintf(stderr, "ERROR: Out of memory for string pool\n");
431 return NO_MEMORY;
432 }
Kenny Root19138462009-12-04 09:38:48 -0800433 dat = (uint8_t*)dat + preSize + strPos;
434 if (mUTF8) {
435 uint8_t* strings = (uint8_t*)dat;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800436
Kenny Root19138462009-12-04 09:38:48 -0800437 ENCODE_LENGTH(strings, sizeof(uint8_t), strSize)
438
439 ENCODE_LENGTH(strings, sizeof(uint8_t), encSize)
440
441 strncpy((char*)strings, encStr, encSize+1);
442 } else {
443 uint16_t* strings = (uint16_t*)dat;
444
445 ENCODE_LENGTH(strings, sizeof(uint16_t), strSize)
446
447 strcpy16_htod(strings, ent.value);
448 }
449
450 strPos += totalSize;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800451 }
452
453 // Pad ending string position up to a uint32_t boundary.
454
455 if (strPos&0x3) {
456 size_t padPos = ((strPos+3)&~0x3);
457 uint8_t* dat = (uint8_t*)pool->editData(preSize + padPos);
458 if (dat == NULL) {
459 fprintf(stderr, "ERROR: Out of memory padding string pool\n");
460 return NO_MEMORY;
461 }
462 memset(dat+preSize+strPos, 0, padPos-strPos);
463 strPos = padPos;
464 }
465
466 // Build the pool of style spans.
467
468 size_t styPos = strPos;
469 for (i=0; i<STYLES; i++) {
470 entry_style& ent = mEntryStyleArray.editItemAt(i);
471 const size_t N = ent.spans.size();
472 const size_t totalSize = (N*sizeof(ResStringPool_span))
473 + sizeof(ResStringPool_ref);
474
475 ent.offset = styPos-strPos;
476 uint8_t* dat = (uint8_t*)pool->editData(preSize + styPos + totalSize);
477 if (dat == NULL) {
478 fprintf(stderr, "ERROR: Out of memory for string styles\n");
479 return NO_MEMORY;
480 }
481 ResStringPool_span* span = (ResStringPool_span*)(dat+preSize+styPos);
482 for (size_t i=0; i<N; i++) {
483 span->name.index = htodl(ent.spans[i].span.name.index);
484 span->firstChar = htodl(ent.spans[i].span.firstChar);
485 span->lastChar = htodl(ent.spans[i].span.lastChar);
486 span++;
487 }
488 span->name.index = htodl(ResStringPool_span::END);
489
490 styPos += totalSize;
491 }
492
493 if (STYLES > 0) {
494 // Add full terminator at the end (when reading we validate that
495 // the end of the pool is fully terminated to simplify error
496 // checking).
497 size_t extra = sizeof(ResStringPool_span)-sizeof(ResStringPool_ref);
498 uint8_t* dat = (uint8_t*)pool->editData(preSize + styPos + extra);
499 if (dat == NULL) {
500 fprintf(stderr, "ERROR: Out of memory for string styles\n");
501 return NO_MEMORY;
502 }
503 uint32_t* p = (uint32_t*)(dat+preSize+styPos);
504 while (extra > 0) {
505 *p++ = htodl(ResStringPool_span::END);
506 extra -= sizeof(uint32_t);
507 }
508 styPos += extra;
509 }
510
511 // Write header.
512
513 ResStringPool_header* header =
514 (ResStringPool_header*)pool->padData(sizeof(uint32_t));
515 if (header == NULL) {
516 fprintf(stderr, "ERROR: Out of memory for string pool\n");
517 return NO_MEMORY;
518 }
519 memset(header, 0, sizeof(*header));
520 header->header.type = htods(RES_STRING_POOL_TYPE);
521 header->header.headerSize = htods(sizeof(*header));
522 header->header.size = htodl(pool->getSize());
523 header->stringCount = htodl(ENTRIES);
524 header->styleCount = htodl(STYLES);
Kenny Root19138462009-12-04 09:38:48 -0800525 if (mUTF8) {
526 header->flags |= htodl(ResStringPool_header::UTF8_FLAG);
527 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800528 header->stringsStart = htodl(preSize);
529 header->stylesStart = htodl(STYLES > 0 ? (preSize+strPos) : 0);
530
531 // Write string index array.
532
533 uint32_t* index = (uint32_t*)(header+1);
Jeff Brown345b7eb2012-03-16 15:25:17 -0700534 for (i=0; i<ENTRIES; i++) {
535 entry& ent = mEntries.editItemAt(mEntryArray[i]);
536 *index++ = htodl(ent.offset);
537 NOISY(printf("Writing entry #%d: \"%s\" ent=%d off=%d\n", i,
538 String8(ent.value).string(),
539 mEntryArray[i], ent.offset));
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800540 }
541
542 // Write style index array.
543
Jeff Brown345b7eb2012-03-16 15:25:17 -0700544 for (i=0; i<STYLES; i++) {
545 *index++ = htodl(mEntryStyleArray[i].offset);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800546 }
547
548 return NO_ERROR;
549}
550
551ssize_t StringPool::offsetForString(const String16& val) const
552{
553 const Vector<size_t>* indices = offsetsForString(val);
554 ssize_t res = indices != NULL && indices->size() > 0 ? indices->itemAt(0) : -1;
555 NOISY(printf("Offset for string %s: %d (%s)\n", String8(val).string(), res,
556 res >= 0 ? String8(mEntries[mEntryArray[res]].value).string() : String8()));
557 return res;
558}
559
560const Vector<size_t>* StringPool::offsetsForString(const String16& val) const
561{
562 ssize_t pos = mValues.valueFor(val);
563 if (pos < 0) {
564 return NULL;
565 }
566 return &mEntries[mEntryArray[pos]].indices;
567}