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