blob: 9ecc974d3a1ca3f65fa4024a5b9b6e1068a55b2d [file] [log] [blame]
Adam Lesinski6f6ceb72014-11-14 14:48:12 -08001/*
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
Adam Lesinski1ab598f2015-08-14 14:26:04 -070017#include "util/BigBuffer.h"
18#include "util/Maybe.h"
19#include "util/StringPiece.h"
20#include "util/Util.h"
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080021
22#include <algorithm>
23#include <ostream>
24#include <string>
25#include <utils/Unicode.h>
26#include <vector>
27
28namespace aapt {
29namespace util {
30
31static std::vector<std::string> splitAndTransform(const StringPiece& str, char sep,
32 const std::function<char(char)>& f) {
33 std::vector<std::string> parts;
34 const StringPiece::const_iterator end = std::end(str);
35 StringPiece::const_iterator start = std::begin(str);
36 StringPiece::const_iterator current;
37 do {
38 current = std::find(start, end, sep);
39 parts.emplace_back(str.substr(start, current).toString());
40 if (f) {
41 std::string& part = parts.back();
42 std::transform(part.begin(), part.end(), part.begin(), f);
43 }
44 start = current + 1;
45 } while (current != end);
46 return parts;
47}
48
49std::vector<std::string> split(const StringPiece& str, char sep) {
50 return splitAndTransform(str, sep, nullptr);
51}
52
53std::vector<std::string> splitAndLowercase(const StringPiece& str, char sep) {
54 return splitAndTransform(str, sep, ::tolower);
55}
56
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080057StringPiece16 trimWhitespace(const StringPiece16& str) {
58 if (str.size() == 0 || str.data() == nullptr) {
59 return str;
60 }
61
62 const char16_t* start = str.data();
63 const char16_t* end = str.data() + str.length();
64
65 while (start != end && util::isspace16(*start)) {
66 start++;
67 }
68
69 while (end != start && util::isspace16(*(end - 1))) {
70 end--;
71 }
72
73 return StringPiece16(start, end - start);
74}
75
Adam Lesinski3b4cd942015-10-30 16:31:42 -070076StringPiece trimWhitespace(const StringPiece& str) {
77 if (str.size() == 0 || str.data() == nullptr) {
78 return str;
79 }
80
81 const char* start = str.data();
82 const char* end = str.data() + str.length();
83
84 while (start != end && isspace(*start)) {
85 start++;
86 }
87
88 while (end != start && isspace(*(end - 1))) {
89 end--;
90 }
91
92 return StringPiece(start, end - start);
93}
94
Adam Lesinski6f6ceb72014-11-14 14:48:12 -080095StringPiece16::const_iterator findNonAlphaNumericAndNotInSet(const StringPiece16& str,
96 const StringPiece16& allowedChars) {
97 const auto endIter = str.end();
98 for (auto iter = str.begin(); iter != endIter; ++iter) {
99 char16_t c = *iter;
100 if ((c >= u'a' && c <= u'z') ||
101 (c >= u'A' && c <= u'Z') ||
102 (c >= u'0' && c <= u'9')) {
103 continue;
104 }
105
106 bool match = false;
107 for (char16_t i : allowedChars) {
108 if (c == i) {
109 match = true;
110 break;
111 }
112 }
113
114 if (!match) {
115 return iter;
116 }
117 }
118 return endIter;
119}
120
Adam Lesinskia1ad4a82015-06-08 11:41:09 -0700121bool isJavaClassName(const StringPiece16& str) {
122 size_t pieces = 0;
123 for (const StringPiece16& piece : tokenize(str, u'.')) {
124 pieces++;
125 if (piece.empty()) {
126 return false;
127 }
128
129 // Can't have starting or trailing $ character.
130 if (piece.data()[0] == u'$' || piece.data()[piece.size() - 1] == u'$') {
131 return false;
132 }
133
134 if (findNonAlphaNumericAndNotInSet(piece, u"$_") != piece.end()) {
135 return false;
136 }
137 }
138 return pieces >= 2;
139}
140
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700141bool isJavaPackageName(const StringPiece16& str) {
142 if (str.empty()) {
143 return false;
144 }
145
146 size_t pieces = 0;
147 for (const StringPiece16& piece : tokenize(str, u'.')) {
148 pieces++;
149 if (piece.empty()) {
150 return false;
151 }
152
153 if (piece.data()[0] == u'_' || piece.data()[piece.size() - 1] == u'_') {
154 return false;
155 }
156
157 if (findNonAlphaNumericAndNotInSet(piece, u"_") != piece.end()) {
158 return false;
159 }
160 }
161 return pieces >= 1;
162}
163
Adam Lesinskia1ad4a82015-06-08 11:41:09 -0700164Maybe<std::u16string> getFullyQualifiedClassName(const StringPiece16& package,
165 const StringPiece16& className) {
166 if (className.empty()) {
167 return {};
168 }
169
170 if (util::isJavaClassName(className)) {
171 return className.toString();
172 }
173
174 if (package.empty()) {
175 return {};
176 }
177
178 std::u16string result(package.data(), package.size());
179 if (className.data()[0] != u'.') {
180 result += u'.';
181 }
182 result.append(className.data(), className.size());
183 if (!isJavaClassName(result)) {
184 return {};
185 }
186 return result;
187}
188
Adam Lesinskib23f1e02015-11-03 12:24:17 -0800189static size_t consumeDigits(const char16_t* start, const char16_t* end) {
190 const char16_t* c = start;
191 for (; c != end && *c >= u'0' && *c <= u'9'; c++) {}
192 return static_cast<size_t>(c - start);
193}
194
195bool verifyJavaStringFormat(const StringPiece16& str) {
196 const char16_t* c = str.begin();
197 const char16_t* const end = str.end();
198
199 size_t argCount = 0;
200 bool nonpositional = false;
201 while (c != end) {
202 if (*c == u'%' && c + 1 < end) {
203 c++;
204
205 if (*c == u'%') {
206 c++;
207 continue;
208 }
209
210 argCount++;
211
212 size_t numDigits = consumeDigits(c, end);
213 if (numDigits > 0) {
214 c += numDigits;
215 if (c != end && *c != u'$') {
216 // The digits were a size, but not a positional argument.
217 nonpositional = true;
218 }
219 } else if (*c == u'<') {
220 // Reusing last argument, bad idea since positions can be moved around
221 // during translation.
222 nonpositional = true;
223
224 c++;
225
226 // Optionally we can have a $ after
227 if (c != end && *c == u'$') {
228 c++;
229 }
230 } else {
231 nonpositional = true;
232 }
233
234 // Ignore size, width, flags, etc.
235 while (c != end && (*c == u'-' ||
236 *c == u'#' ||
237 *c == u'+' ||
238 *c == u' ' ||
239 *c == u',' ||
240 *c == u'(' ||
241 (*c >= u'0' && *c <= '9'))) {
242 c++;
243 }
244
245 /*
246 * This is a shortcut to detect strings that are going to Time.format()
247 * instead of String.format()
248 *
249 * Comparison of String.format() and Time.format() args:
250 *
251 * String: ABC E GH ST X abcdefgh nost x
252 * Time: DEFGHKMS W Za d hkm s w yz
253 *
254 * Therefore we know it's definitely Time if we have:
255 * DFKMWZkmwyz
256 */
257 if (c != end) {
258 switch (*c) {
259 case 'D':
260 case 'F':
261 case 'K':
262 case 'M':
263 case 'W':
264 case 'Z':
265 case 'k':
266 case 'm':
267 case 'w':
268 case 'y':
269 case 'z':
270 return true;
271 }
272 }
273 }
274
275 if (c != end) {
276 c++;
277 }
278 }
279
280 if (argCount > 1 && nonpositional) {
281 // Multiple arguments were specified, but some or all were non positional. Translated
282 // strings may rearrange the order of the arguments, which will break the string.
283 return false;
284 }
285 return true;
286}
287
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800288static Maybe<char16_t> parseUnicodeCodepoint(const char16_t** start, const char16_t* end) {
289 char16_t code = 0;
290 for (size_t i = 0; i < 4 && *start != end; i++, (*start)++) {
291 char16_t c = **start;
292 int a;
293 if (c >= '0' && c <= '9') {
294 a = c - '0';
295 } else if (c >= 'a' && c <= 'f') {
296 a = c - 'a' + 10;
297 } else if (c >= 'A' && c <= 'F') {
298 a = c - 'A' + 10;
299 } else {
300 return make_nothing<char16_t>();
301 }
302 code = (code << 4) | a;
303 }
304 return make_value(code);
305}
306
307StringBuilder& StringBuilder::append(const StringPiece16& str) {
308 if (!mError.empty()) {
309 return *this;
310 }
311
312 const char16_t* const end = str.end();
313 const char16_t* start = str.begin();
314 const char16_t* current = start;
315 while (current != end) {
Adam Lesinski90959882015-07-06 18:09:18 -0700316 if (mLastCharWasEscape) {
317 switch (*current) {
318 case u't':
319 mStr += u'\t';
320 break;
321 case u'n':
322 mStr += u'\n';
323 break;
324 case u'#':
325 mStr += u'#';
326 break;
327 case u'@':
328 mStr += u'@';
329 break;
330 case u'?':
331 mStr += u'?';
332 break;
333 case u'"':
334 mStr += u'"';
335 break;
336 case u'\'':
337 mStr += u'\'';
338 break;
339 case u'\\':
340 mStr += u'\\';
341 break;
342 case u'u': {
343 current++;
344 Maybe<char16_t> c = parseUnicodeCodepoint(&current, end);
345 if (!c) {
346 mError = "invalid unicode escape sequence";
347 return *this;
348 }
349 mStr += c.value();
350 current -= 1;
351 break;
352 }
353
354 default:
355 // Ignore.
356 break;
357 }
358 mLastCharWasEscape = false;
359 start = current + 1;
360 } else if (*current == u'"') {
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800361 if (!mQuote && mTrailingSpace) {
362 // We found an opening quote, and we have
363 // trailing space, so we should append that
364 // space now.
365 if (mTrailingSpace) {
366 // We had trailing whitespace, so
367 // replace with a single space.
368 if (!mStr.empty()) {
369 mStr += u' ';
370 }
371 mTrailingSpace = false;
372 }
373 }
374 mQuote = !mQuote;
375 mStr.append(start, current - start);
376 start = current + 1;
377 } else if (*current == u'\'' && !mQuote) {
378 // This should be escaped.
379 mError = "unescaped apostrophe";
380 return *this;
381 } else if (*current == u'\\') {
382 // This is an escape sequence, convert to the real value.
383 if (!mQuote && mTrailingSpace) {
384 // We had trailing whitespace, so
385 // replace with a single space.
386 if (!mStr.empty()) {
387 mStr += u' ';
388 }
389 mTrailingSpace = false;
390 }
391 mStr.append(start, current - start);
392 start = current + 1;
Adam Lesinski90959882015-07-06 18:09:18 -0700393 mLastCharWasEscape = true;
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800394 } else if (!mQuote) {
395 // This is not quoted text, so look for whitespace.
396 if (isspace16(*current)) {
397 // We found whitespace, see if we have seen some
398 // before.
399 if (!mTrailingSpace) {
400 // We didn't see a previous adjacent space,
401 // so mark that we did.
402 mTrailingSpace = true;
403 mStr.append(start, current - start);
404 }
405
406 // Keep skipping whitespace.
407 start = current + 1;
408 } else if (mTrailingSpace) {
409 // We saw trailing space before, so replace all
410 // that trailing space with one space.
411 if (!mStr.empty()) {
412 mStr += u' ';
413 }
414 mTrailingSpace = false;
415 }
416 }
417 current++;
418 }
419 mStr.append(start, end - start);
420 return *this;
421}
422
423std::u16string utf8ToUtf16(const StringPiece& utf8) {
424 ssize_t utf16Length = utf8_to_utf16_length(reinterpret_cast<const uint8_t*>(utf8.data()),
425 utf8.length());
426 if (utf16Length <= 0) {
427 return {};
428 }
429
430 std::u16string utf16;
431 utf16.resize(utf16Length);
432 utf8_to_utf16(reinterpret_cast<const uint8_t*>(utf8.data()), utf8.length(), &*utf16.begin());
433 return utf16;
434}
435
436std::string utf16ToUtf8(const StringPiece16& utf16) {
437 ssize_t utf8Length = utf16_to_utf8_length(utf16.data(), utf16.length());
438 if (utf8Length <= 0) {
439 return {};
440 }
441
442 std::string utf8;
443 utf8.resize(utf8Length);
444 utf16_to_utf8(utf16.data(), utf16.length(), &*utf8.begin());
445 return utf8;
446}
447
448bool writeAll(std::ostream& out, const BigBuffer& buffer) {
449 for (const auto& b : buffer) {
450 if (!out.write(reinterpret_cast<const char*>(b.buffer.get()), b.size)) {
451 return false;
452 }
453 }
454 return true;
455}
456
457std::unique_ptr<uint8_t[]> copy(const BigBuffer& buffer) {
458 std::unique_ptr<uint8_t[]> data = std::unique_ptr<uint8_t[]>(new uint8_t[buffer.size()]);
459 uint8_t* p = data.get();
460 for (const auto& block : buffer) {
461 memcpy(p, block.buffer.get(), block.size);
462 p += block.size;
463 }
464 return data;
465}
466
Adam Lesinski1ab598f2015-08-14 14:26:04 -0700467bool extractResFilePathParts(const StringPiece16& path, StringPiece16* outPrefix,
468 StringPiece16* outEntry, StringPiece16* outSuffix) {
469 if (!stringStartsWith<char16_t>(path, u"res/")) {
470 return false;
471 }
472
473 StringPiece16::const_iterator lastOccurence = path.end();
474 for (auto iter = path.begin() + StringPiece16(u"res/").size(); iter != path.end(); ++iter) {
475 if (*iter == u'/') {
476 lastOccurence = iter;
477 }
478 }
479
480 if (lastOccurence == path.end()) {
481 return false;
482 }
483
484 auto iter = std::find(lastOccurence, path.end(), u'.');
485 *outSuffix = StringPiece16(iter, path.end() - iter);
486 *outEntry = StringPiece16(lastOccurence + 1, iter - lastOccurence - 1);
487 *outPrefix = StringPiece16(path.begin(), lastOccurence - path.begin() + 1);
488 return true;
489}
490
Adam Lesinski6f6ceb72014-11-14 14:48:12 -0800491} // namespace util
492} // namespace aapt