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 #ifndef AAPT_UTIL_H
18 #define AAPT_UTIL_H
19 
20 #include <functional>
21 #include <memory>
22 #include <ostream>
23 #include <string>
24 #include <vector>
25 
26 #include "androidfw/ResourceTypes.h"
27 #include "androidfw/StringPiece.h"
28 #include "utils/ByteOrder.h"
29 
30 #include "util/BigBuffer.h"
31 #include "util/Maybe.h"
32 
33 #ifdef _WIN32
34 // TODO(adamlesinski): remove once http://b/32447322 is resolved.
35 // utils/ByteOrder.h includes winsock2.h on WIN32,
36 // which will pull in the ERROR definition. This conflicts
37 // with android-base/logging.h, which takes care of undefining
38 // ERROR, but it gets included too early (before winsock2.h).
39 #ifdef ERROR
40 #undef ERROR
41 #endif
42 #endif
43 
44 namespace aapt {
45 namespace util {
46 
47 template <typename T>
48 struct Range {
49   T start;
50   T end;
51 };
52 
53 std::vector<std::string> Split(const android::StringPiece& str, char sep);
54 std::vector<std::string> SplitAndLowercase(const android::StringPiece& str, char sep);
55 
56 // Returns true if the string starts with prefix.
57 bool StartsWith(const android::StringPiece& str, const android::StringPiece& prefix);
58 
59 // Returns true if the string ends with suffix.
60 bool EndsWith(const android::StringPiece& str, const android::StringPiece& suffix);
61 
62 // Creates a new StringPiece that points to a substring of the original string without leading
63 // whitespace.
64 android::StringPiece TrimLeadingWhitespace(const android::StringPiece& str);
65 
66 // Creates a new StringPiece that points to a substring of the original string without trailing
67 // whitespace.
68 android::StringPiece TrimTrailingWhitespace(const android::StringPiece& str);
69 
70 // Creates a new StringPiece that points to a substring of the original string without leading or
71 // trailing whitespace.
72 android::StringPiece TrimWhitespace(const android::StringPiece& str);
73 
74 // Tests that the string is a valid Java class name.
75 bool IsJavaClassName(const android::StringPiece& str);
76 
77 // Tests that the string is a valid Java package name.
78 bool IsJavaPackageName(const android::StringPiece& str);
79 
80 // Tests that the string is a valid Android package name. More strict than a Java package name.
81 // - First character of each component (separated by '.') must be an ASCII letter.
82 // - Subsequent characters of a component can be ASCII alphanumeric or an underscore.
83 // - Package must contain at least two components, unless it is 'android'.
84 // - The maximum package name length is 223.
85 bool IsAndroidPackageName(const android::StringPiece& str);
86 
87 // Tests that the string is a valid Android split name.
88 // - First character of each component (separated by '.') must be an ASCII letter.
89 // - Subsequent characters of a component can be ASCII alphanumeric or an underscore.
90 bool IsAndroidSplitName(const android::StringPiece& str);
91 
92 // Tests that the string is a valid Android shared user id.
93 // - First character of each component (separated by '.') must be an ASCII letter.
94 // - Subsequent characters of a component can be ASCII alphanumeric or an underscore.
95 // - Must contain at least two components, unless package name is 'android'.
96 // - The maximum shared user id length is 223.
97 // - Treat empty string as valid, it's the case of no shared user id.
98 bool IsAndroidSharedUserId(const android::StringPiece& package_name,
99                            const android::StringPiece& shared_user_id);
100 
101 // Converts the class name to a fully qualified class name from the given
102 // `package`. Ex:
103 //
104 // asdf         --> package.asdf
105 // .asdf        --> package.asdf
106 // .a.b         --> package.a.b
107 // asdf.adsf    --> asdf.adsf
108 Maybe<std::string> GetFullyQualifiedClassName(const android::StringPiece& package,
109                                               const android::StringPiece& class_name);
110 
111 // Retrieves the formatted name of aapt2.
112 const char* GetToolName();
113 
114 // Retrieves the build fingerprint of aapt2.
115 std::string GetToolFingerprint();
116 
117 template <typename T>
compare(const T & a,const T & b)118 typename std::enable_if<std::is_arithmetic<T>::value, int>::type compare(const T& a, const T& b) {
119   if (a < b) {
120     return -1;
121   } else if (a > b) {
122     return 1;
123   }
124   return 0;
125 }
126 
127 // Makes a std::unique_ptr<> with the template parameter inferred by the compiler.
128 // This will be present in C++14 and can be removed then.
129 template <typename T, class... Args>
make_unique(Args &&...args)130 std::unique_ptr<T> make_unique(Args&&... args) {
131   return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
132 }
133 
134 // Writes a set of items to the std::ostream, joining the times with the provided separator.
135 template <typename Container>
Joiner(const Container & container,const char * sep)136 ::std::function<::std::ostream&(::std::ostream&)> Joiner(const Container& container,
137                                                          const char* sep) {
138   using std::begin;
139   using std::end;
140   const auto begin_iter = begin(container);
141   const auto end_iter = end(container);
142   return [begin_iter, end_iter, sep](::std::ostream& out) -> ::std::ostream& {
143     for (auto iter = begin_iter; iter != end_iter; ++iter) {
144       if (iter != begin_iter) {
145         out << sep;
146       }
147       out << *iter;
148     }
149     return out;
150   };
151 }
152 
153 // Helper method to extract a UTF-16 string from a StringPool. If the string is stored as UTF-8,
154 // the conversion to UTF-16 happens within ResStringPool.
155 android::StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx);
156 
157 // Helper method to extract a UTF-8 string from a StringPool. If the string is stored as UTF-16,
158 // the conversion from UTF-16 to UTF-8 does not happen in ResStringPool and is done by this method,
159 // which maintains no state or cache. This means we must return an std::string copy.
160 std::string GetString(const android::ResStringPool& pool, size_t idx);
161 
162 // Checks that the Java string format contains no non-positional arguments (arguments without
163 // explicitly specifying an index) when there are more than one argument. This is an error
164 // because translations may rearrange the order of the arguments in the string, which will
165 // break the string interpolation.
166 bool VerifyJavaStringFormat(const android::StringPiece& str);
167 
168 bool AppendStyledString(const android::StringPiece& input, bool preserve_spaces,
169                         std::string* out_str, std::string* out_error);
170 
171 class StringBuilder {
172  public:
173   StringBuilder() = default;
174 
175   StringBuilder& Append(const android::StringPiece& str);
176   const std::string& ToString() const;
177   const std::string& Error() const;
178   bool IsEmpty() const;
179 
180   // When building StyledStrings, we need UTF-16 indices into the string,
181   // which is what the Java layer expects when dealing with java
182   // String.charAt().
183   size_t Utf16Len() const;
184 
185   explicit operator bool() const;
186 
187  private:
188   std::string str_;
189   size_t utf16_len_ = 0;
190   bool quote_ = false;
191   bool trailing_space_ = false;
192   bool last_char_was_escape_ = false;
193   std::string error_;
194 };
195 
ToString()196 inline const std::string& StringBuilder::ToString() const {
197   return str_;
198 }
199 
Error()200 inline const std::string& StringBuilder::Error() const {
201   return error_;
202 }
203 
IsEmpty()204 inline bool StringBuilder::IsEmpty() const {
205   return str_.empty();
206 }
207 
Utf16Len()208 inline size_t StringBuilder::Utf16Len() const {
209   return utf16_len_;
210 }
211 
212 inline StringBuilder::operator bool() const {
213   return error_.empty();
214 }
215 
216 // Converts a UTF8 string into Modified UTF8
217 std::string Utf8ToModifiedUtf8(const std::string& utf8);
218 std::string ModifiedUtf8ToUtf8(const std::string& modified_utf8);
219 
220 // Converts a UTF8 string to a UTF16 string.
221 std::u16string Utf8ToUtf16(const android::StringPiece& utf8);
222 std::string Utf16ToUtf8(const android::StringPiece16& utf16);
223 
224 // Writes the entire BigBuffer to the output stream.
225 bool WriteAll(std::ostream& out, const BigBuffer& buffer);
226 
227 // Copies the entire BigBuffer into a single buffer.
228 std::unique_ptr<uint8_t[]> Copy(const BigBuffer& buffer);
229 
230 // A Tokenizer implemented as an iterable collection. It does not allocate any memory on the heap
231 // nor use standard containers.
232 class Tokenizer {
233  public:
234   class iterator {
235    public:
236     using reference = android::StringPiece&;
237     using value_type = android::StringPiece;
238     using difference_type = size_t;
239     using pointer = android::StringPiece*;
240     using iterator_category = std::forward_iterator_tag;
241 
242     iterator(const iterator&) = default;
243     iterator& operator=(const iterator&) = default;
244 
245     iterator& operator++();
246 
247     android::StringPiece operator*() { return token_; }
248     bool operator==(const iterator& rhs) const;
249     bool operator!=(const iterator& rhs) const;
250 
251    private:
252     friend class Tokenizer;
253 
254     iterator(const android::StringPiece& s, char sep, const android::StringPiece& tok, bool end);
255 
256     android::StringPiece str_;
257     char separator_;
258     android::StringPiece token_;
259     bool end_;
260   };
261 
262   Tokenizer(const android::StringPiece& str, char sep);
263 
begin()264   iterator begin() const {
265     return begin_;
266   }
267 
end()268   iterator end() const {
269     return end_;
270   }
271 
272  private:
273   const iterator begin_;
274   const iterator end_;
275 };
276 
Tokenize(const android::StringPiece & str,char sep)277 inline Tokenizer Tokenize(const android::StringPiece& str, char sep) {
278   return Tokenizer(str, sep);
279 }
280 
HostToDevice16(uint16_t value)281 inline uint16_t HostToDevice16(uint16_t value) {
282   return htods(value);
283 }
284 
HostToDevice32(uint32_t value)285 inline uint32_t HostToDevice32(uint32_t value) {
286   return htodl(value);
287 }
288 
DeviceToHost16(uint16_t value)289 inline uint16_t DeviceToHost16(uint16_t value) {
290   return dtohs(value);
291 }
292 
DeviceToHost32(uint32_t value)293 inline uint32_t DeviceToHost32(uint32_t value) {
294   return dtohl(value);
295 }
296 
297 // Given a path like: res/xml-sw600dp/foo.xml
298 //
299 // Extracts "res/xml-sw600dp/" into outPrefix.
300 // Extracts "foo" into outEntry.
301 // Extracts ".xml" into outSuffix.
302 //
303 // Returns true if successful.
304 bool ExtractResFilePathParts(const android::StringPiece& path, android::StringPiece* out_prefix,
305                              android::StringPiece* out_entry, android::StringPiece* out_suffix);
306 
307 }  // namespace util
308 
309 // Stream operator for functions. Calls the function with the stream as an argument.
310 // In the aapt namespace for lookup.
311 inline ::std::ostream& operator<<(::std::ostream& out,
312                                   const ::std::function<::std::ostream&(::std::ostream&)>& f) {
313   return f(out);
314 }
315 
316 }  // namespace aapt
317 
318 #endif  // AAPT_UTIL_H
319