blob: d6d8754b23e1a38e0bd1d5b583124464d8f54bae [file] [log] [blame]
Steve Blocka7e24c12009-10-30 11:49:00 +00001// Copyright 2009 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 "log-utils.h"
31
32namespace v8 {
33namespace internal {
34
35#ifdef ENABLE_LOGGING_AND_PROFILING
36
37LogDynamicBuffer::LogDynamicBuffer(
38 int block_size, int max_size, const char* seal, int seal_size)
39 : block_size_(block_size),
40 max_size_(max_size - (max_size % block_size_)),
41 seal_(seal),
42 seal_size_(seal_size),
43 blocks_(max_size_ / block_size_ + 1),
44 write_pos_(0), block_index_(0), block_write_pos_(0), is_sealed_(false) {
45 ASSERT(BlocksCount() > 0);
46 AllocateBlock(0);
47 for (int i = 1; i < BlocksCount(); ++i) {
48 blocks_[i] = NULL;
49 }
50}
51
52
53LogDynamicBuffer::~LogDynamicBuffer() {
54 for (int i = 0; i < BlocksCount(); ++i) {
55 DeleteArray(blocks_[i]);
56 }
57}
58
59
60int LogDynamicBuffer::Read(int from_pos, char* dest_buf, int buf_size) {
61 if (buf_size == 0) return 0;
62 int read_pos = from_pos;
63 int block_read_index = BlockIndex(from_pos);
64 int block_read_pos = PosInBlock(from_pos);
65 int dest_buf_pos = 0;
66 // Read until dest_buf is filled, or write_pos_ encountered.
67 while (read_pos < write_pos_ && dest_buf_pos < buf_size) {
68 const int read_size = Min(write_pos_ - read_pos,
69 Min(buf_size - dest_buf_pos, block_size_ - block_read_pos));
70 memcpy(dest_buf + dest_buf_pos,
71 blocks_[block_read_index] + block_read_pos, read_size);
72 block_read_pos += read_size;
73 dest_buf_pos += read_size;
74 read_pos += read_size;
75 if (block_read_pos == block_size_) {
76 block_read_pos = 0;
77 ++block_read_index;
78 }
79 }
80 return dest_buf_pos;
81}
82
83
84int LogDynamicBuffer::Seal() {
85 WriteInternal(seal_, seal_size_);
86 is_sealed_ = true;
87 return 0;
88}
89
90
91int LogDynamicBuffer::Write(const char* data, int data_size) {
92 if (is_sealed_) {
93 return 0;
94 }
95 if ((write_pos_ + data_size) <= (max_size_ - seal_size_)) {
96 return WriteInternal(data, data_size);
97 } else {
98 return Seal();
99 }
100}
101
102
103int LogDynamicBuffer::WriteInternal(const char* data, int data_size) {
104 int data_pos = 0;
105 while (data_pos < data_size) {
106 const int write_size =
107 Min(data_size - data_pos, block_size_ - block_write_pos_);
108 memcpy(blocks_[block_index_] + block_write_pos_, data + data_pos,
109 write_size);
110 block_write_pos_ += write_size;
111 data_pos += write_size;
112 if (block_write_pos_ == block_size_) {
113 block_write_pos_ = 0;
114 AllocateBlock(++block_index_);
115 }
116 }
117 write_pos_ += data_size;
118 return data_size;
119}
120
121
122bool Log::is_stopped_ = false;
123Log::WritePtr Log::Write = NULL;
124FILE* Log::output_handle_ = NULL;
Ben Murdochf87a2032010-10-22 12:50:53 +0100125FILE* Log::output_code_handle_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000126LogDynamicBuffer* Log::output_buffer_ = NULL;
127// Must be the same message as in Logger::PauseProfiler.
128const char* Log::kDynamicBufferSeal = "profiler,\"pause\"\n";
129Mutex* Log::mutex_ = NULL;
130char* Log::message_buffer_ = NULL;
131
132
133void Log::Init() {
134 mutex_ = OS::CreateMutex();
135 message_buffer_ = NewArray<char>(kMessageBufferSize);
136}
137
138
139void Log::OpenStdout() {
140 ASSERT(!IsEnabled());
141 output_handle_ = stdout;
142 Write = WriteToFile;
143 Init();
144}
145
146
Ben Murdochf87a2032010-10-22 12:50:53 +0100147static const char kCodeLogExt[] = ".code";
148
149
Steve Blocka7e24c12009-10-30 11:49:00 +0000150void Log::OpenFile(const char* name) {
151 ASSERT(!IsEnabled());
152 output_handle_ = OS::FOpen(name, OS::LogFileOpenMode);
Ben Murdochf87a2032010-10-22 12:50:53 +0100153 if (FLAG_ll_prof) {
154 // Open a file for logging the contents of code objects so that
155 // they can be disassembled later.
156 size_t name_len = strlen(name);
157 ScopedVector<char> code_name(
158 static_cast<int>(name_len + sizeof(kCodeLogExt)));
159 memcpy(code_name.start(), name, name_len);
160 memcpy(code_name.start() + name_len, kCodeLogExt, sizeof(kCodeLogExt));
161 output_code_handle_ = OS::FOpen(code_name.start(), OS::LogFileOpenMode);
162 }
Steve Blocka7e24c12009-10-30 11:49:00 +0000163 Write = WriteToFile;
164 Init();
165}
166
167
168void Log::OpenMemoryBuffer() {
169 ASSERT(!IsEnabled());
170 output_buffer_ = new LogDynamicBuffer(
171 kDynamicBufferBlockSize, kMaxDynamicBufferSize,
Steve Blockd0582a62009-12-15 09:54:21 +0000172 kDynamicBufferSeal, StrLength(kDynamicBufferSeal));
Steve Blocka7e24c12009-10-30 11:49:00 +0000173 Write = WriteToMemory;
174 Init();
175}
176
177
178void Log::Close() {
179 if (Write == WriteToFile) {
180 if (output_handle_ != NULL) fclose(output_handle_);
181 output_handle_ = NULL;
Ben Murdochf87a2032010-10-22 12:50:53 +0100182 if (output_code_handle_ != NULL) fclose(output_code_handle_);
183 output_code_handle_ = NULL;
Steve Blocka7e24c12009-10-30 11:49:00 +0000184 } else if (Write == WriteToMemory) {
185 delete output_buffer_;
186 output_buffer_ = NULL;
187 } else {
188 ASSERT(Write == NULL);
189 }
190 Write = NULL;
191
192 DeleteArray(message_buffer_);
193 message_buffer_ = NULL;
194
195 delete mutex_;
196 mutex_ = NULL;
197
198 is_stopped_ = false;
199}
200
201
202int Log::GetLogLines(int from_pos, char* dest_buf, int max_size) {
203 if (Write != WriteToMemory) return 0;
204 ASSERT(output_buffer_ != NULL);
205 ASSERT(from_pos >= 0);
206 ASSERT(max_size >= 0);
207 int actual_size = output_buffer_->Read(from_pos, dest_buf, max_size);
208 ASSERT(actual_size <= max_size);
209 if (actual_size == 0) return 0;
210
211 // Find previous log line boundary.
212 char* end_pos = dest_buf + actual_size - 1;
213 while (end_pos >= dest_buf && *end_pos != '\n') --end_pos;
Steve Blockd0582a62009-12-15 09:54:21 +0000214 actual_size = static_cast<int>(end_pos - dest_buf + 1);
Steve Block6ded16b2010-05-10 14:33:55 +0100215 // If the assertion below is hit, it means that there was no line end
216 // found --- something wrong has happened.
217 ASSERT(actual_size > 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000218 ASSERT(actual_size <= max_size);
219 return actual_size;
220}
221
222
223LogMessageBuilder::WriteFailureHandler
224 LogMessageBuilder::write_failure_handler = NULL;
225
226
227LogMessageBuilder::LogMessageBuilder(): sl(Log::mutex_), pos_(0) {
228 ASSERT(Log::message_buffer_ != NULL);
229}
230
231
232void LogMessageBuilder::Append(const char* format, ...) {
233 Vector<char> buf(Log::message_buffer_ + pos_,
234 Log::kMessageBufferSize - pos_);
235 va_list args;
236 va_start(args, format);
237 AppendVA(format, args);
238 va_end(args);
239 ASSERT(pos_ <= Log::kMessageBufferSize);
240}
241
242
243void LogMessageBuilder::AppendVA(const char* format, va_list args) {
244 Vector<char> buf(Log::message_buffer_ + pos_,
245 Log::kMessageBufferSize - pos_);
246 int result = v8::internal::OS::VSNPrintF(buf, format, args);
247
248 // Result is -1 if output was truncated.
249 if (result >= 0) {
250 pos_ += result;
251 } else {
252 pos_ = Log::kMessageBufferSize;
253 }
254 ASSERT(pos_ <= Log::kMessageBufferSize);
255}
256
257
258void LogMessageBuilder::Append(const char c) {
259 if (pos_ < Log::kMessageBufferSize) {
260 Log::message_buffer_[pos_++] = c;
261 }
262 ASSERT(pos_ <= Log::kMessageBufferSize);
263}
264
265
266void LogMessageBuilder::Append(String* str) {
267 AssertNoAllocation no_heap_allocation; // Ensure string stay valid.
268 int length = str->length();
269 for (int i = 0; i < length; i++) {
270 Append(static_cast<char>(str->Get(i)));
271 }
272}
273
274
275void LogMessageBuilder::AppendAddress(Address addr) {
276 static Address last_address_ = NULL;
277 AppendAddress(addr, last_address_);
278 last_address_ = addr;
279}
280
281
282void LogMessageBuilder::AppendAddress(Address addr, Address bias) {
283 if (!FLAG_compress_log) {
284 Append("0x%" V8PRIxPTR, addr);
285 } else if (bias == NULL) {
286 Append("%" V8PRIxPTR, addr);
287 } else {
288 uintptr_t delta;
289 char sign;
290 if (addr >= bias) {
291 delta = addr - bias;
292 sign = '+';
293 } else {
294 delta = bias - addr;
295 sign = '-';
296 }
297 Append("%c%" V8PRIxPTR, sign, delta);
298 }
299}
300
301
302void LogMessageBuilder::AppendDetailed(String* str, bool show_impl_info) {
303 AssertNoAllocation no_heap_allocation; // Ensure string stay valid.
304 int len = str->length();
305 if (len > 0x1000)
306 len = 0x1000;
307 if (show_impl_info) {
308 Append(str->IsAsciiRepresentation() ? 'a' : '2');
309 if (StringShape(str).IsExternal())
310 Append('e');
311 if (StringShape(str).IsSymbol())
312 Append('#');
313 Append(":%i:", str->length());
314 }
315 for (int i = 0; i < len; i++) {
316 uc32 c = str->Get(i);
317 if (c > 0xff) {
318 Append("\\u%04x", c);
319 } else if (c < 32 || c > 126) {
320 Append("\\x%02x", c);
321 } else if (c == ',') {
322 Append("\\,");
323 } else if (c == '\\') {
324 Append("\\\\");
325 } else {
326 Append("%lc", c);
327 }
328 }
329}
330
331
332void LogMessageBuilder::AppendStringPart(const char* str, int len) {
333 if (pos_ + len > Log::kMessageBufferSize) {
334 len = Log::kMessageBufferSize - pos_;
335 ASSERT(len >= 0);
336 if (len == 0) return;
337 }
338 Vector<char> buf(Log::message_buffer_ + pos_,
339 Log::kMessageBufferSize - pos_);
340 OS::StrNCpy(buf, str, len);
341 pos_ += len;
342 ASSERT(pos_ <= Log::kMessageBufferSize);
343}
344
345
346bool LogMessageBuilder::StoreInCompressor(LogRecordCompressor* compressor) {
347 return compressor->Store(Vector<const char>(Log::message_buffer_, pos_));
348}
349
350
351bool LogMessageBuilder::RetrieveCompressedPrevious(
352 LogRecordCompressor* compressor, const char* prefix) {
353 pos_ = 0;
354 if (prefix[0] != '\0') Append(prefix);
355 Vector<char> prev_record(Log::message_buffer_ + pos_,
356 Log::kMessageBufferSize - pos_);
357 const bool has_prev = compressor->RetrievePreviousCompressed(&prev_record);
358 if (!has_prev) return false;
359 pos_ += prev_record.length();
360 return true;
361}
362
363
364void LogMessageBuilder::WriteToLogFile() {
365 ASSERT(pos_ <= Log::kMessageBufferSize);
366 const int written = Log::Write(Log::message_buffer_, pos_);
367 if (written != pos_ && write_failure_handler != NULL) {
368 write_failure_handler();
369 }
370}
371
372
Steve Blocka7e24c12009-10-30 11:49:00 +0000373// Formatting string for back references to the whole line. E.g. "#2" means
374// "the second line above".
375const char* LogRecordCompressor::kLineBackwardReferenceFormat = "#%d";
376
377// Formatting string for back references. E.g. "#2:10" means
378// "the second line above, start from char 10 (0-based)".
379const char* LogRecordCompressor::kBackwardReferenceFormat = "#%d:%d";
380
381
382LogRecordCompressor::~LogRecordCompressor() {
383 for (int i = 0; i < buffer_.length(); ++i) {
384 buffer_[i].Dispose();
385 }
386}
387
388
389static int GetNumberLength(int number) {
390 ASSERT(number >= 0);
391 ASSERT(number < 10000);
392 if (number < 10) return 1;
393 if (number < 100) return 2;
394 if (number < 1000) return 3;
395 return 4;
396}
397
398
399int LogRecordCompressor::GetBackwardReferenceSize(int distance, int pos) {
400 // See kLineBackwardReferenceFormat and kBackwardReferenceFormat.
401 return pos == 0 ? GetNumberLength(distance) + 1
402 : GetNumberLength(distance) + GetNumberLength(pos) + 2;
403}
404
405
406void LogRecordCompressor::PrintBackwardReference(Vector<char> dest,
407 int distance,
408 int pos) {
409 if (pos == 0) {
410 OS::SNPrintF(dest, kLineBackwardReferenceFormat, distance);
411 } else {
412 OS::SNPrintF(dest, kBackwardReferenceFormat, distance, pos);
413 }
414}
415
416
417bool LogRecordCompressor::Store(const Vector<const char>& record) {
418 // Check if the record is the same as the last stored one.
419 if (curr_ != -1) {
420 Vector<const char>& curr = buffer_[curr_];
421 if (record.length() == curr.length()
422 && strncmp(record.start(), curr.start(), record.length()) == 0) {
423 return false;
424 }
425 }
426 // buffer_ is circular.
427 prev_ = curr_++;
428 curr_ %= buffer_.length();
429 Vector<char> record_copy = Vector<char>::New(record.length());
430 memcpy(record_copy.start(), record.start(), record.length());
431 buffer_[curr_].Dispose();
432 buffer_[curr_] =
433 Vector<const char>(record_copy.start(), record_copy.length());
434 return true;
435}
436
437
438bool LogRecordCompressor::RetrievePreviousCompressed(
439 Vector<char>* prev_record) {
440 if (prev_ == -1) return false;
441
442 int index = prev_;
443 // Distance from prev_.
444 int distance = 0;
445 // Best compression result among records in the buffer.
446 struct {
447 intptr_t truncated_len;
448 int distance;
449 int copy_from_pos;
450 int backref_size;
451 } best = {-1, 0, 0, 0};
452 Vector<const char>& prev = buffer_[prev_];
453 const char* const prev_start = prev.start();
454 const char* const prev_end = prev.start() + prev.length();
455 do {
456 // We're moving backwards until we reach the current record.
457 // Remember that buffer_ is circular.
458 if (--index == -1) index = buffer_.length() - 1;
459 ++distance;
460 if (index == curr_) break;
461
462 Vector<const char>& data = buffer_[index];
463 if (data.start() == NULL) break;
464 const char* const data_end = data.start() + data.length();
465 const char* prev_ptr = prev_end;
466 const char* data_ptr = data_end;
467 // Compare strings backwards, stop on the last matching character.
468 while (prev_ptr != prev_start && data_ptr != data.start()
469 && *(prev_ptr - 1) == *(data_ptr - 1)) {
470 --prev_ptr;
471 --data_ptr;
472 }
473 const intptr_t truncated_len = prev_end - prev_ptr;
Steve Blockd0582a62009-12-15 09:54:21 +0000474 const int copy_from_pos = static_cast<int>(data_ptr - data.start());
Steve Blocka7e24c12009-10-30 11:49:00 +0000475 // Check if the length of compressed tail is enough.
476 if (truncated_len <= kMaxBackwardReferenceSize
477 && truncated_len <= GetBackwardReferenceSize(distance, copy_from_pos)) {
478 continue;
479 }
480
481 // Record compression results.
482 if (truncated_len > best.truncated_len) {
483 best.truncated_len = truncated_len;
484 best.distance = distance;
485 best.copy_from_pos = copy_from_pos;
486 best.backref_size = GetBackwardReferenceSize(distance, copy_from_pos);
487 }
488 } while (true);
489
490 if (best.distance == 0) {
491 // Can't compress the previous record. Return as is.
492 ASSERT(prev_record->length() >= prev.length());
493 memcpy(prev_record->start(), prev.start(), prev.length());
494 prev_record->Truncate(prev.length());
495 } else {
496 // Copy the uncompressible part unchanged.
497 const intptr_t unchanged_len = prev.length() - best.truncated_len;
498 // + 1 for '\0'.
499 ASSERT(prev_record->length() >= unchanged_len + best.backref_size + 1);
500 memcpy(prev_record->start(), prev.start(), unchanged_len);
501 // Append the backward reference.
502 Vector<char> backref(
503 prev_record->start() + unchanged_len, best.backref_size + 1);
504 PrintBackwardReference(backref, best.distance, best.copy_from_pos);
505 ASSERT(strlen(backref.start()) - best.backref_size == 0);
Steve Blockd0582a62009-12-15 09:54:21 +0000506 prev_record->Truncate(static_cast<int>(unchanged_len + best.backref_size));
Steve Blocka7e24c12009-10-30 11:49:00 +0000507 }
508 return true;
509}
510
511#endif // ENABLE_LOGGING_AND_PROFILING
512
513} } // namespace v8::internal