VirtualBox

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

Last change on this file since 56290 was 56290, checked in by vboxsync, 9 years ago

IPRT: Updated (C) year.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 130.0 KB
Line 
1/* $Id: log.cpp 56290 2015-06-09 14:01:31Z vboxsync $ */
2/** @file
3 * Runtime VBox - Logger.
4 */
5
6/*
7 * Copyright (C) 2006-2015 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 s_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 s_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, ~0, 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, ~0, 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(s_aLogFlags); i++)
2051 {
2052 if (!strncmp(pszValue, s_aLogFlags[i].pszInstr, s_aLogFlags[i].cchInstr))
2053 {
2054 if (fNo == s_aLogFlags[i].fInverted)
2055 pLogger->fFlags |= s_aLogFlags[i].fFlag;
2056 else
2057 pLogger->fFlags &= ~s_aLogFlags[i].fFlag;
2058 pszValue += s_aLogFlags[i].cchInstr;
2059 break;
2060 }
2061 }
2062
2063 /* unknown instruction? */
2064 if (i >= RT_ELEMENTS(s_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(s_aLogFlags); i++)
2177 if ( !s_aLogFlags[i].fInverted
2178 ? (s_aLogFlags[i].fFlag & fFlags)
2179 : !(s_aLogFlags[i].fFlag & fFlags))
2180 {
2181 size_t cchInstr = s_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, s_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 * Updates the logger destination using the specified string.
2205 *
2206 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
2207 * @param pLogger Logger instance (NULL for default logger).
2208 * @param pszValue The value to parse.
2209 */
2210RTDECL(int) RTLogDestinations(PRTLOGGER pLogger, char const *pszValue)
2211{
2212 /*
2213 * Resolve defaults.
2214 */
2215 if (!pLogger)
2216 {
2217 pLogger = RTLogDefaultInstance();
2218 if (!pLogger)
2219 return VINF_SUCCESS;
2220 }
2221
2222 /*
2223 * Do the parsing.
2224 */
2225 while (*pszValue)
2226 {
2227 bool fNo;
2228 unsigned i;
2229
2230 /* skip blanks. */
2231 while (RT_C_IS_SPACE(*pszValue))
2232 pszValue++;
2233 if (!*pszValue)
2234 break;
2235
2236 /* check no prefix. */
2237 fNo = false;
2238 if (pszValue[0] == 'n' && pszValue[1] == 'o')
2239 {
2240 fNo = true;
2241 pszValue += 2;
2242 }
2243
2244 /* instruction. */
2245 for (i = 0; i < RT_ELEMENTS(s_aLogDst); i++)
2246 {
2247 size_t cchInstr = strlen(s_aLogDst[i].pszInstr);
2248 if (!strncmp(pszValue, s_aLogDst[i].pszInstr, cchInstr))
2249 {
2250 if (!fNo)
2251 pLogger->fDestFlags |= s_aLogDst[i].fFlag;
2252 else
2253 pLogger->fDestFlags &= ~s_aLogDst[i].fFlag;
2254 pszValue += cchInstr;
2255
2256 /* check for value. */
2257 while (RT_C_IS_SPACE(*pszValue))
2258 pszValue++;
2259 if (*pszValue == '=' || *pszValue == ':')
2260 {
2261 const char *pszEnd;
2262
2263 pszValue++;
2264 pszEnd = strchr(pszValue, ';');
2265 if (!pszEnd)
2266 pszEnd = strchr(pszValue, '\0');
2267 size_t cch = pszEnd - pszValue;
2268# ifdef IN_RING3
2269 char szTmp[sizeof(pLogger->pInt->szFilename)];
2270# else
2271 char szTmp[32];
2272# endif
2273 if (0)
2274 { /* nothing */ }
2275#ifdef IN_RING3
2276
2277 /* log file name */
2278 else if (i == 0 /* file */ && !fNo)
2279 {
2280 AssertReturn(cch < sizeof(pLogger->pInt->szFilename), VERR_OUT_OF_RANGE);
2281 memcpy(pLogger->pInt->szFilename, pszValue, cch);
2282 pLogger->pInt->szFilename[cch] = '\0';
2283 /** @todo reopen log file if pLogger->pInt->fCreated is true ... */
2284 }
2285 /* log directory */
2286 else if (i == 1 /* dir */ && !fNo)
2287 {
2288 const char *pszFile = RTPathFilename(pLogger->pInt->szFilename);
2289 size_t cchFile = pszFile ? strlen(pszFile) : 0;
2290 AssertReturn(cchFile + cch + 1 < sizeof(pLogger->pInt->szFilename), VERR_OUT_OF_RANGE);
2291 memcpy(szTmp, cchFile ? pszFile : "", cchFile + 1);
2292
2293 memcpy(pLogger->pInt->szFilename, pszValue, cch);
2294 pLogger->pInt->szFilename[cch] = '\0';
2295 RTPathStripTrailingSlash(pLogger->pInt->szFilename);
2296
2297 cch = strlen(pLogger->pInt->szFilename);
2298 pLogger->pInt->szFilename[cch++] = '/';
2299 memcpy(&pLogger->pInt->szFilename[cch], szTmp, cchFile);
2300 pLogger->pInt->szFilename[cch + cchFile] = '\0';
2301 /** @todo reopen log file if pLogger->pInt->fCreated is true ... */
2302 }
2303 else if (i == 2 /* history */)
2304 {
2305 if (!fNo)
2306 {
2307 uint32_t cHistory = 0;
2308 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2309 if (RT_SUCCESS(rc))
2310 rc = RTStrToUInt32Full(szTmp, 0, &cHistory);
2311 AssertMsgReturn(RT_SUCCESS(rc) && cHistory < _1M, ("Invalid history value %s (%Rrc)!\n", szTmp, rc), rc);
2312 pLogger->pInt->cHistory = cHistory;
2313 }
2314 else
2315 pLogger->pInt->cHistory = 0;
2316 }
2317 else if (i == 3 /* histsize */)
2318 {
2319 if (!fNo)
2320 {
2321 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2322 if (RT_SUCCESS(rc))
2323 rc = RTStrToUInt64Full(szTmp, 0, &pLogger->pInt->cbHistoryFileMax);
2324 AssertMsgRCReturn(rc, ("Invalid history file size value %s (%Rrc)!\n", szTmp, rc), rc);
2325 if (pLogger->pInt->cbHistoryFileMax == 0)
2326 pLogger->pInt->cbHistoryFileMax = UINT64_MAX;
2327 }
2328 else
2329 pLogger->pInt->cbHistoryFileMax = UINT64_MAX;
2330 }
2331 else if (i == 4 /* histtime */)
2332 {
2333 if (!fNo)
2334 {
2335 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2336 if (RT_SUCCESS(rc))
2337 rc = RTStrToUInt32Full(szTmp, 0, &pLogger->pInt->cSecsHistoryTimeSlot);
2338 AssertMsgRCReturn(rc, ("Invalid history time slot value %s (%Rrc)!\n", szTmp, rc), rc);
2339 if (pLogger->pInt->cSecsHistoryTimeSlot == 0)
2340 pLogger->pInt->cSecsHistoryTimeSlot = UINT32_MAX;
2341 }
2342 else
2343 pLogger->pInt->cSecsHistoryTimeSlot = UINT32_MAX;
2344 }
2345# endif /* IN_RING3 */
2346 else if (i == 5 /* ringbuf */ && !fNo)
2347 {
2348 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2349 uint32_t cbRingBuf;
2350 if (RT_SUCCESS(rc))
2351 rc = RTStrToUInt32Full(szTmp, 0, &cbRingBuf);
2352 AssertMsgRCReturn(rc, ("Invalid ring buffer size value '%s' (%Rrc)!\n", szTmp, rc), rc);
2353
2354 if (cbRingBuf == 0)
2355 cbRingBuf = RTLOG_RINGBUF_DEFAULT_SIZE;
2356 else if (cbRingBuf < RTLOG_RINGBUF_MIN_SIZE)
2357 cbRingBuf = RTLOG_RINGBUF_MIN_SIZE;
2358 else if (cbRingBuf > RTLOG_RINGBUF_MAX_SIZE)
2359 cbRingBuf = RTLOG_RINGBUF_MAX_SIZE;
2360 else
2361 cbRingBuf = RT_ALIGN_32(cbRingBuf, 64);
2362 rc = rtLogRingBufAdjust(pLogger, cbRingBuf, false /*fForce*/);
2363 if (RT_FAILURE(rc))
2364 return rc;
2365 }
2366 else
2367 AssertMsgFailedReturn(("Invalid destination value! %s%s doesn't take a value!\n",
2368 fNo ? "no" : "", s_aLogDst[i].pszInstr),
2369 VERR_INVALID_PARAMETER);
2370
2371 pszValue = pszEnd + (*pszEnd != '\0');
2372 }
2373 else if (i == 5 /* ringbuf */ && !fNo && !pLogger->pInt->pszRingBuf)
2374 {
2375 int rc = rtLogRingBufAdjust(pLogger, pLogger->pInt->cbRingBuf, false /*fForce*/);
2376 if (RT_FAILURE(rc))
2377 return rc;
2378 }
2379 break;
2380 }
2381 }
2382
2383 /* assert known instruction */
2384 AssertMsgReturn(i < RT_ELEMENTS(s_aLogDst),
2385 ("Invalid destination value! unknown instruction %.20s\n", pszValue),
2386 VERR_INVALID_PARAMETER);
2387
2388 /* skip blanks and delimiters. */
2389 while (RT_C_IS_SPACE(*pszValue) || *pszValue == ';')
2390 pszValue++;
2391 } /* while more environment variable value left */
2392
2393 return VINF_SUCCESS;
2394}
2395RT_EXPORT_SYMBOL(RTLogDestinations);
2396
2397
2398/**
2399 * Get the current log destinations as a string.
2400 *
2401 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
2402 * @param pLogger Logger instance (NULL for default logger).
2403 * @param pszBuf The output buffer.
2404 * @param cchBuf The size of the output buffer. Must be greater
2405 * than 0.
2406 */
2407RTDECL(int) RTLogGetDestinations(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
2408{
2409 bool fNotFirst = false;
2410 int rc = VINF_SUCCESS;
2411 uint32_t fDestFlags;
2412 unsigned i;
2413
2414 AssertReturn(cchBuf, VERR_INVALID_PARAMETER);
2415 *pszBuf = '\0';
2416
2417 /*
2418 * Resolve defaults.
2419 */
2420 if (!pLogger)
2421 {
2422 pLogger = RTLogDefaultInstance();
2423 if (!pLogger)
2424 return VINF_SUCCESS;
2425 }
2426
2427 /*
2428 * Add the flags in the list.
2429 */
2430 fDestFlags = pLogger->fDestFlags;
2431 for (i = 6; i < RT_ELEMENTS(s_aLogDst); i++)
2432 if (s_aLogDst[i].fFlag & fDestFlags)
2433 {
2434 if (fNotFirst)
2435 {
2436 rc = RTStrCopyP(&pszBuf, &cchBuf, " ");
2437 if (RT_FAILURE(rc))
2438 return rc;
2439 }
2440 rc = RTStrCopyP(&pszBuf, &cchBuf, s_aLogDst[i].pszInstr);
2441 if (RT_FAILURE(rc))
2442 return rc;
2443 fNotFirst = true;
2444 }
2445
2446 char szNum[32];
2447
2448# ifdef IN_RING3
2449 /*
2450 * Add the filename.
2451 */
2452 if (fDestFlags & RTLOGDEST_FILE)
2453 {
2454 rc = RTStrCopyP(&pszBuf, &cchBuf, fNotFirst ? " file=" : "file=");
2455 if (RT_FAILURE(rc))
2456 return rc;
2457 rc = RTStrCopyP(&pszBuf, &cchBuf, pLogger->pInt->szFilename);
2458 if (RT_FAILURE(rc))
2459 return rc;
2460 fNotFirst = true;
2461
2462 if (pLogger->pInt->cHistory)
2463 {
2464 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " history=%u" : "history=%u", pLogger->pInt->cHistory);
2465 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2466 if (RT_FAILURE(rc))
2467 return rc;
2468 fNotFirst = true;
2469 }
2470 if (pLogger->pInt->cbHistoryFileMax != UINT64_MAX)
2471 {
2472 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " histsize=%llu" : "histsize=%llu", pLogger->pInt->cbHistoryFileMax);
2473 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2474 if (RT_FAILURE(rc))
2475 return rc;
2476 fNotFirst = true;
2477 }
2478 if (pLogger->pInt->cSecsHistoryTimeSlot != UINT32_MAX)
2479 {
2480 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " histtime=%llu" : "histtime=%llu", pLogger->pInt->cSecsHistoryTimeSlot);
2481 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2482 if (RT_FAILURE(rc))
2483 return rc;
2484 fNotFirst = true;
2485 }
2486 }
2487# endif /* IN_RING3 */
2488
2489 /*
2490 * Add the ring buffer.
2491 */
2492 if (fDestFlags & RTLOGDEST_RINGBUF)
2493 {
2494 if (pLogger->pInt->cbRingBuf == RTLOG_RINGBUF_DEFAULT_SIZE)
2495 rc = RTStrCopyP(&pszBuf, &cchBuf, fNotFirst ? " ringbuf" : "ringbuf");
2496 else
2497 {
2498 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " ringbuf=%#x" : "ringbuf=%#x", pLogger->pInt->cbRingBuf);
2499 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2500 }
2501 if (RT_FAILURE(rc))
2502 return rc;
2503 fNotFirst = true;
2504 }
2505
2506 return VINF_SUCCESS;
2507}
2508RT_EXPORT_SYMBOL(RTLogGetDestinations);
2509
2510#endif /* !IN_RC */
2511
2512/**
2513 * Flushes the specified logger.
2514 *
2515 * @param pLogger The logger instance to flush.
2516 * If NULL the default instance is used. The default instance
2517 * will not be initialized by this call.
2518 */
2519RTDECL(void) RTLogFlush(PRTLOGGER pLogger)
2520{
2521 /*
2522 * Resolve defaults.
2523 */
2524 if (!pLogger)
2525 {
2526#ifdef IN_RC
2527 pLogger = &g_Logger;
2528#else
2529 pLogger = g_pLogger;
2530#endif
2531 if (!pLogger)
2532 return;
2533 }
2534
2535 /*
2536 * Any thing to flush?
2537 */
2538 if ( pLogger->offScratch
2539#ifndef IN_RC
2540 || (pLogger->fDestFlags & RTLOGDEST_RINGBUF)
2541#endif
2542 )
2543 {
2544#ifndef IN_RC
2545 /*
2546 * Acquire logger instance sem.
2547 */
2548 int rc = rtlogLock(pLogger);
2549 if (RT_FAILURE(rc))
2550 return;
2551#endif
2552 /*
2553 * Call worker.
2554 */
2555 rtlogFlush(pLogger);
2556
2557#ifndef IN_RC
2558 /*
2559 * Since this is an explicit flush call, the ring buffer content should
2560 * be flushed to the other destinations if active.
2561 */
2562 if ( (pLogger->fDestFlags & RTLOGDEST_RINGBUF)
2563 && pLogger->pInt->pszRingBuf /* paranoia */)
2564 rtLogRingBufFlush(pLogger);
2565
2566 /*
2567 * Release the semaphore.
2568 */
2569 rtlogUnlock(pLogger);
2570#endif
2571 }
2572}
2573RT_EXPORT_SYMBOL(RTLogFlush);
2574
2575
2576/**
2577 * Common worker for RTLogDefaultInstance and RTLogDefaultInstanceEx.
2578 */
2579DECL_FORCE_INLINE(PRTLOGGER) rtLogDefaultInstanceCommon(void)
2580{
2581#ifdef IN_RC
2582 return &g_Logger;
2583
2584#else /* !IN_RC */
2585# ifdef IN_RING0
2586 /*
2587 * Check per thread loggers first.
2588 */
2589 if (g_cPerThreadLoggers)
2590 {
2591 const RTNATIVETHREAD Self = RTThreadNativeSelf();
2592 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
2593 while (i-- > 0)
2594 if (g_aPerThreadLoggers[i].NativeThread == Self)
2595 return g_aPerThreadLoggers[i].pLogger;
2596 }
2597# endif /* IN_RING0 */
2598
2599 /*
2600 * If no per thread logger, use the default one.
2601 */
2602 if (!g_pLogger)
2603 g_pLogger = RTLogDefaultInit();
2604 return g_pLogger;
2605#endif /* !IN_RC */
2606}
2607
2608
2609RTDECL(PRTLOGGER) RTLogDefaultInstance(void)
2610{
2611 return rtLogDefaultInstanceCommon();
2612}
2613RT_EXPORT_SYMBOL(RTLogDefaultInstance);
2614
2615
2616RTDECL(PRTLOGGER) RTLogDefaultInstanceEx(uint32_t fFlagsAndGroup)
2617{
2618 PRTLOGGER pLogger = rtLogDefaultInstanceCommon();
2619 if (pLogger)
2620 {
2621 if (pLogger->fFlags & RTLOGFLAGS_DISABLED)
2622 pLogger = NULL;
2623 else
2624 {
2625 uint16_t const fFlags = RT_LO_U16(fFlagsAndGroup);
2626 uint16_t const iGroup = RT_HI_U16(fFlagsAndGroup);
2627 if ( iGroup != UINT16_MAX
2628 && ( (pLogger->afGroups[iGroup < pLogger->cGroups ? iGroup : 0] & (fFlags | RTLOGGRPFLAGS_ENABLED))
2629 != (fFlags | RTLOGGRPFLAGS_ENABLED)))
2630 pLogger = NULL;
2631 }
2632 }
2633 return pLogger;
2634}
2635RT_EXPORT_SYMBOL(RTLogDefaultInstanceEx);
2636
2637
2638/**
2639 * Common worker for RTLogGetDefaultInstance and RTLogGetDefaultInstanceEx.
2640 */
2641DECL_FORCE_INLINE(PRTLOGGER) rtLogGetDefaultInstanceCommon(void)
2642{
2643#ifdef IN_RC
2644 return &g_Logger;
2645#else
2646# ifdef IN_RING0
2647 /*
2648 * Check per thread loggers first.
2649 */
2650 if (g_cPerThreadLoggers)
2651 {
2652 const RTNATIVETHREAD Self = RTThreadNativeSelf();
2653 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
2654 while (i-- > 0)
2655 if (g_aPerThreadLoggers[i].NativeThread == Self)
2656 return g_aPerThreadLoggers[i].pLogger;
2657 }
2658# endif /* IN_RING0 */
2659
2660 return g_pLogger;
2661#endif
2662}
2663
2664
2665RTDECL(PRTLOGGER) RTLogGetDefaultInstance(void)
2666{
2667 return rtLogGetDefaultInstanceCommon();
2668}
2669RT_EXPORT_SYMBOL(RTLogGetDefaultInstance);
2670
2671
2672RTDECL(PRTLOGGER) RTLogGetDefaultInstanceEx(uint32_t fFlagsAndGroup)
2673{
2674 PRTLOGGER pLogger = rtLogGetDefaultInstanceCommon();
2675 if (pLogger)
2676 {
2677 if (pLogger->fFlags & RTLOGFLAGS_DISABLED)
2678 pLogger = NULL;
2679 else
2680 {
2681 uint16_t const fFlags = RT_LO_U16(fFlagsAndGroup);
2682 uint16_t const iGroup = RT_HI_U16(fFlagsAndGroup);
2683 if ( iGroup != UINT16_MAX
2684 && ( (pLogger->afGroups[iGroup < pLogger->cGroups ? iGroup : 0] & (fFlags | RTLOGGRPFLAGS_ENABLED))
2685 != (fFlags | RTLOGGRPFLAGS_ENABLED)))
2686 pLogger = NULL;
2687 }
2688 }
2689 return pLogger;
2690}
2691RT_EXPORT_SYMBOL(RTLogGetDefaultInstanceEx);
2692
2693
2694#ifndef IN_RC
2695/**
2696 * Sets the default logger instance.
2697 *
2698 * @returns iprt status code.
2699 * @param pLogger The new default logger instance.
2700 */
2701RTDECL(PRTLOGGER) RTLogSetDefaultInstance(PRTLOGGER pLogger)
2702{
2703 return ASMAtomicXchgPtrT(&g_pLogger, pLogger, PRTLOGGER);
2704}
2705RT_EXPORT_SYMBOL(RTLogSetDefaultInstance);
2706#endif /* !IN_RC */
2707
2708
2709#ifdef IN_RING0
2710/**
2711 * Changes the default logger instance for the current thread.
2712 *
2713 * @returns IPRT status code.
2714 * @param pLogger The logger instance. Pass NULL for deregistration.
2715 * @param uKey Associated key for cleanup purposes. If pLogger is NULL,
2716 * all instances with this key will be deregistered. So in
2717 * order to only deregister the instance associated with the
2718 * current thread use 0.
2719 */
2720RTDECL(int) RTLogSetDefaultInstanceThread(PRTLOGGER pLogger, uintptr_t uKey)
2721{
2722 int rc;
2723 RTNATIVETHREAD Self = RTThreadNativeSelf();
2724 if (pLogger)
2725 {
2726 int32_t i;
2727 unsigned j;
2728
2729 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
2730
2731 /*
2732 * Iterate the table to see if there is already an entry for this thread.
2733 */
2734 i = RT_ELEMENTS(g_aPerThreadLoggers);
2735 while (i-- > 0)
2736 if (g_aPerThreadLoggers[i].NativeThread == Self)
2737 {
2738 ASMAtomicWritePtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, (void *)uKey);
2739 g_aPerThreadLoggers[i].pLogger = pLogger;
2740 return VINF_SUCCESS;
2741 }
2742
2743 /*
2744 * Allocate a new table entry.
2745 */
2746 i = ASMAtomicIncS32(&g_cPerThreadLoggers);
2747 if (i > (int32_t)RT_ELEMENTS(g_aPerThreadLoggers))
2748 {
2749 ASMAtomicDecS32(&g_cPerThreadLoggers);
2750 return VERR_BUFFER_OVERFLOW; /* horrible error code! */
2751 }
2752
2753 for (j = 0; j < 10; j++)
2754 {
2755 i = RT_ELEMENTS(g_aPerThreadLoggers);
2756 while (i-- > 0)
2757 {
2758 AssertCompile(sizeof(RTNATIVETHREAD) == sizeof(void*));
2759 if ( g_aPerThreadLoggers[i].NativeThread == NIL_RTNATIVETHREAD
2760 && ASMAtomicCmpXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].NativeThread, (void *)Self, (void *)NIL_RTNATIVETHREAD))
2761 {
2762 ASMAtomicWritePtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, (void *)uKey);
2763 ASMAtomicWritePtr(&g_aPerThreadLoggers[i].pLogger, pLogger);
2764 return VINF_SUCCESS;
2765 }
2766 }
2767 }
2768
2769 ASMAtomicDecS32(&g_cPerThreadLoggers);
2770 rc = VERR_INTERNAL_ERROR;
2771 }
2772 else
2773 {
2774 /*
2775 * Search the array for the current thread.
2776 */
2777 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
2778 while (i-- > 0)
2779 if ( g_aPerThreadLoggers[i].NativeThread == Self
2780 || g_aPerThreadLoggers[i].uKey == uKey)
2781 {
2782 ASMAtomicWriteNullPtr((void * volatile *)&g_aPerThreadLoggers[i].uKey);
2783 ASMAtomicWriteNullPtr(&g_aPerThreadLoggers[i].pLogger);
2784 ASMAtomicWriteHandle(&g_aPerThreadLoggers[i].NativeThread, NIL_RTNATIVETHREAD);
2785 ASMAtomicDecS32(&g_cPerThreadLoggers);
2786 }
2787
2788 rc = VINF_SUCCESS;
2789 }
2790 return rc;
2791}
2792RT_EXPORT_SYMBOL(RTLogSetDefaultInstanceThread);
2793#endif /* IN_RING0 */
2794
2795
2796/**
2797 * Write to a logger instance.
2798 *
2799 * @param pLogger Pointer to logger instance.
2800 * @param pszFormat Format string.
2801 * @param args Format arguments.
2802 */
2803RTDECL(void) RTLogLoggerV(PRTLOGGER pLogger, const char *pszFormat, va_list args)
2804{
2805 RTLogLoggerExV(pLogger, 0, ~0U, pszFormat, args);
2806}
2807RT_EXPORT_SYMBOL(RTLogLoggerV);
2808
2809
2810/**
2811 * Write to a logger instance.
2812 *
2813 * This function will check whether the instance, group and flags makes up a
2814 * logging kind which is currently enabled before writing anything to the log.
2815 *
2816 * @param pLogger Pointer to logger instance. If NULL the default logger instance will be attempted.
2817 * @param fFlags The logging flags.
2818 * @param iGroup The group.
2819 * The value ~0U is reserved for compatibility with RTLogLogger[V] and is
2820 * only for internal usage!
2821 * @param pszFormat Format string.
2822 * @param args Format arguments.
2823 */
2824RTDECL(void) RTLogLoggerExV(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args)
2825{
2826 int rc;
2827
2828 /*
2829 * A NULL logger means default instance.
2830 */
2831 if (!pLogger)
2832 {
2833 pLogger = RTLogDefaultInstance();
2834 if (!pLogger)
2835 return;
2836 }
2837
2838 /*
2839 * Validate and correct iGroup.
2840 */
2841 if (iGroup != ~0U && iGroup >= pLogger->cGroups)
2842 iGroup = 0;
2843
2844 /*
2845 * If no output, then just skip it.
2846 */
2847 if ( (pLogger->fFlags & RTLOGFLAGS_DISABLED)
2848#ifndef IN_RC
2849 || !pLogger->fDestFlags
2850#endif
2851 || !pszFormat || !*pszFormat)
2852 return;
2853 if ( iGroup != ~0U
2854 && (pLogger->afGroups[iGroup] & (fFlags | RTLOGGRPFLAGS_ENABLED)) != (fFlags | RTLOGGRPFLAGS_ENABLED))
2855 return;
2856
2857 /*
2858 * Acquire logger instance sem.
2859 */
2860 rc = rtlogLock(pLogger);
2861 if (RT_FAILURE(rc))
2862 {
2863#ifdef IN_RING0
2864 if (pLogger->fDestFlags & ~RTLOGDEST_FILE)
2865 rtR0LogLoggerExFallback(pLogger->fDestFlags, pLogger->fFlags, pLogger->pInt, pszFormat, args);
2866#endif
2867 return;
2868 }
2869
2870 /*
2871 * Check restrictions and call worker.
2872 */
2873#ifndef IN_RC
2874 if (RT_UNLIKELY( (pLogger->fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
2875 && iGroup < pLogger->cGroups
2876 && (pLogger->afGroups[iGroup] & RTLOGGRPFLAGS_RESTRICT)
2877 && ++pLogger->pInt->pacEntriesPerGroup[iGroup] >= pLogger->pInt->cMaxEntriesPerGroup ))
2878 {
2879 uint32_t cEntries = pLogger->pInt->pacEntriesPerGroup[iGroup];
2880 if (cEntries > pLogger->pInt->cMaxEntriesPerGroup)
2881 pLogger->pInt->pacEntriesPerGroup[iGroup] = cEntries - 1;
2882 else
2883 {
2884 rtlogLoggerExVLocked(pLogger, fFlags, iGroup, pszFormat, args);
2885 if ( pLogger->pInt->papszGroups
2886 && pLogger->pInt->papszGroups[iGroup])
2887 rtlogLoggerExFLocked(pLogger, fFlags, iGroup, "%u messages from group %s (#%u), muting it.\n",
2888 cEntries, pLogger->pInt->papszGroups[iGroup], iGroup);
2889 else
2890 rtlogLoggerExFLocked(pLogger, fFlags, iGroup, "%u messages from group #%u, muting it.\n",
2891 cEntries, iGroup);
2892 }
2893 }
2894 else
2895#endif
2896 rtlogLoggerExVLocked(pLogger, fFlags, iGroup, pszFormat, args);
2897
2898 /*
2899 * Release the semaphore.
2900 */
2901 rtlogUnlock(pLogger);
2902}
2903RT_EXPORT_SYMBOL(RTLogLoggerExV);
2904
2905
2906#ifdef IN_RING0
2907/**
2908 * For rtR0LogLoggerExFallbackOutput and rtR0LogLoggerExFallbackFlush.
2909 */
2910typedef struct RTR0LOGLOGGERFALLBACK
2911{
2912 /** The current scratch buffer offset. */
2913 uint32_t offScratch;
2914 /** The destination flags. */
2915 uint32_t fDestFlags;
2916 /** For ring buffer output. */
2917 PRTLOGGERINTERNAL pInt;
2918 /** The scratch buffer. */
2919 char achScratch[80];
2920} RTR0LOGLOGGERFALLBACK;
2921/** Pointer to RTR0LOGLOGGERFALLBACK which is used by
2922 * rtR0LogLoggerExFallbackOutput. */
2923typedef RTR0LOGLOGGERFALLBACK *PRTR0LOGLOGGERFALLBACK;
2924
2925
2926/**
2927 * Flushes the fallback buffer.
2928 *
2929 * @param pThis The scratch buffer.
2930 */
2931static void rtR0LogLoggerExFallbackFlush(PRTR0LOGLOGGERFALLBACK pThis)
2932{
2933 if (!pThis->offScratch)
2934 return;
2935
2936 if ( (pThis->fDestFlags & RTLOGDEST_RINGBUF)
2937 && pThis->pInt
2938 && pThis->pInt->pszRingBuf /* paranoia */)
2939 rtLogRingBufWrite(pThis->pInt, pThis->achScratch, pThis->offScratch);
2940 else
2941 {
2942 if (pThis->fDestFlags & RTLOGDEST_USER)
2943 RTLogWriteUser(pThis->achScratch, pThis->offScratch);
2944
2945 if (pThis->fDestFlags & RTLOGDEST_DEBUGGER)
2946 RTLogWriteDebugger(pThis->achScratch, pThis->offScratch);
2947
2948 if (pThis->fDestFlags & RTLOGDEST_STDOUT)
2949 RTLogWriteStdOut(pThis->achScratch, pThis->offScratch);
2950
2951 if (pThis->fDestFlags & RTLOGDEST_STDERR)
2952 RTLogWriteStdErr(pThis->achScratch, pThis->offScratch);
2953
2954# ifndef LOG_NO_COM
2955 if (pThis->fDestFlags & RTLOGDEST_COM)
2956 RTLogWriteCom(pThis->achScratch, pThis->offScratch);
2957# endif
2958 }
2959
2960 /* empty the buffer. */
2961 pThis->offScratch = 0;
2962}
2963
2964
2965/**
2966 * Callback for RTLogFormatV used by rtR0LogLoggerExFallback.
2967 * See PFNLOGOUTPUT() for details.
2968 */
2969static DECLCALLBACK(size_t) rtR0LogLoggerExFallbackOutput(void *pv, const char *pachChars, size_t cbChars)
2970{
2971 PRTR0LOGLOGGERFALLBACK pThis = (PRTR0LOGLOGGERFALLBACK)pv;
2972 if (cbChars)
2973 {
2974 size_t cbRet = 0;
2975 for (;;)
2976 {
2977 /* how much */
2978 uint32_t cb = sizeof(pThis->achScratch) - pThis->offScratch - 1; /* minus 1 - for the string terminator. */
2979 if (cb > cbChars)
2980 cb = (uint32_t)cbChars;
2981
2982 /* copy */
2983 memcpy(&pThis->achScratch[pThis->offScratch], pachChars, cb);
2984
2985 /* advance */
2986 pThis->offScratch += cb;
2987 cbRet += cb;
2988 cbChars -= cb;
2989
2990 /* done? */
2991 if (cbChars <= 0)
2992 return cbRet;
2993
2994 pachChars += cb;
2995
2996 /* flush */
2997 pThis->achScratch[pThis->offScratch] = '\0';
2998 rtR0LogLoggerExFallbackFlush(pThis);
2999 }
3000
3001 /* won't ever get here! */
3002 }
3003 else
3004 {
3005 /*
3006 * Termination call, flush the log.
3007 */
3008 pThis->achScratch[pThis->offScratch] = '\0';
3009 rtR0LogLoggerExFallbackFlush(pThis);
3010 return 0;
3011 }
3012}
3013
3014
3015/**
3016 * Ring-0 fallback for cases where we're unable to grab the lock.
3017 *
3018 * This will happen when we're at a too high IRQL on Windows for instance and
3019 * needs to be dealt with or we'll drop a lot of log output. This fallback will
3020 * only output to some of the log destinations as a few of them may be doing
3021 * dangerous things. We won't be doing any prefixing here either, at least not
3022 * for the present, because it's too much hassle.
3023 *
3024 * @param fDestFlags The destination flags.
3025 * @param fFlags The logger flags.
3026 * @param pInt The internal logger data, for ring buffer output.
3027 * @param pszFormat The format string.
3028 * @param va The format arguments.
3029 */
3030static void rtR0LogLoggerExFallback(uint32_t fDestFlags, uint32_t fFlags, PRTLOGGERINTERNAL pInt,
3031 const char *pszFormat, va_list va)
3032{
3033 RTR0LOGLOGGERFALLBACK This;
3034 This.fDestFlags = fDestFlags;
3035 This.pInt = pInt;
3036
3037 /* fallback indicator. */
3038 This.offScratch = 2;
3039 This.achScratch[0] = '[';
3040 This.achScratch[1] = 'F';
3041
3042 /* selected prefixes */
3043 if (fFlags & RTLOGFLAGS_PREFIX_PID)
3044 {
3045 RTPROCESS Process = RTProcSelf();
3046 This.achScratch[This.offScratch++] = ' ';
3047 This.offScratch += RTStrFormatNumber(&This.achScratch[This.offScratch], Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
3048 }
3049 if (fFlags & RTLOGFLAGS_PREFIX_TID)
3050 {
3051 RTNATIVETHREAD Thread = RTThreadNativeSelf();
3052 This.achScratch[This.offScratch++] = ' ';
3053 This.offScratch += RTStrFormatNumber(&This.achScratch[This.offScratch], Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
3054 }
3055
3056 This.achScratch[This.offScratch++] = ']';
3057 This.achScratch[This.offScratch++] = ' ';
3058
3059 RTLogFormatV(rtR0LogLoggerExFallbackOutput, &This, pszFormat, va);
3060}
3061#endif /* IN_RING0 */
3062
3063
3064/**
3065 * vprintf like function for writing to the default log.
3066 *
3067 * @param pszFormat Printf like format string.
3068 * @param args Optional arguments as specified in pszFormat.
3069 *
3070 * @remark The API doesn't support formatting of floating point numbers at the moment.
3071 */
3072RTDECL(void) RTLogPrintfV(const char *pszFormat, va_list args)
3073{
3074 RTLogLoggerV(NULL, pszFormat, args);
3075}
3076RT_EXPORT_SYMBOL(RTLogPrintfV);
3077
3078
3079/**
3080 * Dumper vprintf-like function outputting to a logger.
3081 *
3082 * @param pvUser Pointer to the logger instance to use, NULL for
3083 * default instance.
3084 * @param pszFormat Format string.
3085 * @param va Format arguments.
3086 */
3087RTDECL(void) RTLogDumpPrintfV(void *pvUser, const char *pszFormat, va_list va)
3088{
3089 RTLogLoggerV((PRTLOGGER)pvUser, pszFormat, va);
3090}
3091RT_EXPORT_SYMBOL(RTLogDumpPrintfV);
3092
3093
3094#ifdef IN_RING3
3095
3096/**
3097 * Opens/creates the log file.
3098 *
3099 * @param pLogger The logger instance to update. NULL is not allowed!
3100 * @param pszErrorMsg A buffer which is filled with an error message if
3101 * something fails. May be NULL.
3102 * @param cchErrorMsg The size of the error message buffer.
3103 */
3104static int rtlogFileOpen(PRTLOGGER pLogger, char *pszErrorMsg, size_t cchErrorMsg)
3105{
3106 uint32_t fOpen = RTFILE_O_WRITE | RTFILE_O_DENY_NONE;
3107 if (pLogger->fFlags & RTLOGFLAGS_APPEND)
3108 fOpen |= RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND;
3109 else
3110 fOpen |= RTFILE_O_CREATE_REPLACE;
3111 if (pLogger->fFlags & RTLOGFLAGS_WRITE_THROUGH)
3112 fOpen |= RTFILE_O_WRITE_THROUGH;
3113
3114 unsigned cBackoff = 0;
3115 int rc = RTFileOpen(&pLogger->pInt->hFile, pLogger->pInt->szFilename, fOpen);
3116 while ( rc == VERR_SHARING_VIOLATION
3117 && cBackoff < RT_ELEMENTS(g_acMsLogBackoff))
3118 {
3119 RTThreadSleep(g_acMsLogBackoff[cBackoff++]);
3120 rc = RTFileOpen(&pLogger->pInt->hFile, pLogger->pInt->szFilename, fOpen);
3121 }
3122 if (RT_SUCCESS(rc))
3123 {
3124 rc = RTFileGetSize(pLogger->pInt->hFile, &pLogger->pInt->cbHistoryFileWritten);
3125 if (RT_FAILURE(rc))
3126 {
3127 /* Don't complain if this fails, assume the file is empty. */
3128 pLogger->pInt->cbHistoryFileWritten = 0;
3129 rc = VINF_SUCCESS;
3130 }
3131 }
3132 else
3133 {
3134 pLogger->pInt->hFile = NIL_RTFILE;
3135 if (pszErrorMsg)
3136 RTStrPrintf(pszErrorMsg, cchErrorMsg, N_("could not open file '%s' (fOpen=%#x)"), pLogger->pInt->szFilename, fOpen);
3137 }
3138 return rc;
3139}
3140
3141
3142/**
3143 * Closes, rotates and opens the log files if necessary.
3144 *
3145 * Used by the rtlogFlush() function as well as RTLogCreateExV.
3146 *
3147 * @param pLogger The logger instance to update. NULL is not allowed!
3148 * @param uTimeSlit Current time slot (for tikme based rotation).
3149 * @param fFirst Flag whether this is the beginning of logging, i.e.
3150 * called from RTLogCreateExV. Prevents pfnPhase from
3151 * being called.
3152 */
3153static void rtlogRotate(PRTLOGGER pLogger, uint32_t uTimeSlot, bool fFirst)
3154{
3155 /* Suppress rotating empty log files simply because the time elapsed. */
3156 if (RT_UNLIKELY(!pLogger->pInt->cbHistoryFileWritten))
3157 pLogger->pInt->uHistoryTimeSlotStart = uTimeSlot;
3158
3159 /* Check rotation condition: file still small enough and not too old? */
3160 if (RT_LIKELY( pLogger->pInt->cbHistoryFileWritten < pLogger->pInt->cbHistoryFileMax
3161 && uTimeSlot == pLogger->pInt->uHistoryTimeSlotStart))
3162 return;
3163
3164 /*
3165 * Save "disabled" log flag and make sure logging is disabled.
3166 * The logging in the functions called during log file history
3167 * rotation would cause severe trouble otherwise.
3168 */
3169 uint32_t const fSavedFlags = pLogger->fFlags;
3170 pLogger->fFlags |= RTLOGFLAGS_DISABLED;
3171
3172 /*
3173 * Disable log rotation temporarily, otherwise with extreme settings and
3174 * chatty phase logging we could run into endless rotation.
3175 */
3176 uint32_t const cSavedHistory = pLogger->pInt->cHistory;
3177 pLogger->pInt->cHistory = 0;
3178
3179 /*
3180 * Close the old log file.
3181 */
3182 if (pLogger->pInt->hFile != NIL_RTFILE)
3183 {
3184 /* Use the callback to generate some final log contents, but only if
3185 * this is a rotation with a fully set up logger. Leave the other case
3186 * to the RTLogCreateExV function. */
3187 if (pLogger->pInt->pfnPhase && !fFirst)
3188 {
3189 uint32_t fODestFlags = pLogger->fDestFlags;
3190 pLogger->fDestFlags &= RTLOGDEST_FILE;
3191 pLogger->pInt->pfnPhase(pLogger, RTLOGPHASE_PREROTATE, rtlogPhaseMsgLocked);
3192 pLogger->fDestFlags = fODestFlags;
3193 }
3194 RTFileClose(pLogger->pInt->hFile);
3195 pLogger->pInt->hFile = NIL_RTFILE;
3196 }
3197
3198 if (cSavedHistory)
3199 {
3200 /*
3201 * Rotate the log files.
3202 */
3203 for (uint32_t i = cSavedHistory - 1; i + 1 > 0; i--)
3204 {
3205 char szOldName[sizeof(pLogger->pInt->szFilename) + 32];
3206 if (i > 0)
3207 RTStrPrintf(szOldName, sizeof(szOldName), "%s.%u", pLogger->pInt->szFilename, i);
3208 else
3209 RTStrCopy(szOldName, sizeof(szOldName), pLogger->pInt->szFilename);
3210
3211 char szNewName[sizeof(pLogger->pInt->szFilename) + 32];
3212 RTStrPrintf(szNewName, sizeof(szNewName), "%s.%u", pLogger->pInt->szFilename, i + 1);
3213
3214 unsigned cBackoff = 0;
3215 int rc = RTFileRename(szOldName, szNewName, RTFILEMOVE_FLAGS_REPLACE);
3216 while ( rc == VERR_SHARING_VIOLATION
3217 && cBackoff < RT_ELEMENTS(g_acMsLogBackoff))
3218 {
3219 RTThreadSleep(g_acMsLogBackoff[cBackoff++]);
3220 rc = RTFileRename(szOldName, szNewName, RTFILEMOVE_FLAGS_REPLACE);
3221 }
3222
3223 if (rc == VERR_FILE_NOT_FOUND)
3224 RTFileDelete(szNewName);
3225 }
3226
3227 /*
3228 * Delete excess log files.
3229 */
3230 for (uint32_t i = cSavedHistory + 1; ; i++)
3231 {
3232 char szExcessName[sizeof(pLogger->pInt->szFilename) + 32];
3233 RTStrPrintf(szExcessName, sizeof(szExcessName), "%s.%u", pLogger->pInt->szFilename, i);
3234 int rc = RTFileDelete(szExcessName);
3235 if (RT_FAILURE(rc))
3236 break;
3237 }
3238 }
3239
3240 /*
3241 * Update logger state and create new log file.
3242 */
3243 pLogger->pInt->cbHistoryFileWritten = 0;
3244 pLogger->pInt->uHistoryTimeSlotStart = uTimeSlot;
3245 rtlogFileOpen(pLogger, NULL, 0);
3246
3247 /*
3248 * Use the callback to generate some initial log contents, but only if this
3249 * is a rotation with a fully set up logger. Leave the other case to the
3250 * RTLogCreateExV function.
3251 */
3252 if (pLogger->pInt->pfnPhase && !fFirst)
3253 {
3254 uint32_t const fSavedDestFlags = pLogger->fDestFlags;
3255 pLogger->fDestFlags &= RTLOGDEST_FILE;
3256 pLogger->pInt->pfnPhase(pLogger, RTLOGPHASE_POSTROTATE, rtlogPhaseMsgLocked);
3257 pLogger->fDestFlags = fSavedDestFlags;
3258 }
3259
3260 /* Restore saved values. */
3261 pLogger->pInt->cHistory = cSavedHistory;
3262 pLogger->fFlags = fSavedFlags;
3263}
3264
3265#endif /* IN_RING3 */
3266
3267
3268/**
3269 * Writes the buffer to the given log device without checking for buffered
3270 * data or anything.
3271 * Used by the RTLogFlush() function.
3272 *
3273 * @param pLogger The logger instance to write to. NULL is not allowed!
3274 */
3275static void rtlogFlush(PRTLOGGER pLogger)
3276{
3277 uint32_t const cchScratch = pLogger->offScratch;
3278 if (cchScratch == 0)
3279 return; /* nothing to flush. */
3280
3281#ifndef IN_RC
3282 /*
3283 * If the ring buffer is active, the other destinations are only written
3284 * to when the ring buffer is flushed by RTLogFlush().
3285 */
3286 if ( (pLogger->fDestFlags & RTLOGDEST_RINGBUF)
3287 && pLogger->pInt
3288 && pLogger->pInt->pszRingBuf /* paraoia */)
3289 {
3290 rtLogRingBufWrite(pLogger->pInt, pLogger->achScratch, pLogger->offScratch);
3291 pLogger->offScratch = 0; /* empty the buffer. */
3292 }
3293 else
3294#endif
3295 {
3296 /* Make sure the string is terminated. On Windows, RTLogWriteDebugger
3297 will get upset if it isn't. */
3298 if (RT_LIKELY(cchScratch < sizeof(pLogger->achScratch)))
3299 pLogger->achScratch[cchScratch] = '\0';
3300 else
3301 AssertFailed();
3302
3303#ifndef IN_RC
3304 if (pLogger->fDestFlags & RTLOGDEST_USER)
3305 RTLogWriteUser(pLogger->achScratch, cchScratch);
3306
3307 if (pLogger->fDestFlags & RTLOGDEST_DEBUGGER)
3308 RTLogWriteDebugger(pLogger->achScratch, cchScratch);
3309
3310# ifdef IN_RING3
3311 if ((pLogger->fDestFlags & (RTLOGDEST_FILE | RTLOGDEST_RINGBUF)) == RTLOGDEST_FILE)
3312 {
3313 if (pLogger->pInt->hFile != NIL_RTFILE)
3314 {
3315 RTFileWrite(pLogger->pInt->hFile, pLogger->achScratch, cchScratch, NULL);
3316 if (pLogger->fFlags & RTLOGFLAGS_FLUSH)
3317 RTFileFlush(pLogger->pInt->hFile);
3318 }
3319 if (pLogger->pInt->cHistory)
3320 pLogger->pInt->cbHistoryFileWritten += cchScratch;
3321 }
3322# endif
3323
3324 if (pLogger->fDestFlags & RTLOGDEST_STDOUT)
3325 RTLogWriteStdOut(pLogger->achScratch, cchScratch);
3326
3327 if (pLogger->fDestFlags & RTLOGDEST_STDERR)
3328 RTLogWriteStdErr(pLogger->achScratch, cchScratch);
3329
3330# if (defined(IN_RING0) || defined(IN_RC)) && !defined(LOG_NO_COM)
3331 if (pLogger->fDestFlags & RTLOGDEST_COM)
3332 RTLogWriteCom(pLogger->achScratch, cchScratch);
3333# endif
3334#endif /* !IN_RC */
3335
3336#ifdef IN_RC
3337 if (pLogger->pfnFlush)
3338 pLogger->pfnFlush(pLogger);
3339#else
3340 if (pLogger->pInt->pfnFlush)
3341 pLogger->pInt->pfnFlush(pLogger);
3342#endif
3343
3344 /* empty the buffer. */
3345 pLogger->offScratch = 0;
3346
3347#ifdef IN_RING3
3348 /*
3349 * Rotate the log file if configured. Must be done after everything is
3350 * flushed, since this will also use logging/flushing to write the header
3351 * and footer messages.
3352 */
3353 if ( (pLogger->fDestFlags & RTLOGDEST_FILE)
3354 && pLogger->pInt->cHistory)
3355 rtlogRotate(pLogger, RTTimeProgramSecTS() / pLogger->pInt->cSecsHistoryTimeSlot, false /* fFirst */);
3356#endif
3357 }
3358}
3359
3360
3361/**
3362 * Callback for RTLogFormatV which writes to the com port.
3363 * See PFNLOGOUTPUT() for details.
3364 */
3365static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
3366{
3367 PRTLOGGER pLogger = (PRTLOGGER)pv;
3368 if (cbChars)
3369 {
3370 size_t cbRet = 0;
3371 for (;;)
3372 {
3373#if defined(DEBUG) && defined(IN_RING3)
3374 /* sanity */
3375 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
3376 {
3377 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
3378 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
3379 AssertBreakpoint(); AssertBreakpoint();
3380 }
3381#endif
3382
3383 /* how much */
3384 size_t cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3385 if (cb > cbChars)
3386 cb = cbChars;
3387
3388 /* copy */
3389 memcpy(&pLogger->achScratch[pLogger->offScratch], pachChars, cb);
3390
3391 /* advance */
3392 pLogger->offScratch += (uint32_t)cb;
3393 cbRet += cb;
3394 cbChars -= cb;
3395
3396 /* done? */
3397 if (cbChars <= 0)
3398 return cbRet;
3399
3400 pachChars += cb;
3401
3402 /* flush */
3403 rtlogFlush(pLogger);
3404 }
3405
3406 /* won't ever get here! */
3407 }
3408 else
3409 {
3410 /*
3411 * Termination call.
3412 * There's always space for a terminator, and it's not counted.
3413 */
3414 pLogger->achScratch[pLogger->offScratch] = '\0';
3415 return 0;
3416 }
3417}
3418
3419
3420/**
3421 * stpncpy implementation for use in rtLogOutputPrefixed w/ padding.
3422 *
3423 * @returns Pointer to the destination buffer byte following the copied string.
3424 * @param pszDst The destination buffer.
3425 * @param pszSrc The source string.
3426 * @param cchSrcMax The maximum number of characters to copy from
3427 * the string.
3428 * @param cchMinWidth The minimum field with, padd with spaces to
3429 * reach this.
3430 */
3431DECLINLINE(char *) rtLogStPNCpyPad(char *pszDst, const char *pszSrc, size_t cchSrcMax, size_t cchMinWidth)
3432{
3433 size_t cchSrc = 0;
3434 if (pszSrc)
3435 {
3436 cchSrc = strlen(pszSrc);
3437 if (cchSrc > cchSrcMax)
3438 cchSrc = cchSrcMax;
3439
3440 memcpy(pszDst, pszSrc, cchSrc);
3441 pszDst += cchSrc;
3442 }
3443 do
3444 *pszDst++ = ' ';
3445 while (cchSrc++ < cchMinWidth);
3446
3447 return pszDst;
3448}
3449
3450
3451
3452/**
3453 * Callback for RTLogFormatV which writes to the logger instance.
3454 * This version supports prefixes.
3455 *
3456 * See PFNLOGOUTPUT() for details.
3457 */
3458static DECLCALLBACK(size_t) rtLogOutputPrefixed(void *pv, const char *pachChars, size_t cbChars)
3459{
3460 PRTLOGOUTPUTPREFIXEDARGS pArgs = (PRTLOGOUTPUTPREFIXEDARGS)pv;
3461 PRTLOGGER pLogger = pArgs->pLogger;
3462 if (cbChars)
3463 {
3464 size_t cbRet = 0;
3465 for (;;)
3466 {
3467 size_t cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3468 const char *pszNewLine;
3469 char *psz;
3470#ifdef IN_RC
3471 bool *pfPendingPrefix = &pLogger->fPendingPrefix;
3472#else
3473 bool *pfPendingPrefix = &pLogger->pInt->fPendingPrefix;
3474#endif
3475
3476 /*
3477 * Pending prefix?
3478 */
3479 if (*pfPendingPrefix)
3480 {
3481 *pfPendingPrefix = false;
3482
3483#if defined(DEBUG) && defined(IN_RING3)
3484 /* sanity */
3485 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
3486 {
3487 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
3488 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
3489 AssertBreakpoint(); AssertBreakpoint();
3490 }
3491#endif
3492
3493 /*
3494 * Flush the buffer if there isn't enough room for the maximum prefix config.
3495 * Max is 256, add a couple of extra bytes. See CCH_PREFIX check way below.
3496 */
3497 if (cb < 256 + 16)
3498 {
3499 rtlogFlush(pLogger);
3500 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3501 }
3502
3503 /*
3504 * Write the prefixes.
3505 * psz is pointing to the current position.
3506 */
3507 psz = &pLogger->achScratch[pLogger->offScratch];
3508 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TS)
3509 {
3510 uint64_t u64 = RTTimeNanoTS();
3511 int iBase = 16;
3512 unsigned int fFlags = RTSTR_F_ZEROPAD;
3513 if (pLogger->fFlags & RTLOGFLAGS_DECIMAL_TS)
3514 {
3515 iBase = 10;
3516 fFlags = 0;
3517 }
3518 if (pLogger->fFlags & RTLOGFLAGS_REL_TS)
3519 {
3520 static volatile uint64_t s_u64LastTs;
3521 uint64_t u64DiffTs = u64 - s_u64LastTs;
3522 s_u64LastTs = u64;
3523 /* We could have been preempted just before reading of s_u64LastTs by
3524 * another thread which wrote s_u64LastTs. In that case the difference
3525 * is negative which we simply ignore. */
3526 u64 = (int64_t)u64DiffTs < 0 ? 0 : u64DiffTs;
3527 }
3528 /* 1E15 nanoseconds = 11 days */
3529 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags);
3530 *psz++ = ' ';
3531 }
3532#define CCH_PREFIX_01 0 + 17
3533
3534 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TSC)
3535 {
3536#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
3537 uint64_t u64 = ASMReadTSC();
3538#else
3539 uint64_t u64 = RTTimeNanoTS();
3540#endif
3541 int iBase = 16;
3542 unsigned int fFlags = RTSTR_F_ZEROPAD;
3543 if (pLogger->fFlags & RTLOGFLAGS_DECIMAL_TS)
3544 {
3545 iBase = 10;
3546 fFlags = 0;
3547 }
3548 if (pLogger->fFlags & RTLOGFLAGS_REL_TS)
3549 {
3550 static volatile uint64_t s_u64LastTsc;
3551 int64_t i64DiffTsc = u64 - s_u64LastTsc;
3552 s_u64LastTsc = u64;
3553 /* We could have been preempted just before reading of s_u64LastTsc by
3554 * another thread which wrote s_u64LastTsc. In that case the difference
3555 * is negative which we simply ignore. */
3556 u64 = i64DiffTsc < 0 ? 0 : i64DiffTsc;
3557 }
3558 /* 1E15 ticks at 4GHz = 69 hours */
3559 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags);
3560 *psz++ = ' ';
3561 }
3562#define CCH_PREFIX_02 CCH_PREFIX_01 + 17
3563
3564 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_MS_PROG)
3565 {
3566#if defined(IN_RING3) || defined(IN_RC)
3567 uint64_t u64 = RTTimeProgramMilliTS();
3568#else
3569 uint64_t u64 = 0;
3570#endif
3571 /* 1E8 milliseconds = 27 hours */
3572 psz += RTStrFormatNumber(psz, u64, 10, 9, 0, RTSTR_F_ZEROPAD);
3573 *psz++ = ' ';
3574 }
3575#define CCH_PREFIX_03 CCH_PREFIX_02 + 21
3576
3577 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TIME)
3578 {
3579#if defined(IN_RING3) || defined(IN_RING0)
3580 RTTIMESPEC TimeSpec;
3581 RTTIME Time;
3582 RTTimeExplode(&Time, RTTimeNow(&TimeSpec));
3583 psz += RTStrFormatNumber(psz, Time.u8Hour, 10, 2, 0, RTSTR_F_ZEROPAD);
3584 *psz++ = ':';
3585 psz += RTStrFormatNumber(psz, Time.u8Minute, 10, 2, 0, RTSTR_F_ZEROPAD);
3586 *psz++ = ':';
3587 psz += RTStrFormatNumber(psz, Time.u8Second, 10, 2, 0, RTSTR_F_ZEROPAD);
3588 *psz++ = '.';
3589 psz += RTStrFormatNumber(psz, Time.u32Nanosecond / 1000, 10, 6, 0, RTSTR_F_ZEROPAD);
3590 *psz++ = ' ';
3591#else
3592 memset(psz, ' ', 16);
3593 psz += 16;
3594#endif
3595 }
3596#define CCH_PREFIX_04 CCH_PREFIX_03 + (3+1+3+1+3+1+7+1)
3597
3598 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TIME_PROG)
3599 {
3600
3601#if defined(IN_RING3) || defined(IN_RC)
3602 uint64_t u64 = RTTimeProgramMicroTS();
3603 psz += RTStrFormatNumber(psz, (uint32_t)(u64 / RT_US_1HOUR), 10, 2, 0, RTSTR_F_ZEROPAD);
3604 *psz++ = ':';
3605 uint32_t u32 = (uint32_t)(u64 % RT_US_1HOUR);
3606 psz += RTStrFormatNumber(psz, u32 / RT_US_1MIN, 10, 2, 0, RTSTR_F_ZEROPAD);
3607 *psz++ = ':';
3608 u32 %= RT_US_1MIN;
3609
3610 psz += RTStrFormatNumber(psz, u32 / RT_US_1SEC, 10, 2, 0, RTSTR_F_ZEROPAD);
3611 *psz++ = '.';
3612 psz += RTStrFormatNumber(psz, u32 % RT_US_1SEC, 10, 6, 0, RTSTR_F_ZEROPAD);
3613 *psz++ = ' ';
3614#else
3615 memset(psz, ' ', 16);
3616 psz += 16;
3617#endif
3618 }
3619#define CCH_PREFIX_05 CCH_PREFIX_04 + (9+1+2+1+2+1+6+1)
3620
3621# if 0
3622 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_DATETIME)
3623 {
3624 char szDate[32];
3625 RTTIMESPEC Time;
3626 RTTimeSpecToString(RTTimeNow(&Time), szDate, sizeof(szDate));
3627 size_t cch = strlen(szDate);
3628 memcpy(psz, szDate, cch);
3629 psz += cch;
3630 *psz++ = ' ';
3631 }
3632# define CCH_PREFIX_06 CCH_PREFIX_05 + 32
3633# else
3634# define CCH_PREFIX_06 CCH_PREFIX_05 + 0
3635# endif
3636
3637 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_PID)
3638 {
3639#ifndef IN_RC
3640 RTPROCESS Process = RTProcSelf();
3641#else
3642 RTPROCESS Process = NIL_RTPROCESS;
3643#endif
3644 psz += RTStrFormatNumber(psz, Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
3645 *psz++ = ' ';
3646 }
3647#define CCH_PREFIX_07 CCH_PREFIX_06 + 9
3648
3649 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TID)
3650 {
3651#ifndef IN_RC
3652 RTNATIVETHREAD Thread = RTThreadNativeSelf();
3653#else
3654 RTNATIVETHREAD Thread = NIL_RTNATIVETHREAD;
3655#endif
3656 psz += RTStrFormatNumber(psz, Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
3657 *psz++ = ' ';
3658 }
3659#define CCH_PREFIX_08 CCH_PREFIX_07 + 17
3660
3661 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_THREAD)
3662 {
3663#ifdef IN_RING3
3664 const char *pszName = RTThreadSelfName();
3665#elif defined IN_RC
3666 const char *pszName = "EMT-RC";
3667#else
3668 const char *pszName = "R0";
3669#endif
3670 psz = rtLogStPNCpyPad(psz, pszName, 16, 8);
3671 }
3672#define CCH_PREFIX_09 CCH_PREFIX_08 + 17
3673
3674 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_CPUID)
3675 {
3676#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
3677 const uint8_t idCpu = ASMGetApicId();
3678#else
3679 const RTCPUID idCpu = RTMpCpuId();
3680#endif
3681 psz += RTStrFormatNumber(psz, idCpu, 16, sizeof(idCpu) * 2, 0, RTSTR_F_ZEROPAD);
3682 *psz++ = ' ';
3683 }
3684#define CCH_PREFIX_10 CCH_PREFIX_09 + 17
3685
3686#ifndef IN_RC
3687 if ( (pLogger->fFlags & RTLOGFLAGS_PREFIX_CUSTOM)
3688 && pLogger->pInt->pfnPrefix)
3689 {
3690 psz += pLogger->pInt->pfnPrefix(pLogger, psz, 31, pLogger->pInt->pvPrefixUserArg);
3691 *psz++ = ' '; /* +32 */
3692 }
3693#endif
3694#define CCH_PREFIX_11 CCH_PREFIX_10 + 32
3695
3696 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_LOCK_COUNTS)
3697 {
3698#ifdef IN_RING3 /** @todo implement these counters in ring-0 too? */
3699 RTTHREAD Thread = RTThreadSelf();
3700 if (Thread != NIL_RTTHREAD)
3701 {
3702 uint32_t cReadLocks = RTLockValidatorReadLockGetCount(Thread);
3703 uint32_t cWriteLocks = RTLockValidatorWriteLockGetCount(Thread) - g_cLoggerLockCount;
3704 cReadLocks = RT_MIN(0xfff, cReadLocks);
3705 cWriteLocks = RT_MIN(0xfff, cWriteLocks);
3706 psz += RTStrFormatNumber(psz, cReadLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
3707 *psz++ = '/';
3708 psz += RTStrFormatNumber(psz, cWriteLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
3709 }
3710 else
3711#endif
3712 {
3713 *psz++ = '?';
3714 *psz++ = '/';
3715 *psz++ = '?';
3716 }
3717 *psz++ = ' ';
3718 }
3719#define CCH_PREFIX_12 CCH_PREFIX_11 + 8
3720
3721 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_FLAG_NO)
3722 {
3723 psz += RTStrFormatNumber(psz, pArgs->fFlags, 16, 8, 0, RTSTR_F_ZEROPAD);
3724 *psz++ = ' ';
3725 }
3726#define CCH_PREFIX_13 CCH_PREFIX_12 + 9
3727
3728 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_FLAG)
3729 {
3730#ifdef IN_RING3
3731 const char *pszGroup = pArgs->iGroup != ~0U ? pLogger->pInt->papszGroups[pArgs->iGroup] : NULL;
3732#else
3733 const char *pszGroup = NULL;
3734#endif
3735 psz = rtLogStPNCpyPad(psz, pszGroup, 16, 8);
3736 }
3737#define CCH_PREFIX_14 CCH_PREFIX_13 + 17
3738
3739 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_GROUP_NO)
3740 {
3741 if (pArgs->iGroup != ~0U)
3742 {
3743 psz += RTStrFormatNumber(psz, pArgs->iGroup, 16, 3, 0, RTSTR_F_ZEROPAD);
3744 *psz++ = ' ';
3745 }
3746 else
3747 {
3748 memcpy(psz, "-1 ", sizeof("-1 ") - 1);
3749 psz += sizeof("-1 ") - 1;
3750 } /* +9 */
3751 }
3752#define CCH_PREFIX_15 CCH_PREFIX_14 + 9
3753
3754 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_GROUP)
3755 {
3756 const unsigned fGrp = pLogger->afGroups[pArgs->iGroup != ~0U ? pArgs->iGroup : 0];
3757 const char *pszGroup;
3758 size_t cch;
3759 switch (pArgs->fFlags & fGrp)
3760 {
3761 case 0: pszGroup = "--------"; cch = sizeof("--------") - 1; break;
3762 case RTLOGGRPFLAGS_ENABLED: pszGroup = "enabled" ; cch = sizeof("enabled" ) - 1; break;
3763 case RTLOGGRPFLAGS_LEVEL_1: pszGroup = "level 1" ; cch = sizeof("level 1" ) - 1; break;
3764 case RTLOGGRPFLAGS_LEVEL_2: pszGroup = "level 2" ; cch = sizeof("level 2" ) - 1; break;
3765 case RTLOGGRPFLAGS_LEVEL_3: pszGroup = "level 3" ; cch = sizeof("level 3" ) - 1; break;
3766 case RTLOGGRPFLAGS_LEVEL_4: pszGroup = "level 4" ; cch = sizeof("level 4" ) - 1; break;
3767 case RTLOGGRPFLAGS_LEVEL_5: pszGroup = "level 5" ; cch = sizeof("level 5" ) - 1; break;
3768 case RTLOGGRPFLAGS_LEVEL_6: pszGroup = "level 6" ; cch = sizeof("level 6" ) - 1; break;
3769 case RTLOGGRPFLAGS_LEVEL_7: pszGroup = "level 7" ; cch = sizeof("level 7" ) - 1; break;
3770 case RTLOGGRPFLAGS_LEVEL_8: pszGroup = "level 8" ; cch = sizeof("level 8" ) - 1; break;
3771 case RTLOGGRPFLAGS_LEVEL_9: pszGroup = "level 9" ; cch = sizeof("level 9" ) - 1; break;
3772 case RTLOGGRPFLAGS_LEVEL_10: pszGroup = "level 10"; cch = sizeof("level 10") - 1; break;
3773 case RTLOGGRPFLAGS_LEVEL_11: pszGroup = "level 11"; cch = sizeof("level 11") - 1; break;
3774 case RTLOGGRPFLAGS_LEVEL_12: pszGroup = "level 12"; cch = sizeof("level 12") - 1; break;
3775 case RTLOGGRPFLAGS_FLOW: pszGroup = "flow" ; cch = sizeof("flow" ) - 1; break;
3776 case RTLOGGRPFLAGS_WARN: pszGroup = "warn" ; cch = sizeof("warn" ) - 1; break;
3777 default: pszGroup = "????????"; cch = sizeof("????????") - 1; break;
3778 }
3779 psz = rtLogStPNCpyPad(psz, pszGroup, 16, 8);
3780 }
3781#define CCH_PREFIX_16 CCH_PREFIX_15 + 17
3782
3783#define CCH_PREFIX ( CCH_PREFIX_16 )
3784 { AssertCompile(CCH_PREFIX < 256); }
3785
3786 /*
3787 * Done, figure what we've used and advance the buffer and free size.
3788 */
3789 cb = psz - &pLogger->achScratch[pLogger->offScratch];
3790 AssertMsg(cb <= 223, ("%#zx (%zd) - fFlags=%#x\n", cb, cb, pLogger->fFlags));
3791 pLogger->offScratch += (uint32_t)cb;
3792 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3793 }
3794 else if (cb <= 0)
3795 {
3796 rtlogFlush(pLogger);
3797 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
3798 }
3799
3800#if defined(DEBUG) && defined(IN_RING3)
3801 /* sanity */
3802 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
3803 {
3804 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
3805 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
3806 AssertBreakpoint(); AssertBreakpoint();
3807 }
3808#endif
3809
3810 /* how much */
3811 if (cb > cbChars)
3812 cb = cbChars;
3813
3814 /* have newline? */
3815 pszNewLine = (const char *)memchr(pachChars, '\n', cb);
3816 if (pszNewLine)
3817 {
3818 if (pLogger->fFlags & RTLOGFLAGS_USECRLF)
3819 cb = pszNewLine - pachChars;
3820 else
3821 {
3822 cb = pszNewLine - pachChars + 1;
3823 *pfPendingPrefix = true;
3824 }
3825 }
3826
3827 /* copy */
3828 memcpy(&pLogger->achScratch[pLogger->offScratch], pachChars, cb);
3829
3830 /* advance */
3831 pLogger->offScratch += (uint32_t)cb;
3832 cbRet += cb;
3833 cbChars -= cb;
3834
3835 if ( pszNewLine
3836 && (pLogger->fFlags & RTLOGFLAGS_USECRLF)
3837 && pLogger->offScratch + 2 < sizeof(pLogger->achScratch))
3838 {
3839 memcpy(&pLogger->achScratch[pLogger->offScratch], "\r\n", 2);
3840 pLogger->offScratch += 2;
3841 cbRet++;
3842 cbChars--;
3843 cb++;
3844 *pfPendingPrefix = true;
3845 }
3846
3847 /* done? */
3848 if (cbChars <= 0)
3849 return cbRet;
3850 pachChars += cb;
3851 }
3852
3853 /* won't ever get here! */
3854 }
3855 else
3856 {
3857 /*
3858 * Termination call.
3859 * There's always space for a terminator, and it's not counted.
3860 */
3861 pLogger->achScratch[pLogger->offScratch] = '\0';
3862 return 0;
3863 }
3864}
3865
3866
3867/**
3868 * Write to a logger instance (worker function).
3869 *
3870 * This function will check whether the instance, group and flags makes up a
3871 * logging kind which is currently enabled before writing anything to the log.
3872 *
3873 * @param pLogger Pointer to logger instance. Must be non-NULL.
3874 * @param fFlags The logging flags.
3875 * @param iGroup The group.
3876 * The value ~0U is reserved for compatibility with RTLogLogger[V] and is
3877 * only for internal usage!
3878 * @param pszFormat Format string.
3879 * @param args Format arguments.
3880 */
3881static void rtlogLoggerExVLocked(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args)
3882{
3883 /*
3884 * Format the message and perhaps flush it.
3885 */
3886 if (pLogger->fFlags & (RTLOGFLAGS_PREFIX_MASK | RTLOGFLAGS_USECRLF))
3887 {
3888 RTLOGOUTPUTPREFIXEDARGS OutputArgs;
3889 OutputArgs.pLogger = pLogger;
3890 OutputArgs.iGroup = iGroup;
3891 OutputArgs.fFlags = fFlags;
3892 RTLogFormatV(rtLogOutputPrefixed, &OutputArgs, pszFormat, args);
3893 }
3894 else
3895 RTLogFormatV(rtLogOutput, pLogger, pszFormat, args);
3896 if ( !(pLogger->fFlags & RTLOGFLAGS_BUFFERED)
3897 && pLogger->offScratch)
3898 rtlogFlush(pLogger);
3899}
3900
3901
3902#ifndef IN_RC
3903/**
3904 * For calling rtlogLoggerExVLocked.
3905 *
3906 * @param pLogger The logger.
3907 * @param fFlags The logging flags.
3908 * @param iGroup The group.
3909 * The value ~0U is reserved for compatibility with RTLogLogger[V] and is
3910 * only for internal usage!
3911 * @param pszFormat Format string.
3912 * @param ... Format arguments.
3913 */
3914static void rtlogLoggerExFLocked(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, ...)
3915{
3916 va_list va;
3917 va_start(va, pszFormat);
3918 rtlogLoggerExVLocked(pLogger, fFlags, iGroup, pszFormat, va);
3919 va_end(va);
3920}
3921#endif /* !IN_RC */
3922
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