1 // Copyright 2014 the V8 project authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #include "src/string-stream.h" 6 7 #include "src/handles-inl.h" 8 #include "src/prototype.h" 9 10 namespace v8 { 11 namespace internal { 12 13 static const int kMentionedObjectCacheMaxSize = 256; 14 15 char* HeapStringAllocator::allocate(unsigned bytes) { 16 space_ = NewArray<char>(bytes); 17 return space_; 18 } 19 20 21 char* FixedStringAllocator::allocate(unsigned bytes) { 22 CHECK_LE(bytes, length_); 23 return buffer_; 24 } 25 26 27 char* FixedStringAllocator::grow(unsigned* old) { 28 *old = length_; 29 return buffer_; 30 } 31 32 33 bool StringStream::Put(char c) { 34 if (full()) return false; 35 DCHECK(length_ < capacity_); 36 // Since the trailing '\0' is not accounted for in length_ fullness is 37 // indicated by a difference of 1 between length_ and capacity_. Thus when 38 // reaching a difference of 2 we need to grow the buffer. 39 if (length_ == capacity_ - 2) { 40 unsigned new_capacity = capacity_; 41 char* new_buffer = allocator_->grow(&new_capacity); 42 if (new_capacity > capacity_) { 43 capacity_ = new_capacity; 44 buffer_ = new_buffer; 45 } else { 46 // Reached the end of the available buffer. 47 DCHECK(capacity_ >= 5); 48 length_ = capacity_ - 1; // Indicate fullness of the stream. 49 buffer_[length_ - 4] = '.'; 50 buffer_[length_ - 3] = '.'; 51 buffer_[length_ - 2] = '.'; 52 buffer_[length_ - 1] = '\n'; 53 buffer_[length_] = '\0'; 54 return false; 55 } 56 } 57 buffer_[length_] = c; 58 buffer_[length_ + 1] = '\0'; 59 length_++; 60 return true; 61 } 62 63 64 // A control character is one that configures a format element. For 65 // instance, in %.5s, .5 are control characters. 66 static bool IsControlChar(char c) { 67 switch (c) { 68 case '0': case '1': case '2': case '3': case '4': case '5': 69 case '6': case '7': case '8': case '9': case '.': case '-': 70 return true; 71 default: 72 return false; 73 } 74 } 75 76 77 void StringStream::Add(Vector<const char> format, Vector<FmtElm> elms) { 78 // If we already ran out of space then return immediately. 79 if (full()) return; 80 int offset = 0; 81 int elm = 0; 82 while (offset < format.length()) { 83 if (format[offset] != '%' || elm == elms.length()) { 84 Put(format[offset]); 85 offset++; 86 continue; 87 } 88 // Read this formatting directive into a temporary buffer 89 EmbeddedVector<char, 24> temp; 90 int format_length = 0; 91 // Skip over the whole control character sequence until the 92 // format element type 93 temp[format_length++] = format[offset++]; 94 while (offset < format.length() && IsControlChar(format[offset])) 95 temp[format_length++] = format[offset++]; 96 if (offset >= format.length()) 97 return; 98 char type = format[offset]; 99 temp[format_length++] = type; 100 temp[format_length] = '\0'; 101 offset++; 102 FmtElm current = elms[elm++]; 103 switch (type) { 104 case 's': { 105 DCHECK_EQ(FmtElm::C_STR, current.type_); 106 const char* value = current.data_.u_c_str_; 107 Add(value); 108 break; 109 } 110 case 'w': { 111 DCHECK_EQ(FmtElm::LC_STR, current.type_); 112 Vector<const uc16> value = *current.data_.u_lc_str_; 113 for (int i = 0; i < value.length(); i++) 114 Put(static_cast<char>(value[i])); 115 break; 116 } 117 case 'o': { 118 DCHECK_EQ(FmtElm::OBJ, current.type_); 119 Object* obj = current.data_.u_obj_; 120 PrintObject(obj); 121 break; 122 } 123 case 'k': { 124 DCHECK_EQ(FmtElm::INT, current.type_); 125 int value = current.data_.u_int_; 126 if (0x20 <= value && value <= 0x7F) { 127 Put(value); 128 } else if (value <= 0xff) { 129 Add("\\x%02x", value); 130 } else { 131 Add("\\u%04x", value); 132 } 133 break; 134 } 135 case 'i': case 'd': case 'u': case 'x': case 'c': case 'X': { 136 int value = current.data_.u_int_; 137 EmbeddedVector<char, 24> formatted; 138 int length = SNPrintF(formatted, temp.start(), value); 139 Add(Vector<const char>(formatted.start(), length)); 140 break; 141 } 142 case 'f': case 'g': case 'G': case 'e': case 'E': { 143 double value = current.data_.u_double_; 144 int inf = std::isinf(value); 145 if (inf == -1) { 146 Add("-inf"); 147 } else if (inf == 1) { 148 Add("inf"); 149 } else if (std::isnan(value)) { 150 Add("nan"); 151 } else { 152 EmbeddedVector<char, 28> formatted; 153 SNPrintF(formatted, temp.start(), value); 154 Add(formatted.start()); 155 } 156 break; 157 } 158 case 'p': { 159 void* value = current.data_.u_pointer_; 160 EmbeddedVector<char, 20> formatted; 161 SNPrintF(formatted, temp.start(), value); 162 Add(formatted.start()); 163 break; 164 } 165 default: 166 UNREACHABLE(); 167 break; 168 } 169 } 170 171 // Verify that the buffer is 0-terminated 172 DCHECK(buffer_[length_] == '\0'); 173 } 174 175 176 void StringStream::PrintObject(Object* o) { 177 o->ShortPrint(this); 178 if (o->IsString()) { 179 if (String::cast(o)->length() <= String::kMaxShortPrintLength) { 180 return; 181 } 182 } else if (o->IsNumber() || o->IsOddball()) { 183 return; 184 } 185 if (o->IsHeapObject() && object_print_mode_ == kPrintObjectVerbose) { 186 HeapObject* ho = HeapObject::cast(o); 187 DebugObjectCache* debug_object_cache = ho->GetIsolate()-> 188 string_stream_debug_object_cache(); 189 for (int i = 0; i < debug_object_cache->length(); i++) { 190 if ((*debug_object_cache)[i] == o) { 191 Add("#%d#", i); 192 return; 193 } 194 } 195 if (debug_object_cache->length() < kMentionedObjectCacheMaxSize) { 196 Add("#%d#", debug_object_cache->length()); 197 debug_object_cache->Add(HeapObject::cast(o)); 198 } else { 199 Add("@%p", o); 200 } 201 } 202 } 203 204 205 void StringStream::Add(const char* format) { 206 Add(CStrVector(format)); 207 } 208 209 210 void StringStream::Add(Vector<const char> format) { 211 Add(format, Vector<FmtElm>::empty()); 212 } 213 214 215 void StringStream::Add(const char* format, FmtElm arg0) { 216 const char argc = 1; 217 FmtElm argv[argc] = { arg0 }; 218 Add(CStrVector(format), Vector<FmtElm>(argv, argc)); 219 } 220 221 222 void StringStream::Add(const char* format, FmtElm arg0, FmtElm arg1) { 223 const char argc = 2; 224 FmtElm argv[argc] = { arg0, arg1 }; 225 Add(CStrVector(format), Vector<FmtElm>(argv, argc)); 226 } 227 228 229 void StringStream::Add(const char* format, FmtElm arg0, FmtElm arg1, 230 FmtElm arg2) { 231 const char argc = 3; 232 FmtElm argv[argc] = { arg0, arg1, arg2 }; 233 Add(CStrVector(format), Vector<FmtElm>(argv, argc)); 234 } 235 236 237 void StringStream::Add(const char* format, FmtElm arg0, FmtElm arg1, 238 FmtElm arg2, FmtElm arg3) { 239 const char argc = 4; 240 FmtElm argv[argc] = { arg0, arg1, arg2, arg3 }; 241 Add(CStrVector(format), Vector<FmtElm>(argv, argc)); 242 } 243 244 245 void StringStream::Add(const char* format, FmtElm arg0, FmtElm arg1, 246 FmtElm arg2, FmtElm arg3, FmtElm arg4) { 247 const char argc = 5; 248 FmtElm argv[argc] = { arg0, arg1, arg2, arg3, arg4 }; 249 Add(CStrVector(format), Vector<FmtElm>(argv, argc)); 250 } 251 252 253 base::SmartArrayPointer<const char> StringStream::ToCString() const { 254 char* str = NewArray<char>(length_ + 1); 255 MemCopy(str, buffer_, length_); 256 str[length_] = '\0'; 257 return base::SmartArrayPointer<const char>(str); 258 } 259 260 261 void StringStream::Log(Isolate* isolate) { 262 LOG(isolate, StringEvent("StackDump", buffer_)); 263 } 264 265 266 void StringStream::OutputToFile(FILE* out) { 267 // Dump the output to stdout, but make sure to break it up into 268 // manageable chunks to avoid losing parts of the output in the OS 269 // printing code. This is a problem on Windows in particular; see 270 // the VPrint() function implementations in platform-win32.cc. 271 unsigned position = 0; 272 for (unsigned next; (next = position + 2048) < length_; position = next) { 273 char save = buffer_[next]; 274 buffer_[next] = '\0'; 275 internal::PrintF(out, "%s", &buffer_[position]); 276 buffer_[next] = save; 277 } 278 internal::PrintF(out, "%s", &buffer_[position]); 279 } 280 281 282 Handle<String> StringStream::ToString(Isolate* isolate) { 283 return isolate->factory()->NewStringFromUtf8( 284 Vector<const char>(buffer_, length_)).ToHandleChecked(); 285 } 286 287 288 void StringStream::ClearMentionedObjectCache(Isolate* isolate) { 289 isolate->set_string_stream_current_security_token(NULL); 290 if (isolate->string_stream_debug_object_cache() == NULL) { 291 isolate->set_string_stream_debug_object_cache(new DebugObjectCache(0)); 292 } 293 isolate->string_stream_debug_object_cache()->Clear(); 294 } 295 296 297 #ifdef DEBUG 298 bool StringStream::IsMentionedObjectCacheClear(Isolate* isolate) { 299 return object_print_mode_ == kPrintObjectConcise || 300 isolate->string_stream_debug_object_cache()->length() == 0; 301 } 302 #endif 303 304 305 bool StringStream::Put(String* str) { 306 return Put(str, 0, str->length()); 307 } 308 309 310 bool StringStream::Put(String* str, int start, int end) { 311 StringCharacterStream stream(str, start); 312 for (int i = start; i < end && stream.HasMore(); i++) { 313 uint16_t c = stream.GetNext(); 314 if (c >= 127 || c < 32) { 315 c = '?'; 316 } 317 if (!Put(static_cast<char>(c))) { 318 return false; // Output was truncated. 319 } 320 } 321 return true; 322 } 323 324 325 void StringStream::PrintName(Object* name) { 326 if (name->IsString()) { 327 String* str = String::cast(name); 328 if (str->length() > 0) { 329 Put(str); 330 } else { 331 Add("/* anonymous */"); 332 } 333 } else { 334 Add("%o", name); 335 } 336 } 337 338 339 void StringStream::PrintUsingMap(JSObject* js_object) { 340 Map* map = js_object->map(); 341 if (!js_object->GetHeap()->Contains(map) || 342 !map->IsHeapObject() || 343 !map->IsMap()) { 344 Add("<Invalid map>\n"); 345 return; 346 } 347 int real_size = map->NumberOfOwnDescriptors(); 348 DescriptorArray* descs = map->instance_descriptors(); 349 for (int i = 0; i < real_size; i++) { 350 PropertyDetails details = descs->GetDetails(i); 351 if (details.type() == DATA) { 352 Object* key = descs->GetKey(i); 353 if (key->IsString() || key->IsNumber()) { 354 int len = 3; 355 if (key->IsString()) { 356 len = String::cast(key)->length(); 357 } 358 for (; len < 18; len++) 359 Put(' '); 360 if (key->IsString()) { 361 Put(String::cast(key)); 362 } else { 363 key->ShortPrint(); 364 } 365 Add(": "); 366 FieldIndex index = FieldIndex::ForDescriptor(map, i); 367 if (js_object->IsUnboxedDoubleField(index)) { 368 double value = js_object->RawFastDoublePropertyAt(index); 369 Add("<unboxed double> %.16g\n", FmtElm(value)); 370 } else { 371 Object* value = js_object->RawFastPropertyAt(index); 372 Add("%o\n", value); 373 } 374 } 375 } 376 } 377 } 378 379 380 void StringStream::PrintFixedArray(FixedArray* array, unsigned int limit) { 381 Heap* heap = array->GetHeap(); 382 for (unsigned int i = 0; i < 10 && i < limit; i++) { 383 Object* element = array->get(i); 384 if (element != heap->the_hole_value()) { 385 for (int len = 1; len < 18; len++) 386 Put(' '); 387 Add("%d: %o\n", i, array->get(i)); 388 } 389 } 390 if (limit >= 10) { 391 Add(" ...\n"); 392 } 393 } 394 395 396 void StringStream::PrintByteArray(ByteArray* byte_array) { 397 unsigned int limit = byte_array->length(); 398 for (unsigned int i = 0; i < 10 && i < limit; i++) { 399 byte b = byte_array->get(i); 400 Add(" %d: %3d 0x%02x", i, b, b); 401 if (b >= ' ' && b <= '~') { 402 Add(" '%c'", b); 403 } else if (b == '\n') { 404 Add(" '\n'"); 405 } else if (b == '\r') { 406 Add(" '\r'"); 407 } else if (b >= 1 && b <= 26) { 408 Add(" ^%c", b + 'A' - 1); 409 } 410 Add("\n"); 411 } 412 if (limit >= 10) { 413 Add(" ...\n"); 414 } 415 } 416 417 418 void StringStream::PrintMentionedObjectCache(Isolate* isolate) { 419 if (object_print_mode_ == kPrintObjectConcise) return; 420 DebugObjectCache* debug_object_cache = 421 isolate->string_stream_debug_object_cache(); 422 Add("==== Key ============================================\n\n"); 423 for (int i = 0; i < debug_object_cache->length(); i++) { 424 HeapObject* printee = (*debug_object_cache)[i]; 425 Add(" #%d# %p: ", i, printee); 426 printee->ShortPrint(this); 427 Add("\n"); 428 if (printee->IsJSObject()) { 429 if (printee->IsJSValue()) { 430 Add(" value(): %o\n", JSValue::cast(printee)->value()); 431 } 432 PrintUsingMap(JSObject::cast(printee)); 433 if (printee->IsJSArray()) { 434 JSArray* array = JSArray::cast(printee); 435 if (array->HasFastObjectElements()) { 436 unsigned int limit = FixedArray::cast(array->elements())->length(); 437 unsigned int length = 438 static_cast<uint32_t>(JSArray::cast(array)->length()->Number()); 439 if (length < limit) limit = length; 440 PrintFixedArray(FixedArray::cast(array->elements()), limit); 441 } 442 } 443 } else if (printee->IsByteArray()) { 444 PrintByteArray(ByteArray::cast(printee)); 445 } else if (printee->IsFixedArray()) { 446 unsigned int limit = FixedArray::cast(printee)->length(); 447 PrintFixedArray(FixedArray::cast(printee), limit); 448 } 449 } 450 } 451 452 453 void StringStream::PrintSecurityTokenIfChanged(Object* f) { 454 if (!f->IsHeapObject()) return; 455 HeapObject* obj = HeapObject::cast(f); 456 Isolate* isolate = obj->GetIsolate(); 457 Heap* heap = isolate->heap(); 458 if (!heap->Contains(obj)) return; 459 Map* map = obj->map(); 460 if (!map->IsHeapObject() || 461 !heap->Contains(map) || 462 !map->IsMap() || 463 !f->IsJSFunction()) { 464 return; 465 } 466 467 JSFunction* fun = JSFunction::cast(f); 468 Object* perhaps_context = fun->context(); 469 if (perhaps_context->IsHeapObject() && 470 heap->Contains(HeapObject::cast(perhaps_context)) && 471 perhaps_context->IsContext()) { 472 Context* context = fun->context(); 473 if (!heap->Contains(context)) { 474 Add("(Function context is outside heap)\n"); 475 return; 476 } 477 Object* token = context->native_context()->security_token(); 478 if (token != isolate->string_stream_current_security_token()) { 479 Add("Security context: %o\n", token); 480 isolate->set_string_stream_current_security_token(token); 481 } 482 } else { 483 Add("(Function context is corrupt)\n"); 484 } 485 } 486 487 488 void StringStream::PrintFunction(Object* f, Object* receiver, Code** code) { 489 if (!f->IsHeapObject()) { 490 Add("/* warning: 'function' was not a heap object */ "); 491 return; 492 } 493 Heap* heap = HeapObject::cast(f)->GetHeap(); 494 if (!heap->Contains(HeapObject::cast(f))) { 495 Add("/* warning: 'function' was not on the heap */ "); 496 return; 497 } 498 if (!heap->Contains(HeapObject::cast(f)->map())) { 499 Add("/* warning: function's map was not on the heap */ "); 500 return; 501 } 502 if (!HeapObject::cast(f)->map()->IsMap()) { 503 Add("/* warning: function's map was not a valid map */ "); 504 return; 505 } 506 if (f->IsJSFunction()) { 507 JSFunction* fun = JSFunction::cast(f); 508 // Common case: on-stack function present and resolved. 509 PrintPrototype(fun, receiver); 510 *code = fun->code(); 511 } else if (f->IsInternalizedString()) { 512 // Unresolved and megamorphic calls: Instead of the function 513 // we have the function name on the stack. 514 PrintName(f); 515 Add("/* unresolved */ "); 516 } else { 517 // Unless this is the frame of a built-in function, we should always have 518 // the callee function or name on the stack. If we don't, we have a 519 // problem or a change of the stack frame layout. 520 Add("%o", f); 521 Add("/* warning: no JSFunction object or function name found */ "); 522 } 523 } 524 525 526 void StringStream::PrintPrototype(JSFunction* fun, Object* receiver) { 527 Object* name = fun->shared()->name(); 528 bool print_name = false; 529 Isolate* isolate = fun->GetIsolate(); 530 for (PrototypeIterator iter(isolate, receiver, 531 PrototypeIterator::START_AT_RECEIVER); 532 !iter.IsAtEnd(); iter.Advance()) { 533 if (iter.GetCurrent()->IsJSObject()) { 534 Object* key = iter.GetCurrent<JSObject>()->SlowReverseLookup(fun); 535 if (key != isolate->heap()->undefined_value()) { 536 if (!name->IsString() || 537 !key->IsString() || 538 !String::cast(name)->Equals(String::cast(key))) { 539 print_name = true; 540 } 541 if (name->IsString() && String::cast(name)->length() == 0) { 542 print_name = false; 543 } 544 name = key; 545 } 546 } else { 547 print_name = true; 548 } 549 } 550 PrintName(name); 551 // Also known as - if the name in the function doesn't match the name under 552 // which it was looked up. 553 if (print_name) { 554 Add("(aka "); 555 PrintName(fun->shared()->name()); 556 Put(')'); 557 } 558 } 559 560 561 char* HeapStringAllocator::grow(unsigned* bytes) { 562 unsigned new_bytes = *bytes * 2; 563 // Check for overflow. 564 if (new_bytes <= *bytes) { 565 return space_; 566 } 567 char* new_space = NewArray<char>(new_bytes); 568 if (new_space == NULL) { 569 return space_; 570 } 571 MemCopy(new_space, space_, *bytes); 572 *bytes = new_bytes; 573 DeleteArray(space_); 574 space_ = new_space; 575 return new_space; 576 } 577 578 579 } // namespace internal 580 } // namespace v8 581