Home | History | Annotate | Download | only in src
      1 // Copyright 2011 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 SmartArrayPointer<const char> StringStream::ToCString() const {
    256   char* str = NewArray<char>(length_ + 1);
    257   memcpy(str, buffer_, length_);
    258   str[length_] = '\0';
    259   return SmartArrayPointer<const char>(str);
    260 }
    261 
    262 
    263 void StringStream::Log() {
    264   LOG(ISOLATE, StringEvent("StackDump", buffer_));
    265 }
    266 
    267 
    268 void StringStream::OutputToFile(FILE* out) {
    269   // 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';
    277     internal::PrintF(out, "%s", &buffer_[position]);
    278     buffer_[next] = save;
    279   }
    280   internal::PrintF(out, "%s", &buffer_[position]);
    281 }
    282 
    283 
    284 Handle<String> StringStream::ToString() {
    285   return FACTORY->NewStringFromUtf8(Vector<const char>(buffer_, length_));
    286 }
    287 
    288 
    289 void StringStream::ClearMentionedObjectCache() {
    290   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));
    295   }
    296   isolate->string_stream_debug_object_cache()->Clear();
    297 }
    298 
    299 
    300 #ifdef DEBUG
    301 bool StringStream::IsMentionedObjectCacheClear() {
    302   return (
    303       Isolate::Current()->string_stream_debug_object_cache()->length() == 0);
    304 }
    305 #endif
    306 
    307 
    308 bool StringStream::Put(String* str) {
    309   return Put(str, 0, str->length());
    310 }
    311 
    312 
    313 bool 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 
    329 void 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 
    343 void StringStream::PrintUsingMap(JSObject* js_object) {
    344   Map* map = js_object->map();
    345   if (!HEAP->Contains(map) ||
    346       !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     if (descs->GetType(i) == FIELD) {
    354       Object* key = descs->GetKey(i);
    355       if (key->IsString() || key->IsNumber()) {
    356         int len = 3;
    357         if (key->IsString()) {
    358           len = String::cast(key)->length();
    359         }
    360         for (; len < 18; len++)
    361           Put(' ');
    362         if (key->IsString()) {
    363           Put(String::cast(key));
    364         } else {
    365           key->ShortPrint();
    366         }
    367         Add(": ");
    368         Object* value = js_object->FastPropertyAt(descs->GetFieldIndex(i));
    369         Add("%o\n", value);
    370       }
    371     }
    372   }
    373 }
    374 
    375 
    376 void StringStream::PrintFixedArray(FixedArray* array, unsigned int limit) {
    377   Heap* heap = HEAP;
    378   for (unsigned int i = 0; i < 10 && i < limit; i++) {
    379     Object* element = array->get(i);
    380     if (element != heap->the_hole_value()) {
    381       for (int len = 1; len < 18; len++)
    382         Put(' ');
    383       Add("%d: %o\n", i, array->get(i));
    384     }
    385   }
    386   if (limit >= 10) {
    387     Add("                  ...\n");
    388   }
    389 }
    390 
    391 
    392 void StringStream::PrintByteArray(ByteArray* byte_array) {
    393   unsigned int limit = byte_array->length();
    394   for (unsigned int i = 0; i < 10 && i < limit; i++) {
    395     byte b = byte_array->get(i);
    396     Add("             %d: %3d 0x%02x", i, b, b);
    397     if (b >= ' ' && b <= '~') {
    398       Add(" '%c'", b);
    399     } else if (b == '\n') {
    400       Add(" '\n'");
    401     } else if (b == '\r') {
    402       Add(" '\r'");
    403     } else if (b >= 1 && b <= 26) {
    404       Add(" ^%c", b + 'A' - 1);
    405     }
    406     Add("\n");
    407   }
    408   if (limit >= 10) {
    409     Add("                  ...\n");
    410   }
    411 }
    412 
    413 
    414 void StringStream::PrintMentionedObjectCache() {
    415   DebugObjectCache* debug_object_cache =
    416       Isolate::Current()->string_stream_debug_object_cache();
    417   Add("==== Key         ============================================\n\n");
    418   for (int i = 0; i < debug_object_cache->length(); i++) {
    419     HeapObject* printee = (*debug_object_cache)[i];
    420     Add(" #%d# %p: ", i, printee);
    421     printee->ShortPrint(this);
    422     Add("\n");
    423     if (printee->IsJSObject()) {
    424       if (printee->IsJSValue()) {
    425         Add("           value(): %o\n", JSValue::cast(printee)->value());
    426       }
    427       PrintUsingMap(JSObject::cast(printee));
    428       if (printee->IsJSArray()) {
    429         JSArray* array = JSArray::cast(printee);
    430         if (array->HasFastElements()) {
    431           unsigned int limit = FixedArray::cast(array->elements())->length();
    432           unsigned int length =
    433             static_cast<uint32_t>(JSArray::cast(array)->length()->Number());
    434           if (length < limit) limit = length;
    435           PrintFixedArray(FixedArray::cast(array->elements()), limit);
    436         }
    437       }
    438     } else if (printee->IsByteArray()) {
    439       PrintByteArray(ByteArray::cast(printee));
    440     } else if (printee->IsFixedArray()) {
    441       unsigned int limit = FixedArray::cast(printee)->length();
    442       PrintFixedArray(FixedArray::cast(printee), limit);
    443     }
    444   }
    445 }
    446 
    447 
    448 void StringStream::PrintSecurityTokenIfChanged(Object* f) {
    449   Isolate* isolate = Isolate::Current();
    450   Heap* heap = isolate->heap();
    451   if (!f->IsHeapObject() || !heap->Contains(HeapObject::cast(f))) {
    452     return;
    453   }
    454   Map* map = HeapObject::cast(f)->map();
    455   if (!map->IsHeapObject() ||
    456       !heap->Contains(map) ||
    457       !map->IsMap() ||
    458       !f->IsJSFunction()) {
    459     return;
    460   }
    461 
    462   JSFunction* fun = JSFunction::cast(f);
    463   Object* perhaps_context = fun->unchecked_context();
    464   if (perhaps_context->IsHeapObject() &&
    465       heap->Contains(HeapObject::cast(perhaps_context)) &&
    466       perhaps_context->IsContext()) {
    467     Context* context = fun->context();
    468     if (!heap->Contains(context)) {
    469       Add("(Function context is outside heap)\n");
    470       return;
    471     }
    472     Object* token = context->global_context()->security_token();
    473     if (token != isolate->string_stream_current_security_token()) {
    474       Add("Security context: %o\n", token);
    475       isolate->set_string_stream_current_security_token(token);
    476     }
    477   } else {
    478     Add("(Function context is corrupt)\n");
    479   }
    480 }
    481 
    482 
    483 void StringStream::PrintFunction(Object* f, Object* receiver, Code** code) {
    484   if (f->IsHeapObject() &&
    485       HEAP->Contains(HeapObject::cast(f)) &&
    486       HEAP->Contains(HeapObject::cast(f)->map()) &&
    487       HeapObject::cast(f)->map()->IsMap()) {
    488     if (f->IsJSFunction()) {
    489       JSFunction* fun = JSFunction::cast(f);
    490       // Common case: on-stack function present and resolved.
    491       PrintPrototype(fun, receiver);
    492       *code = fun->code();
    493     } else if (f->IsSymbol()) {
    494       // Unresolved and megamorphic calls: Instead of the function
    495       // we have the function name on the stack.
    496       PrintName(f);
    497       Add("/* unresolved */ ");
    498     } else {
    499       // Unless this is the frame of a built-in function, we should always have
    500       // the callee function or name on the stack. If we don't, we have a
    501       // problem or a change of the stack frame layout.
    502       Add("%o", f);
    503       Add("/* warning: no JSFunction object or function name found */ ");
    504     }
    505     /* } else if (is_trampoline()) {
    506        Print("trampoline ");
    507     */
    508   } else {
    509     if (!f->IsHeapObject()) {
    510       Add("/* warning: 'function' was not a heap object */ ");
    511       return;
    512     }
    513     if (!HEAP->Contains(HeapObject::cast(f))) {
    514       Add("/* warning: 'function' was not on the heap */ ");
    515       return;
    516     }
    517     if (!HEAP->Contains(HeapObject::cast(f)->map())) {
    518       Add("/* warning: function's map was not on the heap */ ");
    519       return;
    520     }
    521     if (!HeapObject::cast(f)->map()->IsMap()) {
    522       Add("/* warning: function's map was not a valid map */ ");
    523       return;
    524     }
    525     Add("/* warning: Invalid JSFunction object found */ ");
    526   }
    527 }
    528 
    529 
    530 void StringStream::PrintPrototype(JSFunction* fun, Object* receiver) {
    531   Object* name = fun->shared()->name();
    532   bool print_name = false;
    533   Heap* heap = HEAP;
    534   for (Object* p = receiver; p != heap->null_value(); p = p->GetPrototype()) {
    535     if (p->IsJSObject()) {
    536       Object* key = JSObject::cast(p)->SlowReverseLookup(fun);
    537       if (key != 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 
    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   memcpy(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.
    582 char* NoAllocationStringAllocator::grow(unsigned* bytes) {
    583   ASSERT(size_ >= *bytes);
    584   *bytes = size_;
    585   return space_;
    586 }
    587 
    588 
    589 } }  // namespace v8::internal
    590