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/BigBuffer.h"
27 #include "androidfw/StringPiece.h"
28 #include "androidfw/Util.h"
29 #include "build/version.h"
30 #include "text/Unicode.h"
31 #include "text/Utf8Iterator.h"
32 #include "utils/Unicode.h"
33 
34 using ::aapt::text::Utf8Iterator;
35 using ::android::StringPiece;
36 using ::android::StringPiece16;
37 
38 namespace aapt {
39 namespace util {
40 
41 // Package name and shared user id would be used as a part of the file name.
42 // Limits size to 223 and reserves 32 for the OS.
43 // See frameworks/base/core/java/android/content/pm/parsing/ParsingPackageUtils.java
44 constexpr static const size_t kMaxPackageNameSize = 223;
45 
SplitAndTransform(StringPiece str,char sep,char (* f)(char))46 static std::vector<std::string> SplitAndTransform(StringPiece str, char sep, char (*f)(char)) {
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(start, current);
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(StringPiece str,char sep)63 std::vector<std::string> Split(StringPiece str, char sep) {
64   return SplitAndTransform(str, sep, nullptr);
65 }
66 
SplitAndLowercase(StringPiece str,char sep)67 std::vector<std::string> SplitAndLowercase(StringPiece str, char sep) {
68   return SplitAndTransform(str, sep, [](char c) -> char { return ::tolower(c); });
69 }
70 
StartsWith(StringPiece str,StringPiece prefix)71 bool StartsWith(StringPiece str, StringPiece prefix) {
72   if (str.size() < prefix.size()) {
73     return false;
74   }
75   return str.substr(0, prefix.size()) == prefix;
76 }
77 
EndsWith(StringPiece str,StringPiece suffix)78 bool EndsWith(StringPiece str, 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(StringPiece str)85 StringPiece TrimLeadingWhitespace(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(StringPiece str)99 StringPiece TrimTrailingWhitespace(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(StringPiece str)113 StringPiece TrimWhitespace(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(StringPiece str)132 static int IsJavaNameImpl(StringPiece str) {
133   int pieces = 0;
134   for (StringPiece piece : Tokenize(str, '.')) {
135     pieces++;
136     if (!text::IsJavaIdentifier(piece)) {
137       return -1;
138     }
139   }
140   return pieces;
141 }
142 
IsJavaClassName(StringPiece str)143 bool IsJavaClassName(StringPiece str) {
144   return IsJavaNameImpl(str) >= 2;
145 }
146 
IsJavaPackageName(StringPiece str)147 bool IsJavaPackageName(StringPiece str) {
148   return IsJavaNameImpl(str) >= 1;
149 }
150 
IsAndroidNameImpl(StringPiece str)151 static int IsAndroidNameImpl(StringPiece str) {
152   int pieces = 0;
153   for (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(StringPiece str)175 bool IsAndroidPackageName(StringPiece str) {
176   if (str.size() > kMaxPackageNameSize) {
177     return false;
178   }
179   return IsAndroidNameImpl(str) > 1 || str == "android";
180 }
181 
IsAndroidSharedUserId(android::StringPiece package_name,android::StringPiece shared_user_id)182 bool IsAndroidSharedUserId(android::StringPiece package_name, 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 
IsAndroidSplitName(StringPiece str)190 bool IsAndroidSplitName(StringPiece str) {
191   return IsAndroidNameImpl(str) > 0;
192 }
193 
GetFullyQualifiedClassName(StringPiece package,StringPiece classname)194 std::optional<std::string> GetFullyQualifiedClassName(StringPiece package, StringPiece classname) {
195   if (classname.empty()) {
196     return {};
197   }
198 
199   if (util::IsJavaClassName(classname)) {
200     return std::string(classname);
201   }
202 
203   if (package.empty()) {
204     return {};
205   }
206 
207   std::string result{package};
208   if (classname.data()[0] != '.') {
209     result += '.';
210   }
211 
212   result.append(classname.data(), classname.size());
213   if (!IsJavaClassName(result)) {
214     return {};
215   }
216   return result;
217 }
218 
GetToolName()219 const char* GetToolName() {
220   static const char* const sToolName = "Android Asset Packaging Tool (aapt)";
221   return sToolName;
222 }
223 
GetToolFingerprint()224 std::string GetToolFingerprint() {
225   // DO NOT UPDATE, this is more of a marketing version.
226   static const char* const sMajorVersion = "2";
227 
228   // Update minor version whenever a feature or flag is added.
229   static const char* const sMinorVersion = "19";
230 
231   // The build id of aapt2 binary.
232   static std::string sBuildId = android::build::GetBuildNumber();
233 
234   if (android::base::StartsWith(sBuildId, "eng.")) {
235     time_t now = time(0);
236     tm* ltm = localtime(&now);
237 
238     sBuildId = android::base::StringPrintf("eng.%d%d", 1900 + ltm->tm_year, 1 + ltm->tm_mon);
239   }
240 
241   return android::base::StringPrintf("%s.%s-%s", sMajorVersion, sMinorVersion, sBuildId.c_str());
242 }
243 
ConsumeDigits(const char * start,const char * end)244 static size_t ConsumeDigits(const char* start, const char* end) {
245   const char* c = start;
246   for (; c != end && *c >= '0' && *c <= '9'; c++) {
247   }
248   return static_cast<size_t>(c - start);
249 }
250 
VerifyJavaStringFormat(StringPiece str)251 bool VerifyJavaStringFormat(StringPiece str) {
252   const char* c = str.begin();
253   const char* const end = str.end();
254 
255   size_t arg_count = 0;
256   bool nonpositional = false;
257   while (c != end) {
258     if (*c == '%' && c + 1 < end) {
259       c++;
260 
261       if (*c == '%' || *c == 'n') {
262         c++;
263         continue;
264       }
265 
266       arg_count++;
267 
268       size_t num_digits = ConsumeDigits(c, end);
269       if (num_digits > 0) {
270         c += num_digits;
271         if (c != end && *c != '$') {
272           // The digits were a size, but not a positional argument.
273           nonpositional = true;
274         }
275       } else if (*c == '<') {
276         // Reusing last argument, bad idea since positions can be moved around
277         // during translation.
278         nonpositional = true;
279 
280         c++;
281 
282         // Optionally we can have a $ after
283         if (c != end && *c == '$') {
284           c++;
285         }
286       } else {
287         nonpositional = true;
288       }
289 
290       // Ignore size, width, flags, etc.
291       while (c != end && (*c == '-' || *c == '#' || *c == '+' || *c == ' ' ||
292                           *c == ',' || *c == '(' || (*c >= '0' && *c <= '9'))) {
293         c++;
294       }
295 
296       /*
297        * This is a shortcut to detect strings that are going to Time.format()
298        * instead of String.format()
299        *
300        * Comparison of String.format() and Time.format() args:
301        *
302        * String: ABC E GH  ST X abcdefgh  nost x
303        *   Time:    DEFGHKMS W Za  d   hkm  s w yz
304        *
305        * Therefore we know it's definitely Time if we have:
306        *     DFKMWZkmwyz
307        */
308       if (c != end) {
309         switch (*c) {
310           case 'D':
311           case 'F':
312           case 'K':
313           case 'M':
314           case 'W':
315           case 'Z':
316           case 'k':
317           case 'm':
318           case 'w':
319           case 'y':
320           case 'z':
321             return true;
322         }
323       }
324     }
325 
326     if (c != end) {
327       c++;
328     }
329   }
330 
331   if (arg_count > 1 && nonpositional) {
332     // Multiple arguments were specified, but some or all were non positional.
333     // Translated
334     // strings may rearrange the order of the arguments, which will break the
335     // string.
336     return false;
337   }
338   return true;
339 }
340 
Utf8ToUtf16(StringPiece utf8)341 std::u16string Utf8ToUtf16(StringPiece utf8) {
342   ssize_t utf16_length = utf8_to_utf16_length(
343       reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length());
344   if (utf16_length <= 0) {
345     return {};
346   }
347 
348   std::u16string utf16;
349   utf16.resize(utf16_length);
350   utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(),
351                 &*utf16.begin(), utf16_length + 1);
352   return utf16;
353 }
354 
Utf16ToUtf8(const StringPiece16 & utf16)355 std::string Utf16ToUtf8(const StringPiece16& utf16) {
356   ssize_t utf8_length = utf16_to_utf8_length(utf16.data(), utf16.length());
357   if (utf8_length <= 0) {
358     return {};
359   }
360 
361   std::string utf8;
362   utf8.resize(utf8_length);
363   utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin(), utf8_length + 1);
364   return utf8;
365 }
366 
WriteAll(std::ostream & out,const android::BigBuffer & buffer)367 bool WriteAll(std::ostream& out, const android::BigBuffer& buffer) {
368   for (const auto& b : buffer) {
369     if (!out.write(reinterpret_cast<const char*>(b.buffer.get()), b.size)) {
370       return false;
371     }
372   }
373   return true;
374 }
375 
operator ++()376 typename Tokenizer::iterator& Tokenizer::iterator::operator++() {
377   const char* start = token_.end();
378   const char* end = str_.end();
379   if (start == end) {
380     end_ = true;
381     token_ = StringPiece(token_.end(), 0);
382     return *this;
383   }
384 
385   start += 1;
386   const char* current = start;
387   while (current != end) {
388     if (*current == separator_) {
389       token_ = StringPiece(start, current - start);
390       return *this;
391     }
392     ++current;
393   }
394   token_ = StringPiece(start, end - start);
395   return *this;
396 }
397 
operator ==(const iterator & rhs) const398 bool Tokenizer::iterator::operator==(const iterator& rhs) const {
399   // We check equality here a bit differently.
400   // We need to know that the addresses are the same.
401   return token_.begin() == rhs.token_.begin() &&
402          token_.end() == rhs.token_.end() && end_ == rhs.end_;
403 }
404 
operator !=(const iterator & rhs) const405 bool Tokenizer::iterator::operator!=(const iterator& rhs) const {
406   return !(*this == rhs);
407 }
408 
iterator(StringPiece s,char sep,StringPiece tok,bool end)409 Tokenizer::iterator::iterator(StringPiece s, char sep, StringPiece tok, bool end)
410     : str_(s), separator_(sep), token_(tok), end_(end) {
411 }
412 
Tokenizer(StringPiece str,char sep)413 Tokenizer::Tokenizer(StringPiece str, char sep)
414     : begin_(++iterator(str, sep, StringPiece(str.begin() - 1, 0), false)),
415       end_(str, sep, StringPiece(str.end(), 0), true) {
416 }
417 
ExtractResFilePathParts(StringPiece path,StringPiece * out_prefix,StringPiece * out_entry,StringPiece * out_suffix)418 bool ExtractResFilePathParts(StringPiece path, StringPiece* out_prefix, StringPiece* out_entry,
419                              StringPiece* out_suffix) {
420   const StringPiece res_prefix("res/");
421   if (!StartsWith(path, res_prefix)) {
422     return false;
423   }
424 
425   StringPiece::const_iterator last_occurence = path.end();
426   for (auto iter = path.begin() + res_prefix.size(); iter != path.end();
427        ++iter) {
428     if (*iter == '/') {
429       last_occurence = iter;
430     }
431   }
432 
433   if (last_occurence == path.end()) {
434     return false;
435   }
436 
437   auto iter = std::find(last_occurence, path.end(), '.');
438   *out_suffix = StringPiece(iter, path.end() - iter);
439   *out_entry = StringPiece(last_occurence + 1, iter - last_occurence - 1);
440   *out_prefix = StringPiece(path.begin(), last_occurence - path.begin() + 1);
441   return true;
442 }
443 
444 }  // namespace util
445 }  // namespace aapt
446