2 * Copyright (C) 2008 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
18 * UTF-8 and Unicode string manipulation, plus java/lang/String convenience
21 * In most cases we populate the fields in the String object directly,
22 * rather than going through an instance field lookup.
28 * Initialize string globals.
30 * This isn't part of the VM init sequence because it's hard to get the
31 * timing right -- we need it to happen after java/lang/String has been
32 * loaded, but before anybody wants to use a string. It's easiest to
33 * just initialize it on first use.
35 * In some unusual circumstances (e.g. trying to throw an exception because
36 * String implements java/lang/CharSequence, but CharSequence doesn't exist)
37 * we can try to create an exception string internally before anything has
38 * really tried to use String. In that case we basically self-destruct.
40 static bool stringStartup()
42 if (gDvm.javaLangStringReady < 0) {
43 LOGE("ERROR: reentrant string initialization\n");
47 assert(gDvm.javaLangStringReady == 0);
49 gDvm.javaLangStringReady = -1;
51 if (gDvm.classJavaLangString == NULL)
52 gDvm.classJavaLangString =
53 dvmFindSystemClassNoInit("Ljava/lang/String;");
55 gDvm.offJavaLangString_value =
56 dvmFindFieldOffset(gDvm.classJavaLangString, "value", "[C");
57 gDvm.offJavaLangString_count =
58 dvmFindFieldOffset(gDvm.classJavaLangString, "count", "I");
59 gDvm.offJavaLangString_offset =
60 dvmFindFieldOffset(gDvm.classJavaLangString, "offset", "I");
61 gDvm.offJavaLangString_hashCode =
62 dvmFindFieldOffset(gDvm.classJavaLangString, "hashCode", "I");
64 if (gDvm.offJavaLangString_value < 0 ||
65 gDvm.offJavaLangString_count < 0 ||
66 gDvm.offJavaLangString_offset < 0 ||
67 gDvm.offJavaLangString_hashCode < 0)
69 LOGE("VM-required field missing from java/lang/String\n");
73 bool badValue = false;
74 if (gDvm.offJavaLangString_value != STRING_FIELDOFF_VALUE) {
75 LOGE("InlineNative: String.value offset = %d, expected %d\n",
76 gDvm.offJavaLangString_value, STRING_FIELDOFF_VALUE);
79 if (gDvm.offJavaLangString_count != STRING_FIELDOFF_COUNT) {
80 LOGE("InlineNative: String.count offset = %d, expected %d\n",
81 gDvm.offJavaLangString_count, STRING_FIELDOFF_COUNT);
84 if (gDvm.offJavaLangString_offset != STRING_FIELDOFF_OFFSET) {
85 LOGE("InlineNative: String.offset offset = %d, expected %d\n",
86 gDvm.offJavaLangString_offset, STRING_FIELDOFF_OFFSET);
89 if (gDvm.offJavaLangString_hashCode != STRING_FIELDOFF_HASHCODE) {
90 LOGE("InlineNative: String.hashCode offset = %d, expected %d\n",
91 gDvm.offJavaLangString_hashCode, STRING_FIELDOFF_HASHCODE);
97 gDvm.javaLangStringReady = 1;
103 * Discard heap-allocated storage.
105 void dvmStringShutdown()
111 * Compute a hash code on a UTF-8 string, for use with internal hash tables.
113 * This may or may not yield the same results as the java/lang/String
114 * computeHashCode() function. (To make sure this doesn't get abused,
115 * I'm initializing the hash code to 1 so they *don't* match up.)
117 * It would be more correct to invoke dexGetUtf16FromUtf8() here and compute
118 * the hash with the result. That way, if something encoded the same
119 * character in two different ways, the hash value would be the same. For
120 * our purposes that isn't necessary.
122 u4 dvmComputeUtf8Hash(const char* utf8Str)
126 while (*utf8Str != '\0')
127 hash = hash * 31 + *utf8Str++;
133 * Like "strlen", but for strings encoded with "modified" UTF-8.
135 * The value returned is the number of characters, which may or may not
136 * be the same as the number of bytes.
138 * (If this needs optimizing, try: mask against 0xa0, shift right 5,
139 * get increment {1-3} from table of 8 values.)
141 int dvmUtf8Len(const char* utf8Str)
145 while ((ic = *utf8Str++) != '\0') {
147 if ((ic & 0x80) != 0) {
148 /* two- or three-byte encoding */
150 if ((ic & 0x20) != 0) {
151 /* three-byte encoding */
161 * Convert a "modified" UTF-8 string to UTF-16.
163 void dvmConvertUtf8ToUtf16(u2* utf16Str, const char* utf8Str)
165 while (*utf8Str != '\0')
166 *utf16Str++ = dexGetUtf16FromUtf8(&utf8Str);
170 * Given a UTF-16 string, compute the length of the corresponding UTF-8
173 static int utf16_utf8ByteLen(const u2* utf16Str, int len)
178 unsigned int uic = *utf16Str++;
181 * The most common case is (uic > 0 && uic <= 0x7f).
183 if (uic == 0 || uic > 0x7f) {
186 else /*(uic > 0x7f || uic == 0) */
195 * Convert a UTF-16 string to UTF-8.
197 * Make sure you allocate "utf8Str" with the result of utf16_utf8ByteLen(),
200 static void convertUtf16ToUtf8(char* utf8Str, const u2* utf16Str, int len)
205 unsigned int uic = *utf16Str++;
208 * The most common case is (uic > 0 && uic <= 0x7f).
210 if (uic == 0 || uic > 0x7f) {
212 *utf8Str++ = (uic >> 12) | 0xe0;
213 *utf8Str++ = ((uic >> 6) & 0x3f) | 0x80;
214 *utf8Str++ = (uic & 0x3f) | 0x80;
215 } else /*(uic > 0x7f || uic == 0)*/ {
216 *utf8Str++ = (uic >> 6) | 0xc0;
217 *utf8Str++ = (uic & 0x3f) | 0x80;
228 * Use the java/lang/String.computeHashCode() algorithm.
230 static inline u4 dvmComputeUtf16Hash(const u2* utf16Str, int len)
235 hash = hash * 31 + *utf16Str++;
239 u4 dvmComputeStringHash(StringObject* strObj) {
240 ArrayObject* chars = (ArrayObject*) dvmGetFieldObject((Object*) strObj,
241 STRING_FIELDOFF_VALUE);
244 len = dvmGetFieldInt((Object*) strObj, STRING_FIELDOFF_COUNT);
245 offset = dvmGetFieldInt((Object*) strObj, STRING_FIELDOFF_OFFSET);
247 return dvmComputeUtf16Hash((u2*) chars->contents + offset, len);
251 * Create a new java/lang/String object, using the string data in "utf8Str".
253 * Note that "allocFlags" affects both of the allocations here. If you
254 * use ALLOC_DONT_TRACK in a context where a GC could happen between the
255 * two allocations, you could lose the array reference.
257 * Returns NULL and throws an exception on failure.
259 StringObject* dvmCreateStringFromCstr(const char* utf8Str, int allocFlags)
261 assert(utf8Str != NULL);
263 return dvmCreateStringFromCstrAndLength(utf8Str, dvmUtf8Len(utf8Str),
268 * Create a java/lang/String from a C string, given its UTF-16 length
269 * (number of UTF-16 code points).
271 * The caller must call dvmReleaseTrackedAlloc() on the return value or
272 * use a non-default value for "allocFlags". It is never appropriate
273 * to use ALLOC_DONT_TRACK with this function.
275 * Returns NULL and throws an exception on failure.
277 StringObject* dvmCreateStringFromCstrAndLength(const char* utf8Str,
278 u4 utf16Length, int allocFlags)
280 StringObject* newObj;
284 //LOGV("Creating String from '%s'\n", utf8Str);
285 assert(allocFlags != ALLOC_DONT_TRACK); /* don't currently need */
286 assert(utf8Str != NULL);
288 if (gDvm.javaLangStringReady <= 0) {
289 if (!stringStartup())
293 /* init before alloc */
294 if (!dvmIsClassInitialized(gDvm.classJavaLangString) &&
295 !dvmInitClass(gDvm.classJavaLangString))
300 newObj = (StringObject*) dvmAllocObject(gDvm.classJavaLangString,
305 chars = dvmAllocPrimitiveArray('C', utf16Length, allocFlags);
307 dvmReleaseTrackedAllocIFN((Object*) newObj, NULL, allocFlags);
310 dvmConvertUtf8ToUtf16((u2*)chars->contents, utf8Str);
311 hashCode = dvmComputeUtf16Hash((u2*) chars->contents, utf16Length);
313 dvmSetFieldObject((Object*)newObj, STRING_FIELDOFF_VALUE,
315 dvmReleaseTrackedAllocIFN((Object*) chars, NULL, allocFlags);
316 dvmSetFieldInt((Object*)newObj, STRING_FIELDOFF_COUNT, utf16Length);
317 dvmSetFieldInt((Object*)newObj, STRING_FIELDOFF_HASHCODE, hashCode);
318 /* leave offset set to zero */
320 /* debugging stuff */
321 //dvmDumpObject((Object*)newObj);
322 //printHexDumpEx(ANDROID_LOG_DEBUG, chars->contents, utf16Length * 2,
325 /* caller may need to dvmReleaseTrackedAlloc(newObj) */
330 * Create a new java/lang/String object, using the Unicode data.
332 StringObject* dvmCreateStringFromUnicode(const u2* unichars, int len)
334 StringObject* newObj;
338 /* we allow a null pointer if the length is zero */
339 assert(len == 0 || unichars != NULL);
341 if (gDvm.javaLangStringReady <= 0) {
342 if (!stringStartup())
346 /* init before alloc */
347 if (!dvmIsClassInitialized(gDvm.classJavaLangString) &&
348 !dvmInitClass(gDvm.classJavaLangString))
353 newObj = (StringObject*) dvmAllocObject(gDvm.classJavaLangString,
358 chars = dvmAllocPrimitiveArray('C', len, ALLOC_DEFAULT);
360 dvmReleaseTrackedAlloc((Object*) newObj, NULL);
364 memcpy(chars->contents, unichars, len * sizeof(u2));
365 hashCode = dvmComputeUtf16Hash((u2*) chars->contents, len);
367 dvmSetFieldObject((Object*)newObj, STRING_FIELDOFF_VALUE,
369 dvmReleaseTrackedAlloc((Object*) chars, NULL);
370 dvmSetFieldInt((Object*)newObj, STRING_FIELDOFF_COUNT, len);
371 dvmSetFieldInt((Object*)newObj, STRING_FIELDOFF_HASHCODE, hashCode);
372 /* leave offset set to zero */
374 /* debugging stuff */
375 //dvmDumpObject((Object*)newObj);
376 //printHexDumpEx(ANDROID_LOG_DEBUG, chars->contents, len*2, kHexDumpMem);
378 /* caller must dvmReleaseTrackedAlloc(newObj) */
383 * Create a new C string from a java/lang/String object.
385 * Returns NULL if the object is NULL.
387 char* dvmCreateCstrFromString(StringObject* jstr)
391 int len, byteLen, offset;
394 assert(gDvm.javaLangStringReady > 0);
399 len = dvmGetFieldInt((Object*) jstr, STRING_FIELDOFF_COUNT);
400 offset = dvmGetFieldInt((Object*) jstr, STRING_FIELDOFF_OFFSET);
401 chars = (ArrayObject*) dvmGetFieldObject((Object*) jstr,
402 STRING_FIELDOFF_VALUE);
403 data = (const u2*) chars->contents + offset;
404 assert(offset + len <= (int) chars->length);
406 byteLen = utf16_utf8ByteLen(data, len);
407 newStr = (char*) malloc(byteLen+1);
410 convertUtf16ToUtf8(newStr, data, len);
416 * Create a UTF-8 C string from a region of a java/lang/String. (Used by
417 * the JNI GetStringUTFRegion call.)
419 void dvmCreateCstrFromStringRegion(StringObject* jstr, int start, int len,
424 data = dvmStringChars(jstr) + start;
425 convertUtf16ToUtf8(buf, data, len);
429 * Compute the length, in modified UTF-8, of a java/lang/String object.
431 * Does not include the terminating null byte.
433 int dvmStringUtf8ByteLen(StringObject* jstr)
439 assert(gDvm.javaLangStringReady > 0);
442 return 0; // should we throw something? assert?
444 len = dvmGetFieldInt((Object*) jstr, STRING_FIELDOFF_COUNT);
445 offset = dvmGetFieldInt((Object*) jstr, STRING_FIELDOFF_OFFSET);
446 chars = (ArrayObject*) dvmGetFieldObject((Object*) jstr,
447 STRING_FIELDOFF_VALUE);
448 data = (const u2*) chars->contents + offset;
449 assert(offset + len <= (int) chars->length);
451 return utf16_utf8ByteLen(data, len);
455 * Get the string's length.
457 int dvmStringLen(StringObject* jstr)
459 return dvmGetFieldInt((Object*) jstr, STRING_FIELDOFF_COUNT);
463 * Get the char[] object from the String.
465 ArrayObject* dvmStringCharArray(StringObject* jstr)
467 return (ArrayObject*) dvmGetFieldObject((Object*) jstr,
468 STRING_FIELDOFF_VALUE);
472 * Get the string's data.
474 const u2* dvmStringChars(StringObject* jstr)
479 offset = dvmGetFieldInt((Object*) jstr, STRING_FIELDOFF_OFFSET);
480 chars = (ArrayObject*) dvmGetFieldObject((Object*) jstr,
481 STRING_FIELDOFF_VALUE);
482 return (const u2*) chars->contents + offset;
487 * Compare two String objects.
489 * This is a dvmHashTableLookup() callback. The function has already
490 * compared their hash values; we need to do a full compare to ensure
491 * that the strings really match.
493 int dvmHashcmpStrings(const void* vstrObj1, const void* vstrObj2)
495 const StringObject* strObj1 = (const StringObject*) vstrObj1;
496 const StringObject* strObj2 = (const StringObject*) vstrObj2;
499 int len1, len2, offset1, offset2;
501 assert(gDvm.javaLangStringReady > 0);
503 /* get offset and length into char array; all values are in 16-bit units */
504 len1 = dvmGetFieldInt((Object*) strObj1, STRING_FIELDOFF_COUNT);
505 offset1 = dvmGetFieldInt((Object*) strObj1, STRING_FIELDOFF_OFFSET);
506 len2 = dvmGetFieldInt((Object*) strObj2, STRING_FIELDOFF_COUNT);
507 offset2 = dvmGetFieldInt((Object*) strObj2, STRING_FIELDOFF_OFFSET);
511 chars1 = (ArrayObject*) dvmGetFieldObject((Object*) strObj1,
512 STRING_FIELDOFF_VALUE);
513 chars2 = (ArrayObject*) dvmGetFieldObject((Object*) strObj2,
514 STRING_FIELDOFF_VALUE);
516 /* damage here actually indicates a broken java/lang/String */
517 assert(offset1 + len1 <= (int) chars1->length);
518 assert(offset2 + len2 <= (int) chars2->length);
520 return memcmp((const u2*) chars1->contents + offset1,
521 (const u2*) chars2->contents + offset2,