VirtualBox

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

Last change on this file since 13255 was 13255, checked in by vboxsync, 16 years ago

build fix (log.cpp).

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