VirtualBox

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

Last change on this file since 55747 was 55436, checked in by vboxsync, 10 years ago

Reverted bad commit r99781.

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