blob: 62f0ca62f41300ac71073034a2291f71738e87ed [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;
125LogDynamicBuffer* Log::output_buffer_ = NULL;
126// Must be the same message as in Logger::PauseProfiler.
127const char* Log::kDynamicBufferSeal = "profiler,\"pause\"\n";
128Mutex* Log::mutex_ = NULL;
129char* Log::message_buffer_ = NULL;
130
131
132void Log::Init() {
133 mutex_ = OS::CreateMutex();
134 message_buffer_ = NewArray<char>(kMessageBufferSize);
135}
136
137
138void Log::OpenStdout() {
139 ASSERT(!IsEnabled());
140 output_handle_ = stdout;
141 Write = WriteToFile;
142 Init();
143}
144
145
146void Log::OpenFile(const char* name) {
147 ASSERT(!IsEnabled());
148 output_handle_ = OS::FOpen(name, OS::LogFileOpenMode);
149 Write = WriteToFile;
150 Init();
151}
152
153
154void Log::OpenMemoryBuffer() {
155 ASSERT(!IsEnabled());
156 output_buffer_ = new LogDynamicBuffer(
157 kDynamicBufferBlockSize, kMaxDynamicBufferSize,
Steve Blockd0582a62009-12-15 09:54:21 +0000158 kDynamicBufferSeal, StrLength(kDynamicBufferSeal));
Steve Blocka7e24c12009-10-30 11:49:00 +0000159 Write = WriteToMemory;
160 Init();
161}
162
163
164void Log::Close() {
165 if (Write == WriteToFile) {
166 if (output_handle_ != NULL) fclose(output_handle_);
167 output_handle_ = NULL;
168 } else if (Write == WriteToMemory) {
169 delete output_buffer_;
170 output_buffer_ = NULL;
171 } else {
172 ASSERT(Write == NULL);
173 }
174 Write = NULL;
175
176 DeleteArray(message_buffer_);
177 message_buffer_ = NULL;
178
179 delete mutex_;
180 mutex_ = NULL;
181
182 is_stopped_ = false;
183}
184
185
186int Log::GetLogLines(int from_pos, char* dest_buf, int max_size) {
187 if (Write != WriteToMemory) return 0;
188 ASSERT(output_buffer_ != NULL);
189 ASSERT(from_pos >= 0);
190 ASSERT(max_size >= 0);
191 int actual_size = output_buffer_->Read(from_pos, dest_buf, max_size);
192 ASSERT(actual_size <= max_size);
193 if (actual_size == 0) return 0;
194
195 // Find previous log line boundary.
196 char* end_pos = dest_buf + actual_size - 1;
197 while (end_pos >= dest_buf && *end_pos != '\n') --end_pos;
Steve Blockd0582a62009-12-15 09:54:21 +0000198 actual_size = static_cast<int>(end_pos - dest_buf + 1);
Steve Block6ded16b2010-05-10 14:33:55 +0100199 // If the assertion below is hit, it means that there was no line end
200 // found --- something wrong has happened.
201 ASSERT(actual_size > 0);
Steve Blocka7e24c12009-10-30 11:49:00 +0000202 ASSERT(actual_size <= max_size);
203 return actual_size;
204}
205
206
207LogMessageBuilder::WriteFailureHandler
208 LogMessageBuilder::write_failure_handler = NULL;
209
210
211LogMessageBuilder::LogMessageBuilder(): sl(Log::mutex_), pos_(0) {
212 ASSERT(Log::message_buffer_ != NULL);
213}
214
215
216void LogMessageBuilder::Append(const char* format, ...) {
217 Vector<char> buf(Log::message_buffer_ + pos_,
218 Log::kMessageBufferSize - pos_);
219 va_list args;
220 va_start(args, format);
221 AppendVA(format, args);
222 va_end(args);
223 ASSERT(pos_ <= Log::kMessageBufferSize);
224}
225
226
227void LogMessageBuilder::AppendVA(const char* format, va_list args) {
228 Vector<char> buf(Log::message_buffer_ + pos_,
229 Log::kMessageBufferSize - pos_);
230 int result = v8::internal::OS::VSNPrintF(buf, format, args);
231
232 // Result is -1 if output was truncated.
233 if (result >= 0) {
234 pos_ += result;
235 } else {
236 pos_ = Log::kMessageBufferSize;
237 }
238 ASSERT(pos_ <= Log::kMessageBufferSize);
239}
240
241
242void LogMessageBuilder::Append(const char c) {
243 if (pos_ < Log::kMessageBufferSize) {
244 Log::message_buffer_[pos_++] = c;
245 }
246 ASSERT(pos_ <= Log::kMessageBufferSize);
247}
248
249
250void LogMessageBuilder::Append(String* str) {
251 AssertNoAllocation no_heap_allocation; // Ensure string stay valid.
252 int length = str->length();
253 for (int i = 0; i < length; i++) {
254 Append(static_cast<char>(str->Get(i)));
255 }
256}
257
258
259void LogMessageBuilder::AppendAddress(Address addr) {
260 static Address last_address_ = NULL;
261 AppendAddress(addr, last_address_);
262 last_address_ = addr;
263}
264
265
266void LogMessageBuilder::AppendAddress(Address addr, Address bias) {
267 if (!FLAG_compress_log) {
268 Append("0x%" V8PRIxPTR, addr);
269 } else if (bias == NULL) {
270 Append("%" V8PRIxPTR, addr);
271 } else {
272 uintptr_t delta;
273 char sign;
274 if (addr >= bias) {
275 delta = addr - bias;
276 sign = '+';
277 } else {
278 delta = bias - addr;
279 sign = '-';
280 }
281 Append("%c%" V8PRIxPTR, sign, delta);
282 }
283}
284
285
286void LogMessageBuilder::AppendDetailed(String* str, bool show_impl_info) {
287 AssertNoAllocation no_heap_allocation; // Ensure string stay valid.
288 int len = str->length();
289 if (len > 0x1000)
290 len = 0x1000;
291 if (show_impl_info) {
292 Append(str->IsAsciiRepresentation() ? 'a' : '2');
293 if (StringShape(str).IsExternal())
294 Append('e');
295 if (StringShape(str).IsSymbol())
296 Append('#');
297 Append(":%i:", str->length());
298 }
299 for (int i = 0; i < len; i++) {
300 uc32 c = str->Get(i);
301 if (c > 0xff) {
302 Append("\\u%04x", c);
303 } else if (c < 32 || c > 126) {
304 Append("\\x%02x", c);
305 } else if (c == ',') {
306 Append("\\,");
307 } else if (c == '\\') {
308 Append("\\\\");
309 } else {
310 Append("%lc", c);
311 }
312 }
313}
314
315
316void LogMessageBuilder::AppendStringPart(const char* str, int len) {
317 if (pos_ + len > Log::kMessageBufferSize) {
318 len = Log::kMessageBufferSize - pos_;
319 ASSERT(len >= 0);
320 if (len == 0) return;
321 }
322 Vector<char> buf(Log::message_buffer_ + pos_,
323 Log::kMessageBufferSize - pos_);
324 OS::StrNCpy(buf, str, len);
325 pos_ += len;
326 ASSERT(pos_ <= Log::kMessageBufferSize);
327}
328
329
330bool LogMessageBuilder::StoreInCompressor(LogRecordCompressor* compressor) {
331 return compressor->Store(Vector<const char>(Log::message_buffer_, pos_));
332}
333
334
335bool LogMessageBuilder::RetrieveCompressedPrevious(
336 LogRecordCompressor* compressor, const char* prefix) {
337 pos_ = 0;
338 if (prefix[0] != '\0') Append(prefix);
339 Vector<char> prev_record(Log::message_buffer_ + pos_,
340 Log::kMessageBufferSize - pos_);
341 const bool has_prev = compressor->RetrievePreviousCompressed(&prev_record);
342 if (!has_prev) return false;
343 pos_ += prev_record.length();
344 return true;
345}
346
347
348void LogMessageBuilder::WriteToLogFile() {
349 ASSERT(pos_ <= Log::kMessageBufferSize);
350 const int written = Log::Write(Log::message_buffer_, pos_);
351 if (written != pos_ && write_failure_handler != NULL) {
352 write_failure_handler();
353 }
354}
355
356
Steve Blocka7e24c12009-10-30 11:49:00 +0000357// Formatting string for back references to the whole line. E.g. "#2" means
358// "the second line above".
359const char* LogRecordCompressor::kLineBackwardReferenceFormat = "#%d";
360
361// Formatting string for back references. E.g. "#2:10" means
362// "the second line above, start from char 10 (0-based)".
363const char* LogRecordCompressor::kBackwardReferenceFormat = "#%d:%d";
364
365
366LogRecordCompressor::~LogRecordCompressor() {
367 for (int i = 0; i < buffer_.length(); ++i) {
368 buffer_[i].Dispose();
369 }
370}
371
372
373static int GetNumberLength(int number) {
374 ASSERT(number >= 0);
375 ASSERT(number < 10000);
376 if (number < 10) return 1;
377 if (number < 100) return 2;
378 if (number < 1000) return 3;
379 return 4;
380}
381
382
383int LogRecordCompressor::GetBackwardReferenceSize(int distance, int pos) {
384 // See kLineBackwardReferenceFormat and kBackwardReferenceFormat.
385 return pos == 0 ? GetNumberLength(distance) + 1
386 : GetNumberLength(distance) + GetNumberLength(pos) + 2;
387}
388
389
390void LogRecordCompressor::PrintBackwardReference(Vector<char> dest,
391 int distance,
392 int pos) {
393 if (pos == 0) {
394 OS::SNPrintF(dest, kLineBackwardReferenceFormat, distance);
395 } else {
396 OS::SNPrintF(dest, kBackwardReferenceFormat, distance, pos);
397 }
398}
399
400
401bool LogRecordCompressor::Store(const Vector<const char>& record) {
402 // Check if the record is the same as the last stored one.
403 if (curr_ != -1) {
404 Vector<const char>& curr = buffer_[curr_];
405 if (record.length() == curr.length()
406 && strncmp(record.start(), curr.start(), record.length()) == 0) {
407 return false;
408 }
409 }
410 // buffer_ is circular.
411 prev_ = curr_++;
412 curr_ %= buffer_.length();
413 Vector<char> record_copy = Vector<char>::New(record.length());
414 memcpy(record_copy.start(), record.start(), record.length());
415 buffer_[curr_].Dispose();
416 buffer_[curr_] =
417 Vector<const char>(record_copy.start(), record_copy.length());
418 return true;
419}
420
421
422bool LogRecordCompressor::RetrievePreviousCompressed(
423 Vector<char>* prev_record) {
424 if (prev_ == -1) return false;
425
426 int index = prev_;
427 // Distance from prev_.
428 int distance = 0;
429 // Best compression result among records in the buffer.
430 struct {
431 intptr_t truncated_len;
432 int distance;
433 int copy_from_pos;
434 int backref_size;
435 } best = {-1, 0, 0, 0};
436 Vector<const char>& prev = buffer_[prev_];
437 const char* const prev_start = prev.start();
438 const char* const prev_end = prev.start() + prev.length();
439 do {
440 // We're moving backwards until we reach the current record.
441 // Remember that buffer_ is circular.
442 if (--index == -1) index = buffer_.length() - 1;
443 ++distance;
444 if (index == curr_) break;
445
446 Vector<const char>& data = buffer_[index];
447 if (data.start() == NULL) break;
448 const char* const data_end = data.start() + data.length();
449 const char* prev_ptr = prev_end;
450 const char* data_ptr = data_end;
451 // Compare strings backwards, stop on the last matching character.
452 while (prev_ptr != prev_start && data_ptr != data.start()
453 && *(prev_ptr - 1) == *(data_ptr - 1)) {
454 --prev_ptr;
455 --data_ptr;
456 }
457 const intptr_t truncated_len = prev_end - prev_ptr;
Steve Blockd0582a62009-12-15 09:54:21 +0000458 const int copy_from_pos = static_cast<int>(data_ptr - data.start());
Steve Blocka7e24c12009-10-30 11:49:00 +0000459 // Check if the length of compressed tail is enough.
460 if (truncated_len <= kMaxBackwardReferenceSize
461 && truncated_len <= GetBackwardReferenceSize(distance, copy_from_pos)) {
462 continue;
463 }
464
465 // Record compression results.
466 if (truncated_len > best.truncated_len) {
467 best.truncated_len = truncated_len;
468 best.distance = distance;
469 best.copy_from_pos = copy_from_pos;
470 best.backref_size = GetBackwardReferenceSize(distance, copy_from_pos);
471 }
472 } while (true);
473
474 if (best.distance == 0) {
475 // Can't compress the previous record. Return as is.
476 ASSERT(prev_record->length() >= prev.length());
477 memcpy(prev_record->start(), prev.start(), prev.length());
478 prev_record->Truncate(prev.length());
479 } else {
480 // Copy the uncompressible part unchanged.
481 const intptr_t unchanged_len = prev.length() - best.truncated_len;
482 // + 1 for '\0'.
483 ASSERT(prev_record->length() >= unchanged_len + best.backref_size + 1);
484 memcpy(prev_record->start(), prev.start(), unchanged_len);
485 // Append the backward reference.
486 Vector<char> backref(
487 prev_record->start() + unchanged_len, best.backref_size + 1);
488 PrintBackwardReference(backref, best.distance, best.copy_from_pos);
489 ASSERT(strlen(backref.start()) - best.backref_size == 0);
Steve Blockd0582a62009-12-15 09:54:21 +0000490 prev_record->Truncate(static_cast<int>(unchanged_len + best.backref_size));
Steve Blocka7e24c12009-10-30 11:49:00 +0000491 }
492 return true;
493}
494
495#endif // ENABLE_LOGGING_AND_PROFILING
496
497} } // namespace v8::internal