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 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 // Converts the class name to a fully qualified class name from the given
92 // `package`. Ex:
93 //
94 // asdf         --> package.asdf
95 // .asdf        --> package.asdf
96 // .a.b         --> package.a.b
97 // asdf.adsf    --> asdf.adsf
98 Maybe<std::string> GetFullyQualifiedClassName(const android::StringPiece& package,
99                                               const android::StringPiece& class_name);
100 
101 // Retrieves the formatted name of aapt2.
102 const char* GetToolName();
103 
104 // Retrieves the build fingerprint of aapt2.
105 std::string GetToolFingerprint();
106 
107 template <typename T>
compare(const T & a,const T & b)108 typename std::enable_if<std::is_arithmetic<T>::value, int>::type compare(const T& a, const T& b) {
109   if (a < b) {
110     return -1;
111   } else if (a > b) {
112     return 1;
113   }
114   return 0;
115 }
116 
117 // Makes a std::unique_ptr<> with the template parameter inferred by the compiler.
118 // This will be present in C++14 and can be removed then.
119 template <typename T, class... Args>
make_unique(Args &&...args)120 std::unique_ptr<T> make_unique(Args&&... args) {
121   return std::unique_ptr<T>(new T{std::forward<Args>(args)...});
122 }
123 
124 // Writes a set of items to the std::ostream, joining the times with the provided separator.
125 template <typename Container>
Joiner(const Container & container,const char * sep)126 ::std::function<::std::ostream&(::std::ostream&)> Joiner(const Container& container,
127                                                          const char* sep) {
128   using std::begin;
129   using std::end;
130   const auto begin_iter = begin(container);
131   const auto end_iter = end(container);
132   return [begin_iter, end_iter, sep](::std::ostream& out) -> ::std::ostream& {
133     for (auto iter = begin_iter; iter != end_iter; ++iter) {
134       if (iter != begin_iter) {
135         out << sep;
136       }
137       out << *iter;
138     }
139     return out;
140   };
141 }
142 
143 // Helper method to extract a UTF-16 string from a StringPool. If the string is stored as UTF-8,
144 // the conversion to UTF-16 happens within ResStringPool.
145 android::StringPiece16 GetString16(const android::ResStringPool& pool, size_t idx);
146 
147 // Helper method to extract a UTF-8 string from a StringPool. If the string is stored as UTF-16,
148 // the conversion from UTF-16 to UTF-8 does not happen in ResStringPool and is done by this method,
149 // which maintains no state or cache. This means we must return an std::string copy.
150 std::string GetString(const android::ResStringPool& pool, size_t idx);
151 
152 // Checks that the Java string format contains no non-positional arguments (arguments without
153 // explicitly specifying an index) when there are more than one argument. This is an error
154 // because translations may rearrange the order of the arguments in the string, which will
155 // break the string interpolation.
156 bool VerifyJavaStringFormat(const android::StringPiece& str);
157 
158 bool AppendStyledString(const android::StringPiece& input, bool preserve_spaces,
159                         std::string* out_str, std::string* out_error);
160 
161 class StringBuilder {
162  public:
163   StringBuilder() = default;
164 
165   StringBuilder& Append(const android::StringPiece& str);
166   const std::string& ToString() const;
167   const std::string& Error() const;
168   bool IsEmpty() const;
169 
170   // When building StyledStrings, we need UTF-16 indices into the string,
171   // which is what the Java layer expects when dealing with java
172   // String.charAt().
173   size_t Utf16Len() const;
174 
175   explicit operator bool() const;
176 
177  private:
178   std::string str_;
179   size_t utf16_len_ = 0;
180   bool quote_ = false;
181   bool trailing_space_ = false;
182   bool last_char_was_escape_ = false;
183   std::string error_;
184 };
185 
ToString()186 inline const std::string& StringBuilder::ToString() const {
187   return str_;
188 }
189 
Error()190 inline const std::string& StringBuilder::Error() const {
191   return error_;
192 }
193 
IsEmpty()194 inline bool StringBuilder::IsEmpty() const {
195   return str_.empty();
196 }
197 
Utf16Len()198 inline size_t StringBuilder::Utf16Len() const {
199   return utf16_len_;
200 }
201 
202 inline StringBuilder::operator bool() const {
203   return error_.empty();
204 }
205 
206 // Converts a UTF8 string into Modified UTF8
207 std::string Utf8ToModifiedUtf8(const std::string& utf8);
208 std::string ModifiedUtf8ToUtf8(const std::string& modified_utf8);
209 
210 // Converts a UTF8 string to a UTF16 string.
211 std::u16string Utf8ToUtf16(const android::StringPiece& utf8);
212 std::string Utf16ToUtf8(const android::StringPiece16& utf16);
213 
214 // Writes the entire BigBuffer to the output stream.
215 bool WriteAll(std::ostream& out, const BigBuffer& buffer);
216 
217 // Copies the entire BigBuffer into a single buffer.
218 std::unique_ptr<uint8_t[]> Copy(const BigBuffer& buffer);
219 
220 // A Tokenizer implemented as an iterable collection. It does not allocate any memory on the heap
221 // nor use standard containers.
222 class Tokenizer {
223  public:
224   class iterator {
225    public:
226     using reference = android::StringPiece&;
227     using value_type = android::StringPiece;
228     using difference_type = size_t;
229     using pointer = android::StringPiece*;
230     using iterator_category = std::forward_iterator_tag;
231 
232     iterator(const iterator&) = default;
233     iterator& operator=(const iterator&) = default;
234 
235     iterator& operator++();
236 
237     android::StringPiece operator*() { return token_; }
238     bool operator==(const iterator& rhs) const;
239     bool operator!=(const iterator& rhs) const;
240 
241    private:
242     friend class Tokenizer;
243 
244     iterator(const android::StringPiece& s, char sep, const android::StringPiece& tok, bool end);
245 
246     android::StringPiece str_;
247     char separator_;
248     android::StringPiece token_;
249     bool end_;
250   };
251 
252   Tokenizer(const android::StringPiece& str, char sep);
253 
begin()254   iterator begin() const {
255     return begin_;
256   }
257 
end()258   iterator end() const {
259     return end_;
260   }
261 
262  private:
263   const iterator begin_;
264   const iterator end_;
265 };
266 
Tokenize(const android::StringPiece & str,char sep)267 inline Tokenizer Tokenize(const android::StringPiece& str, char sep) {
268   return Tokenizer(str, sep);
269 }
270 
HostToDevice16(uint16_t value)271 inline uint16_t HostToDevice16(uint16_t value) {
272   return htods(value);
273 }
274 
HostToDevice32(uint32_t value)275 inline uint32_t HostToDevice32(uint32_t value) {
276   return htodl(value);
277 }
278 
DeviceToHost16(uint16_t value)279 inline uint16_t DeviceToHost16(uint16_t value) {
280   return dtohs(value);
281 }
282 
DeviceToHost32(uint32_t value)283 inline uint32_t DeviceToHost32(uint32_t value) {
284   return dtohl(value);
285 }
286 
287 // Given a path like: res/xml-sw600dp/foo.xml
288 //
289 // Extracts "res/xml-sw600dp/" into outPrefix.
290 // Extracts "foo" into outEntry.
291 // Extracts ".xml" into outSuffix.
292 //
293 // Returns true if successful.
294 bool ExtractResFilePathParts(const android::StringPiece& path, android::StringPiece* out_prefix,
295                              android::StringPiece* out_entry, android::StringPiece* out_suffix);
296 
297 }  // namespace util
298 
299 // Stream operator for functions. Calls the function with the stream as an argument.
300 // In the aapt namespace for lookup.
301 inline ::std::ostream& operator<<(::std::ostream& out,
302                                   const ::std::function<::std::ostream&(::std::ostream&)>& f) {
303   return f(out);
304 }
305 
306 }  // namespace aapt
307 
308 #endif  // AAPT_UTIL_H
309