blob: 9002593bddf6e6184322d85951089d8923b9e5e1 [file] [log] [blame]
Ben Murdoch3fb3ca82011-12-02 17:19:32 +00001// Copyright 2011 the V8 project authors. All rights reserved.
Steve Blocka7e24c12009-10-30 11:49:00 +00002// 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
Ben Murdoch3fb3ca82011-12-02 17:19:32 +000033#include "allocation-inl.h"
34
Steve Blocka7e24c12009-10-30 11:49:00 +000035namespace v8 {
36namespace internal {
37
38static const int kMentionedObjectCacheMaxSize = 256;
Steve Blocka7e24c12009-10-30 11:49:00 +000039
40char* HeapStringAllocator::allocate(unsigned bytes) {
41 space_ = NewArray<char>(bytes);
42 return space_;
43}
44
45
46NoAllocationStringAllocator::NoAllocationStringAllocator(char* memory,
47 unsigned size) {
48 size_ = size;
49 space_ = memory;
50}
51
52
53bool 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.
86static 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
97void 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
187void StringStream::PrintObject(Object* o) {
188 o->ShortPrint(this);
189 if (o->IsString()) {
Steve Blockd0582a62009-12-15 09:54:21 +0000190 if (String::cast(o)->length() <= String::kMaxShortPrintLength) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000191 return;
192 }
193 } else if (o->IsNumber() || o->IsOddball()) {
194 return;
195 }
196 if (o->IsHeapObject()) {
Steve Block44f0eee2011-05-26 01:26:41 +0100197 DebugObjectCache* debug_object_cache = Isolate::Current()->
198 string_stream_debug_object_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +0000199 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
215void StringStream::Add(const char* format) {
216 Add(CStrVector(format));
217}
218
219
220void StringStream::Add(Vector<const char> format) {
221 Add(format, Vector<FmtElm>::empty());
222}
223
224
225void 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
232void 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
239void 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
247void 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
255SmartPointer<const char> StringStream::ToCString() const {
256 char* str = NewArray<char>(length_ + 1);
257 memcpy(str, buffer_, length_);
258 str[length_] = '\0';
259 return SmartPointer<const char>(str);
260}
261
262
263void StringStream::Log() {
Steve Block44f0eee2011-05-26 01:26:41 +0100264 LOG(ISOLATE, StringEvent("StackDump", buffer_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000265}
266
267
Ben Murdochb0fe1622011-05-05 13:52:32 +0100268void StringStream::OutputToFile(FILE* out) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000269 // Dump the output to stdout, but make sure to break it up into
270 // manageable chunks to avoid losing parts of the output in the OS
271 // printing code. This is a problem on Windows in particular; see
272 // the VPrint() function implementations in platform-win32.cc.
273 unsigned position = 0;
274 for (unsigned next; (next = position + 2048) < length_; position = next) {
275 char save = buffer_[next];
276 buffer_[next] = '\0';
Ben Murdochb0fe1622011-05-05 13:52:32 +0100277 internal::PrintF(out, "%s", &buffer_[position]);
Steve Blocka7e24c12009-10-30 11:49:00 +0000278 buffer_[next] = save;
279 }
Ben Murdochb0fe1622011-05-05 13:52:32 +0100280 internal::PrintF(out, "%s", &buffer_[position]);
Steve Blocka7e24c12009-10-30 11:49:00 +0000281}
282
283
284Handle<String> StringStream::ToString() {
Steve Block44f0eee2011-05-26 01:26:41 +0100285 return FACTORY->NewStringFromUtf8(Vector<const char>(buffer_, length_));
Steve Blocka7e24c12009-10-30 11:49:00 +0000286}
287
288
289void StringStream::ClearMentionedObjectCache() {
Steve Block44f0eee2011-05-26 01:26:41 +0100290 Isolate* isolate = Isolate::Current();
291 isolate->set_string_stream_current_security_token(NULL);
292 if (isolate->string_stream_debug_object_cache() == NULL) {
293 isolate->set_string_stream_debug_object_cache(
294 new List<HeapObject*, PreallocatedStorage>(0));
Steve Blocka7e24c12009-10-30 11:49:00 +0000295 }
Steve Block44f0eee2011-05-26 01:26:41 +0100296 isolate->string_stream_debug_object_cache()->Clear();
Steve Blocka7e24c12009-10-30 11:49:00 +0000297}
298
299
300#ifdef DEBUG
301bool StringStream::IsMentionedObjectCacheClear() {
Steve Block44f0eee2011-05-26 01:26:41 +0100302 return (
303 Isolate::Current()->string_stream_debug_object_cache()->length() == 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000304}
305#endif
306
307
308bool StringStream::Put(String* str) {
309 return Put(str, 0, str->length());
310}
311
312
313bool StringStream::Put(String* str, int start, int end) {
314 StringInputBuffer name_buffer(str);
315 name_buffer.Seek(start);
316 for (int i = start; i < end && name_buffer.has_more(); i++) {
317 int c = name_buffer.GetNext();
318 if (c >= 127 || c < 32) {
319 c = '?';
320 }
321 if (!Put(c)) {
322 return false; // Output was truncated.
323 }
324 }
325 return true;
326}
327
328
329void StringStream::PrintName(Object* name) {
330 if (name->IsString()) {
331 String* str = String::cast(name);
332 if (str->length() > 0) {
333 Put(str);
334 } else {
335 Add("/* anonymous */");
336 }
337 } else {
338 Add("%o", name);
339 }
340}
341
342
343void StringStream::PrintUsingMap(JSObject* js_object) {
344 Map* map = js_object->map();
Steve Block44f0eee2011-05-26 01:26:41 +0100345 if (!HEAP->Contains(map) ||
Steve Blocka7e24c12009-10-30 11:49:00 +0000346 !map->IsHeapObject() ||
347 !map->IsMap()) {
348 Add("<Invalid map>\n");
349 return;
350 }
351 DescriptorArray* descs = map->instance_descriptors();
352 for (int i = 0; i < descs->number_of_descriptors(); i++) {
353 switch (descs->GetType(i)) {
354 case FIELD: {
355 Object* key = descs->GetKey(i);
356 if (key->IsString() || key->IsNumber()) {
357 int len = 3;
358 if (key->IsString()) {
359 len = String::cast(key)->length();
360 }
361 for (; len < 18; len++)
362 Put(' ');
363 if (key->IsString()) {
364 Put(String::cast(key));
365 } else {
366 key->ShortPrint();
367 }
368 Add(": ");
369 Object* value = js_object->FastPropertyAt(descs->GetFieldIndex(i));
370 Add("%o\n", value);
371 }
372 }
373 break;
374 default:
375 break;
376 }
377 }
378}
379
380
381void StringStream::PrintFixedArray(FixedArray* array, unsigned int limit) {
Steve Block44f0eee2011-05-26 01:26:41 +0100382 Heap* heap = HEAP;
Steve Blocka7e24c12009-10-30 11:49:00 +0000383 for (unsigned int i = 0; i < 10 && i < limit; i++) {
384 Object* element = array->get(i);
Steve Block44f0eee2011-05-26 01:26:41 +0100385 if (element != heap->the_hole_value()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000386 for (int len = 1; len < 18; len++)
387 Put(' ');
388 Add("%d: %o\n", i, array->get(i));
389 }
390 }
391 if (limit >= 10) {
392 Add(" ...\n");
393 }
394}
395
396
397void StringStream::PrintByteArray(ByteArray* byte_array) {
398 unsigned int limit = byte_array->length();
399 for (unsigned int i = 0; i < 10 && i < limit; i++) {
400 byte b = byte_array->get(i);
401 Add(" %d: %3d 0x%02x", i, b, b);
402 if (b >= ' ' && b <= '~') {
403 Add(" '%c'", b);
404 } else if (b == '\n') {
405 Add(" '\n'");
406 } else if (b == '\r') {
407 Add(" '\r'");
408 } else if (b >= 1 && b <= 26) {
409 Add(" ^%c", b + 'A' - 1);
410 }
411 Add("\n");
412 }
413 if (limit >= 10) {
414 Add(" ...\n");
415 }
416}
417
418
419void StringStream::PrintMentionedObjectCache() {
Steve Block44f0eee2011-05-26 01:26:41 +0100420 DebugObjectCache* debug_object_cache =
421 Isolate::Current()->string_stream_debug_object_cache();
Steve Blocka7e24c12009-10-30 11:49:00 +0000422 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->HasFastElements()) {
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
453void StringStream::PrintSecurityTokenIfChanged(Object* f) {
Steve Block44f0eee2011-05-26 01:26:41 +0100454 Isolate* isolate = Isolate::Current();
455 Heap* heap = isolate->heap();
456 if (!f->IsHeapObject() || !heap->Contains(HeapObject::cast(f))) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000457 return;
458 }
459 Map* map = HeapObject::cast(f)->map();
460 if (!map->IsHeapObject() ||
Steve Block44f0eee2011-05-26 01:26:41 +0100461 !heap->Contains(map) ||
Steve Blocka7e24c12009-10-30 11:49:00 +0000462 !map->IsMap() ||
463 !f->IsJSFunction()) {
464 return;
465 }
466
467 JSFunction* fun = JSFunction::cast(f);
468 Object* perhaps_context = fun->unchecked_context();
469 if (perhaps_context->IsHeapObject() &&
Steve Block44f0eee2011-05-26 01:26:41 +0100470 heap->Contains(HeapObject::cast(perhaps_context)) &&
Steve Blocka7e24c12009-10-30 11:49:00 +0000471 perhaps_context->IsContext()) {
472 Context* context = fun->context();
Steve Block44f0eee2011-05-26 01:26:41 +0100473 if (!heap->Contains(context)) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000474 Add("(Function context is outside heap)\n");
475 return;
476 }
477 Object* token = context->global_context()->security_token();
Steve Block44f0eee2011-05-26 01:26:41 +0100478 if (token != isolate->string_stream_current_security_token()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000479 Add("Security context: %o\n", token);
Steve Block44f0eee2011-05-26 01:26:41 +0100480 isolate->set_string_stream_current_security_token(token);
Steve Blocka7e24c12009-10-30 11:49:00 +0000481 }
482 } else {
483 Add("(Function context is corrupt)\n");
484 }
485}
486
487
488void StringStream::PrintFunction(Object* f, Object* receiver, Code** code) {
489 if (f->IsHeapObject() &&
Steve Block44f0eee2011-05-26 01:26:41 +0100490 HEAP->Contains(HeapObject::cast(f)) &&
491 HEAP->Contains(HeapObject::cast(f)->map()) &&
Steve Blocka7e24c12009-10-30 11:49:00 +0000492 HeapObject::cast(f)->map()->IsMap()) {
493 if (f->IsJSFunction()) {
494 JSFunction* fun = JSFunction::cast(f);
495 // Common case: on-stack function present and resolved.
496 PrintPrototype(fun, receiver);
497 *code = fun->code();
498 } else if (f->IsSymbol()) {
499 // Unresolved and megamorphic calls: Instead of the function
500 // we have the function name on the stack.
501 PrintName(f);
502 Add("/* unresolved */ ");
503 } else {
504 // Unless this is the frame of a built-in function, we should always have
505 // the callee function or name on the stack. If we don't, we have a
506 // problem or a change of the stack frame layout.
507 Add("%o", f);
508 Add("/* warning: no JSFunction object or function name found */ ");
509 }
510 /* } else if (is_trampoline()) {
511 Print("trampoline ");
512 */
513 } else {
514 if (!f->IsHeapObject()) {
515 Add("/* warning: 'function' was not a heap object */ ");
516 return;
517 }
Steve Block44f0eee2011-05-26 01:26:41 +0100518 if (!HEAP->Contains(HeapObject::cast(f))) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000519 Add("/* warning: 'function' was not on the heap */ ");
520 return;
521 }
Steve Block44f0eee2011-05-26 01:26:41 +0100522 if (!HEAP->Contains(HeapObject::cast(f)->map())) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000523 Add("/* warning: function's map was not on the heap */ ");
524 return;
525 }
526 if (!HeapObject::cast(f)->map()->IsMap()) {
527 Add("/* warning: function's map was not a valid map */ ");
528 return;
529 }
530 Add("/* warning: Invalid JSFunction object found */ ");
531 }
532}
533
534
535void StringStream::PrintPrototype(JSFunction* fun, Object* receiver) {
536 Object* name = fun->shared()->name();
537 bool print_name = false;
Steve Block44f0eee2011-05-26 01:26:41 +0100538 Heap* heap = HEAP;
539 for (Object* p = receiver; p != heap->null_value(); p = p->GetPrototype()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000540 if (p->IsJSObject()) {
541 Object* key = JSObject::cast(p)->SlowReverseLookup(fun);
Steve Block44f0eee2011-05-26 01:26:41 +0100542 if (key != heap->undefined_value()) {
Steve Blocka7e24c12009-10-30 11:49:00 +0000543 if (!name->IsString() ||
544 !key->IsString() ||
545 !String::cast(name)->Equals(String::cast(key))) {
546 print_name = true;
547 }
548 if (name->IsString() && String::cast(name)->length() == 0) {
549 print_name = false;
550 }
551 name = key;
552 }
553 } else {
554 print_name = true;
555 }
556 }
557 PrintName(name);
558 // Also known as - if the name in the function doesn't match the name under
559 // which it was looked up.
560 if (print_name) {
561 Add("(aka ");
562 PrintName(fun->shared()->name());
563 Put(')');
564 }
565}
566
567
568char* HeapStringAllocator::grow(unsigned* bytes) {
569 unsigned new_bytes = *bytes * 2;
570 // Check for overflow.
571 if (new_bytes <= *bytes) {
572 return space_;
573 }
574 char* new_space = NewArray<char>(new_bytes);
575 if (new_space == NULL) {
576 return space_;
577 }
578 memcpy(new_space, space_, *bytes);
579 *bytes = new_bytes;
580 DeleteArray(space_);
581 space_ = new_space;
582 return new_space;
583}
584
585
586// Only grow once to the maximum allowable size.
587char* NoAllocationStringAllocator::grow(unsigned* bytes) {
588 ASSERT(size_ >= *bytes);
589 *bytes = size_;
590 return space_;
591}
592
593
594} } // namespace v8::internal