1 /* 2 * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. 8 * 9 * This code is distributed in the hope that it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 12 * version 2 for more details (a copy is included in the LICENSE file that 13 * accompanied this code). 14 * 15 * You should have received a copy of the GNU General Public License version 16 * 2 along with this work; if not, write to the Free Software Foundation, 17 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 18 * 19 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 20 * or visit www.oracle.com if you need additional information or have any 21 * questions. 22 * 23 */ 24 25 #include "precompiled.hpp" 26 #include "logging/log.hpp" 27 #include "logging/logStream.hpp" 28 29 LogStream::LineBuffer::LineBuffer() 30 : _buf(_smallbuf), _cap(sizeof(_smallbuf)), _pos(0) 31 { 32 _buf[0] = '\0'; 33 } 34 35 LogStream::LineBuffer::~LineBuffer() { 36 assert(_pos == 0, "still outstanding bytes in the line buffer"); 37 if (_buf != _smallbuf) { 38 os::free(_buf); 39 } 40 } 41 42 void LogStream::LineBuffer::ensure_cap(size_t atleast) { 43 assert(_cap >= sizeof(_smallbuf), "sanity"); 44 if (_cap < atleast) { 45 const size_t newcap = MAX2(_cap * 2, atleast * 2); 46 char* const newbuf = (char*) os::malloc(newcap, mtLogging); 47 if (_pos > 0) { // preserve old content 48 memcpy(newbuf, _buf, _pos + 1); // ..including trailing zero 49 } 50 if (_buf != _smallbuf) { 51 os::free(_buf); 52 } 53 _buf = newbuf; 54 _cap = newcap; 55 } 56 assert(_cap >= atleast, "sanity"); 57 } 58 59 void LogStream::LineBuffer::append(const char* s, size_t len) { 60 assert(_buf[_pos] == '\0', "sanity"); 61 ensure_cap(_pos + len + 1); 62 assert(_cap >= _pos + len + 1, "sanity"); 63 memcpy(_buf + _pos, s, len); 64 _pos += len; 65 _buf[_pos] = '\0'; 66 } 67 68 void LogStream::LineBuffer::reset() { 69 _pos = 0; 70 _buf[_pos] = '\0'; 71 } 72 73 void LogStream::write(const char* s, size_t len) { 74 75 if (len > 0 && s[len - 1] == '\n') { 76 _current_line.append(s, len - 1); // omit the newline. 77 _log_handle.print("%s", _current_line.ptr()); 78 _current_line.reset(); 79 } else { 80 _current_line.append(s, len); 81 } 82 update_position(s, len); 83 } 84