Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
PojavLauncherTeam
GitHub Repository: PojavLauncherTeam/mobile
Path: blob/master/src/hotspot/share/logging/logFileOutput.cpp
40930 views
1
/*
2
* Copyright (c) 2015, 2021, 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
#include "precompiled.hpp"
25
#include "jvm.h"
26
#include "logging/log.hpp"
27
#include "logging/logAsyncWriter.hpp"
28
#include "logging/logConfiguration.hpp"
29
#include "logging/logFileOutput.hpp"
30
#include "memory/allocation.inline.hpp"
31
#include "runtime/arguments.hpp"
32
#include "runtime/os.hpp"
33
#include "utilities/globalDefinitions.hpp"
34
#include "utilities/defaultStream.hpp"
35
36
const char* const LogFileOutput::Prefix = "file=";
37
const char* const LogFileOutput::FileOpenMode = "a";
38
const char* const LogFileOutput::PidFilenamePlaceholder = "%p";
39
const char* const LogFileOutput::TimestampFilenamePlaceholder = "%t";
40
const char* const LogFileOutput::TimestampFormat = "%Y-%m-%d_%H-%M-%S";
41
const char* const LogFileOutput::FileSizeOptionKey = "filesize";
42
const char* const LogFileOutput::FileCountOptionKey = "filecount";
43
char LogFileOutput::_pid_str[PidBufferSize];
44
char LogFileOutput::_vm_start_time_str[StartTimeBufferSize];
45
46
LogFileOutput::LogFileOutput(const char* name)
47
: LogFileStreamOutput(NULL), _name(os::strdup_check_oom(name, mtLogging)),
48
_file_name(NULL), _archive_name(NULL), _current_file(0),
49
_file_count(DefaultFileCount), _is_default_file_count(true), _archive_name_len(0),
50
_rotate_size(DefaultFileSize), _current_size(0), _rotation_semaphore(1) {
51
assert(strstr(name, Prefix) == name, "invalid output name '%s': missing prefix: %s", name, Prefix);
52
_file_name = make_file_name(name + strlen(Prefix), _pid_str, _vm_start_time_str);
53
}
54
55
const char* LogFileOutput::cur_log_file_name() {
56
if (strlen(_archive_name) == 0) {
57
return _file_name;
58
} else {
59
return _archive_name;
60
}
61
}
62
63
void LogFileOutput::set_file_name_parameters(jlong vm_start_time) {
64
int res = jio_snprintf(_pid_str, sizeof(_pid_str), "%d", os::current_process_id());
65
assert(res > 0, "PID buffer too small");
66
67
struct tm local_time;
68
time_t utc_time = vm_start_time / 1000;
69
os::localtime_pd(&utc_time, &local_time);
70
res = (int)strftime(_vm_start_time_str, sizeof(_vm_start_time_str), TimestampFormat, &local_time);
71
assert(res > 0, "VM start time buffer too small.");
72
}
73
74
LogFileOutput::~LogFileOutput() {
75
if (_stream != NULL) {
76
if (fclose(_stream) != 0) {
77
jio_fprintf(defaultStream::error_stream(), "Could not close log file '%s' (%s).\n",
78
_file_name, os::strerror(errno));
79
}
80
}
81
os::free(_archive_name);
82
os::free(_file_name);
83
os::free(const_cast<char*>(_name));
84
}
85
86
static size_t parse_value(const char* value_str) {
87
char* end;
88
unsigned long long value = strtoull(value_str, &end, 10);
89
if (!isdigit(*value_str) || end != value_str + strlen(value_str) || value >= SIZE_MAX) {
90
return SIZE_MAX;
91
}
92
return value;
93
}
94
95
static bool file_exists(const char* filename) {
96
struct stat dummy_stat;
97
return os::stat(filename, &dummy_stat) == 0;
98
}
99
100
static uint number_of_digits(uint number) {
101
return number < 10 ? 1 : (number < 100 ? 2 : 3);
102
}
103
104
static bool is_regular_file(const char* filename) {
105
struct stat st;
106
int ret = os::stat(filename, &st);
107
if (ret != 0) {
108
return false;
109
}
110
return (st.st_mode & S_IFMT) == S_IFREG;
111
}
112
113
static bool is_fifo_file(const char* filename) {
114
struct stat st;
115
int ret = os::stat(filename, &st);
116
if (ret != 0) {
117
return false;
118
}
119
return S_ISFIFO(st.st_mode);
120
}
121
122
// Try to find the next number that should be used for file rotation.
123
// Return UINT_MAX on error.
124
static uint next_file_number(const char* filename,
125
uint number_of_digits,
126
uint filecount,
127
outputStream* errstream) {
128
bool found = false;
129
uint next_num = 0;
130
131
// len is filename + dot + digits + null char
132
size_t len = strlen(filename) + number_of_digits + 2;
133
char* archive_name = NEW_C_HEAP_ARRAY(char, len, mtLogging);
134
char* oldest_name = NEW_C_HEAP_ARRAY(char, len, mtLogging);
135
136
for (uint i = 0; i < filecount; i++) {
137
int ret = jio_snprintf(archive_name, len, "%s.%0*u",
138
filename, number_of_digits, i);
139
assert(ret > 0 && static_cast<size_t>(ret) == len - 1,
140
"incorrect buffer length calculation");
141
142
if (file_exists(archive_name) && !is_regular_file(archive_name)) {
143
// We've encountered something that's not a regular file among the
144
// possible file rotation targets. Fail immediately to prevent
145
// problems later.
146
errstream->print_cr("Possible rotation target file '%s' already exists "
147
"but is not a regular file.", archive_name);
148
next_num = UINT_MAX;
149
break;
150
}
151
152
// Stop looking if we find an unused file name
153
if (!file_exists(archive_name)) {
154
next_num = i;
155
found = true;
156
break;
157
}
158
159
// Keep track of oldest existing log file
160
if (!found
161
|| os::compare_file_modified_times(oldest_name, archive_name) > 0) {
162
strcpy(oldest_name, archive_name);
163
next_num = i;
164
found = true;
165
}
166
}
167
168
FREE_C_HEAP_ARRAY(char, oldest_name);
169
FREE_C_HEAP_ARRAY(char, archive_name);
170
return next_num;
171
}
172
173
bool LogFileOutput::parse_options(const char* options, outputStream* errstream) {
174
if (options == NULL || strlen(options) == 0) {
175
return true;
176
}
177
bool success = true;
178
char* opts = os::strdup_check_oom(options, mtLogging);
179
180
char* comma_pos;
181
char* pos = opts;
182
do {
183
comma_pos = strchr(pos, ',');
184
if (comma_pos != NULL) {
185
*comma_pos = '\0';
186
}
187
188
char* equals_pos = strchr(pos, '=');
189
if (equals_pos == NULL) {
190
errstream->print_cr("Invalid option '%s' for log file output.", pos);
191
success = false;
192
break;
193
}
194
char* key = pos;
195
char* value_str = equals_pos + 1;
196
*equals_pos = '\0';
197
198
if (strcmp(FileCountOptionKey, key) == 0) {
199
size_t value = parse_value(value_str);
200
if (value > MaxRotationFileCount) {
201
errstream->print_cr("Invalid option: %s must be in range [0, %u]",
202
FileCountOptionKey,
203
MaxRotationFileCount);
204
success = false;
205
break;
206
}
207
_file_count = static_cast<uint>(value);
208
_is_default_file_count = false;
209
} else if (strcmp(FileSizeOptionKey, key) == 0) {
210
julong value;
211
success = Arguments::atojulong(value_str, &value);
212
if (!success || (value > SIZE_MAX)) {
213
errstream->print_cr("Invalid option: %s must be in range [0, "
214
SIZE_FORMAT "]", FileSizeOptionKey, (size_t)SIZE_MAX);
215
success = false;
216
break;
217
}
218
_rotate_size = static_cast<size_t>(value);
219
} else {
220
errstream->print_cr("Invalid option '%s' for log file output.", key);
221
success = false;
222
break;
223
}
224
pos = comma_pos + 1;
225
} while (comma_pos != NULL);
226
227
os::free(opts);
228
return success;
229
}
230
231
bool LogFileOutput::initialize(const char* options, outputStream* errstream) {
232
if (!parse_options(options, errstream)) {
233
return false;
234
}
235
236
bool file_exist = file_exists(_file_name);
237
if (file_exist && _is_default_file_count && is_fifo_file(_file_name)) {
238
_file_count = 0; // Prevent file rotation for fifo's such as named pipes.
239
}
240
241
if (_file_count > 0) {
242
// compute digits with filecount - 1 since numbers will start from 0
243
_file_count_max_digits = number_of_digits(_file_count - 1);
244
_archive_name_len = 2 + strlen(_file_name) + _file_count_max_digits;
245
_archive_name = NEW_C_HEAP_ARRAY(char, _archive_name_len, mtLogging);
246
_archive_name[0] = 0;
247
}
248
249
log_trace(logging)("Initializing logging to file '%s' (filecount: %u"
250
", filesize: " SIZE_FORMAT " KiB).",
251
_file_name, _file_count, _rotate_size / K);
252
253
if (_file_count > 0 && file_exist) {
254
if (!is_regular_file(_file_name)) {
255
errstream->print_cr("Unable to log to file %s with log file rotation: "
256
"%s is not a regular file",
257
_file_name, _file_name);
258
return false;
259
}
260
_current_file = next_file_number(_file_name,
261
_file_count_max_digits,
262
_file_count,
263
errstream);
264
if (_current_file == UINT_MAX) {
265
return false;
266
}
267
log_trace(logging)("Existing log file found, saving it as '%s.%0*u'",
268
_file_name, _file_count_max_digits, _current_file);
269
archive();
270
increment_file_count();
271
}
272
273
_stream = os::fopen(_file_name, FileOpenMode);
274
if (_stream == NULL) {
275
errstream->print_cr("Error opening log file '%s': %s",
276
_file_name, os::strerror(errno));
277
return false;
278
}
279
280
if (_file_count == 0 && is_regular_file(_file_name)) {
281
log_trace(logging)("Truncating log file");
282
os::ftruncate(os::get_fileno(_stream), 0);
283
}
284
285
return true;
286
}
287
288
int LogFileOutput::write_blocking(const LogDecorations& decorations, const char* msg) {
289
_rotation_semaphore.wait();
290
int written = LogFileStreamOutput::write(decorations, msg);
291
if (written > 0) {
292
_current_size += written;
293
294
if (should_rotate()) {
295
rotate();
296
}
297
}
298
_rotation_semaphore.signal();
299
300
return written;
301
}
302
303
int LogFileOutput::write(const LogDecorations& decorations, const char* msg) {
304
if (_stream == NULL) {
305
// An error has occurred with this output, avoid writing to it.
306
return 0;
307
}
308
309
AsyncLogWriter* aio_writer = AsyncLogWriter::instance();
310
if (aio_writer != nullptr) {
311
aio_writer->enqueue(*this, decorations, msg);
312
return 0;
313
}
314
315
return write_blocking(decorations, msg);
316
}
317
318
int LogFileOutput::write(LogMessageBuffer::Iterator msg_iterator) {
319
if (_stream == NULL) {
320
// An error has occurred with this output, avoid writing to it.
321
return 0;
322
}
323
324
AsyncLogWriter* aio_writer = AsyncLogWriter::instance();
325
if (aio_writer != nullptr) {
326
aio_writer->enqueue(*this, msg_iterator);
327
return 0;
328
}
329
330
_rotation_semaphore.wait();
331
int written = LogFileStreamOutput::write(msg_iterator);
332
if (written > 0) {
333
_current_size += written;
334
335
if (should_rotate()) {
336
rotate();
337
}
338
}
339
_rotation_semaphore.signal();
340
341
return written;
342
}
343
344
void LogFileOutput::archive() {
345
assert(_archive_name != NULL && _archive_name_len > 0, "Rotation must be configured before using this function.");
346
int ret = jio_snprintf(_archive_name, _archive_name_len, "%s.%0*u",
347
_file_name, _file_count_max_digits, _current_file);
348
assert(ret >= 0, "Buffer should always be large enough");
349
350
// Attempt to remove possibly existing archived log file before we rename.
351
// Don't care if it fails, we really only care about the rename that follows.
352
remove(_archive_name);
353
354
// Rename the file from ex hotspot.log to hotspot.log.2
355
if (rename(_file_name, _archive_name) == -1) {
356
jio_fprintf(defaultStream::error_stream(), "Could not rename log file '%s' to '%s' (%s).\n",
357
_file_name, _archive_name, os::strerror(errno));
358
}
359
}
360
361
void LogFileOutput::force_rotate() {
362
if (_file_count == 0) {
363
// Rotation not possible
364
return;
365
}
366
_rotation_semaphore.wait();
367
rotate();
368
_rotation_semaphore.signal();
369
}
370
371
void LogFileOutput::rotate() {
372
373
if (fclose(_stream)) {
374
jio_fprintf(defaultStream::error_stream(), "Error closing file '%s' during log rotation (%s).\n",
375
_file_name, os::strerror(errno));
376
}
377
378
// Archive the current log file
379
archive();
380
381
// Open the active log file using the same stream as before
382
_stream = os::fopen(_file_name, FileOpenMode);
383
if (_stream == NULL) {
384
jio_fprintf(defaultStream::error_stream(), "Could not reopen file '%s' during log rotation (%s).\n",
385
_file_name, os::strerror(errno));
386
return;
387
}
388
389
// Reset accumulated size, increase current file counter, and check for file count wrap-around.
390
_current_size = 0;
391
increment_file_count();
392
}
393
394
char* LogFileOutput::make_file_name(const char* file_name,
395
const char* pid_string,
396
const char* timestamp_string) {
397
char* result = NULL;
398
399
// Lets start finding out if we have any %d and/or %t in the name.
400
// We will only replace the first occurrence of any placeholder
401
const char* pid = strstr(file_name, PidFilenamePlaceholder);
402
const char* timestamp = strstr(file_name, TimestampFilenamePlaceholder);
403
404
if (pid == NULL && timestamp == NULL) {
405
// We found no place-holders, return the simple filename
406
return os::strdup_check_oom(file_name, mtLogging);
407
}
408
409
// At least one of the place-holders were found in the file_name
410
const char* first = "";
411
size_t first_pos = SIZE_MAX;
412
size_t first_replace_len = 0;
413
414
const char* second = "";
415
size_t second_pos = SIZE_MAX;
416
size_t second_replace_len = 0;
417
418
// If we found a %p, then setup our variables accordingly
419
if (pid != NULL) {
420
if (timestamp == NULL || pid < timestamp) {
421
first = pid_string;
422
first_pos = pid - file_name;
423
first_replace_len = strlen(PidFilenamePlaceholder);
424
} else {
425
second = pid_string;
426
second_pos = pid - file_name;
427
second_replace_len = strlen(PidFilenamePlaceholder);
428
}
429
}
430
431
if (timestamp != NULL) {
432
if (pid == NULL || timestamp < pid) {
433
first = timestamp_string;
434
first_pos = timestamp - file_name;
435
first_replace_len = strlen(TimestampFilenamePlaceholder);
436
} else {
437
second = timestamp_string;
438
second_pos = timestamp - file_name;
439
second_replace_len = strlen(TimestampFilenamePlaceholder);
440
}
441
}
442
443
size_t first_len = strlen(first);
444
size_t second_len = strlen(second);
445
446
// Allocate the new buffer, size it to hold all we want to put in there +1.
447
size_t result_len = strlen(file_name) + first_len - first_replace_len + second_len - second_replace_len;
448
result = NEW_C_HEAP_ARRAY(char, result_len + 1, mtLogging);
449
450
// Assemble the strings
451
size_t file_name_pos = 0;
452
size_t i = 0;
453
while (i < result_len) {
454
if (file_name_pos == first_pos) {
455
// We are in the range of the first placeholder
456
strcpy(result + i, first);
457
// Bump output buffer position with length of replacing string
458
i += first_len;
459
// Bump source buffer position to skip placeholder
460
file_name_pos += first_replace_len;
461
} else if (file_name_pos == second_pos) {
462
// We are in the range of the second placeholder
463
strcpy(result + i, second);
464
i += second_len;
465
file_name_pos += second_replace_len;
466
} else {
467
// Else, copy char by char of the original file
468
result[i] = file_name[file_name_pos++];
469
i++;
470
}
471
}
472
// Add terminating char
473
result[result_len] = '\0';
474
return result;
475
}
476
477
void LogFileOutput::describe(outputStream *out) {
478
LogOutput::describe(out);
479
out->print(" ");
480
481
out->print("filecount=%u,filesize=" SIZE_FORMAT "%s,async=%s", _file_count,
482
byte_size_in_proper_unit(_rotate_size),
483
proper_unit_for_byte_size(_rotate_size),
484
LogConfiguration::is_async_mode() ? "true" : "false");
485
}
486
487