VirtualBox

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

最後變更 在這個檔案從91531是 90974,由 vboxsync 提交於 4 年 前

IPRT/log,VMM: Changed RTLogBulkWrite to take a before/after marker texts. Fixed buffer switching bug in rtlogFlush where we would write terminator to the previous buffer instead of the next. bugref:10086

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

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