1 /*
2  * Copyright (C) 2017 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 #include "slicer/dex_format.h"
18 
19 namespace dex {
20 
21 // Retrieve the next UTF-16 character from a UTF-8 string.
22 // Advances "*pUtf8Ptr" to the start of the next character.
23 //
24 // NOTE: If a string is corrupted by dropping a '\0' in the middle
25 // of a 3-byte sequence, you can end up overrunning the buffer with
26 // reads (and possibly with the writes if the length was computed and
27 // cached before the damage). For performance reasons, this function
28 // assumes that the string being parsed is known to be valid (e.g., by
29 // already being verified).
GetUtf16FromUtf8(const char ** pUtf8Ptr)30 static u2 GetUtf16FromUtf8(const char** pUtf8Ptr) {
31   u4 one = *(*pUtf8Ptr)++;
32   if ((one & 0x80) != 0) {
33     // two- or three-byte encoding
34     u4 two = *(*pUtf8Ptr)++;
35     if ((one & 0x20) != 0) {
36       // three-byte encoding
37       u4 three = *(*pUtf8Ptr)++;
38       return ((one & 0x0f) << 12) | ((two & 0x3f) << 6) | (three & 0x3f);
39     } else {
40       // two-byte encoding
41       return ((one & 0x1f) << 6) | (two & 0x3f);
42     }
43   } else {
44     // one-byte encoding
45     return one;
46   }
47 }
48 
Utf8Cmp(const char * s1,const char * s2)49 int Utf8Cmp(const char* s1, const char* s2) {
50   for (;;) {
51     if (*s1 == '\0') {
52       if (*s2 == '\0') {
53         return 0;
54       }
55       return -1;
56     } else if (*s2 == '\0') {
57       return 1;
58     }
59 
60     int utf1 = GetUtf16FromUtf8(&s1);
61     int utf2 = GetUtf16FromUtf8(&s2);
62     int diff = utf1 - utf2;
63 
64     if (diff != 0) {
65       return diff;
66     }
67   }
68 }
69 
70 }  // namespace dex
71