VirtualBox

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

Last change on this file since 99241 was 98103, checked in by vboxsync, 22 months ago

Copyright year updates by scm.

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