VirtualBox

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

Last change on this file since 93174 was 93115, checked in by vboxsync, 3 years ago

scm --update-copyright-year

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id Revision
File size: 148.1 KB
Line 
1/* $Id: log.cpp 93115 2022-01-01 11:31:46Z vboxsync $ */
2/** @file
3 * Runtime VBox - Logger.
4 */
5
6/*
7 * Copyright (C) 2006-2022 Oracle Corporation
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 */
26
27
28/*********************************************************************************************************************************
29* Header Files *
30*********************************************************************************************************************************/
31#include <iprt/log.h>
32#include "internal/iprt.h"
33
34#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
1357/**
1358 * Destroys a logger instance.
1359 *
1360 * The instance is flushed and all output destinations closed (where applicable).
1361 *
1362 * @returns iprt status code.
1363 * @param pLogger The logger instance which close destroyed. NULL is fine.
1364 */
1365RTDECL(int) RTLogDestroy(PRTLOGGER pLogger)
1366{
1367 int rc;
1368 uint32_t iGroup;
1369 RTSEMSPINMUTEX hSpinMtx;
1370 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1371
1372 /*
1373 * Validate input.
1374 */
1375 if (!pLoggerInt)
1376 return VINF_SUCCESS;
1377 AssertPtrReturn(pLoggerInt, VERR_INVALID_POINTER);
1378 AssertReturn(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
1379
1380 /*
1381 * Acquire logger instance sem and disable all logging. (paranoia)
1382 */
1383 rc = rtlogLock(pLoggerInt);
1384 AssertMsgRCReturn(rc, ("%Rrc\n", rc), rc);
1385
1386 pLoggerInt->fFlags |= RTLOGFLAGS_DISABLED;
1387 iGroup = pLoggerInt->cGroups;
1388 while (iGroup-- > 0)
1389 pLoggerInt->afGroups[iGroup] = 0;
1390
1391 /*
1392 * Flush it.
1393 */
1394 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
1395
1396# ifdef IN_RING3
1397 /*
1398 * Add end of logging message.
1399 */
1400 if ( (pLoggerInt->fDestFlags & RTLOGDEST_FILE)
1401 && pLoggerInt->hFile != NIL_RTFILE)
1402 pLoggerInt->pfnPhase(&pLoggerInt->Core, RTLOGPHASE_END, rtlogPhaseMsgLocked);
1403
1404 /*
1405 * Close output stuffs.
1406 */
1407 if (pLoggerInt->hFile != NIL_RTFILE)
1408 {
1409 int rc2 = RTFileClose(pLoggerInt->hFile);
1410 AssertRC(rc2);
1411 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1412 rc = rc2;
1413 pLoggerInt->hFile = NIL_RTFILE;
1414 }
1415# endif
1416
1417 /*
1418 * Free the mutex, the wrapper and the instance memory.
1419 */
1420 hSpinMtx = pLoggerInt->hSpinMtx;
1421 pLoggerInt->hSpinMtx = NIL_RTSEMSPINMUTEX;
1422 if (hSpinMtx != NIL_RTSEMSPINMUTEX)
1423 {
1424 int rc2;
1425 RTSemSpinMutexRelease(hSpinMtx);
1426 rc2 = RTSemSpinMutexDestroy(hSpinMtx);
1427 AssertRC(rc2);
1428 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1429 rc = rc2;
1430 }
1431
1432 if (pLoggerInt->Core.pfnLogger)
1433 {
1434# if defined(LOG_USE_C99) && defined(RT_WITHOUT_EXEC_ALLOC)
1435 RTMemFree(*(void **)&pLoggerInt->Core.pfnLogger);
1436# else
1437 RTMemExecFree(*(void **)&pLoggerInt->Core.pfnLogger, 64);
1438# endif
1439 pLoggerInt->Core.pfnLogger = NULL;
1440 }
1441 RTMemFree(pLoggerInt);
1442
1443 return rc;
1444}
1445RT_EXPORT_SYMBOL(RTLogDestroy);
1446
1447
1448/**
1449 * Sets the custom prefix callback.
1450 *
1451 * @returns IPRT status code.
1452 * @param pLogger The logger instance.
1453 * @param pfnCallback The callback.
1454 * @param pvUser The user argument for the callback.
1455 * */
1456RTDECL(int) RTLogSetCustomPrefixCallback(PRTLOGGER pLogger, PFNRTLOGPREFIX pfnCallback, void *pvUser)
1457{
1458 int rc;
1459 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1460 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
1461
1462 /*
1463 * Do the work.
1464 */
1465 rc = rtlogLock(pLoggerInt);
1466 if (RT_SUCCESS(rc))
1467 {
1468 pLoggerInt->pvPrefixUserArg = pvUser;
1469 pLoggerInt->pfnPrefix = pfnCallback;
1470 rtlogUnlock(pLoggerInt);
1471 }
1472
1473 return rc;
1474}
1475RT_EXPORT_SYMBOL(RTLogSetCustomPrefixCallback);
1476
1477
1478/**
1479 * Sets the custom flush callback.
1480 *
1481 * This can be handy for special loggers like the per-EMT ones in ring-0,
1482 * but also for implementing a log viewer in the debugger GUI.
1483 *
1484 * @returns IPRT status code.
1485 * @retval VWRN_ALREADY_EXISTS if it was set to a different flusher.
1486 * @param pLogger The logger instance.
1487 * @param pfnFlush The flush callback.
1488 */
1489RTDECL(int) RTLogSetFlushCallback(PRTLOGGER pLogger, PFNRTLOGFLUSH pfnFlush)
1490{
1491 int rc;
1492 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1493 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
1494
1495 /*
1496 * Do the work.
1497 */
1498 rc = rtlogLock(pLoggerInt);
1499 if (RT_SUCCESS(rc))
1500 {
1501 if (pLoggerInt->pfnFlush && pLoggerInt->pfnFlush != pfnFlush)
1502 rc = VWRN_ALREADY_EXISTS;
1503 pLoggerInt->pfnFlush = pfnFlush;
1504 rtlogUnlock(pLoggerInt);
1505 }
1506
1507 return rc;
1508}
1509RT_EXPORT_SYMBOL(RTLogSetFlushCallback);
1510
1511
1512/**
1513 * Matches a group name with a pattern mask in an case insensitive manner (ASCII).
1514 *
1515 * @returns true if matching and *ppachMask set to the end of the pattern.
1516 * @returns false if no match.
1517 * @param pszGrp The group name.
1518 * @param ppachMask Pointer to the pointer to the mask. Only wildcard supported is '*'.
1519 * @param cchMask The length of the mask, including modifiers. The modifiers is why
1520 * we update *ppachMask on match.
1521 */
1522static bool rtlogIsGroupMatching(const char *pszGrp, const char **ppachMask, size_t cchMask)
1523{
1524 const char *pachMask;
1525
1526 if (!pszGrp || !*pszGrp)
1527 return false;
1528 pachMask = *ppachMask;
1529 for (;;)
1530 {
1531 if (RT_C_TO_LOWER(*pszGrp) != RT_C_TO_LOWER(*pachMask))
1532 {
1533 const char *pszTmp;
1534
1535 /*
1536 * Check for wildcard and do a minimal match if found.
1537 */
1538 if (*pachMask != '*')
1539 return false;
1540
1541 /* eat '*'s. */
1542 do pachMask++;
1543 while (--cchMask && *pachMask == '*');
1544
1545 /* is there more to match? */
1546 if ( !cchMask
1547 || *pachMask == '.'
1548 || *pachMask == '=')
1549 break; /* we're good */
1550
1551 /* do extremely minimal matching (fixme) */
1552 pszTmp = strchr(pszGrp, RT_C_TO_LOWER(*pachMask));
1553 if (!pszTmp)
1554 pszTmp = strchr(pszGrp, RT_C_TO_UPPER(*pachMask));
1555 if (!pszTmp)
1556 return false;
1557 pszGrp = pszTmp;
1558 continue;
1559 }
1560
1561 /* done? */
1562 if (!*++pszGrp)
1563 {
1564 /* trailing wildcard is ok. */
1565 do
1566 {
1567 pachMask++;
1568 cchMask--;
1569 } while (cchMask && *pachMask == '*');
1570 if ( !cchMask
1571 || *pachMask == '.'
1572 || *pachMask == '=')
1573 break; /* we're good */
1574 return false;
1575 }
1576
1577 if (!--cchMask)
1578 return false;
1579 pachMask++;
1580 }
1581
1582 /* match */
1583 *ppachMask = pachMask;
1584 return true;
1585}
1586
1587
1588/**
1589 * Updates the group settings for the logger instance using the specified
1590 * specification string.
1591 *
1592 * @returns iprt status code.
1593 * Failures can safely be ignored.
1594 * @param pLogger Logger instance.
1595 * @param pszValue Value to parse.
1596 */
1597RTDECL(int) RTLogGroupSettings(PRTLOGGER pLogger, const char *pszValue)
1598{
1599 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1600 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
1601 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
1602
1603 /*
1604 * Iterate the string.
1605 */
1606 while (*pszValue)
1607 {
1608 /*
1609 * Skip prefixes (blanks, ;, + and -).
1610 */
1611 bool fEnabled = true;
1612 char ch;
1613 const char *pszStart;
1614 unsigned i;
1615 size_t cch;
1616
1617 while ((ch = *pszValue) == '+' || ch == '-' || ch == ' ' || ch == '\t' || ch == '\n' || ch == ';')
1618 {
1619 if (ch == '+' || ch == '-' || ch == ';')
1620 fEnabled = ch != '-';
1621 pszValue++;
1622 }
1623 if (!*pszValue)
1624 break;
1625
1626 /*
1627 * Find end.
1628 */
1629 pszStart = pszValue;
1630 while ((ch = *pszValue) != '\0' && ch != '+' && ch != '-' && ch != ' ' && ch != '\t')
1631 pszValue++;
1632
1633 /*
1634 * Find the group (ascii case insensitive search).
1635 * Special group 'all'.
1636 */
1637 cch = pszValue - pszStart;
1638 if ( cch >= 3
1639 && (pszStart[0] == 'a' || pszStart[0] == 'A')
1640 && (pszStart[1] == 'l' || pszStart[1] == 'L')
1641 && (pszStart[2] == 'l' || pszStart[2] == 'L')
1642 && (cch == 3 || pszStart[3] == '.' || pszStart[3] == '='))
1643 {
1644 /*
1645 * All.
1646 */
1647 unsigned fFlags = cch == 3
1648 ? RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1
1649 : rtlogGroupFlags(&pszStart[3]);
1650 for (i = 0; i < pLoggerInt->cGroups; i++)
1651 {
1652 if (fEnabled)
1653 pLoggerInt->afGroups[i] |= fFlags;
1654 else
1655 pLoggerInt->afGroups[i] &= ~fFlags;
1656 }
1657 }
1658 else
1659 {
1660 /*
1661 * Specific group(s).
1662 */
1663 for (i = 0; i < pLoggerInt->cGroups; i++)
1664 {
1665 const char *psz2 = (const char*)pszStart;
1666 if (rtlogIsGroupMatching(pLoggerInt->papszGroups[i], &psz2, cch))
1667 {
1668 unsigned fFlags = RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1;
1669 if (*psz2 == '.' || *psz2 == '=')
1670 fFlags = rtlogGroupFlags(psz2);
1671 if (fEnabled)
1672 pLoggerInt->afGroups[i] |= fFlags;
1673 else
1674 pLoggerInt->afGroups[i] &= ~fFlags;
1675 }
1676 } /* for each group */
1677 }
1678
1679 } /* parse specification */
1680
1681 return VINF_SUCCESS;
1682}
1683RT_EXPORT_SYMBOL(RTLogGroupSettings);
1684
1685
1686/**
1687 * Interprets the group flags suffix.
1688 *
1689 * @returns Flags specified. (0 is possible!)
1690 * @param psz Start of Suffix. (Either dot or equal sign.)
1691 */
1692static unsigned rtlogGroupFlags(const char *psz)
1693{
1694 unsigned fFlags = 0;
1695
1696 /*
1697 * Literal flags.
1698 */
1699 while (*psz == '.')
1700 {
1701 static struct
1702 {
1703 const char *pszFlag; /* lowercase!! */
1704 unsigned fFlag;
1705 } aFlags[] =
1706 {
1707 { "eo", RTLOGGRPFLAGS_ENABLED },
1708 { "enabledonly",RTLOGGRPFLAGS_ENABLED },
1709 { "e", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_WARN },
1710 { "enabled", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_WARN },
1711 { "l1", RTLOGGRPFLAGS_LEVEL_1 },
1712 { "level1", RTLOGGRPFLAGS_LEVEL_1 },
1713 { "l", RTLOGGRPFLAGS_LEVEL_2 },
1714 { "l2", RTLOGGRPFLAGS_LEVEL_2 },
1715 { "level2", RTLOGGRPFLAGS_LEVEL_2 },
1716 { "l3", RTLOGGRPFLAGS_LEVEL_3 },
1717 { "level3", RTLOGGRPFLAGS_LEVEL_3 },
1718 { "l4", RTLOGGRPFLAGS_LEVEL_4 },
1719 { "level4", RTLOGGRPFLAGS_LEVEL_4 },
1720 { "l5", RTLOGGRPFLAGS_LEVEL_5 },
1721 { "level5", RTLOGGRPFLAGS_LEVEL_5 },
1722 { "l6", RTLOGGRPFLAGS_LEVEL_6 },
1723 { "level6", RTLOGGRPFLAGS_LEVEL_6 },
1724 { "l7", RTLOGGRPFLAGS_LEVEL_7 },
1725 { "level7", RTLOGGRPFLAGS_LEVEL_7 },
1726 { "l8", RTLOGGRPFLAGS_LEVEL_8 },
1727 { "level8", RTLOGGRPFLAGS_LEVEL_8 },
1728 { "l9", RTLOGGRPFLAGS_LEVEL_9 },
1729 { "level9", RTLOGGRPFLAGS_LEVEL_9 },
1730 { "l10", RTLOGGRPFLAGS_LEVEL_10 },
1731 { "level10", RTLOGGRPFLAGS_LEVEL_10 },
1732 { "l11", RTLOGGRPFLAGS_LEVEL_11 },
1733 { "level11", RTLOGGRPFLAGS_LEVEL_11 },
1734 { "l12", RTLOGGRPFLAGS_LEVEL_12 },
1735 { "level12", RTLOGGRPFLAGS_LEVEL_12 },
1736 { "f", RTLOGGRPFLAGS_FLOW },
1737 { "flow", RTLOGGRPFLAGS_FLOW },
1738 { "w", RTLOGGRPFLAGS_WARN },
1739 { "warn", RTLOGGRPFLAGS_WARN },
1740 { "warning", RTLOGGRPFLAGS_WARN },
1741 { "restrict", RTLOGGRPFLAGS_RESTRICT },
1742
1743 };
1744 unsigned i;
1745 bool fFound = false;
1746 psz++;
1747 for (i = 0; i < RT_ELEMENTS(aFlags) && !fFound; i++)
1748 {
1749 const char *psz1 = aFlags[i].pszFlag;
1750 const char *psz2 = psz;
1751 while (*psz1 == RT_C_TO_LOWER(*psz2))
1752 {
1753 psz1++;
1754 psz2++;
1755 if (!*psz1)
1756 {
1757 if ( (*psz2 >= 'a' && *psz2 <= 'z')
1758 || (*psz2 >= 'A' && *psz2 <= 'Z')
1759 || (*psz2 >= '0' && *psz2 <= '9') )
1760 break;
1761 fFlags |= aFlags[i].fFlag;
1762 fFound = true;
1763 psz = psz2;
1764 break;
1765 }
1766 } /* strincmp */
1767 } /* for each flags */
1768 AssertMsg(fFound, ("%.15s...", psz));
1769 }
1770
1771 /*
1772 * Flag value.
1773 */
1774 if (*psz == '=')
1775 {
1776 psz++;
1777 if (*psz == '~')
1778 fFlags = ~RTStrToInt32(psz + 1);
1779 else
1780 fFlags = RTStrToInt32(psz);
1781 }
1782
1783 return fFlags;
1784}
1785
1786
1787/**
1788 * Helper for RTLogGetGroupSettings.
1789 */
1790static int rtLogGetGroupSettingsAddOne(const char *pszName, uint32_t fGroup, char **ppszBuf, size_t *pcchBuf, bool *pfNotFirst)
1791{
1792#define APPEND_PSZ(psz,cch) do { memcpy(*ppszBuf, (psz), (cch)); *ppszBuf += (cch); *pcchBuf -= (cch); } while (0)
1793#define APPEND_SZ(sz) APPEND_PSZ(sz, sizeof(sz) - 1)
1794#define APPEND_CH(ch) do { **ppszBuf = (ch); *ppszBuf += 1; *pcchBuf -= 1; } while (0)
1795
1796 /*
1797 * Add the name.
1798 */
1799 size_t cchName = strlen(pszName);
1800 if (cchName + 1 + *pfNotFirst > *pcchBuf)
1801 return VERR_BUFFER_OVERFLOW;
1802 if (*pfNotFirst)
1803 APPEND_CH(' ');
1804 else
1805 *pfNotFirst = true;
1806 APPEND_PSZ(pszName, cchName);
1807
1808 /*
1809 * Only generate mnemonics for the simple+common bits.
1810 */
1811 if (fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1))
1812 /* nothing */;
1813 else if ( fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_LEVEL_2 | RTLOGGRPFLAGS_FLOW)
1814 && *pcchBuf >= sizeof(".e.l.f"))
1815 APPEND_SZ(".e.l.f");
1816 else if ( fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_FLOW)
1817 && *pcchBuf >= sizeof(".e.f"))
1818 APPEND_SZ(".e.f");
1819 else if (*pcchBuf >= 1 + 10 + 1)
1820 {
1821 size_t cch;
1822 APPEND_CH('=');
1823 cch = RTStrFormatNumber(*ppszBuf, fGroup, 16, 0, 0, RTSTR_F_SPECIAL | RTSTR_F_32BIT);
1824 *ppszBuf += cch;
1825 *pcchBuf -= cch;
1826 }
1827 else
1828 return VERR_BUFFER_OVERFLOW;
1829
1830#undef APPEND_PSZ
1831#undef APPEND_SZ
1832#undef APPEND_CH
1833 return VINF_SUCCESS;
1834}
1835
1836
1837/**
1838 * Get the current log group settings as a string.
1839 *
1840 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
1841 * @param pLogger Logger instance (NULL for default logger).
1842 * @param pszBuf The output buffer.
1843 * @param cchBuf The size of the output buffer. Must be greater
1844 * than zero.
1845 */
1846RTDECL(int) RTLogQueryGroupSettings(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
1847{
1848 bool fNotFirst = false;
1849 int rc = VINF_SUCCESS;
1850 uint32_t cGroups;
1851 uint32_t fGroup;
1852 uint32_t i;
1853 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1854 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
1855 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
1856 Assert(cchBuf);
1857
1858 /*
1859 * Check if all are the same.
1860 */
1861 cGroups = pLoggerInt->cGroups;
1862 fGroup = pLoggerInt->afGroups[0];
1863 for (i = 1; i < cGroups; i++)
1864 if (pLoggerInt->afGroups[i] != fGroup)
1865 break;
1866 if (i >= cGroups)
1867 rc = rtLogGetGroupSettingsAddOne("all", fGroup, &pszBuf, &cchBuf, &fNotFirst);
1868 else
1869 {
1870
1871 /*
1872 * Iterate all the groups and print all that are enabled.
1873 */
1874 for (i = 0; i < cGroups; i++)
1875 {
1876 fGroup = pLoggerInt->afGroups[i];
1877 if (fGroup)
1878 {
1879 const char *pszName = pLoggerInt->papszGroups[i];
1880 if (pszName)
1881 {
1882 rc = rtLogGetGroupSettingsAddOne(pszName, fGroup, &pszBuf, &cchBuf, &fNotFirst);
1883 if (rc)
1884 break;
1885 }
1886 }
1887 }
1888 }
1889
1890 *pszBuf = '\0';
1891 return rc;
1892}
1893RT_EXPORT_SYMBOL(RTLogQueryGroupSettings);
1894
1895
1896/**
1897 * Updates the flags for the logger instance using the specified
1898 * specification string.
1899 *
1900 * @returns iprt status code.
1901 * Failures can safely be ignored.
1902 * @param pLogger Logger instance (NULL for default logger).
1903 * @param pszValue Value to parse.
1904 */
1905RTDECL(int) RTLogFlags(PRTLOGGER pLogger, const char *pszValue)
1906{
1907 int rc = VINF_SUCCESS;
1908 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1909 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
1910 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
1911
1912 /*
1913 * Iterate the string.
1914 */
1915 while (*pszValue)
1916 {
1917 /* check no prefix. */
1918 bool fNo = false;
1919 char ch;
1920 unsigned i;
1921
1922 /* skip blanks. */
1923 while (RT_C_IS_SPACE(*pszValue))
1924 pszValue++;
1925 if (!*pszValue)
1926 return rc;
1927
1928 while ((ch = *pszValue) != '\0')
1929 {
1930 if (ch == 'n' && pszValue[1] == 'o')
1931 {
1932 pszValue += 2;
1933 fNo = !fNo;
1934 }
1935 else if (ch == '+')
1936 {
1937 pszValue++;
1938 fNo = true;
1939 }
1940 else if (ch == '-' || ch == '!' || ch == '~')
1941 {
1942 pszValue++;
1943 fNo = !fNo;
1944 }
1945 else
1946 break;
1947 }
1948
1949 /* instruction. */
1950 for (i = 0; i < RT_ELEMENTS(g_aLogFlags); i++)
1951 {
1952 if (!strncmp(pszValue, g_aLogFlags[i].pszInstr, g_aLogFlags[i].cchInstr))
1953 {
1954 if (!(g_aLogFlags[i].fFixedDest & pLoggerInt->fDestFlags))
1955 {
1956 if (fNo == g_aLogFlags[i].fInverted)
1957 pLoggerInt->fFlags |= g_aLogFlags[i].fFlag;
1958 else
1959 pLoggerInt->fFlags &= ~g_aLogFlags[i].fFlag;
1960 }
1961 pszValue += g_aLogFlags[i].cchInstr;
1962 break;
1963 }
1964 }
1965
1966 /* unknown instruction? */
1967 if (i >= RT_ELEMENTS(g_aLogFlags))
1968 {
1969 AssertMsgFailed(("Invalid flags! unknown instruction %.20s\n", pszValue));
1970 pszValue++;
1971 }
1972
1973 /* skip blanks and delimiters. */
1974 while (RT_C_IS_SPACE(*pszValue) || *pszValue == ';')
1975 pszValue++;
1976 } /* while more environment variable value left */
1977
1978 return rc;
1979}
1980RT_EXPORT_SYMBOL(RTLogFlags);
1981
1982
1983/**
1984 * Changes the buffering setting of the specified logger.
1985 *
1986 * This can be used for optimizing longish logging sequences.
1987 *
1988 * @returns The old state.
1989 * @param pLogger The logger instance (NULL is an alias for the
1990 * default logger).
1991 * @param fBuffered The new state.
1992 */
1993RTDECL(bool) RTLogSetBuffering(PRTLOGGER pLogger, bool fBuffered)
1994{
1995 int rc;
1996 bool fOld = false;
1997 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1998 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, false);
1999
2000 rc = rtlogLock(pLoggerInt);
2001 if (RT_SUCCESS(rc))
2002 {
2003 fOld = !!(pLoggerInt->fFlags & RTLOGFLAGS_BUFFERED);
2004 if (fBuffered)
2005 pLoggerInt->fFlags |= RTLOGFLAGS_BUFFERED;
2006 else
2007 pLoggerInt->fFlags &= ~RTLOGFLAGS_BUFFERED;
2008 rtlogUnlock(pLoggerInt);
2009 }
2010
2011 return fOld;
2012}
2013RT_EXPORT_SYMBOL(RTLogSetBuffering);
2014
2015
2016RTDECL(uint32_t) RTLogSetGroupLimit(PRTLOGGER pLogger, uint32_t cMaxEntriesPerGroup)
2017{
2018 int rc;
2019 uint32_t cOld = UINT32_MAX;
2020 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2021 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, UINT32_MAX);
2022
2023 rc = rtlogLock(pLoggerInt);
2024 if (RT_SUCCESS(rc))
2025 {
2026 cOld = pLoggerInt->cMaxEntriesPerGroup;
2027 pLoggerInt->cMaxEntriesPerGroup = cMaxEntriesPerGroup;
2028 rtlogUnlock(pLoggerInt);
2029 }
2030
2031 return cOld;
2032}
2033RT_EXPORT_SYMBOL(RTLogSetGroupLimit);
2034
2035
2036#ifdef IN_RING0
2037
2038RTR0DECL(int) RTLogSetR0ThreadNameV(PRTLOGGER pLogger, const char *pszNameFmt, va_list va)
2039{
2040 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2041 int rc;
2042 if (pLoggerInt)
2043 {
2044 rc = rtlogLock(pLoggerInt);
2045 if (RT_SUCCESS(rc))
2046 {
2047 ssize_t cch = RTStrPrintf2V(pLoggerInt->szR0ThreadName, sizeof(pLoggerInt->szR0ThreadName), pszNameFmt, va);
2048 rtlogUnlock(pLoggerInt);
2049 rc = cch > 0 ? VINF_SUCCESS : VERR_BUFFER_OVERFLOW;
2050 }
2051 }
2052 else
2053 rc = VERR_INVALID_PARAMETER;
2054 return rc;
2055}
2056RT_EXPORT_SYMBOL(RTLogSetR0ThreadNameV);
2057
2058
2059RTR0DECL(int) RTLogSetR0ProgramStart(PRTLOGGER pLogger, uint64_t nsStart)
2060{
2061 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2062 int rc;
2063 if (pLoggerInt)
2064 {
2065 rc = rtlogLock(pLoggerInt);
2066 if (RT_SUCCESS(rc))
2067 {
2068 pLoggerInt->nsR0ProgramStart = nsStart;
2069 rtlogUnlock(pLoggerInt);
2070 }
2071 }
2072 else
2073 rc = VERR_INVALID_PARAMETER;
2074 return rc;
2075}
2076RT_EXPORT_SYMBOL(RTLogSetR0ProgramStart);
2077
2078#endif /* IN_RING0 */
2079
2080/**
2081 * Gets the current flag settings for the given logger.
2082 *
2083 * @returns Logger flags, UINT64_MAX if no logger.
2084 * @param pLogger Logger instance (NULL for default logger).
2085 */
2086RTDECL(uint64_t) RTLogGetFlags(PRTLOGGER pLogger)
2087{
2088 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2089 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, UINT64_MAX);
2090 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2091 return pLoggerInt->fFlags;
2092}
2093RT_EXPORT_SYMBOL(RTLogGetFlags);
2094
2095
2096/**
2097 * Modifies the flag settings for the given logger.
2098 *
2099 * @returns IPRT status code. Returns VINF_SUCCESS if VINF_LOG_NO_LOGGER and @a
2100 * pLogger is NULL.
2101 * @param pLogger Logger instance (NULL for default logger).
2102 * @param fSet Mask of flags to set (OR).
2103 * @param fClear Mask of flags to clear (NAND). This is allowed to
2104 * include invalid flags - e.g. UINT64_MAX is okay.
2105 */
2106RTDECL(int) RTLogChangeFlags(PRTLOGGER pLogger, uint64_t fSet, uint64_t fClear)
2107{
2108 int rc;
2109 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2110 AssertReturn(!(fSet & ~RTLOG_F_VALID_MASK), VERR_INVALID_FLAGS);
2111 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2112
2113 /*
2114 * Make the changes.
2115 */
2116 rc = rtlogLock(pLoggerInt);
2117 if (RT_SUCCESS(rc))
2118 {
2119 pLoggerInt->fFlags &= ~fClear;
2120 pLoggerInt->fFlags |= fSet;
2121 rtlogUnlock(pLoggerInt);
2122 }
2123 return rc;
2124}
2125RT_EXPORT_SYMBOL(RTLogChangeFlags);
2126
2127
2128/**
2129 * Get the current log flags as a string.
2130 *
2131 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
2132 * @param pLogger Logger instance (NULL for default logger).
2133 * @param pszBuf The output buffer.
2134 * @param cchBuf The size of the output buffer. Must be greater
2135 * than zero.
2136 */
2137RTDECL(int) RTLogQueryFlags(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
2138{
2139 bool fNotFirst = false;
2140 int rc = VINF_SUCCESS;
2141 uint32_t fFlags;
2142 unsigned i;
2143 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2144
2145 Assert(cchBuf);
2146 *pszBuf = '\0';
2147 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2148 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2149
2150 /*
2151 * Add the flags in the list.
2152 */
2153 fFlags = pLoggerInt->fFlags;
2154 for (i = 0; i < RT_ELEMENTS(g_aLogFlags); i++)
2155 if ( !g_aLogFlags[i].fInverted
2156 ? (g_aLogFlags[i].fFlag & fFlags)
2157 : !(g_aLogFlags[i].fFlag & fFlags))
2158 {
2159 size_t cchInstr = g_aLogFlags[i].cchInstr;
2160 if (cchInstr + fNotFirst + 1 > cchBuf)
2161 {
2162 rc = VERR_BUFFER_OVERFLOW;
2163 break;
2164 }
2165 if (fNotFirst)
2166 {
2167 *pszBuf++ = ' ';
2168 cchBuf--;
2169 }
2170 memcpy(pszBuf, g_aLogFlags[i].pszInstr, cchInstr);
2171 pszBuf += cchInstr;
2172 cchBuf -= cchInstr;
2173 fNotFirst = true;
2174 }
2175 *pszBuf = '\0';
2176 return rc;
2177}
2178RT_EXPORT_SYMBOL(RTLogQueryFlags);
2179
2180
2181/**
2182 * Finds the end of a destination value.
2183 *
2184 * The value ends when we counter a ';' or a free standing word (space on both
2185 * from the g_aLogDst table. (If this is problematic for someone, we could
2186 * always do quoting and escaping.)
2187 *
2188 * @returns Value length in chars.
2189 * @param pszValue The first char after '=' or ':'.
2190 */
2191static size_t rtLogDestFindValueLength(const char *pszValue)
2192{
2193 size_t off = 0;
2194 char ch;
2195 while ((ch = pszValue[off]) != '\0' && ch != ';')
2196 {
2197 if (!RT_C_IS_SPACE(ch))
2198 off++;
2199 else
2200 {
2201 unsigned i;
2202 size_t cchThusFar = off;
2203 do
2204 off++;
2205 while ((ch = pszValue[off]) != '\0' && RT_C_IS_SPACE(ch));
2206 if (ch == ';')
2207 return cchThusFar;
2208
2209 if (ch == 'n' && pszValue[off + 1] == 'o')
2210 off += 2;
2211 for (i = 0; i < RT_ELEMENTS(g_aLogDst); i++)
2212 if (!strncmp(&pszValue[off], g_aLogDst[i].pszInstr, g_aLogDst[i].cchInstr))
2213 {
2214 ch = pszValue[off + g_aLogDst[i].cchInstr];
2215 if (ch == '\0' || RT_C_IS_SPACE(ch) || ch == '=' || ch == ':' || ch == ';')
2216 return cchThusFar;
2217 }
2218 }
2219 }
2220 return off;
2221}
2222
2223
2224/**
2225 * Updates the logger destination using the specified string.
2226 *
2227 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
2228 * @param pLogger Logger instance (NULL for default logger).
2229 * @param pszValue The value to parse.
2230 */
2231RTDECL(int) RTLogDestinations(PRTLOGGER pLogger, char const *pszValue)
2232{
2233 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2234 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2235 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2236 /** @todo locking? */
2237
2238 /*
2239 * Do the parsing.
2240 */
2241 while (*pszValue)
2242 {
2243 bool fNo;
2244 unsigned i;
2245
2246 /* skip blanks. */
2247 while (RT_C_IS_SPACE(*pszValue))
2248 pszValue++;
2249 if (!*pszValue)
2250 break;
2251
2252 /* check no prefix. */
2253 fNo = false;
2254 if ( pszValue[0] == 'n'
2255 && pszValue[1] == 'o'
2256 && ( pszValue[2] != 'd'
2257 || pszValue[3] != 'e'
2258 || pszValue[4] != 'n'
2259 || pszValue[5] != 'y'))
2260 {
2261 fNo = true;
2262 pszValue += 2;
2263 }
2264
2265 /* instruction. */
2266 for (i = 0; i < RT_ELEMENTS(g_aLogDst); i++)
2267 {
2268 size_t cchInstr = strlen(g_aLogDst[i].pszInstr);
2269 if (!strncmp(pszValue, g_aLogDst[i].pszInstr, cchInstr))
2270 {
2271 if (!fNo)
2272 pLoggerInt->fDestFlags |= g_aLogDst[i].fFlag;
2273 else
2274 pLoggerInt->fDestFlags &= ~g_aLogDst[i].fFlag;
2275 pszValue += cchInstr;
2276
2277 /* check for value. */
2278 while (RT_C_IS_SPACE(*pszValue))
2279 pszValue++;
2280 if (*pszValue == '=' || *pszValue == ':')
2281 {
2282 pszValue++;
2283 size_t cch = rtLogDestFindValueLength(pszValue);
2284 const char *pszEnd = pszValue + cch;
2285
2286# ifdef IN_RING3
2287 char szTmp[sizeof(pLoggerInt->szFilename)];
2288# else
2289 char szTmp[32];
2290# endif
2291 if (0)
2292 { /* nothing */ }
2293# ifdef IN_RING3
2294
2295 /* log file name */
2296 else if (i == 0 /* file */ && !fNo)
2297 {
2298 if (!(pLoggerInt->fDestFlags & RTLOGDEST_FIXED_FILE))
2299 {
2300 AssertReturn(cch < sizeof(pLoggerInt->szFilename), VERR_OUT_OF_RANGE);
2301 memcpy(pLoggerInt->szFilename, pszValue, cch);
2302 pLoggerInt->szFilename[cch] = '\0';
2303 /** @todo reopen log file if pLoggerInt->fCreated is true ... */
2304 }
2305 }
2306 /* log directory */
2307 else if (i == 1 /* dir */ && !fNo)
2308 {
2309 if (!(pLoggerInt->fDestFlags & RTLOGDEST_FIXED_DIR))
2310 {
2311 const char *pszFile = RTPathFilename(pLoggerInt->szFilename);
2312 size_t cchFile = pszFile ? strlen(pszFile) : 0;
2313 AssertReturn(cchFile + cch + 1 < sizeof(pLoggerInt->szFilename), VERR_OUT_OF_RANGE);
2314 memcpy(szTmp, cchFile ? pszFile : "", cchFile + 1);
2315
2316 memcpy(pLoggerInt->szFilename, pszValue, cch);
2317 pLoggerInt->szFilename[cch] = '\0';
2318 RTPathStripTrailingSlash(pLoggerInt->szFilename);
2319
2320 cch = strlen(pLoggerInt->szFilename);
2321 pLoggerInt->szFilename[cch++] = '/';
2322 memcpy(&pLoggerInt->szFilename[cch], szTmp, cchFile);
2323 pLoggerInt->szFilename[cch + cchFile] = '\0';
2324 /** @todo reopen log file if pLoggerInt->fCreated is true ... */
2325 }
2326 }
2327 else if (i == 2 /* history */)
2328 {
2329 if (!fNo)
2330 {
2331 uint32_t cHistory = 0;
2332 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2333 if (RT_SUCCESS(rc))
2334 rc = RTStrToUInt32Full(szTmp, 0, &cHistory);
2335 AssertMsgReturn(RT_SUCCESS(rc) && cHistory < _1M, ("Invalid history value %s (%Rrc)!\n", szTmp, rc), rc);
2336 pLoggerInt->cHistory = cHistory;
2337 }
2338 else
2339 pLoggerInt->cHistory = 0;
2340 }
2341 else if (i == 3 /* histsize */)
2342 {
2343 if (!fNo)
2344 {
2345 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2346 if (RT_SUCCESS(rc))
2347 rc = RTStrToUInt64Full(szTmp, 0, &pLoggerInt->cbHistoryFileMax);
2348 AssertMsgRCReturn(rc, ("Invalid history file size value %s (%Rrc)!\n", szTmp, rc), rc);
2349 if (pLoggerInt->cbHistoryFileMax == 0)
2350 pLoggerInt->cbHistoryFileMax = UINT64_MAX;
2351 }
2352 else
2353 pLoggerInt->cbHistoryFileMax = UINT64_MAX;
2354 }
2355 else if (i == 4 /* histtime */)
2356 {
2357 if (!fNo)
2358 {
2359 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2360 if (RT_SUCCESS(rc))
2361 rc = RTStrToUInt32Full(szTmp, 0, &pLoggerInt->cSecsHistoryTimeSlot);
2362 AssertMsgRCReturn(rc, ("Invalid history time slot value %s (%Rrc)!\n", szTmp, rc), rc);
2363 if (pLoggerInt->cSecsHistoryTimeSlot == 0)
2364 pLoggerInt->cSecsHistoryTimeSlot = UINT32_MAX;
2365 }
2366 else
2367 pLoggerInt->cSecsHistoryTimeSlot = UINT32_MAX;
2368 }
2369# endif /* IN_RING3 */
2370 else if (i == 5 /* ringbuf */ && !fNo)
2371 {
2372 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2373 uint32_t cbRingBuf = 0;
2374 if (RT_SUCCESS(rc))
2375 rc = RTStrToUInt32Full(szTmp, 0, &cbRingBuf);
2376 AssertMsgRCReturn(rc, ("Invalid ring buffer size value '%s' (%Rrc)!\n", szTmp, rc), rc);
2377
2378 if (cbRingBuf == 0)
2379 cbRingBuf = RTLOG_RINGBUF_DEFAULT_SIZE;
2380 else if (cbRingBuf < RTLOG_RINGBUF_MIN_SIZE)
2381 cbRingBuf = RTLOG_RINGBUF_MIN_SIZE;
2382 else if (cbRingBuf > RTLOG_RINGBUF_MAX_SIZE)
2383 cbRingBuf = RTLOG_RINGBUF_MAX_SIZE;
2384 else
2385 cbRingBuf = RT_ALIGN_32(cbRingBuf, 64);
2386 rc = rtLogRingBufAdjust(pLoggerInt, cbRingBuf, false /*fForce*/);
2387 if (RT_FAILURE(rc))
2388 return rc;
2389 }
2390 else
2391 AssertMsgFailedReturn(("Invalid destination value! %s%s doesn't take a value!\n",
2392 fNo ? "no" : "", g_aLogDst[i].pszInstr),
2393 VERR_INVALID_PARAMETER);
2394
2395 pszValue = pszEnd + (*pszEnd != '\0');
2396 }
2397 else if (i == 5 /* ringbuf */ && !fNo && !pLoggerInt->pszRingBuf)
2398 {
2399 int rc = rtLogRingBufAdjust(pLoggerInt, pLoggerInt->cbRingBuf, false /*fForce*/);
2400 if (RT_FAILURE(rc))
2401 return rc;
2402 }
2403 break;
2404 }
2405 }
2406
2407 /* assert known instruction */
2408 AssertMsgReturn(i < RT_ELEMENTS(g_aLogDst),
2409 ("Invalid destination value! unknown instruction %.20s\n", pszValue),
2410 VERR_INVALID_PARAMETER);
2411
2412 /* skip blanks and delimiters. */
2413 while (RT_C_IS_SPACE(*pszValue) || *pszValue == ';')
2414 pszValue++;
2415 } /* while more environment variable value left */
2416
2417 return VINF_SUCCESS;
2418}
2419RT_EXPORT_SYMBOL(RTLogDestinations);
2420
2421
2422/**
2423 * Clear the file delay flag if set, opening the destination and flushing.
2424 *
2425 * @returns IPRT status code.
2426 * @param pLogger Logger instance (NULL for default logger).
2427 * @param pErrInfo Where to return extended error info. Optional.
2428 */
2429RTDECL(int) RTLogClearFileDelayFlag(PRTLOGGER pLogger, PRTERRINFO pErrInfo)
2430{
2431 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2432 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2433
2434 /*
2435 * Do the work.
2436 */
2437 int rc = rtlogLock(pLoggerInt);
2438 if (RT_SUCCESS(rc))
2439 {
2440 if (pLoggerInt->fDestFlags & RTLOGDEST_F_DELAY_FILE)
2441 {
2442 pLoggerInt->fDestFlags &= ~RTLOGDEST_F_DELAY_FILE;
2443# ifdef IN_RING3
2444 if ( pLoggerInt->fDestFlags & RTLOGDEST_FILE
2445 && pLoggerInt->hFile == NIL_RTFILE)
2446 {
2447 rc = rtR3LogOpenFileDestination(pLoggerInt, pErrInfo);
2448 if (RT_SUCCESS(rc))
2449 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
2450 }
2451# endif
2452 RT_NOREF(pErrInfo); /** @todo fix create API to use RTErrInfo */
2453 }
2454 rtlogUnlock(pLoggerInt);
2455 }
2456 return VINF_SUCCESS;
2457}
2458RT_EXPORT_SYMBOL(RTLogClearFileDelayFlag);
2459
2460
2461/**
2462 * Modifies the log destinations settings for the given logger.
2463 *
2464 * This is only suitable for simple destination settings that doesn't take
2465 * additional arguments, like RTLOGDEST_FILE.
2466 *
2467 * @returns IPRT status code. Returns VINF_LOG_NO_LOGGER if VINF_LOG_NO_LOGGER
2468 * and @a pLogger is NULL.
2469 * @param pLogger Logger instance (NULL for default logger).
2470 * @param fSet Mask of destinations to set (OR).
2471 * @param fClear Mask of destinations to clear (NAND).
2472 */
2473RTDECL(int) RTLogChangeDestinations(PRTLOGGER pLogger, uint32_t fSet, uint32_t fClear)
2474{
2475 int rc;
2476 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2477 AssertCompile((RTLOG_DST_VALID_MASK & RTLOG_DST_CHANGE_MASK) == RTLOG_DST_CHANGE_MASK);
2478 AssertReturn(!(fSet & ~RTLOG_DST_CHANGE_MASK), VERR_INVALID_FLAGS);
2479 AssertReturn(!(fClear & ~RTLOG_DST_CHANGE_MASK), VERR_INVALID_FLAGS);
2480 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2481
2482 /*
2483 * Make the changes.
2484 */
2485 rc = rtlogLock(pLoggerInt);
2486 if (RT_SUCCESS(rc))
2487 {
2488 pLoggerInt->fDestFlags &= ~fClear;
2489 pLoggerInt->fDestFlags |= fSet;
2490 rtlogUnlock(pLoggerInt);
2491 }
2492
2493 return VINF_SUCCESS;
2494}
2495RT_EXPORT_SYMBOL(RTLogChangeDestinations);
2496
2497
2498/**
2499 * Gets the current destinations flags for the given logger.
2500 *
2501 * @returns Logger destination flags, UINT32_MAX if no logger.
2502 * @param pLogger Logger instance (NULL for default logger).
2503 */
2504RTDECL(uint32_t) RTLogGetDestinations(PRTLOGGER pLogger)
2505{
2506 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2507 if (!pLoggerInt)
2508 {
2509 pLoggerInt = (PRTLOGGERINTERNAL)RTLogDefaultInstance();
2510 if (!pLoggerInt)
2511 return UINT32_MAX;
2512 }
2513 return pLoggerInt->fFlags;
2514}
2515RT_EXPORT_SYMBOL(RTLogGetDestinations);
2516
2517
2518/**
2519 * Get the current log destinations as a string.
2520 *
2521 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
2522 * @param pLogger Logger instance (NULL for default logger).
2523 * @param pszBuf The output buffer.
2524 * @param cchBuf The size of the output buffer. Must be greater
2525 * than 0.
2526 */
2527RTDECL(int) RTLogQueryDestinations(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
2528{
2529 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2530 bool fNotFirst = false;
2531 int rc = VINF_SUCCESS;
2532 uint32_t fDestFlags;
2533 unsigned i;
2534
2535 AssertReturn(cchBuf, VERR_INVALID_PARAMETER);
2536 *pszBuf = '\0';
2537 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2538 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2539
2540 /*
2541 * Add the flags in the list.
2542 */
2543 fDestFlags = pLoggerInt->fDestFlags;
2544 for (i = 6; i < RT_ELEMENTS(g_aLogDst); i++)
2545 if (g_aLogDst[i].fFlag & fDestFlags)
2546 {
2547 if (fNotFirst)
2548 {
2549 rc = RTStrCopyP(&pszBuf, &cchBuf, " ");
2550 if (RT_FAILURE(rc))
2551 return rc;
2552 }
2553 rc = RTStrCopyP(&pszBuf, &cchBuf, g_aLogDst[i].pszInstr);
2554 if (RT_FAILURE(rc))
2555 return rc;
2556 fNotFirst = true;
2557 }
2558
2559 char szNum[32];
2560
2561# ifdef IN_RING3
2562 /*
2563 * Add the filename.
2564 */
2565 if (fDestFlags & RTLOGDEST_FILE)
2566 {
2567 rc = RTStrCopyP(&pszBuf, &cchBuf, fNotFirst ? " file=" : "file=");
2568 if (RT_FAILURE(rc))
2569 return rc;
2570 rc = RTStrCopyP(&pszBuf, &cchBuf, pLoggerInt->szFilename);
2571 if (RT_FAILURE(rc))
2572 return rc;
2573 fNotFirst = true;
2574
2575 if (pLoggerInt->cHistory)
2576 {
2577 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " history=%u" : "history=%u", pLoggerInt->cHistory);
2578 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2579 if (RT_FAILURE(rc))
2580 return rc;
2581 fNotFirst = true;
2582 }
2583 if (pLoggerInt->cbHistoryFileMax != UINT64_MAX)
2584 {
2585 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " histsize=%llu" : "histsize=%llu", pLoggerInt->cbHistoryFileMax);
2586 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2587 if (RT_FAILURE(rc))
2588 return rc;
2589 fNotFirst = true;
2590 }
2591 if (pLoggerInt->cSecsHistoryTimeSlot != UINT32_MAX)
2592 {
2593 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " histtime=%llu" : "histtime=%llu", pLoggerInt->cSecsHistoryTimeSlot);
2594 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2595 if (RT_FAILURE(rc))
2596 return rc;
2597 fNotFirst = true;
2598 }
2599 }
2600# endif /* IN_RING3 */
2601
2602 /*
2603 * Add the ring buffer.
2604 */
2605 if (fDestFlags & RTLOGDEST_RINGBUF)
2606 {
2607 if (pLoggerInt->cbRingBuf == RTLOG_RINGBUF_DEFAULT_SIZE)
2608 rc = RTStrCopyP(&pszBuf, &cchBuf, fNotFirst ? " ringbuf" : "ringbuf");
2609 else
2610 {
2611 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " ringbuf=%#x" : "ringbuf=%#x", pLoggerInt->cbRingBuf);
2612 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2613 }
2614 if (RT_FAILURE(rc))
2615 return rc;
2616 fNotFirst = true;
2617 }
2618
2619 return VINF_SUCCESS;
2620}
2621RT_EXPORT_SYMBOL(RTLogQueryDestinations);
2622
2623
2624/**
2625 * Helper for calculating the CRC32 of all the group names.
2626 */
2627static uint32_t rtLogCalcGroupNameCrc32(PRTLOGGERINTERNAL pLoggerInt)
2628{
2629 const char * const * const papszGroups = pLoggerInt->papszGroups;
2630 uint32_t iGroup = pLoggerInt->cGroups;
2631 uint32_t uCrc32 = RTCrc32Start();
2632 while (iGroup-- > 0)
2633 {
2634 const char *pszGroup = papszGroups[iGroup];
2635 uCrc32 = RTCrc32Process(uCrc32, pszGroup, strlen(pszGroup) + 1);
2636 }
2637 return RTCrc32Finish(uCrc32);
2638}
2639
2640#ifdef IN_RING3
2641
2642/**
2643 * Opens/creates the log file.
2644 *
2645 * @param pLoggerInt The logger instance to update. NULL is not allowed!
2646 * @param pErrInfo Where to return extended error information.
2647 * Optional.
2648 */
2649static int rtlogFileOpen(PRTLOGGERINTERNAL pLoggerInt, PRTERRINFO pErrInfo)
2650{
2651 uint32_t fOpen = RTFILE_O_WRITE | RTFILE_O_DENY_NONE;
2652 if (pLoggerInt->fFlags & RTLOGFLAGS_APPEND)
2653 fOpen |= RTFILE_O_OPEN_CREATE | RTFILE_O_APPEND;
2654 else
2655 {
2656 RTFileDelete(pLoggerInt->szFilename);
2657 fOpen |= RTFILE_O_CREATE;
2658 }
2659 if (pLoggerInt->fFlags & RTLOGFLAGS_WRITE_THROUGH)
2660 fOpen |= RTFILE_O_WRITE_THROUGH;
2661 if (pLoggerInt->fDestFlags & RTLOGDEST_F_NO_DENY)
2662 fOpen = (fOpen & ~RTFILE_O_DENY_NONE) | RTFILE_O_DENY_NOT_DELETE;
2663
2664 unsigned cBackoff = 0;
2665 int rc = RTFileOpen(&pLoggerInt->hFile, pLoggerInt->szFilename, fOpen);
2666 while ( ( rc == VERR_SHARING_VIOLATION
2667 || (rc == VERR_ALREADY_EXISTS && !(pLoggerInt->fFlags & RTLOGFLAGS_APPEND)))
2668 && cBackoff < RT_ELEMENTS(g_acMsLogBackoff))
2669 {
2670 RTThreadSleep(g_acMsLogBackoff[cBackoff++]);
2671 if (!(pLoggerInt->fFlags & RTLOGFLAGS_APPEND))
2672 RTFileDelete(pLoggerInt->szFilename);
2673 rc = RTFileOpen(&pLoggerInt->hFile, pLoggerInt->szFilename, fOpen);
2674 }
2675 if (RT_SUCCESS(rc))
2676 {
2677 rc = RTFileQuerySize(pLoggerInt->hFile, &pLoggerInt->cbHistoryFileWritten);
2678 if (RT_FAILURE(rc))
2679 {
2680 /* Don't complain if this fails, assume the file is empty. */
2681 pLoggerInt->cbHistoryFileWritten = 0;
2682 rc = VINF_SUCCESS;
2683 }
2684 }
2685 else
2686 {
2687 pLoggerInt->hFile = NIL_RTFILE;
2688 RTErrInfoSetF(pErrInfo, rc, N_("could not open file '%s' (fOpen=%#x)"), pLoggerInt->szFilename, fOpen);
2689 }
2690 return rc;
2691}
2692
2693
2694/**
2695 * Closes, rotates and opens the log files if necessary.
2696 *
2697 * Used by the rtlogFlush() function as well as RTLogCreateExV() by way of
2698 * rtR3LogOpenFileDestination().
2699 *
2700 * @param pLoggerInt The logger instance to update. NULL is not allowed!
2701 * @param uTimeSlot Current time slot (for tikme based rotation).
2702 * @param fFirst Flag whether this is the beginning of logging, i.e.
2703 * called from RTLogCreateExV. Prevents pfnPhase from
2704 * being called.
2705 * @param pErrInfo Where to return extended error information. Optional.
2706 */
2707static void rtlogRotate(PRTLOGGERINTERNAL pLoggerInt, uint32_t uTimeSlot, bool fFirst, PRTERRINFO pErrInfo)
2708{
2709 /* Suppress rotating empty log files simply because the time elapsed. */
2710 if (RT_UNLIKELY(!pLoggerInt->cbHistoryFileWritten))
2711 pLoggerInt->uHistoryTimeSlotStart = uTimeSlot;
2712
2713 /* Check rotation condition: file still small enough and not too old? */
2714 if (RT_LIKELY( pLoggerInt->cbHistoryFileWritten < pLoggerInt->cbHistoryFileMax
2715 && uTimeSlot == pLoggerInt->uHistoryTimeSlotStart))
2716 return;
2717
2718 /*
2719 * Save "disabled" log flag and make sure logging is disabled.
2720 * The logging in the functions called during log file history
2721 * rotation would cause severe trouble otherwise.
2722 */
2723 uint32_t const fSavedFlags = pLoggerInt->fFlags;
2724 pLoggerInt->fFlags |= RTLOGFLAGS_DISABLED;
2725
2726 /*
2727 * Disable log rotation temporarily, otherwise with extreme settings and
2728 * chatty phase logging we could run into endless rotation.
2729 */
2730 uint32_t const cSavedHistory = pLoggerInt->cHistory;
2731 pLoggerInt->cHistory = 0;
2732
2733 /*
2734 * Close the old log file.
2735 */
2736 if (pLoggerInt->hFile != NIL_RTFILE)
2737 {
2738 /* Use the callback to generate some final log contents, but only if
2739 * this is a rotation with a fully set up logger. Leave the other case
2740 * to the RTLogCreateExV function. */
2741 if (pLoggerInt->pfnPhase && !fFirst)
2742 {
2743 uint32_t fODestFlags = pLoggerInt->fDestFlags;
2744 pLoggerInt->fDestFlags &= RTLOGDEST_FILE;
2745 pLoggerInt->pfnPhase(&pLoggerInt->Core, RTLOGPHASE_PREROTATE, rtlogPhaseMsgLocked);
2746 pLoggerInt->fDestFlags = fODestFlags;
2747 }
2748 RTFileClose(pLoggerInt->hFile);
2749 pLoggerInt->hFile = NIL_RTFILE;
2750 }
2751
2752 if (cSavedHistory)
2753 {
2754 /*
2755 * Rotate the log files.
2756 */
2757 for (uint32_t i = cSavedHistory - 1; i + 1 > 0; i--)
2758 {
2759 char szOldName[sizeof(pLoggerInt->szFilename) + 32];
2760 if (i > 0)
2761 RTStrPrintf(szOldName, sizeof(szOldName), "%s.%u", pLoggerInt->szFilename, i);
2762 else
2763 RTStrCopy(szOldName, sizeof(szOldName), pLoggerInt->szFilename);
2764
2765 char szNewName[sizeof(pLoggerInt->szFilename) + 32];
2766 RTStrPrintf(szNewName, sizeof(szNewName), "%s.%u", pLoggerInt->szFilename, i + 1);
2767
2768 unsigned cBackoff = 0;
2769 int rc = RTFileRename(szOldName, szNewName, RTFILEMOVE_FLAGS_REPLACE);
2770 while ( rc == VERR_SHARING_VIOLATION
2771 && cBackoff < RT_ELEMENTS(g_acMsLogBackoff))
2772 {
2773 RTThreadSleep(g_acMsLogBackoff[cBackoff++]);
2774 rc = RTFileRename(szOldName, szNewName, RTFILEMOVE_FLAGS_REPLACE);
2775 }
2776
2777 if (rc == VERR_FILE_NOT_FOUND)
2778 RTFileDelete(szNewName);
2779 }
2780
2781 /*
2782 * Delete excess log files.
2783 */
2784 for (uint32_t i = cSavedHistory + 1; ; i++)
2785 {
2786 char szExcessName[sizeof(pLoggerInt->szFilename) + 32];
2787 RTStrPrintf(szExcessName, sizeof(szExcessName), "%s.%u", pLoggerInt->szFilename, i);
2788 int rc = RTFileDelete(szExcessName);
2789 if (RT_FAILURE(rc))
2790 break;
2791 }
2792 }
2793
2794 /*
2795 * Update logger state and create new log file.
2796 */
2797 pLoggerInt->cbHistoryFileWritten = 0;
2798 pLoggerInt->uHistoryTimeSlotStart = uTimeSlot;
2799 rtlogFileOpen(pLoggerInt, pErrInfo);
2800
2801 /*
2802 * Use the callback to generate some initial log contents, but only if this
2803 * is a rotation with a fully set up logger. Leave the other case to the
2804 * RTLogCreateExV function.
2805 */
2806 if (pLoggerInt->pfnPhase && !fFirst)
2807 {
2808 uint32_t const fSavedDestFlags = pLoggerInt->fDestFlags;
2809 pLoggerInt->fDestFlags &= RTLOGDEST_FILE;
2810 pLoggerInt->pfnPhase(&pLoggerInt->Core, RTLOGPHASE_POSTROTATE, rtlogPhaseMsgLocked);
2811 pLoggerInt->fDestFlags = fSavedDestFlags;
2812 }
2813
2814 /* Restore saved values. */
2815 pLoggerInt->cHistory = cSavedHistory;
2816 pLoggerInt->fFlags = fSavedFlags;
2817}
2818
2819
2820/**
2821 * Worker for RTLogCreateExV and RTLogClearFileDelayFlag.
2822 *
2823 * This will later be used to reopen the file by RTLogDestinations.
2824 *
2825 * @returns IPRT status code.
2826 * @param pLoggerInt The logger.
2827 * @param pErrInfo Where to return extended error information.
2828 * Optional.
2829 */
2830static int rtR3LogOpenFileDestination(PRTLOGGERINTERNAL pLoggerInt, PRTERRINFO pErrInfo)
2831{
2832 int rc;
2833 if (pLoggerInt->fFlags & RTLOGFLAGS_APPEND)
2834 {
2835 rc = rtlogFileOpen(pLoggerInt, pErrInfo);
2836
2837 /* Rotate in case of appending to a too big log file,
2838 otherwise this simply doesn't do anything. */
2839 rtlogRotate(pLoggerInt, 0, true /* fFirst */, pErrInfo);
2840 }
2841 else
2842 {
2843 /* Force rotation if it is configured. */
2844 pLoggerInt->cbHistoryFileWritten = UINT64_MAX;
2845 rtlogRotate(pLoggerInt, 0, true /* fFirst */, pErrInfo);
2846
2847 /* If the file is not open then rotation is not set up. */
2848 if (pLoggerInt->hFile == NIL_RTFILE)
2849 {
2850 pLoggerInt->cbHistoryFileWritten = 0;
2851 rc = rtlogFileOpen(pLoggerInt, pErrInfo);
2852 }
2853 else
2854 rc = VINF_SUCCESS;
2855 }
2856 return rc;
2857}
2858
2859#endif /* IN_RING3 */
2860
2861
2862/*********************************************************************************************************************************
2863* Bulk Reconfig & Logging for ring-0 EMT loggers. *
2864*********************************************************************************************************************************/
2865
2866/**
2867 * Performs a bulk update of logger flags and group flags.
2868 *
2869 * This is for instanced used for copying settings from ring-3 to ring-0
2870 * loggers.
2871 *
2872 * @returns IPRT status code.
2873 * @param pLogger The logger instance (NULL for default logger).
2874 * @param fFlags The new logger flags.
2875 * @param uGroupCrc32 The CRC32 of the group name strings.
2876 * @param cGroups Number of groups.
2877 * @param pafGroups Array of group flags.
2878 * @sa RTLogQueryBulk
2879 */
2880RTDECL(int) RTLogBulkUpdate(PRTLOGGER pLogger, uint64_t fFlags, uint32_t uGroupCrc32, uint32_t cGroups, uint32_t const *pafGroups)
2881{
2882 int rc;
2883 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2884 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2885
2886 /*
2887 * Do the updating.
2888 */
2889 rc = rtlogLock(pLoggerInt);
2890 if (RT_SUCCESS(rc))
2891 {
2892 pLoggerInt->fFlags = fFlags;
2893 if ( uGroupCrc32 == rtLogCalcGroupNameCrc32(pLoggerInt)
2894 && pLoggerInt->cGroups == cGroups)
2895 {
2896 memcpy(pLoggerInt->afGroups, pafGroups, sizeof(pLoggerInt->afGroups[0]) * cGroups);
2897 rc = VINF_SUCCESS;
2898 }
2899 else
2900 rc = VERR_MISMATCH;
2901
2902 rtlogUnlock(pLoggerInt);
2903 }
2904 return rc;
2905}
2906RT_EXPORT_SYMBOL(RTLogBulkUpdate);
2907
2908
2909/**
2910 * Queries data for a bulk update of logger flags and group flags.
2911 *
2912 * This is for instanced used for copying settings from ring-3 to ring-0
2913 * loggers.
2914 *
2915 * @returns IPRT status code.
2916 * @retval VERR_BUFFER_OVERFLOW if pafGroups is too small, @a pcGroups will be
2917 * set to the actual number of groups.
2918 * @param pLogger The logger instance (NULL for default logger).
2919 * @param pfFlags Where to return the logger flags.
2920 * @param puGroupCrc32 Where to return the CRC32 of the group names.
2921 * @param pcGroups Input: Size of the @a pafGroups allocation.
2922 * Output: Actual number of groups returned.
2923 * @param pafGroups Where to return the flags for each group.
2924 * @sa RTLogBulkUpdate
2925 */
2926RTDECL(int) RTLogQueryBulk(PRTLOGGER pLogger, uint64_t *pfFlags, uint32_t *puGroupCrc32, uint32_t *pcGroups, uint32_t *pafGroups)
2927{
2928 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2929 uint32_t const cGroupsAlloc = *pcGroups;
2930
2931 *pfFlags = 0;
2932 *puGroupCrc32 = 0;
2933 *pcGroups = 0;
2934 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2935 AssertReturn(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
2936
2937 /*
2938 * Get the data.
2939 */
2940 *pfFlags = pLoggerInt->fFlags;
2941 *pcGroups = pLoggerInt->cGroups;
2942 if (cGroupsAlloc >= pLoggerInt->cGroups)
2943 {
2944 memcpy(pafGroups, pLoggerInt->afGroups, sizeof(pLoggerInt->afGroups[0]) * pLoggerInt->cGroups);
2945 *puGroupCrc32 = rtLogCalcGroupNameCrc32(pLoggerInt);
2946 return VINF_SUCCESS;
2947 }
2948 return VERR_BUFFER_OVERFLOW;
2949}
2950RT_EXPORT_SYMBOL(RTLogQueryBulk);
2951
2952
2953/**
2954 * Write/copy bulk log data from another logger.
2955 *
2956 * This is used for transferring stuff from the ring-0 loggers and into the
2957 * ring-3 one. The text goes in as-is w/o any processing (i.e. prefixing or
2958 * newline fun).
2959 *
2960 * @returns IRPT status code.
2961 * @param pLogger The logger instance (NULL for default logger).
2962 * @param pszBefore Text to log before the bulk text. Optional.
2963 * @param pch Pointer to the block of bulk log text to write.
2964 * @param cch Size of the block of bulk log text to write.
2965 * @param pszAfter Text to log after the bulk text. Optional.
2966 */
2967RTDECL(int) RTLogBulkWrite(PRTLOGGER pLogger, const char *pszBefore, const char *pch, size_t cch, const char *pszAfter)
2968{
2969 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2970 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2971
2972 /*
2973 * Lock and validate it.
2974 */
2975 int rc = rtlogLock(pLoggerInt);
2976 if (RT_SUCCESS(rc))
2977 {
2978 if (cch > 0)
2979 {
2980 /*
2981 * Heading/marker.
2982 */
2983 if (pszBefore)
2984 rtlogLoggerExFLocked(pLoggerInt, RTLOGGRPFLAGS_LEVEL_1, UINT32_MAX, "%s", pszBefore);
2985
2986 /*
2987 * Do the copying.
2988 */
2989 do
2990 {
2991 PRTLOGBUFFERDESC const pBufDesc = pLoggerInt->pBufDesc;
2992 char * const pchBuf = pBufDesc->pchBuf;
2993 uint32_t const cbBuf = pBufDesc->cbBuf;
2994 uint32_t offBuf = pBufDesc->offBuf;
2995 if (cch + 1 < cbBuf - offBuf)
2996 {
2997 memcpy(&pchBuf[offBuf], pch, cch);
2998 offBuf += (uint32_t)cch;
2999 pchBuf[offBuf] = '\0';
3000 pBufDesc->offBuf = offBuf;
3001 if (pBufDesc->pAux)
3002 pBufDesc->pAux->offBuf = offBuf;
3003 if (!(pLoggerInt->fDestFlags & RTLOGFLAGS_BUFFERED))
3004 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
3005 break;
3006 }
3007
3008 /* Not enough space. */
3009 if (offBuf + 1 < cbBuf)
3010 {
3011 uint32_t cbToCopy = cbBuf - offBuf - 1;
3012 memcpy(&pchBuf[offBuf], pch, cbToCopy);
3013 offBuf += cbToCopy;
3014 pchBuf[offBuf] = '\0';
3015 pBufDesc->offBuf = offBuf;
3016 if (pBufDesc->pAux)
3017 pBufDesc->pAux->offBuf = offBuf;
3018 pch += cbToCopy;
3019 cch -= cbToCopy;
3020 }
3021
3022 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
3023 } while (cch > 0);
3024
3025 /*
3026 * Footer/marker.
3027 */
3028 if (pszAfter)
3029 rtlogLoggerExFLocked(pLoggerInt, RTLOGGRPFLAGS_LEVEL_1, UINT32_MAX, "%s", pszAfter);
3030 }
3031
3032 rtlogUnlock(pLoggerInt);
3033 }
3034 return rc;
3035}
3036RT_EXPORT_SYMBOL(RTLogBulkWrite);
3037
3038
3039/*********************************************************************************************************************************
3040* Flushing *
3041*********************************************************************************************************************************/
3042
3043/**
3044 * Flushes the specified logger.
3045 *
3046 * @param pLogger The logger instance to flush.
3047 * If NULL the default instance is used. The default instance
3048 * will not be initialized by this call.
3049 */
3050RTDECL(int) RTLogFlush(PRTLOGGER pLogger)
3051{
3052 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
3053 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
3054 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
3055 AssertPtr(pLoggerInt->pBufDesc);
3056 Assert(pLoggerInt->pBufDesc->u32Magic == RTLOGBUFFERDESC_MAGIC);
3057
3058 /*
3059 * Acquire logger instance sem.
3060 */
3061 int rc = rtlogLock(pLoggerInt);
3062 if (RT_SUCCESS(rc))
3063 {
3064 /*
3065 * Any thing to flush?
3066 */
3067 if ( pLoggerInt->pBufDesc->offBuf > 0
3068 || (pLoggerInt->fDestFlags & RTLOGDEST_RINGBUF))
3069 {
3070 /*
3071 * Call worker.
3072 */
3073 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
3074
3075 /*
3076 * Since this is an explicit flush call, the ring buffer content should
3077 * be flushed to the other destinations if active.
3078 */
3079 if ( (pLoggerInt->fDestFlags & RTLOGDEST_RINGBUF)
3080 && pLoggerInt->pszRingBuf /* paranoia */)
3081 rtLogRingBufFlush(pLoggerInt);
3082 }
3083
3084 rtlogUnlock(pLoggerInt);
3085 }
3086 return rc;
3087}
3088RT_EXPORT_SYMBOL(RTLogFlush);
3089
3090
3091/**
3092 * Writes the buffer to the given log device without checking for buffered
3093 * data or anything.
3094 *
3095 * Used by the RTLogFlush() function.
3096 *
3097 * @param pLoggerInt The logger instance to write to. NULL is not allowed!
3098 * @param fNeedSpace Set if the caller assumes space will be made available.
3099 */
3100static void rtlogFlush(PRTLOGGERINTERNAL pLoggerInt, bool fNeedSpace)
3101{
3102 PRTLOGBUFFERDESC pBufDesc = pLoggerInt->pBufDesc;
3103 uint32_t cchToFlush = pBufDesc->offBuf;
3104 char * pchToFlush = pBufDesc->pchBuf;
3105 uint32_t const cbBuf = pBufDesc->cbBuf;
3106 Assert(pBufDesc->u32Magic == RTLOGBUFFERDESC_MAGIC);
3107
3108 NOREF(fNeedSpace);
3109 if (cchToFlush == 0)
3110 return; /* nothing to flush. */
3111
3112 AssertPtrReturnVoid(pchToFlush);
3113 AssertReturnVoid(cbBuf > 0);
3114 AssertMsgStmt(cchToFlush < cbBuf, ("%#x vs %#x\n", cchToFlush, cbBuf), cchToFlush = cbBuf - 1);
3115
3116 /*
3117 * If the ring buffer is active, the other destinations are only written
3118 * to when the ring buffer is flushed by RTLogFlush().
3119 */
3120 if ( (pLoggerInt->fDestFlags & RTLOGDEST_RINGBUF)
3121 && pLoggerInt->pszRingBuf /* paranoia */)
3122 {
3123 rtLogRingBufWrite(pLoggerInt, pchToFlush, cchToFlush);
3124
3125 /* empty the buffer. */
3126 pBufDesc->offBuf = 0;
3127 *pchToFlush = '\0';
3128 }
3129 /*
3130 * In file delay mode, we ignore flush requests except when we're full
3131 * and the caller really needs some scratch space to get work done.
3132 */
3133 else
3134#ifdef IN_RING3
3135 if (!(pLoggerInt->fDestFlags & RTLOGDEST_F_DELAY_FILE))
3136#endif
3137 {
3138 /* Make sure the string is terminated. On Windows, RTLogWriteDebugger
3139 will get upset if it isn't. */
3140 pchToFlush[cchToFlush] = '\0';
3141
3142 if (pLoggerInt->fDestFlags & RTLOGDEST_USER)
3143 RTLogWriteUser(pchToFlush, cchToFlush);
3144
3145 if (pLoggerInt->fDestFlags & RTLOGDEST_DEBUGGER)
3146 RTLogWriteDebugger(pchToFlush, cchToFlush);
3147
3148#ifdef IN_RING3
3149 if ((pLoggerInt->fDestFlags & (RTLOGDEST_FILE | RTLOGDEST_RINGBUF)) == RTLOGDEST_FILE)
3150 {
3151 if (pLoggerInt->hFile != NIL_RTFILE)
3152 {
3153 RTFileWrite(pLoggerInt->hFile, pchToFlush, cchToFlush, NULL);
3154 if (pLoggerInt->fFlags & RTLOGFLAGS_FLUSH)
3155 RTFileFlush(pLoggerInt->hFile);
3156 }
3157 if (pLoggerInt->cHistory)
3158 pLoggerInt->cbHistoryFileWritten += cchToFlush;
3159 }
3160#endif
3161
3162 if (pLoggerInt->fDestFlags & RTLOGDEST_STDOUT)
3163 RTLogWriteStdOut(pchToFlush, cchToFlush);
3164
3165 if (pLoggerInt->fDestFlags & RTLOGDEST_STDERR)
3166 RTLogWriteStdErr(pchToFlush, cchToFlush);
3167
3168#if (defined(IN_RING0) || defined(IN_RC)) && !defined(LOG_NO_COM)
3169 if (pLoggerInt->fDestFlags & RTLOGDEST_COM)
3170 RTLogWriteCom(pchToFlush, cchToFlush);
3171#endif
3172
3173 if (pLoggerInt->pfnFlush)
3174 {
3175 /*
3176 * We have a custom flush callback. Before calling it we must make
3177 * sure the aux descriptor is up to date. When we get back, we may
3178 * need to switch to the next buffer if the current is being flushed
3179 * asynchronously. This of course requires there to be more than one
3180 * buffer. (The custom flush callback is responsible for making sure
3181 * the next buffer isn't being flushed before returning.)
3182 */
3183 if (pBufDesc->pAux)
3184 pBufDesc->pAux->offBuf = cchToFlush;
3185 if (!pLoggerInt->pfnFlush(&pLoggerInt->Core, pBufDesc))
3186 {
3187 /* advance to the next buffer */
3188 Assert(pLoggerInt->cBufDescs > 1);
3189 size_t idxBufDesc = pBufDesc - pLoggerInt->paBufDescs;
3190 Assert(idxBufDesc < pLoggerInt->cBufDescs);
3191 idxBufDesc = (idxBufDesc + 1) % pLoggerInt->cBufDescs;
3192 pLoggerInt->idxBufDesc = (uint8_t)idxBufDesc;
3193 pLoggerInt->pBufDesc = pBufDesc = &pLoggerInt->paBufDescs[idxBufDesc];
3194 pchToFlush = pBufDesc->pchBuf;
3195 }
3196 }
3197
3198 /* Empty the buffer. */
3199 pBufDesc->offBuf = 0;
3200 if (pBufDesc->pAux)
3201 pBufDesc->pAux->offBuf = 0;
3202 *pchToFlush = '\0';
3203
3204#ifdef IN_RING3
3205 /*
3206 * Rotate the log file if configured. Must be done after everything is
3207 * flushed, since this will also use logging/flushing to write the header
3208 * and footer messages.
3209 */
3210 if ( pLoggerInt->cHistory > 0
3211 && (pLoggerInt->fDestFlags & RTLOGDEST_FILE))
3212 rtlogRotate(pLoggerInt, RTTimeProgramSecTS() / pLoggerInt->cSecsHistoryTimeSlot, false /*fFirst*/, NULL /*pErrInfo*/);
3213#endif
3214 }
3215#ifdef IN_RING3
3216 else
3217 {
3218 /*
3219 * Delay file open but the caller really need some space. So, give him half a
3220 * buffer and insert a message indicating that we've dropped output.
3221 */
3222 uint32_t offHalf = cbBuf / 2;
3223 if (cchToFlush > offHalf)
3224 {
3225 static const char s_szDropMsgLf[] = "\n[DROP DROP DROP]\n";
3226 static const char s_szDropMsgCrLf[] = "\r\n[DROP DROP DROP]\r\n";
3227 if (!(pLoggerInt->fFlags & RTLOGFLAGS_USECRLF))
3228 {
3229 memcpy(&pchToFlush[offHalf], RT_STR_TUPLE(s_szDropMsgLf));
3230 offHalf += sizeof(s_szDropMsgLf) - 1;
3231 }
3232 else
3233 {
3234 memcpy(&pchToFlush[offHalf], RT_STR_TUPLE(s_szDropMsgCrLf));
3235 offHalf += sizeof(s_szDropMsgCrLf) - 1;
3236 }
3237 pBufDesc->offBuf = offHalf;
3238 }
3239 }
3240#endif
3241}
3242
3243
3244/*********************************************************************************************************************************
3245* Logger Core *
3246*********************************************************************************************************************************/
3247
3248#ifdef IN_RING0
3249
3250/**
3251 * For rtR0LogLoggerExFallbackOutput and rtR0LogLoggerExFallbackFlush.
3252 */
3253typedef struct RTR0LOGLOGGERFALLBACK
3254{
3255 /** The current scratch buffer offset. */
3256 uint32_t offScratch;
3257 /** The destination flags. */
3258 uint32_t fDestFlags;
3259 /** For ring buffer output. */
3260 PRTLOGGERINTERNAL pInt;
3261 /** The scratch buffer. */
3262 char achScratch[80];
3263} RTR0LOGLOGGERFALLBACK;
3264/** Pointer to RTR0LOGLOGGERFALLBACK which is used by
3265 * rtR0LogLoggerExFallbackOutput. */
3266typedef RTR0LOGLOGGERFALLBACK *PRTR0LOGLOGGERFALLBACK;
3267
3268
3269/**
3270 * Flushes the fallback buffer.
3271 *
3272 * @param pThis The scratch buffer.
3273 */
3274static void rtR0LogLoggerExFallbackFlush(PRTR0LOGLOGGERFALLBACK pThis)
3275{
3276 if (!pThis->offScratch)
3277 return;
3278
3279 if ( (pThis->fDestFlags & RTLOGDEST_RINGBUF)
3280 && pThis->pInt
3281 && pThis->pInt->pszRingBuf /* paranoia */)
3282 rtLogRingBufWrite(pThis->pInt, pThis->achScratch, pThis->offScratch);
3283 else
3284 {
3285 if (pThis->fDestFlags & RTLOGDEST_USER)
3286 RTLogWriteUser(pThis->achScratch, pThis->offScratch);
3287
3288 if (pThis->fDestFlags & RTLOGDEST_DEBUGGER)
3289 RTLogWriteDebugger(pThis->achScratch, pThis->offScratch);
3290
3291 if (pThis->fDestFlags & RTLOGDEST_STDOUT)
3292 RTLogWriteStdOut(pThis->achScratch, pThis->offScratch);
3293
3294 if (pThis->fDestFlags & RTLOGDEST_STDERR)
3295 RTLogWriteStdErr(pThis->achScratch, pThis->offScratch);
3296
3297# ifndef LOG_NO_COM
3298 if (pThis->fDestFlags & RTLOGDEST_COM)
3299 RTLogWriteCom(pThis->achScratch, pThis->offScratch);
3300# endif
3301 }
3302
3303 /* empty the buffer. */
3304 pThis->offScratch = 0;
3305}
3306
3307
3308/**
3309 * Callback for RTLogFormatV used by rtR0LogLoggerExFallback.
3310 * See PFNLOGOUTPUT() for details.
3311 */
3312static DECLCALLBACK(size_t) rtR0LogLoggerExFallbackOutput(void *pv, const char *pachChars, size_t cbChars)
3313{
3314 PRTR0LOGLOGGERFALLBACK pThis = (PRTR0LOGLOGGERFALLBACK)pv;
3315 if (cbChars)
3316 {
3317 size_t cbRet = 0;
3318 for (;;)
3319 {
3320 /* how much */
3321 uint32_t cb = sizeof(pThis->achScratch) - pThis->offScratch - 1; /* minus 1 - for the string terminator. */
3322 if (cb > cbChars)
3323 cb = (uint32_t)cbChars;
3324
3325 /* copy */
3326 memcpy(&pThis->achScratch[pThis->offScratch], pachChars, cb);
3327
3328 /* advance */
3329 pThis->offScratch += cb;
3330 cbRet += cb;
3331 cbChars -= cb;
3332
3333 /* done? */
3334 if (cbChars <= 0)
3335 return cbRet;
3336
3337 pachChars += cb;
3338
3339 /* flush */
3340 pThis->achScratch[pThis->offScratch] = '\0';
3341 rtR0LogLoggerExFallbackFlush(pThis);
3342 }
3343
3344 /* won't ever get here! */
3345 }
3346 else
3347 {
3348 /*
3349 * Termination call, flush the log.
3350 */
3351 pThis->achScratch[pThis->offScratch] = '\0';
3352 rtR0LogLoggerExFallbackFlush(pThis);
3353 return 0;
3354 }
3355}
3356
3357
3358/**
3359 * Ring-0 fallback for cases where we're unable to grab the lock.
3360 *
3361 * This will happen when we're at a too high IRQL on Windows for instance and
3362 * needs to be dealt with or we'll drop a lot of log output. This fallback will
3363 * only output to some of the log destinations as a few of them may be doing
3364 * dangerous things. We won't be doing any prefixing here either, at least not
3365 * for the present, because it's too much hassle.
3366 *
3367 * @param fDestFlags The destination flags.
3368 * @param fFlags The logger flags.
3369 * @param pInt The internal logger data, for ring buffer output.
3370 * @param pszFormat The format string.
3371 * @param va The format arguments.
3372 */
3373static void rtR0LogLoggerExFallback(uint32_t fDestFlags, uint32_t fFlags, PRTLOGGERINTERNAL pInt,
3374 const char *pszFormat, va_list va)
3375{
3376 RTR0LOGLOGGERFALLBACK This;
3377 This.fDestFlags = fDestFlags;
3378 This.pInt = pInt;
3379
3380 /* fallback indicator. */
3381 This.offScratch = 2;
3382 This.achScratch[0] = '[';
3383 This.achScratch[1] = 'F';
3384
3385 /* selected prefixes */
3386 if (fFlags & RTLOGFLAGS_PREFIX_PID)
3387 {
3388 RTPROCESS Process = RTProcSelf();
3389 This.achScratch[This.offScratch++] = ' ';
3390 This.offScratch += RTStrFormatNumber(&This.achScratch[This.offScratch], Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
3391 }
3392 if (fFlags & RTLOGFLAGS_PREFIX_TID)
3393 {
3394 RTNATIVETHREAD Thread = RTThreadNativeSelf();
3395 This.achScratch[This.offScratch++] = ' ';
3396 This.offScratch += RTStrFormatNumber(&This.achScratch[This.offScratch], Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
3397 }
3398
3399 This.achScratch[This.offScratch++] = ']';
3400 This.achScratch[This.offScratch++] = ' ';
3401
3402 RTLogFormatV(rtR0LogLoggerExFallbackOutput, &This, pszFormat, va);
3403}
3404
3405#endif /* IN_RING0 */
3406
3407
3408/**
3409 * Callback for RTLogFormatV which writes to the com port.
3410 * See PFNLOGOUTPUT() for details.
3411 */
3412static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
3413{
3414 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pv;
3415 if (cbChars)
3416 {
3417 size_t cbRet = 0;
3418 for (;;)
3419 {
3420 PRTLOGBUFFERDESC const pBufDesc = pLoggerInt->pBufDesc;
3421 if (pBufDesc->offBuf < pBufDesc->cbBuf)
3422 {
3423 /* how much */
3424 char *pchBuf = pBufDesc->pchBuf;
3425 uint32_t offBuf = pBufDesc->offBuf;
3426 size_t cb = pBufDesc->cbBuf - offBuf - 1;
3427 if (cb > cbChars)
3428 cb = cbChars;
3429
3430 switch (cb)
3431 {
3432 default:
3433 memcpy(&pchBuf[offBuf], pachChars, cb);
3434 pBufDesc->offBuf = offBuf + (uint32_t)cb;
3435 cbRet += cb;
3436 cbChars -= cb;
3437 if (cbChars <= 0)
3438 return cbRet;
3439 pachChars += cb;
3440 break;
3441
3442 case 1:
3443 pchBuf[offBuf] = pachChars[0];
3444 pBufDesc->offBuf = offBuf + 1;
3445 if (cbChars == 1)
3446 return cbRet + 1;
3447 cbChars -= 1;
3448 pachChars += 1;
3449 break;
3450
3451 case 2:
3452 pchBuf[offBuf] = pachChars[0];
3453 pchBuf[offBuf + 1] = pachChars[1];
3454 pBufDesc->offBuf = offBuf + 2;
3455 if (cbChars == 2)
3456 return cbRet + 2;
3457 cbChars -= 2;
3458 pachChars += 2;
3459 break;
3460
3461 case 3:
3462 pchBuf[offBuf] = pachChars[0];
3463 pchBuf[offBuf + 1] = pachChars[1];
3464 pchBuf[offBuf + 2] = pachChars[2];
3465 pBufDesc->offBuf = offBuf + 3;
3466 if (cbChars == 3)
3467 return cbRet + 3;
3468 cbChars -= 3;
3469 pachChars += 3;
3470 break;
3471 }
3472
3473 }
3474#if defined(RT_STRICT) && defined(IN_RING3)
3475 else
3476 {
3477 fprintf(stderr, "pBufDesc->offBuf >= pBufDesc->cbBuf (%#x >= %#x)\n", pBufDesc->offBuf, pBufDesc->cbBuf);
3478 AssertBreakpoint(); AssertBreakpoint();
3479 }
3480#endif
3481
3482 /* flush */
3483 rtlogFlush(pLoggerInt, true /*fNeedSpace*/);
3484 }
3485
3486 /* won't ever get here! */
3487 }
3488 else
3489 {
3490 /*
3491 * Termination call.
3492 * There's always space for a terminator, and it's not counted.
3493 */
3494 PRTLOGBUFFERDESC const pBufDesc = pLoggerInt->pBufDesc;
3495 pBufDesc->pchBuf[RT_MIN(pBufDesc->offBuf, pBufDesc->cbBuf - 1)] = '\0';
3496 return 0;
3497 }
3498}
3499
3500
3501/**
3502 * stpncpy implementation for use in rtLogOutputPrefixed w/ padding.
3503 *
3504 * @returns Pointer to the destination buffer byte following the copied string.
3505 * @param pszDst The destination buffer.
3506 * @param pszSrc The source string.
3507 * @param cchSrcMax The maximum number of characters to copy from
3508 * the string.
3509 * @param cchMinWidth The minimum field with, padd with spaces to
3510 * reach this.
3511 */
3512DECLINLINE(char *) rtLogStPNCpyPad(char *pszDst, const char *pszSrc, size_t cchSrcMax, size_t cchMinWidth)
3513{
3514 size_t cchSrc = 0;
3515 if (pszSrc)
3516 {
3517 cchSrc = strlen(pszSrc);
3518 if (cchSrc > cchSrcMax)
3519 cchSrc = cchSrcMax;
3520
3521 memcpy(pszDst, pszSrc, cchSrc);
3522 pszDst += cchSrc;
3523 }
3524 do
3525 *pszDst++ = ' ';
3526 while (cchSrc++ < cchMinWidth);
3527
3528 return pszDst;
3529}
3530
3531
3532/**
3533 * stpncpy implementation for use in rtLogOutputPrefixed w/ padding.
3534 *
3535 * @returns Pointer to the destination buffer byte following the copied string.
3536 * @param pszDst The destination buffer.
3537 * @param pszSrc The source string.
3538 * @param cchSrc The number of characters to copy from the
3539 * source. Equal or less than string length.
3540 * @param cchMinWidth The minimum field with, padd with spaces to
3541 * reach this.
3542 */
3543DECLINLINE(char *) rtLogStPNCpyPad2(char *pszDst, const char *pszSrc, size_t cchSrc, size_t cchMinWidth)
3544{
3545 Assert(pszSrc);
3546 Assert(strlen(pszSrc) >= cchSrc);
3547
3548 memcpy(pszDst, pszSrc, cchSrc);
3549 pszDst += cchSrc;
3550 do
3551 *pszDst++ = ' ';
3552 while (cchSrc++ < cchMinWidth);
3553
3554 return pszDst;
3555}
3556
3557
3558
3559/**
3560 * Callback for RTLogFormatV which writes to the logger instance.
3561 * This version supports prefixes.
3562 *
3563 * See PFNLOGOUTPUT() for details.
3564 */
3565static DECLCALLBACK(size_t) rtLogOutputPrefixed(void *pv, const char *pachChars, size_t cbChars)
3566{
3567 PRTLOGOUTPUTPREFIXEDARGS pArgs = (PRTLOGOUTPUTPREFIXEDARGS)pv;
3568 PRTLOGGERINTERNAL pLoggerInt = pArgs->pLoggerInt;
3569 if (cbChars)
3570 {
3571 size_t cbRet = 0;
3572 for (;;)
3573 {
3574 PRTLOGBUFFERDESC const pBufDesc = pLoggerInt->pBufDesc;
3575 char * const pchBuf = pBufDesc->pchBuf;
3576 uint32_t const cbBuf = pBufDesc->cbBuf;
3577 uint32_t offBuf = pBufDesc->offBuf;
3578 size_t cb = cbBuf - offBuf - 1;
3579 const char *pszNewLine;
3580 char *psz;
3581
3582#if defined(RT_STRICT) && defined(IN_RING3)
3583 /* sanity */
3584 if (offBuf < cbBuf)
3585 { /* likely */ }
3586 else
3587 {
3588 fprintf(stderr, "offBuf >= cbBuf (%#x >= %#x)\n", offBuf, cbBuf);
3589 AssertBreakpoint(); AssertBreakpoint();
3590 }
3591#endif
3592
3593 /*
3594 * Pending prefix?
3595 */
3596 if (pLoggerInt->fPendingPrefix)
3597 {
3598 /*
3599 * Flush the buffer if there isn't enough room for the maximum prefix config.
3600 * Max is 256, add a couple of extra bytes. See CCH_PREFIX check way below.
3601 */
3602 if (cb >= 256 + 16)
3603 pLoggerInt->fPendingPrefix = false;
3604 else
3605 {
3606 rtlogFlush(pLoggerInt, true /*fNeedSpace*/);
3607 continue;
3608 }
3609
3610 /*
3611 * Write the prefixes.
3612 * psz is pointing to the current position.
3613 */
3614 psz = &pchBuf[offBuf];
3615 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_TS)
3616 {
3617 uint64_t u64 = RTTimeNanoTS();
3618 int iBase = 16;
3619 unsigned int fFlags = RTSTR_F_ZEROPAD;
3620 if (pLoggerInt->fFlags & RTLOGFLAGS_DECIMAL_TS)
3621 {
3622 iBase = 10;
3623 fFlags = 0;
3624 }
3625 if (pLoggerInt->fFlags & RTLOGFLAGS_REL_TS)
3626 {
3627 static volatile uint64_t s_u64LastTs;
3628 uint64_t u64DiffTs = u64 - s_u64LastTs;
3629 s_u64LastTs = u64;
3630 /* We could have been preempted just before reading of s_u64LastTs by
3631 * another thread which wrote s_u64LastTs. In that case the difference
3632 * is negative which we simply ignore. */
3633 u64 = (int64_t)u64DiffTs < 0 ? 0 : u64DiffTs;
3634 }
3635 /* 1E15 nanoseconds = 11 days */
3636 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags);
3637 *psz++ = ' ';
3638 }
3639#define CCH_PREFIX_01 0 + 17
3640
3641 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_TSC)
3642 {
3643#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
3644 uint64_t u64 = ASMReadTSC();
3645#else
3646 uint64_t u64 = RTTimeNanoTS();
3647#endif
3648 int iBase = 16;
3649 unsigned int fFlags = RTSTR_F_ZEROPAD;
3650 if (pLoggerInt->fFlags & RTLOGFLAGS_DECIMAL_TS)
3651 {
3652 iBase = 10;
3653 fFlags = 0;
3654 }
3655 if (pLoggerInt->fFlags & RTLOGFLAGS_REL_TS)
3656 {
3657 static volatile uint64_t s_u64LastTsc;
3658 int64_t i64DiffTsc = u64 - s_u64LastTsc;
3659 s_u64LastTsc = u64;
3660 /* We could have been preempted just before reading of s_u64LastTsc by
3661 * another thread which wrote s_u64LastTsc. In that case the difference
3662 * is negative which we simply ignore. */
3663 u64 = i64DiffTsc < 0 ? 0 : i64DiffTsc;
3664 }
3665 /* 1E15 ticks at 4GHz = 69 hours */
3666 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags);
3667 *psz++ = ' ';
3668 }
3669#define CCH_PREFIX_02 CCH_PREFIX_01 + 17
3670
3671 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_MS_PROG)
3672 {
3673#ifndef IN_RING0
3674 uint64_t u64 = RTTimeProgramMilliTS();
3675#else
3676 uint64_t u64 = (RTTimeNanoTS() - pLoggerInt->nsR0ProgramStart) / RT_NS_1MS;
3677#endif
3678 /* 1E8 milliseconds = 27 hours */
3679 psz += RTStrFormatNumber(psz, u64, 10, 9, 0, RTSTR_F_ZEROPAD);
3680 *psz++ = ' ';
3681 }
3682#define CCH_PREFIX_03 CCH_PREFIX_02 + 21
3683
3684 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_TIME)
3685 {
3686#if defined(IN_RING3) || defined(IN_RING0)
3687 RTTIMESPEC TimeSpec;
3688 RTTIME Time;
3689 RTTimeExplode(&Time, RTTimeNow(&TimeSpec));
3690 psz += RTStrFormatNumber(psz, Time.u8Hour, 10, 2, 0, RTSTR_F_ZEROPAD);
3691 *psz++ = ':';
3692 psz += RTStrFormatNumber(psz, Time.u8Minute, 10, 2, 0, RTSTR_F_ZEROPAD);
3693 *psz++ = ':';
3694 psz += RTStrFormatNumber(psz, Time.u8Second, 10, 2, 0, RTSTR_F_ZEROPAD);
3695 *psz++ = '.';
3696 psz += RTStrFormatNumber(psz, Time.u32Nanosecond / 1000, 10, 6, 0, RTSTR_F_ZEROPAD);
3697 *psz++ = ' ';
3698#else
3699 memset(psz, ' ', 16);
3700 psz += 16;
3701#endif
3702 }
3703#define CCH_PREFIX_04 CCH_PREFIX_03 + (3+1+3+1+3+1+7+1)
3704
3705 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_TIME_PROG)
3706 {
3707
3708#ifndef IN_RING0
3709 uint64_t u64 = RTTimeProgramMicroTS();
3710#else
3711 uint64_t u64 = (RTTimeNanoTS() - pLoggerInt->nsR0ProgramStart) / RT_NS_1US;
3712
3713#endif
3714 psz += RTStrFormatNumber(psz, (uint32_t)(u64 / RT_US_1HOUR), 10, 2, 0, RTSTR_F_ZEROPAD);
3715 *psz++ = ':';
3716 uint32_t u32 = (uint32_t)(u64 % RT_US_1HOUR);
3717 psz += RTStrFormatNumber(psz, u32 / RT_US_1MIN, 10, 2, 0, RTSTR_F_ZEROPAD);
3718 *psz++ = ':';
3719 u32 %= RT_US_1MIN;
3720
3721 psz += RTStrFormatNumber(psz, u32 / RT_US_1SEC, 10, 2, 0, RTSTR_F_ZEROPAD);
3722 *psz++ = '.';
3723 psz += RTStrFormatNumber(psz, u32 % RT_US_1SEC, 10, 6, 0, RTSTR_F_ZEROPAD);
3724 *psz++ = ' ';
3725 }
3726#define CCH_PREFIX_05 CCH_PREFIX_04 + (9+1+2+1+2+1+6+1)
3727
3728# if 0
3729 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_DATETIME)
3730 {
3731 char szDate[32];
3732 RTTIMESPEC Time;
3733 RTTimeSpecToString(RTTimeNow(&Time), szDate, sizeof(szDate));
3734 size_t cch = strlen(szDate);
3735 memcpy(psz, szDate, cch);
3736 psz += cch;
3737 *psz++ = ' ';
3738 }
3739# define CCH_PREFIX_06 CCH_PREFIX_05 + 32
3740# else
3741# define CCH_PREFIX_06 CCH_PREFIX_05 + 0
3742# endif
3743
3744 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_PID)
3745 {
3746 RTPROCESS Process = RTProcSelf();
3747 psz += RTStrFormatNumber(psz, Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
3748 *psz++ = ' ';
3749 }
3750#define CCH_PREFIX_07 CCH_PREFIX_06 + 9
3751
3752 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_TID)
3753 {
3754 RTNATIVETHREAD Thread = RTThreadNativeSelf();
3755 psz += RTStrFormatNumber(psz, Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
3756 *psz++ = ' ';
3757 }
3758#define CCH_PREFIX_08 CCH_PREFIX_07 + 17
3759
3760 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_THREAD)
3761 {
3762#ifdef IN_RING3
3763 const char *pszName = RTThreadSelfName();
3764#elif defined IN_RC
3765 const char *pszName = "EMT-RC";
3766#else
3767 const char *pszName = pLoggerInt->szR0ThreadName[0] ? pLoggerInt->szR0ThreadName : "R0";
3768#endif
3769 psz = rtLogStPNCpyPad(psz, pszName, 16, 8);
3770 }
3771#define CCH_PREFIX_09 CCH_PREFIX_08 + 17
3772
3773 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_CPUID)
3774 {
3775#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
3776 const uint8_t idCpu = ASMGetApicId();
3777#else
3778 const RTCPUID idCpu = RTMpCpuId();
3779#endif
3780 psz += RTStrFormatNumber(psz, idCpu, 16, sizeof(idCpu) * 2, 0, RTSTR_F_ZEROPAD);
3781 *psz++ = ' ';
3782 }
3783#define CCH_PREFIX_10 CCH_PREFIX_09 + 17
3784
3785 if ( (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_CUSTOM)
3786 && pLoggerInt->pfnPrefix)
3787 {
3788 psz += pLoggerInt->pfnPrefix(&pLoggerInt->Core, psz, 31, pLoggerInt->pvPrefixUserArg);
3789 *psz++ = ' '; /* +32 */
3790 }
3791#define CCH_PREFIX_11 CCH_PREFIX_10 + 32
3792
3793 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_LOCK_COUNTS)
3794 {
3795#ifdef IN_RING3 /** @todo implement these counters in ring-0 too? */
3796 RTTHREAD Thread = RTThreadSelf();
3797 if (Thread != NIL_RTTHREAD)
3798 {
3799 uint32_t cReadLocks = RTLockValidatorReadLockGetCount(Thread);
3800 uint32_t cWriteLocks = RTLockValidatorWriteLockGetCount(Thread) - g_cLoggerLockCount;
3801 cReadLocks = RT_MIN(0xfff, cReadLocks);
3802 cWriteLocks = RT_MIN(0xfff, cWriteLocks);
3803 psz += RTStrFormatNumber(psz, cReadLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
3804 *psz++ = '/';
3805 psz += RTStrFormatNumber(psz, cWriteLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
3806 }
3807 else
3808#endif
3809 {
3810 *psz++ = '?';
3811 *psz++ = '/';
3812 *psz++ = '?';
3813 }
3814 *psz++ = ' ';
3815 }
3816#define CCH_PREFIX_12 CCH_PREFIX_11 + 8
3817
3818 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_FLAG_NO)
3819 {
3820 psz += RTStrFormatNumber(psz, pArgs->fFlags, 16, 8, 0, RTSTR_F_ZEROPAD);
3821 *psz++ = ' ';
3822 }
3823#define CCH_PREFIX_13 CCH_PREFIX_12 + 9
3824
3825 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_FLAG)
3826 {
3827#ifdef IN_RING3
3828 const char *pszGroup = pArgs->iGroup != ~0U ? pLoggerInt->papszGroups[pArgs->iGroup] : NULL;
3829#else
3830 const char *pszGroup = NULL;
3831#endif
3832 psz = rtLogStPNCpyPad(psz, pszGroup, 16, 8);
3833 }
3834#define CCH_PREFIX_14 CCH_PREFIX_13 + 17
3835
3836 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_GROUP_NO)
3837 {
3838 if (pArgs->iGroup != ~0U)
3839 {
3840 psz += RTStrFormatNumber(psz, pArgs->iGroup, 16, 3, 0, RTSTR_F_ZEROPAD);
3841 *psz++ = ' ';
3842 }
3843 else
3844 {
3845 memcpy(psz, "-1 ", sizeof("-1 ") - 1);
3846 psz += sizeof("-1 ") - 1;
3847 } /* +9 */
3848 }
3849#define CCH_PREFIX_15 CCH_PREFIX_14 + 9
3850
3851 if (pLoggerInt->fFlags & RTLOGFLAGS_PREFIX_GROUP)
3852 {
3853 const unsigned fGrp = pLoggerInt->afGroups[pArgs->iGroup != ~0U ? pArgs->iGroup : 0];
3854 const char *pszGroup;
3855 size_t cchGroup;
3856 switch (pArgs->fFlags & fGrp)
3857 {
3858 case 0: pszGroup = "--------"; cchGroup = sizeof("--------") - 1; break;
3859 case RTLOGGRPFLAGS_ENABLED: pszGroup = "enabled" ; cchGroup = sizeof("enabled" ) - 1; break;
3860 case RTLOGGRPFLAGS_LEVEL_1: pszGroup = "level 1" ; cchGroup = sizeof("level 1" ) - 1; break;
3861 case RTLOGGRPFLAGS_LEVEL_2: pszGroup = "level 2" ; cchGroup = sizeof("level 2" ) - 1; break;
3862 case RTLOGGRPFLAGS_LEVEL_3: pszGroup = "level 3" ; cchGroup = sizeof("level 3" ) - 1; break;
3863 case RTLOGGRPFLAGS_LEVEL_4: pszGroup = "level 4" ; cchGroup = sizeof("level 4" ) - 1; break;
3864 case RTLOGGRPFLAGS_LEVEL_5: pszGroup = "level 5" ; cchGroup = sizeof("level 5" ) - 1; break;
3865 case RTLOGGRPFLAGS_LEVEL_6: pszGroup = "level 6" ; cchGroup = sizeof("level 6" ) - 1; break;
3866 case RTLOGGRPFLAGS_LEVEL_7: pszGroup = "level 7" ; cchGroup = sizeof("level 7" ) - 1; break;
3867 case RTLOGGRPFLAGS_LEVEL_8: pszGroup = "level 8" ; cchGroup = sizeof("level 8" ) - 1; break;
3868 case RTLOGGRPFLAGS_LEVEL_9: pszGroup = "level 9" ; cchGroup = sizeof("level 9" ) - 1; break;
3869 case RTLOGGRPFLAGS_LEVEL_10: pszGroup = "level 10"; cchGroup = sizeof("level 10") - 1; break;
3870 case RTLOGGRPFLAGS_LEVEL_11: pszGroup = "level 11"; cchGroup = sizeof("level 11") - 1; break;
3871 case RTLOGGRPFLAGS_LEVEL_12: pszGroup = "level 12"; cchGroup = sizeof("level 12") - 1; break;
3872 case RTLOGGRPFLAGS_FLOW: pszGroup = "flow" ; cchGroup = sizeof("flow" ) - 1; break;
3873 case RTLOGGRPFLAGS_WARN: pszGroup = "warn" ; cchGroup = sizeof("warn" ) - 1; break;
3874 default: pszGroup = "????????"; cchGroup = sizeof("????????") - 1; break;
3875 }
3876 psz = rtLogStPNCpyPad2(psz, pszGroup, RT_MIN(cchGroup, 16), 8);
3877 }
3878#define CCH_PREFIX_16 CCH_PREFIX_15 + 17
3879
3880#define CCH_PREFIX ( CCH_PREFIX_16 )
3881 { AssertCompile(CCH_PREFIX < 256); }
3882
3883 /*
3884 * Done, figure what we've used and advance the buffer and free size.
3885 */
3886 AssertMsg(psz - &pchBuf[offBuf] <= 223,
3887 ("%#zx (%zd) - fFlags=%#x\n", psz - &pchBuf[offBuf], psz - &pchBuf[offBuf], pLoggerInt->fFlags));
3888 pBufDesc->offBuf = offBuf = (uint32_t)(psz - pchBuf);
3889 cb = cbBuf - offBuf - 1;
3890 }
3891 else if (cb <= 2) /* 2 - Make sure we can write a \r\n and not loop forever. */
3892 {
3893 rtlogFlush(pLoggerInt, true /*fNeedSpace*/);
3894 continue;
3895 }
3896
3897 /*
3898 * Done with the prefixing. Copy message text past the next newline.
3899 */
3900
3901 /* how much */
3902 if (cb > cbChars)
3903 cb = cbChars;
3904
3905 /* have newline? */
3906 pszNewLine = (const char *)memchr(pachChars, '\n', cb);
3907 if (pszNewLine)
3908 {
3909 cb = pszNewLine - pachChars;
3910 if (!(pLoggerInt->fFlags & RTLOGFLAGS_USECRLF))
3911 {
3912 cb += 1;
3913 memcpy(&pchBuf[offBuf], pachChars, cb);
3914 pLoggerInt->fPendingPrefix = true;
3915 }
3916 else if (cb + 2U < cbBuf - offBuf)
3917 {
3918 memcpy(&pchBuf[offBuf], pachChars, cb);
3919 pchBuf[offBuf + cb++] = '\r';
3920 pchBuf[offBuf + cb++] = '\n';
3921 cbChars++; /* Discount the extra '\r'. */
3922 pachChars--; /* Ditto. */
3923 cbRet--; /* Ditto. */
3924 pLoggerInt->fPendingPrefix = true;
3925 }
3926 else
3927 {
3928 /* Insufficient buffer space, leave the '\n' for the next iteration. */
3929 memcpy(&pchBuf[offBuf], pachChars, cb);
3930 }
3931 }
3932 else
3933 memcpy(&pchBuf[offBuf], pachChars, cb);
3934
3935 /* advance */
3936 pBufDesc->offBuf = offBuf += (uint32_t)cb;
3937 cbRet += cb;
3938 cbChars -= cb;
3939
3940 /* done? */
3941 if (cbChars <= 0)
3942 return cbRet;
3943 pachChars += cb;
3944 }
3945
3946 /* won't ever get here! */
3947 }
3948 else
3949 {
3950 /*
3951 * Termination call.
3952 * There's always space for a terminator, and it's not counted.
3953 */
3954 PRTLOGBUFFERDESC const pBufDesc = pLoggerInt->pBufDesc;
3955 pBufDesc->pchBuf[RT_MIN(pBufDesc->offBuf, pBufDesc->cbBuf - 1)] = '\0';
3956 return 0;
3957 }
3958}
3959
3960
3961/**
3962 * Write to a logger instance (worker function).
3963 *
3964 * This function will check whether the instance, group and flags makes up a
3965 * logging kind which is currently enabled before writing anything to the log.
3966 *
3967 * @param pLoggerInt Pointer to logger instance. Must be non-NULL.
3968 * @param fFlags The logging flags.
3969 * @param iGroup The group.
3970 * The value ~0U is reserved for compatibility with RTLogLogger[V] and is
3971 * only for internal usage!
3972 * @param pszFormat Format string.
3973 * @param args Format arguments.
3974 */
3975static void rtlogLoggerExVLocked(PRTLOGGERINTERNAL pLoggerInt, unsigned fFlags, unsigned iGroup,
3976 const char *pszFormat, va_list args)
3977{
3978 /*
3979 * If we've got an auxilary descriptor, check if the buffer was flushed.
3980 */
3981 PRTLOGBUFFERDESC pBufDesc = pLoggerInt->pBufDesc;
3982 PRTLOGBUFFERAUXDESC pAuxDesc = pBufDesc->pAux;
3983 if (!pAuxDesc || !pAuxDesc->fFlushedIndicator)
3984 { /* likely, except maybe for ring-0 */ }
3985 else
3986 {
3987 pAuxDesc->fFlushedIndicator = false;
3988 pBufDesc->offBuf = 0;
3989 }
3990
3991 /*
3992 * Format the message.
3993 */
3994 if (pLoggerInt->fFlags & (RTLOGFLAGS_PREFIX_MASK | RTLOGFLAGS_USECRLF))
3995 {
3996 RTLOGOUTPUTPREFIXEDARGS OutputArgs;
3997 OutputArgs.pLoggerInt = pLoggerInt;
3998 OutputArgs.iGroup = iGroup;
3999 OutputArgs.fFlags = fFlags;
4000 RTLogFormatV(rtLogOutputPrefixed, &OutputArgs, pszFormat, args);
4001 }
4002 else
4003 RTLogFormatV(rtLogOutput, pLoggerInt, pszFormat, args);
4004
4005 /*
4006 * Maybe flush the buffer and update the auxiliary descriptor if there is one.
4007 */
4008 pBufDesc = pLoggerInt->pBufDesc; /* (the descriptor may have changed) */
4009 if ( !(pLoggerInt->fFlags & RTLOGFLAGS_BUFFERED)
4010 && pBufDesc->offBuf)
4011 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
4012 else
4013 {
4014 pAuxDesc = pBufDesc->pAux;
4015 if (pAuxDesc)
4016 pAuxDesc->offBuf = pBufDesc->offBuf;
4017 }
4018}
4019
4020
4021/**
4022 * For calling rtlogLoggerExVLocked.
4023 *
4024 * @param pLoggerInt The logger.
4025 * @param fFlags The logging flags.
4026 * @param iGroup The group.
4027 * The value ~0U is reserved for compatibility with RTLogLogger[V] and is
4028 * only for internal usage!
4029 * @param pszFormat Format string.
4030 * @param ... Format arguments.
4031 */
4032static void rtlogLoggerExFLocked(PRTLOGGERINTERNAL pLoggerInt, unsigned fFlags, unsigned iGroup, const char *pszFormat, ...)
4033{
4034 va_list va;
4035 va_start(va, pszFormat);
4036 rtlogLoggerExVLocked(pLoggerInt, fFlags, iGroup, pszFormat, va);
4037 va_end(va);
4038}
4039
4040
4041/**
4042 * Write to a logger instance.
4043 *
4044 * This function will check whether the instance, group and flags makes up a
4045 * logging kind which is currently enabled before writing anything to the log.
4046 *
4047 * @returns VINF_SUCCESS, VINF_LOG_NO_LOGGER, VINF_LOG_DISABLED, or IPRT error
4048 * status.
4049 * @param pLogger Pointer to logger instance. If NULL the default logger instance will be attempted.
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 args Format arguments.
4056 */
4057RTDECL(int) RTLogLoggerExV(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args)
4058{
4059 int rc;
4060 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
4061 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
4062
4063 /*
4064 * Validate and correct iGroup.
4065 */
4066 if (iGroup != ~0U && iGroup >= pLoggerInt->cGroups)
4067 iGroup = 0;
4068
4069 /*
4070 * If no output, then just skip it.
4071 */
4072 if ( (pLoggerInt->fFlags & RTLOGFLAGS_DISABLED)
4073 || !pLoggerInt->fDestFlags
4074 || !pszFormat || !*pszFormat)
4075 return VINF_LOG_DISABLED;
4076 if ( iGroup != ~0U
4077 && (pLoggerInt->afGroups[iGroup] & (fFlags | RTLOGGRPFLAGS_ENABLED)) != (fFlags | RTLOGGRPFLAGS_ENABLED))
4078 return VINF_LOG_DISABLED;
4079
4080 /*
4081 * Acquire logger instance sem.
4082 */
4083 rc = rtlogLock(pLoggerInt);
4084 if (RT_SUCCESS(rc))
4085 {
4086 /*
4087 * Check group restrictions and call worker.
4088 */
4089 if (RT_LIKELY( !(pLoggerInt->fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
4090 || iGroup >= pLoggerInt->cGroups
4091 || !(pLoggerInt->afGroups[iGroup] & RTLOGGRPFLAGS_RESTRICT)
4092 || ++pLoggerInt->pacEntriesPerGroup[iGroup] < pLoggerInt->cMaxEntriesPerGroup ))
4093 rtlogLoggerExVLocked(pLoggerInt, fFlags, iGroup, pszFormat, args);
4094 else
4095 {
4096 uint32_t cEntries = pLoggerInt->pacEntriesPerGroup[iGroup];
4097 if (cEntries > pLoggerInt->cMaxEntriesPerGroup)
4098 pLoggerInt->pacEntriesPerGroup[iGroup] = cEntries - 1;
4099 else
4100 {
4101 rtlogLoggerExVLocked(pLoggerInt, fFlags, iGroup, pszFormat, args);
4102 if ( pLoggerInt->papszGroups
4103 && pLoggerInt->papszGroups[iGroup])
4104 rtlogLoggerExFLocked(pLoggerInt, fFlags, iGroup, "%u messages from group %s (#%u), muting it.\n",
4105 cEntries, pLoggerInt->papszGroups[iGroup], iGroup);
4106 else
4107 rtlogLoggerExFLocked(pLoggerInt, fFlags, iGroup, "%u messages from group #%u, muting it.\n", cEntries, iGroup);
4108 }
4109 }
4110
4111 /*
4112 * Release the semaphore.
4113 */
4114 rtlogUnlock(pLoggerInt);
4115 return VINF_SUCCESS;
4116 }
4117
4118#ifdef IN_RING0
4119 if (pLoggerInt->fDestFlags & ~RTLOGDEST_FILE)
4120 {
4121 rtR0LogLoggerExFallback(pLoggerInt->fDestFlags, pLoggerInt->fFlags, pLoggerInt, pszFormat, args);
4122 return VINF_SUCCESS;
4123 }
4124#endif
4125 return rc;
4126}
4127RT_EXPORT_SYMBOL(RTLogLoggerExV);
4128
4129
4130/**
4131 * Write to a logger instance.
4132 *
4133 * @param pLogger Pointer to logger instance.
4134 * @param pszFormat Format string.
4135 * @param args Format arguments.
4136 */
4137RTDECL(void) RTLogLoggerV(PRTLOGGER pLogger, const char *pszFormat, va_list args)
4138{
4139 RTLogLoggerExV(pLogger, 0, ~0U, pszFormat, args);
4140}
4141RT_EXPORT_SYMBOL(RTLogLoggerV);
4142
4143
4144/**
4145 * vprintf like function for writing to the default log.
4146 *
4147 * @param pszFormat Printf like format string.
4148 * @param va Optional arguments as specified in pszFormat.
4149 *
4150 * @remark The API doesn't support formatting of floating point numbers at the moment.
4151 */
4152RTDECL(void) RTLogPrintfV(const char *pszFormat, va_list va)
4153{
4154 RTLogLoggerV(NULL, pszFormat, va);
4155}
4156RT_EXPORT_SYMBOL(RTLogPrintfV);
4157
4158
4159/**
4160 * Dumper vprintf-like function outputting to a logger.
4161 *
4162 * @param pvUser Pointer to the logger instance to use, NULL for
4163 * default instance.
4164 * @param pszFormat Format string.
4165 * @param va Format arguments.
4166 */
4167RTDECL(void) RTLogDumpPrintfV(void *pvUser, const char *pszFormat, va_list va)
4168{
4169 RTLogLoggerV((PRTLOGGER)pvUser, pszFormat, va);
4170}
4171RT_EXPORT_SYMBOL(RTLogDumpPrintfV);
4172
4173#ifdef IN_RING3
4174
4175/**
4176 * @callback_method_impl{FNRTLOGPHASEMSG,
4177 * Log phase callback function - assumes the lock is already held.}
4178 */
4179static DECLCALLBACK(void) rtlogPhaseMsgLocked(PRTLOGGER pLogger, const char *pszFormat, ...)
4180{
4181 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
4182 AssertPtrReturnVoid(pLoggerInt);
4183 Assert(pLoggerInt->hSpinMtx != NIL_RTSEMSPINMUTEX);
4184
4185 va_list args;
4186 va_start(args, pszFormat);
4187 rtlogLoggerExVLocked(pLoggerInt, 0, ~0U, pszFormat, args);
4188 va_end(args);
4189}
4190
4191
4192/**
4193 * @callback_method_impl{FNRTLOGPHASEMSG,
4194 * Log phase callback function - assumes the lock is not held.}
4195 */
4196static DECLCALLBACK(void) rtlogPhaseMsgNormal(PRTLOGGER pLogger, const char *pszFormat, ...)
4197{
4198 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
4199 AssertPtrReturnVoid(pLoggerInt);
4200 Assert(pLoggerInt->hSpinMtx != NIL_RTSEMSPINMUTEX);
4201
4202 va_list args;
4203 va_start(args, pszFormat);
4204 RTLogLoggerExV(&pLoggerInt->Core, 0, ~0U, pszFormat, args);
4205 va_end(args);
4206}
4207
4208#endif /* IN_RING3 */
4209
Note: See TracBrowser for help on using the repository browser.

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