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