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