VirtualBox

source: vbox/trunk/src/VBox/Runtime/common/log/log.cpp@ 62477

Last change on this file since 62477 was 62477, checked in by vboxsync, 8 years ago

(C) 2016

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 131.9 KB
Line 
1/* $Id: log.cpp 62477 2016-07-22 18:27:37Z vboxsync $ */
2/** @file
3 * Runtime VBox - Logger.
4 */
5
6/*
7 * Copyright (C) 2006-2016 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#include <iprt/log.h>
32#include "internal/iprt.h"
33
34#ifndef IN_RC
35# include <iprt/alloc.h>
36# include <iprt/process.h>
37# include <iprt/semaphore.h>
38# include <iprt/thread.h>
39# include <iprt/mp.h>
40#endif
41#ifdef IN_RING3
42# include <iprt/env.h>
43# include <iprt/file.h>
44# include <iprt/lockvalidator.h>
45# include <iprt/path.h>
46#endif
47#include <iprt/time.h>
48#include <iprt/asm.h>
49#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
50# include <iprt/asm-amd64-x86.h>
51#endif
52#include <iprt/assert.h>
53#include <iprt/err.h>
54#include <iprt/param.h>
55
56#include <iprt/stdarg.h>
57#include <iprt/string.h>
58#include <iprt/ctype.h>
59#ifdef IN_RING3
60# include <iprt/alloca.h>
61# include <stdio.h>
62#endif
63
64
65/*********************************************************************************************************************************
66* Defined Constants And Macros *
67*********************************************************************************************************************************/
68/** @def RTLOG_RINGBUF_DEFAULT_SIZE
69 * The default ring buffer size. */
70/** @def RTLOG_RINGBUF_MAX_SIZE
71 * The max ring buffer size. */
72/** @def RTLOG_RINGBUF_MIN_SIZE
73 * The min ring buffer size. */
74#ifdef IN_RING0
75# define RTLOG_RINGBUF_DEFAULT_SIZE _64K
76# define RTLOG_RINGBUF_MAX_SIZE _4M
77# define RTLOG_RINGBUF_MIN_SIZE _1K
78#elif defined(IN_RING3) || defined(DOXYGEN_RUNNING)
79# define RTLOG_RINGBUF_DEFAULT_SIZE _512K
80# define RTLOG_RINGBUF_MAX_SIZE _1G
81# define RTLOG_RINGBUF_MIN_SIZE _4K
82#endif
83/** The start of ring buffer eye catcher (16 bytes). */
84#define RTLOG_RINGBUF_EYE_CATCHER "START RING BUF\0"
85AssertCompile(sizeof(RTLOG_RINGBUF_EYE_CATCHER) == 16);
86/** The end of ring buffer eye catcher (16 bytes). This also ensures that the ring buffer
87 * forms are properly terminated C string (leading zero chars). */
88#define RTLOG_RINGBUF_EYE_CATCHER_END "\0\0\0END RING BUF"
89AssertCompile(sizeof(RTLOG_RINGBUF_EYE_CATCHER_END) == 16);
90
91
92/*********************************************************************************************************************************
93* Structures and Typedefs *
94*********************************************************************************************************************************/
95/**
96 * Arguments passed to the output function.
97 */
98typedef struct RTLOGOUTPUTPREFIXEDARGS
99{
100 /** The logger instance. */
101 PRTLOGGER pLogger;
102 /** The flags. (used for prefixing.) */
103 unsigned fFlags;
104 /** The group. (used for prefixing.) */
105 unsigned iGroup;
106} RTLOGOUTPUTPREFIXEDARGS, *PRTLOGOUTPUTPREFIXEDARGS;
107
108#ifndef IN_RC
109
110/**
111 * Internal logger data.
112 *
113 * @remarks Don't make casual changes to this structure.
114 */
115typedef struct RTLOGGERINTERNAL
116{
117 /** The structure revision (RTLOGGERINTERNAL_REV). */
118 uint32_t uRevision;
119 /** The size of the internal logger structure. */
120 uint32_t cbSelf;
121
122 /** Spinning mutex semaphore. Can be NIL. */
123 RTSEMSPINMUTEX hSpinMtx;
124 /** Pointer to the flush function. */
125 PFNRTLOGFLUSH pfnFlush;
126
127 /** Custom prefix callback. */
128 PFNRTLOGPREFIX pfnPrefix;
129 /** Prefix callback argument. */
130 void *pvPrefixUserArg;
131 /** This is set if a prefix is pending. */
132 bool fPendingPrefix;
133 /** Alignment padding. */
134 bool afPadding1[2];
135 /** Set if fully created. Used to avoid confusing in a few functions used to
136 * parse logger settings from environment variables. */
137 bool fCreated;
138
139 /** The max number of groups that there is room for in afGroups and papszGroups.
140 * Used by RTLogCopyGroupAndFlags(). */
141 uint32_t cMaxGroups;
142 /** Pointer to the group name array.
143 * (The data is readonly and provided by the user.) */
144 const char * const *papszGroups;
145
146 /** The number of log entries per group. NULL if
147 * RTLOGFLAGS_RESTRICT_GROUPS is not specified. */
148 uint32_t *pacEntriesPerGroup;
149 /** The max number of entries per group. */
150 uint32_t cMaxEntriesPerGroup;
151
152 /** @name Ring buffer logging
153 * The ring buffer records the last cbRingBuf - 1 of log output. The
154 * other configured log destinations are not touched until someone calls
155 * RTLogFlush(), when the ring buffer content is written to them all.
156 *
157 * The aim here is a fast logging destination, that avoids wasting storage
158 * space saving disk space when dealing with huge log volumes where the
159 * interesting bits usually are found near the end of the log. This is
160 * typically the case for scenarios that crashes or hits assertions.
161 *
162 * RTLogFlush() is called implicitly when hitting an assertion. While on a
163 * crash the most debuggers are able to make calls these days, it's usually
164 * possible to view the ring buffer memory.
165 *
166 * @{ */
167 /** Ring buffer size (including both eye catchers). */
168 uint32_t cbRingBuf;
169 /** Number of bytes passing thru the ring buffer since last RTLogFlush call.
170 * (This is used to avoid writing out the same bytes twice.) */
171 uint64_t volatile cbRingBufUnflushed;
172 /** Ring buffer pointer (points at RTLOG_RINGBUF_EYE_CATCHER). */
173 char *pszRingBuf;
174 /** Current ring buffer position (where to write the next char). */
175 char * volatile pchRingBufCur;
176 /** @} */
177
178# ifdef IN_RING3 /* Note! Must be at the end! */
179 /** @name File logging bits for the logger.
180 * @{ */
181 /** Pointer to the function called when starting logging, and when
182 * ending or starting a new log file as part of history rotation.
183 * This can be NULL. */
184 PFNRTLOGPHASE pfnPhase;
185
186 /** Handle to log file (if open). */
187 RTFILE hFile;
188 /** Log file history settings: maximum amount of data to put in a file. */
189 uint64_t cbHistoryFileMax;
190 /** Log file history settings: current amount of data in a file. */
191 uint64_t cbHistoryFileWritten;
192 /** Log file history settings: maximum time to use a file (in seconds). */
193 uint32_t cSecsHistoryTimeSlot;
194 /** Log file history settings: in what time slot was the file created. */
195 uint32_t uHistoryTimeSlotStart;
196 /** Log file history settings: number of older files to keep.
197 * 0 means no history. */
198 uint32_t cHistory;
199 /** Pointer to filename. */
200 char szFilename[RTPATH_MAX];
201 /** @} */
202# endif /* IN_RING3 */
203} RTLOGGERINTERNAL;
204
205/** The revision of the internal logger structure. */
206# define RTLOGGERINTERNAL_REV UINT32_C(10)
207
208# ifdef IN_RING3
209/** The size of the RTLOGGERINTERNAL structure in ring-0. */
210# define RTLOGGERINTERNAL_R0_SIZE RT_OFFSETOF(RTLOGGERINTERNAL, pfnPhase)
211AssertCompileMemberAlignment(RTLOGGERINTERNAL, hFile, sizeof(void *));
212AssertCompileMemberAlignment(RTLOGGERINTERNAL, cbHistoryFileMax, sizeof(uint64_t));
213# endif
214AssertCompileMemberAlignment(RTLOGGERINTERNAL, cbRingBufUnflushed, sizeof(uint64_t));
215
216#endif /* !IN_RC */
217
218
219/*********************************************************************************************************************************
220* Internal Functions *
221*********************************************************************************************************************************/
222#ifndef IN_RC
223static unsigned rtlogGroupFlags(const char *psz);
224#endif
225#ifdef IN_RING0
226static void rtR0LogLoggerExFallback(uint32_t fDestFlags, uint32_t fFlags, PRTLOGGERINTERNAL pInt,
227 const char *pszFormat, va_list va);
228#endif
229#ifdef IN_RING3
230static int rtlogFileOpen(PRTLOGGER pLogger, char *pszErrorMsg, size_t cchErrorMsg);
231static void rtlogRotate(PRTLOGGER pLogger, uint32_t uTimeSlot, bool fFirst);
232#endif
233#ifndef IN_RC
234static void rtLogRingBufFlush(PRTLOGGER pLogger);
235#endif
236static void rtlogFlush(PRTLOGGER pLogger);
237static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars);
238static DECLCALLBACK(size_t) rtLogOutputPrefixed(void *pv, const char *pachChars, size_t cbChars);
239static void rtlogLoggerExVLocked(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args);
240#ifndef IN_RC
241static void rtlogLoggerExFLocked(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, ...);
242#endif
243
244
245/*********************************************************************************************************************************
246* Global Variables *
247*********************************************************************************************************************************/
248#ifdef IN_RC
249/** Default logger instance. Make it weak because our RC module loader does not
250 * necessarily resolve this symbol and the compiler _must_ check if this is
251 * the case or not. That doesn't work for Darwin (``incompatible feature used:
252 * .weak_reference (must specify "-dynamic" to be used'') */
253# ifdef RT_OS_DARWIN
254extern "C" DECLIMPORT(RTLOGGERRC) g_Logger;
255# else
256extern "C" DECLWEAK(DECLIMPORT(RTLOGGERRC)) g_Logger;
257# endif
258#else /* !IN_RC */
259/** Default logger instance. */
260static PRTLOGGER g_pLogger;
261#endif /* !IN_RC */
262#ifdef IN_RING3
263/** The RTThreadGetWriteLockCount() change caused by the logger mutex semaphore. */
264static uint32_t volatile g_cLoggerLockCount;
265#endif
266
267#ifdef IN_RING0
268/** Number of per-thread loggers. */
269static int32_t volatile g_cPerThreadLoggers;
270/** Per-thread loggers.
271 * This is just a quick TLS hack suitable for debug logging only.
272 * If we run out of entries, just unload and reload the driver. */
273static struct RTLOGGERPERTHREAD
274{
275 /** The thread. */
276 RTNATIVETHREAD volatile NativeThread;
277 /** The (process / session) key. */
278 uintptr_t volatile uKey;
279 /** The logger instance.*/
280 PRTLOGGER volatile pLogger;
281} g_aPerThreadLoggers[8] =
282{
283 { NIL_RTNATIVETHREAD, 0, 0},
284 { NIL_RTNATIVETHREAD, 0, 0},
285 { NIL_RTNATIVETHREAD, 0, 0},
286 { NIL_RTNATIVETHREAD, 0, 0},
287 { NIL_RTNATIVETHREAD, 0, 0},
288 { NIL_RTNATIVETHREAD, 0, 0},
289 { NIL_RTNATIVETHREAD, 0, 0},
290 { NIL_RTNATIVETHREAD, 0, 0}
291};
292#endif /* IN_RING0 */
293
294/**
295 * Logger flags instructions.
296 */
297static struct
298{
299 const char *pszInstr; /**< The name */
300 size_t cchInstr; /**< The size of the name. */
301 uint32_t fFlag; /**< The flag value. */
302 bool fInverted; /**< Inverse meaning? */
303} const g_aLogFlags[] =
304{
305 { "disabled", sizeof("disabled" ) - 1, RTLOGFLAGS_DISABLED, false },
306 { "enabled", sizeof("enabled" ) - 1, RTLOGFLAGS_DISABLED, true },
307 { "buffered", sizeof("buffered" ) - 1, RTLOGFLAGS_BUFFERED, false },
308 { "unbuffered", sizeof("unbuffered" ) - 1, RTLOGFLAGS_BUFFERED, true },
309 { "usecrlf", sizeof("usecrlf" ) - 1, RTLOGFLAGS_USECRLF, false },
310 { "uself", sizeof("uself" ) - 1, RTLOGFLAGS_USECRLF, true },
311 { "append", sizeof("append" ) - 1, RTLOGFLAGS_APPEND, false },
312 { "overwrite", sizeof("overwrite" ) - 1, RTLOGFLAGS_APPEND, true },
313 { "rel", sizeof("rel" ) - 1, RTLOGFLAGS_REL_TS, false },
314 { "abs", sizeof("abs" ) - 1, RTLOGFLAGS_REL_TS, true },
315 { "dec", sizeof("dec" ) - 1, RTLOGFLAGS_DECIMAL_TS, false },
316 { "hex", sizeof("hex" ) - 1, RTLOGFLAGS_DECIMAL_TS, true },
317 { "writethru", sizeof("writethru" ) - 1, RTLOGFLAGS_WRITE_THROUGH, false },
318 { "writethrough", sizeof("writethrough") - 1, RTLOGFLAGS_WRITE_THROUGH, false },
319 { "flush", sizeof("flush" ) - 1, RTLOGFLAGS_FLUSH, false },
320 { "lockcnts", sizeof("lockcnts" ) - 1, RTLOGFLAGS_PREFIX_LOCK_COUNTS, false },
321 { "cpuid", sizeof("cpuid" ) - 1, RTLOGFLAGS_PREFIX_CPUID, false },
322 { "pid", sizeof("pid" ) - 1, RTLOGFLAGS_PREFIX_PID, false },
323 { "flagno", sizeof("flagno" ) - 1, RTLOGFLAGS_PREFIX_FLAG_NO, false },
324 { "flag", sizeof("flag" ) - 1, RTLOGFLAGS_PREFIX_FLAG, false },
325 { "groupno", sizeof("groupno" ) - 1, RTLOGFLAGS_PREFIX_GROUP_NO, false },
326 { "group", sizeof("group" ) - 1, RTLOGFLAGS_PREFIX_GROUP, false },
327 { "tid", sizeof("tid" ) - 1, RTLOGFLAGS_PREFIX_TID, false },
328 { "thread", sizeof("thread" ) - 1, RTLOGFLAGS_PREFIX_THREAD, false },
329 { "custom", sizeof("custom" ) - 1, RTLOGFLAGS_PREFIX_CUSTOM, false },
330 { "timeprog", sizeof("timeprog" ) - 1, RTLOGFLAGS_PREFIX_TIME_PROG, false },
331 { "time", sizeof("time" ) - 1, RTLOGFLAGS_PREFIX_TIME, false },
332 { "msprog", sizeof("msprog" ) - 1, RTLOGFLAGS_PREFIX_MS_PROG, false },
333 { "tsc", sizeof("tsc" ) - 1, RTLOGFLAGS_PREFIX_TSC, false }, /* before ts! */
334 { "ts", sizeof("ts" ) - 1, RTLOGFLAGS_PREFIX_TS, false },
335 /* We intentionally omit RTLOGFLAGS_RESTRICT_GROUPS. */
336};
337
338/**
339 * Logger destination instructions.
340 */
341static struct
342{
343 const char *pszInstr; /**< The name. */
344 size_t cchInstr; /**< The size of the name. */
345 uint32_t fFlag; /**< The corresponding destination flag. */
346} const g_aLogDst[] =
347{
348 { RT_STR_TUPLE("file"), RTLOGDEST_FILE }, /* Must be 1st! */
349 { RT_STR_TUPLE("dir"), RTLOGDEST_FILE }, /* Must be 2nd! */
350 { RT_STR_TUPLE("history"), 0 }, /* Must be 3rd! */
351 { RT_STR_TUPLE("histsize"), 0 }, /* Must be 4th! */
352 { RT_STR_TUPLE("histtime"), 0 }, /* Must be 5th! */
353 { RT_STR_TUPLE("ringbuf"), RTLOGDEST_RINGBUF }, /* Must be 6th! */
354 { RT_STR_TUPLE("stdout"), RTLOGDEST_STDOUT },
355 { RT_STR_TUPLE("stderr"), RTLOGDEST_STDERR },
356 { RT_STR_TUPLE("debugger"), RTLOGDEST_DEBUGGER },
357 { RT_STR_TUPLE("com"), RTLOGDEST_COM },
358 { RT_STR_TUPLE("user"), RTLOGDEST_USER },
359};
360
361/** Log rotation backoff table - millisecond sleep intervals.
362 * Important on Windows host, especially for VBoxSVC release logging. Only a
363 * medium term solution, until a proper fix for log file handling is available.
364 * 10 seconds total.
365 */
366static const uint32_t g_acMsLogBackoff[] =
367{ 10, 10, 10, 20, 50, 100, 200, 200, 200, 200, 500, 500, 500, 500, 1000, 1000, 1000, 1000, 1000, 1000, 1000 };
368
369
370/**
371 * Locks the logger instance.
372 *
373 * @returns See RTSemSpinMutexRequest().
374 * @param pLogger The logger instance.
375 */
376DECLINLINE(int) rtlogLock(PRTLOGGER pLogger)
377{
378#ifndef IN_RC
379 PRTLOGGERINTERNAL pInt = pLogger->pInt;
380 AssertMsgReturn(pInt->uRevision == RTLOGGERINTERNAL_REV, ("%#x != %#x\n", pInt->uRevision, RTLOGGERINTERNAL_REV),
381 VERR_LOG_REVISION_MISMATCH);
382 AssertMsgReturn(pInt->cbSelf == sizeof(*pInt), ("%#x != %#x\n", pInt->cbSelf, sizeof(*pInt)),
383 VERR_LOG_REVISION_MISMATCH);
384 if (pInt->hSpinMtx != NIL_RTSEMSPINMUTEX)
385 {
386 int rc = RTSemSpinMutexRequest(pInt->hSpinMtx);
387 if (RT_FAILURE(rc))
388 return rc;
389 }
390#else
391 NOREF(pLogger);
392#endif
393 return VINF_SUCCESS;
394}
395
396
397/**
398 * Unlocks the logger instance.
399 * @param pLogger The logger instance.
400 */
401DECLINLINE(void) rtlogUnlock(PRTLOGGER pLogger)
402{
403#ifndef IN_RC
404 if (pLogger->pInt->hSpinMtx != NIL_RTSEMSPINMUTEX)
405 RTSemSpinMutexRelease(pLogger->pInt->hSpinMtx);
406#else
407 NOREF(pLogger);
408#endif
409 return;
410}
411
412#ifndef IN_RC
413# ifdef IN_RING3
414
415# ifdef SOME_UNUSED_FUNCTION
416/**
417 * Logging to file, output callback.
418 *
419 * @param pvArg User argument.
420 * @param pachChars Pointer to an array of utf-8 characters.
421 * @param cbChars Number of bytes in the character array pointed to by pachChars.
422 */
423static DECLCALLBACK(size_t) rtlogPhaseWrite(void *pvArg, const char *pachChars, size_t cbChars)
424{
425 PRTLOGGER pLogger = (PRTLOGGER)pvArg;
426 RTFileWrite(pLogger->pInt->hFile, pachChars, cbChars, NULL);
427 return cbChars;
428}
429
430
431/**
432 * Callback to format VBox formatting extentions.
433 * See @ref pg_rt_str_format for a reference on the format types.
434 *
435 * @returns The number of bytes formatted.
436 * @param pvArg Formatter argument.
437 * @param pfnOutput Pointer to output function.
438 * @param pvArgOutput Argument for the output function.
439 * @param ppszFormat Pointer to the format string pointer. Advance this till the char
440 * after the format specifier.
441 * @param pArgs Pointer to the argument list. Use this to fetch the arguments.
442 * @param cchWidth Format Width. -1 if not specified.
443 * @param cchPrecision Format Precision. -1 if not specified.
444 * @param fFlags Flags (RTSTR_NTFS_*).
445 * @param chArgSize The argument size specifier, 'l' or 'L'.
446 */
447static DECLCALLBACK(size_t) rtlogPhaseFormatStr(void *pvArg, PFNRTSTROUTPUT pfnOutput, void *pvArgOutput,
448 const char **ppszFormat, va_list *pArgs, int cchWidth,
449 int cchPrecision, unsigned fFlags, char chArgSize)
450{
451 char ch = *(*ppszFormat)++;
452
453 AssertMsgFailed(("Invalid logger phase format type '%%%c%.10s'!\n", ch, *ppszFormat)); NOREF(ch);
454
455 return 0;
456}
457
458# endif /* SOME_UNUSED_FUNCTION */
459
460
461/**
462 * Log phase callback function, assumes the lock is already held
463 *
464 * @param pLogger The logger instance.
465 * @param pszFormat Format string.
466 * @param ... Optional arguments as specified in the format string.
467 */
468static DECLCALLBACK(void) rtlogPhaseMsgLocked(PRTLOGGER pLogger, const char *pszFormat, ...)
469{
470 va_list args;
471 AssertPtrReturnVoid(pLogger);
472 AssertPtrReturnVoid(pLogger->pInt);
473 Assert(pLogger->pInt->hSpinMtx != NIL_RTSEMSPINMUTEX);
474
475 va_start(args, pszFormat);
476 rtlogLoggerExVLocked(pLogger, 0, ~0U, pszFormat, args);
477 va_end(args);
478}
479
480
481/**
482 * Log phase callback function, assumes the lock is not held.
483 *
484 * @param pLogger The logger instance.
485 * @param pszFormat Format string.
486 * @param ... Optional arguments as specified in the format string.
487 */
488static DECLCALLBACK(void) rtlogPhaseMsgNormal(PRTLOGGER pLogger, const char *pszFormat, ...)
489{
490 va_list args;
491 AssertPtrReturnVoid(pLogger);
492 AssertPtrReturnVoid(pLogger->pInt);
493 Assert(pLogger->pInt->hSpinMtx != NIL_RTSEMSPINMUTEX);
494
495 va_start(args, pszFormat);
496 RTLogLoggerExV(pLogger, 0, ~0U, pszFormat, args);
497 va_end(args);
498}
499
500# endif /* IN_RING3 */
501
502/**
503 * Adjusts the ring buffer.
504 *
505 * @returns IPRT status code.
506 * @param pLogger The logger instance.
507 * @param cbNewSize The new ring buffer size (0 == default).
508 * @param fForce Whether to do this even if the logger instance hasn't
509 * really been fully created yet (i.e. during RTLogCreate).
510 */
511static int rtLogRingBufAdjust(PRTLOGGER pLogger, uint32_t cbNewSize, bool fForce)
512{
513 /*
514 * If this is early logger init, don't do anything.
515 */
516 if (!pLogger->pInt->fCreated && !fForce)
517 return VINF_SUCCESS;
518
519 /*
520 * Lock the logger and make the necessary changes.
521 */
522 int rc = rtlogLock(pLogger);
523 if (RT_SUCCESS(rc))
524 {
525 if (cbNewSize == 0)
526 cbNewSize = RTLOG_RINGBUF_DEFAULT_SIZE;
527 if ( pLogger->pInt->cbRingBuf != cbNewSize
528 || !pLogger->pInt->pchRingBufCur)
529 {
530 uintptr_t offOld = pLogger->pInt->pchRingBufCur - pLogger->pInt->pszRingBuf;
531 if (offOld < sizeof(RTLOG_RINGBUF_EYE_CATCHER))
532 offOld = sizeof(RTLOG_RINGBUF_EYE_CATCHER);
533 else if (offOld >= cbNewSize)
534 {
535 memmove(pLogger->pInt->pszRingBuf, &pLogger->pInt->pszRingBuf[offOld - cbNewSize], cbNewSize);
536 offOld = sizeof(RTLOG_RINGBUF_EYE_CATCHER);
537 }
538
539 void *pvNew = RTMemRealloc(pLogger->pInt->pchRingBufCur, cbNewSize);
540 if (pvNew)
541 {
542 pLogger->pInt->pszRingBuf = (char *)pvNew;
543 pLogger->pInt->pchRingBufCur = (char *)pvNew + offOld;
544 pLogger->pInt->cbRingBuf = cbNewSize;
545 memcpy(pvNew, RTLOG_RINGBUF_EYE_CATCHER, sizeof(RTLOG_RINGBUF_EYE_CATCHER));
546 memcpy((char *)pvNew + cbNewSize - sizeof(RTLOG_RINGBUF_EYE_CATCHER_END),
547 RTLOG_RINGBUF_EYE_CATCHER_END, sizeof(RTLOG_RINGBUF_EYE_CATCHER_END));
548 rc = VINF_SUCCESS;
549 }
550 else
551 rc = VERR_NO_MEMORY;
552 }
553 rtlogUnlock(pLogger);
554 }
555
556 return rc;
557}
558
559
560/**
561 * Writes text to the ring buffer.
562 *
563 * @param pInt The internal logger data structure.
564 * @param pachText The text to write.
565 * @param cchText The number of chars (bytes) to write.
566 */
567static void rtLogRingBufWrite(PRTLOGGERINTERNAL pInt, const char *pachText, size_t cchText)
568{
569 /*
570 * Get the ring buffer data, adjusting it to only describe the writable
571 * part of the buffer.
572 */
573 char * const pchStart = &pInt->pszRingBuf[sizeof(RTLOG_RINGBUF_EYE_CATCHER)];
574 size_t const cchBuf = pInt->cbRingBuf - sizeof(RTLOG_RINGBUF_EYE_CATCHER) - sizeof(RTLOG_RINGBUF_EYE_CATCHER_END);
575 char *pchCur = pInt->pchRingBufCur;
576 size_t cchLeft = pchCur - pchStart;
577 if (RT_LIKELY(cchLeft < cchBuf))
578 cchLeft = cchBuf - cchLeft;
579 else
580 {
581 /* May happen in ring-0 where a thread or two went ahead without getting the lock. */
582 pchCur = pchStart;
583 cchLeft = cchBuf;
584 }
585 Assert(cchBuf < pInt->cbRingBuf);
586
587 if (cchText < cchLeft)
588 {
589 /*
590 * The text fits in the remaining space.
591 */
592 memcpy(pchCur, pachText, cchText);
593 pchCur[cchText] = '\0';
594 pInt->pchRingBufCur = &pchCur[cchText];
595 pInt->cbRingBufUnflushed += cchText;
596 }
597 else
598 {
599 /*
600 * The text wraps around. Taking the simple but inefficient approach
601 * to input texts that are longer than the ring buffer since that
602 * is unlikely to the be a frequent case.
603 */
604 /* Fill to the end of the buffer. */
605 memcpy(pchCur, pachText, cchLeft);
606 pachText += cchLeft;
607 cchText -= cchLeft;
608 pInt->cbRingBufUnflushed += cchLeft;
609 pInt->pchRingBufCur = pchStart;
610
611 /* Ring buffer overflows (the plainly inefficient bit). */
612 while (cchText >= cchBuf)
613 {
614 memcpy(pchStart, pachText, cchBuf);
615 pachText += cchBuf;
616 cchText -= cchBuf;
617 pInt->cbRingBufUnflushed += cchBuf;
618 }
619
620 /* The final bit, if any. */
621 if (cchText > 0)
622 {
623 memcpy(pchStart, pachText, cchText);
624 pInt->cbRingBufUnflushed += cchText;
625 }
626 pchStart[cchText] = '\0';
627 pInt->pchRingBufCur = &pchStart[cchText];
628 }
629}
630
631
632/**
633 * Flushes the ring buffer to all the other log destinations.
634 *
635 * @param pLogger The logger instance which ring buffer should be flushed.
636 */
637static void rtLogRingBufFlush(PRTLOGGER pLogger)
638{
639 const char *pszPreamble;
640 size_t cchPreamble;
641 const char *pszFirst;
642 size_t cchFirst;
643 const char *pszSecond;
644 size_t cchSecond;
645
646 /*
647 * Get the ring buffer data, adjusting it to only describe the writable
648 * part of the buffer.
649 */
650 uint64_t cchUnflushed = pLogger->pInt->cbRingBufUnflushed;
651 char * const pszBuf = &pLogger->pInt->pszRingBuf[sizeof(RTLOG_RINGBUF_EYE_CATCHER)];
652 size_t const cchBuf = pLogger->pInt->cbRingBuf - sizeof(RTLOG_RINGBUF_EYE_CATCHER) - sizeof(RTLOG_RINGBUF_EYE_CATCHER_END);
653 size_t offCur = pLogger->pInt->pchRingBufCur - pszBuf;
654 size_t cchAfter;
655 if (RT_LIKELY(offCur < cchBuf))
656 cchAfter = cchBuf - offCur;
657 else /* May happen in ring-0 where a thread or two went ahead without getting the lock. */
658 {
659 offCur = 0;
660 cchAfter = cchBuf;
661 }
662
663 pLogger->pInt->cbRingBufUnflushed = 0;
664
665 /*
666 * Figure out whether there are one or two segments that needs writing,
667 * making the last segment is terminated. (The first is always
668 * terminated because of the eye-catcher at the end of the buffer.)
669 */
670 if (cchUnflushed == 0)
671 return;
672 pszBuf[offCur] = '\0';
673 if (cchUnflushed >= cchBuf)
674 {
675 pszFirst = &pszBuf[offCur + 1];
676 cchFirst = cchAfter ? cchAfter - 1 : 0;
677 pszSecond = pszBuf;
678 cchSecond = offCur;
679 pszPreamble = "\n*FLUSH RING BUF*\n";
680 cchPreamble = sizeof("\n*FLUSH RING BUF*\n") - 1;
681 }
682 else if ((size_t)cchUnflushed <= offCur)
683 {
684 cchFirst = (size_t)cchUnflushed;
685 pszFirst = &pszBuf[offCur - cchFirst];
686 pszSecond = "";
687 cchSecond = 0;
688 pszPreamble = "";
689 cchPreamble = 0;
690 }
691 else
692 {
693 cchFirst = (size_t)cchUnflushed - offCur;
694 pszFirst = &pszBuf[cchBuf - cchFirst];
695 pszSecond = pszBuf;
696 cchSecond = offCur;
697 pszPreamble = "";
698 cchPreamble = 0;
699 }
700
701 /*
702 * Write the ring buffer to all other destiations.
703 */
704 if (pLogger->fDestFlags & RTLOGDEST_USER)
705 {
706 if (cchPreamble)
707 RTLogWriteUser(pszPreamble, cchPreamble);
708 if (cchFirst)
709 RTLogWriteUser(pszFirst, cchFirst);
710 if (cchSecond)
711 RTLogWriteUser(pszSecond, cchSecond);
712 }
713
714 if (pLogger->fDestFlags & RTLOGDEST_DEBUGGER)
715 {
716 if (cchPreamble)
717 RTLogWriteDebugger(pszPreamble, cchPreamble);
718 if (cchFirst)
719 RTLogWriteDebugger(pszFirst, cchFirst);
720 if (cchSecond)
721 RTLogWriteDebugger(pszSecond, cchSecond);
722 }
723
724# ifdef IN_RING3
725 if (pLogger->fDestFlags & RTLOGDEST_FILE)
726 {
727 if (pLogger->pInt->hFile != NIL_RTFILE)
728 {
729 if (cchPreamble)
730 RTFileWrite(pLogger->pInt->hFile, pszPreamble, cchPreamble, NULL);
731 if (cchFirst)
732 RTFileWrite(pLogger->pInt->hFile, pszFirst, cchFirst, NULL);
733 if (cchSecond)
734 RTFileWrite(pLogger->pInt->hFile, pszSecond, cchSecond, NULL);
735 if (pLogger->fFlags & RTLOGFLAGS_FLUSH)
736 RTFileFlush(pLogger->pInt->hFile);
737 }
738 if (pLogger->pInt->cHistory)
739 pLogger->pInt->cbHistoryFileWritten += cchFirst + cchSecond;
740 }
741# endif
742
743 if (pLogger->fDestFlags & RTLOGDEST_STDOUT)
744 {
745 if (cchPreamble)
746 RTLogWriteStdOut(pszPreamble, cchPreamble);
747 if (cchFirst)
748 RTLogWriteStdOut(pszFirst, cchFirst);
749 if (cchSecond)
750 RTLogWriteStdOut(pszSecond, cchSecond);
751 }
752
753 if (pLogger->fDestFlags & RTLOGDEST_STDERR)
754 {
755 if (cchPreamble)
756 RTLogWriteStdErr(pszPreamble, cchPreamble);
757 if (cchFirst)
758 RTLogWriteStdErr(pszFirst, cchFirst);
759 if (cchSecond)
760 RTLogWriteStdErr(pszSecond, cchSecond);
761 }
762
763# if defined(IN_RING0) && !defined(LOG_NO_COM)
764 if (pLogger->fDestFlags & RTLOGDEST_COM)
765 {
766 if (cchPreamble)
767 RTLogWriteCom(pszPreamble, cchPreamble);
768 if (cchFirst)
769 RTLogWriteCom(pszFirst, cchFirst);
770 if (cchSecond)
771 RTLogWriteCom(pszSecond, cchSecond);
772 }
773# endif
774}
775
776
777
778
779RTDECL(int) RTLogCreateExV(PRTLOGGER *ppLogger, uint32_t fFlags, const char *pszGroupSettings,
780 const char *pszEnvVarBase, unsigned cGroups, const char * const *papszGroups,
781 uint32_t fDestFlags, PFNRTLOGPHASE pfnPhase, uint32_t cHistory,
782 uint64_t cbHistoryFileMax, uint32_t cSecsHistoryTimeSlot,
783 char *pszErrorMsg, size_t cchErrorMsg, const char *pszFilenameFmt, va_list args)
784{
785 int rc;
786 size_t offInternal;
787 size_t cbLogger;
788 PRTLOGGER pLogger;
789
790 /*
791 * Validate input.
792 */
793 if ( (cGroups && !papszGroups)
794 || !VALID_PTR(ppLogger) )
795 {
796 AssertMsgFailed(("Invalid parameters!\n"));
797 return VERR_INVALID_PARAMETER;
798 }
799 *ppLogger = NULL;
800
801 if (pszErrorMsg)
802 RTStrPrintf(pszErrorMsg, cchErrorMsg, N_("unknown error"));
803
804 AssertMsgReturn(cHistory < _1M, ("%#x", cHistory), VERR_OUT_OF_RANGE);
805
806 /*
807 * Allocate a logger instance.
808 */
809 offInternal = RT_OFFSETOF(RTLOGGER, afGroups[cGroups]);
810 offInternal = RT_ALIGN_Z(offInternal, sizeof(uint64_t));
811 cbLogger = offInternal + sizeof(RTLOGGERINTERNAL);
812 if (fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
813 cbLogger += cGroups * sizeof(uint32_t);
814 pLogger = (PRTLOGGER)RTMemAllocZVar(cbLogger);
815 if (pLogger)
816 {
817# if defined(RT_ARCH_X86) && (!defined(LOG_USE_C99) || !defined(RT_WITHOUT_EXEC_ALLOC))
818 uint8_t *pu8Code;
819# endif
820 pLogger->u32Magic = RTLOGGER_MAGIC;
821 pLogger->cGroups = cGroups;
822 pLogger->fFlags = fFlags;
823 pLogger->fDestFlags = fDestFlags;
824 pLogger->pInt = (PRTLOGGERINTERNAL)((uintptr_t)pLogger + offInternal);
825 pLogger->pInt->uRevision = RTLOGGERINTERNAL_REV;
826 pLogger->pInt->cbSelf = sizeof(RTLOGGERINTERNAL);
827 pLogger->pInt->hSpinMtx = NIL_RTSEMSPINMUTEX;
828 pLogger->pInt->pfnFlush = NULL;
829 pLogger->pInt->pfnPrefix = NULL;
830 pLogger->pInt->pvPrefixUserArg = NULL;
831 pLogger->pInt->afPadding1[0] = false;
832 pLogger->pInt->afPadding1[1] = false;
833 pLogger->pInt->fCreated = false;
834 pLogger->pInt->cMaxGroups = cGroups;
835 pLogger->pInt->papszGroups = papszGroups;
836 if (fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
837 pLogger->pInt->pacEntriesPerGroup = (uint32_t *)(pLogger->pInt + 1);
838 else
839 pLogger->pInt->pacEntriesPerGroup = NULL;
840 pLogger->pInt->cMaxEntriesPerGroup = UINT32_MAX;
841# ifdef IN_RING3
842 pLogger->pInt->pfnPhase = pfnPhase;
843 pLogger->pInt->hFile = NIL_RTFILE;
844 pLogger->pInt->cHistory = cHistory;
845 if (cbHistoryFileMax == 0)
846 pLogger->pInt->cbHistoryFileMax = UINT64_MAX;
847 else
848 pLogger->pInt->cbHistoryFileMax = cbHistoryFileMax;
849 if (cSecsHistoryTimeSlot == 0)
850 pLogger->pInt->cSecsHistoryTimeSlot = UINT32_MAX;
851 else
852 pLogger->pInt->cSecsHistoryTimeSlot = cSecsHistoryTimeSlot;
853# endif /* IN_RING3 */
854 if (pszGroupSettings)
855 RTLogGroupSettings(pLogger, pszGroupSettings);
856
857# if defined(RT_ARCH_X86) && (!defined(LOG_USE_C99) || !defined(RT_WITHOUT_EXEC_ALLOC))
858 /*
859 * Emit wrapper code.
860 */
861 pu8Code = (uint8_t *)RTMemExecAlloc(64);
862 if (pu8Code)
863 {
864 pLogger->pfnLogger = *(PFNRTLOGGER*)&pu8Code;
865 *pu8Code++ = 0x68; /* push imm32 */
866 *(void **)pu8Code = pLogger;
867 pu8Code += sizeof(void *);
868 *pu8Code++ = 0xe8; /* call rel32 */
869 *(uint32_t *)pu8Code = (uintptr_t)RTLogLogger - ((uintptr_t)pu8Code + sizeof(uint32_t));
870 pu8Code += sizeof(uint32_t);
871 *pu8Code++ = 0x8d; /* lea esp, [esp + 4] */
872 *pu8Code++ = 0x64;
873 *pu8Code++ = 0x24;
874 *pu8Code++ = 0x04;
875 *pu8Code++ = 0xc3; /* ret near */
876 AssertMsg((uintptr_t)pu8Code - (uintptr_t)pLogger->pfnLogger <= 64,
877 ("Wrapper assembly is too big! %d bytes\n", (uintptr_t)pu8Code - (uintptr_t)pLogger->pfnLogger));
878 rc = VINF_SUCCESS;
879 }
880 else
881 {
882# ifdef RT_OS_LINUX
883 if (pszErrorMsg) /* Most probably SELinux causing trouble since the larger RTMemAlloc succeeded. */
884 RTStrPrintf(pszErrorMsg, cchErrorMsg, N_("mmap(PROT_WRITE | PROT_EXEC) failed -- SELinux?"));
885# endif
886 rc = VERR_NO_MEMORY;
887 }
888 if (RT_SUCCESS(rc))
889# endif /* X86 wrapper code*/
890 {
891# ifdef IN_RING3 /* files and env.vars. are only accessible when in R3 at the present time. */
892 /*
893 * Format the filename.
894 */
895 if (pszFilenameFmt)
896 {
897 /** @todo validate the length, fail on overflow. */
898 RTStrPrintfV(pLogger->pInt->szFilename, sizeof(pLogger->pInt->szFilename), pszFilenameFmt, args);
899 pLogger->fDestFlags |= RTLOGDEST_FILE;
900 }
901
902 /*
903 * Parse the environment variables.
904 */
905 if (pszEnvVarBase)
906 {
907 /* make temp copy of environment variable base. */
908 size_t cchEnvVarBase = strlen(pszEnvVarBase);
909 char *pszEnvVar = (char *)alloca(cchEnvVarBase + 16);
910 memcpy(pszEnvVar, pszEnvVarBase, cchEnvVarBase);
911
912 /*
913 * Destination.
914 */
915 strcpy(pszEnvVar + cchEnvVarBase, "_DEST");
916 const char *pszValue = RTEnvGet(pszEnvVar);
917 if (pszValue)
918 RTLogDestinations(pLogger, pszValue);
919
920 /*
921 * The flags.
922 */
923 strcpy(pszEnvVar + cchEnvVarBase, "_FLAGS");
924 pszValue = RTEnvGet(pszEnvVar);
925 if (pszValue)
926 RTLogFlags(pLogger, pszValue);
927
928 /*
929 * The group settings.
930 */
931 pszEnvVar[cchEnvVarBase] = '\0';
932 pszValue = RTEnvGet(pszEnvVar);
933 if (pszValue)
934 RTLogGroupSettings(pLogger, pszValue);
935 }
936# endif /* IN_RING3 */
937
938 /*
939 * Open the destination(s).
940 */
941 rc = VINF_SUCCESS;
942# ifdef IN_RING3
943 if (pLogger->fDestFlags & RTLOGDEST_FILE)
944 {
945 if (pLogger->fFlags & RTLOGFLAGS_APPEND)
946 {
947 rc = rtlogFileOpen(pLogger, pszErrorMsg, cchErrorMsg);
948
949 /* Rotate in case of appending to a too big log file,
950 otherwise this simply doesn't do anything. */
951 rtlogRotate(pLogger, 0, true /* fFirst */);
952 }
953 else
954 {
955 /* Force rotation if it is configured. */
956 pLogger->pInt->cbHistoryFileWritten = UINT64_MAX;
957 rtlogRotate(pLogger, 0, true /* fFirst */);
958
959 /* If the file is not open then rotation is not set up. */
960 if (pLogger->pInt->hFile == NIL_RTFILE)
961 {
962 pLogger->pInt->cbHistoryFileWritten = 0;
963 rc = rtlogFileOpen(pLogger, pszErrorMsg, cchErrorMsg);
964 }
965 }
966 }
967# endif /* IN_RING3 */
968
969 if ((pLogger->fDestFlags & RTLOGDEST_RINGBUF) && RT_SUCCESS(rc))
970 rc = rtLogRingBufAdjust(pLogger, pLogger->pInt->cbRingBuf, true /*fForce*/);
971
972 /*
973 * Create mutex and check how much it counts when entering the lock
974 * so that we can report the values for RTLOGFLAGS_PREFIX_LOCK_COUNTS.
975 */
976 if (RT_SUCCESS(rc))
977 {
978 rc = RTSemSpinMutexCreate(&pLogger->pInt->hSpinMtx, RTSEMSPINMUTEX_FLAGS_IRQ_SAFE);
979 if (RT_SUCCESS(rc))
980 {
981# ifdef IN_RING3 /** @todo do counters in ring-0 too? */
982 RTTHREAD Thread = RTThreadSelf();
983 if (Thread != NIL_RTTHREAD)
984 {
985 int32_t c = RTLockValidatorWriteLockGetCount(Thread);
986 RTSemSpinMutexRequest(pLogger->pInt->hSpinMtx);
987 c = RTLockValidatorWriteLockGetCount(Thread) - c;
988 RTSemSpinMutexRelease(pLogger->pInt->hSpinMtx);
989 ASMAtomicWriteU32(&g_cLoggerLockCount, c);
990 }
991
992 /* Use the callback to generate some initial log contents. */
993 Assert(VALID_PTR(pLogger->pInt->pfnPhase) || pLogger->pInt->pfnPhase == NULL);
994 if (pLogger->pInt->pfnPhase)
995 pLogger->pInt->pfnPhase(pLogger, RTLOGPHASE_BEGIN, rtlogPhaseMsgNormal);
996# endif
997 pLogger->pInt->fCreated = true;
998 *ppLogger = pLogger;
999 return VINF_SUCCESS;
1000 }
1001
1002 if (pszErrorMsg)
1003 RTStrPrintf(pszErrorMsg, cchErrorMsg, N_("failed to create semaphore"));
1004 }
1005# ifdef IN_RING3
1006 RTFileClose(pLogger->pInt->hFile);
1007# endif
1008# if defined(LOG_USE_C99) && defined(RT_WITHOUT_EXEC_ALLOC)
1009 RTMemFree(*(void **)&pLogger->pfnLogger);
1010# else
1011 RTMemExecFree(*(void **)&pLogger->pfnLogger, 64);
1012# endif
1013 }
1014 RTMemFree(pLogger);
1015 }
1016 else
1017 rc = VERR_NO_MEMORY;
1018
1019 return rc;
1020}
1021RT_EXPORT_SYMBOL(RTLogCreateExV);
1022
1023
1024RTDECL(int) RTLogCreate(PRTLOGGER *ppLogger, uint32_t fFlags, const char *pszGroupSettings,
1025 const char *pszEnvVarBase, unsigned cGroups, const char * const * papszGroups,
1026 uint32_t fDestFlags, const char *pszFilenameFmt, ...)
1027{
1028 va_list args;
1029 int rc;
1030
1031 va_start(args, pszFilenameFmt);
1032 rc = RTLogCreateExV(ppLogger, fFlags, pszGroupSettings, pszEnvVarBase, cGroups, papszGroups,
1033 fDestFlags, NULL /*pfnPhase*/, 0 /*cHistory*/, 0 /*cbHistoryFileMax*/, 0 /*cSecsHistoryTimeSlot*/,
1034 NULL /*pszErrorMsg*/, 0 /*cchErrorMsg*/, pszFilenameFmt, args);
1035 va_end(args);
1036 return rc;
1037}
1038RT_EXPORT_SYMBOL(RTLogCreate);
1039
1040
1041RTDECL(int) RTLogCreateEx(PRTLOGGER *ppLogger, uint32_t fFlags, const char *pszGroupSettings,
1042 const char *pszEnvVarBase, unsigned cGroups, const char * const * papszGroups,
1043 uint32_t fDestFlags, PFNRTLOGPHASE pfnPhase, uint32_t cHistory,
1044 uint64_t cbHistoryFileMax, uint32_t cSecsHistoryTimeSlot,
1045 char *pszErrorMsg, size_t cchErrorMsg, const char *pszFilenameFmt, ...)
1046{
1047 va_list args;
1048 int rc;
1049
1050 va_start(args, pszFilenameFmt);
1051 rc = RTLogCreateExV(ppLogger, fFlags, pszGroupSettings, pszEnvVarBase, cGroups, papszGroups,
1052 fDestFlags, pfnPhase, cHistory, cbHistoryFileMax, cSecsHistoryTimeSlot,
1053 pszErrorMsg, cchErrorMsg, pszFilenameFmt, args);
1054 va_end(args);
1055 return rc;
1056}
1057RT_EXPORT_SYMBOL(RTLogCreateEx);
1058
1059
1060/**
1061 * Destroys a logger instance.
1062 *
1063 * The instance is flushed and all output destinations closed (where applicable).
1064 *
1065 * @returns iprt status code.
1066 * @param pLogger The logger instance which close destroyed. NULL is fine.
1067 */
1068RTDECL(int) RTLogDestroy(PRTLOGGER pLogger)
1069{
1070 int rc;
1071 uint32_t iGroup;
1072 RTSEMSPINMUTEX hSpinMtx;
1073
1074 /*
1075 * Validate input.
1076 */
1077 if (!pLogger)
1078 return VINF_SUCCESS;
1079 AssertPtrReturn(pLogger, VERR_INVALID_POINTER);
1080 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
1081 AssertPtrReturn(pLogger->pInt, VERR_INVALID_POINTER);
1082
1083 /*
1084 * Acquire logger instance sem and disable all logging. (paranoia)
1085 */
1086 rc = rtlogLock(pLogger);
1087 AssertMsgRCReturn(rc, ("%Rrc\n", rc), rc);
1088
1089 pLogger->fFlags |= RTLOGFLAGS_DISABLED;
1090 iGroup = pLogger->cGroups;
1091 while (iGroup-- > 0)
1092 pLogger->afGroups[iGroup] = 0;
1093
1094 /*
1095 * Flush it.
1096 */
1097 rtlogFlush(pLogger);
1098
1099# ifdef IN_RING3
1100 /*
1101 * Add end of logging message.
1102 */
1103 if ( (pLogger->fDestFlags & RTLOGDEST_FILE)
1104 && pLogger->pInt->hFile != NIL_RTFILE)
1105 pLogger->pInt->pfnPhase(pLogger, RTLOGPHASE_END, rtlogPhaseMsgLocked);
1106
1107 /*
1108 * Close output stuffs.
1109 */
1110 if (pLogger->pInt->hFile != NIL_RTFILE)
1111 {
1112 int rc2 = RTFileClose(pLogger->pInt->hFile);
1113 AssertRC(rc2);
1114 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1115 rc = rc2;
1116 pLogger->pInt->hFile = NIL_RTFILE;
1117 }
1118# endif
1119
1120 /*
1121 * Free the mutex, the wrapper and the instance memory.
1122 */
1123 hSpinMtx = pLogger->pInt->hSpinMtx;
1124 pLogger->pInt->hSpinMtx = NIL_RTSEMSPINMUTEX;
1125 if (hSpinMtx != NIL_RTSEMSPINMUTEX)
1126 {
1127 int rc2;
1128 RTSemSpinMutexRelease(hSpinMtx);
1129 rc2 = RTSemSpinMutexDestroy(hSpinMtx);
1130 AssertRC(rc2);
1131 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1132 rc = rc2;
1133 }
1134
1135 if (pLogger->pfnLogger)
1136 {
1137# if defined(LOG_USE_C99) && defined(RT_WITHOUT_EXEC_ALLOC)
1138 RTMemFree(*(void **)&pLogger->pfnLogger);
1139# else
1140 RTMemExecFree(*(void **)&pLogger->pfnLogger, 64);
1141# endif
1142 pLogger->pfnLogger = NULL;
1143 }
1144 RTMemFree(pLogger);
1145
1146 return rc;
1147}
1148RT_EXPORT_SYMBOL(RTLogDestroy);
1149
1150
1151/**
1152 * Create a logger instance clone for RC usage.
1153 *
1154 * @returns iprt status code.
1155 *
1156 * @param pLogger The logger instance to be cloned.
1157 * @param pLoggerRC Where to create the RC logger instance.
1158 * @param cbLoggerRC Amount of memory allocated to for the RC logger
1159 * instance clone.
1160 * @param pfnLoggerRCPtr Pointer to logger wrapper function for this
1161 * instance (RC Ptr).
1162 * @param pfnFlushRCPtr Pointer to flush function (RC Ptr).
1163 * @param fFlags Logger instance flags, a combination of the RTLOGFLAGS_* values.
1164 */
1165RTDECL(int) RTLogCloneRC(PRTLOGGER pLogger, PRTLOGGERRC pLoggerRC, size_t cbLoggerRC,
1166 RTRCPTR pfnLoggerRCPtr, RTRCPTR pfnFlushRCPtr, uint32_t fFlags)
1167{
1168 /*
1169 * Validate input.
1170 */
1171 if ( !pLoggerRC
1172 || !pfnFlushRCPtr
1173 || !pfnLoggerRCPtr)
1174 {
1175 AssertMsgFailed(("Invalid parameters!\n"));
1176 return VERR_INVALID_PARAMETER;
1177 }
1178 if (cbLoggerRC < sizeof(*pLoggerRC))
1179 {
1180 AssertMsgFailed(("%d min=%d\n", cbLoggerRC, sizeof(*pLoggerRC)));
1181 return VERR_INVALID_PARAMETER;
1182 }
1183
1184 /*
1185 * Initialize GC instance.
1186 */
1187 pLoggerRC->offScratch = 0;
1188 pLoggerRC->fPendingPrefix = false;
1189 pLoggerRC->pfnLogger = pfnLoggerRCPtr;
1190 pLoggerRC->pfnFlush = pfnFlushRCPtr;
1191 pLoggerRC->u32Magic = RTLOGGERRC_MAGIC;
1192 pLoggerRC->fFlags = fFlags | RTLOGFLAGS_DISABLED;
1193 pLoggerRC->cGroups = 1;
1194 pLoggerRC->afGroups[0] = 0;
1195
1196 /*
1197 * Resolve defaults.
1198 */
1199 if (!pLogger)
1200 {
1201 pLogger = RTLogDefaultInstance();
1202 if (!pLogger)
1203 return VINF_SUCCESS;
1204 }
1205
1206 /*
1207 * Check if there's enough space for the groups.
1208 */
1209 if (cbLoggerRC < (size_t)RT_OFFSETOF(RTLOGGERRC, afGroups[pLogger->cGroups]))
1210 {
1211 AssertMsgFailed(("%d req=%d cGroups=%d\n", cbLoggerRC, RT_OFFSETOF(RTLOGGERRC, afGroups[pLogger->cGroups]), pLogger->cGroups));
1212 return VERR_BUFFER_OVERFLOW;
1213 }
1214 memcpy(&pLoggerRC->afGroups[0], &pLogger->afGroups[0], pLogger->cGroups * sizeof(pLoggerRC->afGroups[0]));
1215 pLoggerRC->cGroups = pLogger->cGroups;
1216
1217 /*
1218 * Copy bits from the HC instance.
1219 */
1220 pLoggerRC->fPendingPrefix = pLogger->pInt->fPendingPrefix;
1221 pLoggerRC->fFlags |= pLogger->fFlags;
1222
1223 /*
1224 * Check if we can remove the disabled flag.
1225 */
1226 if ( pLogger->fDestFlags
1227 && !((pLogger->fFlags | fFlags) & RTLOGFLAGS_DISABLED))
1228 pLoggerRC->fFlags &= ~RTLOGFLAGS_DISABLED;
1229
1230 return VINF_SUCCESS;
1231}
1232RT_EXPORT_SYMBOL(RTLogCloneRC);
1233
1234
1235/**
1236 * Flushes a RC logger instance to a R3 logger.
1237 *
1238 *
1239 * @returns iprt status code.
1240 * @param pLogger The R3 logger instance to flush pLoggerRC to. If NULL
1241 * the default logger is used.
1242 * @param pLoggerRC The RC logger instance to flush.
1243 */
1244RTDECL(void) RTLogFlushRC(PRTLOGGER pLogger, PRTLOGGERRC pLoggerRC)
1245{
1246 /*
1247 * Resolve defaults.
1248 */
1249 if (!pLogger)
1250 {
1251 pLogger = RTLogDefaultInstance();
1252 if (!pLogger)
1253 {
1254 pLoggerRC->offScratch = 0;
1255 return;
1256 }
1257 }
1258
1259 /*
1260 * Any thing to flush?
1261 */
1262 if ( pLogger->offScratch
1263 || pLoggerRC->offScratch)
1264 {
1265 /*
1266 * Acquire logger instance sem.
1267 */
1268 int rc = rtlogLock(pLogger);
1269 if (RT_FAILURE(rc))
1270 return;
1271
1272 /*
1273 * Write whatever the GC instance contains to the HC one, and then
1274 * flush the HC instance.
1275 */
1276 if (pLoggerRC->offScratch)
1277 {
1278 rtLogOutput(pLogger, pLoggerRC->achScratch, pLoggerRC->offScratch);
1279 rtLogOutput(pLogger, NULL, 0);
1280 pLoggerRC->offScratch = 0;
1281 }
1282
1283 /*
1284 * Release the semaphore.
1285 */
1286 rtlogUnlock(pLogger);
1287 }
1288}
1289RT_EXPORT_SYMBOL(RTLogFlushRC);
1290
1291# ifdef IN_RING3
1292
1293RTDECL(int) RTLogCreateForR0(PRTLOGGER pLogger, size_t cbLogger,
1294 RTR0PTR pLoggerR0Ptr, RTR0PTR pfnLoggerR0Ptr, RTR0PTR pfnFlushR0Ptr,
1295 uint32_t fFlags, uint32_t fDestFlags)
1296{
1297 /*
1298 * Validate input.
1299 */
1300 AssertPtrReturn(pLogger, VERR_INVALID_PARAMETER);
1301 size_t const cbRequired = sizeof(*pLogger) + RTLOGGERINTERNAL_R0_SIZE;
1302 AssertReturn(cbLogger >= cbRequired, VERR_BUFFER_OVERFLOW);
1303 AssertReturn(pLoggerR0Ptr != NIL_RTR0PTR, VERR_INVALID_PARAMETER);
1304 AssertReturn(pfnLoggerR0Ptr != NIL_RTR0PTR, VERR_INVALID_PARAMETER);
1305
1306 /*
1307 * Initialize the ring-0 instance.
1308 */
1309 pLogger->achScratch[0] = 0;
1310 pLogger->offScratch = 0;
1311 pLogger->pfnLogger = (PFNRTLOGGER)pfnLoggerR0Ptr;
1312 pLogger->fFlags = fFlags;
1313 pLogger->fDestFlags = fDestFlags & ~RTLOGDEST_FILE;
1314 pLogger->pInt = NULL;
1315 pLogger->cGroups = 1;
1316 pLogger->afGroups[0] = 0;
1317
1318 uint32_t cMaxGroups = (uint32_t)((cbLogger - cbRequired) / sizeof(pLogger->afGroups[0]));
1319 if (fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
1320 cMaxGroups /= 2;
1321 PRTLOGGERINTERNAL pInt;
1322 for (;;)
1323 {
1324 AssertReturn(cMaxGroups > 0, VERR_BUFFER_OVERFLOW);
1325 pInt = (PRTLOGGERINTERNAL)&pLogger->afGroups[cMaxGroups];
1326 if (!((uintptr_t)pInt & (sizeof(uint64_t) - 1)))
1327 break;
1328 cMaxGroups--;
1329 }
1330 pLogger->pInt = (PRTLOGGERINTERNAL)(pLoggerR0Ptr + (uintptr_t)pInt - (uintptr_t)pLogger);
1331 pInt->uRevision = RTLOGGERINTERNAL_REV;
1332 pInt->cbSelf = RTLOGGERINTERNAL_R0_SIZE;
1333 pInt->hSpinMtx = NIL_RTSEMSPINMUTEX; /* Not serialized. */
1334 pInt->pfnFlush = (PFNRTLOGFLUSH)pfnFlushR0Ptr;
1335 pInt->pfnPrefix = NULL;
1336 pInt->pvPrefixUserArg = NULL;
1337 pInt->fPendingPrefix = false;
1338 pInt->cMaxGroups = cMaxGroups;
1339 pInt->papszGroups = NULL;
1340 pInt->cMaxEntriesPerGroup = UINT32_MAX;
1341 if (fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
1342 {
1343 memset(pInt + 1, 0, sizeof(uint32_t) * cMaxGroups);
1344 pInt->pacEntriesPerGroup= (uint32_t *)(pLogger->pInt + 1);
1345 }
1346 else
1347 pInt->pacEntriesPerGroup= NULL;
1348
1349 pInt->fCreated = true;
1350 pLogger->u32Magic = RTLOGGER_MAGIC;
1351 return VINF_SUCCESS;
1352}
1353RT_EXPORT_SYMBOL(RTLogCreateForR0);
1354
1355
1356RTDECL(size_t) RTLogCalcSizeForR0(uint32_t cGroups, uint32_t fFlags)
1357{
1358 size_t cb = RT_OFFSETOF(RTLOGGER, afGroups[cGroups]);
1359 cb = RT_ALIGN_Z(cb, sizeof(uint64_t));
1360 cb += sizeof(RTLOGGERINTERNAL);
1361 if (fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
1362 cb += sizeof(uint32_t) * cGroups;
1363 return cb;
1364}
1365RT_EXPORT_SYMBOL(RTLogCalcSizeForR0);
1366
1367
1368RTDECL(int) RTLogCopyGroupsAndFlagsForR0(PRTLOGGER pDstLogger, RTR0PTR pDstLoggerR0Ptr,
1369 PCRTLOGGER pSrcLogger, uint32_t fFlagsOr, uint32_t fFlagsAnd)
1370{
1371 /*
1372 * Validate input.
1373 */
1374 AssertPtrReturn(pDstLogger, VERR_INVALID_PARAMETER);
1375 AssertPtrNullReturn(pSrcLogger, VERR_INVALID_PARAMETER);
1376
1377 /*
1378 * Resolve defaults.
1379 */
1380 if (!pSrcLogger)
1381 {
1382 pSrcLogger = RTLogDefaultInstance();
1383 if (!pSrcLogger)
1384 {
1385 pDstLogger->fFlags |= RTLOGFLAGS_DISABLED | fFlagsOr;
1386 pDstLogger->cGroups = 1;
1387 pDstLogger->afGroups[0] = 0;
1388 return VINF_SUCCESS;
1389 }
1390 }
1391
1392 /*
1393 * Copy flags and group settings.
1394 */
1395 pDstLogger->fFlags = (pSrcLogger->fFlags & fFlagsAnd & ~RTLOGFLAGS_RESTRICT_GROUPS) | fFlagsOr;
1396
1397 PRTLOGGERINTERNAL pDstInt = (PRTLOGGERINTERNAL)((uintptr_t)pDstLogger->pInt - pDstLoggerR0Ptr + (uintptr_t)pDstLogger);
1398 int rc = VINF_SUCCESS;
1399 uint32_t cGroups = pSrcLogger->cGroups;
1400 if (cGroups > pDstInt->cMaxGroups)
1401 {
1402 AssertMsgFailed(("cMaxGroups=%zd cGroups=%zd (min size %d)\n", pDstInt->cMaxGroups,
1403 pSrcLogger->cGroups, RT_OFFSETOF(RTLOGGER, afGroups[pSrcLogger->cGroups]) + RTLOGGERINTERNAL_R0_SIZE));
1404 rc = VERR_INVALID_PARAMETER;
1405 cGroups = pDstInt->cMaxGroups;
1406 }
1407 memcpy(&pDstLogger->afGroups[0], &pSrcLogger->afGroups[0], cGroups * sizeof(pDstLogger->afGroups[0]));
1408 pDstLogger->cGroups = cGroups;
1409
1410 return rc;
1411}
1412RT_EXPORT_SYMBOL(RTLogCopyGroupsAndFlagsForR0);
1413
1414
1415RTDECL(int) RTLogSetCustomPrefixCallbackForR0(PRTLOGGER pLogger, RTR0PTR pLoggerR0Ptr,
1416 RTR0PTR pfnCallbackR0Ptr, RTR0PTR pvUserR0Ptr)
1417{
1418 AssertPtrReturn(pLogger, VERR_INVALID_POINTER);
1419 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
1420
1421 /*
1422 * Do the work.
1423 */
1424 PRTLOGGERINTERNAL pInt = (PRTLOGGERINTERNAL)((uintptr_t)pLogger->pInt - pLoggerR0Ptr + (uintptr_t)pLogger);
1425 AssertReturn(pInt->uRevision == RTLOGGERINTERNAL_REV, VERR_LOG_REVISION_MISMATCH);
1426 pInt->pvPrefixUserArg = (void *)pvUserR0Ptr;
1427 pInt->pfnPrefix = (PFNRTLOGPREFIX)pfnCallbackR0Ptr;
1428
1429 return VINF_SUCCESS;
1430}
1431RT_EXPORT_SYMBOL(RTLogSetCustomPrefixCallbackForR0);
1432
1433RTDECL(void) RTLogFlushR0(PRTLOGGER pLogger, PRTLOGGER pLoggerR0)
1434{
1435 /*
1436 * Resolve defaults.
1437 */
1438 if (!pLogger)
1439 {
1440 pLogger = RTLogDefaultInstance();
1441 if (!pLogger)
1442 {
1443 /* flushing to "/dev/null". */
1444 if (pLoggerR0->offScratch)
1445 pLoggerR0->offScratch = 0;
1446 return;
1447 }
1448 }
1449
1450 /*
1451 * Anything to flush?
1452 */
1453 if ( pLoggerR0->offScratch
1454 || pLogger->offScratch)
1455 {
1456 /*
1457 * Acquire logger semaphores.
1458 */
1459 int rc = rtlogLock(pLogger);
1460 if (RT_FAILURE(rc))
1461 return;
1462 if (RT_SUCCESS(rc))
1463 {
1464 /*
1465 * Write whatever the GC instance contains to the HC one, and then
1466 * flush the HC instance.
1467 */
1468 if (pLoggerR0->offScratch)
1469 {
1470 rtLogOutput(pLogger, pLoggerR0->achScratch, pLoggerR0->offScratch);
1471 rtLogOutput(pLogger, NULL, 0);
1472 pLoggerR0->offScratch = 0;
1473 }
1474 }
1475 rtlogUnlock(pLogger);
1476 }
1477}
1478RT_EXPORT_SYMBOL(RTLogFlushR0);
1479
1480# endif /* IN_RING3 */
1481
1482
1483/**
1484 * Flushes the buffer in one logger instance onto another logger.
1485 *
1486 * @returns iprt status code.
1487 *
1488 * @param pSrcLogger The logger instance to flush.
1489 * @param pDstLogger The logger instance to flush onto.
1490 * If NULL the default logger will be used.
1491 */
1492RTDECL(void) RTLogFlushToLogger(PRTLOGGER pSrcLogger, PRTLOGGER pDstLogger)
1493{
1494 /*
1495 * Resolve defaults.
1496 */
1497 if (!pDstLogger)
1498 {
1499 pDstLogger = RTLogDefaultInstance();
1500 if (!pDstLogger)
1501 {
1502 /* flushing to "/dev/null". */
1503 if (pSrcLogger->offScratch)
1504 {
1505 int rc = rtlogLock(pSrcLogger);
1506 if (RT_SUCCESS(rc))
1507 {
1508 pSrcLogger->offScratch = 0;
1509 rtlogUnlock(pSrcLogger);
1510 }
1511 }
1512 return;
1513 }
1514 }
1515
1516 /*
1517 * Any thing to flush?
1518 */
1519 if ( pSrcLogger->offScratch
1520 || pDstLogger->offScratch)
1521 {
1522 /*
1523 * Acquire logger semaphores.
1524 */
1525 int rc = rtlogLock(pDstLogger);
1526 if (RT_FAILURE(rc))
1527 return;
1528 rc = rtlogLock(pSrcLogger);
1529 if (RT_SUCCESS(rc))
1530 {
1531 /*
1532 * Write whatever the GC instance contains to the HC one, and then
1533 * flush the HC instance.
1534 */
1535 if (pSrcLogger->offScratch)
1536 {
1537 rtLogOutput(pDstLogger, pSrcLogger->achScratch, pSrcLogger->offScratch);
1538 rtLogOutput(pDstLogger, NULL, 0);
1539 pSrcLogger->offScratch = 0;
1540 }
1541
1542 /*
1543 * Release the semaphores.
1544 */
1545 rtlogUnlock(pSrcLogger);
1546 }
1547 rtlogUnlock(pDstLogger);
1548 }
1549}
1550RT_EXPORT_SYMBOL(RTLogFlushToLogger);
1551
1552
1553/**
1554 * Sets the custom prefix callback.
1555 *
1556 * @returns IPRT status code.
1557 * @param pLogger The logger instance.
1558 * @param pfnCallback The callback.
1559 * @param pvUser The user argument for the callback.
1560 * */
1561RTDECL(int) RTLogSetCustomPrefixCallback(PRTLOGGER pLogger, PFNRTLOGPREFIX pfnCallback, void *pvUser)
1562{
1563 /*
1564 * Resolve defaults.
1565 */
1566 if (!pLogger)
1567 {
1568 pLogger = RTLogDefaultInstance();
1569 if (!pLogger)
1570 return VINF_SUCCESS;
1571 }
1572 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
1573
1574 /*
1575 * Do the work.
1576 */
1577 rtlogLock(pLogger);
1578 pLogger->pInt->pvPrefixUserArg = pvUser;
1579 pLogger->pInt->pfnPrefix = pfnCallback;
1580 rtlogUnlock(pLogger);
1581
1582 return VINF_SUCCESS;
1583}
1584RT_EXPORT_SYMBOL(RTLogSetCustomPrefixCallback);
1585
1586
1587/**
1588 * Matches a group name with a pattern mask in an case insensitive manner (ASCII).
1589 *
1590 * @returns true if matching and *ppachMask set to the end of the pattern.
1591 * @returns false if no match.
1592 * @param pszGrp The group name.
1593 * @param ppachMask Pointer to the pointer to the mask. Only wildcard supported is '*'.
1594 * @param cchMask The length of the mask, including modifiers. The modifiers is why
1595 * we update *ppachMask on match.
1596 */
1597static bool rtlogIsGroupMatching(const char *pszGrp, const char **ppachMask, size_t cchMask)
1598{
1599 const char *pachMask;
1600
1601 if (!pszGrp || !*pszGrp)
1602 return false;
1603 pachMask = *ppachMask;
1604 for (;;)
1605 {
1606 if (RT_C_TO_LOWER(*pszGrp) != RT_C_TO_LOWER(*pachMask))
1607 {
1608 const char *pszTmp;
1609
1610 /*
1611 * Check for wildcard and do a minimal match if found.
1612 */
1613 if (*pachMask != '*')
1614 return false;
1615
1616 /* eat '*'s. */
1617 do pachMask++;
1618 while (--cchMask && *pachMask == '*');
1619
1620 /* is there more to match? */
1621 if ( !cchMask
1622 || *pachMask == '.'
1623 || *pachMask == '=')
1624 break; /* we're good */
1625
1626 /* do extremely minimal matching (fixme) */
1627 pszTmp = strchr(pszGrp, RT_C_TO_LOWER(*pachMask));
1628 if (!pszTmp)
1629 pszTmp = strchr(pszGrp, RT_C_TO_UPPER(*pachMask));
1630 if (!pszTmp)
1631 return false;
1632 pszGrp = pszTmp;
1633 continue;
1634 }
1635
1636 /* done? */
1637 if (!*++pszGrp)
1638 {
1639 /* trailing wildcard is ok. */
1640 do
1641 {
1642 pachMask++;
1643 cchMask--;
1644 } while (cchMask && *pachMask == '*');
1645 if ( !cchMask
1646 || *pachMask == '.'
1647 || *pachMask == '=')
1648 break; /* we're good */
1649 return false;
1650 }
1651
1652 if (!--cchMask)
1653 return false;
1654 pachMask++;
1655 }
1656
1657 /* match */
1658 *ppachMask = pachMask;
1659 return true;
1660}
1661
1662
1663/**
1664 * Updates the group settings for the logger instance using the specified
1665 * specification string.
1666 *
1667 * @returns iprt status code.
1668 * Failures can safely be ignored.
1669 * @param pLogger Logger instance.
1670 * @param pszValue Value to parse.
1671 */
1672RTDECL(int) RTLogGroupSettings(PRTLOGGER pLogger, const char *pszValue)
1673{
1674 /*
1675 * Resolve defaults.
1676 */
1677 if (!pLogger)
1678 {
1679 pLogger = RTLogDefaultInstance();
1680 if (!pLogger)
1681 return VINF_SUCCESS;
1682 }
1683
1684 /*
1685 * Iterate the string.
1686 */
1687 while (*pszValue)
1688 {
1689 /*
1690 * Skip prefixes (blanks, ;, + and -).
1691 */
1692 bool fEnabled = true;
1693 char ch;
1694 const char *pszStart;
1695 unsigned i;
1696 size_t cch;
1697
1698 while ((ch = *pszValue) == '+' || ch == '-' || ch == ' ' || ch == '\t' || ch == '\n' || ch == ';')
1699 {
1700 if (ch == '+' || ch == '-' || ch == ';')
1701 fEnabled = ch != '-';
1702 pszValue++;
1703 }
1704 if (!*pszValue)
1705 break;
1706
1707 /*
1708 * Find end.
1709 */
1710 pszStart = pszValue;
1711 while ((ch = *pszValue) != '\0' && ch != '+' && ch != '-' && ch != ' ' && ch != '\t')
1712 pszValue++;
1713
1714 /*
1715 * Find the group (ascii case insensitive search).
1716 * Special group 'all'.
1717 */
1718 cch = pszValue - pszStart;
1719 if ( cch >= 3
1720 && (pszStart[0] == 'a' || pszStart[0] == 'A')
1721 && (pszStart[1] == 'l' || pszStart[1] == 'L')
1722 && (pszStart[2] == 'l' || pszStart[2] == 'L')
1723 && (cch == 3 || pszStart[3] == '.' || pszStart[3] == '='))
1724 {
1725 /*
1726 * All.
1727 */
1728 unsigned fFlags = cch == 3
1729 ? RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1
1730 : rtlogGroupFlags(&pszStart[3]);
1731 for (i = 0; i < pLogger->cGroups; i++)
1732 {
1733 if (fEnabled)
1734 pLogger->afGroups[i] |= fFlags;
1735 else
1736 pLogger->afGroups[i] &= ~fFlags;
1737 }
1738 }
1739 else
1740 {
1741 /*
1742 * Specific group(s).
1743 */
1744 for (i = 0; i < pLogger->cGroups; i++)
1745 {
1746 const char *psz2 = (const char*)pszStart;
1747 if (rtlogIsGroupMatching(pLogger->pInt->papszGroups[i], &psz2, cch))
1748 {
1749 unsigned fFlags = RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1;
1750 if (*psz2 == '.' || *psz2 == '=')
1751 fFlags = rtlogGroupFlags(psz2);
1752 if (fEnabled)
1753 pLogger->afGroups[i] |= fFlags;
1754 else
1755 pLogger->afGroups[i] &= ~fFlags;
1756 }
1757 } /* for each group */
1758 }
1759
1760 } /* parse specification */
1761
1762 return VINF_SUCCESS;
1763}
1764RT_EXPORT_SYMBOL(RTLogGroupSettings);
1765
1766
1767/**
1768 * Interprets the group flags suffix.
1769 *
1770 * @returns Flags specified. (0 is possible!)
1771 * @param psz Start of Suffix. (Either dot or equal sign.)
1772 */
1773static unsigned rtlogGroupFlags(const char *psz)
1774{
1775 unsigned fFlags = 0;
1776
1777 /*
1778 * Literal flags.
1779 */
1780 while (*psz == '.')
1781 {
1782 static struct
1783 {
1784 const char *pszFlag; /* lowercase!! */
1785 unsigned fFlag;
1786 } aFlags[] =
1787 {
1788 { "eo", RTLOGGRPFLAGS_ENABLED },
1789 { "enabledonly",RTLOGGRPFLAGS_ENABLED },
1790 { "e", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_WARN },
1791 { "enabled", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_WARN },
1792 { "l1", RTLOGGRPFLAGS_LEVEL_1 },
1793 { "level1", RTLOGGRPFLAGS_LEVEL_1 },
1794 { "l", RTLOGGRPFLAGS_LEVEL_2 },
1795 { "l2", RTLOGGRPFLAGS_LEVEL_2 },
1796 { "level2", RTLOGGRPFLAGS_LEVEL_2 },
1797 { "l3", RTLOGGRPFLAGS_LEVEL_3 },
1798 { "level3", RTLOGGRPFLAGS_LEVEL_3 },
1799 { "l4", RTLOGGRPFLAGS_LEVEL_4 },
1800 { "level4", RTLOGGRPFLAGS_LEVEL_4 },
1801 { "l5", RTLOGGRPFLAGS_LEVEL_5 },
1802 { "level5", RTLOGGRPFLAGS_LEVEL_5 },
1803 { "l6", RTLOGGRPFLAGS_LEVEL_6 },
1804 { "level6", RTLOGGRPFLAGS_LEVEL_6 },
1805 { "l7", RTLOGGRPFLAGS_LEVEL_7 },
1806 { "level7", RTLOGGRPFLAGS_LEVEL_7 },
1807 { "l8", RTLOGGRPFLAGS_LEVEL_8 },
1808 { "level8", RTLOGGRPFLAGS_LEVEL_8 },
1809 { "l9", RTLOGGRPFLAGS_LEVEL_9 },
1810 { "level9", RTLOGGRPFLAGS_LEVEL_9 },
1811 { "l10", RTLOGGRPFLAGS_LEVEL_10 },
1812 { "level10", RTLOGGRPFLAGS_LEVEL_10 },
1813 { "l11", RTLOGGRPFLAGS_LEVEL_11 },
1814 { "level11", RTLOGGRPFLAGS_LEVEL_11 },
1815 { "l12", RTLOGGRPFLAGS_LEVEL_12 },
1816 { "level12", RTLOGGRPFLAGS_LEVEL_12 },
1817 { "f", RTLOGGRPFLAGS_FLOW },
1818 { "flow", RTLOGGRPFLAGS_FLOW },
1819 { "w", RTLOGGRPFLAGS_WARN },
1820 { "warn", RTLOGGRPFLAGS_WARN },
1821 { "warning", RTLOGGRPFLAGS_WARN },
1822 { "restrict", RTLOGGRPFLAGS_RESTRICT },
1823
1824 };
1825 unsigned i;
1826 bool fFound = false;
1827 psz++;
1828 for (i = 0; i < RT_ELEMENTS(aFlags) && !fFound; i++)
1829 {
1830 const char *psz1 = aFlags[i].pszFlag;
1831 const char *psz2 = psz;
1832 while (*psz1 == RT_C_TO_LOWER(*psz2))
1833 {
1834 psz1++;
1835 psz2++;
1836 if (!*psz1)
1837 {
1838 if ( (*psz2 >= 'a' && *psz2 <= 'z')
1839 || (*psz2 >= 'A' && *psz2 <= 'Z')
1840 || (*psz2 >= '0' && *psz2 <= '9') )
1841 break;
1842 fFlags |= aFlags[i].fFlag;
1843 fFound = true;
1844 psz = psz2;
1845 break;
1846 }
1847 } /* strincmp */
1848 } /* for each flags */
1849 AssertMsg(fFound, ("%.15s...", psz));
1850 }
1851
1852 /*
1853 * Flag value.
1854 */
1855 if (*psz == '=')
1856 {
1857 psz++;
1858 if (*psz == '~')
1859 fFlags = ~RTStrToInt32(psz + 1);
1860 else
1861 fFlags = RTStrToInt32(psz);
1862 }
1863
1864 return fFlags;
1865}
1866
1867/**
1868 * Helper for RTLogGetGroupSettings.
1869 */
1870static int rtLogGetGroupSettingsAddOne(const char *pszName, uint32_t fGroup, char **ppszBuf, size_t *pcchBuf, bool *pfNotFirst)
1871{
1872# define APPEND_PSZ(psz,cch) do { memcpy(*ppszBuf, (psz), (cch)); *ppszBuf += (cch); *pcchBuf -= (cch); } while (0)
1873# define APPEND_SZ(sz) APPEND_PSZ(sz, sizeof(sz) - 1)
1874# define APPEND_CH(ch) do { **ppszBuf = (ch); *ppszBuf += 1; *pcchBuf -= 1; } while (0)
1875
1876 /*
1877 * Add the name.
1878 */
1879 size_t cchName = strlen(pszName);
1880 if (cchName + 1 + *pfNotFirst > *pcchBuf)
1881 return VERR_BUFFER_OVERFLOW;
1882 if (*pfNotFirst)
1883 APPEND_CH(' ');
1884 else
1885 *pfNotFirst = true;
1886 APPEND_PSZ(pszName, cchName);
1887
1888 /*
1889 * Only generate mnemonics for the simple+common bits.
1890 */
1891 if (fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1))
1892 /* nothing */;
1893 else if ( fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_LEVEL_2 | RTLOGGRPFLAGS_FLOW)
1894 && *pcchBuf >= sizeof(".e.l.f"))
1895 APPEND_SZ(".e.l.f");
1896 else if ( fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_FLOW)
1897 && *pcchBuf >= sizeof(".e.f"))
1898 APPEND_SZ(".e.f");
1899 else if (*pcchBuf >= 1 + 10 + 1)
1900 {
1901 size_t cch;
1902 APPEND_CH('=');
1903 cch = RTStrFormatNumber(*ppszBuf, fGroup, 16, 0, 0, RTSTR_F_SPECIAL | RTSTR_F_32BIT);
1904 *ppszBuf += cch;
1905 *pcchBuf -= cch;
1906 }
1907 else
1908 return VERR_BUFFER_OVERFLOW;
1909
1910# undef APPEND_PSZ
1911# undef APPEND_SZ
1912# undef APPEND_CH
1913 return VINF_SUCCESS;
1914}
1915
1916
1917/**
1918 * Get the current log group settings as a string.
1919 *
1920 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
1921 * @param pLogger Logger instance (NULL for default logger).
1922 * @param pszBuf The output buffer.
1923 * @param cchBuf The size of the output buffer. Must be greater
1924 * than zero.
1925 */
1926RTDECL(int) RTLogGetGroupSettings(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
1927{
1928 bool fNotFirst = false;
1929 int rc = VINF_SUCCESS;
1930 uint32_t cGroups;
1931 uint32_t fGroup;
1932 uint32_t i;
1933
1934 Assert(cchBuf);
1935
1936 /*
1937 * Resolve defaults.
1938 */
1939 if (!pLogger)
1940 {
1941 pLogger = RTLogDefaultInstance();
1942 if (!pLogger)
1943 {
1944 *pszBuf = '\0';
1945 return VINF_SUCCESS;
1946 }
1947 }
1948
1949 cGroups = pLogger->cGroups;
1950
1951 /*
1952 * Check if all are the same.
1953 */
1954 fGroup = pLogger->afGroups[0];
1955 for (i = 1; i < cGroups; i++)
1956 if (pLogger->afGroups[i] != fGroup)
1957 break;
1958 if (i >= cGroups)
1959 rc = rtLogGetGroupSettingsAddOne("all", fGroup, &pszBuf, &cchBuf, &fNotFirst);
1960 else
1961 {
1962
1963 /*
1964 * Iterate all the groups and print all that are enabled.
1965 */
1966 for (i = 0; i < cGroups; i++)
1967 {
1968 fGroup = pLogger->afGroups[i];
1969 if (fGroup)
1970 {
1971 const char *pszName = pLogger->pInt->papszGroups[i];
1972 if (pszName)
1973 {
1974 rc = rtLogGetGroupSettingsAddOne(pszName, fGroup, &pszBuf, &cchBuf, &fNotFirst);
1975 if (rc)
1976 break;
1977 }
1978 }
1979 }
1980 }
1981
1982 *pszBuf = '\0';
1983 return rc;
1984}
1985RT_EXPORT_SYMBOL(RTLogGetGroupSettings);
1986
1987#endif /* !IN_RC */
1988
1989/**
1990 * Updates the flags for the logger instance using the specified
1991 * specification string.
1992 *
1993 * @returns iprt status code.
1994 * Failures can safely be ignored.
1995 * @param pLogger Logger instance (NULL for default logger).
1996 * @param pszValue Value to parse.
1997 */
1998RTDECL(int) RTLogFlags(PRTLOGGER pLogger, const char *pszValue)
1999{
2000 int rc = VINF_SUCCESS;
2001
2002 /*
2003 * Resolve defaults.
2004 */
2005 if (!pLogger)
2006 {
2007 pLogger = RTLogDefaultInstance();
2008 if (!pLogger)
2009 return VINF_SUCCESS;
2010 }
2011
2012 /*
2013 * Iterate the string.
2014 */
2015 while (*pszValue)
2016 {
2017 /* check no prefix. */
2018 bool fNo = false;
2019 char ch;
2020 unsigned i;
2021
2022 /* skip blanks. */
2023 while (RT_C_IS_SPACE(*pszValue))
2024 pszValue++;
2025 if (!*pszValue)
2026 return rc;
2027
2028 while ((ch = *pszValue) != '\0')
2029 {
2030 if (ch == 'n' && pszValue[1] == 'o')
2031 {
2032 pszValue += 2;
2033 fNo = !fNo;
2034 }
2035 else if (ch == '+')
2036 {
2037 pszValue++;
2038 fNo = true;
2039 }
2040 else if (ch == '-' || ch == '!' || ch == '~')
2041 {
2042 pszValue++;
2043 fNo = !fNo;
2044 }
2045 else
2046 break;
2047 }
2048
2049 /* instruction. */
2050 for (i = 0; i < RT_ELEMENTS(g_aLogFlags); i++)
2051 {
2052 if (!strncmp(pszValue, g_aLogFlags[i].pszInstr, g_aLogFlags[i].cchInstr))
2053 {
2054 if (fNo == g_aLogFlags[i].fInverted)
2055 pLogger->fFlags |= g_aLogFlags[i].fFlag;
2056 else
2057 pLogger->fFlags &= ~g_aLogFlags[i].fFlag;
2058 pszValue += g_aLogFlags[i].cchInstr;
2059 break;
2060 }
2061 }
2062
2063 /* unknown instruction? */
2064 if (i >= RT_ELEMENTS(g_aLogFlags))
2065 {
2066 AssertMsgFailed(("Invalid flags! unknown instruction %.20s\n", pszValue));
2067 pszValue++;
2068 }
2069
2070 /* skip blanks and delimiters. */
2071 while (RT_C_IS_SPACE(*pszValue) || *pszValue == ';')
2072 pszValue++;
2073 } /* while more environment variable value left */
2074
2075 return rc;
2076}
2077RT_EXPORT_SYMBOL(RTLogFlags);
2078
2079
2080/**
2081 * Changes the buffering setting of the specified logger.
2082 *
2083 * This can be used for optimizing longish logging sequences.
2084 *
2085 * @returns The old state.
2086 * @param pLogger The logger instance (NULL is an alias for the
2087 * default logger).
2088 * @param fBuffered The new state.
2089 */
2090RTDECL(bool) RTLogSetBuffering(PRTLOGGER pLogger, bool fBuffered)
2091{
2092 bool fOld;
2093
2094 /*
2095 * Resolve the logger instance.
2096 */
2097 if (!pLogger)
2098 {
2099 pLogger = RTLogDefaultInstance();
2100 if (!pLogger)
2101 return false;
2102 }
2103
2104 rtlogLock(pLogger);
2105 fOld = !!(pLogger->fFlags & RTLOGFLAGS_BUFFERED);
2106 if (fBuffered)
2107 pLogger->fFlags |= RTLOGFLAGS_BUFFERED;
2108 else
2109 pLogger->fFlags &= ~RTLOGFLAGS_BUFFERED;
2110 rtlogUnlock(pLogger);
2111
2112 return fOld;
2113}
2114RT_EXPORT_SYMBOL(RTLogSetBuffering);
2115
2116
2117#ifdef IN_RING3
2118RTDECL(uint32_t) RTLogSetGroupLimit(PRTLOGGER pLogger, uint32_t cMaxEntriesPerGroup)
2119{
2120 /*
2121 * Resolve the logger instance.
2122 */
2123 if (!pLogger)
2124 {
2125 pLogger = RTLogDefaultInstance();
2126 if (!pLogger)
2127 return UINT32_MAX;
2128 }
2129
2130 rtlogLock(pLogger);
2131 uint32_t cOld = pLogger->pInt->cMaxEntriesPerGroup;
2132 pLogger->pInt->cMaxEntriesPerGroup = cMaxEntriesPerGroup;
2133 rtlogUnlock(pLogger);
2134
2135 return cOld;
2136}
2137#endif
2138
2139#ifndef IN_RC
2140
2141/**
2142 * Get the current log flags as a string.
2143 *
2144 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
2145 * @param pLogger Logger instance (NULL for default logger).
2146 * @param pszBuf The output buffer.
2147 * @param cchBuf The size of the output buffer. Must be greater
2148 * than zero.
2149 */
2150RTDECL(int) RTLogGetFlags(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
2151{
2152 bool fNotFirst = false;
2153 int rc = VINF_SUCCESS;
2154 uint32_t fFlags;
2155 unsigned i;
2156
2157 Assert(cchBuf);
2158
2159 /*
2160 * Resolve defaults.
2161 */
2162 if (!pLogger)
2163 {
2164 pLogger = RTLogDefaultInstance();
2165 if (!pLogger)
2166 {
2167 *pszBuf = '\0';
2168 return VINF_SUCCESS;
2169 }
2170 }
2171
2172 /*
2173 * Add the flags in the list.
2174 */
2175 fFlags = pLogger->fFlags;
2176 for (i = 0; i < RT_ELEMENTS(g_aLogFlags); i++)
2177 if ( !g_aLogFlags[i].fInverted
2178 ? (g_aLogFlags[i].fFlag & fFlags)
2179 : !(g_aLogFlags[i].fFlag & fFlags))
2180 {
2181 size_t cchInstr = g_aLogFlags[i].cchInstr;
2182 if (cchInstr + fNotFirst + 1 > cchBuf)
2183 {
2184 rc = VERR_BUFFER_OVERFLOW;
2185 break;
2186 }
2187 if (fNotFirst)
2188 {
2189 *pszBuf++ = ' ';
2190 cchBuf--;
2191 }
2192 memcpy(pszBuf, g_aLogFlags[i].pszInstr, cchInstr);
2193 pszBuf += cchInstr;
2194 cchBuf -= cchInstr;
2195 fNotFirst = true;
2196 }
2197 *pszBuf = '\0';
2198 return rc;
2199}
2200RT_EXPORT_SYMBOL(RTLogGetFlags);
2201
2202
2203/**
2204 * Finds the end of a destination value.
2205 *
2206 * The value ends when we counter a ';' or a free standing word (space on both
2207 * from the g_aLogDst table. (If this is problematic for someone, we could
2208 * always do quoting and escaping.)
2209 *
2210 * @returns Value length in chars.
2211 * @param pszValue The first char after '=' or ':'.
2212 */
2213static size_t rtLogDestFindValueLength(const char *pszValue)
2214{
2215 size_t off = 0;
2216 char ch;
2217 while ((ch = pszValue[off]) != '\0' && ch != ';')
2218 {
2219 if (!RT_C_IS_SPACE(ch))
2220 off++;
2221 else
2222 {
2223 unsigned i;
2224 size_t cchThusFar = off;
2225 do
2226 off++;
2227 while ((ch = pszValue[off]) != '\0' && RT_C_IS_SPACE(ch));
2228 if (ch == ';')
2229 return cchThusFar;
2230
2231 if (ch == 'n' && pszValue[off + 1] == 'o')
2232 off += 2;
2233 for (i = 0; i < RT_ELEMENTS(g_aLogDst); i++)
2234 if (!strncmp(&pszValue[off], g_aLogDst[i].pszInstr, g_aLogDst[i].cchInstr))
2235 {
2236 ch = pszValue[off + g_aLogDst[i].cchInstr];
2237 if (ch == '\0' || RT_C_IS_SPACE(ch) || ch == '=' || ch == ':' || ch == ';')
2238 return cchThusFar;
2239 }
2240 }
2241 }
2242 return off;
2243}
2244
2245
2246/**
2247 * Updates the logger destination using the specified string.
2248 *
2249 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
2250 * @param pLogger Logger instance (NULL for default logger).
2251 * @param pszValue The value to parse.
2252 */
2253RTDECL(int) RTLogDestinations(PRTLOGGER pLogger, char const *pszValue)
2254{
2255 /*
2256 * Resolve defaults.
2257 */
2258 if (!pLogger)
2259 {
2260 pLogger = RTLogDefaultInstance();
2261 if (!pLogger)
2262 return VINF_SUCCESS;
2263 }
2264
2265 /*
2266 * Do the parsing.
2267 */
2268 while (*pszValue)
2269 {
2270 bool fNo;
2271 unsigned i;
2272
2273 /* skip blanks. */
2274 while (RT_C_IS_SPACE(*pszValue))
2275 pszValue++;
2276 if (!*pszValue)
2277 break;
2278
2279 /* check no prefix. */
2280 fNo = false;
2281 if (pszValue[0] == 'n' && pszValue[1] == 'o')
2282 {
2283 fNo = true;
2284 pszValue += 2;
2285 }
2286
2287 /* instruction. */
2288 for (i = 0; i < RT_ELEMENTS(g_aLogDst); i++)
2289 {
2290 size_t cchInstr = strlen(g_aLogDst[i].pszInstr);
2291 if (!strncmp(pszValue, g_aLogDst[i].pszInstr, cchInstr))
2292 {
2293 if (!fNo)
2294 pLogger->fDestFlags |= g_aLogDst[i].fFlag;
2295 else
2296 pLogger->fDestFlags &= ~g_aLogDst[i].fFlag;
2297 pszValue += cchInstr;
2298
2299 /* check for value. */
2300 while (RT_C_IS_SPACE(*pszValue))
2301 pszValue++;
2302 if (*pszValue == '=' || *pszValue == ':')
2303 {
2304 pszValue++;
2305 size_t cch = rtLogDestFindValueLength(pszValue);
2306 const char *pszEnd = pszValue + cch;
2307
2308# ifdef IN_RING3
2309 char szTmp[sizeof(pLogger->pInt->szFilename)];
2310# else
2311 char szTmp[32];
2312# endif
2313 if (0)
2314 { /* nothing */ }
2315#ifdef IN_RING3
2316
2317 /* log file name */
2318 else if (i == 0 /* file */ && !fNo)
2319 {
2320 AssertReturn(cch < sizeof(pLogger->pInt->szFilename), VERR_OUT_OF_RANGE);
2321 memcpy(pLogger->pInt->szFilename, pszValue, cch);
2322 pLogger->pInt->szFilename[cch] = '\0';
2323 /** @todo reopen log file if pLogger->pInt->fCreated is true ... */
2324 }
2325 /* log directory */
2326 else if (i == 1 /* dir */ && !fNo)
2327 {
2328 const char *pszFile = RTPathFilename(pLogger->pInt->szFilename);
2329 size_t cchFile = pszFile ? strlen(pszFile) : 0;
2330 AssertReturn(cchFile + cch + 1 < sizeof(pLogger->pInt->szFilename), VERR_OUT_OF_RANGE);
2331 memcpy(szTmp, cchFile ? pszFile : "", cchFile + 1);
2332
2333 memcpy(pLogger->pInt->szFilename, pszValue, cch);
2334 pLogger->pInt->szFilename[cch] = '\0';
2335 RTPathStripTrailingSlash(pLogger->pInt->szFilename);
2336
2337 cch = strlen(pLogger->pInt->szFilename);
2338 pLogger->pInt->szFilename[cch++] = '/';
2339 memcpy(&pLogger->pInt->szFilename[cch], szTmp, cchFile);
2340 pLogger->pInt->szFilename[cch + cchFile] = '\0';
2341 /** @todo reopen log file if pLogger->pInt->fCreated is true ... */
2342 }
2343 else if (i == 2 /* history */)
2344 {
2345 if (!fNo)
2346 {
2347 uint32_t cHistory = 0;
2348 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2349 if (RT_SUCCESS(rc))
2350 rc = RTStrToUInt32Full(szTmp, 0, &cHistory);
2351 AssertMsgReturn(RT_SUCCESS(rc) && cHistory < _1M, ("Invalid history value %s (%Rrc)!\n", szTmp, rc), rc);
2352 pLogger->pInt->cHistory = cHistory;
2353 }
2354 else
2355 pLogger->pInt->cHistory = 0;
2356 }
2357 else if (i == 3 /* histsize */)
2358 {
2359 if (!fNo)
2360 {
2361 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2362 if (RT_SUCCESS(rc))
2363 rc = RTStrToUInt64Full(szTmp, 0, &pLogger->pInt->cbHistoryFileMax);
2364 AssertMsgRCReturn(rc, ("Invalid history file size value %s (%Rrc)!\n", szTmp, rc), rc);
2365 if (pLogger->pInt->cbHistoryFileMax == 0)
2366 pLogger->pInt->cbHistoryFileMax = UINT64_MAX;
2367 }
2368 else
2369 pLogger->pInt->cbHistoryFileMax = UINT64_MAX;
2370 }
2371 else if (i == 4 /* histtime */)
2372 {
2373 if (!fNo)
2374 {
2375 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2376 if (RT_SUCCESS(rc))
2377 rc = RTStrToUInt32Full(szTmp, 0, &pLogger->pInt->cSecsHistoryTimeSlot);
2378 AssertMsgRCReturn(rc, ("Invalid history time slot value %s (%Rrc)!\n", szTmp, rc), rc);
2379 if (pLogger->pInt->cSecsHistoryTimeSlot == 0)
2380 pLogger->pInt->cSecsHistoryTimeSlot = UINT32_MAX;
2381 }
2382 else
2383 pLogger->pInt->cSecsHistoryTimeSlot = UINT32_MAX;
2384 }
2385# endif /* IN_RING3 */
2386 else if (i == 5 /* ringbuf */ && !fNo)
2387 {
2388 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2389 uint32_t cbRingBuf = 0;
2390 if (RT_SUCCESS(rc))
2391 rc = RTStrToUInt32Full(szTmp, 0, &cbRingBuf);
2392 AssertMsgRCReturn(rc, ("Invalid ring buffer size value '%s' (%Rrc)!\n", szTmp, rc), rc);
2393
2394 if (cbRingBuf == 0)
2395 cbRingBuf = RTLOG_RINGBUF_DEFAULT_SIZE;
2396 else if (cbRingBuf < RTLOG_RINGBUF_MIN_SIZE)
2397 cbRingBuf = RTLOG_RINGBUF_MIN_SIZE;
2398 else if (cbRingBuf > RTLOG_RINGBUF_MAX_SIZE)
2399 cbRingBuf = RTLOG_RINGBUF_MAX_SIZE;
2400 else
2401 cbRingBuf = RT_ALIGN_32(cbRingBuf, 64);
2402 rc = rtLogRingBufAdjust(pLogger, cbRingBuf, false /*fForce*/);
2403 if (RT_FAILURE(rc))
2404 return rc;
2405 }
2406 else
2407 AssertMsgFailedReturn(("Invalid destination value! %s%s doesn't take a value!\n",
2408 fNo ? "no" : "", g_aLogDst[i].pszInstr),
2409 VERR_INVALID_PARAMETER);
2410
2411 pszValue = pszEnd + (*pszEnd != '\0');
2412 }
2413 else if (i == 5 /* ringbuf */ && !fNo && !pLogger->pInt->pszRingBuf)
2414 {
2415 int rc = rtLogRingBufAdjust(pLogger, pLogger->pInt->cbRingBuf, false /*fForce*/);
2416 if (RT_FAILURE(rc))
2417 return rc;
2418 }
2419 break;
2420 }
2421 }
2422
2423 /* assert known instruction */
2424 AssertMsgReturn(i < RT_ELEMENTS(g_aLogDst),
2425 ("Invalid destination value! unknown instruction %.20s\n", pszValue),
2426 VERR_INVALID_PARAMETER);
2427
2428 /* skip blanks and delimiters. */
2429 while (RT_C_IS_SPACE(*pszValue) || *pszValue == ';')
2430 pszValue++;
2431 } /* while more environment variable value left */
2432
2433 return VINF_SUCCESS;
2434}
2435RT_EXPORT_SYMBOL(RTLogDestinations);
2436
2437
2438/**
2439 * Get the current log destinations as a string.
2440 *
2441 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
2442 * @param pLogger Logger instance (NULL for default logger).
2443 * @param pszBuf The output buffer.
2444 * @param cchBuf The size of the output buffer. Must be greater
2445 * than 0.
2446 */
2447RTDECL(int) RTLogGetDestinations(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
2448{
2449 bool fNotFirst = false;
2450 int rc = VINF_SUCCESS;
2451 uint32_t fDestFlags;
2452 unsigned i;
2453
2454 AssertReturn(cchBuf, VERR_INVALID_PARAMETER);
2455 *pszBuf = '\0';
2456
2457 /*
2458 * Resolve defaults.
2459 */
2460 if (!pLogger)
2461 {
2462 pLogger = RTLogDefaultInstance();
2463 if (!pLogger)
2464 return VINF_SUCCESS;
2465 }
2466
2467 /*
2468 * Add the flags in the list.
2469 */
2470 fDestFlags = pLogger->fDestFlags;
2471 for (i = 6; i < RT_ELEMENTS(g_aLogDst); i++)
2472 if (g_aLogDst[i].fFlag & fDestFlags)
2473 {
2474 if (fNotFirst)
2475 {
2476 rc = RTStrCopyP(&pszBuf, &cchBuf, " ");
2477 if (RT_FAILURE(rc))
2478 return rc;
2479 }
2480 rc = RTStrCopyP(&pszBuf, &cchBuf, g_aLogDst[i].pszInstr);
2481 if (RT_FAILURE(rc))
2482 return rc;
2483 fNotFirst = true;
2484 }
2485
2486 char szNum[32];
2487
2488# ifdef IN_RING3
2489 /*
2490 * Add the filename.
2491 */
2492 if (fDestFlags & RTLOGDEST_FILE)
2493 {
2494 rc = RTStrCopyP(&pszBuf, &cchBuf, fNotFirst ? " file=" : "file=");
2495 if (RT_FAILURE(rc))
2496 return rc;
2497 rc = RTStrCopyP(&pszBuf, &cchBuf, pLogger->pInt->szFilename);
2498 if (RT_FAILURE(rc))
2499 return rc;
2500 fNotFirst = true;
2501
2502 if (pLogger->pInt->cHistory)
2503 {
2504 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " history=%u" : "history=%u", pLogger->pInt->cHistory);
2505 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2506 if (RT_FAILURE(rc))
2507 return rc;
2508 fNotFirst = true;
2509 }
2510 if (pLogger->pInt->cbHistoryFileMax != UINT64_MAX)
2511 {
2512 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " histsize=%llu" : "histsize=%llu", pLogger->pInt->cbHistoryFileMax);
2513 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2514 if (RT_FAILURE(rc))
2515 return rc;
2516 fNotFirst = true;
2517 }
2518 if (pLogger->pInt->cSecsHistoryTimeSlot != UINT32_MAX)
2519 {
2520 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " histtime=%llu" : "histtime=%llu", pLogger->pInt->cSecsHistoryTimeSlot);
2521 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2522 if (RT_FAILURE(rc))
2523 return rc;
2524 fNotFirst = true;
2525 }
2526 }
2527# endif /* IN_RING3 */
2528
2529 /*
2530 * Add the ring buffer.
2531 */
2532 if (fDestFlags & RTLOGDEST_RINGBUF)
2533 {
2534 if (pLogger->pInt->cbRingBuf == RTLOG_RINGBUF_DEFAULT_SIZE)
2535 rc = RTStrCopyP(&pszBuf, &cchBuf, fNotFirst ? " ringbuf" : "ringbuf");
2536 else
2537 {
2538 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " ringbuf=%#x" : "ringbuf=%#x", pLogger->pInt->cbRingBuf);
2539 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2540 }
2541 if (RT_FAILURE(rc))
2542 return rc;
2543 fNotFirst = true;
2544 }
2545
2546 return VINF_SUCCESS;
2547}
2548RT_EXPORT_SYMBOL(RTLogGetDestinations);
2549
2550#endif /* !IN_RC */
2551
2552/**
2553 * Flushes the specified logger.
2554 *
2555 * @param pLogger The logger instance to flush.
2556 * If NULL the default instance is used. The default instance
2557 * will not be initialized by this call.
2558 */
2559RTDECL(void) RTLogFlush(PRTLOGGER pLogger)
2560{
2561 /*
2562 * Resolve defaults.
2563 */
2564 if (!pLogger)
2565 {
2566#ifdef IN_RC
2567 pLogger = &g_Logger;
2568#else
2569 pLogger = g_pLogger;
2570#endif
2571 if (!pLogger)
2572 return;
2573 }
2574
2575 /*
2576 * Any thing to flush?
2577 */
2578 if ( pLogger->offScratch
2579#ifndef IN_RC
2580 || (pLogger->fDestFlags & RTLOGDEST_RINGBUF)
2581#endif
2582 )
2583 {
2584#ifndef IN_RC
2585 /*
2586 * Acquire logger instance sem.
2587 */
2588 int rc = rtlogLock(pLogger);
2589 if (RT_FAILURE(rc))
2590 return;
2591#endif
2592 /*
2593 * Call worker.
2594 */
2595 rtlogFlush(pLogger);
2596
2597#ifndef IN_RC
2598 /*
2599 * Since this is an explicit flush call, the ring buffer content should
2600 * be flushed to the other destinations if active.
2601 */
2602 if ( (pLogger->fDestFlags & RTLOGDEST_RINGBUF)
2603 && pLogger->pInt->pszRingBuf /* paranoia */)
2604 rtLogRingBufFlush(pLogger);
2605
2606 /*
2607 * Release the semaphore.
2608 */
2609 rtlogUnlock(pLogger);
2610#endif
2611 }
2612}
2613RT_EXPORT_SYMBOL(RTLogFlush);
2614
2615
2616/**
2617 * Common worker for RTLogDefaultInstance and RTLogDefaultInstanceEx.
2618 */
2619DECL_FORCE_INLINE(PRTLOGGER) rtLogDefaultInstanceCommon(void)
2620{
2621#ifdef IN_RC
2622 return &g_Logger;
2623
2624#else /* !IN_RC */
2625# ifdef IN_RING0
2626 /*
2627 * Check per thread loggers first.
2628 */
2629 if (g_cPerThreadLoggers)
2630 {
2631 const RTNATIVETHREAD Self = RTThreadNativeSelf();
2632 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
2633 while (i-- > 0)
2634 if (g_aPerThreadLoggers[i].NativeThread == Self)
2635 return g_aPerThreadLoggers[i].pLogger;
2636 }
2637# endif /* IN_RING0 */
2638
2639 /*
2640 * If no per thread logger, use the default one.
2641 */
2642 if (!g_pLogger)
2643 g_pLogger = RTLogDefaultInit();
2644 return g_pLogger;
2645#endif /* !IN_RC */
2646}
2647
2648
2649RTDECL(PRTLOGGER) RTLogDefaultInstance(void)
2650{
2651 return rtLogDefaultInstanceCommon();
2652}
2653RT_EXPORT_SYMBOL(RTLogDefaultInstance);
2654
2655
2656RTDECL(PRTLOGGER) RTLogDefaultInstanceEx(uint32_t fFlagsAndGroup)
2657{
2658 PRTLOGGER pLogger = rtLogDefaultInstanceCommon();
2659 if (pLogger)
2660 {
2661 if (pLogger->fFlags & RTLOGFLAGS_DISABLED)
2662 pLogger = NULL;
2663 else
2664 {
2665 uint16_t const fFlags = RT_LO_U16(fFlagsAndGroup);
2666 uint16_t const iGroup = RT_HI_U16(fFlagsAndGroup);
2667 if ( iGroup != UINT16_MAX
2668 && ( (pLogger->afGroups[iGroup < pLogger->cGroups ? iGroup : 0] & (fFlags | (uint32_t)RTLOGGRPFLAGS_ENABLED))
2669 != (fFlags | (uint32_t)RTLOGGRPFLAGS_ENABLED)))
2670 pLogger = NULL;
2671 }
2672 }
2673 return pLogger;
2674}
2675RT_EXPORT_SYMBOL(RTLogDefaultInstanceEx);
2676
2677
2678/**
2679 * Common worker for RTLogGetDefaultInstance and RTLogGetDefaultInstanceEx.
2680 */
2681DECL_FORCE_INLINE(PRTLOGGER) rtLogGetDefaultInstanceCommon(void)
2682{
2683#ifdef IN_RC
2684 return &g_Logger;
2685#else
2686# ifdef IN_RING0
2687 /*
2688 * Check per thread loggers first.
2689 */
2690 if (g_cPerThreadLoggers)
2691 {
2692 const RTNATIVETHREAD Self = RTThreadNativeSelf();
2693 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
2694 while (i-- > 0)
2695 if (g_aPerThreadLoggers[i].NativeThread == Self)
2696 return g_aPerThreadLoggers[i].pLogger;
2697 }
2698# endif /* IN_RING0 */
2699
2700 return g_pLogger;
2701#endif
2702}
2703
2704
2705RTDECL(PRTLOGGER) RTLogGetDefaultInstance(void)
2706{
2707 return rtLogGetDefaultInstanceCommon();
2708}
2709RT_EXPORT_SYMBOL(RTLogGetDefaultInstance);
2710
2711
2712RTDECL(PRTLOGGER) RTLogGetDefaultInstanceEx(uint32_t fFlagsAndGroup)
2713{
2714 PRTLOGGER pLogger = rtLogGetDefaultInstanceCommon();
2715 if (pLogger)
2716 {
2717 if (pLogger->fFlags & RTLOGFLAGS_DISABLED)
2718 pLogger = NULL;
2719 else
2720 {
2721 uint32_t const fFlags = RT_LO_U16(fFlagsAndGroup);
2722 uint16_t const iGroup = RT_HI_U16(fFlagsAndGroup);
2723 if ( iGroup != UINT16_MAX
2724 && ( (pLogger->afGroups[iGroup < pLogger->cGroups ? iGroup : 0] & (fFlags | RTLOGGRPFLAGS_ENABLED))
2725 != (fFlags | RTLOGGRPFLAGS_ENABLED)))
2726 pLogger = NULL;
2727 }
2728 }
2729 return pLogger;
2730}
2731RT_EXPORT_SYMBOL(RTLogGetDefaultInstanceEx);
2732
2733
2734#ifndef IN_RC
2735/**
2736 * Sets the default logger instance.
2737 *
2738 * @returns iprt status code.
2739 * @param pLogger The new default logger instance.
2740 */
2741RTDECL(PRTLOGGER) RTLogSetDefaultInstance(PRTLOGGER pLogger)
2742{
2743 return ASMAtomicXchgPtrT(&g_pLogger, pLogger, PRTLOGGER);
2744}
2745RT_EXPORT_SYMBOL(RTLogSetDefaultInstance);
2746#endif /* !IN_RC */
2747
2748
2749#ifdef IN_RING0
2750/**
2751 * Changes the default logger instance for the current thread.
2752 *
2753 * @returns IPRT status code.
2754 * @param pLogger The logger instance. Pass NULL for deregistration.
2755 * @param uKey Associated key for cleanup purposes. If pLogger is NULL,
2756 * all instances with this key will be deregistered. So in
2757 * order to only deregister the instance associated with the
2758 * current thread use 0.
2759 */
2760RTDECL(int) RTLogSetDefaultInstanceThread(PRTLOGGER pLogger, uintptr_t uKey)
2761{
2762 int rc;
2763 RTNATIVETHREAD Self = RTThreadNativeSelf();
2764 if (pLogger)
2765 {
2766 int32_t i;
2767 unsigned j;
2768
2769 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
2770
2771 /*
2772 * Iterate the table to see if there is already an entry for this thread.
2773 */
2774 i = RT_ELEMENTS(g_aPerThreadLoggers);
2775 while (i-- > 0)
2776 if (g_aPerThreadLoggers[i].NativeThread == Self)
2777 {
2778 ASMAtomicWritePtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, (void *)uKey);
2779 g_aPerThreadLoggers[i].pLogger = pLogger;
2780 return VINF_SUCCESS;
2781 }
2782
2783 /*
2784 * Allocate a new table entry.
2785 */
2786 i = ASMAtomicIncS32(&g_cPerThreadLoggers);
2787 if (i > (int32_t)RT_ELEMENTS(g_aPerThreadLoggers))
2788 {
2789 ASMAtomicDecS32(&g_cPerThreadLoggers);
2790 return VERR_BUFFER_OVERFLOW; /* horrible error code! */
2791 }
2792
2793 for (j = 0; j < 10; j++)
2794 {
2795 i = RT_ELEMENTS(g_aPerThreadLoggers);
2796 while (i-- > 0)
2797 {
2798 AssertCompile(sizeof(RTNATIVETHREAD) == sizeof(void*));
2799 if ( g_aPerThreadLoggers[i].NativeThread == NIL_RTNATIVETHREAD
2800 && ASMAtomicCmpXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].NativeThread, (void *)Self, (void *)NIL_RTNATIVETHREAD))
2801 {
2802 ASMAtomicWritePtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, (void *)uKey);
2803 ASMAtomicWritePtr(&g_aPerThreadLoggers[i].pLogger, pLogger);
2804 return VINF_SUCCESS;
2805 }
2806 }
2807 }
2808
2809 ASMAtomicDecS32(&g_cPerThreadLoggers);
2810 rc = VERR_INTERNAL_ERROR;
2811 }
2812 else
2813 {
2814 /*
2815 * Search the array for the current thread.
2816 */
2817 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
2818 while (i-- > 0)
2819 if ( g_aPerThreadLoggers[i].NativeThread == Self
2820 || g_aPerThreadLoggers[i].uKey == uKey)
2821 {
2822 ASMAtomicWriteNullPtr((void * volatile *)&g_aPerThreadLoggers[i].uKey);
2823 ASMAtomicWriteNullPtr(&g_aPerThreadLoggers[i].pLogger);
2824 ASMAtomicWriteHandle(&g_aPerThreadLoggers[i].NativeThread, NIL_RTNATIVETHREAD);
2825 ASMAtomicDecS32(&g_cPerThreadLoggers);
2826 }
2827
2828 rc = VINF_SUCCESS;
2829 }
2830 return rc;
2831}
2832RT_EXPORT_SYMBOL(RTLogSetDefaultInstanceThread);
2833#endif /* IN_RING0 */
2834
2835
2836/**
2837 * Write to a logger instance.
2838 *
2839 * @param pLogger Pointer to logger instance.
2840 * @param pszFormat Format string.
2841 * @param args Format arguments.
2842 */
2843RTDECL(void) RTLogLoggerV(PRTLOGGER pLogger, const char *pszFormat, va_list args)
2844{
2845 RTLogLoggerExV(pLogger, 0, ~0U, pszFormat, args);
2846}
2847RT_EXPORT_SYMBOL(RTLogLoggerV);
2848
2849
2850/**
2851 * Write to a logger instance.
2852 *
2853 * This function will check whether the instance, group and flags makes up a
2854 * logging kind which is currently enabled before writing anything to the log.
2855 *
2856 * @param pLogger Pointer to logger instance. If NULL the default logger instance will be attempted.
2857 * @param fFlags The logging flags.
2858 * @param iGroup The group.
2859 * The value ~0U is reserved for compatibility with RTLogLogger[V] and is
2860 * only for internal usage!
2861 * @param pszFormat Format string.
2862 * @param args Format arguments.
2863 */
2864RTDECL(void) RTLogLoggerExV(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args)
2865{
2866 int rc;
2867
2868 /*
2869 * A NULL logger means default instance.
2870 */
2871 if (!pLogger)
2872 {
2873 pLogger = RTLogDefaultInstance();
2874 if (!pLogger)
2875 return;
2876 }
2877
2878 /*
2879 * Validate and correct iGroup.
2880 */
2881 if (iGroup != ~0U && iGroup >= pLogger->cGroups)
2882 iGroup = 0;
2883
2884 /*
2885 * If no output, then just skip it.
2886 */
2887 if ( (pLogger->fFlags & RTLOGFLAGS_DISABLED)
2888#ifndef IN_RC
2889 || !pLogger->fDestFlags
2890#endif
2891 || !pszFormat || !*pszFormat)
2892 return;
2893 if ( iGroup != ~0U
2894 && (pLogger->afGroups[iGroup] & (fFlags | RTLOGGRPFLAGS_ENABLED)) != (fFlags | RTLOGGRPFLAGS_ENABLED))
2895 return;
2896
2897 /*
2898 * Acquire logger instance sem.
2899 */
2900 rc = rtlogLock(pLogger);
2901 if (RT_FAILURE(rc))
2902 {
2903#ifdef IN_RING0
2904 if (pLogger->fDestFlags & ~RTLOGDEST_FILE)
2905 rtR0LogLoggerExFallback(pLogger->fDestFlags, pLogger->fFlags, pLogger->pInt, pszFormat, args);
2906#endif
2907 return;
2908 }
2909
2910 /*
2911 * Check restrictions and call worker.
2912 */
2913#ifndef IN_RC
2914 if (RT_UNLIKELY( (pLogger->fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
2915 && iGroup < pLogger->cGroups
2916 && (pLogger->afGroups[iGroup] & RTLOGGRPFLAGS_RESTRICT)
2917 && ++pLogger->pInt->pacEntriesPerGroup[iGroup] >= pLogger->pInt->cMaxEntriesPerGroup ))
2918 {
2919 uint32_t cEntries = pLogger->pInt->pacEntriesPerGroup[iGroup];
2920 if (cEntries > pLogger->pInt->cMaxEntriesPerGroup)
2921 pLogger->pInt->pacEntriesPerGroup[iGroup] = cEntries - 1;
2922 else
2923 {
2924 rtlogLoggerExVLocked(pLogger, fFlags, iGroup, pszFormat, args);
2925 if ( pLogger->pInt->papszGroups
2926 && pLogger->pInt->papszGroups[iGroup])
2927 rtlogLoggerExFLocked(pLogger, fFlags, iGroup, "%u messages from group %s (#%u), muting it.\n",
2928 cEntries, pLogger->pInt->papszGroups[iGroup], iGroup);
2929 else
2930 rtlogLoggerExFLocked(pLogger, fFlags, iGroup, "%u messages from group #%u, muting it.\n",
2931 cEntries, iGroup);
2932 }
2933 }
2934 else
2935#endif
2936 rtlogLoggerExVLocked(pLogger, fFlags, iGroup, pszFormat, args);
2937
2938 /*
2939 * Release the semaphore.
2940 */
2941 rtlogUnlock(pLogger);
2942}
2943RT_EXPORT_SYMBOL(RTLogLoggerExV);
2944
2945
2946#ifdef IN_RING0
2947/**
2948 * For rtR0LogLoggerExFallbackOutput and rtR0LogLoggerExFallbackFlush.
2949 */
2950typedef struct RTR0LOGLOGGERFALLBACK
2951{
2952 /** The current scratch buffer offset. */
2953 uint32_t offScratch;
2954 /** The destination flags. */
2955 uint32_t fDestFlags;
2956 /** For ring buffer output. */
2957 PRTLOGGERINTERNAL pInt;
2958 /** The scratch buffer. */
2959 char achScratch[80];
2960} RTR0LOGLOGGERFALLBACK;
2961/** Pointer to RTR0LOGLOGGERFALLBACK which is used by
2962 * rtR0LogLoggerExFallbackOutput. */
2963typedef RTR0LOGLOGGERFALLBACK *PRTR0LOGLOGGERFALLBACK;
2964
2965
2966/**
2967 * Flushes the fallback buffer.
2968 *
2969 * @param pThis The scratch buffer.
2970 */
2971static void rtR0LogLoggerExFallbackFlush(PRTR0LOGLOGGERFALLBACK pThis)
2972{
2973 if (!pThis->offScratch)
2974 return;
2975
2976 if ( (pThis->fDestFlags & RTLOGDEST_RINGBUF)
2977 && pThis->pInt
2978 && pThis->pInt->pszRingBuf /* paranoia */)
2979 rtLogRingBufWrite(pThis->pInt, pThis->achScratch, pThis->offScratch);
2980 else
2981 {
2982 if (pThis->fDestFlags & RTLOGDEST_USER)
2983 RTLogWriteUser(pThis->achScratch, pThis->offScratch);
2984
2985 if (pThis->fDestFlags & RTLOGDEST_DEBUGGER)
2986 RTLogWriteDebugger(pThis->achScratch, pThis->offScratch);
2987
2988 if (pThis->fDestFlags & RTLOGDEST_STDOUT)
2989 RTLogWriteStdOut(pThis->achScratch, pThis->offScratch);
2990
2991 if (pThis->fDestFlags & RTLOGDEST_STDERR)
2992 RTLogWriteStdErr(pThis->achScratch, pThis->offScratch);
2993
2994# ifndef LOG_NO_COM
2995 if (pThis->fDestFlags & RTLOGDEST_COM)
2996 RTLogWriteCom(pThis->achScratch, pThis->offScratch);
2997# endif
2998 }
2999
3000 /* empty the buffer. */
3001 pThis->offScratch = 0;
3002}
3003
3004
3005/**
3006 * Callback for RTLogFormatV used by rtR0LogLoggerExFallback.
3007 * See PFNLOGOUTPUT() for details.
3008 */
3009static DECLCALLBACK(size_t) rtR0LogLoggerExFallbackOutput(void *pv, const char *pachChars, size_t cbChars)
3010{
3011 PRTR0LOGLOGGERFALLBACK pThis = (PRTR0LOGLOGGERFALLBACK)pv;
3012 if (cbChars)
3013 {
3014 size_t cbRet = 0;
3015 for (;;)
3016 {
3017 /* how much */
3018 uint32_t cb = sizeof(pThis->achScratch) - pThis->offScratch - 1; /* minus 1 - for the string terminator. */
3019 if (cb > cbChars)
3020 cb = (uint32_t)cbChars;
3021
3022 /* copy */
3023 memcpy(&pThis->achScratch[pThis->offScratch], pachChars, cb);
3024
3025 /* advance */
3026 pThis->offScratch += cb;
3027 cbRet += cb;
3028 cbChars -= cb;
3029
3030 /* done? */
3031 if (cbChars <= 0)
3032 return cbRet;
3033
3034 pachChars += cb;
3035
3036 /* flush */
3037 pThis->achScratch[pThis->offScratch] = '\0';
3038 rtR0LogLoggerExFallbackFlush(pThis);
3039 }
3040
3041 /* won't ever get here! */
3042 }
3043 else
3044 {
3045 /*
3046 * Termination call, flush the log.
3047 */
3048 pThis->achScratch[pThis->offScratch] = '\0';
3049 rtR0LogLoggerExFallbackFlush(pThis);
3050 return 0;
3051 }
3052}
3053
3054
3055/**
3056 * Ring-0 fallback for cases where we're unable to grab the lock.
3057 *
3058 * This will happen when we're at a too high IRQL on Windows for instance and
3059 * needs to be dealt with or we'll drop a lot of log output. This fallback will
3060 * only output to some of the log destinations as a few of them may be doing
3061 * dangerous things. We won't be doing any prefixing here either, at least not
3062 * for the present, because it's too much hassle.
3063 *
3064 * @param fDestFlags The destination flags.
3065 * @param fFlags The logger flags.
3066 * @param pInt The internal logger data, for ring buffer output.
3067 * @param pszFormat The format string.
3068 * @param va The format arguments.
3069 */
3070static void rtR0LogLoggerExFallback(uint32_t fDestFlags, uint32_t fFlags, PRTLOGGERINTERNAL pInt,
3071 const char *pszFormat, va_list va)
3072{
3073 RTR0LOGLOGGERFALLBACK This;
3074 This.fDestFlags = fDestFlags;
3075 This.pInt = pInt;
3076
3077 /* fallback indicator. */
3078 This.offScratch = 2;
3079 This.achScratch[0] = '[';
3080 This.achScratch[1] = 'F';
3081
3082 /* selected prefixes */
3083 if (fFlags & RTLOGFLAGS_PREFIX_PID)
3084 {
3085 RTPROCESS Process = RTProcSelf();
3086 This.achScratch[This.offScratch++] = ' ';
3087 This.offScratch += RTStrFormatNumber(&This.achScratch[This.offScratch], Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
3088 }
3089 if (fFlags & RTLOGFLAGS_PREFIX_TID)
3090 {
3091 RTNATIVETHREAD Thread = RTThreadNativeSelf();
3092 This.achScratch[This.offScratch++] = ' ';
3093 This.offScratch += RTStrFormatNumber(&This.achScratch[This.offScratch], Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
3094 }
3095
3096 This.achScratch[This.offScratch++] = ']';
3097 This.achScratch[This.offScratch++] = ' ';
3098
3099 RTLogFormatV(rtR0LogLoggerExFallbackOutput, &This, pszFormat, va);
3100}
3101#endif /* IN_RING0 */
3102
3103
3104/**
3105 * vprintf like function for writing to the default log.
3106 *
3107 * @param pszFormat Printf like format string.
3108 * @param va Optional arguments as specified in pszFormat.
3109 *
3110 * @remark The API doesn't support formatting of floating point numbers at the moment.
3111 */
3112RTDECL(void) RTLogPrintfV(const char *pszFormat, va_list va)
3113{
3114 RTLogLoggerV(NULL, pszFormat, va);
3115}
3116RT_EXPORT_SYMBOL(RTLogPrintfV);
3117
3118
3119/**
3120 * Dumper vprintf-like function outputting to a logger.
3121 *
3122 * @param pvUser Pointer to the logger instance to use, NULL for
3123 * default instance.
3124 * @param pszFormat Format string.
3125 * @param va Format arguments.
3126 */
3127RTDECL(void) RTLogDumpPrintfV(void *pvUser, const char *pszFormat, va_list va)
3128{
3129 RTLogLoggerV((PRTLOGGER)pvUser, pszFormat, va);
3130}
3131RT_EXPORT_SYMBOL(RTLogDumpPrintfV);
3132
3133
3134#ifdef IN_RING3
3135
3136/**
3137 * Opens/creates the log file.
3138 *
3139 * @param pLogger The logger instance to update. NULL is not allowed!
3140 * @param pszErrorMsg A buffer which is filled with an error message if
3141 * something fails. May be NULL.
3142 * @param cchErrorMsg The size of the error message buffer.
3143 */
3144static int rtlogFileOpen(PRTLOGGER pLogger, char *pszErrorMsg, size_t cchErrorMsg)
3145{
3146 uint32_t fOpen = RTFILE_O_WRITE | RTFILE_O_DENY_NONE;
3147 if (pLogger->fFlags & RTLOGFLAGS_APPEND)
3148 fOpen |= RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND;
3149 else
3150 fOpen |= RTFILE_O_CREATE_REPLACE;
3151 if (pLogger->fFlags & RTLOGFLAGS_WRITE_THROUGH)
3152 fOpen |= RTFILE_O_WRITE_THROUGH;
3153
3154 unsigned cBackoff = 0;
3155 int rc = RTFileOpen(&pLogger->pInt->hFile, pLogger->pInt->szFilename, fOpen);
3156 while ( rc == VERR_SHARING_VIOLATION
3157 && cBackoff < RT_ELEMENTS(g_acMsLogBackoff))
3158 {
3159 RTThreadSleep(g_acMsLogBackoff[cBackoff++]);
3160 rc = RTFileOpen(&pLogger->pInt->hFile, pLogger->pInt->szFilename, fOpen);
3161 }
3162 if (RT_SUCCESS(rc))
3163 {
3164 rc = RTFileGetSize(pLogger->pInt->hFile, &pLogger->pInt->cbHistoryFileWritten);
3165 if (RT_FAILURE(rc))
3166 {
3167 /* Don't complain if this fails, assume the file is empty. */
3168 pLogger->pInt->cbHistoryFileWritten = 0;
3169 rc = VINF_SUCCESS;
3170 }
3171 }
3172 else
3173 {
3174 pLogger->pInt->hFile = NIL_RTFILE;
3175 if (pszErrorMsg)
3176 RTStrPrintf(pszErrorMsg, cchErrorMsg, N_("could not open file '%s' (fOpen=%#x)"), pLogger->pInt->szFilename, fOpen);
3177 }
3178 return rc;
3179}
3180
3181
3182/**
3183 * Closes, rotates and opens the log files if necessary.
3184 *
3185 * Used by the rtlogFlush() function as well as RTLogCreateExV.
3186 *
3187 * @param pLogger The logger instance to update. NULL is not allowed!
3188 * @param uTimeSlot Current time slot (for tikme based rotation).
3189 * @param fFirst Flag whether this is the beginning of logging, i.e.
3190 * called from RTLogCreateExV. Prevents pfnPhase from
3191 * being called.
3192 */
3193static void rtlogRotate(PRTLOGGER pLogger, uint32_t uTimeSlot, bool fFirst)
3194{
3195 /* Suppress rotating empty log files simply because the time elapsed. */
3196 if (RT_UNLIKELY(!pLogger->pInt->cbHistoryFileWritten))
3197 pLogger->pInt->uHistoryTimeSlotStart = uTimeSlot;
3198
3199 /* Check rotation condition: file still small enough and not too old? */
3200 if (RT_LIKELY( pLogger->pInt->cbHistoryFileWritten < pLogger->pInt->cbHistoryFileMax
3201 && uTimeSlot == pLogger->pInt->uHistoryTimeSlotStart))
3202 return;
3203
3204 /*
3205 * Save "disabled" log flag and make sure logging is disabled.
3206 * The logging in the functions called during log file history
3207 * rotation would cause severe trouble otherwise.
3208 */
3209 uint32_t const fSavedFlags = pLogger->fFlags;
3210 pLogger->fFlags |= RTLOGFLAGS_DISABLED;
3211
3212 /*
3213 * Disable log rotation temporarily, otherwise with extreme settings and
3214 * chatty phase logging we could run into endless rotation.
3215 */
3216 uint32_t const cSavedHistory = pLogger->pInt->cHistory;
3217 pLogger->pInt->cHistory = 0;
3218
3219 /*
3220 * Close the old log file.
3221 */
3222 if (pLogger->pInt->hFile != NIL_RTFILE)
3223 {
3224 /* Use the callback to generate some final log contents, but only if
3225 * this is a rotation with a fully set up logger. Leave the other case
3226 * to the RTLogCreateExV function. */
3227 if (pLogger->pInt->pfnPhase && !fFirst)
3228 {
3229 uint32_t fODestFlags = pLogger->fDestFlags;
3230 pLogger->fDestFlags &= RTLOGDEST_FILE;
3231 pLogger->pInt->pfnPhase(pLogger, RTLOGPHASE_PREROTATE, rtlogPhaseMsgLocked);
3232 pLogger->fDestFlags = fODestFlags;
3233 }
3234 RTFileClose(pLogger->pInt->hFile);
3235 pLogger->pInt->hFile = NIL_RTFILE;
3236 }
3237
3238 if (cSavedHistory)
3239 {
3240 /*
3241 * Rotate the log files.
3242 */
3243 for (uint32_t i = cSavedHistory - 1; i + 1 > 0; i--)
3244 {
3245 char szOldName[sizeof(pLogger->pInt->szFilename) + 32];
3246 if (i > 0)
3247 RTStrPrintf(szOldName, sizeof(szOldName), "%s.%u", pLogger->pInt->szFilename, i);
3248 else
3249 RTStrCopy(szOldName, sizeof(szOldName), pLogger->pInt->szFilename);
3250
3251 char szNewName[sizeof(pLogger->pInt->szFilename) + 32];
3252 RTStrPrintf(szNewName, sizeof(szNewName), "%s.%u", pLogger->pInt->szFilename, i + 1);
3253
3254 unsigned cBackoff = 0;
3255 int rc = RTFileRename(szOldName, szNewName, RTFILEMOVE_FLAGS_REPLACE);
3256 while ( rc == VERR_SHARING_VIOLATION
3257 && cBackoff < RT_ELEMENTS(g_acMsLogBackoff))
3258 {
3259 RTThreadSleep(g_acMsLogBackoff[cBackoff++]);
3260 rc = RTFileRename(szOldName, szNewName, RTFILEMOVE_FLAGS_REPLACE);
3261 }
3262
3263 if (rc == VERR_FILE_NOT_FOUND)
3264 RTFileDelete(szNewName);
3265 }
3266
3267 /*
3268 * Delete excess log files.
3269 */
3270 for (uint32_t i = cSavedHistory + 1; ; i++)
3271 {
3272 char szExcessName[sizeof(pLogger->pInt->szFilename) + 32];
3273 RTStrPrintf(szExcessName, sizeof(szExcessName), "%s.%u", pLogger->pInt->szFilename, i);
3274 int rc = RTFileDelete(szExcessName);
3275 if (RT_FAILURE(rc))
3276 break;
3277 }
3278 }
3279
3280 /*
3281 * Update logger state and create new log file.
3282 */
3283 pLogger->pInt->cbHistoryFileWritten = 0;
3284 pLogger->pInt->uHistoryTimeSlotStart = uTimeSlot;
3285 rtlogFileOpen(pLogger, NULL, 0);
3286
3287 /*
3288 * Use the callback to generate some initial log contents, but only if this
3289 * is a rotation with a fully set up logger. Leave the other case to the
3290 * RTLogCreateExV function.
3291 */
3292 if (pLogger->pInt->pfnPhase && !fFirst)
3293 {
3294 uint32_t const fSavedDestFlags = pLogger->fDestFlags;
3295 pLogger->fDestFlags &= RTLOGDEST_FILE;
3296 pLogger->pInt->pfnPhase(pLogger, RTLOGPHASE_POSTROTATE, rtlogPhaseMsgLocked);
3297 pLogger->fDestFlags = fSavedDestFlags;
3298 }
3299
3300 /* Restore saved values. */
3301 pLogger->pInt->cHistory = cSavedHistory;
3302 pLogger->fFlags = fSavedFlags;
3303}
3304
3305#endif /* IN_RING3 */
3306
3307
3308/**
3309 * Writes the buffer to the given log device without checking for buffered
3310 * data or anything.
3311 * Used by the RTLogFlush() function.
3312 *
3313 * @param pLogger The logger instance to write to. NULL is not allowed!
3314 */
3315static void rtlogFlush(PRTLOGGER pLogger)
3316{
3317 uint32_t const cchScratch = pLogger->offScratch;
3318 if (cchScratch == 0)
3319 return; /* nothing to flush. */
3320
3321#ifndef IN_RC
3322 /*
3323 * If the ring buffer is active, the other destinations are only written
3324 * to when the ring buffer is flushed by RTLogFlush().
3325 */
3326 if ( (pLogger->fDestFlags & RTLOGDEST_RINGBUF)
3327 && pLogger->pInt
3328 && pLogger->pInt->pszRingBuf /* paraoia */)
3329 {
3330 rtLogRingBufWrite(pLogger->pInt, pLogger->achScratch, pLogger->offScratch);
3331 pLogger->offScratch = 0; /* empty the buffer. */
3332 }
3333 else
3334#endif
3335 {
3336 /* Make sure the string is terminated. On Windows, RTLogWriteDebugger
3337 will get upset if it isn't. */
3338 if (RT_LIKELY(cchScratch < sizeof(pLogger->achScratch)))
3339 pLogger->achScratch[cchScratch] = '\0';
3340 else
3341 AssertFailed();
3342
3343#ifndef IN_RC
3344 if (pLogger->fDestFlags & RTLOGDEST_USER)
3345 RTLogWriteUser(pLogger->achScratch, cchScratch);
3346
3347 if (pLogger->fDestFlags & RTLOGDEST_DEBUGGER)
3348 RTLogWriteDebugger(pLogger->achScratch, cchScratch);
3349
3350# ifdef IN_RING3
3351 if ((pLogger->fDestFlags & (RTLOGDEST_FILE | RTLOGDEST_RINGBUF)) == RTLOGDEST_FILE)
3352 {
3353 if (pLogger->pInt->hFile != NIL_RTFILE)
3354 {
3355 RTFileWrite(pLogger->pInt->hFile, pLogger->achScratch, cchScratch, NULL);
3356 if (pLogger->fFlags & RTLOGFLAGS_FLUSH)
3357 RTFileFlush(pLogger->pInt->hFile);
3358 }
3359 if (pLogger->pInt->cHistory)
3360 pLogger->pInt->cbHistoryFileWritten += cchScratch;
3361 }
3362# endif
3363
3364 if (pLogger->fDestFlags & RTLOGDEST_STDOUT)
3365 RTLogWriteStdOut(pLogger->achScratch, cchScratch);
3366
3367 if (pLogger->fDestFlags & RTLOGDEST_STDERR)
3368 RTLogWriteStdErr(pLogger->achScratch, cchScratch);
3369
3370# if (defined(IN_RING0) || defined(IN_RC)) && !defined(LOG_NO_COM)
3371 if (pLogger->fDestFlags & RTLOGDEST_COM)
3372 RTLogWriteCom(pLogger->achScratch, cchScratch);
3373# endif
3374#endif /* !IN_RC */
3375
3376#ifdef IN_RC
3377 if (pLogger->pfnFlush)
3378 pLogger->pfnFlush(pLogger);
3379#else
3380 if (pLogger->pInt->pfnFlush)
3381 pLogger->pInt->pfnFlush(pLogger);
3382#endif
3383
3384 /* empty the buffer. */
3385 pLogger->offScratch = 0;
3386
3387#ifdef IN_RING3
3388 /*
3389 * Rotate the log file if configured. Must be done after everything is
3390 * flushed, since this will also use logging/flushing to write the header
3391 * and footer messages.
3392 */
3393 if ( (pLogger->fDestFlags & RTLOGDEST_FILE)
3394 && pLogger->pInt->cHistory)
3395 rtlogRotate(pLogger, RTTimeProgramSecTS() / pLogger->pInt->cSecsHistoryTimeSlot, false /* fFirst */);
3396#endif
3397 }
3398}
3399
3400
3401/**
3402 * Callback for RTLogFormatV which writes to the com port.
3403 * See PFNLOGOUTPUT() for details.
3404 */
3405static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
3406{
3407 PRTLOGGER pLogger = (PRTLOGGER)pv;
3408 if (cbChars)
3409 {
3410 size_t cbRet = 0;
3411 for (;;)
3412 {
3413#if defined(DEBUG) && defined(IN_RING3)
3414 /* sanity */
3415 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
3416 {
3417 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
3418 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
3419 AssertBreakpoint(); AssertBreakpoint();
3420 }
3421#endif
3422
3423 /* how much */
3424 size_t cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3425 if (cb > cbChars)
3426 cb = cbChars;
3427
3428 /* copy */
3429 memcpy(&pLogger->achScratch[pLogger->offScratch], pachChars, cb);
3430
3431 /* advance */
3432 pLogger->offScratch += (uint32_t)cb;
3433 cbRet += cb;
3434 cbChars -= cb;
3435
3436 /* done? */
3437 if (cbChars <= 0)
3438 return cbRet;
3439
3440 pachChars += cb;
3441
3442 /* flush */
3443 rtlogFlush(pLogger);
3444 }
3445
3446 /* won't ever get here! */
3447 }
3448 else
3449 {
3450 /*
3451 * Termination call.
3452 * There's always space for a terminator, and it's not counted.
3453 */
3454 pLogger->achScratch[pLogger->offScratch] = '\0';
3455 return 0;
3456 }
3457}
3458
3459
3460/**
3461 * stpncpy implementation for use in rtLogOutputPrefixed w/ padding.
3462 *
3463 * @returns Pointer to the destination buffer byte following the copied string.
3464 * @param pszDst The destination buffer.
3465 * @param pszSrc The source string.
3466 * @param cchSrcMax The maximum number of characters to copy from
3467 * the string.
3468 * @param cchMinWidth The minimum field with, padd with spaces to
3469 * reach this.
3470 */
3471DECLINLINE(char *) rtLogStPNCpyPad(char *pszDst, const char *pszSrc, size_t cchSrcMax, size_t cchMinWidth)
3472{
3473 size_t cchSrc = 0;
3474 if (pszSrc)
3475 {
3476 cchSrc = strlen(pszSrc);
3477 if (cchSrc > cchSrcMax)
3478 cchSrc = cchSrcMax;
3479
3480 memcpy(pszDst, pszSrc, cchSrc);
3481 pszDst += cchSrc;
3482 }
3483 do
3484 *pszDst++ = ' ';
3485 while (cchSrc++ < cchMinWidth);
3486
3487 return pszDst;
3488}
3489
3490
3491
3492/**
3493 * Callback for RTLogFormatV which writes to the logger instance.
3494 * This version supports prefixes.
3495 *
3496 * See PFNLOGOUTPUT() for details.
3497 */
3498static DECLCALLBACK(size_t) rtLogOutputPrefixed(void *pv, const char *pachChars, size_t cbChars)
3499{
3500 PRTLOGOUTPUTPREFIXEDARGS pArgs = (PRTLOGOUTPUTPREFIXEDARGS)pv;
3501 PRTLOGGER pLogger = pArgs->pLogger;
3502 if (cbChars)
3503 {
3504 size_t cbRet = 0;
3505 for (;;)
3506 {
3507 size_t cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3508 const char *pszNewLine;
3509 char *psz;
3510#ifdef IN_RC
3511 bool *pfPendingPrefix = &pLogger->fPendingPrefix;
3512#else
3513 bool *pfPendingPrefix = &pLogger->pInt->fPendingPrefix;
3514#endif
3515
3516 /*
3517 * Pending prefix?
3518 */
3519 if (*pfPendingPrefix)
3520 {
3521 *pfPendingPrefix = false;
3522
3523#if defined(DEBUG) && defined(IN_RING3)
3524 /* sanity */
3525 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
3526 {
3527 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
3528 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
3529 AssertBreakpoint(); AssertBreakpoint();
3530 }
3531#endif
3532
3533 /*
3534 * Flush the buffer if there isn't enough room for the maximum prefix config.
3535 * Max is 256, add a couple of extra bytes. See CCH_PREFIX check way below.
3536 */
3537 if (cb < 256 + 16)
3538 {
3539 rtlogFlush(pLogger);
3540 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3541 }
3542
3543 /*
3544 * Write the prefixes.
3545 * psz is pointing to the current position.
3546 */
3547 psz = &pLogger->achScratch[pLogger->offScratch];
3548 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TS)
3549 {
3550 uint64_t u64 = RTTimeNanoTS();
3551 int iBase = 16;
3552 unsigned int fFlags = RTSTR_F_ZEROPAD;
3553 if (pLogger->fFlags & RTLOGFLAGS_DECIMAL_TS)
3554 {
3555 iBase = 10;
3556 fFlags = 0;
3557 }
3558 if (pLogger->fFlags & RTLOGFLAGS_REL_TS)
3559 {
3560 static volatile uint64_t s_u64LastTs;
3561 uint64_t u64DiffTs = u64 - s_u64LastTs;
3562 s_u64LastTs = u64;
3563 /* We could have been preempted just before reading of s_u64LastTs by
3564 * another thread which wrote s_u64LastTs. In that case the difference
3565 * is negative which we simply ignore. */
3566 u64 = (int64_t)u64DiffTs < 0 ? 0 : u64DiffTs;
3567 }
3568 /* 1E15 nanoseconds = 11 days */
3569 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags);
3570 *psz++ = ' ';
3571 }
3572#define CCH_PREFIX_01 0 + 17
3573
3574 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TSC)
3575 {
3576#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
3577 uint64_t u64 = ASMReadTSC();
3578#else
3579 uint64_t u64 = RTTimeNanoTS();
3580#endif
3581 int iBase = 16;
3582 unsigned int fFlags = RTSTR_F_ZEROPAD;
3583 if (pLogger->fFlags & RTLOGFLAGS_DECIMAL_TS)
3584 {
3585 iBase = 10;
3586 fFlags = 0;
3587 }
3588 if (pLogger->fFlags & RTLOGFLAGS_REL_TS)
3589 {
3590 static volatile uint64_t s_u64LastTsc;
3591 int64_t i64DiffTsc = u64 - s_u64LastTsc;
3592 s_u64LastTsc = u64;
3593 /* We could have been preempted just before reading of s_u64LastTsc by
3594 * another thread which wrote s_u64LastTsc. In that case the difference
3595 * is negative which we simply ignore. */
3596 u64 = i64DiffTsc < 0 ? 0 : i64DiffTsc;
3597 }
3598 /* 1E15 ticks at 4GHz = 69 hours */
3599 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags);
3600 *psz++ = ' ';
3601 }
3602#define CCH_PREFIX_02 CCH_PREFIX_01 + 17
3603
3604 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_MS_PROG)
3605 {
3606#if defined(IN_RING3) || defined(IN_RC)
3607 uint64_t u64 = RTTimeProgramMilliTS();
3608#else
3609 uint64_t u64 = 0;
3610#endif
3611 /* 1E8 milliseconds = 27 hours */
3612 psz += RTStrFormatNumber(psz, u64, 10, 9, 0, RTSTR_F_ZEROPAD);
3613 *psz++ = ' ';
3614 }
3615#define CCH_PREFIX_03 CCH_PREFIX_02 + 21
3616
3617 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TIME)
3618 {
3619#if defined(IN_RING3) || defined(IN_RING0)
3620 RTTIMESPEC TimeSpec;
3621 RTTIME Time;
3622 RTTimeExplode(&Time, RTTimeNow(&TimeSpec));
3623 psz += RTStrFormatNumber(psz, Time.u8Hour, 10, 2, 0, RTSTR_F_ZEROPAD);
3624 *psz++ = ':';
3625 psz += RTStrFormatNumber(psz, Time.u8Minute, 10, 2, 0, RTSTR_F_ZEROPAD);
3626 *psz++ = ':';
3627 psz += RTStrFormatNumber(psz, Time.u8Second, 10, 2, 0, RTSTR_F_ZEROPAD);
3628 *psz++ = '.';
3629 psz += RTStrFormatNumber(psz, Time.u32Nanosecond / 1000, 10, 6, 0, RTSTR_F_ZEROPAD);
3630 *psz++ = ' ';
3631#else
3632 memset(psz, ' ', 16);
3633 psz += 16;
3634#endif
3635 }
3636#define CCH_PREFIX_04 CCH_PREFIX_03 + (3+1+3+1+3+1+7+1)
3637
3638 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TIME_PROG)
3639 {
3640
3641#if defined(IN_RING3) || defined(IN_RC)
3642 uint64_t u64 = RTTimeProgramMicroTS();
3643 psz += RTStrFormatNumber(psz, (uint32_t)(u64 / RT_US_1HOUR), 10, 2, 0, RTSTR_F_ZEROPAD);
3644 *psz++ = ':';
3645 uint32_t u32 = (uint32_t)(u64 % RT_US_1HOUR);
3646 psz += RTStrFormatNumber(psz, u32 / RT_US_1MIN, 10, 2, 0, RTSTR_F_ZEROPAD);
3647 *psz++ = ':';
3648 u32 %= RT_US_1MIN;
3649
3650 psz += RTStrFormatNumber(psz, u32 / RT_US_1SEC, 10, 2, 0, RTSTR_F_ZEROPAD);
3651 *psz++ = '.';
3652 psz += RTStrFormatNumber(psz, u32 % RT_US_1SEC, 10, 6, 0, RTSTR_F_ZEROPAD);
3653 *psz++ = ' ';
3654#else
3655 memset(psz, ' ', 16);
3656 psz += 16;
3657#endif
3658 }
3659#define CCH_PREFIX_05 CCH_PREFIX_04 + (9+1+2+1+2+1+6+1)
3660
3661# if 0
3662 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_DATETIME)
3663 {
3664 char szDate[32];
3665 RTTIMESPEC Time;
3666 RTTimeSpecToString(RTTimeNow(&Time), szDate, sizeof(szDate));
3667 size_t cch = strlen(szDate);
3668 memcpy(psz, szDate, cch);
3669 psz += cch;
3670 *psz++ = ' ';
3671 }
3672# define CCH_PREFIX_06 CCH_PREFIX_05 + 32
3673# else
3674# define CCH_PREFIX_06 CCH_PREFIX_05 + 0
3675# endif
3676
3677 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_PID)
3678 {
3679#ifndef IN_RC
3680 RTPROCESS Process = RTProcSelf();
3681#else
3682 RTPROCESS Process = NIL_RTPROCESS;
3683#endif
3684 psz += RTStrFormatNumber(psz, Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
3685 *psz++ = ' ';
3686 }
3687#define CCH_PREFIX_07 CCH_PREFIX_06 + 9
3688
3689 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TID)
3690 {
3691#ifndef IN_RC
3692 RTNATIVETHREAD Thread = RTThreadNativeSelf();
3693#else
3694 RTNATIVETHREAD Thread = NIL_RTNATIVETHREAD;
3695#endif
3696 psz += RTStrFormatNumber(psz, Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
3697 *psz++ = ' ';
3698 }
3699#define CCH_PREFIX_08 CCH_PREFIX_07 + 17
3700
3701 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_THREAD)
3702 {
3703#ifdef IN_RING3
3704 const char *pszName = RTThreadSelfName();
3705#elif defined IN_RC
3706 const char *pszName = "EMT-RC";
3707#else
3708 const char *pszName = "R0";
3709#endif
3710 psz = rtLogStPNCpyPad(psz, pszName, 16, 8);
3711 }
3712#define CCH_PREFIX_09 CCH_PREFIX_08 + 17
3713
3714 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_CPUID)
3715 {
3716#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
3717 const uint8_t idCpu = ASMGetApicId();
3718#else
3719 const RTCPUID idCpu = RTMpCpuId();
3720#endif
3721 psz += RTStrFormatNumber(psz, idCpu, 16, sizeof(idCpu) * 2, 0, RTSTR_F_ZEROPAD);
3722 *psz++ = ' ';
3723 }
3724#define CCH_PREFIX_10 CCH_PREFIX_09 + 17
3725
3726#ifndef IN_RC
3727 if ( (pLogger->fFlags & RTLOGFLAGS_PREFIX_CUSTOM)
3728 && pLogger->pInt->pfnPrefix)
3729 {
3730 psz += pLogger->pInt->pfnPrefix(pLogger, psz, 31, pLogger->pInt->pvPrefixUserArg);
3731 *psz++ = ' '; /* +32 */
3732 }
3733#endif
3734#define CCH_PREFIX_11 CCH_PREFIX_10 + 32
3735
3736 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_LOCK_COUNTS)
3737 {
3738#ifdef IN_RING3 /** @todo implement these counters in ring-0 too? */
3739 RTTHREAD Thread = RTThreadSelf();
3740 if (Thread != NIL_RTTHREAD)
3741 {
3742 uint32_t cReadLocks = RTLockValidatorReadLockGetCount(Thread);
3743 uint32_t cWriteLocks = RTLockValidatorWriteLockGetCount(Thread) - g_cLoggerLockCount;
3744 cReadLocks = RT_MIN(0xfff, cReadLocks);
3745 cWriteLocks = RT_MIN(0xfff, cWriteLocks);
3746 psz += RTStrFormatNumber(psz, cReadLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
3747 *psz++ = '/';
3748 psz += RTStrFormatNumber(psz, cWriteLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
3749 }
3750 else
3751#endif
3752 {
3753 *psz++ = '?';
3754 *psz++ = '/';
3755 *psz++ = '?';
3756 }
3757 *psz++ = ' ';
3758 }
3759#define CCH_PREFIX_12 CCH_PREFIX_11 + 8
3760
3761 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_FLAG_NO)
3762 {
3763 psz += RTStrFormatNumber(psz, pArgs->fFlags, 16, 8, 0, RTSTR_F_ZEROPAD);
3764 *psz++ = ' ';
3765 }
3766#define CCH_PREFIX_13 CCH_PREFIX_12 + 9
3767
3768 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_FLAG)
3769 {
3770#ifdef IN_RING3
3771 const char *pszGroup = pArgs->iGroup != ~0U ? pLogger->pInt->papszGroups[pArgs->iGroup] : NULL;
3772#else
3773 const char *pszGroup = NULL;
3774#endif
3775 psz = rtLogStPNCpyPad(psz, pszGroup, 16, 8);
3776 }
3777#define CCH_PREFIX_14 CCH_PREFIX_13 + 17
3778
3779 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_GROUP_NO)
3780 {
3781 if (pArgs->iGroup != ~0U)
3782 {
3783 psz += RTStrFormatNumber(psz, pArgs->iGroup, 16, 3, 0, RTSTR_F_ZEROPAD);
3784 *psz++ = ' ';
3785 }
3786 else
3787 {
3788 memcpy(psz, "-1 ", sizeof("-1 ") - 1);
3789 psz += sizeof("-1 ") - 1;
3790 } /* +9 */
3791 }
3792#define CCH_PREFIX_15 CCH_PREFIX_14 + 9
3793
3794 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_GROUP)
3795 {
3796 const unsigned fGrp = pLogger->afGroups[pArgs->iGroup != ~0U ? pArgs->iGroup : 0];
3797 const char *pszGroup;
3798 size_t cch;
3799 switch (pArgs->fFlags & fGrp)
3800 {
3801 case 0: pszGroup = "--------"; cch = sizeof("--------") - 1; break;
3802 case RTLOGGRPFLAGS_ENABLED: pszGroup = "enabled" ; cch = sizeof("enabled" ) - 1; break;
3803 case RTLOGGRPFLAGS_LEVEL_1: pszGroup = "level 1" ; cch = sizeof("level 1" ) - 1; break;
3804 case RTLOGGRPFLAGS_LEVEL_2: pszGroup = "level 2" ; cch = sizeof("level 2" ) - 1; break;
3805 case RTLOGGRPFLAGS_LEVEL_3: pszGroup = "level 3" ; cch = sizeof("level 3" ) - 1; break;
3806 case RTLOGGRPFLAGS_LEVEL_4: pszGroup = "level 4" ; cch = sizeof("level 4" ) - 1; break;
3807 case RTLOGGRPFLAGS_LEVEL_5: pszGroup = "level 5" ; cch = sizeof("level 5" ) - 1; break;
3808 case RTLOGGRPFLAGS_LEVEL_6: pszGroup = "level 6" ; cch = sizeof("level 6" ) - 1; break;
3809 case RTLOGGRPFLAGS_LEVEL_7: pszGroup = "level 7" ; cch = sizeof("level 7" ) - 1; break;
3810 case RTLOGGRPFLAGS_LEVEL_8: pszGroup = "level 8" ; cch = sizeof("level 8" ) - 1; break;
3811 case RTLOGGRPFLAGS_LEVEL_9: pszGroup = "level 9" ; cch = sizeof("level 9" ) - 1; break;
3812 case RTLOGGRPFLAGS_LEVEL_10: pszGroup = "level 10"; cch = sizeof("level 10") - 1; break;
3813 case RTLOGGRPFLAGS_LEVEL_11: pszGroup = "level 11"; cch = sizeof("level 11") - 1; break;
3814 case RTLOGGRPFLAGS_LEVEL_12: pszGroup = "level 12"; cch = sizeof("level 12") - 1; break;
3815 case RTLOGGRPFLAGS_FLOW: pszGroup = "flow" ; cch = sizeof("flow" ) - 1; break;
3816 case RTLOGGRPFLAGS_WARN: pszGroup = "warn" ; cch = sizeof("warn" ) - 1; break;
3817 default: pszGroup = "????????"; cch = sizeof("????????") - 1; break;
3818 }
3819 psz = rtLogStPNCpyPad(psz, pszGroup, 16, 8);
3820 }
3821#define CCH_PREFIX_16 CCH_PREFIX_15 + 17
3822
3823#define CCH_PREFIX ( CCH_PREFIX_16 )
3824 { AssertCompile(CCH_PREFIX < 256); }
3825
3826 /*
3827 * Done, figure what we've used and advance the buffer and free size.
3828 */
3829 cb = psz - &pLogger->achScratch[pLogger->offScratch];
3830 AssertMsg(cb <= 223, ("%#zx (%zd) - fFlags=%#x\n", cb, cb, pLogger->fFlags));
3831 pLogger->offScratch += (uint32_t)cb;
3832 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3833 }
3834 else if (cb <= 0)
3835 {
3836 rtlogFlush(pLogger);
3837 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3838 }
3839
3840#if defined(DEBUG) && defined(IN_RING3)
3841 /* sanity */
3842 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
3843 {
3844 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
3845 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
3846 AssertBreakpoint(); AssertBreakpoint();
3847 }
3848#endif
3849
3850 /* how much */
3851 if (cb > cbChars)
3852 cb = cbChars;
3853
3854 /* have newline? */
3855 pszNewLine = (const char *)memchr(pachChars, '\n', cb);
3856 if (pszNewLine)
3857 {
3858 if (pLogger->fFlags & RTLOGFLAGS_USECRLF)
3859 cb = pszNewLine - pachChars;
3860 else
3861 {
3862 cb = pszNewLine - pachChars + 1;
3863 *pfPendingPrefix = true;
3864 }
3865 }
3866
3867 /* copy */
3868 memcpy(&pLogger->achScratch[pLogger->offScratch], pachChars, cb);
3869
3870 /* advance */
3871 pLogger->offScratch += (uint32_t)cb;
3872 cbRet += cb;
3873 cbChars -= cb;
3874
3875 if ( pszNewLine
3876 && (pLogger->fFlags & RTLOGFLAGS_USECRLF)
3877 && pLogger->offScratch + 2 < sizeof(pLogger->achScratch))
3878 {
3879 memcpy(&pLogger->achScratch[pLogger->offScratch], "\r\n", 2);
3880 pLogger->offScratch += 2;
3881 cbRet++;
3882 cbChars--;
3883 cb++;
3884 *pfPendingPrefix = true;
3885 }
3886
3887 /* done? */
3888 if (cbChars <= 0)
3889 return cbRet;
3890 pachChars += cb;
3891 }
3892
3893 /* won't ever get here! */
3894 }
3895 else
3896 {
3897 /*
3898 * Termination call.
3899 * There's always space for a terminator, and it's not counted.
3900 */
3901 pLogger->achScratch[pLogger->offScratch] = '\0';
3902 return 0;
3903 }
3904}
3905
3906
3907/**
3908 * Write to a logger instance (worker function).
3909 *
3910 * This function will check whether the instance, group and flags makes up a
3911 * logging kind which is currently enabled before writing anything to the log.
3912 *
3913 * @param pLogger Pointer to logger instance. Must be non-NULL.
3914 * @param fFlags The logging flags.
3915 * @param iGroup The group.
3916 * The value ~0U is reserved for compatibility with RTLogLogger[V] and is
3917 * only for internal usage!
3918 * @param pszFormat Format string.
3919 * @param args Format arguments.
3920 */
3921static void rtlogLoggerExVLocked(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args)
3922{
3923 /*
3924 * Format the message and perhaps flush it.
3925 */
3926 if (pLogger->fFlags & (RTLOGFLAGS_PREFIX_MASK | RTLOGFLAGS_USECRLF))
3927 {
3928 RTLOGOUTPUTPREFIXEDARGS OutputArgs;
3929 OutputArgs.pLogger = pLogger;
3930 OutputArgs.iGroup = iGroup;
3931 OutputArgs.fFlags = fFlags;
3932 RTLogFormatV(rtLogOutputPrefixed, &OutputArgs, pszFormat, args);
3933 }
3934 else
3935 RTLogFormatV(rtLogOutput, pLogger, pszFormat, args);
3936 if ( !(pLogger->fFlags & RTLOGFLAGS_BUFFERED)
3937 && pLogger->offScratch)
3938 rtlogFlush(pLogger);
3939}
3940
3941
3942#ifndef IN_RC
3943/**
3944 * For calling rtlogLoggerExVLocked.
3945 *
3946 * @param pLogger The logger.
3947 * @param fFlags The logging flags.
3948 * @param iGroup The group.
3949 * The value ~0U is reserved for compatibility with RTLogLogger[V] and is
3950 * only for internal usage!
3951 * @param pszFormat Format string.
3952 * @param ... Format arguments.
3953 */
3954static void rtlogLoggerExFLocked(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, ...)
3955{
3956 va_list va;
3957 va_start(va, pszFormat);
3958 rtlogLoggerExVLocked(pLogger, fFlags, iGroup, pszFormat, va);
3959 va_end(va);
3960}
3961#endif /* !IN_RC */
3962
Note: See TracBrowser for help on using the repository browser.

© 2024 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette