VirtualBox

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

Last change on this file since 96407 was 96407, checked in by vboxsync, 2 years ago

scm copyright and license note update

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

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