• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2011 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 "string-alloc-inl.h"
18 
19 #include "arch/memcmp16.h"
20 #include "array-alloc-inl.h"
21 #include "base/array_ref.h"
22 #include "base/casts.h"
23 #include "base/stl_util.h"
24 #include "class-inl.h"
25 #include "dex/descriptors_names.h"
26 #include "dex/utf-inl.h"
27 #include "gc/accounting/card_table-inl.h"
28 #include "handle_scope-inl.h"
29 #include "intern_table.h"
30 #include "object-inl.h"
31 #include "runtime.h"
32 #include "string-inl.h"
33 #include "thread.h"
34 
35 namespace art HIDDEN {
36 namespace mirror {
37 
FastIndexOf(int32_t ch,int32_t start)38 int32_t String::FastIndexOf(int32_t ch, int32_t start) {
39   int32_t count = GetLength();
40   if (start >= count) {
41     return -1;
42   } else if (start < 0) {
43     start = 0;
44   }
45   if (IsCompressed()) {
46     return FastIndexOf<uint8_t>(GetValueCompressed(), ch, start);
47   } else {
48     return FastIndexOf<uint16_t>(GetValue(), ch, start);
49   }
50 }
51 
LastIndexOf(int32_t ch)52 int32_t String::LastIndexOf(int32_t ch) {
53   int32_t count = GetLength();
54   if (count == 0) {
55     return -1;
56   }
57   if (IsCompressed()) {
58     return LastIndexOf<uint8_t>(GetValueCompressed(), ch, count - 1);
59   } else {
60     return LastIndexOf<uint16_t>(GetValue(), ch, count - 1);
61   }
62 }
63 
ComputeAndSetHashCode()64 int32_t String::ComputeAndSetHashCode() {
65   int32_t new_hash_code = ComputeHashCode();
66   SetHashCode(new_hash_code);
67   return new_hash_code;
68 }
69 
AllASCIIExcept(const uint16_t * chars,int32_t length,uint16_t non_ascii)70 inline bool String::AllASCIIExcept(const uint16_t* chars, int32_t length, uint16_t non_ascii) {
71   DCHECK(!IsASCII(non_ascii));
72   for (int32_t i = 0; i < length; ++i) {
73     if (!IsASCII(chars[i]) && chars[i] != non_ascii) {
74       return false;
75     }
76   }
77   return true;
78 }
79 
DoReplace(Thread * self,Handle<String> src,uint16_t old_c,uint16_t new_c)80 ObjPtr<String> String::DoReplace(Thread* self, Handle<String> src, uint16_t old_c, uint16_t new_c) {
81   int32_t length = src->GetLength();
82   DCHECK(src->IsCompressed()
83              ? ContainsElement(ArrayRef<uint8_t>(src->value_compressed_, length), old_c)
84              : ContainsElement(ArrayRef<uint16_t>(src->value_, length), old_c));
85   bool compressible =
86       kUseStringCompression &&
87       IsASCII(new_c) &&
88       (src->IsCompressed() || (!IsASCII(old_c) && AllASCIIExcept(src->value_, length, old_c)));
89   gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
90   const int32_t length_with_flag = String::GetFlaggedCount(length, compressible);
91 
92   auto visitor = [=](ObjPtr<Object> obj, size_t usable_size) REQUIRES_SHARED(Locks::mutator_lock_) {
93     SetStringCountVisitor set_string_count_visitor(length_with_flag);
94     set_string_count_visitor(obj, usable_size);
95     ObjPtr<String> new_string = obj->AsString();
96     if (compressible) {
97       auto replace = [old_c, new_c](uint16_t c) {
98         return dchecked_integral_cast<uint8_t>((old_c != c) ? c : new_c);
99       };
100       uint8_t* out = new_string->value_compressed_;
101       if (LIKELY(src->IsCompressed())) {  // LIKELY(compressible == src->IsCompressed())
102         std::transform(src->value_compressed_, src->value_compressed_ + length, out, replace);
103       } else {
104         std::transform(src->value_, src->value_ + length, out, replace);
105       }
106       DCHECK(kUseStringCompression && AllASCII(out, length));
107     } else {
108       auto replace = [old_c, new_c](uint16_t c) {
109         return (old_c != c) ? c : new_c;
110       };
111       uint16_t* out = new_string->value_;
112       if (UNLIKELY(src->IsCompressed())) {  // LIKELY(compressible == src->IsCompressed())
113         std::transform(src->value_compressed_, src->value_compressed_ + length, out, replace);
114       } else {
115         std::transform(src->value_, src->value_ + length, out, replace);
116       }
117       DCHECK_IMPLIES(kUseStringCompression, !AllASCII(out, length));
118     }
119   };
120   return Alloc(self, length_with_flag, allocator_type, visitor);
121 }
122 
DoConcat(Thread * self,Handle<String> h_this,Handle<String> h_arg)123 ObjPtr<String> String::DoConcat(Thread* self, Handle<String> h_this, Handle<String> h_arg) {
124   int32_t length_this = h_this->GetLength();
125   int32_t length_arg = h_arg->GetLength();
126   gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
127   const bool compressible =
128       kUseStringCompression && (h_this->IsCompressed() && h_arg->IsCompressed());
129   const int32_t length_with_flag = String::GetFlaggedCount(length_this + length_arg, compressible);
130 
131   auto visitor = [=](ObjPtr<Object> obj, size_t usable_size) REQUIRES_SHARED(Locks::mutator_lock_) {
132     SetStringCountVisitor set_string_count_visitor(length_with_flag);
133     set_string_count_visitor(obj, usable_size);
134     ObjPtr<String> new_string = obj->AsString();
135     if (compressible) {
136       uint8_t* new_value = new_string->GetValueCompressed();
137       memcpy(new_value, h_this->GetValueCompressed(), length_this * sizeof(uint8_t));
138       memcpy(new_value + length_this, h_arg->GetValueCompressed(), length_arg * sizeof(uint8_t));
139     } else {
140       uint16_t* new_value = new_string->GetValue();
141       if (h_this->IsCompressed()) {
142         const uint8_t* value_this = h_this->GetValueCompressed();
143         for (int i = 0; i < length_this; ++i) {
144           new_value[i] = value_this[i];
145         }
146       } else {
147         memcpy(new_value, h_this->GetValue(), length_this * sizeof(uint16_t));
148       }
149       if (h_arg->IsCompressed()) {
150         const uint8_t* value_arg = h_arg->GetValueCompressed();
151         for (int i = 0; i < length_arg; ++i) {
152           new_value[i + length_this] = value_arg[i];
153         }
154       } else {
155         memcpy(new_value + length_this, h_arg->GetValue(), length_arg * sizeof(uint16_t));
156       }
157     }
158   };
159   return Alloc(self, length_with_flag, allocator_type, visitor);
160 }
161 
162 template<typename T>
RepeatCharacters(ObjPtr<String> new_string,Handle<String> h_this,int32_t count)163 static void RepeatCharacters(ObjPtr<String> new_string, Handle<String> h_this, int32_t count)
164     REQUIRES_SHARED(Locks::mutator_lock_) {
165   T *new_value, *h_this_value;
166   if constexpr (std::is_same_v<T, uint8_t>) {
167     new_value = new_string->GetValueCompressed();
168     h_this_value = h_this->GetValueCompressed();
169   } else {
170     new_value = new_string->GetValue();
171     h_this_value = h_this->GetValue();
172   }
173   int32_t length_this = h_this->GetLength();
174   if (length_this == 1) {
175     // compiler is smart enough to use memset for uint8_t
176     std::fill(new_value, new_value + count, h_this_value[0]);
177   } else {
178     memcpy(new_value, h_this_value, length_this * sizeof(T));
179     int32_t copied = length_this;
180     int32_t limit = length_this * count;
181     for (; copied < limit - copied; copied <<= 1) {
182       memcpy(new_value + copied, new_value, copied * sizeof(T));
183     }
184     memcpy(new_value + copied, new_value, (limit - copied) * sizeof(T));
185   }
186 }
187 
DoRepeat(Thread * self,Handle<String> h_this,int32_t count)188 ObjPtr<String> String::DoRepeat(Thread* self, Handle<String> h_this, int32_t count) {
189   int32_t length_this = h_this->GetLength();
190   DCHECK_GT(count, 1);
191   DCHECK_LE(length_this, std::numeric_limits<int32_t>::max() / count);
192   gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
193   const bool compressible = kUseStringCompression && (h_this->IsCompressed());
194   const int32_t length_with_flag = String::GetFlaggedCount(length_this * count, compressible);
195 
196   auto visitor = [=](ObjPtr<Object> obj, size_t usable_size) REQUIRES_SHARED(Locks::mutator_lock_) {
197       SetStringCountVisitor set_string_count_visitor(length_with_flag);
198       set_string_count_visitor(obj, usable_size);
199       ObjPtr<String> new_string = obj->AsString();
200 
201       if (compressible) {
202         RepeatCharacters<uint8_t>(new_string, h_this, count);
203       } else {
204         RepeatCharacters<uint16_t>(new_string, h_this, count);
205       }
206   };
207   return Alloc(self, length_with_flag, allocator_type, visitor);
208 }
209 
AllocFromUtf16(Thread * self,int32_t utf16_length,const uint16_t * utf16_data_in)210 ObjPtr<String> String::AllocFromUtf16(Thread* self,
211                                       int32_t utf16_length,
212                                       const uint16_t* utf16_data_in) {
213   CHECK_IMPLIES(utf16_data_in == nullptr, utf16_length == 0);
214   gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
215   const bool compressible = kUseStringCompression &&
216                             String::AllASCII<uint16_t>(utf16_data_in, utf16_length);
217   int32_t length_with_flag = String::GetFlaggedCount(utf16_length, compressible);
218 
219   auto visitor = [=](ObjPtr<Object> obj, size_t usable_size) REQUIRES_SHARED(Locks::mutator_lock_) {
220     SetStringCountVisitor set_string_count_visitor(length_with_flag);
221     set_string_count_visitor(obj, usable_size);
222     ObjPtr<String> new_string = obj->AsString();
223     if (compressible) {
224       uint8_t* value = new_string->GetValueCompressed();
225       for (int i = 0; i < utf16_length; ++i) {
226         value[i] = static_cast<uint8_t>(utf16_data_in[i]);
227       }
228     } else {
229       memcpy(new_string->GetValue(), utf16_data_in, utf16_length * sizeof(uint16_t));
230     }
231   };
232   return Alloc(self, length_with_flag, allocator_type, visitor);
233 }
234 
AllocFromModifiedUtf8(Thread * self,const char * utf)235 ObjPtr<String> String::AllocFromModifiedUtf8(Thread* self, const char* utf) {
236   DCHECK(utf != nullptr);
237   size_t byte_count = strlen(utf);
238   size_t char_count = CountModifiedUtf8Chars(utf, byte_count);
239   return AllocFromModifiedUtf8(self, char_count, utf, byte_count);
240 }
241 
AllocFromModifiedUtf8(Thread * self,int32_t utf16_length,const char * utf8_data_in)242 ObjPtr<String> String::AllocFromModifiedUtf8(Thread* self,
243                                              int32_t utf16_length,
244                                              const char* utf8_data_in) {
245   return AllocFromModifiedUtf8(self, utf16_length, utf8_data_in, strlen(utf8_data_in));
246 }
247 
AllocFromModifiedUtf8(Thread * self,int32_t utf16_length,const char * utf8_data_in,int32_t utf8_length)248 ObjPtr<String> String::AllocFromModifiedUtf8(Thread* self,
249                                              int32_t utf16_length,
250                                              const char* utf8_data_in,
251                                              int32_t utf8_length) {
252   gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator();
253   const bool compressible = kUseStringCompression && (utf16_length == utf8_length);
254   const int32_t length_with_flag = String::GetFlaggedCount(utf16_length, compressible);
255 
256   auto visitor = [=](ObjPtr<Object> obj, size_t usable_size) REQUIRES_SHARED(Locks::mutator_lock_) {
257     SetStringCountVisitor set_string_count_visitor(length_with_flag);
258     set_string_count_visitor(obj, usable_size);
259     ObjPtr<String> new_string = obj->AsString();
260     if (compressible) {
261       memcpy(new_string->GetValueCompressed(), utf8_data_in, utf16_length * sizeof(uint8_t));
262     } else {
263       uint16_t* utf16_data_out = new_string->GetValue();
264       ConvertModifiedUtf8ToUtf16(utf16_data_out, utf16_length, utf8_data_in, utf8_length);
265     }
266   };
267   return Alloc(self, length_with_flag, allocator_type, visitor);
268 }
269 
Equals(mirror::String * that)270 bool String::Equals(mirror::String* that) {
271   if (this == that) {
272     // Quick reference equality test
273     return true;
274   } else if (that == nullptr) {
275     // Null isn't an instanceof anything
276     return false;
277   } else if (this->GetCount() != that->GetCount()) {
278     // Quick length and compression inequality test
279     return false;
280   } else {
281     // Note: don't short circuit on hash code as we're presumably here as the
282     // hash code was already equal
283     if (this->IsCompressed()) {
284       return memcmp(this->GetValueCompressed(), that->GetValueCompressed(), this->GetLength()) == 0;
285     } else {
286       return memcmp(this->GetValue(), that->GetValue(), sizeof(uint16_t) * this->GetLength()) == 0;
287     }
288   }
289 }
290 
Equals(const char * modified_utf8)291 bool String::Equals(const char* modified_utf8) {
292   const int32_t length = GetLength();
293   if (IsCompressed()) {
294     return strlen(modified_utf8) == dchecked_integral_cast<uint32_t>(length) &&
295            memcmp(modified_utf8, GetValueCompressed(), length) == 0;
296   }
297   const uint16_t* value = GetValue();
298   int32_t i = 0;
299   while (i < length) {
300     const uint32_t ch = GetUtf16FromUtf8(&modified_utf8);
301     if (ch == '\0') {
302       return false;
303     }
304 
305     if (GetLeadingUtf16Char(ch) != value[i++]) {
306       return false;
307     }
308 
309     const uint16_t trailing = GetTrailingUtf16Char(ch);
310     if (trailing != 0) {
311       if (i == length) {
312         return false;
313       }
314 
315       if (value[i++] != trailing) {
316         return false;
317       }
318     }
319   }
320   return *modified_utf8 == '\0';
321 }
322 
323 // Create a modified UTF-8 encoded std::string from a java/lang/String object.
ToModifiedUtf8()324 std::string String::ToModifiedUtf8() {
325   if (IsCompressed()) {
326     return std::string(reinterpret_cast<const char*>(GetValueCompressed()), GetLength());
327   } else {
328     size_t byte_count = GetModifiedUtf8Length();
329     std::string result(byte_count, static_cast<char>(0));
330     ConvertUtf16ToModifiedUtf8(&result[0], byte_count, GetValue(), GetLength());
331     return result;
332   }
333 }
334 
CompareTo(ObjPtr<String> rhs)335 int32_t String::CompareTo(ObjPtr<String> rhs) {
336   // Quick test for comparison of a string with itself.
337   ObjPtr<String> lhs = this;
338   if (lhs == rhs) {
339     return 0;
340   }
341   int32_t lhs_count = lhs->GetLength();
342   int32_t rhs_count = rhs->GetLength();
343   int32_t count_diff = lhs_count - rhs_count;
344   int32_t min_count = (count_diff < 0) ? lhs_count : rhs_count;
345   if (lhs->IsCompressed() && rhs->IsCompressed()) {
346     const uint8_t* lhs_chars = lhs->GetValueCompressed();
347     const uint8_t* rhs_chars = rhs->GetValueCompressed();
348     for (int32_t i = 0; i < min_count; ++i) {
349       int32_t char_diff = static_cast<int32_t>(lhs_chars[i]) - static_cast<int32_t>(rhs_chars[i]);
350       if (char_diff != 0) {
351         return char_diff;
352       }
353     }
354   } else if (lhs->IsCompressed() || rhs->IsCompressed()) {
355     const uint8_t* compressed_chars =
356         lhs->IsCompressed() ? lhs->GetValueCompressed() : rhs->GetValueCompressed();
357     const uint16_t* uncompressed_chars = lhs->IsCompressed() ? rhs->GetValue() : lhs->GetValue();
358     for (int32_t i = 0; i < min_count; ++i) {
359       int32_t char_diff =
360           static_cast<int32_t>(compressed_chars[i]) - static_cast<int32_t>(uncompressed_chars[i]);
361       if (char_diff != 0) {
362         return lhs->IsCompressed() ? char_diff : -char_diff;
363       }
364     }
365   } else {
366     const uint16_t* lhs_chars = lhs->GetValue();
367     const uint16_t* rhs_chars = rhs->GetValue();
368     // FIXME: The MemCmp16() name is misleading. It returns the char difference on mismatch
369     // where memcmp() only guarantees that the returned value has the same sign.
370     int32_t char_diff = MemCmp16(lhs_chars, rhs_chars, min_count);
371     if (char_diff != 0) {
372       return char_diff;
373     }
374   }
375   return count_diff;
376 }
377 
ToCharArray(Handle<String> h_this,Thread * self)378 ObjPtr<CharArray> String::ToCharArray(Handle<String> h_this, Thread* self) {
379   ObjPtr<CharArray> result = CharArray::Alloc(self, h_this->GetLength());
380   if (result != nullptr) {
381     if (h_this->IsCompressed()) {
382       int32_t length = h_this->GetLength();
383       const uint8_t* src = h_this->GetValueCompressed();
384       uint16_t* dest = result->GetData();
385       for (int i = 0; i < length; ++i) {
386         dest[i] = src[i];
387       }
388     } else {
389       memcpy(result->GetData(), h_this->GetValue(), h_this->GetLength() * sizeof(uint16_t));
390     }
391   } else {
392     self->AssertPendingOOMException();
393   }
394   return result;
395 }
396 
GetChars(int32_t start,int32_t end,Handle<CharArray> array,int32_t index)397 void String::GetChars(int32_t start, int32_t end, Handle<CharArray> array, int32_t index) {
398   uint16_t* data = array->GetData() + index;
399   DCHECK_LE(start, end);
400   int32_t length = end - start;
401   if (IsCompressed()) {
402     const uint8_t* value = GetValueCompressed() + start;
403     for (int i = 0; i < length; ++i) {
404       data[i] = value[i];
405     }
406   } else {
407     uint16_t* value = GetValue() + start;
408     memcpy(data, value, length * sizeof(uint16_t));
409   }
410 }
411 
FillBytesLatin1(Handle<ByteArray> array,int32_t index)412 void String::FillBytesLatin1(Handle<ByteArray> array, int32_t index) {
413   int8_t* data = array->GetData() + index;
414   int32_t length = GetLength();
415   if (IsCompressed()) {
416     const uint8_t* value = GetValueCompressed();
417     memcpy(data, value, length * sizeof(uint8_t));
418   } else {
419     // Drop the high byte of the characters.
420     // The caller should check that all dropped high bytes are zeros.
421     const uint16_t* value = GetValue();
422     for (int32_t i = 0; i < length; ++i) {
423       data[i] = static_cast<int8_t>(dchecked_integral_cast<uint8_t>(value[i]));
424     }
425   }
426 }
427 
FillBytesUTF16(Handle<ByteArray> array,int32_t index)428 void String::FillBytesUTF16(Handle<ByteArray> array, int32_t index) {
429   int8_t* data = array->GetData() + index;
430   int32_t length = GetLength();
431   if (IsCompressed()) {
432     const uint8_t* value = GetValueCompressed();
433     uint32_t d_index = 0;
434     for (int i = 0; i < length; ++i) {
435       data[d_index++] = static_cast<int8_t>(value[i]);
436       data[d_index++] = 0;
437     }
438   } else {
439     const uint16_t* value = GetValue();
440     memcpy(data, value, length * sizeof(uint16_t));
441   }
442 }
443 
IsValueNull()444 bool String::IsValueNull() {
445   return (IsCompressed()) ? (GetValueCompressed() == nullptr) : (GetValue() == nullptr);
446 }
447 
PrettyStringDescriptor(ObjPtr<mirror::String> java_descriptor)448 std::string String::PrettyStringDescriptor(ObjPtr<mirror::String> java_descriptor) {
449   if (java_descriptor == nullptr) {
450     return "null";
451   }
452   return java_descriptor->PrettyStringDescriptor();
453 }
454 
PrettyStringDescriptor()455 std::string String::PrettyStringDescriptor() {
456   return PrettyDescriptor(ToModifiedUtf8().c_str());
457 }
458 
Intern()459 ObjPtr<String> String::Intern() {
460   return Runtime::Current()->GetInternTable()->InternWeak(this);
461 }
462 
463 }  // namespace mirror
464 }  // namespace art
465