VirtualBox

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

Last change on this file since 104286 was 104286, checked in by vboxsync, 5 weeks ago

IPRT/log,Main: Open the parent directory of the log file on Windows before we opening the log file and do any log rotating to prevent reparse hacks. bugref:10632

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

© 2023 Oracle
ContactPrivacy policyTerms of Use