VirtualBox

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

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

IPRT: Added custom prefix callback to the logger.

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