Debian Codegraph @

brut.apktool/apktool-lib/src/main/java/brut/androlib/res/decoder/StringBlock.java

raw
1 /*
2 * Copyright (C) 2010 Ryszard Wiśniewski <[email protected]>
3 * Copyright (C) 2010 Connor Tumbleson <[email protected]>
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * https://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17 package brut.androlib.res.decoder;
18
19 import brut.androlib.res.xml.ResXmlEncoders;
20 import brut.util.ExtDataInput;
21 import com.google.common.annotations.VisibleForTesting;
22
23 import java.io.IOException;
24 import java.nio.ByteBuffer;
25 import java.nio.charset.*;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.List;
29 import java.util.logging.Logger;
30
31 public class StringBlock {
32
33 /**
34 * Reads whole (including chunk type) string block from stream. Stream must
35 * be at the chunk type.
36 * @param reader ExtDataInput
37 * @return StringBlock
38 *
39 * @throws IOException Parsing resources.arsc error
40 */
41 public static StringBlock read(ExtDataInput reader) throws IOException {
42 reader.skipCheckChunkTypeInt(CHUNK_STRINGPOOL_TYPE, CHUNK_NULL_TYPE);
43 int chunkSize = reader.readInt();
44
45 // ResStringPool_header
46 int stringCount = reader.readInt();
47 int styleCount = reader.readInt();
48 int flags = reader.readInt();
49 int stringsOffset = reader.readInt();
50 int stylesOffset = reader.readInt();
51
52 StringBlock block = new StringBlock();
53 block.m_isUTF8 = (flags & UTF8_FLAG) != 0;
54 block.m_stringOffsets = reader.readIntArray(stringCount);
55
56 if (styleCount != 0) {
57 block.m_styleOffsets = reader.readIntArray(styleCount);
58 }
59
60 int size = ((stylesOffset == 0) ? chunkSize : stylesOffset) - stringsOffset;
61 block.m_strings = new byte[size];
62 reader.readFully(block.m_strings);
63
64 if (stylesOffset != 0) {
65 size = (chunkSize - stylesOffset);
66 block.m_styles = reader.readIntArray(size / 4);
67
68 // read remaining bytes
69 int remaining = size % 4;
70 if (remaining >= 1) {
71 while (remaining-- > 0) {
72 reader.readByte();
73 }
74 }
75 }
76
77 return block;
78 }
79
80 /**
81 * Returns raw string (without any styling information) at specified index.
82 * @param index int
83 * @return String
84 */
85 public String getString(int index) {
86 if (index < 0 || m_stringOffsets == null || index >= m_stringOffsets.length) {
87 return null;
88 }
89 int offset = m_stringOffsets[index];
90 int length;
91
92 int[] val;
93 if (m_isUTF8) {
94 val = getUtf8(m_strings, offset);
95 offset = val[0];
96 } else {
97 val = getUtf16(m_strings, offset);
98 offset += val[0];
99 }
100 length = val[1];
101 return decodeString(offset, length);
102 }
103
104 /**
105 * @param index Location (index) of string to process to HTML
106 * @return String Returns string with style tags (html-like).
107 */
108 public String getHTML(int index) {
109 String text = getString(index);
110 if (text == null) {
111 return null;
112 }
113 int[] style = getStyle(index);
114 if (style == null) {
115 return ResXmlEncoders.escapeXmlChars(text);
116 }
117
118 // If the returned style is further in string, than string length. Lets skip it.
119 if (style[1] > text.length()) {
120 return ResXmlEncoders.escapeXmlChars(text);
121 }
122
123 // Convert styles to spans
124 List<StyledString.Span> spans = new ArrayList<>(style.length / 3);
125 for (int i = 0; i < style.length; i += 3) {
126 spans.add(new StyledString.Span(getString(style[i]), style[i + 1], style[i + 2]));
127 }
128 Collections.sort(spans);
129
130 StyledString styledString = new StyledString(text, spans);
131 return styledString.toString();
132 }
133
134 /**
135 * Finds index of the string. Returns -1 if the string was not found.
136 *
137 * @param string String to index location of
138 * @return int (Returns -1 if not found)
139 */
140 public int find(String string) {
141 if (string == null) {
142 return -1;
143 }
144 for (int i = 0; i != m_stringOffsets.length; ++i) {
145 int offset = m_stringOffsets[i];
146 int length = getShort(m_strings, offset);
147 if (length != string.length()) {
148 continue;
149 }
150 int j = 0;
151 for (; j != length; ++j) {
152 offset += 2;
153 if (string.charAt(j) != getShort(m_strings, offset)) {
154 break;
155 }
156 }
157 if (j == length) {
158 return i;
159 }
160 }
161 return -1;
162 }
163
164 private StringBlock() {
165 }
166
167 @VisibleForTesting
168 StringBlock(byte[] strings, boolean isUTF8) {
169 m_strings = strings;
170 m_isUTF8 = isUTF8;
171 }
172
173 /**
174 * Returns style information - array of int triplets, where in each triplet:
175 * * first int is index of tag name ('b','i', etc.) * second int is tag
176 * start index in string * third int is tag end index in string
177 */
178 private int[] getStyle(int index) {
179 if (m_styleOffsets == null || m_styles == null|| index >= m_styleOffsets.length) {
180 return null;
181 }
182 int offset = m_styleOffsets[index] / 4;
183 int count = 0;
184 int[] style;
185
186 for (int i = offset; i < m_styles.length; ++i) {
187 if (m_styles[i] == -1) {
188 break;
189 }
190 count += 1;
191 }
192
193 if (count == 0 || (count % 3) != 0) {
194 return null;
195 }
196 style = new int[count];
197
198 for (int i = offset, j = 0; i < m_styles.length;) {
199 if (m_styles[i] == -1) {
200 break;
201 }
202 style[j++] = m_styles[i++];
203 }
204 return style;
205 }
206
207 @VisibleForTesting
208 String decodeString(int offset, int length) {
209 try {
210 final ByteBuffer wrappedBuffer = ByteBuffer.wrap(m_strings, offset, length);
211 return (m_isUTF8 ? UTF8_DECODER : UTF16LE_DECODER).decode(wrappedBuffer).toString();
212 } catch (CharacterCodingException ex) {
213 if (!m_isUTF8) {
214 LOGGER.warning("Failed to decode a string at offset " + offset + " of length " + length);
215 return null;
216 }
217 }
218
219 try {
220 final ByteBuffer wrappedBufferRetry = ByteBuffer.wrap(m_strings, offset, length);
221 // in some places, Android uses 3-byte UTF-8 sequences instead of 4-bytes.
222 // If decoding failed, we try to use CESU-8 decoder, which is closer to what Android actually uses.
223 return CESU8_DECODER.decode(wrappedBufferRetry).toString();
224 } catch (CharacterCodingException e) {
225 LOGGER.warning("Failed to decode a string with CESU-8 decoder.");
226 return null;
227 }
228 }
229
230 private static int getShort(byte[] array, int offset) {
231 return (array[offset + 1] & 0xff) << 8 | array[offset] & 0xff;
232 }
233
234 private static int[] getUtf8(byte[] array, int offset) {
235 int val = array[offset];
236 int length;
237 // We skip the utf16 length of the string
238 if ((val & 0x80) != 0) {
239 offset += 2;
240 } else {
241 offset += 1;
242 }
243 // And we read only the utf-8 encoded length of the string
244 val = array[offset];
245 offset += 1;
246 if ((val & 0x80) != 0) {
247 int low = (array[offset] & 0xFF);
248 length = ((val & 0x7F) << 8) + low;
249 offset += 1;
250 } else {
251 length = val;
252 }
253 return new int[] { offset, length};
254 }
255
256 private static int[] getUtf16(byte[] array, int offset) {
257 int val = ((array[offset + 1] & 0xFF) << 8 | array[offset] & 0xFF);
258
259 if ((val & 0x8000) != 0) {
260 int high = (array[offset + 3] & 0xFF) << 8;
261 int low = (array[offset + 2] & 0xFF);
262 int len_value = ((val & 0x7FFF) << 16) + (high + low);
263 return new int[] {4, len_value * 2};
264
265 }
266 return new int[] {2, val * 2};
267 }
268
269 private int[] m_stringOffsets;
270 private byte[] m_strings;
271 private int[] m_styleOffsets;
272 private int[] m_styles;
273 private boolean m_isUTF8;
274
275 private final CharsetDecoder UTF16LE_DECODER = StandardCharsets.UTF_16LE.newDecoder();
276 private final CharsetDecoder UTF8_DECODER = StandardCharsets.UTF_8.newDecoder();
277 private final CharsetDecoder CESU8_DECODER = Charset.forName("CESU8").newDecoder();
278 private static final Logger LOGGER = Logger.getLogger(StringBlock.class.getName());
279
280 // ResChunk_header = header.type (0x0001) + header.headerSize (0x001C)
281 private static final int CHUNK_STRINGPOOL_TYPE = 0x001C0001;
282 private static final int CHUNK_NULL_TYPE = 0x00000000;
283 private static final int UTF8_FLAG = 0x00000100;
284 }