Debian Codegraph @

tools/aapt2/util/Util.cpp

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "util/Util.h"
18
19 #include <algorithm>
20 #include <ostream>
21 #include <string>
22 #include <vector>
23
24 #include "android-base/stringprintf.h"
25 #include "android-base/strings.h"
26 #include "androidfw/StringPiece.h"
27 #include "text/Unicode.h"
28 #include "text/Utf8Iterator.h"
29 #include "util/BigBuffer.h"
30 #include "utils/Unicode.h"
31
32 using ::aapt::text::Utf8Iterator;
33 using ::android::StringPiece;
34 using ::android::StringPiece16;
35
36 namespace aapt {
37 namespace util {
38
39 // Package name and shared user id would be used as a part of the file name.
40 // Limits size to 223 and reserves 32 for the OS.
41 // See frameworks/base/core/java/android/content/pm/parsing/ParsingPackageUtils.java
42 constexpr static const size_t kMaxPackageNameSize = 223;
43
44 static std::vector<std::string> SplitAndTransform(
45 const StringPiece& str, char sep, const std::function<char(char)>& f) {
46 std::vector<std::string> parts;
47 const StringPiece::const_iterator end = std::end(str);
48 StringPiece::const_iterator start = std::begin(str);
49 StringPiece::const_iterator current;
50 do {
51 current = std::find(start, end, sep);
52 parts.emplace_back(str.substr(start, current).to_string());
53 if (f) {
54 std::string& part = parts.back();
55 std::transform(part.begin(), part.end(), part.begin(), f);
56 }
57 start = current + 1;
58 } while (current != end);
59 return parts;
60 }
61
62 std::vector<std::string> Split(const StringPiece& str, char sep) {
63 return SplitAndTransform(str, sep, nullptr);
64 }
65
66 std::vector<std::string> SplitAndLowercase(const StringPiece& str, char sep) {
67 return SplitAndTransform(str, sep, ::tolower);
68 }
69
70 bool StartsWith(const StringPiece& str, const StringPiece& prefix) {
71 if (str.size() < prefix.size()) {
72 return false;
73 }
74 return str.substr(0, prefix.size()) == prefix;
75 }
76
77 bool EndsWith(const StringPiece& str, const StringPiece& suffix) {
78 if (str.size() < suffix.size()) {
79 return false;
80 }
81 return str.substr(str.size() - suffix.size(), suffix.size()) == suffix;
82 }
83
84 StringPiece TrimLeadingWhitespace(const StringPiece& str) {
85 if (str.size() == 0 || str.data() == nullptr) {
86 return str;
87 }
88
89 const char* start = str.data();
90 const char* end = start + str.length();
91
92 while (start != end && isspace(*start)) {
93 start++;
94 }
95 return StringPiece(start, end - start);
96 }
97
98 StringPiece TrimTrailingWhitespace(const StringPiece& str) {
99 if (str.size() == 0 || str.data() == nullptr) {
100 return str;
101 }
102
103 const char* start = str.data();
104 const char* end = start + str.length();
105
106 while (end != start && isspace(*(end - 1))) {
107 end--;
108 }
109 return StringPiece(start, end - start);
110 }
111
112 StringPiece TrimWhitespace(const StringPiece& str) {
113 if (str.size() == 0 || str.data() == nullptr) {
114 return str;
115 }
116
117 const char* start = str.data();
118 const char* end = str.data() + str.length();
119
120 while (start != end && isspace(*start)) {
121 start++;
122 }
123
124 while (end != start && isspace(*(end - 1))) {
125 end--;
126 }
127
128 return StringPiece(start, end - start);
129 }
130
131 static int IsJavaNameImpl(const StringPiece& str) {
132 int pieces = 0;
133 for (const StringPiece& piece : Tokenize(str, '.')) {
134 pieces++;
135 if (!text::IsJavaIdentifier(piece)) {
136 return -1;
137 }
138 }
139 return pieces;
140 }
141
142 bool IsJavaClassName(const StringPiece& str) {
143 return IsJavaNameImpl(str) >= 2;
144 }
145
146 bool IsJavaPackageName(const StringPiece& str) {
147 return IsJavaNameImpl(str) >= 1;
148 }
149
150 static int IsAndroidNameImpl(const StringPiece& str) {
151 int pieces = 0;
152 for (const StringPiece& piece : Tokenize(str, '.')) {
153 if (piece.empty()) {
154 return -1;
155 }
156
157 const char first_character = piece.data()[0];
158 if (!::isalpha(first_character)) {
159 return -1;
160 }
161
162 bool valid = std::all_of(piece.begin() + 1, piece.end(), [](const char c) -> bool {
163 return ::isalnum(c) || c == '_';
164 });
165
166 if (!valid) {
167 return -1;
168 }
169 pieces++;
170 }
171 return pieces;
172 }
173
174 bool IsAndroidPackageName(const StringPiece& str) {
175 if (str.size() > kMaxPackageNameSize) {
176 return false;
177 }
178 return IsAndroidNameImpl(str) > 1 || str == "android";
179 }
180
181 bool IsAndroidSharedUserId(const android::StringPiece& package_name,
182 const android::StringPiece& shared_user_id) {
183 if (shared_user_id.size() > kMaxPackageNameSize) {
184 return false;
185 }
186 return shared_user_id.empty() || IsAndroidNameImpl(shared_user_id) > 1 ||
187 package_name == "android";
188 }
189
190 bool IsAndroidSplitName(const StringPiece& str) {
191 return IsAndroidNameImpl(str) > 0;
192 }
193
194 std::optional<std::string> GetFullyQualifiedClassName(const StringPiece& package,
195 const StringPiece& classname) {
196 if (classname.empty()) {
197 return {};
198 }
199
200 if (util::IsJavaClassName(classname)) {
201 return classname.to_string();
202 }
203
204 if (package.empty()) {
205 return {};
206 }
207
208 std::string result = package.to_string();
209 if (classname.data()[0] != '.') {
210 result += '.';
211 }
212
213 result.append(classname.data(), classname.size());
214 if (!IsJavaClassName(result)) {
215 return {};
216 }
217 return result;
218 }
219
220 const char* GetToolName() {
221 static const char* const sToolName = "Android Asset Packaging Tool (aapt)";
222 return sToolName;
223 }
224
225 std::string GetToolFingerprint() {
226 // DO NOT UPDATE, this is more of a marketing version.
227 static const char* const sMajorVersion = "2";
228
229 // Update minor version whenever a feature or flag is added.
230 static const char* const sMinorVersion = "19";
231
•232 return android::base::StringPrintf("%s.%s-%s", sMajorVersion, sMinorVersion, "debian");
233 }
234
235 static size_t ConsumeDigits(const char* start, const char* end) {
236 const char* c = start;
237 for (; c != end && *c >= '0' && *c <= '9'; c++) {
238 }
239 return static_cast<size_t>(c - start);
240 }
241
242 bool VerifyJavaStringFormat(const StringPiece& str) {
243 const char* c = str.begin();
244 const char* const end = str.end();
245
246 size_t arg_count = 0;
247 bool nonpositional = false;
248 while (c != end) {
249 if (*c == '%' && c + 1 < end) {
250 c++;
251
252 if (*c == '%' || *c == 'n') {
253 c++;
254 continue;
255 }
256
257 arg_count++;
258
259 size_t num_digits = ConsumeDigits(c, end);
260 if (num_digits > 0) {
261 c += num_digits;
262 if (c != end && *c != '$') {
263 // The digits were a size, but not a positional argument.
264 nonpositional = true;
265 }
266 } else if (*c == '<') {
267 // Reusing last argument, bad idea since positions can be moved around
268 // during translation.
269 nonpositional = true;
270
271 c++;
272
273 // Optionally we can have a $ after
274 if (c != end && *c == '$') {
275 c++;
276 }
277 } else {
278 nonpositional = true;
279 }
280
281 // Ignore size, width, flags, etc.
282 while (c != end && (*c == '-' || *c == '#' || *c == '+' || *c == ' ' ||
283 *c == ',' || *c == '(' || (*c >= '0' && *c <= '9'))) {
284 c++;
285 }
286
287 /*
288 * This is a shortcut to detect strings that are going to Time.format()
289 * instead of String.format()
290 *
291 * Comparison of String.format() and Time.format() args:
292 *
293 * String: ABC E GH ST X abcdefgh nost x
294 * Time: DEFGHKMS W Za d hkm s w yz
295 *
296 * Therefore we know it's definitely Time if we have:
297 * DFKMWZkmwyz
298 */
299 if (c != end) {
300 switch (*c) {
301 case 'D':
302 case 'F':
303 case 'K':
304 case 'M':
305 case 'W':
306 case 'Z':
307 case 'k':
308 case 'm':
309 case 'w':
310 case 'y':
311 case 'z':
312 return true;
313 }
314 }
315 }
316
317 if (c != end) {
318 c++;
319 }
320 }
321
322 if (arg_count > 1 && nonpositional) {
323 // Multiple arguments were specified, but some or all were non positional.
324 // Translated
325 // strings may rearrange the order of the arguments, which will break the
326 // string.
327 return false;
328 }
329 return true;
330 }
331
332 std::string Utf8ToModifiedUtf8(const std::string& utf8) {
333 // Java uses Modified UTF-8 which only supports the 1, 2, and 3 byte formats of UTF-8. To encode
334 // 4 byte UTF-8 codepoints, Modified UTF-8 allows the use of surrogate pairs in the same format
335 // of CESU-8 surrogate pairs. Calculate the size of the utf8 string with all 4 byte UTF-8
336 // codepoints replaced with 2 3 byte surrogate pairs
337 size_t modified_size = 0;
338 const size_t size = utf8.size();
339 for (size_t i = 0; i < size; i++) {
340 if (((uint8_t) utf8[i] >> 4) == 0xF) {
341 modified_size += 6;
342 i += 3;
343 } else {
344 modified_size++;
345 }
346 }
347
348 // Early out if no 4 byte codepoints are found
349 if (size == modified_size) {
350 return utf8;
351 }
352
353 std::string output;
354 output.reserve(modified_size);
355 for (size_t i = 0; i < size; i++) {
356 if (((uint8_t) utf8[i] >> 4) == 0xF) {
357 int32_t codepoint = utf32_from_utf8_at(utf8.data(), size, i, nullptr);
358
359 // Calculate the high and low surrogates as UTF-16 would
360 int32_t high = ((codepoint - 0x10000) / 0x400) + 0xD800;
361 int32_t low = ((codepoint - 0x10000) % 0x400) + 0xDC00;
362
363 // Encode each surrogate in UTF-8
364 output.push_back((char) (0xE4 | ((high >> 12) & 0xF)));
365 output.push_back((char) (0x80 | ((high >> 6) & 0x3F)));
366 output.push_back((char) (0x80 | (high & 0x3F)));
367 output.push_back((char) (0xE4 | ((low >> 12) & 0xF)));
368 output.push_back((char) (0x80 | ((low >> 6) & 0x3F)));
369 output.push_back((char) (0x80 | (low & 0x3F)));
370 i += 3;
371 } else {
372 output.push_back(utf8[i]);
373 }
374 }
375
376 return output;
377 }
378
379 std::string ModifiedUtf8ToUtf8(const std::string& modified_utf8) {
380 // The UTF-8 representation will have a byte length less than or equal to the Modified UTF-8
381 // representation.
382 std::string output;
383 output.reserve(modified_utf8.size());
384
385 size_t index = 0;
386 const size_t modified_size = modified_utf8.size();
387 while (index < modified_size) {
388 size_t next_index;
389 int32_t high_surrogate = utf32_from_utf8_at(modified_utf8.data(), modified_size, index,
390 &next_index);
391 if (high_surrogate < 0) {
392 return {};
393 }
394
395 // Check that the first codepoint is within the high surrogate range
396 if (high_surrogate >= 0xD800 && high_surrogate <= 0xDB7F) {
397 int32_t low_surrogate = utf32_from_utf8_at(modified_utf8.data(), modified_size, next_index,
398 &next_index);
399 if (low_surrogate < 0) {
400 return {};
401 }
402
403 // Check that the second codepoint is within the low surrogate range
404 if (low_surrogate >= 0xDC00 && low_surrogate <= 0xDFFF) {
405 const char32_t codepoint = (char32_t) (((high_surrogate - 0xD800) * 0x400)
406 + (low_surrogate - 0xDC00) + 0x10000);
407
408 // The decoded codepoint should represent a 4 byte, UTF-8 character
409 const size_t utf8_length = (size_t) utf32_to_utf8_length(&codepoint, 1);
410 if (utf8_length != 4) {
411 return {};
412 }
413
414 // Encode the UTF-8 representation of the codepoint into the string
415 char* start = &output[output.size()];
416 output.resize(output.size() + utf8_length);
417 utf32_to_utf8((char32_t*) &codepoint, 1, start, utf8_length + 1);
418
419 index = next_index;
420 continue;
421 }
422 }
423
424 // Append non-surrogate pairs to the output string
425 for (size_t i = index; i < next_index; i++) {
426 output.push_back(modified_utf8[i]);
427 }
428 index = next_index;
429 }
430 return output;
431 }
432
433 std::u16string Utf8ToUtf16(const StringPiece& utf8) {
434 ssize_t utf16_length = utf8_to_utf16_length(
435 reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length());
436 if (utf16_length <= 0) {
437 return {};
438 }
439
440 std::u16string utf16;
441 utf16.resize(utf16_length);
442 utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(),
443 &*utf16.begin(), utf16_length + 1);
444 return utf16;
445 }
446
447 std::string Utf16ToUtf8(const StringPiece16& utf16) {
448 ssize_t utf8_length = utf16_to_utf8_length(utf16.data(), utf16.length());
449 if (utf8_length <= 0) {
450 return {};
451 }
452
453 std::string utf8;
454 utf8.resize(utf8_length);
455 utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8_length + 1);
456 return utf8;
457 }
458
459 bool WriteAll(std::ostream& out, const BigBuffer& buffer) {
460 for (const auto& b : buffer) {
461 if (!out.write(reinterpret_cast<const char*>(b.buffer.get()), b.size)) {
462 return false;
463 }
464 }
465 return true;
466 }
467
468 std::unique_ptr<uint8_t[]> Copy(const BigBuffer& buffer) {
469 std::unique_ptr<uint8_t[]> data =
470 std::unique_ptr<uint8_t[]>(new uint8_t[buffer.size()]);
471 uint8_t* p = data.get();
472 for (const auto& block : buffer) {
473 memcpy(p, block.buffer.get(), block.size);
474 p += block.size;
475 }
476 return data;
477 }
478
479 typename Tokenizer::iterator& Tokenizer::iterator::operator++() {
480 const char* start = token_.end();
481 const char* end = str_.end();
482 if (start == end) {
483 end_ = true;
484 token_.assign(token_.end(), 0);
485 return *this;
486 }
487
488 start += 1;
489 const char* current = start;
490 while (current != end) {
491 if (*current == separator_) {
492 token_.assign(start, current - start);
493 return *this;
494 }
495 ++current;
496 }
497 token_.assign(start, end - start);
498 return *this;
499 }
500
501 bool Tokenizer::iterator::operator==(const iterator& rhs) const {
502 // We check equality here a bit differently.
503 // We need to know that the addresses are the same.
504 return token_.begin() == rhs.token_.begin() &&
505 token_.end() == rhs.token_.end() && end_ == rhs.end_;
506 }
507
508 bool Tokenizer::iterator::operator!=(const iterator& rhs) const {
509 return !(*this == rhs);
510 }
511
512 Tokenizer::iterator::iterator(const StringPiece& s, char sep, const StringPiece& tok, bool end)
513 : str_(s), separator_(sep), token_(tok), end_(end) {}
514
515 Tokenizer::Tokenizer(const StringPiece& str, char sep)
516 : begin_(++iterator(str, sep, StringPiece(str.begin() - 1, 0), false)),
517 end_(str, sep, StringPiece(str.end(), 0), true) {}
518
519 bool ExtractResFilePathParts(const StringPiece& path, StringPiece* out_prefix,
520 StringPiece* out_entry, StringPiece* out_suffix) {
521 const StringPiece res_prefix("res/");
522 if (!StartsWith(path, res_prefix)) {
523 return false;
524 }
525
526 StringPiece::const_iterator last_occurence = path.end();
527 for (auto iter = path.begin() + res_prefix.size(); iter != path.end();
528 ++iter) {
529 if (*iter == '/') {
530 last_occurence = iter;
531 }
532 }
533
534 if (last_occurence == path.end()) {
535 return false;
536 }
537
538 auto iter = std::find(last_occurence, path.end(), '.');
539 *out_suffix = StringPiece(iter, path.end() - iter);
540 *out_entry = StringPiece(last_occurence + 1, iter - last_occurence - 1);
541 *out_prefix = StringPiece(path.begin(), last_occurence - path.begin() + 1);
542 return true;
543 }
544
545 StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx) {
546 if (auto str = pool.stringAt(idx); str.ok()) {
547 return *str;
548 }
549 return StringPiece16();
550 }
551
552 std::string GetString(const android::ResStringPool& pool, size_t idx) {
553 if (auto str = pool.string8At(idx); str.ok()) {
554 return ModifiedUtf8ToUtf8(str->to_string());
555 }
556 return Utf16ToUtf8(GetString16(pool, idx));
557 }
558
559 } // namespace util
560 } // namespace aapt