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, 3 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
Line 
1/* $Id: log.cpp 104286 2024-04-11 01:56:27Z vboxsync $ */
2/** @file
3 * Runtime VBox - Logger.
4 */
5
6/*
7 * Copyright (C) 2006-2023 Oracle and/or its affiliates.
8 *
9 * This file is part of VirtualBox base platform packages, as
10 * available from https://www.virtualbox.org.
11 *
12 * This program is free software; you can redistribute it and/or
13 * modify it under the terms of the GNU General Public License
14 * as published by the Free Software Foundation, in version 3 of the
15 * License.
16 *
17 * This program is distributed in the hope that it will be useful, but
18 * WITHOUT ANY WARRANTY; without even the implied warranty of
19 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 * General Public License for more details.
21 *
22 * You should have received a copy of the GNU General Public License
23 * along with this program; if not, see <https://www.gnu.org/licenses>.
24 *
25 * The contents of this file may alternatively be used under the terms
26 * of the Common Development and Distribution License Version 1.0
27 * (CDDL), a copy of it is provided in the "COPYING.CDDL" file included
28 * in the VirtualBox distribution, in which case the provisions of the
29 * CDDL are applicable instead of those of the GPL.
30 *
31 * You may elect to license modified versions of this file under the
32 * terms and conditions of either the GPL or the CDDL or both.
33 *
34 * SPDX-License-Identifier: GPL-3.0-only OR CDDL-1.0
35 */
36
37
38/*********************************************************************************************************************************
39* Header Files *
40*********************************************************************************************************************************/
41#include <iprt/log.h>
42#include "internal/iprt.h"
43
44#include <iprt/alloc.h>
45#include <iprt/crc.h>
46#include <iprt/process.h>
47#include <iprt/semaphore.h>
48#include <iprt/thread.h>
49#include <iprt/mp.h>
50#ifdef IN_RING3
51# ifdef RT_OS_WINDOWS
52# include <iprt/dir.h>
53# endif
54# include <iprt/env.h>
55# include <iprt/file.h>
56# include <iprt/lockvalidator.h>
57# include <iprt/path.h>
58#endif
59#include <iprt/time.h>
60#include <iprt/asm.h>
61#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
62# include <iprt/asm-amd64-x86.h>
63#endif
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>
70#include <iprt/ctype.h>
71#ifdef IN_RING3
72# include <iprt/alloca.h>
73# ifndef IPRT_NO_CRT
74# include <stdio.h>
75# endif
76#endif
77
78
79/*********************************************************************************************************************************
80* Defined Constants And Macros *
81*********************************************************************************************************************************/
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
105/** The default buffer size. */
106#ifdef IN_RING0
107# define RTLOG_BUFFER_DEFAULT_SIZE _16K
108#else
109# define RTLOG_BUFFER_DEFAULT_SIZE _128K
110#endif
111/** Buffer alignment used RTLogCreateExV. */
112#define RTLOG_BUFFER_ALIGN 64
113
114
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
129/*********************************************************************************************************************************
130* Structures and Typedefs *
131*********************************************************************************************************************************/
132/**
133 * Internal logger data.
134 *
135 * @remarks Don't make casual changes to this structure.
136 */
137typedef struct RTLOGGERINTERNAL
138{
139 /** The public logger core. */
140 RTLOGGER Core;
141
142 /** The structure revision (RTLOGGERINTERNAL_REV). */
143 uint32_t uRevision;
144 /** The size of the internal logger structure. */
145 uint32_t cbSelf;
146
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
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. */
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;
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
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
217 /** Program time base for ring-0 (copy of g_u64ProgramStartNanoTS). */
218 uint64_t nsR0ProgramStart;
219 /** Thread name for use in ring-0 with RTLOGFLAGS_PREFIX_THREAD. */
220 char szR0ThreadName[16];
221
222#ifdef IN_RING3
223 /** @name File logging bits for the logger.
224 * @{ */
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;
229 /** Pointer to the output interface used. */
230 PCRTLOGOUTPUTIF pOutputIf;
231 /** Opaque user data passed to the callbacks in the output interface. */
232 void *pvOutputIfUser;
233 /** Opaque directory context.
234 * This is kept open while we have an open log file. */
235 void *pvDirCtx;
236
237 /** Handle to log file (if open) - only used by the default output interface to avoid additional layers of indirection. */
238 RTFILE hFile;
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;
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];
252 /** Flag whether the log file was opened successfully. */
253 bool fLogOpened;
254 /** @} */
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];
264} RTLOGGERINTERNAL;
265
266/** The revision of the internal logger structure. */
267# define RTLOGGERINTERNAL_REV UINT32_C(14)
268
269AssertCompileMemberAlignment(RTLOGGERINTERNAL, cbRingBufUnflushed, sizeof(uint64_t));
270#ifdef IN_RING3
271AssertCompileMemberAlignment(RTLOGGERINTERNAL, hFile, sizeof(void *));
272AssertCompileMemberAlignment(RTLOGGERINTERNAL, cbHistoryFileMax, sizeof(uint64_t));
273#endif
274
275/** Pointer to internal logger bits. */
276typedef struct RTLOGGERINTERNAL *PRTLOGGERINTERNAL;
277
278
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;
290 /** Used by RTLogBulkNestedWrite. */
291 const char *pszInfix;
292} RTLOGOUTPUTPREFIXEDARGS, *PRTLOGOUTPUTPREFIXEDARGS;
293
294
295/*********************************************************************************************************************************
296* Internal Functions *
297*********************************************************************************************************************************/
298static unsigned rtlogGroupFlags(const char *psz);
299#ifdef IN_RING3
300static int rtR3LogOpenFileDestination(PRTLOGGERINTERNAL pLoggerInt, PRTERRINFO pErrInfo);
301#endif
302static void rtLogRingBufFlush(PRTLOGGERINTERNAL pLoggerInt);
303static void rtlogFlush(PRTLOGGERINTERNAL pLoggerInt, bool fNeedSpace);
304#ifdef IN_RING3
305static FNRTLOGPHASEMSG rtlogPhaseMsgLocked;
306static FNRTLOGPHASEMSG rtlogPhaseMsgNormal;
307#endif
308static DECLCALLBACK(size_t) rtLogOutputPrefixed(void *pv, const char *pachChars, size_t cbChars);
309static void rtlogLoggerExFLocked(PRTLOGGERINTERNAL pLoggerInt, unsigned fFlags, unsigned iGroup, const char *pszFormat, ...);
310
311
312/*********************************************************************************************************************************
313* Global Variables *
314*********************************************************************************************************************************/
315/** Default logger instance. */
316static PRTLOGGER g_pLogger;
317/** Default release logger instance. */
318static PRTLOGGER g_pRelLogger;
319#ifdef IN_RING3
320/** The RTThreadGetWriteLockCount() change caused by the logger mutex semaphore. */
321static uint32_t volatile g_cLoggerLockCount;
322#endif
323
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. */
333 RTNATIVETHREAD volatile NativeThread;
334 /** The (process / session) key. */
335 uintptr_t volatile uKey;
336 /** The logger instance.*/
337 PRTLOGGER volatile pLogger;
338} g_aPerThreadLoggers[8] =
339{
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},
346 { NIL_RTNATIVETHREAD, 0, 0},
347 { NIL_RTNATIVETHREAD, 0, 0}
348};
349#endif /* IN_RING0 */
350
351/**
352 * Logger flags instructions.
353 */
354static struct
355{
356 const char *pszInstr; /**< The name */
357 size_t cchInstr; /**< The size of the name. */
358 uint64_t fFlag; /**< The flag value. */
359 bool fInverted; /**< Inverse meaning? */
360 uint32_t fFixedDest; /**< RTLOGDEST_FIXED_XXX flags blocking this. */
361} const g_aLogFlags[] =
362{
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 },
393 /* We intentionally omit RTLOGFLAGS_RESTRICT_GROUPS. */
394};
395
396/**
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. */
404} const g_aLogDst[] =
405{
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 },
416 { RT_STR_TUPLE("nodeny"), RTLOGDEST_F_NO_DENY },
417 { RT_STR_TUPLE("vmmrel"), RTLOGDEST_VMM_REL }, /* before vmm */
418 { RT_STR_TUPLE("vmm"), RTLOGDEST_VMM },
419 { RT_STR_TUPLE("user"), RTLOGDEST_USER },
420 /* The RTLOGDEST_FIXED_XXX flags are omitted on purpose. */
421};
422
423#ifdef IN_RING3
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.
428 */
429static const uint32_t g_acMsLogBackoff[] =
430{ 10, 10, 10, 20, 50, 100, 200, 200, 200, 200, 500, 500, 500, 500, 1000, 1000, 1000, 1000, 1000, 1000, 1000 };
431#endif
432
433
434/**
435 * Locks the logger instance.
436 *
437 * @returns See RTSemSpinMutexRequest().
438 * @param pLoggerInt The logger instance.
439 */
440DECLINLINE(int) rtlogLock(PRTLOGGERINTERNAL pLoggerInt)
441{
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),
445 VERR_LOG_REVISION_MISMATCH);
446 AssertMsgReturn(pLoggerInt->cbSelf == sizeof(*pLoggerInt), ("%#x != %#x\n", pLoggerInt->cbSelf, sizeof(*pLoggerInt)),
447 VERR_LOG_REVISION_MISMATCH);
448 if (pLoggerInt->hSpinMtx != NIL_RTSEMSPINMUTEX)
449 {
450 int rc = RTSemSpinMutexRequest(pLoggerInt->hSpinMtx);
451 if (RT_FAILURE(rc))
452 return rc;
453 }
454 return VINF_SUCCESS;
455}
456
457
458/**
459 * Unlocks the logger instance.
460 * @param pLoggerInt The logger instance.
461 */
462DECLINLINE(void) rtlogUnlock(PRTLOGGERINTERNAL pLoggerInt)
463{
464 if (pLoggerInt->hSpinMtx != NIL_RTSEMSPINMUTEX)
465 RTSemSpinMutexRelease(pLoggerInt->hSpinMtx);
466 return;
467}
468
469
470/*********************************************************************************************************************************
471* Logger Instance Management. *
472*********************************************************************************************************************************/
473
474/**
475 * Common worker for RTLogDefaultInstance and RTLogDefaultInstanceEx.
476 */
477DECL_NO_INLINE(static, PRTLOGGER) rtLogDefaultInstanceCreateNew(void)
478{
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))
488 {
489 pRet = RTLogDefaultInit();
490 if (pRet)
491 {
492 bool fRc = ASMAtomicCmpXchgPtr(&g_pLogger, pRet, NULL);
493 if (!fRc)
494 {
495 RTLogDestroy(pRet);
496 pRet = g_pLogger;
497 }
498 }
499 ASMAtomicWriteBool(&s_fCreating, true);
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
558 && ( (pLoggerInt->afGroups[iGroup < pLoggerInt->cGroups ? iGroup : 0] & (fFlags | RTLOGGRPFLAGS_ENABLED))
559 != (fFlags | RTLOGGRPFLAGS_ENABLED)))
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)
619{
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
629 return ASMAtomicXchgPtrT(&g_pLogger, pLogger, PRTLOGGER);
630}
631RT_EXPORT_SYMBOL(RTLogSetDefaultInstance);
632
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;
716}
717RT_EXPORT_SYMBOL(RTLogSetDefaultInstanceThread);
718#endif /* IN_RING0 */
719
720
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)
739{
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
749 return ASMAtomicXchgPtrT(&g_pRelLogger, pLogger, PRTLOGGER);
750}
751RT_EXPORT_SYMBOL(RTLogRelSetDefaultInstance);
752
753
754RTDECL(PRTLOGGER) RTLogCheckGroupFlags(PRTLOGGER pLogger, uint32_t fFlagsAndGroup)
755{
756 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
757 if (pLoggerInt)
758 pLoggerInt = rtLogCheckGroupFlagsWorker(pLoggerInt, fFlagsAndGroup);
759 return (PRTLOGGER)pLoggerInt;
760}
761RT_EXPORT_SYMBOL(RTLogCheckGroupFlags);
762
763
764/*********************************************************************************************************************************
765* Default file I/O interface *
766*********************************************************************************************************************************/
767
768#ifdef IN_RING3
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)
777{
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{
853 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pvUser;
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
860
861 return RTFileOpen(&pLoggerInt->hFile, pszFilename, fFlags);
862}
863
864
865/**
866 * @callback_method_impl{RTLOGOUTPUTIF,pfnClose}
867 */
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
882/**
883 * @callback_method_impl{RTLOGOUTPUTIF,pfnQuerySize}
884 */
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
898/**
899 * @callback_method_impl{RTLOGOUTPUTIF,pfnWrite}
900 */
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
914/**
915 * @callback_method_impl{RTLOGOUTPUTIF,pfnFlush}
916 */
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{
934 rtLogOutputIfDefDirCtxOpen,
935 rtLogOutputIfDefDirCtxClose,
936 rtLogOutputIfDefDelete,
937 rtLogOutputIfDefRename,
938 rtLogOutputIfDefOpen,
939 rtLogOutputIfDefClose,
940 rtLogOutputIfDefQuerySize,
941 rtLogOutputIfDefWrite,
942 rtLogOutputIfDefFlush
943};
944
945#endif /* IN_RING3 */
946
947
948/*********************************************************************************************************************************
949* Ring Buffer *
950*********************************************************************************************************************************/
951
952/**
953 * Adjusts the ring buffer.
954 *
955 * @returns IPRT status code.
956 * @param pLoggerInt The logger instance.
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 */
961static int rtLogRingBufAdjust(PRTLOGGERINTERNAL pLoggerInt, uint32_t cbNewSize, bool fForce)
962{
963 /*
964 * If this is early logger init, don't do anything.
965 */
966 if (!pLoggerInt->fCreated && !fForce)
967 return VINF_SUCCESS;
968
969 /*
970 * Lock the logger and make the necessary changes.
971 */
972 int rc = rtlogLock(pLoggerInt);
973 if (RT_SUCCESS(rc))
974 {
975 if (cbNewSize == 0)
976 cbNewSize = RTLOG_RINGBUF_DEFAULT_SIZE;
977 if ( pLoggerInt->cbRingBuf != cbNewSize
978 || !pLoggerInt->pchRingBufCur)
979 {
980 uintptr_t offOld = pLoggerInt->pchRingBufCur - pLoggerInt->pszRingBuf;
981 if (offOld < sizeof(RTLOG_RINGBUF_EYE_CATCHER))
982 offOld = sizeof(RTLOG_RINGBUF_EYE_CATCHER);
983 else if (offOld >= cbNewSize)
984 {
985 memmove(pLoggerInt->pszRingBuf, &pLoggerInt->pszRingBuf[offOld - cbNewSize], cbNewSize);
986 offOld = sizeof(RTLOG_RINGBUF_EYE_CATCHER);
987 }
988
989 void *pvNew = RTMemRealloc(pLoggerInt->pchRingBufCur, cbNewSize);
990 if (pvNew)
991 {
992 pLoggerInt->pszRingBuf = (char *)pvNew;
993 pLoggerInt->pchRingBufCur = (char *)pvNew + offOld;
994 pLoggerInt->cbRingBuf = cbNewSize;
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 }
1003 rtlogUnlock(pLoggerInt);
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 *
1085 * @param pLoggerInt The logger instance which ring buffer should be flushed.
1086 */
1087static void rtLogRingBufFlush(PRTLOGGERINTERNAL pLoggerInt)
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 */
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;
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
1113 pLoggerInt->cbRingBufUnflushed = 0;
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 */
1154 if (pLoggerInt->fDestFlags & RTLOGDEST_USER)
1155 {
1156 if (cchPreamble)
1157 RTLogWriteUser(pszPreamble, cchPreamble);
1158 if (cchFirst)
1159 RTLogWriteUser(pszFirst, cchFirst);
1160 if (cchSecond)
1161 RTLogWriteUser(pszSecond, cchSecond);
1162 }
1163
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
1186 if (pLoggerInt->fDestFlags & RTLOGDEST_DEBUGGER)
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
1197 if (pLoggerInt->fDestFlags & RTLOGDEST_FILE)
1198 {
1199 if (pLoggerInt->fLogOpened)
1200 {
1201 if (cchPreamble)
1202 pLoggerInt->pOutputIf->pfnWrite(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser,
1203 pszPreamble, cchPreamble, NULL /*pcbWritten*/);
1204 if (cchFirst)
1205 pLoggerInt->pOutputIf->pfnWrite(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser,
1206 pszFirst, cchFirst, NULL /*pcbWritten*/);
1207 if (cchSecond)
1208 pLoggerInt->pOutputIf->pfnWrite(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser,
1209 pszSecond, cchSecond, NULL /*pcbWritten*/);
1210 if (pLoggerInt->fFlags & RTLOGFLAGS_FLUSH)
1211 pLoggerInt->pOutputIf->pfnFlush(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser);
1212 }
1213 if (pLoggerInt->cHistory)
1214 pLoggerInt->cbHistoryFileWritten += cchFirst + cchSecond;
1215 }
1216# endif
1217
1218 if (pLoggerInt->fDestFlags & RTLOGDEST_STDOUT)
1219 {
1220 if (cchPreamble)
1221 RTLogWriteStdOut(pszPreamble, cchPreamble);
1222 if (cchFirst)
1223 RTLogWriteStdOut(pszFirst, cchFirst);
1224 if (cchSecond)
1225 RTLogWriteStdOut(pszSecond, cchSecond);
1226 }
1227
1228 if (pLoggerInt->fDestFlags & RTLOGDEST_STDERR)
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)
1239 if (pLoggerInt->fDestFlags & RTLOGDEST_COM)
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
1252/*********************************************************************************************************************************
1253* Create, Destroy, Setup *
1254*********************************************************************************************************************************/
1255
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,
1258 uint32_t cBufDescs, PRTLOGBUFFERDESC paBufDescs, uint32_t fDestFlags,
1259 PFNRTLOGPHASE pfnPhase, uint32_t cHistory, uint64_t cbHistoryFileMax, uint32_t cSecsHistoryTimeSlot,
1260 PCRTLOGOUTPUTIF pOutputIf, void *pvOutputIfUser,
1261 PRTERRINFO pErrInfo, const char *pszFilenameFmt, va_list args)
1262{
1263 int rc;
1264 size_t cbLogger;
1265 size_t offBuffers;
1266 PRTLOGGERINTERNAL pLoggerInt;
1267 uint32_t i;
1268
1269 /*
1270 * Validate input.
1271 */
1272 AssertPtrReturn(ppLogger, VERR_INVALID_POINTER);
1273 *ppLogger = NULL;
1274 if (cGroups)
1275 {
1276 AssertPtrReturn(papszGroups, VERR_INVALID_POINTER);
1277 AssertReturn(cGroups < _8K, VERR_OUT_OF_RANGE);
1278 }
1279 AssertMsgReturn(cHistory < _1M, ("%#x", cHistory), VERR_OUT_OF_RANGE);
1280 AssertReturn(cBufDescs <= 128, VERR_OUT_OF_RANGE);
1281
1282 /*
1283 * Calculate the logger size.
1284 */
1285 AssertCompileSize(RTLOGGER, 32);
1286 cbLogger = RT_UOFFSETOF_DYN(RTLOGGERINTERNAL, afGroups[cGroups]);
1287 if (fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
1288 cbLogger += cGroups * sizeof(uint32_t);
1289 if (cBufDescs == 0)
1290 {
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 {
1335# if defined(RT_ARCH_X86) && !defined(LOG_USE_C99)
1336 uint8_t *pu8Code;
1337# endif
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;
1345 pLoggerInt->pfnFlush = NULL;
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;
1354 if (fFlags & RTLOGFLAGS_RESTRICT_GROUPS)
1355 pLoggerInt->pacEntriesPerGroup = &pLoggerInt->afGroups[cGroups];
1356 else
1357 pLoggerInt->pacEntriesPerGroup = NULL;
1358 pLoggerInt->cMaxEntriesPerGroup = cMaxEntriesPerGroup ? cMaxEntriesPerGroup : UINT32_MAX;
1359# ifdef IN_RING3
1360 pLoggerInt->pfnPhase = pfnPhase;
1361 pLoggerInt->hFile = NIL_RTFILE;
1362 pLoggerInt->fLogOpened = false;
1363 pLoggerInt->cHistory = cHistory;
1364 if (cbHistoryFileMax == 0)
1365 pLoggerInt->cbHistoryFileMax = UINT64_MAX;
1366 else
1367 pLoggerInt->cbHistoryFileMax = cbHistoryFileMax;
1368 if (cSecsHistoryTimeSlot == 0)
1369 pLoggerInt->cSecsHistoryTimeSlot = UINT32_MAX;
1370 else
1371 pLoggerInt->cSecsHistoryTimeSlot = cSecsHistoryTimeSlot;
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
1385# else /* !IN_RING3 */
1386 RT_NOREF_PV(pfnPhase); RT_NOREF_PV(cHistory); RT_NOREF_PV(cbHistoryFileMax); RT_NOREF_PV(cSecsHistoryTimeSlot);
1387 RT_NOREF_PV(pOutputIf); RT_NOREF_PV(pvOutputIfUser);
1388# endif /* !IN_RING3 */
1389 if (pszGroupSettings)
1390 RTLogGroupSettings(&pLoggerInt->Core, pszGroupSettings);
1391
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
1434# if defined(RT_ARCH_X86) && !defined(LOG_USE_C99) && 0 /* retired */
1435 /*
1436 * Emit wrapper code.
1437 */
1438 pu8Code = (uint8_t *)RTMemExecAlloc(64);
1439 if (pu8Code)
1440 {
1441 pLoggerInt->Core.pfnLogger = *(PFNRTLOGGER *)&pu8Code;
1442 *pu8Code++ = 0x68; /* push imm32 */
1443 *(void **)pu8Code = &pLoggerInt->Core;
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 */
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));
1455 rc = VINF_SUCCESS;
1456 }
1457 else
1458 {
1459 rc = VERR_NO_MEMORY;
1460# ifdef RT_OS_LINUX
1461 /* Most probably SELinux causing trouble since the larger RTMemAlloc succeeded. */
1462 RTErrInfoSet(pErrInfo, rc, N_("mmap(PROT_WRITE | PROT_EXEC) failed -- SELinux?"));
1463# endif
1464 }
1465 if (RT_SUCCESS(rc))
1466# endif /* X86 wrapper code */
1467 {
1468# ifdef IN_RING3 /* files and env.vars. are only accessible when in R3 at the present time. */
1469 /*
1470 * Format the filename.
1471 */
1472 if (pszFilenameFmt)
1473 {
1474 /** @todo validate the length, fail on overflow. */
1475 RTStrPrintfV(pLoggerInt->szFilename, sizeof(pLoggerInt->szFilename), pszFilenameFmt, args);
1476 if (pLoggerInt->szFilename[0])
1477 pLoggerInt->fDestFlags |= RTLOGDEST_FILE;
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");
1494 const char *pszValue = RTEnvGet(pszEnvVar);
1495 if (pszValue)
1496 RTLogDestinations(&pLoggerInt->Core, pszValue);
1497
1498 /*
1499 * The flags.
1500 */
1501 strcpy(pszEnvVar + cchEnvVarBase, "_FLAGS");
1502 pszValue = RTEnvGet(pszEnvVar);
1503 if (pszValue)
1504 RTLogFlags(&pLoggerInt->Core, pszValue);
1505
1506 /*
1507 * The group settings.
1508 */
1509 pszEnvVar[cchEnvVarBase] = '\0';
1510 pszValue = RTEnvGet(pszEnvVar);
1511 if (pszValue)
1512 RTLogGroupSettings(&pLoggerInt->Core, pszValue);
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))
1524 pLoggerInt->cMaxEntriesPerGroup = cMax ? cMax : UINT32_MAX;
1525 else
1526 AssertMsgFailed(("Invalid group limit! %s=%s\n", pszEnvVar, pszValue));
1527 }
1528
1529 }
1530# else /* !IN_RING3 */
1531 RT_NOREF_PV(pszEnvVarBase); RT_NOREF_PV(pszFilenameFmt); RT_NOREF_PV(args);
1532# endif /* !IN_RING3 */
1533
1534 /*
1535 * Open the destination(s).
1536 */
1537 rc = VINF_SUCCESS;
1538 if ((pLoggerInt->fDestFlags & (RTLOGDEST_F_DELAY_FILE | RTLOGDEST_FILE)) == RTLOGDEST_F_DELAY_FILE)
1539 pLoggerInt->fDestFlags &= ~RTLOGDEST_F_DELAY_FILE;
1540# ifdef IN_RING3
1541 if ((pLoggerInt->fDestFlags & (RTLOGDEST_FILE | RTLOGDEST_F_DELAY_FILE)) == RTLOGDEST_FILE)
1542 rc = rtR3LogOpenFileDestination(pLoggerInt, pErrInfo);
1543# endif
1544
1545 if ((pLoggerInt->fDestFlags & RTLOGDEST_RINGBUF) && RT_SUCCESS(rc))
1546 rc = rtLogRingBufAdjust(pLoggerInt, pLoggerInt->cbRingBuf, true /*fForce*/);
1547
1548 /*
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.
1551 */
1552 if (RT_SUCCESS(rc))
1553 {
1554 if (!(fFlags & RTLOG_F_NO_LOCKING))
1555 rc = RTSemSpinMutexCreate(&pLoggerInt->hSpinMtx, RTSEMSPINMUTEX_FLAGS_IRQ_SAFE);
1556 if (RT_SUCCESS(rc))
1557 {
1558# ifdef IN_RING3 /** @todo do counters in ring-0 too? */
1559 RTTHREAD Thread = RTThreadSelf();
1560 if (Thread != NIL_RTTHREAD)
1561 {
1562 int32_t c = RTLockValidatorWriteLockGetCount(Thread);
1563 RTSemSpinMutexRequest(pLoggerInt->hSpinMtx);
1564 c = RTLockValidatorWriteLockGetCount(Thread) - c;
1565 RTSemSpinMutexRelease(pLoggerInt->hSpinMtx);
1566 ASMAtomicWriteU32(&g_cLoggerLockCount, c);
1567 }
1568
1569 /* Use the callback to generate some initial log contents. */
1570 AssertPtrNull(pLoggerInt->pfnPhase);
1571 if (pLoggerInt->pfnPhase)
1572 pLoggerInt->pfnPhase(&pLoggerInt->Core, RTLOGPHASE_BEGIN, rtlogPhaseMsgNormal);
1573# endif
1574 pLoggerInt->fCreated = true;
1575 *ppLogger = &pLoggerInt->Core;
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
1582 return VINF_SUCCESS;
1583 }
1584
1585 RTErrInfoSet(pErrInfo, rc, N_("failed to create semaphore"));
1586 }
1587# ifdef IN_RING3
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
1595# if defined(RT_ARCH_X86) && !defined(LOG_USE_C99) && 0 /* retired */
1596 if (pLoggerInt->Core.pfnLogger)
1597 {
1598 RTMemExecFree(*(void **)&pLoggerInt->Core.pfnLogger, 64);
1599 pLoggerInt->Core.pfnLogger = NULL;
1600 }
1601# endif
1602 }
1603 RTMemFree(pLoggerInt);
1604 }
1605 else
1606 rc = VERR_NO_MEMORY;
1607
1608 return rc;
1609}
1610RT_EXPORT_SYMBOL(RTLogCreateExV);
1611
1612
1613RTDECL(int) RTLogCreate(PRTLOGGER *ppLogger, uint64_t fFlags, const char *pszGroupSettings,
1614 const char *pszEnvVarBase, unsigned cGroups, const char * const * papszGroups,
1615 uint32_t fDestFlags, const char *pszFilenameFmt, ...)
1616{
1617 va_list va;
1618 int rc;
1619
1620 va_start(va, pszFilenameFmt);
1621 rc = RTLogCreateExV(ppLogger, pszEnvVarBase, fFlags, pszGroupSettings, cGroups, papszGroups,
1622 UINT32_MAX /*cMaxEntriesPerGroup*/,
1623 0 /*cBufDescs*/, NULL /*paBufDescs*/, fDestFlags,
1624 NULL /*pfnPhase*/, 0 /*cHistory*/, 0 /*cbHistoryFileMax*/, 0 /*cSecsHistoryTimeSlot*/,
1625 NULL /*pOutputIf*/, NULL /*pvOutputIfUser*/,
1626 NULL /*pErrInfo*/, pszFilenameFmt, va);
1627 va_end(va);
1628 return rc;
1629}
1630RT_EXPORT_SYMBOL(RTLogCreate);
1631
1632
1633RTDECL(int) RTLogDestroy(PRTLOGGER pLogger)
1634{
1635 int rc;
1636 uint32_t iGroup;
1637 RTSEMSPINMUTEX hSpinMtx;
1638 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1639
1640 /*
1641 * Validate input.
1642 */
1643 if (!pLoggerInt)
1644 return VINF_SUCCESS;
1645 AssertPtrReturn(pLoggerInt, VERR_INVALID_POINTER);
1646 AssertReturn(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
1647
1648 /*
1649 * Acquire logger instance sem and disable all logging. (paranoia)
1650 */
1651 rc = rtlogLock(pLoggerInt);
1652 AssertMsgRCReturn(rc, ("%Rrc\n", rc), rc);
1653
1654 pLoggerInt->fFlags |= RTLOGFLAGS_DISABLED;
1655 iGroup = pLoggerInt->cGroups;
1656 while (iGroup-- > 0)
1657 pLoggerInt->afGroups[iGroup] = 0;
1658
1659 /*
1660 * Flush it.
1661 */
1662 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
1663
1664# ifdef IN_RING3
1665 /*
1666 * Add end of logging message.
1667 */
1668 if ( (pLoggerInt->fDestFlags & RTLOGDEST_FILE)
1669 && pLoggerInt->fLogOpened)
1670 pLoggerInt->pfnPhase(&pLoggerInt->Core, RTLOGPHASE_END, rtlogPhaseMsgLocked);
1671
1672 /*
1673 * Close output stuffs.
1674 */
1675 if (pLoggerInt->fLogOpened)
1676 {
1677 int rc2 = pLoggerInt->pOutputIf->pfnClose(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser);
1678 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1679 rc = rc2;
1680 pLoggerInt->fLogOpened = false;
1681
1682 pLoggerInt->pOutputIf->pfnDirCtxClose(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx);
1683 pLoggerInt->pvDirCtx = NULL;
1684 }
1685# endif
1686
1687 /*
1688 * Free the mutex, the wrapper and the instance memory.
1689 */
1690 hSpinMtx = pLoggerInt->hSpinMtx;
1691 pLoggerInt->hSpinMtx = NIL_RTSEMSPINMUTEX;
1692 if (hSpinMtx != NIL_RTSEMSPINMUTEX)
1693 {
1694 int rc2;
1695 RTSemSpinMutexRelease(hSpinMtx);
1696 rc2 = RTSemSpinMutexDestroy(hSpinMtx);
1697 AssertRC(rc2);
1698 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
1699 rc = rc2;
1700 }
1701
1702# if defined(RT_ARCH_X86) && !defined(LOG_USE_C99) && 0 /* retired */
1703 if (pLoggerInt->Core.pfnLogger)
1704 {
1705 RTMemExecFree(*(void **)&pLoggerInt->Core.pfnLogger, 64);
1706 pLoggerInt->Core.pfnLogger = NULL;
1707 }
1708# endif
1709 RTMemFree(pLoggerInt);
1710
1711 return rc;
1712}
1713RT_EXPORT_SYMBOL(RTLogDestroy);
1714
1715
1716RTDECL(int) RTLogSetCustomPrefixCallback(PRTLOGGER pLogger, PFNRTLOGPREFIX pfnCallback, void *pvUser)
1717{
1718 int rc;
1719 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1720 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
1721
1722 /*
1723 * Do the work.
1724 */
1725 rc = rtlogLock(pLoggerInt);
1726 if (RT_SUCCESS(rc))
1727 {
1728 pLoggerInt->pvPrefixUserArg = pvUser;
1729 pLoggerInt->pfnPrefix = pfnCallback;
1730 rtlogUnlock(pLoggerInt);
1731 }
1732
1733 return rc;
1734}
1735RT_EXPORT_SYMBOL(RTLogSetCustomPrefixCallback);
1736
1737
1738RTDECL(int) RTLogSetFlushCallback(PRTLOGGER pLogger, PFNRTLOGFLUSH pfnFlush)
1739{
1740 int rc;
1741 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1742 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
1743
1744 /*
1745 * Do the work.
1746 */
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 }
1755
1756 return rc;
1757}
1758RT_EXPORT_SYMBOL(RTLogSetFlushCallback);
1759
1760
1761/**
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 */
1771static bool rtlogIsGroupMatching(const char *pszGrp, const char **ppachMask, size_t cchMask)
1772{
1773 const char *pachMask;
1774
1775 if (!pszGrp || !*pszGrp)
1776 return false;
1777 pachMask = *ppachMask;
1778 for (;;)
1779 {
1780 if (RT_C_TO_LOWER(*pszGrp) != RT_C_TO_LOWER(*pachMask))
1781 {
1782 const char *pszTmp;
1783
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) */
1801 pszTmp = strchr(pszGrp, RT_C_TO_LOWER(*pachMask));
1802 if (!pszTmp)
1803 pszTmp = strchr(pszGrp, RT_C_TO_UPPER(*pachMask));
1804 if (!pszTmp)
1805 return false;
1806 pszGrp = pszTmp;
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
1837RTDECL(int) RTLogGroupSettings(PRTLOGGER pLogger, const char *pszValue)
1838{
1839 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
1840 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
1841 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
1842
1843 /*
1844 * Iterate the string.
1845 */
1846 while (*pszValue)
1847 {
1848 /*
1849 * Skip prefixes (blanks, ;, + and -).
1850 */
1851 bool fEnabled = true;
1852 char ch;
1853 const char *pszStart;
1854 unsigned i;
1855 size_t cch;
1856
1857 while ((ch = *pszValue) == '+' || ch == '-' || ch == ' ' || ch == '\t' || ch == '\n' || ch == ';')
1858 {
1859 if (ch == '+' || ch == '-' || ch == ';')
1860 fEnabled = ch != '-';
1861 pszValue++;
1862 }
1863 if (!*pszValue)
1864 break;
1865
1866 /*
1867 * Find end.
1868 */
1869 pszStart = pszValue;
1870 while ((ch = *pszValue) != '\0' && ch != '+' && ch != '-' && ch != ' ' && ch != '\t')
1871 pszValue++;
1872
1873 /*
1874 * Find the group (ascii case insensitive search).
1875 * Special group 'all'.
1876 */
1877 cch = pszValue - pszStart;
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]);
1890 for (i = 0; i < pLoggerInt->cGroups; i++)
1891 {
1892 if (fEnabled)
1893 pLoggerInt->afGroups[i] |= fFlags;
1894 else
1895 pLoggerInt->afGroups[i] &= ~fFlags;
1896 }
1897 }
1898 else
1899 {
1900 /*
1901 * Specific group(s).
1902 */
1903 for (i = 0; i < pLoggerInt->cGroups; i++)
1904 {
1905 const char *psz2 = (const char*)pszStart;
1906 if (rtlogIsGroupMatching(pLoggerInt->papszGroups[i], &psz2, cch))
1907 {
1908 unsigned fFlags = RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1;
1909 if (*psz2 == '.' || *psz2 == '=')
1910 fFlags = rtlogGroupFlags(psz2);
1911 if (fEnabled)
1912 pLoggerInt->afGroups[i] |= fFlags;
1913 else
1914 pLoggerInt->afGroups[i] &= ~fFlags;
1915 }
1916 } /* for each group */
1917 }
1918
1919 } /* parse specification */
1920
1921 return VINF_SUCCESS;
1922}
1923RT_EXPORT_SYMBOL(RTLogGroupSettings);
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 /*
1937 * Literal flags.
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 },
1949 { "e", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_WARN },
1950 { "enabled", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_WARN },
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 },
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 },
1976 { "f", RTLOGGRPFLAGS_FLOW },
1977 { "flow", RTLOGGRPFLAGS_FLOW },
1978 { "w", RTLOGGRPFLAGS_WARN },
1979 { "warn", RTLOGGRPFLAGS_WARN },
1980 { "warning", RTLOGGRPFLAGS_WARN },
1981 { "restrict", RTLOGGRPFLAGS_RESTRICT },
1982
1983 };
1984 unsigned i;
1985 bool fFound = false;
1986 psz++;
1987 for (i = 0; i < RT_ELEMENTS(aFlags) && !fFound; i++)
1988 {
1989 const char *psz1 = aFlags[i].pszFlag;
1990 const char *psz2 = psz;
1991 while (*psz1 == RT_C_TO_LOWER(*psz2))
1992 {
1993 psz1++;
1994 psz2++;
1995 if (!*psz1)
1996 {
1997 if ( (*psz2 >= 'a' && *psz2 <= 'z')
1998 || (*psz2 >= 'A' && *psz2 <= 'Z')
1999 || (*psz2 >= '0' && *psz2 <= '9') )
2000 break;
2001 fFlags |= aFlags[i].fFlag;
2002 fFound = true;
2003 psz = psz2;
2004 break;
2005 }
2006 } /* strincmp */
2007 } /* for each flags */
2008 AssertMsg(fFound, ("%.15s...", psz));
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
2026
2027/**
2028 * Helper for RTLogGetGroupSettings.
2029 */
2030static int rtLogGetGroupSettingsAddOne(const char *pszName, uint32_t fGroup, char **ppszBuf, size_t *pcchBuf, bool *pfNotFirst)
2031{
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)
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
2070#undef APPEND_PSZ
2071#undef APPEND_SZ
2072#undef APPEND_CH
2073 return VINF_SUCCESS;
2074}
2075
2076
2077RTDECL(int) RTLogQueryGroupSettings(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
2078{
2079 bool fNotFirst = false;
2080 int rc = VINF_SUCCESS;
2081 uint32_t cGroups;
2082 uint32_t fGroup;
2083 uint32_t i;
2084 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2085 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2086 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2087 Assert(cchBuf);
2088
2089 /*
2090 * Check if all are the same.
2091 */
2092 cGroups = pLoggerInt->cGroups;
2093 fGroup = pLoggerInt->afGroups[0];
2094 for (i = 1; i < cGroups; i++)
2095 if (pLoggerInt->afGroups[i] != fGroup)
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 {
2107 fGroup = pLoggerInt->afGroups[i];
2108 if (fGroup)
2109 {
2110 const char *pszName = pLoggerInt->papszGroups[i];
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}
2124RT_EXPORT_SYMBOL(RTLogQueryGroupSettings);
2125
2126
2127RTDECL(int) RTLogFlags(PRTLOGGER pLogger, const char *pszValue)
2128{
2129 int rc = VINF_SUCCESS;
2130 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2131 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2132 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2133
2134 /*
2135 * Iterate the string.
2136 */
2137 while (*pszValue)
2138 {
2139 /* check no prefix. */
2140 bool fNo = false;
2141 char ch;
2142 unsigned i;
2143
2144 /* skip blanks. */
2145 while (RT_C_IS_SPACE(*pszValue))
2146 pszValue++;
2147 if (!*pszValue)
2148 return rc;
2149
2150 while ((ch = *pszValue) != '\0')
2151 {
2152 if (ch == 'n' && pszValue[1] == 'o')
2153 {
2154 pszValue += 2;
2155 fNo = !fNo;
2156 }
2157 else if (ch == '+')
2158 {
2159 pszValue++;
2160 fNo = true;
2161 }
2162 else if (ch == '-' || ch == '!' || ch == '~')
2163 {
2164 pszValue++;
2165 fNo = !fNo;
2166 }
2167 else
2168 break;
2169 }
2170
2171 /* instruction. */
2172 for (i = 0; i < RT_ELEMENTS(g_aLogFlags); i++)
2173 {
2174 if (!strncmp(pszValue, g_aLogFlags[i].pszInstr, g_aLogFlags[i].cchInstr))
2175 {
2176 if (!(g_aLogFlags[i].fFixedDest & pLoggerInt->fDestFlags))
2177 {
2178 if (fNo == g_aLogFlags[i].fInverted)
2179 pLoggerInt->fFlags |= g_aLogFlags[i].fFlag;
2180 else
2181 pLoggerInt->fFlags &= ~g_aLogFlags[i].fFlag;
2182 }
2183 pszValue += g_aLogFlags[i].cchInstr;
2184 break;
2185 }
2186 }
2187
2188 /* unknown instruction? */
2189 if (i >= RT_ELEMENTS(g_aLogFlags))
2190 {
2191 AssertMsgFailed(("Invalid flags! unknown instruction %.20s\n", pszValue));
2192 pszValue++;
2193 }
2194
2195 /* skip blanks and delimiters. */
2196 while (RT_C_IS_SPACE(*pszValue) || *pszValue == ';')
2197 pszValue++;
2198 } /* while more environment variable value left */
2199
2200 return rc;
2201}
2202RT_EXPORT_SYMBOL(RTLogFlags);
2203
2204
2205RTDECL(bool) RTLogSetBuffering(PRTLOGGER pLogger, bool fBuffered)
2206{
2207 int rc;
2208 bool fOld = false;
2209 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2210 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, false);
2211
2212 rc = rtlogLock(pLoggerInt);
2213 if (RT_SUCCESS(rc))
2214 {
2215 fOld = !!(pLoggerInt->fFlags & RTLOGFLAGS_BUFFERED);
2216 if (fBuffered)
2217 pLoggerInt->fFlags |= RTLOGFLAGS_BUFFERED;
2218 else
2219 pLoggerInt->fFlags &= ~RTLOGFLAGS_BUFFERED;
2220 rtlogUnlock(pLoggerInt);
2221 }
2222
2223 return fOld;
2224}
2225RT_EXPORT_SYMBOL(RTLogSetBuffering);
2226
2227
2228RTDECL(uint32_t) RTLogSetGroupLimit(PRTLOGGER pLogger, uint32_t cMaxEntriesPerGroup)
2229{
2230 int rc;
2231 uint32_t cOld = UINT32_MAX;
2232 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2233 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, UINT32_MAX);
2234
2235 rc = rtlogLock(pLoggerInt);
2236 if (RT_SUCCESS(rc))
2237 {
2238 cOld = pLoggerInt->cMaxEntriesPerGroup;
2239 pLoggerInt->cMaxEntriesPerGroup = cMaxEntriesPerGroup;
2240 rtlogUnlock(pLoggerInt);
2241 }
2242
2243 return cOld;
2244}
2245RT_EXPORT_SYMBOL(RTLogSetGroupLimit);
2246
2247
2248#ifdef IN_RING0
2249
2250RTR0DECL(int) RTLogSetR0ThreadNameV(PRTLOGGER pLogger, const char *pszNameFmt, va_list va)
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}
2268RT_EXPORT_SYMBOL(RTLogSetR0ThreadNameV);
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
2290#endif /* IN_RING0 */
2291
2292RTDECL(uint64_t) RTLogGetFlags(PRTLOGGER pLogger)
2293{
2294 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2295 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, UINT64_MAX);
2296 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2297 return pLoggerInt->fFlags;
2298}
2299RT_EXPORT_SYMBOL(RTLogGetFlags);
2300
2301
2302RTDECL(int) RTLogChangeFlags(PRTLOGGER pLogger, uint64_t fSet, uint64_t fClear)
2303{
2304 int rc;
2305 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2306 AssertReturn(!(fSet & ~RTLOG_F_VALID_MASK), VERR_INVALID_FLAGS);
2307 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2308
2309 /*
2310 * Make the changes.
2311 */
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;
2320}
2321RT_EXPORT_SYMBOL(RTLogChangeFlags);
2322
2323
2324RTDECL(int) RTLogQueryFlags(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
2325{
2326 bool fNotFirst = false;
2327 int rc = VINF_SUCCESS;
2328 uint32_t fFlags;
2329 unsigned i;
2330 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2331
2332 Assert(cchBuf);
2333 *pszBuf = '\0';
2334 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2335 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2336
2337 /*
2338 * Add the flags in the list.
2339 */
2340 fFlags = pLoggerInt->fFlags;
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))
2345 {
2346 size_t cchInstr = g_aLogFlags[i].cchInstr;
2347 if (cchInstr + fNotFirst + 1 > cchBuf)
2348 {
2349 rc = VERR_BUFFER_OVERFLOW;
2350 break;
2351 }
2352 if (fNotFirst)
2353 {
2354 *pszBuf++ = ' ';
2355 cchBuf--;
2356 }
2357 memcpy(pszBuf, g_aLogFlags[i].pszInstr, cchInstr);
2358 pszBuf += cchInstr;
2359 cchBuf -= cchInstr;
2360 fNotFirst = true;
2361 }
2362 *pszBuf = '\0';
2363 return rc;
2364}
2365RT_EXPORT_SYMBOL(RTLogQueryFlags);
2366
2367
2368/**
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 {
2388 unsigned i;
2389 size_t cchThusFar = off;
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;
2398 for (i = 0; i < RT_ELEMENTS(g_aLogDst); i++)
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
2411RTDECL(int) RTLogDestinations(PRTLOGGER pLogger, char const *pszValue)
2412{
2413 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2414 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2415 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2416 /** @todo locking? */
2417
2418 /*
2419 * Do the parsing.
2420 */
2421 while (*pszValue)
2422 {
2423 bool fNo;
2424 unsigned i;
2425
2426 /* skip blanks. */
2427 while (RT_C_IS_SPACE(*pszValue))
2428 pszValue++;
2429 if (!*pszValue)
2430 break;
2431
2432 /* check no prefix. */
2433 fNo = false;
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'))
2440 {
2441 fNo = true;
2442 pszValue += 2;
2443 }
2444
2445 /* instruction. */
2446 for (i = 0; i < RT_ELEMENTS(g_aLogDst); i++)
2447 {
2448 if (!strncmp(pszValue, g_aLogDst[i].pszInstr, g_aLogDst[i].cchInstr))
2449 {
2450 if (!fNo)
2451 pLoggerInt->fDestFlags |= g_aLogDst[i].fFlag;
2452 else
2453 pLoggerInt->fDestFlags &= ~g_aLogDst[i].fFlag;
2454 pszValue += g_aLogDst[i].cchInstr;
2455
2456 /* check for value. */
2457 while (RT_C_IS_SPACE(*pszValue))
2458 pszValue++;
2459 if (*pszValue == '=' || *pszValue == ':')
2460 {
2461 pszValue++;
2462 size_t cch = rtLogDestFindValueLength(pszValue);
2463 const char *pszEnd = pszValue + cch;
2464
2465# ifdef IN_RING3
2466 char szTmp[sizeof(pLoggerInt->szFilename)];
2467# else
2468 char szTmp[32];
2469# endif
2470 if (0)
2471 { /* nothing */ }
2472# ifdef IN_RING3
2473
2474 /* log file name */
2475 else if (i == 0 /* file */ && !fNo)
2476 {
2477 if (!(pLoggerInt->fDestFlags & RTLOGDEST_FIXED_FILE))
2478 {
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 ... */
2483 }
2484 }
2485 /* log directory */
2486 else if (i == 1 /* dir */ && !fNo)
2487 {
2488 if (!(pLoggerInt->fDestFlags & RTLOGDEST_FIXED_DIR))
2489 {
2490 const char *pszFile = RTPathFilename(pLoggerInt->szFilename);
2491 size_t cchFile = pszFile ? strlen(pszFile) : 0;
2492 AssertReturn(cchFile + cch + 1 < sizeof(pLoggerInt->szFilename), VERR_OUT_OF_RANGE);
2493 memcpy(szTmp, cchFile ? pszFile : "", cchFile + 1);
2494
2495 memcpy(pLoggerInt->szFilename, pszValue, cch);
2496 pLoggerInt->szFilename[cch] = '\0';
2497 RTPathStripTrailingSlash(pLoggerInt->szFilename);
2498
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 ... */
2504 }
2505 }
2506 else if (i == 2 /* history */)
2507 {
2508 if (!fNo)
2509 {
2510 uint32_t cHistory = 0;
2511 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2512 if (RT_SUCCESS(rc))
2513 rc = RTStrToUInt32Full(szTmp, 0, &cHistory);
2514 AssertMsgReturn(RT_SUCCESS(rc) && cHistory < _1M, ("Invalid history value %s (%Rrc)!\n", szTmp, rc), rc);
2515 pLoggerInt->cHistory = cHistory;
2516 }
2517 else
2518 pLoggerInt->cHistory = 0;
2519 }
2520 else if (i == 3 /* histsize */)
2521 {
2522 if (!fNo)
2523 {
2524 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2525 if (RT_SUCCESS(rc))
2526 rc = RTStrToUInt64Full(szTmp, 0, &pLoggerInt->cbHistoryFileMax);
2527 AssertMsgRCReturn(rc, ("Invalid history file size value %s (%Rrc)!\n", szTmp, rc), rc);
2528 if (pLoggerInt->cbHistoryFileMax == 0)
2529 pLoggerInt->cbHistoryFileMax = UINT64_MAX;
2530 }
2531 else
2532 pLoggerInt->cbHistoryFileMax = UINT64_MAX;
2533 }
2534 else if (i == 4 /* histtime */)
2535 {
2536 if (!fNo)
2537 {
2538 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2539 if (RT_SUCCESS(rc))
2540 rc = RTStrToUInt32Full(szTmp, 0, &pLoggerInt->cSecsHistoryTimeSlot);
2541 AssertMsgRCReturn(rc, ("Invalid history time slot value %s (%Rrc)!\n", szTmp, rc), rc);
2542 if (pLoggerInt->cSecsHistoryTimeSlot == 0)
2543 pLoggerInt->cSecsHistoryTimeSlot = UINT32_MAX;
2544 }
2545 else
2546 pLoggerInt->cSecsHistoryTimeSlot = UINT32_MAX;
2547 }
2548# endif /* IN_RING3 */
2549 else if (i == 5 /* ringbuf */ && !fNo)
2550 {
2551 int rc = RTStrCopyEx(szTmp, sizeof(szTmp), pszValue, cch);
2552 uint32_t cbRingBuf = 0;
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);
2565 rc = rtLogRingBufAdjust(pLoggerInt, cbRingBuf, false /*fForce*/);
2566 if (RT_FAILURE(rc))
2567 return rc;
2568 }
2569 else
2570 AssertMsgFailedReturn(("Invalid destination value! %s%s doesn't take a value!\n",
2571 fNo ? "no" : "", g_aLogDst[i].pszInstr),
2572 VERR_INVALID_PARAMETER);
2573
2574 pszValue = pszEnd + (*pszEnd != '\0');
2575 }
2576 else if (i == 5 /* ringbuf */ && !fNo && !pLoggerInt->pszRingBuf)
2577 {
2578 int rc = rtLogRingBufAdjust(pLoggerInt, pLoggerInt->cbRingBuf, false /*fForce*/);
2579 if (RT_FAILURE(rc))
2580 return rc;
2581 }
2582 break;
2583 }
2584 }
2585
2586 /* assert known instruction */
2587 AssertMsgReturn(i < RT_ELEMENTS(g_aLogDst),
2588 ("Invalid destination value! unknown instruction %.20s\n", pszValue),
2589 VERR_INVALID_PARAMETER);
2590
2591 /* skip blanks and delimiters. */
2592 while (RT_C_IS_SPACE(*pszValue) || *pszValue == ';')
2593 pszValue++;
2594 } /* while more environment variable value left */
2595
2596 return VINF_SUCCESS;
2597}
2598RT_EXPORT_SYMBOL(RTLogDestinations);
2599
2600
2601RTDECL(int) RTLogClearFileDelayFlag(PRTLOGGER pLogger, PRTERRINFO pErrInfo)
2602{
2603 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2604 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2605
2606 /*
2607 * Do the work.
2608 */
2609 int rc = rtlogLock(pLoggerInt);
2610 if (RT_SUCCESS(rc))
2611 {
2612 if (pLoggerInt->fDestFlags & RTLOGDEST_F_DELAY_FILE)
2613 {
2614 pLoggerInt->fDestFlags &= ~RTLOGDEST_F_DELAY_FILE;
2615# ifdef IN_RING3
2616 if ( pLoggerInt->fDestFlags & RTLOGDEST_FILE
2617 && !pLoggerInt->fLogOpened)
2618 {
2619 rc = rtR3LogOpenFileDestination(pLoggerInt, pErrInfo);
2620 if (RT_SUCCESS(rc))
2621 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
2622 }
2623# endif
2624 RT_NOREF(pErrInfo); /** @todo fix create API to use RTErrInfo */
2625 }
2626 rtlogUnlock(pLoggerInt);
2627 }
2628 return VINF_SUCCESS;
2629}
2630RT_EXPORT_SYMBOL(RTLogClearFileDelayFlag);
2631
2632
2633RTDECL(int) RTLogChangeDestinations(PRTLOGGER pLogger, uint32_t fSet, uint32_t fClear)
2634{
2635 int rc;
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);
2640 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2641
2642 /*
2643 * Make the changes.
2644 */
2645 rc = rtlogLock(pLoggerInt);
2646 if (RT_SUCCESS(rc))
2647 {
2648 pLoggerInt->fDestFlags &= ~fClear;
2649 pLoggerInt->fDestFlags |= fSet;
2650 rtlogUnlock(pLoggerInt);
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 }
2667 return pLoggerInt->fDestFlags;
2668}
2669RT_EXPORT_SYMBOL(RTLogGetDestinations);
2670
2671
2672RTDECL(int) RTLogQueryDestinations(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
2673{
2674 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
2675 bool fNotFirst = false;
2676 int rc = VINF_SUCCESS;
2677 uint32_t fDestFlags;
2678 unsigned i;
2679
2680 AssertReturn(cchBuf, VERR_INVALID_PARAMETER);
2681 *pszBuf = '\0';
2682 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
2683 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
2684
2685 /*
2686 * Add the flags in the list.
2687 */
2688 fDestFlags = pLoggerInt->fDestFlags;
2689 for (i = 6; i < RT_ELEMENTS(g_aLogDst); i++)
2690 if (g_aLogDst[i].fFlag & fDestFlags)
2691 {
2692 if (fNotFirst)
2693 {
2694 rc = RTStrCopyP(&pszBuf, &cchBuf, " ");
2695 if (RT_FAILURE(rc))
2696 return rc;
2697 }
2698 rc = RTStrCopyP(&pszBuf, &cchBuf, g_aLogDst[i].pszInstr);
2699 if (RT_FAILURE(rc))
2700 return rc;
2701 fNotFirst = true;
2702 }
2703
2704 char szNum[32];
2705
2706# ifdef IN_RING3
2707 /*
2708 * Add the filename.
2709 */
2710 if (fDestFlags & RTLOGDEST_FILE)
2711 {
2712 rc = RTStrCopyP(&pszBuf, &cchBuf, fNotFirst ? " file=" : "file=");
2713 if (RT_FAILURE(rc))
2714 return rc;
2715 rc = RTStrCopyP(&pszBuf, &cchBuf, pLoggerInt->szFilename);
2716 if (RT_FAILURE(rc))
2717 return rc;
2718 fNotFirst = true;
2719
2720 if (pLoggerInt->cHistory)
2721 {
2722 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " history=%u" : "history=%u", pLoggerInt->cHistory);
2723 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2724 if (RT_FAILURE(rc))
2725 return rc;
2726 fNotFirst = true;
2727 }
2728 if (pLoggerInt->cbHistoryFileMax != UINT64_MAX)
2729 {
2730 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " histsize=%llu" : "histsize=%llu", pLoggerInt->cbHistoryFileMax);
2731 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2732 if (RT_FAILURE(rc))
2733 return rc;
2734 fNotFirst = true;
2735 }
2736 if (pLoggerInt->cSecsHistoryTimeSlot != UINT32_MAX)
2737 {
2738 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " histtime=%llu" : "histtime=%llu", pLoggerInt->cSecsHistoryTimeSlot);
2739 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2740 if (RT_FAILURE(rc))
2741 return rc;
2742 fNotFirst = true;
2743 }
2744 }
2745# endif /* IN_RING3 */
2746
2747 /*
2748 * Add the ring buffer.
2749 */
2750 if (fDestFlags & RTLOGDEST_RINGBUF)
2751 {
2752 if (pLoggerInt->cbRingBuf == RTLOG_RINGBUF_DEFAULT_SIZE)
2753 rc = RTStrCopyP(&pszBuf, &cchBuf, fNotFirst ? " ringbuf" : "ringbuf");
2754 else
2755 {
2756 RTStrPrintf(szNum, sizeof(szNum), fNotFirst ? " ringbuf=%#x" : "ringbuf=%#x", pLoggerInt->cbRingBuf);
2757 rc = RTStrCopyP(&pszBuf, &cchBuf, szNum);
2758 }
2759 if (RT_FAILURE(rc))
2760 return rc;
2761 fNotFirst = true;
2762 }
2763
2764 return VINF_SUCCESS;
2765}
2766RT_EXPORT_SYMBOL(RTLogQueryDestinations);
2767
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
2785#ifdef IN_RING3
2786
2787/**
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 {
2801 pLoggerInt->pOutputIf->pfnDelete(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx,
2802 pLoggerInt->szFilename);
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;
2811 int rc = pLoggerInt->pOutputIf->pfnOpen(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx,
2812 pLoggerInt->szFilename, fOpen);
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))
2819 pLoggerInt->pOutputIf->pfnDelete(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx,
2820 pLoggerInt->szFilename);
2821 rc = pLoggerInt->pOutputIf->pfnOpen(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx,
2822 pLoggerInt->szFilename, fOpen);
2823 }
2824 if (RT_SUCCESS(rc))
2825 {
2826 pLoggerInt->fLogOpened = true;
2827
2828 rc = pLoggerInt->pOutputIf->pfnQuerySize(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser,
2829 &pLoggerInt->cbHistoryFileWritten);
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 {
2839 pLoggerInt->fLogOpened = false;
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 */
2888 if (pLoggerInt->fLogOpened)
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 }
2900
2901 pLoggerInt->pOutputIf->pfnClose(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser);
2902 }
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 }
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;
2932 int rc = pLoggerInt->pOutputIf->pfnRename(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx,
2933 szOldName, szNewName, RTFILEMOVE_FLAGS_REPLACE);
2934 while ( rc == VERR_SHARING_VIOLATION
2935 && cBackoff < RT_ELEMENTS(g_acMsLogBackoff))
2936 {
2937 RTThreadSleep(g_acMsLogBackoff[cBackoff++]);
2938 rc = pLoggerInt->pOutputIf->pfnRename(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx,
2939 szOldName, szNewName, RTFILEMOVE_FLAGS_REPLACE);
2940 }
2941
2942 if (rc == VERR_FILE_NOT_FOUND)
2943 pLoggerInt->pOutputIf->pfnDelete(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx,
2944 szNewName);
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);
2954 int rc = pLoggerInt->pOutputIf->pfnDelete(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx,
2955 szExcessName);
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
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 */
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{
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))
3019 {
3020 if (pLoggerInt->fFlags & RTLOGFLAGS_APPEND)
3021 {
3022 rc = rtlogFileOpen(pLoggerInt, pErrInfo);
3023
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);
3033
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 */
3048 if (!pLoggerInt->fLogOpened)
3049 {
3050 pLoggerInt->pOutputIf->pfnDirCtxClose(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser, pLoggerInt->pvDirCtx);
3051 pLoggerInt->pvDirCtx = NULL;
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
3064RTDECL(int) RTLogBulkUpdate(PRTLOGGER pLogger, uint64_t fFlags, uint32_t uGroupCrc32, uint32_t cGroups, uint32_t const *pafGroups)
3065{
3066 int rc;
3067 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
3068 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
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 {
3080 RT_BCOPY_UNFORTIFIED(pLoggerInt->afGroups, pafGroups, sizeof(pLoggerInt->afGroups[0]) * cGroups);
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
3098 *pfFlags = 0;
3099 *puGroupCrc32 = 0;
3100 *pcGroups = 0;
3101 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
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
3120RTDECL(int) RTLogBulkWrite(PRTLOGGER pLogger, const char *pszBefore, const char *pch, size_t cch, const char *pszAfter)
3121{
3122 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
3123 RTLOG_RESOLVE_DEFAULT_RET(pLoggerInt, VINF_LOG_NO_LOGGER);
3124
3125 /*
3126 * Lock and validate it.
3127 */
3128 int rc = rtlogLock(pLoggerInt);
3129 if (RT_SUCCESS(rc))
3130 {
3131 if (cch > 0)
3132 {
3133 /*
3134 * Heading/marker.
3135 */
3136 if (pszBefore)
3137 rtlogLoggerExFLocked(pLoggerInt, RTLOGGRPFLAGS_LEVEL_1, UINT32_MAX, "%s", pszBefore);
3138
3139 /*
3140 * Do the copying.
3141 */
3142 do
3143 {
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 }
3160
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);
3183 }
3184
3185 rtlogUnlock(pLoggerInt);
3186 }
3187 return rc;
3188}
3189RT_EXPORT_SYMBOL(RTLogBulkWrite);
3190
3191
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
3252/*********************************************************************************************************************************
3253* Flushing *
3254*********************************************************************************************************************************/
3255
3256RTDECL(int) RTLogFlush(PRTLOGGER pLogger)
3257{
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 }
3264 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pLogger;
3265 Assert(pLoggerInt->Core.u32Magic == RTLOGGER_MAGIC);
3266 AssertPtr(pLoggerInt->pBufDesc);
3267 Assert(pLoggerInt->pBufDesc->u32Magic == RTLOGBUFFERDESC_MAGIC);
3268
3269 /*
3270 * Acquire logger instance sem.
3271 */
3272 int rc = rtlogLock(pLoggerInt);
3273 if (RT_SUCCESS(rc))
3274 {
3275 /*
3276 * Any thing to flush?
3277 */
3278 if ( pLoggerInt->pBufDesc->offBuf > 0
3279 || (pLoggerInt->fDestFlags & RTLOGDEST_RINGBUF))
3280 {
3281 /*
3282 * Call worker.
3283 */
3284 rtlogFlush(pLoggerInt, false /*fNeedSpace*/);
3285
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);
3293 }
3294
3295 rtlogUnlock(pLoggerInt);
3296 }
3297 return rc;
3298}
3299RT_EXPORT_SYMBOL(RTLogFlush);
3300
3301
3302/**
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.
3310 */
3311static void rtlogFlush(PRTLOGGERINTERNAL pLoggerInt, bool fNeedSpace)
3312{
3313 PRTLOGBUFFERDESC pBufDesc = pLoggerInt->pBufDesc;
3314 uint32_t cchToFlush = pBufDesc->offBuf;
3315 char * pchToFlush = pBufDesc->pchBuf;
3316 uint32_t const cbBuf = pBufDesc->cbBuf;
3317 Assert(pBufDesc->u32Magic == RTLOGBUFFERDESC_MAGIC);
3318
3319 NOREF(fNeedSpace);
3320 if (cchToFlush == 0)
3321 return; /* nothing to flush. */
3322
3323 AssertPtrReturnVoid(pchToFlush);
3324 AssertReturnVoid(cbBuf > 0);
3325 AssertMsgStmt(cchToFlush < cbBuf, ("%#x vs %#x\n", cchToFlush, cbBuf), cchToFlush = cbBuf - 1);
3326
3327 /*
3328 * If the ring buffer is active, the other destinations are only written
3329 * to when the ring buffer is flushed by RTLogFlush().
3330 */
3331 if ( (pLoggerInt->fDestFlags & RTLOGDEST_RINGBUF)
3332 && pLoggerInt->pszRingBuf /* paranoia */)
3333 {
3334 rtLogRingBufWrite(pLoggerInt, pchToFlush, cchToFlush);
3335
3336 /* empty the buffer. */
3337 pBufDesc->offBuf = 0;
3338 *pchToFlush = '\0';
3339 }
3340 /*
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.
3343 */
3344 else
3345#ifdef IN_RING3
3346 if (!(pLoggerInt->fDestFlags & RTLOGDEST_F_DELAY_FILE))
3347#endif
3348 {
3349 /* Make sure the string is terminated. On Windows, RTLogWriteDebugger
3350 will get upset if it isn't. */
3351 pchToFlush[cchToFlush] = '\0';
3352
3353 if (pLoggerInt->fDestFlags & RTLOGDEST_USER)
3354 RTLogWriteUser(pchToFlush, cchToFlush);
3355
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
3364 if (pLoggerInt->fDestFlags & RTLOGDEST_DEBUGGER)
3365 RTLogWriteDebugger(pchToFlush, cchToFlush);
3366
3367#ifdef IN_RING3
3368 if ((pLoggerInt->fDestFlags & (RTLOGDEST_FILE | RTLOGDEST_RINGBUF)) == RTLOGDEST_FILE)
3369 {
3370 if (pLoggerInt->fLogOpened)
3371 {
3372 pLoggerInt->pOutputIf->pfnWrite(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser,
3373 pchToFlush, cchToFlush, NULL /*pcbWritten*/);
3374 if (pLoggerInt->fFlags & RTLOGFLAGS_FLUSH)
3375 pLoggerInt->pOutputIf->pfnFlush(pLoggerInt->pOutputIf, pLoggerInt->pvOutputIfUser);
3376 }
3377 if (pLoggerInt->cHistory)
3378 pLoggerInt->cbHistoryFileWritten += cchToFlush;
3379 }
3380#endif
3381
3382 if (pLoggerInt->fDestFlags & RTLOGDEST_STDOUT)
3383 RTLogWriteStdOut(pchToFlush, cchToFlush);
3384
3385 if (pLoggerInt->fDestFlags & RTLOGDEST_STDERR)
3386 RTLogWriteStdErr(pchToFlush, cchToFlush);
3387
3388#if (defined(IN_RING0) || defined(IN_RC)) && !defined(LOG_NO_COM)
3389 if (pLoggerInt->fDestFlags & RTLOGDEST_COM)
3390 RTLogWriteCom(pchToFlush, cchToFlush);
3391#endif
3392
3393 if (pLoggerInt->pfnFlush)
3394 {
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 */
3403 if (pBufDesc->pAux)
3404 pBufDesc->pAux->offBuf = cchToFlush;
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];
3414 pchToFlush = pBufDesc->pchBuf;
3415 }
3416 }
3417
3418 /* Empty the buffer. */
3419 pBufDesc->offBuf = 0;
3420 if (pBufDesc->pAux)
3421 pBufDesc->pAux->offBuf = 0;
3422 *pchToFlush = '\0';
3423
3424#ifdef IN_RING3
3425 /*
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.
3429 */
3430 if ( pLoggerInt->cHistory > 0
3431 && (pLoggerInt->fDestFlags & RTLOGDEST_FILE))
3432 rtlogRotate(pLoggerInt, RTTimeProgramSecTS() / pLoggerInt->cSecsHistoryTimeSlot, false /*fFirst*/, NULL /*pErrInfo*/);
3433#endif
3434 }
3435#ifdef IN_RING3
3436 else
3437 {
3438 /*
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.
3441 */
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))
3448 {
3449 memcpy(&pchToFlush[offHalf], RT_STR_TUPLE(s_szDropMsgLf));
3450 offHalf += sizeof(s_szDropMsgLf) - 1;
3451 }
3452 else
3453 {
3454 memcpy(&pchToFlush[offHalf], RT_STR_TUPLE(s_szDropMsgCrLf));
3455 offHalf += sizeof(s_szDropMsgCrLf) - 1;
3456 }
3457 pBufDesc->offBuf = offHalf;
3458 }
3459 }
3460#endif
3461}
3462
3463
3464/*********************************************************************************************************************************
3465* Logger Core *
3466*********************************************************************************************************************************/
3467
3468#ifdef IN_RING0
3469
3470/**
3471 * For rtR0LogLoggerExFallbackOutput and rtR0LogLoggerExFallbackFlush.
3472 */
3473typedef struct RTR0LOGLOGGERFALLBACK
3474{
3475 /** The current scratch buffer offset. */
3476 uint32_t offScratch;
3477 /** The destination flags. */
3478 uint32_t fDestFlags;
3479 /** For ring buffer output. */
3480 PRTLOGGERINTERNAL pInt;
3481 /** The scratch buffer. */
3482 char achScratch[80];
3483} RTR0LOGLOGGERFALLBACK;
3484/** Pointer to RTR0LOGLOGGERFALLBACK which is used by
3485 * rtR0LogLoggerExFallbackOutput. */
3486typedef RTR0LOGLOGGERFALLBACK *PRTR0LOGLOGGERFALLBACK;
3487
3488
3489/**
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
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);
3507
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
3516 if (pThis->fDestFlags & RTLOGDEST_DEBUGGER)
3517 RTLogWriteDebugger(pThis->achScratch, pThis->offScratch);
3518
3519 if (pThis->fDestFlags & RTLOGDEST_STDOUT)
3520 RTLogWriteStdOut(pThis->achScratch, pThis->offScratch);
3521
3522 if (pThis->fDestFlags & RTLOGDEST_STDERR)
3523 RTLogWriteStdErr(pThis->achScratch, pThis->offScratch);
3524
3525# ifndef LOG_NO_COM
3526 if (pThis->fDestFlags & RTLOGDEST_COM)
3527 RTLogWriteCom(pThis->achScratch, pThis->offScratch);
3528# endif
3529 }
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)
3551 cb = (uint32_t)cbChars;
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
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.
3594 *
3595 * @param fDestFlags The destination flags.
3596 * @param fFlags The logger flags.
3597 * @param pInt The internal logger data, for ring buffer output.
3598 * @param pszFormat The format string.
3599 * @param va The format arguments.
3600 */
3601static void rtR0LogLoggerExFallback(uint32_t fDestFlags, uint32_t fFlags, PRTLOGGERINTERNAL pInt,
3602 const char *pszFormat, va_list va)
3603{
3604 RTR0LOGLOGGERFALLBACK This;
3605 This.fDestFlags = fDestFlags;
3606 This.pInt = pInt;
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
3630 RTLogFormatV(rtR0LogLoggerExFallbackOutput, &This, pszFormat, va);
3631}
3632
3633#endif /* IN_RING0 */
3634
3635
3636/**
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{
3642 PRTLOGGERINTERNAL pLoggerInt = (PRTLOGGERINTERNAL)pv;
3643 if (cbChars)
3644 {
3645 size_t cbRet = 0;
3646 for (;;)
3647 {
3648 PRTLOGBUFFERDESC const pBufDesc = pLoggerInt->pBufDesc;
3649 if (pBufDesc->offBuf < pBufDesc->cbBuf)
3650 {
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;
3657
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;
3669
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;
3678
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;
3688
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 }
3700
3701 }
3702#if defined(RT_STRICT) && defined(IN_RING3)
3703 else
3704 {
3705# ifndef IPRT_NO_CRT
3706 fprintf(stderr, "pBufDesc->offBuf >= pBufDesc->cbBuf (%#x >= %#x)\n", pBufDesc->offBuf, pBufDesc->cbBuf);
3707# else
3708 RTLogWriteStdErr(RT_STR_TUPLE("pBufDesc->offBuf >= pBufDesc->cbBuf\n"));
3709# endif
3710 AssertBreakpoint(); AssertBreakpoint();
3711 }
3712#endif
3713
3714 /* flush */
3715 rtlogFlush(pLoggerInt, true /*fNeedSpace*/);
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 */
3726 PRTLOGBUFFERDESC const pBufDesc = pLoggerInt->pBufDesc;
3727 pBufDesc->pchBuf[RT_MIN(pBufDesc->offBuf, pBufDesc->cbBuf - 1)] = '\0';
3728 return 0;
3729 }
3730}
3731
3732
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{
3746 size_t cchSrc = 0;
3747 if (pszSrc)
3748 {
3749 cchSrc = strlen(pszSrc);
3750 if (cchSrc > cchSrcMax)
3751 cchSrc = cchSrcMax;
3752
3753 memcpy(pszDst, pszSrc, cchSrc);
3754 pszDst += cchSrc;
3755 }
3756 do
3757 *pszDst++ = ' ';
3758 while (cchSrc++ < cchMinWidth);
3759
3760 return pszDst;
3761}
3762
3763
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);
3779
3780 memcpy(pszDst, pszSrc, cchSrc);
3781 pszDst += cchSrc;
3782 do
3783 *pszDst++ = ' ';
3784 while (cchSrc++ < cchMinWidth);
3785
3786 return pszDst;
3787}
3788
3789
3790
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{
3799 PRTLOGOUTPUTPREFIXEDARGS pArgs = (PRTLOGOUTPUTPREFIXEDARGS)pv;
3800 PRTLOGGERINTERNAL pLoggerInt = pArgs->pLoggerInt;
3801 if (cbChars)
3802 {
3803 uint64_t const fFlags = pLoggerInt->fFlags;
3804 size_t cbRet = 0;
3805 for (;;)
3806 {
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 {
3821# ifndef IPRT_NO_CRT
3822 fprintf(stderr, "offBuf >= cbBuf (%#x >= %#x)\n", offBuf, cbBuf);
3823# else
3824 RTLogWriteStdErr(RT_STR_TUPLE("offBuf >= cbBuf\n"));
3825# endif
3826 AssertBreakpoint(); AssertBreakpoint();
3827 }
3828#endif
3829
3830 /*
3831 * Pending prefix?
3832 */
3833 if (pLoggerInt->fPendingPrefix)
3834 {
3835 /*
3836 * Flush the buffer if there isn't enough room for the maximum prefix config.
3837 * Max is 265, add a couple of extra bytes. See CCH_PREFIX check way below.
3838 */
3839 if (cb >= 265 + 16)
3840 pLoggerInt->fPendingPrefix = false;
3841 else
3842 {
3843 rtlogFlush(pLoggerInt, true /*fNeedSpace*/);
3844 continue;
3845 }
3846
3847 /*
3848 * Write the prefixes.
3849 * psz is pointing to the current position.
3850 */
3851 psz = &pchBuf[offBuf];
3852 if (fFlags & RTLOGFLAGS_PREFIX_TS)
3853 {
3854 uint64_t u64 = RTTimeNanoTS();
3855 int iBase = 16;
3856 unsigned int fStrFlags = RTSTR_F_ZEROPAD;
3857 if (fFlags & RTLOGFLAGS_DECIMAL_TS)
3858 {
3859 iBase = 10;
3860 fStrFlags = 0;
3861 }
3862 if (fFlags & RTLOGFLAGS_REL_TS)
3863 {
3864 static volatile uint64_t s_u64LastTs;
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 */
3873 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fStrFlags);
3874 *psz++ = ' ';
3875 }
3876#define CCH_PREFIX_01 0 + 17
3877
3878 if (fFlags & RTLOGFLAGS_PREFIX_TSC)
3879 {
3880#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
3881 uint64_t u64 = ASMReadTSC();
3882#else
3883 uint64_t u64 = RTTimeNanoTS();
3884#endif
3885 int iBase = 16;
3886 unsigned int fStrFlags = RTSTR_F_ZEROPAD;
3887 if (fFlags & RTLOGFLAGS_DECIMAL_TS)
3888 {
3889 iBase = 10;
3890 fStrFlags = 0;
3891 }
3892 if (fFlags & RTLOGFLAGS_REL_TS)
3893 {
3894 static volatile uint64_t s_u64LastTsc;
3895 int64_t i64DiffTsc = u64 - s_u64LastTsc;
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. */
3900 u64 = i64DiffTsc < 0 ? 0 : i64DiffTsc;
3901 }
3902 /* 1E15 ticks at 4GHz = 69 hours */
3903 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fStrFlags);
3904 *psz++ = ' ';
3905 }
3906#define CCH_PREFIX_02 CCH_PREFIX_01 + 17
3907
3908 if (fFlags & RTLOGFLAGS_PREFIX_MS_PROG)
3909 {
3910#ifndef IN_RING0
3911 uint64_t u64 = RTTimeProgramMilliTS();
3912#else
3913 uint64_t u64 = (RTTimeNanoTS() - pLoggerInt->nsR0ProgramStart) / RT_NS_1MS;
3914#endif
3915 /* 1E8 milliseconds = 27 hours */
3916 psz += RTStrFormatNumber(psz, u64, 10, 9, 0, RTSTR_F_ZEROPAD);
3917 *psz++ = ' ';
3918 }
3919#define CCH_PREFIX_03 CCH_PREFIX_02 + 21
3920
3921 if (fFlags & RTLOGFLAGS_PREFIX_TIME)
3922 {
3923#if defined(IN_RING3) || defined(IN_RING0)
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++ = '.';
3933 psz += RTStrFormatNumber(psz, Time.u32Nanosecond / 1000, 10, 6, 0, RTSTR_F_ZEROPAD);
3934 *psz++ = ' ';
3935#else
3936 memset(psz, ' ', 16);
3937 psz += 16;
3938#endif
3939 }
3940#define CCH_PREFIX_04 CCH_PREFIX_03 + (3+1+3+1+3+1+7+1)
3941
3942 if (fFlags & RTLOGFLAGS_PREFIX_TIME_PROG)
3943 {
3944
3945#ifndef IN_RING0
3946 uint64_t u64 = RTTimeProgramMicroTS();
3947#else
3948 uint64_t u64 = (RTTimeNanoTS() - pLoggerInt->nsR0ProgramStart) / RT_NS_1US;
3949
3950#endif
3951 psz += RTStrFormatNumber(psz, (uint32_t)(u64 / RT_US_1HOUR), 10, 2, 0, RTSTR_F_ZEROPAD);
3952 *psz++ = ':';
3953 uint32_t u32 = (uint32_t)(u64 % RT_US_1HOUR);
3954 psz += RTStrFormatNumber(psz, u32 / RT_US_1MIN, 10, 2, 0, RTSTR_F_ZEROPAD);
3955 *psz++ = ':';
3956 u32 %= RT_US_1MIN;
3957
3958 psz += RTStrFormatNumber(psz, u32 / RT_US_1SEC, 10, 2, 0, RTSTR_F_ZEROPAD);
3959 *psz++ = '.';
3960 psz += RTStrFormatNumber(psz, u32 % RT_US_1SEC, 10, 6, 0, RTSTR_F_ZEROPAD);
3961 *psz++ = ' ';
3962 }
3963#define CCH_PREFIX_05 CCH_PREFIX_04 + (9+1+2+1+2+1+6+1)
3964
3965# if 0
3966 if (fFlags & RTLOGFLAGS_PREFIX_DATETIME)
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;
3974 *psz++ = ' ';
3975 }
3976# define CCH_PREFIX_06 CCH_PREFIX_05 + 32
3977# else
3978# define CCH_PREFIX_06 CCH_PREFIX_05 + 0
3979# endif
3980
3981 if (fFlags & RTLOGFLAGS_PREFIX_PID)
3982 {
3983 RTPROCESS Process = RTProcSelf();
3984 psz += RTStrFormatNumber(psz, Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
3985 *psz++ = ' ';
3986 }
3987#define CCH_PREFIX_07 CCH_PREFIX_06 + 9
3988
3989 if (fFlags & RTLOGFLAGS_PREFIX_TID)
3990 {
3991 RTNATIVETHREAD Thread = RTThreadNativeSelf();
3992 psz += RTStrFormatNumber(psz, Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
3993 *psz++ = ' ';
3994 }
3995#define CCH_PREFIX_08 CCH_PREFIX_07 + 17
3996
3997 if (fFlags & RTLOGFLAGS_PREFIX_THREAD)
3998 {
3999#ifdef IN_RING3
4000 const char *pszName = RTThreadSelfName();
4001#elif defined IN_RC
4002 const char *pszName = "EMT-RC";
4003#else
4004 const char *pszName = pLoggerInt->szR0ThreadName[0] ? pLoggerInt->szR0ThreadName : "R0";
4005#endif
4006 psz = rtLogStPNCpyPad(psz, pszName, 16, 8);
4007 }
4008#define CCH_PREFIX_09 CCH_PREFIX_08 + 17
4009
4010 if (fFlags & RTLOGFLAGS_PREFIX_CPUID)
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);
4018 *psz++ = ' ';
4019 }
4020#define CCH_PREFIX_10 CCH_PREFIX_09 + 17
4021
4022 if ( (fFlags & RTLOGFLAGS_PREFIX_CUSTOM)
4023 && pLoggerInt->pfnPrefix)
4024 {
4025 psz += pLoggerInt->pfnPrefix(&pLoggerInt->Core, psz, 31, pLoggerInt->pvPrefixUserArg);
4026 *psz++ = ' '; /* +32 */
4027 }
4028#define CCH_PREFIX_11 CCH_PREFIX_10 + 32
4029
4030 if (fFlags & RTLOGFLAGS_PREFIX_LOCK_COUNTS)
4031 {
4032#ifdef IN_RING3 /** @todo implement these counters in ring-0 too? */
4033 RTTHREAD Thread = RTThreadSelf();
4034 if (Thread != NIL_RTTHREAD)
4035 {
4036 uint32_t cReadLocks = RTLockValidatorReadLockGetCount(Thread);
4037 uint32_t cWriteLocks = RTLockValidatorWriteLockGetCount(Thread) - g_cLoggerLockCount;
4038 cReadLocks = RT_MIN(0xfff, cReadLocks);
4039 cWriteLocks = RT_MIN(0xfff, cWriteLocks);
4040 psz += RTStrFormatNumber(psz, cReadLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
4041 *psz++ = '/';
4042 psz += RTStrFormatNumber(psz, cWriteLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
4043 }
4044 else
4045#endif
4046 {
4047 *psz++ = '?';
4048 *psz++ = '/';
4049 *psz++ = '?';
4050 }
4051 *psz++ = ' ';
4052 }
4053#define CCH_PREFIX_12 CCH_PREFIX_11 + 8
4054
4055 if (fFlags & RTLOGFLAGS_PREFIX_FLAG_NO)
4056 {
4057 psz += RTStrFormatNumber(psz, pArgs->fFlags, 16, 8, 0, RTSTR_F_ZEROPAD);
4058 *psz++ = ' ';
4059 }
4060#define CCH_PREFIX_13 CCH_PREFIX_12 + 9
4061
4062 if (fFlags & RTLOGFLAGS_PREFIX_FLAG)
4063 {
4064#ifdef IN_RING3
4065 const char *pszGroup = pArgs->iGroup != ~0U ? pLoggerInt->papszGroups[pArgs->iGroup] : NULL;
4066#else
4067 const char *pszGroup = NULL;
4068#endif
4069 psz = rtLogStPNCpyPad(psz, pszGroup, 16, 8);
4070 }
4071#define CCH_PREFIX_14 CCH_PREFIX_13 + 17
4072
4073 if (fFlags & RTLOGFLAGS_PREFIX_GROUP_NO)
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;
4084 } /* +9 */
4085 }
4086#define CCH_PREFIX_15 CCH_PREFIX_14 + 9
4087
4088 if (fFlags & RTLOGFLAGS_PREFIX_GROUP)
4089 {
4090 const unsigned fGrp = pLoggerInt->afGroups[pArgs->iGroup != ~0U ? pArgs->iGroup : 0];
4091 const char *pszGroup;
4092 size_t cchGroup;
4093 switch (pArgs->fFlags & fGrp)
4094 {
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;
4112 }
4113 psz = rtLogStPNCpyPad2(psz, pszGroup, RT_MIN(cchGroup, 16), 8);
4114 }
4115#define CCH_PREFIX_16 CCH_PREFIX_15 + 17
4116
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
4123
4124
4125#define CCH_PREFIX ( CCH_PREFIX_17 )
4126 { AssertCompile(CCH_PREFIX < 265); }
4127
4128 /*
4129 * Done, figure what we've used and advance the buffer and free size.
4130 */
4131 AssertMsg(psz - &pchBuf[offBuf] <= 223,
4132 ("%#zx (%zd) - fFlags=%#x\n", psz - &pchBuf[offBuf], psz - &pchBuf[offBuf], fFlags));
4133 pBufDesc->offBuf = offBuf = (uint32_t)(psz - pchBuf);
4134 cb = cbBuf - offBuf - 1;
4135 }
4136 else if (cb <= 2) /* 2 - Make sure we can write a \r\n and not loop forever. */
4137 {
4138 rtlogFlush(pLoggerInt, true /*fNeedSpace*/);
4139 continue;
4140 }
4141
4142 /*
4143 * Done with the prefixing. Copy message text past the next newline.
4144 */
4145
4146 /* how much */
4147 if (cb > cbChars)
4148 cb = cbChars;
4149
4150 /* have newline? */
4151 pszNewLine = (const char *)memchr(pachChars, '\n', cb);
4152 if (pszNewLine)
4153 {
4154 cb = pszNewLine - pachChars;
4155 if (!(fFlags & RTLOGFLAGS_USECRLF))
4156 {
4157 cb += 1;
4158 memcpy(&pchBuf[offBuf], pachChars, cb);
4159 pLoggerInt->fPendingPrefix = true;
4160 }
4161 else if (cb + 2U < cbBuf - offBuf)
4162 {
4163 memcpy(&pchBuf[offBuf], pachChars, cb);
4164 pchBuf[offBuf + cb++] = '\r';
4165 pchBuf[offBuf + cb++] = '\n';
4166 cbChars++; /* Discount the extra '\r'. */
4167 pachChars--; /* Ditto. */
4168 cbRet--; /* Ditto. */
4169 pLoggerInt->fPendingPrefix = true;
4170 }
4171 else
4172 {
4173 /* Insufficient buffer space, leave the '\n' for the next iteration. */
4174 memcpy(&pchBuf[offBuf], pachChars, cb);
4175 }
4176 }
4177 else
4178 memcpy(&pchBuf[offBuf], pachChars, cb);
4179
4180 /* advance */
4181 pBufDesc->offBuf = offBuf += (uint32_t)cb;
4182 cbRet += cb;
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 */
4199 PRTLOGBUFFERDESC const pBufDesc = pLoggerInt->pBufDesc;
4200 pBufDesc->pchBuf[RT_MIN(pBufDesc->offBuf, pBufDesc->cbBuf - 1)] = '\0';
4201 return 0;
4202 }
4203}
4204
4205
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 *
4212 * @param pLoggerInt Pointer to logger instance. Must be non-NULL.
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 */
4220static void rtlogLoggerExVLocked(PRTLOGGERINTERNAL pLoggerInt, unsigned fFlags, unsigned iGroup,
4221 const char *pszFormat, va_list args)
4222{
4223 /*
4224 * If we've got an auxilary descriptor, check if the buffer was flushed.
4225 */
4226 PRTLOGBUFFERDESC pBufDesc = pLoggerInt->pBufDesc;
4227 PRTLOGBUFFERAUXDESC pAuxDesc = pBufDesc->pAux;
4228 if (!pAuxDesc || !pAuxDesc->fFlushedIndicator)
4229 { /* likely, except maybe for ring-0 */ }
4230 else
4231 {
4232 pAuxDesc->fFlushedIndicator = false;
4233 pBufDesc->offBuf = 0;
4234 }
4235
4236 /*
4237 * Format the message.
4238 */
4239 if (pLoggerInt->fFlags & (RTLOGFLAGS_PREFIX_MASK | RTLOGFLAGS_USECRLF))
4240 {
4241 RTLOGOUTPUTPREFIXEDARGS OutputArgs;
4242 OutputArgs.pLoggerInt = pLoggerInt;
4243 OutputArgs.iGroup = iGroup;
4244 OutputArgs.fFlags = fFlags;
4245 OutputArgs.pszInfix = NULL;
4246 RTLogFormatV(rtLogOutputPrefixed, &OutputArgs, pszFormat, args);
4247 }
4248 else
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 }
4264}
4265
4266
4267/**
4268 * For calling rtlogLoggerExVLocked.
4269 *
4270 * @param pLoggerInt The logger.
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 */
4278static void rtlogLoggerExFLocked(PRTLOGGERINTERNAL pLoggerInt, unsigned fFlags, unsigned iGroup, const char *pszFormat, ...)
4279{
4280 va_list va;
4281 va_start(va, pszFormat);
4282 rtlogLoggerExVLocked(pLoggerInt, fFlags, iGroup, pszFormat, va);
4283 va_end(va);
4284}
4285
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
4307 && (pLoggerInt->afGroups[iGroup] & (fFlags | RTLOGGRPFLAGS_ENABLED)) != (fFlags | RTLOGGRPFLAGS_ENABLED))
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
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
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