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