1 /*
2  * Copyright (C) 2010 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 "libcore_util_CharsetUtils.h"
18 
19 #include <string.h>
20 
21 #include "handle_scope-inl.h"
22 #include "jni/jni_internal.h"
23 #include "mirror/string-inl.h"
24 #include "mirror/string.h"
25 #include "native_util.h"
26 #include "nativehelper/scoped_primitive_array.h"
27 #include "nativehelper/jni_macros.h"
28 #include "scoped_fast_native_object_access-inl.h"
29 #include "unicode/utf16.h"
30 
31 namespace art {
32 
CharsetUtils_asciiBytesToChars(JNIEnv * env,jclass,jbyteArray javaBytes,jint offset,jint length,jcharArray javaChars)33 static void CharsetUtils_asciiBytesToChars(JNIEnv* env, jclass, jbyteArray javaBytes, jint offset,
34                                            jint length, jcharArray javaChars) {
35   ScopedByteArrayRO bytes(env, javaBytes);
36   if (bytes.get() == nullptr) {
37     return;
38   }
39   ScopedCharArrayRW chars(env, javaChars);
40   if (chars.get() == nullptr) {
41     return;
42   }
43 
44   const jbyte* src = &bytes[offset];
45   jchar* dst = &chars[0];
46   static const jchar REPLACEMENT_CHAR = 0xfffd;
47   for (int i = length - 1; i >= 0; --i) {
48     jchar ch = static_cast<jchar>(*src++ & 0xff);
49     *dst++ = (ch <= 0x7f) ? ch : REPLACEMENT_CHAR;
50   }
51 }
52 
CharsetUtils_isoLatin1BytesToChars(JNIEnv * env,jclass,jbyteArray javaBytes,jint offset,jint length,jcharArray javaChars)53 static void CharsetUtils_isoLatin1BytesToChars(JNIEnv* env, jclass, jbyteArray javaBytes,
54                                                jint offset, jint length, jcharArray javaChars) {
55   ScopedByteArrayRO bytes(env, javaBytes);
56   if (bytes.get() == nullptr) {
57     return;
58   }
59   ScopedCharArrayRW chars(env, javaChars);
60   if (chars.get() == nullptr) {
61     return;
62   }
63 
64   const jbyte* src = &bytes[offset];
65   jchar* dst = &chars[0];
66   for (int i = length - 1; i >= 0; --i) {
67     *dst++ = static_cast<jchar>(*src++ & 0xff);
68   }
69 }
70 
71 /**
72  * Translates the given characters to US-ASCII or ISO-8859-1 bytes, using the fact that
73  * Unicode code points between U+0000 and U+007f inclusive are identical to US-ASCII, while
74  * U+0000 to U+00ff inclusive are identical to ISO-8859-1.
75  */
charsToBytes(JNIEnv * env,jstring java_string,jint offset,jint length,jchar maxValidChar)76 static jbyteArray charsToBytes(JNIEnv* env, jstring java_string, jint offset, jint length,
77                                jchar maxValidChar) {
78   ScopedFastNativeObjectAccess soa(env);
79   StackHandleScope<1> hs(soa.Self());
80   Handle<mirror::String> string(hs.NewHandle(soa.Decode<mirror::String>(java_string)));
81   if (string == nullptr) {
82     return nullptr;
83   }
84 
85   ObjPtr<mirror::ByteArray> result = mirror::ByteArray::Alloc(soa.Self(), length);
86   if (result == nullptr) {
87     return nullptr;
88   }
89 
90   if (string->IsCompressed()) {
91     // All characters in a compressed string are ASCII and therefore do not need a replacement.
92     DCHECK_GE(maxValidChar, 0x7f);
93     memcpy(result->GetData(), string->GetValueCompressed() + offset, length);
94   } else {
95     const uint16_t* src = string->GetValue() + offset;
96     auto clamp = [maxValidChar](uint16_t c) {
97       return static_cast<jbyte>(dchecked_integral_cast<uint8_t>((c > maxValidChar) ? '?' : c));
98     };
99     std::transform(src, src + length, result->GetData(), clamp);
100   }
101   return soa.AddLocalReference<jbyteArray>(result);
102 }
103 
CharsetUtils_toAsciiBytes(JNIEnv * env,jclass,jstring java_string,jint offset,jint length)104 static jbyteArray CharsetUtils_toAsciiBytes(JNIEnv* env, jclass, jstring java_string, jint offset,
105                                             jint length) {
106     return charsToBytes(env, java_string, offset, length, 0x7f);
107 }
108 
CharsetUtils_toIsoLatin1Bytes(JNIEnv * env,jclass,jstring java_string,jint offset,jint length)109 static jbyteArray CharsetUtils_toIsoLatin1Bytes(JNIEnv* env, jclass, jstring java_string,
110                                                 jint offset, jint length) {
111     return charsToBytes(env, java_string, offset, length, 0xff);
112 }
113 
CharsetUtils_toUtf8Bytes(JNIEnv * env,jclass,jstring java_string,jint offset,jint length)114 static jbyteArray CharsetUtils_toUtf8Bytes(JNIEnv* env, jclass, jstring java_string, jint offset,
115                                            jint length) {
116   ScopedFastNativeObjectAccess soa(env);
117   StackHandleScope<1> hs(soa.Self());
118   Handle<mirror::String> string(hs.NewHandle(soa.Decode<mirror::String>(java_string)));
119   if (string == nullptr) {
120     return nullptr;
121   }
122 
123   DCHECK_GE(offset, 0);
124   DCHECK_LE(offset, string->GetLength());
125   DCHECK_GE(length, 0);
126   DCHECK_LE(length, string->GetLength() - offset);
127 
128   auto visit_chars16 = [string, offset, length](auto append) REQUIRES_SHARED(Locks::mutator_lock_) {
129     const uint16_t* chars16 = string->GetValue() + offset;
130     for (int i = 0; i < length; ++i) {
131       jint ch = chars16[i];
132       if (ch < 0x80) {
133         // One byte.
134         append(ch);
135       } else if (ch < 0x800) {
136         // Two bytes.
137         append((ch >> 6) | 0xc0);
138         append((ch & 0x3f) | 0x80);
139       } else if (U16_IS_SURROGATE(ch)) {
140         // A supplementary character.
141         jchar high = static_cast<jchar>(ch);
142         jchar low = (i + 1 != length) ? chars16[i + 1] : 0;
143         if (!U16_IS_SURROGATE_LEAD(high) || !U16_IS_SURROGATE_TRAIL(low)) {
144           append('?');
145           continue;
146         }
147         // Now we know we have a *valid* surrogate pair, we can consume the low surrogate.
148         ++i;
149         ch = U16_GET_SUPPLEMENTARY(high, low);
150         // Four bytes.
151         append((ch >> 18) | 0xf0);
152         append(((ch >> 12) & 0x3f) | 0x80);
153         append(((ch >> 6) & 0x3f) | 0x80);
154         append((ch & 0x3f) | 0x80);
155       } else {
156         // Three bytes.
157         append((ch >> 12) | 0xe0);
158         append(((ch >> 6) & 0x3f) | 0x80);
159         append((ch & 0x3f) | 0x80);
160       }
161     }
162   };
163 
164   bool compressed = string->IsCompressed();
165   size_t utf8_length = 0;
166   if (compressed) {
167     utf8_length = length;
168   } else {
169     visit_chars16([&utf8_length](jbyte c ATTRIBUTE_UNUSED) { ++utf8_length; });
170   }
171   ObjPtr<mirror::ByteArray> result =
172       mirror::ByteArray::Alloc(soa.Self(), dchecked_integral_cast<int32_t>(utf8_length));
173   if (result == nullptr) {
174     return nullptr;
175   }
176 
177   if (compressed) {
178     memcpy(result->GetData(), string->GetValueCompressed() + offset, length);
179   } else {
180     int8_t* data = result->GetData();
181     visit_chars16([&data](jbyte c) { *data++ = c; });
182   }
183   return soa.AddLocalReference<jbyteArray>(result);
184 }
185 
186 static JNINativeMethod gMethods[] = {
187   FAST_NATIVE_METHOD(CharsetUtils, asciiBytesToChars, "([BII[C)V"),
188   FAST_NATIVE_METHOD(CharsetUtils, isoLatin1BytesToChars, "([BII[C)V"),
189   FAST_NATIVE_METHOD(CharsetUtils, toAsciiBytes, "(Ljava/lang/String;II)[B"),
190   FAST_NATIVE_METHOD(CharsetUtils, toIsoLatin1Bytes, "(Ljava/lang/String;II)[B"),
191   FAST_NATIVE_METHOD(CharsetUtils, toUtf8Bytes, "(Ljava/lang/String;II)[B"),
192 };
193 
register_libcore_util_CharsetUtils(JNIEnv * env)194 void register_libcore_util_CharsetUtils(JNIEnv* env) {
195   REGISTER_NATIVE_METHODS("libcore/util/CharsetUtils");
196 }
197 
198 }  // namespace art
199