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.
5 #include "src/string-stream.h"
7 #include "src/handles-inl.h"
8 #include "src/prototype.h"
13 static const int kMentionedObjectCacheMaxSize = 256;
15 char* HeapStringAllocator::allocate(unsigned bytes) {
16 space_ = NewArray<char>(bytes);
21 bool StringStream::Put(char c) {
22 if (full()) return false;
23 DCHECK(length_ < capacity_);
24 // Since the trailing '\0' is not accounted for in length_ fullness is
25 // indicated by a difference of 1 between length_ and capacity_. Thus when
26 // reaching a difference of 2 we need to grow the buffer.
27 if (length_ == capacity_ - 2) {
28 unsigned new_capacity = capacity_;
29 char* new_buffer = allocator_->grow(&new_capacity);
30 if (new_capacity > capacity_) {
31 capacity_ = new_capacity;
34 // Reached the end of the available buffer.
35 DCHECK(capacity_ >= 5);
36 length_ = capacity_ - 1; // Indicate fullness of the stream.
37 buffer_[length_ - 4] = '.';
38 buffer_[length_ - 3] = '.';
39 buffer_[length_ - 2] = '.';
40 buffer_[length_ - 1] = '\n';
41 buffer_[length_] = '\0';
46 buffer_[length_ + 1] = '\0';
52 // A control character is one that configures a format element. For
53 // instance, in %.5s, .5 are control characters.
54 static bool IsControlChar(char c) {
56 case '0': case '1': case '2': case '3': case '4': case '5':
57 case '6': case '7': case '8': case '9': case '.': case '-':
65 void StringStream::Add(Vector<const char> format, Vector<FmtElm> elms) {
66 // If we already ran out of space then return immediately.
70 while (offset < format.length()) {
71 if (format[offset] != '%' || elm == elms.length()) {
76 // Read this formatting directive into a temporary buffer
77 EmbeddedVector<char, 24> temp;
78 int format_length = 0;
79 // Skip over the whole control character sequence until the
80 // format element type
81 temp[format_length++] = format[offset++];
82 while (offset < format.length() && IsControlChar(format[offset]))
83 temp[format_length++] = format[offset++];
84 if (offset >= format.length())
86 char type = format[offset];
87 temp[format_length++] = type;
88 temp[format_length] = '\0';
90 FmtElm current = elms[elm++];
93 DCHECK_EQ(FmtElm::C_STR, current.type_);
94 const char* value = current.data_.u_c_str_;
99 DCHECK_EQ(FmtElm::LC_STR, current.type_);
100 Vector<const uc16> value = *current.data_.u_lc_str_;
101 for (int i = 0; i < value.length(); i++)
102 Put(static_cast<char>(value[i]));
106 DCHECK_EQ(FmtElm::OBJ, current.type_);
107 Object* obj = current.data_.u_obj_;
112 DCHECK_EQ(FmtElm::INT, current.type_);
113 int value = current.data_.u_int_;
114 if (0x20 <= value && value <= 0x7F) {
116 } else if (value <= 0xff) {
117 Add("\\x%02x", value);
119 Add("\\u%04x", value);
123 case 'i': case 'd': case 'u': case 'x': case 'c': case 'X': {
124 int value = current.data_.u_int_;
125 EmbeddedVector<char, 24> formatted;
126 int length = SNPrintF(formatted, temp.start(), value);
127 Add(Vector<const char>(formatted.start(), length));
130 case 'f': case 'g': case 'G': case 'e': case 'E': {
131 double value = current.data_.u_double_;
132 int inf = std::isinf(value);
135 } else if (inf == 1) {
137 } else if (std::isnan(value)) {
140 EmbeddedVector<char, 28> formatted;
141 SNPrintF(formatted, temp.start(), value);
142 Add(formatted.start());
147 void* value = current.data_.u_pointer_;
148 EmbeddedVector<char, 20> formatted;
149 SNPrintF(formatted, temp.start(), value);
150 Add(formatted.start());
159 // Verify that the buffer is 0-terminated
160 DCHECK(buffer_[length_] == '\0');
164 void StringStream::PrintObject(Object* o) {
167 if (String::cast(o)->length() <= String::kMaxShortPrintLength) {
170 } else if (o->IsNumber() || o->IsOddball()) {
173 if (o->IsHeapObject()) {
174 HeapObject* ho = HeapObject::cast(o);
175 DebugObjectCache* debug_object_cache = ho->GetIsolate()->
176 string_stream_debug_object_cache();
177 for (int i = 0; i < debug_object_cache->length(); i++) {
178 if ((*debug_object_cache)[i] == o) {
183 if (debug_object_cache->length() < kMentionedObjectCacheMaxSize) {
184 Add("#%d#", debug_object_cache->length());
185 debug_object_cache->Add(HeapObject::cast(o));
193 void StringStream::Add(const char* format) {
194 Add(CStrVector(format));
198 void StringStream::Add(Vector<const char> format) {
199 Add(format, Vector<FmtElm>::empty());
203 void StringStream::Add(const char* format, FmtElm arg0) {
205 FmtElm argv[argc] = { arg0 };
206 Add(CStrVector(format), Vector<FmtElm>(argv, argc));
210 void StringStream::Add(const char* format, FmtElm arg0, FmtElm arg1) {
212 FmtElm argv[argc] = { arg0, arg1 };
213 Add(CStrVector(format), Vector<FmtElm>(argv, argc));
217 void StringStream::Add(const char* format, FmtElm arg0, FmtElm arg1,
220 FmtElm argv[argc] = { arg0, arg1, arg2 };
221 Add(CStrVector(format), Vector<FmtElm>(argv, argc));
225 void StringStream::Add(const char* format, FmtElm arg0, FmtElm arg1,
226 FmtElm arg2, FmtElm arg3) {
228 FmtElm argv[argc] = { arg0, arg1, arg2, arg3 };
229 Add(CStrVector(format), Vector<FmtElm>(argv, argc));
233 void StringStream::Add(const char* format, FmtElm arg0, FmtElm arg1,
234 FmtElm arg2, FmtElm arg3, FmtElm arg4) {
236 FmtElm argv[argc] = { arg0, arg1, arg2, arg3, arg4 };
237 Add(CStrVector(format), Vector<FmtElm>(argv, argc));
241 SmartArrayPointer<const char> StringStream::ToCString() const {
242 char* str = NewArray<char>(length_ + 1);
243 MemCopy(str, buffer_, length_);
245 return SmartArrayPointer<const char>(str);
249 void StringStream::Log(Isolate* isolate) {
250 LOG(isolate, StringEvent("StackDump", buffer_));
254 void StringStream::OutputToFile(FILE* out) {
255 // Dump the output to stdout, but make sure to break it up into
256 // manageable chunks to avoid losing parts of the output in the OS
257 // printing code. This is a problem on Windows in particular; see
258 // the VPrint() function implementations in platform-win32.cc.
259 unsigned position = 0;
260 for (unsigned next; (next = position + 2048) < length_; position = next) {
261 char save = buffer_[next];
262 buffer_[next] = '\0';
263 internal::PrintF(out, "%s", &buffer_[position]);
264 buffer_[next] = save;
266 internal::PrintF(out, "%s", &buffer_[position]);
270 Handle<String> StringStream::ToString(Isolate* isolate) {
271 return isolate->factory()->NewStringFromUtf8(
272 Vector<const char>(buffer_, length_)).ToHandleChecked();
276 void StringStream::ClearMentionedObjectCache(Isolate* isolate) {
277 isolate->set_string_stream_current_security_token(NULL);
278 if (isolate->string_stream_debug_object_cache() == NULL) {
279 isolate->set_string_stream_debug_object_cache(new DebugObjectCache(0));
281 isolate->string_stream_debug_object_cache()->Clear();
286 bool StringStream::IsMentionedObjectCacheClear(Isolate* isolate) {
287 return isolate->string_stream_debug_object_cache()->length() == 0;
292 bool StringStream::Put(String* str) {
293 return Put(str, 0, str->length());
297 bool StringStream::Put(String* str, int start, int end) {
298 StringCharacterStream stream(str, start);
299 for (int i = start; i < end && stream.HasMore(); i++) {
300 uint16_t c = stream.GetNext();
301 if (c >= 127 || c < 32) {
304 if (!Put(static_cast<char>(c))) {
305 return false; // Output was truncated.
312 void StringStream::PrintName(Object* name) {
313 if (name->IsString()) {
314 String* str = String::cast(name);
315 if (str->length() > 0) {
318 Add("/* anonymous */");
326 void StringStream::PrintUsingMap(JSObject* js_object) {
327 Map* map = js_object->map();
328 if (!js_object->GetHeap()->Contains(map) ||
329 !map->IsHeapObject() ||
331 Add("<Invalid map>\n");
334 int real_size = map->NumberOfOwnDescriptors();
335 DescriptorArray* descs = map->instance_descriptors();
336 for (int i = 0; i < real_size; i++) {
337 PropertyDetails details = descs->GetDetails(i);
338 if (details.type() == FIELD) {
339 Object* key = descs->GetKey(i);
340 if (key->IsString() || key->IsNumber()) {
342 if (key->IsString()) {
343 len = String::cast(key)->length();
345 for (; len < 18; len++)
347 if (key->IsString()) {
348 Put(String::cast(key));
353 FieldIndex index = FieldIndex::ForDescriptor(map, i);
354 Object* value = js_object->RawFastPropertyAt(index);
362 void StringStream::PrintFixedArray(FixedArray* array, unsigned int limit) {
363 Heap* heap = array->GetHeap();
364 for (unsigned int i = 0; i < 10 && i < limit; i++) {
365 Object* element = array->get(i);
366 if (element != heap->the_hole_value()) {
367 for (int len = 1; len < 18; len++)
369 Add("%d: %o\n", i, array->get(i));
378 void StringStream::PrintByteArray(ByteArray* byte_array) {
379 unsigned int limit = byte_array->length();
380 for (unsigned int i = 0; i < 10 && i < limit; i++) {
381 byte b = byte_array->get(i);
382 Add(" %d: %3d 0x%02x", i, b, b);
383 if (b >= ' ' && b <= '~') {
385 } else if (b == '\n') {
387 } else if (b == '\r') {
389 } else if (b >= 1 && b <= 26) {
390 Add(" ^%c", b + 'A' - 1);
400 void StringStream::PrintMentionedObjectCache(Isolate* isolate) {
401 DebugObjectCache* debug_object_cache =
402 isolate->string_stream_debug_object_cache();
403 Add("==== Key ============================================\n\n");
404 for (int i = 0; i < debug_object_cache->length(); i++) {
405 HeapObject* printee = (*debug_object_cache)[i];
406 Add(" #%d# %p: ", i, printee);
407 printee->ShortPrint(this);
409 if (printee->IsJSObject()) {
410 if (printee->IsJSValue()) {
411 Add(" value(): %o\n", JSValue::cast(printee)->value());
413 PrintUsingMap(JSObject::cast(printee));
414 if (printee->IsJSArray()) {
415 JSArray* array = JSArray::cast(printee);
416 if (array->HasFastObjectElements()) {
417 unsigned int limit = FixedArray::cast(array->elements())->length();
418 unsigned int length =
419 static_cast<uint32_t>(JSArray::cast(array)->length()->Number());
420 if (length < limit) limit = length;
421 PrintFixedArray(FixedArray::cast(array->elements()), limit);
424 } else if (printee->IsByteArray()) {
425 PrintByteArray(ByteArray::cast(printee));
426 } else if (printee->IsFixedArray()) {
427 unsigned int limit = FixedArray::cast(printee)->length();
428 PrintFixedArray(FixedArray::cast(printee), limit);
434 void StringStream::PrintSecurityTokenIfChanged(Object* f) {
435 if (!f->IsHeapObject()) return;
436 HeapObject* obj = HeapObject::cast(f);
437 Isolate* isolate = obj->GetIsolate();
438 Heap* heap = isolate->heap();
439 if (!heap->Contains(obj)) return;
440 Map* map = obj->map();
441 if (!map->IsHeapObject() ||
442 !heap->Contains(map) ||
444 !f->IsJSFunction()) {
448 JSFunction* fun = JSFunction::cast(f);
449 Object* perhaps_context = fun->context();
450 if (perhaps_context->IsHeapObject() &&
451 heap->Contains(HeapObject::cast(perhaps_context)) &&
452 perhaps_context->IsContext()) {
453 Context* context = fun->context();
454 if (!heap->Contains(context)) {
455 Add("(Function context is outside heap)\n");
458 Object* token = context->native_context()->security_token();
459 if (token != isolate->string_stream_current_security_token()) {
460 Add("Security context: %o\n", token);
461 isolate->set_string_stream_current_security_token(token);
464 Add("(Function context is corrupt)\n");
469 void StringStream::PrintFunction(Object* f, Object* receiver, Code** code) {
470 if (!f->IsHeapObject()) {
471 Add("/* warning: 'function' was not a heap object */ ");
474 Heap* heap = HeapObject::cast(f)->GetHeap();
475 if (!heap->Contains(HeapObject::cast(f))) {
476 Add("/* warning: 'function' was not on the heap */ ");
479 if (!heap->Contains(HeapObject::cast(f)->map())) {
480 Add("/* warning: function's map was not on the heap */ ");
483 if (!HeapObject::cast(f)->map()->IsMap()) {
484 Add("/* warning: function's map was not a valid map */ ");
487 if (f->IsJSFunction()) {
488 JSFunction* fun = JSFunction::cast(f);
489 // Common case: on-stack function present and resolved.
490 PrintPrototype(fun, receiver);
492 } else if (f->IsInternalizedString()) {
493 // Unresolved and megamorphic calls: Instead of the function
494 // we have the function name on the stack.
496 Add("/* unresolved */ ");
498 // Unless this is the frame of a built-in function, we should always have
499 // the callee function or name on the stack. If we don't, we have a
500 // problem or a change of the stack frame layout.
502 Add("/* warning: no JSFunction object or function name found */ ");
507 void StringStream::PrintPrototype(JSFunction* fun, Object* receiver) {
508 Object* name = fun->shared()->name();
509 bool print_name = false;
510 Isolate* isolate = fun->GetIsolate();
511 for (PrototypeIterator iter(isolate, receiver,
512 PrototypeIterator::START_AT_RECEIVER);
513 !iter.IsAtEnd(); iter.Advance()) {
514 if (iter.GetCurrent()->IsJSObject()) {
515 Object* key = JSObject::cast(iter.GetCurrent())->SlowReverseLookup(fun);
516 if (key != isolate->heap()->undefined_value()) {
517 if (!name->IsString() ||
519 !String::cast(name)->Equals(String::cast(key))) {
522 if (name->IsString() && String::cast(name)->length() == 0) {
532 // Also known as - if the name in the function doesn't match the name under
533 // which it was looked up.
536 PrintName(fun->shared()->name());
542 char* HeapStringAllocator::grow(unsigned* bytes) {
543 unsigned new_bytes = *bytes * 2;
544 // Check for overflow.
545 if (new_bytes <= *bytes) {
548 char* new_space = NewArray<char>(new_bytes);
549 if (new_space == NULL) {
552 MemCopy(new_space, space_, *bytes);
560 } } // namespace v8::internal