blob: 028eb3a015b1ce782304442df652839156e68ee5 [file] [log] [blame]
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +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;
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000126// Must be the same message as in Logger::PauseProfiler.
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000127const 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,
158 kDynamicBufferSeal, strlen(kDynamicBufferSeal));
159 Write = WriteToMemory;
160 Init();
161}
162
163
164void Log::Close() {
165 if (Write == WriteToFile) {
166 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
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000176 DeleteArray(message_buffer_);
177 message_buffer_ = NULL;
178
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000179 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;
198 actual_size = end_pos - dest_buf + 1;
199 ASSERT(actual_size <= max_size);
200 return actual_size;
201}
202
203
204LogMessageBuilder::WriteFailureHandler
205 LogMessageBuilder::write_failure_handler = NULL;
206
207
208LogMessageBuilder::LogMessageBuilder(): sl(Log::mutex_), pos_(0) {
209 ASSERT(Log::message_buffer_ != NULL);
210}
211
212
213void LogMessageBuilder::Append(const char* format, ...) {
214 Vector<char> buf(Log::message_buffer_ + pos_,
215 Log::kMessageBufferSize - pos_);
216 va_list args;
217 va_start(args, format);
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000218 AppendVA(format, args);
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000219 va_end(args);
220 ASSERT(pos_ <= Log::kMessageBufferSize);
221}
222
223
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000224void LogMessageBuilder::AppendVA(const char* format, va_list args) {
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000225 Vector<char> buf(Log::message_buffer_ + pos_,
226 Log::kMessageBufferSize - pos_);
227 int result = v8::internal::OS::VSNPrintF(buf, format, args);
228
229 // Result is -1 if output was truncated.
230 if (result >= 0) {
231 pos_ += result;
232 } else {
233 pos_ = Log::kMessageBufferSize;
234 }
235 ASSERT(pos_ <= Log::kMessageBufferSize);
236}
237
238
239void LogMessageBuilder::Append(const char c) {
240 if (pos_ < Log::kMessageBufferSize) {
241 Log::message_buffer_[pos_++] = c;
242 }
243 ASSERT(pos_ <= Log::kMessageBufferSize);
244}
245
246
247void LogMessageBuilder::Append(String* str) {
248 AssertNoAllocation no_heap_allocation; // Ensure string stay valid.
249 int length = str->length();
250 for (int i = 0; i < length; i++) {
251 Append(static_cast<char>(str->Get(i)));
252 }
253}
254
255
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000256void LogMessageBuilder::AppendAddress(Address addr) {
257 static Address last_address_ = NULL;
258 AppendAddress(addr, last_address_);
259 last_address_ = addr;
260}
261
262
263void LogMessageBuilder::AppendAddress(Address addr, Address bias) {
264 if (!FLAG_compress_log || bias == NULL) {
265 Append("0x%" V8PRIxPTR, addr);
266 } else {
267 intptr_t delta = addr - bias;
268 // To avoid printing negative offsets in an unsigned form,
269 // we are printing an absolute value with a sign.
270 const char sign = delta >= 0 ? '+' : '-';
271 if (sign == '-') { delta = -delta; }
272 Append("%c%" V8PRIxPTR, sign, delta);
273 }
274}
275
276
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000277void LogMessageBuilder::AppendDetailed(String* str, bool show_impl_info) {
278 AssertNoAllocation no_heap_allocation; // Ensure string stay valid.
279 int len = str->length();
280 if (len > 0x1000)
281 len = 0x1000;
282 if (show_impl_info) {
283 Append(str->IsAsciiRepresentation() ? 'a' : '2');
284 if (StringShape(str).IsExternal())
285 Append('e');
286 if (StringShape(str).IsSymbol())
287 Append('#');
288 Append(":%i:", str->length());
289 }
290 for (int i = 0; i < len; i++) {
291 uc32 c = str->Get(i);
292 if (c > 0xff) {
293 Append("\\u%04x", c);
294 } else if (c < 32 || c > 126) {
295 Append("\\x%02x", c);
296 } else if (c == ',') {
297 Append("\\,");
298 } else if (c == '\\') {
299 Append("\\\\");
300 } else {
301 Append("%lc", c);
302 }
303 }
304}
305
306
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000307bool LogMessageBuilder::StoreInCompressor(LogRecordCompressor* compressor) {
308 return compressor->Store(Vector<const char>(Log::message_buffer_, pos_));
309}
310
311
312bool LogMessageBuilder::RetrieveCompressedPrevious(
313 LogRecordCompressor* compressor, const char* prefix) {
314 pos_ = 0;
315 if (prefix[0] != '\0') Append(prefix);
316 Vector<char> prev_record(Log::message_buffer_ + pos_,
317 Log::kMessageBufferSize - pos_);
318 const bool has_prev = compressor->RetrievePreviousCompressed(&prev_record);
319 if (!has_prev) return false;
320 pos_ += prev_record.length();
321 return true;
322}
323
324
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000325void LogMessageBuilder::WriteToLogFile() {
326 ASSERT(pos_ <= Log::kMessageBufferSize);
327 const int written = Log::Write(Log::message_buffer_, pos_);
328 if (written != pos_ && write_failure_handler != NULL) {
329 write_failure_handler();
330 }
331}
332
333
334void LogMessageBuilder::WriteCStringToLogFile(const char* str) {
335 const int len = strlen(str);
336 const int written = Log::Write(str, len);
337 if (written != len && write_failure_handler != NULL) {
338 write_failure_handler();
339 }
340}
341
ager@chromium.orgeadaf222009-06-16 09:43:10 +0000342
343// Formatting string for back references to the whole line. E.g. "#2" means
344// "the second line above".
345const char* LogRecordCompressor::kLineBackwardReferenceFormat = "#%d";
346
347// Formatting string for back references. E.g. "#2:10" means
348// "the second line above, start from char 10 (0-based)".
349const char* LogRecordCompressor::kBackwardReferenceFormat = "#%d:%d";
350
351
352LogRecordCompressor::~LogRecordCompressor() {
353 for (int i = 0; i < buffer_.length(); ++i) {
354 buffer_[i].Dispose();
355 }
356}
357
358
359static int GetNumberLength(int number) {
360 ASSERT(number >= 0);
361 ASSERT(number < 10000);
362 if (number < 10) return 1;
363 if (number < 100) return 2;
364 if (number < 1000) return 3;
365 return 4;
366}
367
368
369int LogRecordCompressor::GetBackwardReferenceSize(int distance, int pos) {
370 // See kLineBackwardReferenceFormat and kBackwardReferenceFormat.
371 return pos == 0 ? GetNumberLength(distance) + 1
372 : GetNumberLength(distance) + GetNumberLength(pos) + 2;
373}
374
375
376void LogRecordCompressor::PrintBackwardReference(Vector<char> dest,
377 int distance,
378 int pos) {
379 if (pos == 0) {
380 OS::SNPrintF(dest, kLineBackwardReferenceFormat, distance);
381 } else {
382 OS::SNPrintF(dest, kBackwardReferenceFormat, distance, pos);
383 }
384}
385
386
387bool LogRecordCompressor::Store(const Vector<const char>& record) {
388 // Check if the record is the same as the last stored one.
389 if (curr_ != -1) {
390 Vector<const char>& curr = buffer_[curr_];
391 if (record.length() == curr.length()
392 && strncmp(record.start(), curr.start(), record.length()) == 0) {
393 return false;
394 }
395 }
396 // buffer_ is circular.
397 prev_ = curr_++;
398 curr_ %= buffer_.length();
399 Vector<char> record_copy = Vector<char>::New(record.length());
400 memcpy(record_copy.start(), record.start(), record.length());
401 buffer_[curr_].Dispose();
402 buffer_[curr_] =
403 Vector<const char>(record_copy.start(), record_copy.length());
404 return true;
405}
406
407
408bool LogRecordCompressor::RetrievePreviousCompressed(
409 Vector<char>* prev_record) {
410 if (prev_ == -1) return false;
411
412 int index = prev_;
413 // Distance from prev_.
414 int distance = 0;
415 // Best compression result among records in the buffer.
416 struct {
417 intptr_t truncated_len;
418 int distance;
419 int copy_from_pos;
420 int backref_size;
421 } best = {-1, 0, 0, 0};
422 Vector<const char>& prev = buffer_[prev_];
423 const char* const prev_start = prev.start();
424 const char* const prev_end = prev.start() + prev.length();
425 do {
426 // We're moving backwards until we reach the current record.
427 // Remember that buffer_ is circular.
428 if (--index == -1) index = buffer_.length() - 1;
429 ++distance;
430 if (index == curr_) break;
431
432 Vector<const char>& data = buffer_[index];
433 if (data.start() == NULL) break;
434 const char* const data_end = data.start() + data.length();
435 const char* prev_ptr = prev_end;
436 const char* data_ptr = data_end;
437 // Compare strings backwards, stop on the last matching character.
438 while (prev_ptr != prev_start && data_ptr != data.start()
439 && *(prev_ptr - 1) == *(data_ptr - 1)) {
440 --prev_ptr;
441 --data_ptr;
442 }
443 const intptr_t truncated_len = prev_end - prev_ptr;
444 const int copy_from_pos = data_ptr - data.start();
445 // Check if the length of compressed tail is enough.
446 if (truncated_len <= kMaxBackwardReferenceSize
447 && truncated_len <= GetBackwardReferenceSize(distance, copy_from_pos)) {
448 continue;
449 }
450
451 // Record compression results.
452 if (truncated_len > best.truncated_len) {
453 best.truncated_len = truncated_len;
454 best.distance = distance;
455 best.copy_from_pos = copy_from_pos;
456 best.backref_size = GetBackwardReferenceSize(distance, copy_from_pos);
457 }
458 } while (true);
459
460 if (best.distance == 0) {
461 // Can't compress the previous record. Return as is.
462 ASSERT(prev_record->length() >= prev.length());
463 memcpy(prev_record->start(), prev.start(), prev.length());
464 prev_record->Truncate(prev.length());
465 } else {
466 // Copy the uncompressible part unchanged.
467 const intptr_t unchanged_len = prev.length() - best.truncated_len;
468 // + 1 for '\0'.
469 ASSERT(prev_record->length() >= unchanged_len + best.backref_size + 1);
470 memcpy(prev_record->start(), prev.start(), unchanged_len);
471 // Append the backward reference.
472 Vector<char> backref(
473 prev_record->start() + unchanged_len, best.backref_size + 1);
474 PrintBackwardReference(backref, best.distance, best.copy_from_pos);
475 ASSERT(strlen(backref.start()) - best.backref_size == 0);
476 prev_record->Truncate(unchanged_len + best.backref_size);
477 }
478 return true;
479}
480
sgjesse@chromium.org755c5b12009-05-29 11:04:38 +0000481#endif // ENABLE_LOGGING_AND_PROFILING
482
483} } // namespace v8::internal