VirtualBox

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

Last change on this file since 43363 was 42599, checked in by vboxsync, 12 years ago

log.h/log.cpp: s/pszVar/pszValue/g

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