VirtualBox

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

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

IPRT/log: Changed the default buffer size in ring-0 to 16KB as it's usually not buffered or we specify our own buffers (VMM). bugref:10086

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

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