VirtualBox

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

Last change on this file since 21812 was 21549, checked in by vboxsync, 15 years ago

iprt/log.h: Use the spinning mutexes.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 87.0 KB
Line 
1/* $Id: log.cpp 21549 2009-07-13 16:28:52Z vboxsync $ */
2/** @file
3 * Runtime VBox - Logger.
4 */
5
6/*
7 * Copyright (C) 2006-2007 Sun Microsystems, Inc.
8 *
9 * This file is part of VirtualBox Open Source Edition (OSE), as
10 * available from http://www.virtualbox.org. This file is free software;
11 * you can redistribute it and/or modify it under the terms of the GNU
12 * General Public License (GPL) as published by the Free Software
13 * Foundation, in version 2 as it comes in the "COPYING" file of the
14 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
15 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
16 *
17 * The contents of this file may alternatively be used under the terms
18 * of the Common Development and Distribution License Version 1.0
19 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
20 * VirtualBox OSE distribution, in which case the provisions of the
21 * CDDL are applicable instead of those of the GPL.
22 *
23 * You may elect to license modified versions of this file under the
24 * terms and conditions of either the GPL or the CDDL or both.
25 *
26 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa
27 * Clara, CA 95054 USA or visit http://www.sun.com if you need
28 * additional information or have any questions.
29 */
30
31
32/*******************************************************************************
33* Header Files *
34*******************************************************************************/
35#include <iprt/log.h>
36#include "internal/iprt.h"
37
38#ifndef IN_RC
39# include <iprt/alloc.h>
40# include <iprt/process.h>
41# include <iprt/semaphore.h>
42# include <iprt/thread.h>
43# include <iprt/mp.h>
44#endif
45#ifdef IN_RING3
46# include <iprt/env.h>
47# include <iprt/file.h>
48# include <iprt/path.h>
49#endif
50#include <iprt/time.h>
51#include <iprt/asm.h>
52#include <iprt/assert.h>
53#include <iprt/err.h>
54#include <iprt/param.h>
55
56#include <iprt/stdarg.h>
57#include <iprt/string.h>
58#include <iprt/ctype.h>
59#ifdef IN_RING3
60# include <iprt/alloca.h>
61# include <stdio.h>
62#endif
63
64
65/*******************************************************************************
66* Structures and Typedefs *
67*******************************************************************************/
68/**
69 * Arguments passed to the output function.
70 */
71typedef struct RTLOGOUTPUTPREFIXEDARGS
72{
73 /** The logger instance. */
74 PRTLOGGER pLogger;
75 /** The flags. (used for prefixing.) */
76 unsigned fFlags;
77 /** The group. (used for prefixing.) */
78 unsigned iGroup;
79} RTLOGOUTPUTPREFIXEDARGS, *PRTLOGOUTPUTPREFIXEDARGS;
80
81
82/*******************************************************************************
83* Internal Functions *
84*******************************************************************************/
85#ifndef IN_RC
86static unsigned rtlogGroupFlags(const char *psz);
87#endif
88#ifdef IN_RING0
89static void rtR0LogLoggerExFallback(uint32_t fDestFlags, uint32_t fFlags, const char *pszFormat, va_list va);
90#endif
91static void rtlogFlush(PRTLOGGER pLogger);
92static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars);
93static DECLCALLBACK(size_t) rtLogOutputPrefixed(void *pv, const char *pachChars, size_t cbChars);
94
95
96/*******************************************************************************
97* Global Variables *
98*******************************************************************************/
99#ifdef IN_RC
100/** Default logger instance. */
101extern "C" DECLIMPORT(RTLOGGERRC) g_Logger;
102#else /* !IN_RC */
103/** Default logger instance. */
104static PRTLOGGER g_pLogger;
105#endif /* !IN_RC */
106#ifdef IN_RING3
107/** The RTThreadGetWriteLockCount() change caused by the logger mutex semaphore. */
108static uint32_t volatile g_cLoggerLockCount;
109#endif
110#ifdef IN_RING0
111/** Number of per-thread loggers. */
112static int32_t volatile g_cPerThreadLoggers;
113/** Per-thread loggers.
114 * This is just a quick TLS hack suitable for debug logging only.
115 * If we run out of entries, just unload and reload the driver. */
116static struct RTLOGGERPERTHREAD
117{
118 /** The thread. */
119 RTNATIVETHREAD volatile NativeThread;
120 /** The (process / session) key. */
121 uintptr_t volatile uKey;
122 /** The logger instance.*/
123 PRTLOGGER volatile pLogger;
124} g_aPerThreadLoggers[8] =
125{ { NIL_RTNATIVETHREAD, 0, 0},
126 { NIL_RTNATIVETHREAD, 0, 0},
127 { NIL_RTNATIVETHREAD, 0, 0},
128 { NIL_RTNATIVETHREAD, 0, 0},
129 { NIL_RTNATIVETHREAD, 0, 0},
130 { NIL_RTNATIVETHREAD, 0, 0},
131 { NIL_RTNATIVETHREAD, 0, 0},
132 { NIL_RTNATIVETHREAD, 0, 0}
133};
134#endif /* IN_RING0 */
135
136/**
137 * Logger flags instructions.
138 */
139static struct
140{
141 const char *pszInstr; /**< The name */
142 size_t cchInstr; /**< The size of the name. */
143 uint32_t fFlag; /**< The flag value. */
144 bool fInverted; /**< Inverse meaning? */
145}
146const s_aLogFlags[] =
147{
148 { "disabled", sizeof("disabled" ) - 1, RTLOGFLAGS_DISABLED, false },
149 { "enabled", sizeof("enabled" ) - 1, RTLOGFLAGS_DISABLED, true },
150 { "buffered", sizeof("buffered" ) - 1, RTLOGFLAGS_BUFFERED, false },
151 { "unbuffered", sizeof("unbuffered" ) - 1, RTLOGFLAGS_BUFFERED, true },
152 { "usecrlf", sizeof("usecrlf" ) - 1, RTLOGFLAGS_USECRLF, false },
153 { "uself", sizeof("uself" ) - 1, RTLOGFLAGS_USECRLF, true },
154 { "append", sizeof("append" ) - 1, RTLOGFLAGS_APPEND, false },
155 { "overwrite", sizeof("overwrite" ) - 1, RTLOGFLAGS_APPEND, true },
156 { "rel", sizeof("rel" ) - 1, RTLOGFLAGS_REL_TS, false },
157 { "abs", sizeof("abs" ) - 1, RTLOGFLAGS_REL_TS, true },
158 { "dec", sizeof("dec" ) - 1, RTLOGFLAGS_DECIMAL_TS, false },
159 { "hex", sizeof("hex" ) - 1, RTLOGFLAGS_DECIMAL_TS, true },
160 { "lockcnts", sizeof("lockcnts" ) - 1, RTLOGFLAGS_PREFIX_LOCK_COUNTS, false },
161 { "cpuid", sizeof("cpuid" ) - 1, RTLOGFLAGS_PREFIX_CPUID, false },
162 { "pid", sizeof("pid" ) - 1, RTLOGFLAGS_PREFIX_PID, false },
163 { "flagno", sizeof("flagno" ) - 1, RTLOGFLAGS_PREFIX_FLAG_NO, false },
164 { "flag", sizeof("flag" ) - 1, RTLOGFLAGS_PREFIX_FLAG, false },
165 { "groupno", sizeof("groupno" ) - 1, RTLOGFLAGS_PREFIX_GROUP_NO, false },
166 { "group", sizeof("group" ) - 1, RTLOGFLAGS_PREFIX_GROUP, false },
167 { "tid", sizeof("tid" ) - 1, RTLOGFLAGS_PREFIX_TID, false },
168 { "thread", sizeof("thread" ) - 1, RTLOGFLAGS_PREFIX_THREAD, false },
169 { "custom", sizeof("custom" ) - 1, RTLOGFLAGS_PREFIX_CUSTOM, false },
170 { "timeprog", sizeof("timeprog" ) - 1, RTLOGFLAGS_PREFIX_TIME_PROG, false },
171 { "time", sizeof("time" ) - 1, RTLOGFLAGS_PREFIX_TIME, false },
172 { "msprog", sizeof("msprog" ) - 1, RTLOGFLAGS_PREFIX_MS_PROG, false },
173 { "tsc", sizeof("tsc" ) - 1, RTLOGFLAGS_PREFIX_TSC, false }, /* before ts! */
174 { "ts", sizeof("ts" ) - 1, RTLOGFLAGS_PREFIX_TS, false },
175};
176
177/**
178 * Logger destination instructions.
179 */
180static struct
181{
182 const char *pszInstr; /**< The name. */
183 size_t cchInstr; /**< The size of the name. */
184 uint32_t fFlag; /**< The corresponding destination flag. */
185} const s_aLogDst[] =
186{
187 { "file", sizeof("file" ) - 1, RTLOGDEST_FILE }, /* Must be 1st! */
188 { "dir", sizeof("dir" ) - 1, RTLOGDEST_FILE }, /* Must be 2nd! */
189 { "stdout", sizeof("stdout" ) - 1, RTLOGDEST_STDOUT },
190 { "stderr", sizeof("stderr" ) - 1, RTLOGDEST_STDERR },
191 { "debugger", sizeof("debugger") - 1, RTLOGDEST_DEBUGGER },
192 { "com", sizeof("com" ) - 1, RTLOGDEST_COM },
193 { "user", sizeof("user" ) - 1, RTLOGDEST_USER },
194};
195
196
197/**
198 * Locks the logger instance.
199 *
200 * @returns See RTSemSpinMutexRequest().
201 * @param pLogger The logger instance.
202 */
203DECLINLINE(int) rtlogLock(PRTLOGGER pLogger)
204{
205#ifndef IN_RC
206 if (pLogger->hSpinMtx != NIL_RTSEMSPINMUTEX)
207 {
208 int rc = RTSemSpinMutexRequest(pLogger->hSpinMtx);
209 if (RT_FAILURE(rc))
210 return rc;
211 }
212#endif
213 return VINF_SUCCESS;
214}
215
216
217/**
218 * Unlocks the logger instance.
219 * @param pLogger The logger instance.
220 */
221DECLINLINE(void) rtlogUnlock(PRTLOGGER pLogger)
222{
223#ifndef IN_RC
224 if (pLogger->hSpinMtx != NIL_RTSEMFASTMUTEX)
225 RTSemSpinMutexRelease(pLogger->hSpinMtx);
226#endif
227 return;
228}
229
230
231#ifndef IN_RC
232/**
233 * Create a logger instance, comprehensive version.
234 *
235 * @returns iprt status code.
236 *
237 * @param ppLogger Where to store the logger instance.
238 * @param fFlags Logger instance flags, a combination of the RTLOGFLAGS_* values.
239 * @param pszGroupSettings The initial group settings.
240 * @param pszEnvVarBase Base name for the environment variables for this instance.
241 * @param cGroups Number of groups in the array.
242 * @param papszGroups Pointer to array of groups. This must stick around for the life of the
243 * logger instance.
244 * @param fDestFlags The destination flags. RTLOGDEST_FILE is ORed if pszFilenameFmt specified.
245 * @param pszErrorMsg A buffer which is filled with an error message if something fails. May be NULL.
246 * @param cchErrorMsg The size of the error message buffer.
247 * @param pszFilenameFmt Log filename format string. Standard RTStrFormat().
248 * @param ... Format arguments.
249 */
250RTDECL(int) RTLogCreateExV(PRTLOGGER *ppLogger, uint32_t fFlags, const char *pszGroupSettings,
251 const char *pszEnvVarBase, unsigned cGroups, const char * const * papszGroups,
252 uint32_t fDestFlags, char *pszErrorMsg, size_t cchErrorMsg, const char *pszFilenameFmt, va_list args)
253{
254 int rc;
255 size_t cb;
256 PRTLOGGER pLogger;
257
258 /*
259 * Validate input.
260 */
261 if ( (cGroups && !papszGroups)
262 || !VALID_PTR(ppLogger)
263 )
264 {
265 AssertMsgFailed(("Invalid parameters!\n"));
266 return VERR_INVALID_PARAMETER;
267 }
268 *ppLogger = NULL;
269
270 if (pszErrorMsg)
271 RTStrPrintf(pszErrorMsg, cchErrorMsg, "unknown error");
272
273 /*
274 * Allocate a logger instance.
275 */
276 cb = RT_OFFSETOF(RTLOGGER, afGroups[cGroups + 1]) + RTPATH_MAX;
277 pLogger = (PRTLOGGER)RTMemAllocZ(cb);
278 if (pLogger)
279 {
280 uint8_t *pu8Code;
281
282 pLogger->u32Magic = RTLOGGER_MAGIC;
283 pLogger->papszGroups = papszGroups;
284 pLogger->cMaxGroups = cGroups;
285 pLogger->cGroups = cGroups;
286 pLogger->pszFilename = (char *)&pLogger->afGroups[cGroups + 1];
287 pLogger->File = NIL_RTFILE;
288 pLogger->fFlags = fFlags;
289 pLogger->fDestFlags = fDestFlags;
290 pLogger->fPendingPrefix = true;
291 if (pszGroupSettings)
292 RTLogGroupSettings(pLogger, pszGroupSettings);
293
294 /*
295 * Emit wrapper code.
296 */
297 pu8Code = (uint8_t *)RTMemExecAlloc(64);
298 if (pu8Code)
299 {
300 pLogger->pfnLogger = *(PFNRTLOGGER*)&pu8Code;
301#ifdef RT_ARCH_AMD64
302 /* this wrapper will not be used on AMD64, we will be requiring C99 compilers there. */
303 *pu8Code++ = 0xcc;
304#else
305 *pu8Code++ = 0x68; /* push imm32 */
306 *(void **)pu8Code = pLogger;
307 pu8Code += sizeof(void *);
308 *pu8Code++ = 0xe8; /* call rel32 */
309 *(uint32_t *)pu8Code = (uintptr_t)RTLogLogger - ((uintptr_t)pu8Code + sizeof(uint32_t));
310 pu8Code += sizeof(uint32_t);
311 *pu8Code++ = 0x8d; /* lea esp, [esp + 4] */
312 *pu8Code++ = 0x64;
313 *pu8Code++ = 0x24;
314 *pu8Code++ = 0x04;
315 *pu8Code++ = 0xc3; /* ret near */
316#endif
317 AssertMsg((uintptr_t)pu8Code - (uintptr_t)pLogger->pfnLogger <= 64,
318 ("Wrapper assembly is too big! %d bytes\n", (uintptr_t)pu8Code - (uintptr_t)pLogger->pfnLogger));
319
320
321#ifdef IN_RING3 /* files and env.vars. are only accessible when in R3 at the present time. */
322 /*
323 * Format the filename.
324 */
325 if (pszFilenameFmt)
326 {
327 RTStrPrintfV(pLogger->pszFilename, RTPATH_MAX, pszFilenameFmt, args);
328 pLogger->fDestFlags |= RTLOGDEST_FILE;
329 }
330
331 /*
332 * Parse the environment variables.
333 */
334 if (pszEnvVarBase)
335 {
336 /* make temp copy of environment variable base. */
337 size_t cchEnvVarBase = strlen(pszEnvVarBase);
338 char *pszEnvVar = (char *)alloca(cchEnvVarBase + 16);
339 memcpy(pszEnvVar, pszEnvVarBase, cchEnvVarBase);
340
341 /*
342 * Destination.
343 */
344 strcpy(pszEnvVar + cchEnvVarBase, "_DEST");
345 const char *pszVar = RTEnvGet(pszEnvVar);
346 if (pszVar)
347 RTLogDestinations(pLogger, pszVar);
348
349 /*
350 * The flags.
351 */
352 strcpy(pszEnvVar + cchEnvVarBase, "_FLAGS");
353 pszVar = RTEnvGet(pszEnvVar);
354 if (pszVar)
355 RTLogFlags(pLogger, pszVar);
356
357 /*
358 * The group settings.
359 */
360 pszEnvVar[cchEnvVarBase] = '\0';
361 pszVar = RTEnvGet(pszEnvVar);
362 if (pszVar)
363 RTLogGroupSettings(pLogger, pszVar);
364 }
365#endif /* IN_RING3 */
366
367 /*
368 * Open the destination(s).
369 */
370 rc = VINF_SUCCESS;
371#ifdef IN_RING3
372 if (pLogger->fDestFlags & RTLOGDEST_FILE)
373 {
374 if (!(pLogger->fFlags & RTLOGFLAGS_APPEND))
375 rc = RTFileOpen(&pLogger->File, pLogger->pszFilename,
376 RTFILE_O_WRITE | RTFILE_O_CREATE_REPLACE | RTFILE_O_DENY_WRITE);
377 else
378 {
379 /** @todo RTFILE_O_APPEND. */
380 rc = RTFileOpen(&pLogger->File, pLogger->pszFilename,
381 RTFILE_O_WRITE | RTFILE_O_OPEN_CREATE | RTFILE_O_DENY_WRITE);
382 if (RT_SUCCESS(rc))
383 {
384 rc = RTFileSeek(pLogger->File, 0, RTFILE_SEEK_END, NULL);
385 if (RT_FAILURE(rc))
386 {
387 RTFileClose(pLogger->File);
388 pLogger->File = NIL_RTFILE;
389 }
390 }
391 }
392 if (RT_FAILURE(rc) && pszErrorMsg)
393 RTStrPrintf(pszErrorMsg, cchErrorMsg, "could not open file '%s'", pLogger->pszFilename);
394 }
395#endif /* IN_RING3 */
396
397 /*
398 * Create mutex and check how much it counts when entering the lock
399 * so that we can report the values for RTLOGFLAGS_PREFIX_LOCK_COUNTS.
400 */
401 if (RT_SUCCESS(rc))
402 {
403 rc = RTSemSpinMutexCreate(&pLogger->hSpinMtx, RTSEMSPINMUTEX_FLAGS_IRQ_SAFE);
404 if (RT_SUCCESS(rc))
405 {
406#ifdef IN_RING3 /** @todo do counters in ring-0 too? */
407 RTTHREAD Thread = RTThreadSelf();
408 if (Thread != NIL_RTTHREAD)
409 {
410 int32_t c = RTThreadGetWriteLockCount(Thread);
411 RTSemSpinMutexRequest(pLogger->hSpinMtx);
412 c = RTThreadGetWriteLockCount(Thread) - c;
413 RTSemSpinMutexRelease(pLogger->hSpinMtx);
414 ASMAtomicWriteU32(&g_cLoggerLockCount, c);
415 }
416#endif
417 *ppLogger = pLogger;
418 return VINF_SUCCESS;
419 }
420
421 if (pszErrorMsg)
422 RTStrPrintf(pszErrorMsg, cchErrorMsg, "failed to create sempahore");
423 }
424#ifdef IN_RING3
425 RTFileClose(pLogger->File);
426#endif
427 RTMemExecFree(*(void **)&pLogger->pfnLogger);
428 }
429 else
430 {
431#ifdef RT_OS_LINUX
432 /*
433 * RTMemAlloc() succeeded but RTMemExecAlloc() failed -- most probably an SELinux problem.
434 */
435 if (pszErrorMsg)
436 RTStrPrintf(pszErrorMsg, cchErrorMsg, "mmap(PROT_WRITE | PROT_EXEC) failed -- SELinux?");
437#endif /* RT_OS_LINUX */
438 rc = VERR_NO_MEMORY;
439 }
440 RTMemFree(pLogger);
441 }
442 else
443 rc = VERR_NO_MEMORY;
444
445 return rc;
446}
447RT_EXPORT_SYMBOL(RTLogCreateExV);
448
449
450/**
451 * Create a logger instance.
452 *
453 * @returns iprt status code.
454 *
455 * @param ppLogger Where to store the logger instance.
456 * @param fFlags Logger instance flags, a combination of the RTLOGFLAGS_* values.
457 * @param pszGroupSettings The initial group settings.
458 * @param pszEnvVarBase Base name for the environment variables for this instance.
459 * @param cGroups Number of groups in the array.
460 * @param papszGroups Pointer to array of groups. This must stick around for the life of the
461 * logger instance.
462 * @param fDestFlags The destination flags. RTLOGDEST_FILE is ORed if pszFilenameFmt specified.
463 * @param pszFilenameFmt Log filename format string. Standard RTStrFormat().
464 * @param ... Format arguments.
465 */
466RTDECL(int) RTLogCreate(PRTLOGGER *ppLogger, uint32_t fFlags, const char *pszGroupSettings,
467 const char *pszEnvVarBase, unsigned cGroups, const char * const * papszGroups,
468 uint32_t fDestFlags, const char *pszFilenameFmt, ...)
469{
470 va_list args;
471 int rc;
472
473 va_start(args, pszFilenameFmt);
474 rc = RTLogCreateExV(ppLogger, fFlags, pszGroupSettings, pszEnvVarBase, cGroups, papszGroups, fDestFlags, NULL, 0, pszFilenameFmt, args);
475 va_end(args);
476 return rc;
477}
478RT_EXPORT_SYMBOL(RTLogCreate);
479
480
481/**
482 * Create a logger instance.
483 *
484 * @returns iprt status code.
485 *
486 * @param ppLogger Where to store the logger instance.
487 * @param fFlags Logger instance flags, a combination of the RTLOGFLAGS_* values.
488 * @param pszGroupSettings The initial group settings.
489 * @param pszEnvVarBase Base name for the environment variables for this instance.
490 * @param cGroups Number of groups in the array.
491 * @param papszGroups Pointer to array of groups. This must stick around for the life of the
492 * logger instance.
493 * @param fDestFlags The destination flags. RTLOGDEST_FILE is ORed if pszFilenameFmt specified.
494 * @param pszErrorMsg A buffer which is filled with an error message if something fails. May be NULL.
495 * @param cchErrorMsg The size of the error message buffer.
496 * @param pszFilenameFmt Log filename format string. Standard RTStrFormat().
497 * @param ... Format arguments.
498 */
499RTDECL(int) RTLogCreateEx(PRTLOGGER *ppLogger, uint32_t fFlags, const char *pszGroupSettings,
500 const char *pszEnvVarBase, unsigned cGroups, const char * const * papszGroups,
501 uint32_t fDestFlags, char *pszErrorMsg, size_t cchErrorMsg, const char *pszFilenameFmt, ...)
502{
503 va_list args;
504 int rc;
505
506 va_start(args, pszFilenameFmt);
507 rc = RTLogCreateExV(ppLogger, fFlags, pszGroupSettings, pszEnvVarBase, cGroups, papszGroups, fDestFlags, pszErrorMsg, cchErrorMsg, pszFilenameFmt, args);
508 va_end(args);
509 return rc;
510}
511RT_EXPORT_SYMBOL(RTLogCreateEx);
512
513
514/**
515 * Destroys a logger instance.
516 *
517 * The instance is flushed and all output destinations closed (where applicable).
518 *
519 * @returns iprt status code.
520 * @param pLogger The logger instance which close destroyed. NULL is fine.
521 */
522RTDECL(int) RTLogDestroy(PRTLOGGER pLogger)
523{
524 int rc;
525 uint32_t iGroup;
526 RTSEMSPINMUTEX hSpinMtx;
527
528 /*
529 * Validate input.
530 */
531 if (!pLogger)
532 return VINF_SUCCESS;
533 AssertReturn(VALID_PTR(pLogger), VERR_INVALID_POINTER);
534 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
535
536 /*
537 * Acquire logger instance sem and disable all logging. (paranoia)
538 */
539 rc = rtlogLock(pLogger);
540 AssertMsgRCReturn(rc, ("%Rrc\n", rc), rc);
541
542 pLogger->fFlags |= RTLOGFLAGS_DISABLED;
543 iGroup = pLogger->cGroups;
544 while (iGroup-- > 0)
545 pLogger->afGroups[iGroup] = 0;
546
547 /*
548 * Flush it.
549 */
550 rtlogFlush(pLogger);
551
552 /*
553 * Close output stuffs.
554 */
555#ifdef IN_RING3
556 if (pLogger->File != NIL_RTFILE)
557 {
558 int rc2 = RTFileClose(pLogger->File);
559 AssertRC(rc2);
560 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
561 rc = rc2;
562 pLogger->File = NIL_RTFILE;
563 }
564#endif
565
566 /*
567 * Free the mutex, the wrapper and the instance memory.
568 */
569 hSpinMtx = pLogger->hSpinMtx;
570 pLogger->hSpinMtx = NIL_RTSEMSPINMUTEX;
571 if (hSpinMtx != NIL_RTSEMSPINMUTEX)
572 {
573 int rc2;
574 RTSemSpinMutexRelease(hSpinMtx);
575 rc2 = RTSemSpinMutexDestroy(hSpinMtx);
576 AssertRC(rc2);
577 if (RT_FAILURE(rc2) && RT_SUCCESS(rc))
578 rc = rc2;
579 }
580
581 if (pLogger->pfnLogger)
582 {
583 RTMemExecFree(*(void **)&pLogger->pfnLogger);
584 pLogger->pfnLogger = NULL;
585 }
586 RTMemFree(pLogger);
587
588 return rc;
589}
590RT_EXPORT_SYMBOL(RTLogDestroy);
591
592
593/**
594 * Create a logger instance clone for RC usage.
595 *
596 * @returns iprt status code.
597 *
598 * @param pLogger The logger instance to be cloned.
599 * @param pLoggerRC Where to create the RC logger instance.
600 * @param cbLoggerRC Amount of memory allocated to for the RC logger
601 * instance clone.
602 * @param pfnLoggerRCPtr Pointer to logger wrapper function for this
603 * instance (RC Ptr).
604 * @param pfnFlushRCPtr Pointer to flush function (RC Ptr).
605 * @param fFlags Logger instance flags, a combination of the RTLOGFLAGS_* values.
606 */
607RTDECL(int) RTLogCloneRC(PRTLOGGER pLogger, PRTLOGGERRC pLoggerRC, size_t cbLoggerRC,
608 RTRCPTR pfnLoggerRCPtr, RTRCPTR pfnFlushRCPtr, uint32_t fFlags)
609{
610 /*
611 * Validate input.
612 */
613 if ( !pLoggerRC
614 || !pfnFlushRCPtr
615 || !pfnLoggerRCPtr)
616 {
617 AssertMsgFailed(("Invalid parameters!\n"));
618 return VERR_INVALID_PARAMETER;
619 }
620 if (cbLoggerRC < sizeof(*pLoggerRC))
621 {
622 AssertMsgFailed(("%d min=%d\n", cbLoggerRC, sizeof(*pLoggerRC)));
623 return VERR_INVALID_PARAMETER;
624 }
625
626 /*
627 * Initialize GC instance.
628 */
629 pLoggerRC->offScratch = 0;
630 pLoggerRC->fPendingPrefix = false;
631 pLoggerRC->pfnLogger = pfnLoggerRCPtr;
632 pLoggerRC->pfnFlush = pfnFlushRCPtr;
633 pLoggerRC->u32Magic = RTLOGGERRC_MAGIC;
634 pLoggerRC->fFlags = fFlags | RTLOGFLAGS_DISABLED;
635 pLoggerRC->cGroups = 1;
636 pLoggerRC->afGroups[0] = 0;
637
638 /*
639 * Resolve defaults.
640 */
641 if (!pLogger)
642 {
643 pLogger = RTLogDefaultInstance();
644 if (!pLogger)
645 return VINF_SUCCESS;
646 }
647
648 /*
649 * Check if there's enough space for the groups.
650 */
651 if (cbLoggerRC < (size_t)RT_OFFSETOF(RTLOGGERRC, afGroups[pLogger->cGroups]))
652 {
653 AssertMsgFailed(("%d req=%d cGroups=%d\n", cbLoggerRC, RT_OFFSETOF(RTLOGGERRC, afGroups[pLogger->cGroups]), pLogger->cGroups));
654 return VERR_INVALID_PARAMETER;
655 }
656 memcpy(&pLoggerRC->afGroups[0], &pLogger->afGroups[0], pLogger->cGroups * sizeof(pLoggerRC->afGroups[0]));
657 pLoggerRC->cGroups = pLogger->cGroups;
658
659 /*
660 * Copy bits from the HC instance.
661 */
662 pLoggerRC->fPendingPrefix = pLogger->fPendingPrefix;
663 pLoggerRC->fFlags |= pLogger->fFlags;
664
665 /*
666 * Check if we can remove the disabled flag.
667 */
668 if ( pLogger->fDestFlags
669 && !((pLogger->fFlags | fFlags) & RTLOGFLAGS_DISABLED))
670 pLoggerRC->fFlags &= ~RTLOGFLAGS_DISABLED;
671
672 return VINF_SUCCESS;
673}
674RT_EXPORT_SYMBOL(RTLogCloneRC);
675
676
677/**
678 * Flushes a RC logger instance to a R3 logger.
679 *
680 *
681 * @returns iprt status code.
682 * @param pLogger The R3 logger instance to flush pLoggerRC to. If NULL
683 * the default logger is used.
684 * @param pLoggerRC The RC logger instance to flush.
685 */
686RTDECL(void) RTLogFlushRC(PRTLOGGER pLogger, PRTLOGGERRC pLoggerRC)
687{
688 /*
689 * Resolve defaults.
690 */
691 if (!pLogger)
692 {
693 pLogger = RTLogDefaultInstance();
694 if (!pLogger)
695 {
696 pLoggerRC->offScratch = 0;
697 return;
698 }
699 }
700
701 /*
702 * Any thing to flush?
703 */
704 if ( pLogger->offScratch
705 || pLoggerRC->offScratch)
706 {
707 /*
708 * Acquire logger instance sem.
709 */
710 int rc = rtlogLock(pLogger);
711 if (RT_FAILURE(rc))
712 return;
713
714 /*
715 * Write whatever the GC instance contains to the HC one, and then
716 * flush the HC instance.
717 */
718 if (pLoggerRC->offScratch)
719 {
720 rtLogOutput(pLogger, pLoggerRC->achScratch, pLoggerRC->offScratch);
721 rtLogOutput(pLogger, NULL, 0);
722 pLoggerRC->offScratch = 0;
723 }
724
725 /*
726 * Release the semaphore.
727 */
728 rtlogUnlock(pLogger);
729 }
730}
731RT_EXPORT_SYMBOL(RTLogFlushRC);
732
733
734#ifdef IN_RING3
735/**
736 * Create a logger instance for singled threaded ring-0 usage.
737 *
738 * @returns iprt status code.
739 *
740 * @param pLogger Where to create the logger instance.
741 * @param cbLogger The amount of memory available for the logger instance.
742 * @param pfnLogger Pointer to logger wrapper function for the clone.
743 * @param pfnFlush Pointer to flush function for the clone.
744 * @param fFlags Logger instance flags for the clone, a combination of the RTLOGFLAGS_* values.
745 * @param fDestFlags The destination flags.
746 */
747RTDECL(int) RTLogCreateForR0(PRTLOGGER pLogger, size_t cbLogger, PFNRTLOGGER pfnLogger, PFNRTLOGFLUSH pfnFlush,
748 uint32_t fFlags, uint32_t fDestFlags)
749{
750 /*
751 * Validate input.
752 */
753 AssertPtrReturn(pLogger, VERR_INVALID_PARAMETER);
754 AssertReturn(cbLogger >= sizeof(*pLogger), VERR_INVALID_PARAMETER);
755 AssertReturn(pfnLogger, VERR_INVALID_PARAMETER);
756 AssertReturn(pfnFlush, VERR_INVALID_PARAMETER);
757
758 /*
759 * Initialize the ring-0 instance.
760 */
761 pLogger->offScratch = 0;
762 pLogger->fPendingPrefix = false;
763 pLogger->pfnLogger = pfnLogger;
764 pLogger->pfnFlush = pfnFlush;
765 pLogger->hSpinMtx = NIL_RTSEMSPINMUTEX; /* Not serialized. */
766 pLogger->u32Magic = RTLOGGER_MAGIC;
767 pLogger->fFlags = fFlags;
768 pLogger->fDestFlags = fDestFlags & ~RTLOGDEST_FILE;
769 pLogger->File = NIL_RTFILE;
770 pLogger->pszFilename = NULL;
771 pLogger->papszGroups = NULL;
772 pLogger->cMaxGroups = (uint32_t)((cbLogger - RT_OFFSETOF(RTLOGGER, afGroups[0])) / sizeof(pLogger->afGroups[0]));
773 pLogger->cGroups = 1;
774 pLogger->afGroups[0] = 0;
775 return VINF_SUCCESS;
776}
777RT_EXPORT_SYMBOL(RTLogCreateForR0);
778#endif /* IN_RING3 */
779
780
781/**
782 * Copies the group settings and flags from logger instance to another.
783 *
784 * @returns IPRT status code.
785 * @param pDstLogger The destination logger instance.
786 * @param pSrcLogger The source logger instance. If NULL the default one is used.
787 * @param fFlagsOr OR mask for the flags.
788 * @param fFlagsAnd AND mask for the flags.
789 */
790RTDECL(int) RTLogCopyGroupsAndFlags(PRTLOGGER pDstLogger, PCRTLOGGER pSrcLogger, unsigned fFlagsOr, unsigned fFlagsAnd)
791{
792 int rc;
793 unsigned cGroups;
794
795 /*
796 * Validate input.
797 */
798 AssertPtrReturn(pDstLogger, VERR_INVALID_PARAMETER);
799 AssertPtrNullReturn(pSrcLogger, VERR_INVALID_PARAMETER);
800
801 /*
802 * Resolve defaults.
803 */
804 if (!pSrcLogger)
805 {
806 pSrcLogger = RTLogDefaultInstance();
807 if (!pSrcLogger)
808 {
809 pDstLogger->fFlags |= RTLOGFLAGS_DISABLED;
810 pDstLogger->cGroups = 1;
811 pDstLogger->afGroups[0] = 0;
812 return VINF_SUCCESS;
813 }
814 }
815
816 /*
817 * Copy flags and group settings.
818 */
819 pDstLogger->fFlags = (pSrcLogger->fFlags & fFlagsAnd) | fFlagsOr;
820
821 rc = VINF_SUCCESS;
822 cGroups = pSrcLogger->cGroups;
823 if (cGroups < pDstLogger->cMaxGroups)
824 {
825 AssertMsgFailed(("cMaxGroups=%zd cGroups=%zd (min size %d)\n", pDstLogger->cMaxGroups,
826 pSrcLogger->cGroups, RT_OFFSETOF(RTLOGGER, afGroups[pSrcLogger->cGroups])));
827 rc = VERR_INVALID_PARAMETER;
828 cGroups = pDstLogger->cMaxGroups;
829 }
830 memcpy(&pDstLogger->afGroups[0], &pSrcLogger->afGroups[0], cGroups * sizeof(pDstLogger->afGroups[0]));
831 pDstLogger->cGroups = cGroups;
832
833 return rc;
834}
835RT_EXPORT_SYMBOL(RTLogCopyGroupsAndFlags);
836
837
838/**
839 * Flushes the buffer in one logger instance onto another logger.
840 *
841 * @returns iprt status code.
842 *
843 * @param pSrcLogger The logger instance to flush.
844 * @param pDstLogger The logger instance to flush onto.
845 * If NULL the default logger will be used.
846 */
847RTDECL(void) RTLogFlushToLogger(PRTLOGGER pSrcLogger, PRTLOGGER pDstLogger)
848{
849 /*
850 * Resolve defaults.
851 */
852 if (!pDstLogger)
853 {
854 pDstLogger = RTLogDefaultInstance();
855 if (!pDstLogger)
856 {
857 /* flushing to "/dev/null". */
858 if (pSrcLogger->offScratch)
859 {
860 int rc = rtlogLock(pSrcLogger);
861 if (RT_SUCCESS(rc))
862 {
863 pSrcLogger->offScratch = 0;
864 rtlogLock(pSrcLogger);
865 }
866 }
867 return;
868 }
869 }
870
871 /*
872 * Any thing to flush?
873 */
874 if ( pSrcLogger->offScratch
875 || pDstLogger->offScratch)
876 {
877 /*
878 * Acquire logger semaphores.
879 */
880 int rc = rtlogLock(pDstLogger);
881 if (RT_FAILURE(rc))
882 return;
883 rc = rtlogLock(pSrcLogger);
884 if (RT_SUCCESS(rc))
885 {
886 /*
887 * Write whatever the GC instance contains to the HC one, and then
888 * flush the HC instance.
889 */
890 if (pSrcLogger->offScratch)
891 {
892 rtLogOutput(pDstLogger, pSrcLogger->achScratch, pSrcLogger->offScratch);
893 rtLogOutput(pDstLogger, NULL, 0);
894 pSrcLogger->offScratch = 0;
895 }
896
897 /*
898 * Release the semaphores.
899 */
900 rtlogUnlock(pSrcLogger);
901 }
902 rtlogUnlock(pDstLogger);
903 }
904}
905RT_EXPORT_SYMBOL(RTLogFlushToLogger);
906
907
908/**
909 * Sets the custom prefix callback.
910 *
911 * @returns IPRT status code.
912 * @param pLogger The logger instance.
913 * @param pfnCallback The callback.
914 * @param pvUser The user argument for the callback.
915 * */
916RTDECL(int) RTLogSetCustomPrefixCallback(PRTLOGGER pLogger, PFNRTLOGPREFIX pfnCallback, void *pvUser)
917{
918 /*
919 * Resolve defaults.
920 */
921 if (!pLogger)
922 {
923 pLogger = RTLogDefaultInstance();
924 if (!pLogger)
925 return VINF_SUCCESS;
926 }
927 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
928
929 /*
930 * Do the work.
931 */
932 rtlogLock(pLogger);
933 pLogger->pvPrefixUserArg = pvUser;
934 pLogger->pfnPrefix = pfnCallback;
935 rtlogUnlock(pLogger);
936
937 return VINF_SUCCESS;
938}
939RT_EXPORT_SYMBOL(RTLogSetCustomPrefixCallback);
940
941
942/**
943 * Matches a group name with a pattern mask in an case insensitive manner (ASCII).
944 *
945 * @returns true if matching and *ppachMask set to the end of the pattern.
946 * @returns false if no match.
947 * @param pszGrp The group name.
948 * @param ppachMask Pointer to the pointer to the mask. Only wildcard supported is '*'.
949 * @param cchMask The length of the mask, including modifiers. The modifiers is why
950 * we update *ppachMask on match.
951 */
952static bool rtlogIsGroupMatching(const char *pszGrp, const char **ppachMask, size_t cchMask)
953{
954 const char *pachMask;
955
956 if (!pszGrp || !*pszGrp)
957 return false;
958 pachMask = *ppachMask;
959 for (;;)
960 {
961 if (RT_C_TO_LOWER(*pszGrp) != RT_C_TO_LOWER(*pachMask))
962 {
963 const char *pszTmp;
964
965 /*
966 * Check for wildcard and do a minimal match if found.
967 */
968 if (*pachMask != '*')
969 return false;
970
971 /* eat '*'s. */
972 do pachMask++;
973 while (--cchMask && *pachMask == '*');
974
975 /* is there more to match? */
976 if ( !cchMask
977 || *pachMask == '.'
978 || *pachMask == '=')
979 break; /* we're good */
980
981 /* do extremely minimal matching (fixme) */
982 pszTmp = strchr(pszGrp, RT_C_TO_LOWER(*pachMask));
983 if (!pszTmp)
984 pszTmp = strchr(pszGrp, RT_C_TO_UPPER(*pachMask));
985 if (!pszTmp)
986 return false;
987 pszGrp = pszTmp;
988 continue;
989 }
990
991 /* done? */
992 if (!*++pszGrp)
993 {
994 /* trailing wildcard is ok. */
995 do
996 {
997 pachMask++;
998 cchMask--;
999 } while (cchMask && *pachMask == '*');
1000 if ( !cchMask
1001 || *pachMask == '.'
1002 || *pachMask == '=')
1003 break; /* we're good */
1004 return false;
1005 }
1006
1007 if (!--cchMask)
1008 return false;
1009 pachMask++;
1010 }
1011
1012 /* match */
1013 *ppachMask = pachMask;
1014 return true;
1015}
1016
1017
1018/**
1019 * Updates the group settings for the logger instance using the specified
1020 * specification string.
1021 *
1022 * @returns iprt status code.
1023 * Failures can safely be ignored.
1024 * @param pLogger Logger instance.
1025 * @param pszVar Value to parse.
1026 */
1027RTDECL(int) RTLogGroupSettings(PRTLOGGER pLogger, const char *pszVar)
1028{
1029 /*
1030 * Resolve defaults.
1031 */
1032 if (!pLogger)
1033 {
1034 pLogger = RTLogDefaultInstance();
1035 if (!pLogger)
1036 return VINF_SUCCESS;
1037 }
1038
1039 /*
1040 * Iterate the string.
1041 */
1042 while (*pszVar)
1043 {
1044 /*
1045 * Skip prefixes (blanks, ;, + and -).
1046 */
1047 bool fEnabled = true;
1048 char ch;
1049 const char *pszStart;
1050 unsigned i;
1051 size_t cch;
1052
1053 while ((ch = *pszVar) == '+' || ch == '-' || ch == ' ' || ch == '\t' || ch == '\n' || ch == ';')
1054 {
1055 if (ch == '+' || ch == '-' || ';')
1056 fEnabled = ch != '-';
1057 pszVar++;
1058 }
1059 if (!*pszVar)
1060 break;
1061
1062 /*
1063 * Find end.
1064 */
1065 pszStart = pszVar;
1066 while ((ch = *pszVar) != '\0' && ch != '+' && ch != '-' && ch != ' ' && ch != '\t')
1067 pszVar++;
1068
1069 /*
1070 * Find the group (ascii case insensitive search).
1071 * Special group 'all'.
1072 */
1073 cch = pszVar - pszStart;
1074 if ( cch >= 3
1075 && (pszStart[0] == 'a' || pszStart[0] == 'A')
1076 && (pszStart[1] == 'l' || pszStart[1] == 'L')
1077 && (pszStart[2] == 'l' || pszStart[2] == 'L')
1078 && (cch == 3 || pszStart[3] == '.' || pszStart[3] == '='))
1079 {
1080 /*
1081 * All.
1082 */
1083 unsigned fFlags = cch == 3
1084 ? RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1
1085 : rtlogGroupFlags(&pszStart[3]);
1086 for (i = 0; i < pLogger->cGroups; i++)
1087 {
1088 if (fEnabled)
1089 pLogger->afGroups[i] |= fFlags;
1090 else
1091 pLogger->afGroups[i] &= ~fFlags;
1092 }
1093 }
1094 else
1095 {
1096 /*
1097 * Specific group(s).
1098 */
1099 for (i = 0; i < pLogger->cGroups; i++)
1100 {
1101 const char *psz2 = (const char*)pszStart;
1102 if (rtlogIsGroupMatching(pLogger->papszGroups[i], &psz2, cch))
1103 {
1104 unsigned fFlags = RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1;
1105 if (*psz2 == '.' || *psz2 == '=')
1106 fFlags = rtlogGroupFlags(psz2);
1107 if (fEnabled)
1108 pLogger->afGroups[i] |= fFlags;
1109 else
1110 pLogger->afGroups[i] &= ~fFlags;
1111 }
1112 } /* for each group */
1113 }
1114
1115 } /* parse specification */
1116
1117 return VINF_SUCCESS;
1118}
1119RT_EXPORT_SYMBOL(RTLogGroupSettings);
1120
1121
1122/**
1123 * Interprets the group flags suffix.
1124 *
1125 * @returns Flags specified. (0 is possible!)
1126 * @param psz Start of Suffix. (Either dot or equal sign.)
1127 */
1128static unsigned rtlogGroupFlags(const char *psz)
1129{
1130 unsigned fFlags = 0;
1131
1132 /*
1133 * Litteral flags.
1134 */
1135 while (*psz == '.')
1136 {
1137 static struct
1138 {
1139 const char *pszFlag; /* lowercase!! */
1140 unsigned fFlag;
1141 } aFlags[] =
1142 {
1143 { "eo", RTLOGGRPFLAGS_ENABLED },
1144 { "enabledonly",RTLOGGRPFLAGS_ENABLED },
1145 { "e", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 },
1146 { "enabled", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 },
1147 { "l1", RTLOGGRPFLAGS_LEVEL_1 },
1148 { "level1", RTLOGGRPFLAGS_LEVEL_1 },
1149 { "l", RTLOGGRPFLAGS_LEVEL_2 },
1150 { "l2", RTLOGGRPFLAGS_LEVEL_2 },
1151 { "level2", RTLOGGRPFLAGS_LEVEL_2 },
1152 { "l3", RTLOGGRPFLAGS_LEVEL_3 },
1153 { "level3", RTLOGGRPFLAGS_LEVEL_3 },
1154 { "l4", RTLOGGRPFLAGS_LEVEL_4 },
1155 { "level4", RTLOGGRPFLAGS_LEVEL_4 },
1156 { "l5", RTLOGGRPFLAGS_LEVEL_5 },
1157 { "level5", RTLOGGRPFLAGS_LEVEL_5 },
1158 { "l6", RTLOGGRPFLAGS_LEVEL_6 },
1159 { "level6", RTLOGGRPFLAGS_LEVEL_6 },
1160 { "f", RTLOGGRPFLAGS_FLOW },
1161 { "flow", RTLOGGRPFLAGS_FLOW },
1162
1163 { "lelik", RTLOGGRPFLAGS_LELIK },
1164 { "michael", RTLOGGRPFLAGS_MICHAEL },
1165 { "dmik", RTLOGGRPFLAGS_DMIK },
1166 { "sunlover", RTLOGGRPFLAGS_SUNLOVER },
1167 { "achim", RTLOGGRPFLAGS_ACHIM },
1168 { "achimha", RTLOGGRPFLAGS_ACHIM },
1169 { "s", RTLOGGRPFLAGS_SANDER },
1170 { "sander", RTLOGGRPFLAGS_SANDER },
1171 { "sandervl", RTLOGGRPFLAGS_SANDER },
1172 { "klaus", RTLOGGRPFLAGS_KLAUS },
1173 { "frank", RTLOGGRPFLAGS_FRANK },
1174 { "b", RTLOGGRPFLAGS_BIRD },
1175 { "bird", RTLOGGRPFLAGS_BIRD },
1176 { "aleksey", RTLOGGRPFLAGS_ALEKSEY },
1177 { "n", RTLOGGRPFLAGS_NONAME },
1178 { "noname", RTLOGGRPFLAGS_NONAME }
1179 };
1180 unsigned i;
1181 bool fFound = false;
1182 psz++;
1183 for (i = 0; i < RT_ELEMENTS(aFlags) && !fFound; i++)
1184 {
1185 const char *psz1 = aFlags[i].pszFlag;
1186 const char *psz2 = psz;
1187 while (*psz1 == RT_C_TO_LOWER(*psz2))
1188 {
1189 psz1++;
1190 psz2++;
1191 if (!*psz1)
1192 {
1193 if ( (*psz2 >= 'a' && *psz2 <= 'z')
1194 || (*psz2 >= 'A' && *psz2 <= 'Z')
1195 || (*psz2 >= '0' && *psz2 <= '9') )
1196 break;
1197 fFlags |= aFlags[i].fFlag;
1198 fFound = true;
1199 psz = psz2;
1200 break;
1201 }
1202 } /* strincmp */
1203 } /* for each flags */
1204 }
1205
1206 /*
1207 * Flag value.
1208 */
1209 if (*psz == '=')
1210 {
1211 psz++;
1212 if (*psz == '~')
1213 fFlags = ~RTStrToInt32(psz + 1);
1214 else
1215 fFlags = RTStrToInt32(psz);
1216 }
1217
1218 return fFlags;
1219}
1220
1221/**
1222 * Helper for RTLogGetGroupSettings.
1223 */
1224static int rtLogGetGroupSettingsAddOne(const char *pszName, uint32_t fGroup, char **ppszBuf, size_t *pcchBuf, bool *pfNotFirst)
1225{
1226#define APPEND_PSZ(psz,cch) do { memcpy(*ppszBuf, (psz), (cch)); *ppszBuf += (cch); *pcchBuf -= (cch); } while (0)
1227#define APPEND_SZ(sz) APPEND_PSZ(sz, sizeof(sz) - 1)
1228#define APPEND_CH(ch) do { **ppszBuf = (ch); *ppszBuf += 1; *pcchBuf -= 1; } while (0)
1229
1230 /*
1231 * Add the name.
1232 */
1233 size_t cchName = strlen(pszName);
1234 if (cchName + 1 + *pfNotFirst > *pcchBuf)
1235 return VERR_BUFFER_OVERFLOW;
1236 if (*pfNotFirst)
1237 APPEND_CH(' ');
1238 else
1239 *pfNotFirst = true;
1240 APPEND_PSZ(pszName, cchName);
1241
1242 /*
1243 * Only generate mnemonics for the simple+common bits.
1244 */
1245 if (fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1))
1246 /* nothing */;
1247 else if ( fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_LEVEL_2 | RTLOGGRPFLAGS_FLOW)
1248 && *pcchBuf >= sizeof(".e.l.f"))
1249 APPEND_SZ(".e.l.f");
1250 else if ( fGroup == (RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 | RTLOGGRPFLAGS_FLOW)
1251 && *pcchBuf >= sizeof(".e.f"))
1252 APPEND_SZ(".e.f");
1253 else if (*pcchBuf >= 1 + 10 + 1)
1254 {
1255 size_t cch;
1256 APPEND_CH('=');
1257 cch = RTStrFormatNumber(*ppszBuf, fGroup, 16, 0, 0, RTSTR_F_SPECIAL | RTSTR_F_32BIT);
1258 *ppszBuf += cch;
1259 *pcchBuf -= cch;
1260 }
1261 else
1262 return VERR_BUFFER_OVERFLOW;
1263
1264#undef APPEND_PSZ
1265#undef APPEND_SZ
1266#undef APPEND_CH
1267 return VINF_SUCCESS;
1268}
1269
1270
1271/**
1272 * Get the current log group settings as a string.
1273 *
1274 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
1275 * @param pLogger Logger instance (NULL for default logger).
1276 * @param pszBuf The output buffer.
1277 * @param cchBuf The size of the output buffer. Must be greater
1278 * than zero.
1279 */
1280RTDECL(int) RTLogGetGroupSettings(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
1281{
1282 bool fNotFirst = false;
1283 int rc = VINF_SUCCESS;
1284 uint32_t cGroups;
1285 uint32_t fGroup;
1286 uint32_t i;
1287
1288 Assert(cchBuf);
1289
1290 /*
1291 * Resolve defaults.
1292 */
1293 if (!pLogger)
1294 {
1295 pLogger = RTLogDefaultInstance();
1296 if (!pLogger)
1297 {
1298 *pszBuf = '\0';
1299 return VINF_SUCCESS;
1300 }
1301 }
1302
1303 cGroups = pLogger->cGroups;
1304
1305 /*
1306 * Check if all are the same.
1307 */
1308 fGroup = pLogger->afGroups[0];
1309 for (i = 1; i < cGroups; i++)
1310 if (pLogger->afGroups[i] != fGroup)
1311 break;
1312 if (i >= cGroups)
1313 rc = rtLogGetGroupSettingsAddOne("all", fGroup, &pszBuf, &cchBuf, &fNotFirst);
1314 else
1315 {
1316
1317 /*
1318 * Iterate all the groups and print all that are enabled.
1319 */
1320 for (i = 0; i < cGroups; i++)
1321 {
1322 fGroup = pLogger->afGroups[i];
1323 if (fGroup)
1324 {
1325 const char *pszName = pLogger->papszGroups[i];
1326 if (pszName)
1327 {
1328 rc = rtLogGetGroupSettingsAddOne(pszName, fGroup, &pszBuf, &cchBuf, &fNotFirst);
1329 if (rc)
1330 break;
1331 }
1332 }
1333 }
1334 }
1335
1336 *pszBuf = '\0';
1337 return rc;
1338}
1339RT_EXPORT_SYMBOL(RTLogGetGroupSettings);
1340#endif /* !IN_RC */
1341
1342
1343/**
1344 * Updates the flags for the logger instance using the specified
1345 * specification string.
1346 *
1347 * @returns iprt status code.
1348 * Failures can safely be ignored.
1349 * @param pLogger Logger instance (NULL for default logger).
1350 * @param pszVar Value to parse.
1351 */
1352RTDECL(int) RTLogFlags(PRTLOGGER pLogger, const char *pszVar)
1353{
1354 int rc = VINF_SUCCESS;
1355
1356 /*
1357 * Resolve defaults.
1358 */
1359 if (!pLogger)
1360 {
1361 pLogger = RTLogDefaultInstance();
1362 if (!pLogger)
1363 return VINF_SUCCESS;
1364 }
1365
1366 /*
1367 * Iterate the string.
1368 */
1369 while (*pszVar)
1370 {
1371 /* check no prefix. */
1372 bool fNo = false;
1373 char ch;
1374 unsigned i;
1375
1376 /* skip blanks. */
1377 while (RT_C_IS_SPACE(*pszVar))
1378 pszVar++;
1379 if (!*pszVar)
1380 return rc;
1381
1382 while ((ch = *pszVar) != '\0')
1383 {
1384 if (ch == 'n' && pszVar[1] == 'o')
1385 {
1386 pszVar += 2;
1387 fNo = !fNo;
1388 }
1389 else if (ch == '+')
1390 {
1391 pszVar++;
1392 fNo = true;
1393 }
1394 else if (ch == '-' || ch == '!' || ch == '~')
1395 {
1396 pszVar++;
1397 fNo = !fNo;
1398 }
1399 else
1400 break;
1401 }
1402
1403 /* instruction. */
1404 for (i = 0; i < RT_ELEMENTS(s_aLogFlags); i++)
1405 {
1406 if (!strncmp(pszVar, s_aLogFlags[i].pszInstr, s_aLogFlags[i].cchInstr))
1407 {
1408 if (fNo == s_aLogFlags[i].fInverted)
1409 pLogger->fFlags |= s_aLogFlags[i].fFlag;
1410 else
1411 pLogger->fFlags &= ~s_aLogFlags[i].fFlag;
1412 pszVar += s_aLogFlags[i].cchInstr;
1413 break;
1414 }
1415 }
1416
1417 /* unknown instruction? */
1418 if (i >= RT_ELEMENTS(s_aLogFlags))
1419 {
1420 AssertMsgFailed(("Invalid flags! unknown instruction %.20s\n", pszVar));
1421 pszVar++;
1422 }
1423
1424 /* skip blanks and delimiters. */
1425 while (RT_C_IS_SPACE(*pszVar) || *pszVar == ';')
1426 pszVar++;
1427 } /* while more environment variable value left */
1428
1429 return rc;
1430}
1431RT_EXPORT_SYMBOL(RTLogFlags);
1432
1433
1434#ifndef IN_RC
1435/**
1436 * Get the current log flags as a string.
1437 *
1438 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
1439 * @param pLogger Logger instance (NULL for default logger).
1440 * @param pszBuf The output buffer.
1441 * @param cchBuf The size of the output buffer. Must be greater
1442 * than zero.
1443 */
1444RTDECL(int) RTLogGetFlags(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
1445{
1446 bool fNotFirst = false;
1447 int rc = VINF_SUCCESS;
1448 uint32_t fFlags;
1449 unsigned i;
1450
1451 Assert(cchBuf);
1452
1453 /*
1454 * Resolve defaults.
1455 */
1456 if (!pLogger)
1457 {
1458 pLogger = RTLogDefaultInstance();
1459 if (!pLogger)
1460 {
1461 *pszBuf = '\0';
1462 return VINF_SUCCESS;
1463 }
1464 }
1465
1466 /*
1467 * Add the flags in the list.
1468 */
1469 fFlags = pLogger->fFlags;
1470 for (i = 0; i < RT_ELEMENTS(s_aLogFlags); i++)
1471 if ( !s_aLogFlags[i].fInverted
1472 ? (s_aLogFlags[i].fFlag & fFlags)
1473 : !(s_aLogFlags[i].fFlag & fFlags))
1474 {
1475 size_t cchInstr = s_aLogFlags[i].cchInstr;
1476 if (cchInstr + fNotFirst + 1 > cchBuf)
1477 {
1478 rc = VERR_BUFFER_OVERFLOW;
1479 break;
1480 }
1481 if (fNotFirst)
1482 {
1483 *pszBuf++ = ' ';
1484 cchBuf--;
1485 }
1486 memcpy(pszBuf, s_aLogFlags[i].pszInstr, cchInstr);
1487 pszBuf += cchInstr;
1488 cchBuf -= cchInstr;
1489 fNotFirst = true;
1490 }
1491 *pszBuf = '\0';
1492 return rc;
1493}
1494RT_EXPORT_SYMBOL(RTLogGetFlags);
1495
1496
1497/**
1498 * Updates the logger desination using the specified string.
1499 *
1500 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
1501 * @param pLogger Logger instance (NULL for default logger).
1502 * @param pszVar The value to parse.
1503 */
1504RTDECL(int) RTLogDestinations(PRTLOGGER pLogger, char const *pszVar)
1505{
1506 /*
1507 * Resolve defaults.
1508 */
1509 if (!pLogger)
1510 {
1511 pLogger = RTLogDefaultInstance();
1512 if (!pLogger)
1513 return VINF_SUCCESS;
1514 }
1515
1516 /*
1517 * Do the parsing.
1518 */
1519 while (*pszVar)
1520 {
1521 bool fNo;
1522 unsigned i;
1523
1524 /* skip blanks. */
1525 while (RT_C_IS_SPACE(*pszVar))
1526 pszVar++;
1527 if (!*pszVar)
1528 break;
1529
1530 /* check no prefix. */
1531 fNo = false;
1532 if (pszVar[0] == 'n' && pszVar[1] == 'o')
1533 {
1534 fNo = true;
1535 pszVar += 2;
1536 }
1537
1538 /* instruction. */
1539 for (i = 0; i < RT_ELEMENTS(s_aLogDst); i++)
1540 {
1541 size_t cchInstr = strlen(s_aLogDst[i].pszInstr);
1542 if (!strncmp(pszVar, s_aLogDst[i].pszInstr, cchInstr))
1543 {
1544 if (!fNo)
1545 pLogger->fDestFlags |= s_aLogDst[i].fFlag;
1546 else
1547 pLogger->fDestFlags &= ~s_aLogDst[i].fFlag;
1548 pszVar += cchInstr;
1549
1550 /* check for value. */
1551 while (RT_C_IS_SPACE(*pszVar))
1552 pszVar++;
1553 if (*pszVar == '=' || *pszVar == ':')
1554 {
1555 const char *pszEnd;
1556
1557 pszVar++;
1558 pszEnd = strchr(pszVar, ';');
1559 if (!pszEnd)
1560 pszEnd = strchr(pszVar, '\0');
1561#ifndef IN_RING0
1562 size_t cch = pszEnd - pszVar;
1563
1564 /* log file name */
1565 if (i == 0 /* file */ && !fNo)
1566 {
1567 AssertReturn(cch < RTPATH_MAX, VERR_OUT_OF_RANGE);
1568 memcpy(pLogger->pszFilename, pszVar, cch);
1569 pLogger->pszFilename[cch] = '\0';
1570 }
1571 /* log directory */
1572 else if (i == 1 /* dir */ && !fNo)
1573 {
1574 char szTmp[RTPATH_MAX];
1575 const char *pszFile = RTPathFilename(pLogger->pszFilename);
1576 size_t cchFile = pszFile ? strlen(pszFile) : 0;
1577 AssertReturn(cchFile + cch + 1 < RTPATH_MAX, VERR_OUT_OF_RANGE);
1578 memcpy(szTmp, cchFile ? pszFile : "", cchFile + 1);
1579
1580 memcpy(pLogger->pszFilename, pszVar, cch);
1581 pLogger->pszFilename[cch] = '\0';
1582 RTPathStripTrailingSlash(pLogger->pszFilename);
1583
1584 cch = strlen(pLogger->pszFilename);
1585 pLogger->pszFilename[cch++] = '/';
1586 memcpy(&pLogger->pszFilename[cch], szTmp, cchFile);
1587 pLogger->pszFilename[cch+cchFile] = '\0';
1588 }
1589 else
1590 AssertMsgFailedReturn(("Invalid destination value! %s%s doesn't take a value!\n",
1591 fNo ? "no" : "", s_aLogDst[i].pszInstr),
1592 VERR_INVALID_PARAMETER);
1593#endif
1594 pszVar = pszEnd + (*pszEnd != '\0');
1595 }
1596 break;
1597 }
1598 }
1599
1600 /* assert known instruction */
1601 AssertMsgReturn(i < RT_ELEMENTS(s_aLogDst),
1602 ("Invalid destination value! unknown instruction %.20s\n", pszVar),
1603 VERR_INVALID_PARAMETER);
1604
1605 /* skip blanks and delimiters. */
1606 while (RT_C_IS_SPACE(*pszVar) || *pszVar == ';')
1607 pszVar++;
1608 } /* while more environment variable value left */
1609
1610 return VINF_SUCCESS;
1611}
1612RT_EXPORT_SYMBOL(RTLogDestinations);
1613
1614
1615/**
1616 * Get the current log destinations as a string.
1617 *
1618 * @returns VINF_SUCCESS or VERR_BUFFER_OVERFLOW.
1619 * @param pLogger Logger instance (NULL for default logger).
1620 * @param pszBuf The output buffer.
1621 * @param cchBuf The size of the output buffer. Must be greater
1622 * than 0.
1623 */
1624RTDECL(int) RTLogGetDestinations(PRTLOGGER pLogger, char *pszBuf, size_t cchBuf)
1625{
1626 bool fNotFirst = false;
1627 int rc = VINF_SUCCESS;
1628 uint32_t fDestFlags;
1629 unsigned i;
1630
1631 Assert(cchBuf);
1632
1633 /*
1634 * Resolve defaults.
1635 */
1636 if (!pLogger)
1637 {
1638 pLogger = RTLogDefaultInstance();
1639 if (!pLogger)
1640 {
1641 *pszBuf = '\0';
1642 return VINF_SUCCESS;
1643 }
1644 }
1645#define APPEND_PSZ(psz,cch) do { memcpy(pszBuf, (psz), (cch)); pszBuf += (cch); cchBuf -= (cch); } while (0)
1646#define APPEND_SZ(sz) APPEND_PSZ(sz, sizeof(sz) - 1)
1647#define APPEND_CH(ch) do { *pszBuf++ = (ch); cchBuf--; } while (0)
1648
1649 /*
1650 * Add the flags in the list.
1651 */
1652 fDestFlags = pLogger->fDestFlags;
1653 for (i = 2; i < RT_ELEMENTS(s_aLogDst); i++)
1654 if (s_aLogDst[i].fFlag & fDestFlags)
1655 {
1656 size_t cchInstr = s_aLogDst[i].cchInstr;
1657 if (cchInstr + fNotFirst + 1 > cchBuf)
1658 {
1659 rc = VERR_BUFFER_OVERFLOW;
1660 break;
1661 }
1662 if (fNotFirst)
1663 APPEND_CH(' ');
1664 fNotFirst = true;
1665 APPEND_PSZ(s_aLogDst[i].pszInstr, cchInstr);
1666 }
1667
1668 /*
1669 * Add the filename.
1670 */
1671 if ( (fDestFlags & RTLOGDEST_FILE)
1672 && VALID_PTR(pLogger->pszFilename)
1673 && RT_SUCCESS(rc))
1674 {
1675 size_t cchFilename = strlen(pLogger->pszFilename);
1676 if (cchFilename + sizeof("file=") - 1 + fNotFirst + 1 <= cchBuf)
1677 {
1678 if (fNotFirst)
1679 APPEND_SZ(" file=");
1680 else
1681 APPEND_SZ("file=");
1682 APPEND_PSZ(pLogger->pszFilename, cchFilename);
1683 }
1684 else
1685 rc = VERR_BUFFER_OVERFLOW;
1686 }
1687
1688#undef APPEND_PSZ
1689#undef APPEND_SZ
1690#undef APPEND_CH
1691
1692 *pszBuf = '\0';
1693 return rc;
1694}
1695RT_EXPORT_SYMBOL(RTLogGetDestinations);
1696#endif /* !IN_RC */
1697
1698
1699/**
1700 * Flushes the specified logger.
1701 *
1702 * @param pLogger The logger instance to flush.
1703 * If NULL the default instance is used. The default instance
1704 * will not be initialized by this call.
1705 */
1706RTDECL(void) RTLogFlush(PRTLOGGER pLogger)
1707{
1708 /*
1709 * Resolve defaults.
1710 */
1711 if (!pLogger)
1712 {
1713#ifdef IN_RC
1714 pLogger = &g_Logger;
1715#else
1716 pLogger = g_pLogger;
1717#endif
1718 if (!pLogger)
1719 return;
1720 }
1721
1722 /*
1723 * Any thing to flush?
1724 */
1725 if (pLogger->offScratch)
1726 {
1727#ifndef IN_RC
1728 /*
1729 * Acquire logger instance sem.
1730 */
1731 int rc = rtlogLock(pLogger);
1732 if (RT_FAILURE(rc))
1733 return;
1734#endif
1735 /*
1736 * Call worker.
1737 */
1738 rtlogFlush(pLogger);
1739
1740#ifndef IN_RC
1741 /*
1742 * Release the semaphore.
1743 */
1744 rtlogUnlock(pLogger);
1745#endif
1746 }
1747}
1748RT_EXPORT_SYMBOL(RTLogFlush);
1749
1750
1751/**
1752 * Gets the default logger instance, creating it if necessary.
1753 *
1754 * @returns Pointer to default logger instance.
1755 * @returns NULL if no default logger instance available.
1756 */
1757RTDECL(PRTLOGGER) RTLogDefaultInstance(void)
1758{
1759#ifdef IN_RC
1760 return &g_Logger;
1761
1762#else /* !IN_RC */
1763# ifdef IN_RING0
1764 /*
1765 * Check per thread loggers first.
1766 */
1767 if (g_cPerThreadLoggers)
1768 {
1769 const RTNATIVETHREAD Self = RTThreadNativeSelf();
1770 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
1771 while (i-- > 0)
1772 if (g_aPerThreadLoggers[i].NativeThread == Self)
1773 return g_aPerThreadLoggers[i].pLogger;
1774 }
1775# endif /* IN_RING0 */
1776
1777 /*
1778 * If no per thread logger, use the default one.
1779 */
1780 if (!g_pLogger)
1781 g_pLogger = RTLogDefaultInit();
1782 return g_pLogger;
1783#endif /* !IN_RC */
1784}
1785RT_EXPORT_SYMBOL(RTLogDefaultInstance);
1786
1787
1788/**
1789 * Gets the default logger instance.
1790 *
1791 * @returns Pointer to default logger instance.
1792 * @returns NULL if no default logger instance available.
1793 */
1794RTDECL(PRTLOGGER) RTLogGetDefaultInstance(void)
1795{
1796#ifdef IN_RC
1797 return &g_Logger;
1798#else
1799# ifdef IN_RING0
1800 /*
1801 * Check per thread loggers first.
1802 */
1803 if (g_cPerThreadLoggers)
1804 {
1805 const RTNATIVETHREAD Self = RTThreadNativeSelf();
1806 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
1807 while (i-- > 0)
1808 if (g_aPerThreadLoggers[i].NativeThread == Self)
1809 return g_aPerThreadLoggers[i].pLogger;
1810 }
1811# endif /* IN_RING0 */
1812
1813 return g_pLogger;
1814#endif
1815}
1816RT_EXPORT_SYMBOL(RTLogGetDefaultInstance);
1817
1818
1819#ifndef IN_RC
1820/**
1821 * Sets the default logger instance.
1822 *
1823 * @returns iprt status code.
1824 * @param pLogger The new default logger instance.
1825 */
1826RTDECL(PRTLOGGER) RTLogSetDefaultInstance(PRTLOGGER pLogger)
1827{
1828 return (PRTLOGGER)ASMAtomicXchgPtr((void * volatile *)&g_pLogger, pLogger);
1829}
1830RT_EXPORT_SYMBOL(RTLogSetDefaultInstance);
1831#endif /* !IN_RC */
1832
1833
1834#ifdef IN_RING0
1835/**
1836 * Changes the default logger instance for the current thread.
1837 *
1838 * @returns IPRT status code.
1839 * @param pLogger The logger instance. Pass NULL for deregistration.
1840 * @param uKey Associated key for cleanup purposes. If pLogger is NULL,
1841 * all instances with this key will be deregistered. So in
1842 * order to only deregister the instance associated with the
1843 * current thread use 0.
1844 */
1845RTDECL(int) RTLogSetDefaultInstanceThread(PRTLOGGER pLogger, uintptr_t uKey)
1846{
1847 int rc;
1848 RTNATIVETHREAD Self = RTThreadNativeSelf();
1849 if (pLogger)
1850 {
1851 int32_t i;
1852 unsigned j;
1853
1854 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
1855
1856 /*
1857 * Iterate the table to see if there is already an entry for this thread.
1858 */
1859 i = RT_ELEMENTS(g_aPerThreadLoggers);
1860 while (i-- > 0)
1861 if (g_aPerThreadLoggers[i].NativeThread == Self)
1862 {
1863 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, (void *)uKey);
1864 g_aPerThreadLoggers[i].pLogger = pLogger;
1865 return VINF_SUCCESS;
1866 }
1867
1868 /*
1869 * Allocate a new table entry.
1870 */
1871 i = ASMAtomicIncS32(&g_cPerThreadLoggers);
1872 if (i > (int32_t)RT_ELEMENTS(g_aPerThreadLoggers))
1873 {
1874 ASMAtomicDecS32(&g_cPerThreadLoggers);
1875 return VERR_BUFFER_OVERFLOW; /* horrible error code! */
1876 }
1877
1878 for (j = 0; j < 10; j++)
1879 {
1880 i = RT_ELEMENTS(g_aPerThreadLoggers);
1881 while (i-- > 0)
1882 {
1883 AssertCompile(sizeof(RTNATIVETHREAD) == sizeof(void*));
1884 if ( g_aPerThreadLoggers[i].NativeThread == NIL_RTNATIVETHREAD
1885 && ASMAtomicCmpXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].NativeThread, (void *)Self, (void *)NIL_RTNATIVETHREAD))
1886 {
1887 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, (void *)uKey);
1888 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].pLogger, pLogger);
1889 return VINF_SUCCESS;
1890 }
1891 }
1892 }
1893
1894 ASMAtomicDecS32(&g_cPerThreadLoggers);
1895 rc = VERR_INTERNAL_ERROR;
1896 }
1897 else
1898 {
1899 /*
1900 * Search the array for the current thread.
1901 */
1902 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
1903 while (i-- > 0)
1904 if ( g_aPerThreadLoggers[i].NativeThread == Self
1905 || g_aPerThreadLoggers[i].uKey == uKey)
1906 {
1907 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, NULL);
1908 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].pLogger, NULL);
1909 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].NativeThread, (void *)NIL_RTNATIVETHREAD);
1910 ASMAtomicDecS32(&g_cPerThreadLoggers);
1911 }
1912
1913 rc = VINF_SUCCESS;
1914 }
1915 return rc;
1916}
1917RT_EXPORT_SYMBOL(RTLogSetDefaultInstanceThread);
1918#endif
1919
1920
1921/**
1922 * Write to a logger instance.
1923 *
1924 * @param pLogger Pointer to logger instance.
1925 * @param pszFormat Format string.
1926 * @param args Format arguments.
1927 */
1928RTDECL(void) RTLogLoggerV(PRTLOGGER pLogger, const char *pszFormat, va_list args)
1929{
1930 RTLogLoggerExV(pLogger, 0, ~0U, pszFormat, args);
1931}
1932RT_EXPORT_SYMBOL(RTLogLoggerV);
1933
1934
1935/**
1936 * Write to a logger instance.
1937 *
1938 * This function will check whether the instance, group and flags makes up a
1939 * logging kind which is currently enabled before writing anything to the log.
1940 *
1941 * @param pLogger Pointer to logger instance. If NULL the default logger instance will be attempted.
1942 * @param fFlags The logging flags.
1943 * @param iGroup The group.
1944 * The value ~0U is reserved for compatability with RTLogLogger[V] and is
1945 * only for internal usage!
1946 * @param pszFormat Format string.
1947 * @param args Format arguments.
1948 */
1949RTDECL(void) RTLogLoggerExV(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args)
1950{
1951 int rc;
1952
1953 /*
1954 * A NULL logger means default instance.
1955 */
1956 if (!pLogger)
1957 {
1958 pLogger = RTLogDefaultInstance();
1959 if (!pLogger)
1960 return;
1961 }
1962
1963 /*
1964 * Validate and correct iGroup.
1965 */
1966 if (iGroup != ~0U && iGroup >= pLogger->cGroups)
1967 iGroup = 0;
1968
1969 /*
1970 * If no output, then just skip it.
1971 */
1972 if ( (pLogger->fFlags & RTLOGFLAGS_DISABLED)
1973#ifndef IN_RC
1974 || !pLogger->fDestFlags
1975#endif
1976 || !pszFormat || !*pszFormat)
1977 return;
1978 if ( iGroup != ~0U
1979 && (pLogger->afGroups[iGroup] & (fFlags | RTLOGGRPFLAGS_ENABLED)) != (fFlags | RTLOGGRPFLAGS_ENABLED))
1980 return;
1981
1982 /*
1983 * Acquire logger instance sem.
1984 */
1985 rc = rtlogLock(pLogger);
1986 if (RT_FAILURE(rc))
1987 {
1988#ifdef IN_RING0
1989 if (pLogger->fDestFlags & ~RTLOGDEST_FILE)
1990 rtR0LogLoggerExFallback(pLogger->fDestFlags, pLogger->fFlags, pszFormat, args);
1991#endif
1992 return;
1993 }
1994
1995 /*
1996 * Format the message and perhaps flush it.
1997 */
1998 if (pLogger->fFlags & (RTLOGFLAGS_PREFIX_MASK | RTLOGFLAGS_USECRLF))
1999 {
2000 RTLOGOUTPUTPREFIXEDARGS OutputArgs;
2001 OutputArgs.pLogger = pLogger;
2002 OutputArgs.iGroup = iGroup;
2003 OutputArgs.fFlags = fFlags;
2004 RTLogFormatV(rtLogOutputPrefixed, &OutputArgs, pszFormat, args);
2005 }
2006 else
2007 RTLogFormatV(rtLogOutput, pLogger, pszFormat, args);
2008 if ( !(pLogger->fFlags & RTLOGFLAGS_BUFFERED)
2009 && pLogger->offScratch)
2010 rtlogFlush(pLogger);
2011
2012 /*
2013 * Release the semaphore.
2014 */
2015 rtlogUnlock(pLogger);
2016}
2017RT_EXPORT_SYMBOL(RTLogLoggerExV);
2018
2019
2020#ifdef IN_RING0
2021/**
2022 * For rtR0LogLoggerExFallbackOutput and rtR0LogLoggerExFallbackFlush.
2023 */
2024typedef struct RTR0LOGLOGGERFALLBACK
2025{
2026 /** The current scratch buffer offset. */
2027 uint32_t offScratch;
2028 /** The destination flags. */
2029 uint32_t fDestFlags;
2030 /** The scratch buffer. */
2031 char achScratch[80];
2032} RTR0LOGLOGGERFALLBACK;
2033/** Pointer to RTR0LOGLOGGERFALLBACK which is used by
2034 * rtR0LogLoggerExFallbackOutput. */
2035typedef RTR0LOGLOGGERFALLBACK *PRTR0LOGLOGGERFALLBACK;
2036
2037
2038/**
2039 * Flushes the fallback buffer.
2040 *
2041 * @param pThis The scratch buffer.
2042 */
2043static void rtR0LogLoggerExFallbackFlush(PRTR0LOGLOGGERFALLBACK pThis)
2044{
2045 if (!pThis->offScratch)
2046 return;
2047
2048 if (pThis->fDestFlags & RTLOGDEST_USER)
2049 RTLogWriteUser(pThis->achScratch, pThis->offScratch);
2050
2051 if (pThis->fDestFlags & RTLOGDEST_DEBUGGER)
2052 RTLogWriteDebugger(pThis->achScratch, pThis->offScratch);
2053
2054 if (pThis->fDestFlags & RTLOGDEST_STDOUT)
2055 RTLogWriteStdOut(pThis->achScratch, pThis->offScratch);
2056
2057 if (pThis->fDestFlags & RTLOGDEST_STDERR)
2058 RTLogWriteStdErr(pThis->achScratch, pThis->offScratch);
2059
2060#ifndef LOG_NO_COM
2061 if (pThis->fDestFlags & RTLOGDEST_COM)
2062 RTLogWriteCom(pThis->achScratch, pThis->offScratch);
2063#endif
2064
2065 /* empty the buffer. */
2066 pThis->offScratch = 0;
2067}
2068
2069
2070/**
2071 * Callback for RTLogFormatV used by rtR0LogLoggerExFallback.
2072 * See PFNLOGOUTPUT() for details.
2073 */
2074static DECLCALLBACK(size_t) rtR0LogLoggerExFallbackOutput(void *pv, const char *pachChars, size_t cbChars)
2075{
2076 PRTR0LOGLOGGERFALLBACK pThis = (PRTR0LOGLOGGERFALLBACK)pv;
2077 if (cbChars)
2078 {
2079 size_t cbRet = 0;
2080 for (;;)
2081 {
2082 /* how much */
2083 uint32_t cb = sizeof(pThis->achScratch) - pThis->offScratch - 1; /* minus 1 - for the string terminator. */
2084 if (cb > cbChars)
2085 cb = (uint32_t)cbChars;
2086
2087 /* copy */
2088 memcpy(&pThis->achScratch[pThis->offScratch], pachChars, cb);
2089
2090 /* advance */
2091 pThis->offScratch += cb;
2092 cbRet += cb;
2093 cbChars -= cb;
2094
2095 /* done? */
2096 if (cbChars <= 0)
2097 return cbRet;
2098
2099 pachChars += cb;
2100
2101 /* flush */
2102 pThis->achScratch[pThis->offScratch] = '\0';
2103 rtR0LogLoggerExFallbackFlush(pThis);
2104 }
2105
2106 /* won't ever get here! */
2107 }
2108 else
2109 {
2110 /*
2111 * Termination call, flush the log.
2112 */
2113 pThis->achScratch[pThis->offScratch] = '\0';
2114 rtR0LogLoggerExFallbackFlush(pThis);
2115 return 0;
2116 }
2117}
2118
2119
2120/**
2121 * Ring-0 fallback for cases where we're unable to grab the lock.
2122 *
2123 * This will happen when we're at a too high IRQL on Windows for instance and
2124 * needs to be dealt with or we'll drop a lot of log output. This fallback will
2125 * only output to some of the log destinations as a few of them may be doing
2126 * dangerouse things. We won't be doing any prefixing here either, at least not
2127 * for the present, because it's too much hazzle.
2128 *
2129 * @param fDestFlags The destination flags.
2130 * @param fFlags The logger flags.
2131 * @param pszFormat The format string.
2132 * @param va The format arguments.
2133 */
2134static void rtR0LogLoggerExFallback(uint32_t fDestFlags, uint32_t fFlags, const char *pszFormat, va_list va)
2135{
2136 RTR0LOGLOGGERFALLBACK This;
2137 This.fDestFlags = fDestFlags;
2138
2139 /* fallback indicator. */
2140 This.offScratch = 2;
2141 This.achScratch[0] = '[';
2142 This.achScratch[1] = 'F';
2143
2144 /* selected prefixes */
2145 if (fFlags & RTLOGFLAGS_PREFIX_PID)
2146 {
2147 RTPROCESS Process = RTProcSelf();
2148 This.achScratch[This.offScratch++] = ' ';
2149 This.offScratch += RTStrFormatNumber(&This.achScratch[This.offScratch], Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
2150 }
2151 if (fFlags & RTLOGFLAGS_PREFIX_TID)
2152 {
2153 RTNATIVETHREAD Thread = RTThreadNativeSelf();
2154 This.achScratch[This.offScratch++] = ' ';
2155 This.offScratch += RTStrFormatNumber(&This.achScratch[This.offScratch], Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
2156 }
2157
2158 This.achScratch[This.offScratch++] = ']';
2159 This.achScratch[This.offScratch++] = ' ';
2160
2161 RTLogFormatV(rtR0LogLoggerExFallbackOutput, &This, pszFormat, va);
2162}
2163#endif /* IN_RING0 */
2164
2165
2166/**
2167 * vprintf like function for writing to the default log.
2168 *
2169 * @param pszFormat Printf like format string.
2170 * @param args Optional arguments as specified in pszFormat.
2171 *
2172 * @remark The API doesn't support formatting of floating point numbers at the moment.
2173 */
2174RTDECL(void) RTLogPrintfV(const char *pszFormat, va_list args)
2175{
2176 RTLogLoggerV(NULL, pszFormat, args);
2177}
2178RT_EXPORT_SYMBOL(RTLogPrintfV);
2179
2180
2181/**
2182 * Writes the buffer to the given log device without checking for buffered
2183 * data or anything.
2184 * Used by the RTLogFlush() function.
2185 *
2186 * @param pLogger The logger instance to write to. NULL is not allowed!
2187 */
2188static void rtlogFlush(PRTLOGGER pLogger)
2189{
2190#ifndef IN_RC
2191 if (pLogger->fDestFlags & RTLOGDEST_USER)
2192 RTLogWriteUser(pLogger->achScratch, pLogger->offScratch);
2193
2194 if (pLogger->fDestFlags & RTLOGDEST_DEBUGGER)
2195 RTLogWriteDebugger(pLogger->achScratch, pLogger->offScratch);
2196
2197# ifdef IN_RING3
2198 if (pLogger->fDestFlags & RTLOGDEST_FILE)
2199 RTFileWrite(pLogger->File, pLogger->achScratch, pLogger->offScratch, NULL);
2200# endif
2201
2202 if (pLogger->fDestFlags & RTLOGDEST_STDOUT)
2203 RTLogWriteStdOut(pLogger->achScratch, pLogger->offScratch);
2204
2205 if (pLogger->fDestFlags & RTLOGDEST_STDERR)
2206 RTLogWriteStdErr(pLogger->achScratch, pLogger->offScratch);
2207
2208# if (defined(IN_RING0) || defined(IN_RC)) && !defined(LOG_NO_COM)
2209 if (pLogger->fDestFlags & RTLOGDEST_COM)
2210 RTLogWriteCom(pLogger->achScratch, pLogger->offScratch);
2211# endif
2212#endif /* !IN_RC */
2213
2214 if (pLogger->pfnFlush)
2215 pLogger->pfnFlush(pLogger);
2216
2217 /* empty the buffer. */
2218 pLogger->offScratch = 0;
2219}
2220
2221
2222/**
2223 * Callback for RTLogFormatV which writes to the com port.
2224 * See PFNLOGOUTPUT() for details.
2225 */
2226static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
2227{
2228 PRTLOGGER pLogger = (PRTLOGGER)pv;
2229 if (cbChars)
2230 {
2231 size_t cbRet = 0;
2232 for (;;)
2233 {
2234#if defined(DEBUG) && defined(IN_RING3)
2235 /* sanity */
2236 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
2237 {
2238 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
2239 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
2240 AssertBreakpoint(); AssertBreakpoint();
2241 }
2242#endif
2243
2244 /* how much */
2245 size_t cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
2246 if (cb > cbChars)
2247 cb = cbChars;
2248
2249 /* copy */
2250 memcpy(&pLogger->achScratch[pLogger->offScratch], pachChars, cb);
2251
2252 /* advance */
2253 pLogger->offScratch += (uint32_t)cb;
2254 cbRet += cb;
2255 cbChars -= cb;
2256
2257 /* done? */
2258 if (cbChars <= 0)
2259 return cbRet;
2260
2261 pachChars += cb;
2262
2263 /* flush */
2264 rtlogFlush(pLogger);
2265 }
2266
2267 /* won't ever get here! */
2268 }
2269 else
2270 {
2271 /*
2272 * Termination call.
2273 * There's always space for a terminator, and it's not counted.
2274 */
2275 pLogger->achScratch[pLogger->offScratch] = '\0';
2276 return 0;
2277 }
2278}
2279
2280
2281
2282/**
2283 * Callback for RTLogFormatV which writes to the logger instance.
2284 * This version supports prefixes.
2285 *
2286 * See PFNLOGOUTPUT() for details.
2287 */
2288static DECLCALLBACK(size_t) rtLogOutputPrefixed(void *pv, const char *pachChars, size_t cbChars)
2289{
2290 PRTLOGOUTPUTPREFIXEDARGS pArgs = (PRTLOGOUTPUTPREFIXEDARGS)pv;
2291 PRTLOGGER pLogger = pArgs->pLogger;
2292 if (cbChars)
2293 {
2294 size_t cbRet = 0;
2295 for (;;)
2296 {
2297 size_t cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
2298 char *psz;
2299 const char *pszNewLine;
2300
2301 /*
2302 * Pending prefix?
2303 */
2304 if (pLogger->fPendingPrefix)
2305 {
2306 pLogger->fPendingPrefix = false;
2307
2308#if defined(DEBUG) && defined(IN_RING3)
2309 /* sanity */
2310 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
2311 {
2312 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
2313 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
2314 AssertBreakpoint(); AssertBreakpoint();
2315 }
2316#endif
2317
2318 /*
2319 * Flush the buffer if there isn't enough room for the maximum prefix config.
2320 * Max is 256, add a couple of extra bytes.
2321 */
2322 if (cb < 256 + 16)
2323 {
2324 rtlogFlush(pLogger);
2325 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
2326 }
2327
2328 /*
2329 * Write the prefixes.
2330 * psz is pointing to the current position.
2331 */
2332 psz = &pLogger->achScratch[pLogger->offScratch];
2333 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TS)
2334 {
2335#if defined(IN_RING3) || defined(IN_RC)
2336 uint64_t u64 = RTTimeNanoTS();
2337#else
2338 uint64_t u64 = ~0;
2339#endif
2340 int iBase = 16;
2341 unsigned int fFlags = RTSTR_F_ZEROPAD;
2342 if (pLogger->fFlags & RTLOGFLAGS_DECIMAL_TS)
2343 {
2344 iBase = 10;
2345 fFlags = 0;
2346 }
2347 if (pLogger->fFlags & RTLOGFLAGS_REL_TS)
2348 {
2349 static volatile uint64_t s_u64LastTs;
2350 uint64_t u64DiffTs = u64 - s_u64LastTs;
2351 s_u64LastTs = u64;
2352 /* We could have been preempted just before reading of s_u64LastTs by
2353 * another thread which wrote s_u64LastTs. In that case the difference
2354 * is negative which we simply ignore. */
2355 u64 = (int64_t)u64DiffTs < 0 ? 0 : u64DiffTs;
2356 }
2357 /* 1E15 nanoseconds = 11 days */
2358 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags); /* +17 */
2359 *psz++ = ' ';
2360 }
2361 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TSC)
2362 {
2363 uint64_t u64 = ASMReadTSC();
2364 int iBase = 16;
2365 unsigned int fFlags = RTSTR_F_ZEROPAD;
2366 if (pLogger->fFlags & RTLOGFLAGS_DECIMAL_TS)
2367 {
2368 iBase = 10;
2369 fFlags = 0;
2370 }
2371 if (pLogger->fFlags & RTLOGFLAGS_REL_TS)
2372 {
2373 static volatile uint64_t s_u64LastTsc;
2374 int64_t i64DiffTsc = u64 - s_u64LastTsc;
2375 s_u64LastTsc = u64;
2376 /* We could have been preempted just before reading of s_u64LastTsc by
2377 * another thread which wrote s_u64LastTsc. In that case the difference
2378 * is negative which we simply ignore. */
2379 u64 = i64DiffTsc < 0 ? 0 : i64DiffTsc;
2380 }
2381 /* 1E15 ticks at 4GHz = 69 hours */
2382 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags); /* +17 */
2383 *psz++ = ' ';
2384 }
2385 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_MS_PROG)
2386 {
2387#if defined(IN_RING3) || defined(IN_RC)
2388 uint64_t u64 = RTTimeProgramMilliTS();
2389#else
2390 uint64_t u64 = 0;
2391#endif
2392 /* 1E8 milliseconds = 27 hours */
2393 psz += RTStrFormatNumber(psz, u64, 10, 9, 0, RTSTR_F_ZEROPAD);
2394 *psz++ = ' ';
2395 }
2396 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TIME)
2397 {
2398#ifdef IN_RING3
2399 RTTIMESPEC TimeSpec;
2400 RTTIME Time;
2401 RTTimeExplode(&Time, RTTimeNow(&TimeSpec));
2402 psz += RTStrFormatNumber(psz, Time.u8Hour, 10, 2, 0, RTSTR_F_ZEROPAD);
2403 *psz++ = ':';
2404 psz += RTStrFormatNumber(psz, Time.u8Minute, 10, 2, 0, RTSTR_F_ZEROPAD);
2405 *psz++ = ':';
2406 psz += RTStrFormatNumber(psz, Time.u8Second, 10, 2, 0, RTSTR_F_ZEROPAD);
2407 *psz++ = '.';
2408 psz += RTStrFormatNumber(psz, Time.u32Nanosecond / 1000000, 10, 3, 0, RTSTR_F_ZEROPAD);
2409 *psz++ = ' '; /* +17 (3+1+3+1+3+1+4+1) */
2410#else
2411 memset(psz, ' ', 13);
2412 psz += 13;
2413#endif
2414 }
2415 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TIME_PROG)
2416 {
2417#ifdef IN_RING3
2418 uint64_t u64 = RTTimeProgramMilliTS();
2419 psz += RTStrFormatNumber(psz, (uint32_t)(u64 / (60 * 60 * 1000)), 10, 2, 0, RTSTR_F_ZEROPAD);
2420 *psz++ = ':';
2421 uint32_t u32 = (uint32_t)(u64 % (60 * 60 * 1000));
2422 psz += RTStrFormatNumber(psz, u32 / (60 * 1000), 10, 2, 0, RTSTR_F_ZEROPAD);
2423 *psz++ = ':';
2424 u32 %= 60 * 1000;
2425 psz += RTStrFormatNumber(psz, u32 / 1000, 10, 2, 0, RTSTR_F_ZEROPAD);
2426 *psz++ = '.';
2427 psz += RTStrFormatNumber(psz, u32 % 1000, 10, 3, 0, RTSTR_F_ZEROPAD);
2428 *psz++ = ' '; /* +20 (9+1+2+1+2+1+3+1) */
2429#else
2430 memset(psz, ' ', 13);
2431 psz += 13;
2432#endif
2433 }
2434# if 0
2435 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_DATETIME)
2436 {
2437 char szDate[32];
2438 RTTIMESPEC Time;
2439 RTTimeSpecToString(RTTimeNow(&Time), szDate, sizeof(szDate));
2440 size_t cch = strlen(szDate);
2441 memcpy(psz, szDate, cch);
2442 psz += cch;
2443 *psz++ = ' '; /* +32 */
2444 }
2445# endif
2446 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_PID)
2447 {
2448#ifndef IN_RC
2449 RTPROCESS Process = RTProcSelf();
2450#else
2451 RTPROCESS Process = NIL_RTPROCESS;
2452#endif
2453 psz += RTStrFormatNumber(psz, Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
2454 *psz++ = ' '; /* +9 */
2455 }
2456 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TID)
2457 {
2458#ifndef IN_RC
2459 RTNATIVETHREAD Thread = RTThreadNativeSelf();
2460#else
2461 RTNATIVETHREAD Thread = NIL_RTNATIVETHREAD;
2462#endif
2463 psz += RTStrFormatNumber(psz, Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
2464 *psz++ = ' '; /* +17 */
2465 }
2466 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_THREAD)
2467 {
2468#ifdef IN_RING3
2469 const char *pszName = RTThreadSelfName();
2470#elif defined IN_RC
2471 const char *pszName = "EMT-RC";
2472#else
2473 const char *pszName = "R0";
2474#endif
2475 size_t cch = 0;
2476 if (pszName)
2477 {
2478 cch = strlen(pszName);
2479 cch = RT_MIN(cch, 16);
2480 memcpy(psz, pszName, cch);
2481 psz += cch;
2482 }
2483 do
2484 *psz++ = ' ';
2485 while (cch++ < 8); /* +17 */
2486 }
2487 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_CPUID)
2488 {
2489#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
2490 const uint8_t idCpu = ASMGetApicId();
2491#else
2492 const RTCPUID idCpu = RTMpCpuId();
2493#endif
2494 psz += RTStrFormatNumber(psz, idCpu, 16, sizeof(idCpu) * 2, 0, RTSTR_F_ZEROPAD);
2495 *psz++ = ' '; /* +17 */
2496 }
2497#ifndef IN_RC
2498 if ( (pLogger->fFlags & RTLOGFLAGS_PREFIX_CUSTOM)
2499 && pLogger->pfnPrefix)
2500 {
2501 psz += pLogger->pfnPrefix(pLogger, psz, 31, pLogger->pvPrefixUserArg);
2502 *psz++ = ' '; /* +32 */
2503 }
2504#endif
2505 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_LOCK_COUNTS)
2506 {
2507#ifdef IN_RING3 /** @todo implement these counters in ring-0 too? */
2508 RTTHREAD Thread = RTThreadSelf();
2509 if (Thread != NIL_RTTHREAD)
2510 {
2511 uint32_t cReadLocks = RTThreadGetReadLockCount(Thread);
2512 uint32_t cWriteLocks = RTThreadGetWriteLockCount(Thread) - g_cLoggerLockCount;
2513 cReadLocks = RT_MIN(0xfff, cReadLocks);
2514 cWriteLocks = RT_MIN(0xfff, cWriteLocks);
2515 psz += RTStrFormatNumber(psz, cReadLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
2516 *psz++ = '/';
2517 psz += RTStrFormatNumber(psz, cWriteLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
2518 }
2519 else
2520#endif
2521 {
2522 *psz++ = '?';
2523 *psz++ = '/';
2524 *psz++ = '?';
2525 }
2526 *psz++ = ' '; /* +8 */
2527 }
2528 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_FLAG_NO)
2529 {
2530 psz += RTStrFormatNumber(psz, pArgs->fFlags, 16, 8, 0, RTSTR_F_ZEROPAD);
2531 *psz++ = ' '; /* +9 */
2532 }
2533 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_FLAG)
2534 {
2535#ifdef IN_RING3
2536 const char *pszGroup = pArgs->iGroup != ~0U ? pLogger->papszGroups[pArgs->iGroup] : NULL;
2537#else
2538 const char *pszGroup = NULL;
2539#endif
2540 size_t cch = 0;
2541 if (pszGroup)
2542 {
2543 cch = strlen(pszGroup);
2544 cch = RT_MIN(cch, 16);
2545 memcpy(psz, pszGroup, cch);
2546 psz += cch;
2547 }
2548 do
2549 *psz++ = ' ';
2550 while (cch++ < 8); /* +17 */
2551 }
2552 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_GROUP_NO)
2553 {
2554 if (pArgs->iGroup != ~0U)
2555 {
2556 psz += RTStrFormatNumber(psz, pArgs->iGroup, 16, 3, 0, RTSTR_F_ZEROPAD);
2557 *psz++ = ' ';
2558 }
2559 else
2560 {
2561 memcpy(psz, "-1 ", sizeof("-1 ") - 1);
2562 psz += sizeof("-1 ") - 1;
2563 } /* +9 */
2564 }
2565 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_GROUP)
2566 {
2567 const unsigned fGrp = pLogger->afGroups[pArgs->iGroup != ~0U ? pArgs->iGroup : 0];
2568 const char *pszGroup;
2569 size_t cch;
2570 switch (pArgs->fFlags & fGrp)
2571 {
2572 case 0: pszGroup = "--------"; cch = sizeof("--------") - 1; break;
2573 case RTLOGGRPFLAGS_ENABLED: pszGroup = "enabled" ; cch = sizeof("enabled" ) - 1; break;
2574 case RTLOGGRPFLAGS_LEVEL_1: pszGroup = "level 1" ; cch = sizeof("level 1" ) - 1; break;
2575 case RTLOGGRPFLAGS_LEVEL_2: pszGroup = "level 2" ; cch = sizeof("level 2" ) - 1; break;
2576 case RTLOGGRPFLAGS_LEVEL_3: pszGroup = "level 3" ; cch = sizeof("level 3" ) - 1; break;
2577 case RTLOGGRPFLAGS_LEVEL_4: pszGroup = "level 4" ; cch = sizeof("level 4" ) - 1; break;
2578 case RTLOGGRPFLAGS_LEVEL_5: pszGroup = "level 5" ; cch = sizeof("level 5" ) - 1; break;
2579 case RTLOGGRPFLAGS_LEVEL_6: pszGroup = "level 6" ; cch = sizeof("level 6" ) - 1; break;
2580 case RTLOGGRPFLAGS_FLOW: pszGroup = "flow" ; cch = sizeof("flow" ) - 1; break;
2581
2582 /* personal groups */
2583 case RTLOGGRPFLAGS_LELIK: pszGroup = "lelik" ; cch = sizeof("lelik" ) - 1; break;
2584 case RTLOGGRPFLAGS_MICHAEL: pszGroup = "Michael" ; cch = sizeof("Michael" ) - 1; break;
2585 case RTLOGGRPFLAGS_DMIK: pszGroup = "dmik" ; cch = sizeof("dmik" ) - 1; break;
2586 case RTLOGGRPFLAGS_SUNLOVER: pszGroup = "sunlover"; cch = sizeof("sunlover") - 1; break;
2587 case RTLOGGRPFLAGS_ACHIM: pszGroup = "Achim" ; cch = sizeof("Achim" ) - 1; break;
2588 case RTLOGGRPFLAGS_SANDER: pszGroup = "Sander" ; cch = sizeof("Sander" ) - 1; break;
2589 case RTLOGGRPFLAGS_KLAUS: pszGroup = "Klaus" ; cch = sizeof("Klaus" ) - 1; break;
2590 case RTLOGGRPFLAGS_FRANK: pszGroup = "Frank" ; cch = sizeof("Frank" ) - 1; break;
2591 case RTLOGGRPFLAGS_BIRD: pszGroup = "bird" ; cch = sizeof("bird" ) - 1; break;
2592 case RTLOGGRPFLAGS_NONAME: pszGroup = "noname" ; cch = sizeof("noname" ) - 1; break;
2593 default: pszGroup = "????????"; cch = sizeof("????????") - 1; break;
2594 }
2595 if (pszGroup)
2596 {
2597 cch = RT_MIN(cch, 16);
2598 memcpy(psz, pszGroup, cch);
2599 psz += cch;
2600 }
2601 do
2602 *psz++ = ' ';
2603 while (cch++ < 8); /* +17 */
2604 }
2605
2606 /*
2607 * Done, figure what we've used and advance the buffer and free size.
2608 */
2609 cb = psz - &pLogger->achScratch[pLogger->offScratch];
2610 Assert(cb <= 198);
2611 pLogger->offScratch += (uint32_t)cb;
2612 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
2613 }
2614 else if (cb <= 0)
2615 {
2616 rtlogFlush(pLogger);
2617 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
2618 }
2619
2620#if defined(DEBUG) && defined(IN_RING3)
2621 /* sanity */
2622 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
2623 {
2624 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
2625 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
2626 AssertBreakpoint(); AssertBreakpoint();
2627 }
2628#endif
2629
2630 /* how much */
2631 if (cb > cbChars)
2632 cb = cbChars;
2633
2634 /* have newline? */
2635 pszNewLine = (const char *)memchr(pachChars, '\n', cb);
2636 if (pszNewLine)
2637 {
2638 if (pLogger->fFlags & RTLOGFLAGS_USECRLF)
2639 cb = pszNewLine - pachChars;
2640 else
2641 {
2642 cb = pszNewLine - pachChars + 1;
2643 pLogger->fPendingPrefix = true;
2644 }
2645 }
2646
2647 /* copy */
2648 memcpy(&pLogger->achScratch[pLogger->offScratch], pachChars, cb);
2649
2650 /* advance */
2651 pLogger->offScratch += (uint32_t)cb;
2652 cbRet += cb;
2653 cbChars -= cb;
2654
2655 if ( pszNewLine
2656 && (pLogger->fFlags & RTLOGFLAGS_USECRLF)
2657 && pLogger->offScratch + 2 < sizeof(pLogger->achScratch))
2658 {
2659 memcpy(&pLogger->achScratch[pLogger->offScratch], "\r\n", 2);
2660 pLogger->offScratch += 2;
2661 cbRet++;
2662 cbChars--;
2663 cb++;
2664 pLogger->fPendingPrefix = true;
2665 }
2666
2667 /* done? */
2668 if (cbChars <= 0)
2669 return cbRet;
2670 pachChars += cb;
2671 }
2672
2673 /* won't ever get here! */
2674 }
2675 else
2676 {
2677 /*
2678 * Termination call.
2679 * There's always space for a terminator, and it's not counted.
2680 */
2681 pLogger->achScratch[pLogger->offScratch] = '\0';
2682 return 0;
2683 }
2684}
2685
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