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/strings/string-stream.h"
6 
7 #include <memory>
8 
9 #include "src/handles/handles-inl.h"
10 #include "src/logging/log.h"
11 #include "src/objects/js-array-inl.h"
12 #include "src/objects/objects-inl.h"
13 #include "src/objects/prototype.h"
14 #include "src/utils/vector.h"
15 
16 namespace v8 {
17 namespace internal {
18 
19 static const int kMentionedObjectCacheMaxSize = 256;
20 
allocate(unsigned bytes)21 char* HeapStringAllocator::allocate(unsigned bytes) {
22   space_ = NewArray<char>(bytes);
23   return space_;
24 }
25 
allocate(unsigned bytes)26 char* FixedStringAllocator::allocate(unsigned bytes) {
27   CHECK_LE(bytes, length_);
28   return buffer_;
29 }
30 
grow(unsigned * old)31 char* FixedStringAllocator::grow(unsigned* old) {
32   *old = length_;
33   return buffer_;
34 }
35 
Put(char c)36 bool StringStream::Put(char c) {
37   if (full()) return false;
38   DCHECK(length_ < capacity_);
39   // Since the trailing '\0' is not accounted for in length_ fullness is
40   // indicated by a difference of 1 between length_ and capacity_. Thus when
41   // reaching a difference of 2 we need to grow the buffer.
42   if (length_ == capacity_ - 2) {
43     unsigned new_capacity = capacity_;
44     char* new_buffer = allocator_->grow(&new_capacity);
45     if (new_capacity > capacity_) {
46       capacity_ = new_capacity;
47       buffer_ = new_buffer;
48     } else {
49       // Reached the end of the available buffer.
50       DCHECK_GE(capacity_, 5);
51       length_ = capacity_ - 1;  // Indicate fullness of the stream.
52       buffer_[length_ - 4] = '.';
53       buffer_[length_ - 3] = '.';
54       buffer_[length_ - 2] = '.';
55       buffer_[length_ - 1] = '\n';
56       buffer_[length_] = '\0';
57       return false;
58     }
59   }
60   buffer_[length_] = c;
61   buffer_[length_ + 1] = '\0';
62   length_++;
63   return true;
64 }
65 
66 // A control character is one that configures a format element.  For
67 // instance, in %.5s, .5 are control characters.
IsControlChar(char c)68 static bool IsControlChar(char c) {
69   switch (c) {
70     case '0':
71     case '1':
72     case '2':
73     case '3':
74     case '4':
75     case '5':
76     case '6':
77     case '7':
78     case '8':
79     case '9':
80     case '.':
81     case '-':
82       return true;
83     default:
84       return false;
85   }
86 }
87 
Add(Vector<const char> format,Vector<FmtElm> elms)88 void StringStream::Add(Vector<const char> format, Vector<FmtElm> elms) {
89   // If we already ran out of space then return immediately.
90   if (full()) return;
91   int offset = 0;
92   int elm = 0;
93   while (offset < format.length()) {
94     if (format[offset] != '%' || elm == elms.length()) {
95       Put(format[offset]);
96       offset++;
97       continue;
98     }
99     // Read this formatting directive into a temporary buffer
100     EmbeddedVector<char, 24> temp;
101     int format_length = 0;
102     // Skip over the whole control character sequence until the
103     // format element type
104     temp[format_length++] = format[offset++];
105     while (offset < format.length() && IsControlChar(format[offset]))
106       temp[format_length++] = format[offset++];
107     if (offset >= format.length()) return;
108     char type = format[offset];
109     temp[format_length++] = type;
110     temp[format_length] = '\0';
111     offset++;
112     FmtElm current = elms[elm++];
113     switch (type) {
114       case 's': {
115         DCHECK_EQ(FmtElm::C_STR, current.type_);
116         const char* value = current.data_.u_c_str_;
117         Add(value);
118         break;
119       }
120       case 'w': {
121         DCHECK_EQ(FmtElm::LC_STR, current.type_);
122         Vector<const uc16> value = *current.data_.u_lc_str_;
123         for (int i = 0; i < value.length(); i++)
124           Put(static_cast<char>(value[i]));
125         break;
126       }
127       case 'o': {
128         DCHECK_EQ(FmtElm::OBJ, current.type_);
129         Object obj(current.data_.u_obj_);
130         PrintObject(obj);
131         break;
132       }
133       case 'k': {
134         DCHECK_EQ(FmtElm::INT, current.type_);
135         int value = current.data_.u_int_;
136         if (0x20 <= value && value <= 0x7F) {
137           Put(value);
138         } else if (value <= 0xFF) {
139           Add("\\x%02x", value);
140         } else {
141           Add("\\u%04x", value);
142         }
143         break;
144       }
145       case 'i':
146       case 'd':
147       case 'u':
148       case 'x':
149       case 'c':
150       case 'X': {
151         int value = current.data_.u_int_;
152         EmbeddedVector<char, 24> formatted;
153         int length = SNPrintF(formatted, temp.begin(), value);
154         Add(Vector<const char>(formatted.begin(), length));
155         break;
156       }
157       case 'f':
158       case 'g':
159       case 'G':
160       case 'e':
161       case 'E': {
162         double value = current.data_.u_double_;
163         int inf = std::isinf(value);
164         if (inf == -1) {
165           Add("-inf");
166         } else if (inf == 1) {
167           Add("inf");
168         } else if (std::isnan(value)) {
169           Add("nan");
170         } else {
171           EmbeddedVector<char, 28> formatted;
172           SNPrintF(formatted, temp.begin(), value);
173           Add(formatted.begin());
174         }
175         break;
176       }
177       case 'p': {
178         void* value = current.data_.u_pointer_;
179         EmbeddedVector<char, 20> formatted;
180         SNPrintF(formatted, temp.begin(), value);
181         Add(formatted.begin());
182         break;
183       }
184       default:
185         UNREACHABLE();
186     }
187   }
188 
189   // Verify that the buffer is 0-terminated
190   DCHECK_EQ(buffer_[length_], '\0');
191 }
192 
PrintObject(Object o)193 void StringStream::PrintObject(Object o) {
194   o.ShortPrint(this);
195   if (o.IsString()) {
196     if (String::cast(o).length() <= String::kMaxShortPrintLength) {
197       return;
198     }
199   } else if (o.IsNumber() || o.IsOddball()) {
200     return;
201   }
202   if (o.IsHeapObject() && object_print_mode_ == kPrintObjectVerbose) {
203     // TODO(delphick): Consider whether we can get the isolate without using
204     // TLS.
205     Isolate* isolate = Isolate::Current();
206     DebugObjectCache* debug_object_cache =
207         isolate->string_stream_debug_object_cache();
208     for (size_t i = 0; i < debug_object_cache->size(); i++) {
209       if (*(*debug_object_cache)[i] == o) {
210         Add("#%d#", static_cast<int>(i));
211         return;
212       }
213     }
214     if (debug_object_cache->size() < kMentionedObjectCacheMaxSize) {
215       Add("#%d#", static_cast<int>(debug_object_cache->size()));
216       debug_object_cache->push_back(handle(HeapObject::cast(o), isolate));
217     } else {
218       Add("@%p", o);
219     }
220   }
221 }
222 
ToCString() const223 std::unique_ptr<char[]> StringStream::ToCString() const {
224   char* str = NewArray<char>(length_ + 1);
225   MemCopy(str, buffer_, length_);
226   str[length_] = '\0';
227   return std::unique_ptr<char[]>(str);
228 }
229 
Log(Isolate * isolate)230 void StringStream::Log(Isolate* isolate) {
231   LOG(isolate, StringEvent("StackDump", buffer_));
232 }
233 
OutputToFile(FILE * out)234 void StringStream::OutputToFile(FILE* out) {
235   // Dump the output to stdout, but make sure to break it up into
236   // manageable chunks to avoid losing parts of the output in the OS
237   // printing code. This is a problem on Windows in particular; see
238   // the VPrint() function implementations in platform-win32.cc.
239   unsigned position = 0;
240   for (unsigned next; (next = position + 2048) < length_; position = next) {
241     char save = buffer_[next];
242     buffer_[next] = '\0';
243     internal::PrintF(out, "%s", &buffer_[position]);
244     buffer_[next] = save;
245   }
246   internal::PrintF(out, "%s", &buffer_[position]);
247 }
248 
ToString(Isolate * isolate)249 Handle<String> StringStream::ToString(Isolate* isolate) {
250   return isolate->factory()
251       ->NewStringFromUtf8(Vector<const char>(buffer_, length_))
252       .ToHandleChecked();
253 }
254 
ClearMentionedObjectCache(Isolate * isolate)255 void StringStream::ClearMentionedObjectCache(Isolate* isolate) {
256   isolate->set_string_stream_current_security_token(Object());
257   if (isolate->string_stream_debug_object_cache() == nullptr) {
258     isolate->set_string_stream_debug_object_cache(new DebugObjectCache());
259   }
260   isolate->string_stream_debug_object_cache()->clear();
261 }
262 
263 #ifdef DEBUG
IsMentionedObjectCacheClear(Isolate * isolate)264 bool StringStream::IsMentionedObjectCacheClear(Isolate* isolate) {
265   return object_print_mode_ == kPrintObjectConcise ||
266          isolate->string_stream_debug_object_cache()->size() == 0;
267 }
268 #endif
269 
Put(String str)270 bool StringStream::Put(String str) { return Put(str, 0, str.length()); }
271 
Put(String str,int start,int end)272 bool StringStream::Put(String str, int start, int end) {
273   StringCharacterStream stream(str, start);
274   for (int i = start; i < end && stream.HasMore(); i++) {
275     uint16_t c = stream.GetNext();
276     if (c >= 127 || c < 32) {
277       c = '?';
278     }
279     if (!Put(static_cast<char>(c))) {
280       return false;  // Output was truncated.
281     }
282   }
283   return true;
284 }
285 
PrintName(Object name)286 void StringStream::PrintName(Object name) {
287   if (name.IsString()) {
288     String str = String::cast(name);
289     if (str.length() > 0) {
290       Put(str);
291     } else {
292       Add("/* anonymous */");
293     }
294   } else {
295     Add("%o", name);
296   }
297 }
298 
PrintUsingMap(JSObject js_object)299 void StringStream::PrintUsingMap(JSObject js_object) {
300   Map map = js_object.map();
301   DescriptorArray descs = map.instance_descriptors(kRelaxedLoad);
302   for (InternalIndex i : map.IterateOwnDescriptors()) {
303     PropertyDetails details = descs.GetDetails(i);
304     if (details.location() == kField) {
305       DCHECK_EQ(kData, details.kind());
306       Object key = descs.GetKey(i);
307       if (key.IsString() || key.IsNumber()) {
308         int len = 3;
309         if (key.IsString()) {
310           len = String::cast(key).length();
311         }
312         for (; len < 18; len++) Put(' ');
313         if (key.IsString()) {
314           Put(String::cast(key));
315         } else {
316           key.ShortPrint();
317         }
318         Add(": ");
319         FieldIndex index = FieldIndex::ForDescriptor(map, i);
320         if (js_object.IsUnboxedDoubleField(index)) {
321           double value = js_object.RawFastDoublePropertyAt(index);
322           Add("<unboxed double> %.16g\n", FmtElm(value));
323         } else {
324           Object value = js_object.RawFastPropertyAt(index);
325           Add("%o\n", value);
326         }
327       }
328     }
329   }
330 }
331 
PrintFixedArray(FixedArray array,unsigned int limit)332 void StringStream::PrintFixedArray(FixedArray array, unsigned int limit) {
333   ReadOnlyRoots roots = array.GetReadOnlyRoots();
334   for (unsigned int i = 0; i < 10 && i < limit; i++) {
335     Object element = array.get(i);
336     if (element.IsTheHole(roots)) continue;
337     for (int len = 1; len < 18; len++) {
338       Put(' ');
339     }
340     Add("%d: %o\n", i, array.get(i));
341   }
342   if (limit >= 10) {
343     Add("                  ...\n");
344   }
345 }
346 
PrintByteArray(ByteArray byte_array)347 void StringStream::PrintByteArray(ByteArray byte_array) {
348   unsigned int limit = byte_array.length();
349   for (unsigned int i = 0; i < 10 && i < limit; i++) {
350     byte b = byte_array.get(i);
351     Add("             %d: %3d 0x%02x", i, b, b);
352     if (b >= ' ' && b <= '~') {
353       Add(" '%c'", b);
354     } else if (b == '\n') {
355       Add(" '\n'");
356     } else if (b == '\r') {
357       Add(" '\r'");
358     } else if (b >= 1 && b <= 26) {
359       Add(" ^%c", b + 'A' - 1);
360     }
361     Add("\n");
362   }
363   if (limit >= 10) {
364     Add("                  ...\n");
365   }
366 }
367 
PrintMentionedObjectCache(Isolate * isolate)368 void StringStream::PrintMentionedObjectCache(Isolate* isolate) {
369   if (object_print_mode_ == kPrintObjectConcise) return;
370   DebugObjectCache* debug_object_cache =
371       isolate->string_stream_debug_object_cache();
372   Add("==== Key         ============================================\n\n");
373   for (size_t i = 0; i < debug_object_cache->size(); i++) {
374     HeapObject printee = *(*debug_object_cache)[i];
375     Add(" #%d# %p: ", static_cast<int>(i),
376         reinterpret_cast<void*>(printee.ptr()));
377     printee.ShortPrint(this);
378     Add("\n");
379     if (printee.IsJSObject()) {
380       if (printee.IsJSPrimitiveWrapper()) {
381         Add("           value(): %o\n",
382             JSPrimitiveWrapper::cast(printee).value());
383       }
384       PrintUsingMap(JSObject::cast(printee));
385       if (printee.IsJSArray()) {
386         JSArray array = JSArray::cast(printee);
387         if (array.HasObjectElements()) {
388           unsigned int limit = FixedArray::cast(array.elements()).length();
389           unsigned int length =
390               static_cast<uint32_t>(JSArray::cast(array).length().Number());
391           if (length < limit) limit = length;
392           PrintFixedArray(FixedArray::cast(array.elements()), limit);
393         }
394       }
395     } else if (printee.IsByteArray()) {
396       PrintByteArray(ByteArray::cast(printee));
397     } else if (printee.IsFixedArray()) {
398       unsigned int limit = FixedArray::cast(printee).length();
399       PrintFixedArray(FixedArray::cast(printee), limit);
400     }
401   }
402 }
403 
PrintSecurityTokenIfChanged(JSFunction fun)404 void StringStream::PrintSecurityTokenIfChanged(JSFunction fun) {
405   Object token = fun.native_context().security_token();
406   Isolate* isolate = fun.GetIsolate();
407   if (token != isolate->string_stream_current_security_token()) {
408     Add("Security context: %o\n", token);
409     isolate->set_string_stream_current_security_token(token);
410   }
411 }
412 
PrintFunction(JSFunction fun,Object receiver,Code * code)413 void StringStream::PrintFunction(JSFunction fun, Object receiver, Code* code) {
414   PrintPrototype(fun, receiver);
415   *code = fun.code();
416 }
417 
PrintPrototype(JSFunction fun,Object receiver)418 void StringStream::PrintPrototype(JSFunction fun, Object receiver) {
419   Object name = fun.shared().Name();
420   bool print_name = false;
421   Isolate* isolate = fun.GetIsolate();
422   if (receiver.IsNullOrUndefined(isolate) || receiver.IsTheHole(isolate) ||
423       receiver.IsJSProxy()) {
424     print_name = true;
425   } else if (!isolate->context().is_null()) {
426     if (!receiver.IsJSObject()) {
427       receiver = receiver.GetPrototypeChainRootMap(isolate).prototype();
428     }
429 
430     for (PrototypeIterator iter(isolate, JSObject::cast(receiver),
431                                 kStartAtReceiver);
432          !iter.IsAtEnd(); iter.Advance()) {
433       if (iter.GetCurrent().IsJSProxy()) break;
434       Object key = iter.GetCurrent<JSObject>().SlowReverseLookup(fun);
435       if (!key.IsUndefined(isolate)) {
436         if (!name.IsString() || !key.IsString() ||
437             !String::cast(name).Equals(String::cast(key))) {
438           print_name = true;
439         }
440         if (name.IsString() && String::cast(name).length() == 0) {
441           print_name = false;
442         }
443         name = key;
444         break;
445       }
446     }
447   }
448   PrintName(name);
449   // Also known as - if the name in the function doesn't match the name under
450   // which it was looked up.
451   if (print_name) {
452     Add("(aka ");
453     PrintName(fun.shared().Name());
454     Put(')');
455   }
456 }
457 
grow(unsigned * bytes)458 char* HeapStringAllocator::grow(unsigned* bytes) {
459   unsigned new_bytes = *bytes * 2;
460   // Check for overflow.
461   if (new_bytes <= *bytes) {
462     return space_;
463   }
464   char* new_space = NewArray<char>(new_bytes);
465   if (new_space == nullptr) {
466     return space_;
467   }
468   MemCopy(new_space, space_, *bytes);
469   *bytes = new_bytes;
470   DeleteArray(space_);
471   space_ = new_space;
472   return new_space;
473 }
474 
475 }  // namespace internal
476 }  // namespace v8
477