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