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