VirtualBox

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

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

getenv -> RTEnvGet.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 77.4 KB
Line 
1/* $Id: log.cpp 20819 2009-06-23 12:15:07Z 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 * Matches a group name with a pattern mask in an case insensitive manner (ASCII).
940 *
941 * @returns true if matching and *ppachMask set to the end of the pattern.
942 * @returns false if no match.
943 * @param pszGrp The group name.
944 * @param ppachMask Pointer to the pointer to the mask. Only wildcard supported is '*'.
945 * @param cchMask The length of the mask, including modifiers. The modifiers is why
946 * we update *ppachMask on match.
947 */
948static bool rtlogIsGroupMatching(const char *pszGrp, const char **ppachMask, size_t cchMask)
949{
950 const char *pachMask;
951
952 if (!pszGrp || !*pszGrp)
953 return false;
954 pachMask = *ppachMask;
955 for (;;)
956 {
957 if (RT_C_TO_LOWER(*pszGrp) != RT_C_TO_LOWER(*pachMask))
958 {
959 const char *pszTmp;
960
961 /*
962 * Check for wildcard and do a minimal match if found.
963 */
964 if (*pachMask != '*')
965 return false;
966
967 /* eat '*'s. */
968 do pachMask++;
969 while (--cchMask && *pachMask == '*');
970
971 /* is there more to match? */
972 if ( !cchMask
973 || *pachMask == '.'
974 || *pachMask == '=')
975 break; /* we're good */
976
977 /* do extremely minimal matching (fixme) */
978 pszTmp = strchr(pszGrp, RT_C_TO_LOWER(*pachMask));
979 if (!pszTmp)
980 pszTmp = strchr(pszGrp, RT_C_TO_UPPER(*pachMask));
981 if (!pszTmp)
982 return false;
983 pszGrp = pszTmp;
984 continue;
985 }
986
987 /* done? */
988 if (!*++pszGrp)
989 {
990 /* trailing wildcard is ok. */
991 do
992 {
993 pachMask++;
994 cchMask--;
995 } while (cchMask && *pachMask == '*');
996 if ( !cchMask
997 || *pachMask == '.'
998 || *pachMask == '=')
999 break; /* we're good */
1000 return false;
1001 }
1002
1003 if (!--cchMask)
1004 return false;
1005 pachMask++;
1006 }
1007
1008 /* match */
1009 *ppachMask = pachMask;
1010 return true;
1011}
1012
1013
1014/**
1015 * Updates the group settings for the logger instance using the specified
1016 * specification string.
1017 *
1018 * @returns iprt status code.
1019 * Failures can safely be ignored.
1020 * @param pLogger Logger instance.
1021 * @param pszVar Value to parse.
1022 */
1023RTDECL(int) RTLogGroupSettings(PRTLOGGER pLogger, const char *pszVar)
1024{
1025 /*
1026 * Resolve defaults.
1027 */
1028 if (!pLogger)
1029 {
1030 pLogger = RTLogDefaultInstance();
1031 if (!pLogger)
1032 return VINF_SUCCESS;
1033 }
1034
1035 /*
1036 * Iterate the string.
1037 */
1038 while (*pszVar)
1039 {
1040 /*
1041 * Skip prefixes (blanks, ;, + and -).
1042 */
1043 bool fEnabled = true;
1044 char ch;
1045 const char *pszStart;
1046 unsigned i;
1047 size_t cch;
1048
1049 while ((ch = *pszVar) == '+' || ch == '-' || ch == ' ' || ch == '\t' || ch == '\n' || ch == ';')
1050 {
1051 if (ch == '+' || ch == '-' || ';')
1052 fEnabled = ch != '-';
1053 pszVar++;
1054 }
1055 if (!*pszVar)
1056 break;
1057
1058 /*
1059 * Find end.
1060 */
1061 pszStart = pszVar;
1062 while ((ch = *pszVar) != '\0' && ch != '+' && ch != '-' && ch != ' ' && ch != '\t')
1063 pszVar++;
1064
1065 /*
1066 * Find the group (ascii case insensitive search).
1067 * Special group 'all'.
1068 */
1069 cch = pszVar - pszStart;
1070 if ( cch >= 3
1071 && (pszStart[0] == 'a' || pszStart[0] == 'A')
1072 && (pszStart[1] == 'l' || pszStart[1] == 'L')
1073 && (pszStart[2] == 'l' || pszStart[2] == 'L')
1074 && (cch == 3 || pszStart[3] == '.' || pszStart[3] == '='))
1075 {
1076 /*
1077 * All.
1078 */
1079 unsigned fFlags = cch == 3
1080 ? RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1
1081 : rtlogGroupFlags(&pszStart[3]);
1082 for (i = 0; i < pLogger->cGroups; i++)
1083 {
1084 if (fEnabled)
1085 pLogger->afGroups[i] |= fFlags;
1086 else
1087 pLogger->afGroups[i] &= ~fFlags;
1088 }
1089 }
1090 else
1091 {
1092 /*
1093 * Specific group(s).
1094 */
1095 for (i = 0; i < pLogger->cGroups; i++)
1096 {
1097 const char *psz2 = (const char*)pszStart;
1098 if (rtlogIsGroupMatching(pLogger->papszGroups[i], &psz2, cch))
1099 {
1100 unsigned fFlags = RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1;
1101 if (*psz2 == '.' || *psz2 == '=')
1102 fFlags = rtlogGroupFlags(psz2);
1103 if (fEnabled)
1104 pLogger->afGroups[i] |= fFlags;
1105 else
1106 pLogger->afGroups[i] &= ~fFlags;
1107 }
1108 } /* for each group */
1109 }
1110
1111 } /* parse specification */
1112
1113 return VINF_SUCCESS;
1114}
1115
1116
1117/**
1118 * Interprets the group flags suffix.
1119 *
1120 * @returns Flags specified. (0 is possible!)
1121 * @param psz Start of Suffix. (Either dot or equal sign.)
1122 */
1123static unsigned rtlogGroupFlags(const char *psz)
1124{
1125 unsigned fFlags = 0;
1126
1127 /*
1128 * Litteral flags.
1129 */
1130 while (*psz == '.')
1131 {
1132 static struct
1133 {
1134 const char *pszFlag; /* lowercase!! */
1135 unsigned fFlag;
1136 } aFlags[] =
1137 {
1138 { "eo", RTLOGGRPFLAGS_ENABLED },
1139 { "enabledonly",RTLOGGRPFLAGS_ENABLED },
1140 { "e", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 },
1141 { "enabled", RTLOGGRPFLAGS_ENABLED | RTLOGGRPFLAGS_LEVEL_1 },
1142 { "l1", RTLOGGRPFLAGS_LEVEL_1 },
1143 { "level1", RTLOGGRPFLAGS_LEVEL_1 },
1144 { "l", RTLOGGRPFLAGS_LEVEL_2 },
1145 { "l2", RTLOGGRPFLAGS_LEVEL_2 },
1146 { "level2", RTLOGGRPFLAGS_LEVEL_2 },
1147 { "l3", RTLOGGRPFLAGS_LEVEL_3 },
1148 { "level3", RTLOGGRPFLAGS_LEVEL_3 },
1149 { "l4", RTLOGGRPFLAGS_LEVEL_4 },
1150 { "level4", RTLOGGRPFLAGS_LEVEL_4 },
1151 { "l5", RTLOGGRPFLAGS_LEVEL_5 },
1152 { "level5", RTLOGGRPFLAGS_LEVEL_5 },
1153 { "l6", RTLOGGRPFLAGS_LEVEL_6 },
1154 { "level6", RTLOGGRPFLAGS_LEVEL_6 },
1155 { "f", RTLOGGRPFLAGS_FLOW },
1156 { "flow", RTLOGGRPFLAGS_FLOW },
1157
1158 { "lelik", RTLOGGRPFLAGS_LELIK },
1159 { "michael", RTLOGGRPFLAGS_MICHAEL },
1160 { "dmik", RTLOGGRPFLAGS_DMIK },
1161 { "sunlover", RTLOGGRPFLAGS_SUNLOVER },
1162 { "achim", RTLOGGRPFLAGS_ACHIM },
1163 { "achimha", RTLOGGRPFLAGS_ACHIM },
1164 { "s", RTLOGGRPFLAGS_SANDER },
1165 { "sander", RTLOGGRPFLAGS_SANDER },
1166 { "sandervl", RTLOGGRPFLAGS_SANDER },
1167 { "klaus", RTLOGGRPFLAGS_KLAUS },
1168 { "frank", RTLOGGRPFLAGS_FRANK },
1169 { "b", RTLOGGRPFLAGS_BIRD },
1170 { "bird", RTLOGGRPFLAGS_BIRD },
1171 { "aleksey", RTLOGGRPFLAGS_ALEKSEY },
1172 { "n", RTLOGGRPFLAGS_NONAME },
1173 { "noname", RTLOGGRPFLAGS_NONAME }
1174 };
1175 unsigned i;
1176 bool fFound = false;
1177 psz++;
1178 for (i = 0; i < RT_ELEMENTS(aFlags) && !fFound; i++)
1179 {
1180 const char *psz1 = aFlags[i].pszFlag;
1181 const char *psz2 = psz;
1182 while (*psz1 == RT_C_TO_LOWER(*psz2))
1183 {
1184 psz1++;
1185 psz2++;
1186 if (!*psz1)
1187 {
1188 if ( (*psz2 >= 'a' && *psz2 <= 'z')
1189 || (*psz2 >= 'A' && *psz2 <= 'Z')
1190 || (*psz2 >= '0' && *psz2 <= '9') )
1191 break;
1192 fFlags |= aFlags[i].fFlag;
1193 fFound = true;
1194 psz = psz2;
1195 break;
1196 }
1197 } /* strincmp */
1198 } /* for each flags */
1199 }
1200
1201 /*
1202 * Flag value.
1203 */
1204 if (*psz == '=')
1205 {
1206 psz++;
1207 if (*psz == '~')
1208 fFlags = ~RTStrToInt32(psz + 1);
1209 else
1210 fFlags = RTStrToInt32(psz);
1211 }
1212
1213 return fFlags;
1214}
1215
1216#endif /* !IN_RC */
1217
1218
1219/**
1220 * Updates the flags for the logger instance using the specified
1221 * specification string.
1222 *
1223 * @returns iprt status code.
1224 * Failures can safely be ignored.
1225 * @param pLogger Logger instance (NULL for default logger).
1226 * @param pszVar Value to parse.
1227 */
1228RTDECL(int) RTLogFlags(PRTLOGGER pLogger, const char *pszVar)
1229{
1230 int rc = VINF_SUCCESS;
1231
1232 /*
1233 * Resolve defaults.
1234 */
1235 if (!pLogger)
1236 {
1237 pLogger = RTLogDefaultInstance();
1238 if (!pLogger)
1239 return VINF_SUCCESS;
1240 }
1241
1242 /*
1243 * Iterate the string.
1244 */
1245 while (*pszVar)
1246 {
1247 /* parse instruction. */
1248 static struct
1249 {
1250 const char *pszInstr;
1251 size_t cchInstr;
1252 unsigned fFlag;
1253 bool fInverted;
1254 } const aDest[] =
1255 {
1256 { "disabled", sizeof("disabled" ) - 1, RTLOGFLAGS_DISABLED, false },
1257 { "enabled", sizeof("enabled" ) - 1, RTLOGFLAGS_DISABLED, true },
1258 { "buffered", sizeof("buffered" ) - 1, RTLOGFLAGS_BUFFERED, false },
1259 { "unbuffered", sizeof("unbuffered" ) - 1, RTLOGFLAGS_BUFFERED, true },
1260 { "usecrlf", sizeof("usecrlf" ) - 1, RTLOGFLAGS_USECRLF, true },
1261 { "uself", sizeof("uself" ) - 1, RTLOGFLAGS_USECRLF, false },
1262 { "append", sizeof("append" ) - 1, RTLOGFLAGS_APPEND, false },
1263 { "overwrite", sizeof("overwrite" ) - 1, RTLOGFLAGS_APPEND, true },
1264 { "rel", sizeof("rel" ) - 1, RTLOGFLAGS_REL_TS, false },
1265 { "abs", sizeof("abs" ) - 1, RTLOGFLAGS_REL_TS, true },
1266 { "dec", sizeof("dec" ) - 1, RTLOGFLAGS_DECIMAL_TS, false },
1267 { "hex", sizeof("hex" ) - 1, RTLOGFLAGS_DECIMAL_TS, true },
1268 { "lockcnts", sizeof("lockcnts" ) - 1, RTLOGFLAGS_PREFIX_LOCK_COUNTS, false },
1269 { "cpuid", sizeof("cpuid" ) - 1, RTLOGFLAGS_PREFIX_CPUID, false },
1270 { "pid", sizeof("pid" ) - 1, RTLOGFLAGS_PREFIX_PID, false },
1271 { "flagno", sizeof("flagno" ) - 1, RTLOGFLAGS_PREFIX_FLAG_NO, false },
1272 { "flag", sizeof("flag" ) - 1, RTLOGFLAGS_PREFIX_FLAG, false },
1273 { "groupno", sizeof("groupno" ) - 1, RTLOGFLAGS_PREFIX_GROUP_NO, false },
1274 { "group", sizeof("group" ) - 1, RTLOGFLAGS_PREFIX_GROUP, false },
1275 { "tid", sizeof("tid" ) - 1, RTLOGFLAGS_PREFIX_TID, false },
1276 { "thread", sizeof("thread" ) - 1, RTLOGFLAGS_PREFIX_THREAD, false },
1277 { "timeprog", sizeof("timeprog" ) - 1, RTLOGFLAGS_PREFIX_TIME_PROG, false },
1278 { "time", sizeof("time" ) - 1, RTLOGFLAGS_PREFIX_TIME, false },
1279 { "msprog", sizeof("msprog" ) - 1, RTLOGFLAGS_PREFIX_MS_PROG, false },
1280 { "tsc", sizeof("tsc" ) - 1, RTLOGFLAGS_PREFIX_TSC, false }, /* before ts! */
1281 { "ts", sizeof("ts" ) - 1, RTLOGFLAGS_PREFIX_TS, false },
1282 };
1283
1284 /* check no prefix. */
1285 bool fNo = false;
1286 char ch;
1287 unsigned i;
1288
1289 /* skip blanks. */
1290 while (RT_C_IS_SPACE(*pszVar))
1291 pszVar++;
1292 if (!*pszVar)
1293 return rc;
1294
1295 while ((ch = *pszVar) != '\0')
1296 {
1297 if (ch == 'n' && pszVar[1] == 'o')
1298 {
1299 pszVar += 2;
1300 fNo = !fNo;
1301 }
1302 else if (ch == '+')
1303 {
1304 pszVar++;
1305 fNo = true;
1306 }
1307 else if (ch == '-' || ch == '!' || ch == '~')
1308 {
1309 pszVar++;
1310 fNo = !fNo;
1311 }
1312 else
1313 break;
1314 }
1315
1316 /* instruction. */
1317 for (i = 0; i < RT_ELEMENTS(aDest); i++)
1318 {
1319 if (!strncmp(pszVar, aDest[i].pszInstr, aDest[i].cchInstr))
1320 {
1321 if (fNo == aDest[i].fInverted)
1322 pLogger->fFlags |= aDest[i].fFlag;
1323 else
1324 pLogger->fFlags &= ~aDest[i].fFlag;
1325 pszVar += aDest[i].cchInstr;
1326 break;
1327 }
1328 }
1329
1330 /* unknown instruction? */
1331 if (i >= RT_ELEMENTS(aDest))
1332 {
1333 AssertMsgFailed(("Invalid flags! unknown instruction %.20s\n", pszVar));
1334 pszVar++;
1335 }
1336
1337 /* skip blanks and delimiters. */
1338 while (RT_C_IS_SPACE(*pszVar) || *pszVar == ';')
1339 pszVar++;
1340 } /* while more environment variable value left */
1341
1342 return rc;
1343}
1344
1345
1346/**
1347 * Flushes the specified logger.
1348 *
1349 * @param pLogger The logger instance to flush.
1350 * If NULL the default instance is used. The default instance
1351 * will not be initialized by this call.
1352 */
1353RTDECL(void) RTLogFlush(PRTLOGGER pLogger)
1354{
1355 /*
1356 * Resolve defaults.
1357 */
1358 if (!pLogger)
1359 {
1360#ifdef IN_RC
1361 pLogger = &g_Logger;
1362#else
1363 pLogger = g_pLogger;
1364#endif
1365 if (!pLogger)
1366 return;
1367 }
1368
1369 /*
1370 * Any thing to flush?
1371 */
1372 if (pLogger->offScratch)
1373 {
1374#ifndef IN_RC
1375 /*
1376 * Acquire logger instance sem.
1377 */
1378 int rc = rtlogLock(pLogger);
1379 if (RT_FAILURE(rc))
1380 return;
1381#endif
1382 /*
1383 * Call worker.
1384 */
1385 rtlogFlush(pLogger);
1386
1387#ifndef IN_RC
1388 /*
1389 * Release the semaphore.
1390 */
1391 rtlogUnlock(pLogger);
1392#endif
1393 }
1394}
1395
1396
1397/**
1398 * Gets the default logger instance, creating it if necessary.
1399 *
1400 * @returns Pointer to default logger instance.
1401 * @returns NULL if no default logger instance available.
1402 */
1403RTDECL(PRTLOGGER) RTLogDefaultInstance(void)
1404{
1405#ifdef IN_RC
1406 return &g_Logger;
1407
1408#else /* !IN_RC */
1409# ifdef IN_RING0
1410 /*
1411 * Check per thread loggers first.
1412 */
1413 if (g_cPerThreadLoggers)
1414 {
1415 const RTNATIVETHREAD Self = RTThreadNativeSelf();
1416 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
1417 while (i-- > 0)
1418 if (g_aPerThreadLoggers[i].NativeThread == Self)
1419 return g_aPerThreadLoggers[i].pLogger;
1420 }
1421# endif /* IN_RING0 */
1422
1423 /*
1424 * If no per thread logger, use the default one.
1425 */
1426 if (!g_pLogger)
1427 g_pLogger = RTLogDefaultInit();
1428 return g_pLogger;
1429#endif /* !IN_RC */
1430}
1431
1432
1433/**
1434 * Gets the default logger instance.
1435 *
1436 * @returns Pointer to default logger instance.
1437 * @returns NULL if no default logger instance available.
1438 */
1439RTDECL(PRTLOGGER) RTLogGetDefaultInstance(void)
1440{
1441#ifdef IN_RC
1442 return &g_Logger;
1443#else
1444# ifdef IN_RING0
1445 /*
1446 * Check per thread loggers first.
1447 */
1448 if (g_cPerThreadLoggers)
1449 {
1450 const RTNATIVETHREAD Self = RTThreadNativeSelf();
1451 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
1452 while (i-- > 0)
1453 if (g_aPerThreadLoggers[i].NativeThread == Self)
1454 return g_aPerThreadLoggers[i].pLogger;
1455 }
1456# endif /* IN_RING0 */
1457
1458 return g_pLogger;
1459#endif
1460}
1461
1462
1463#ifndef IN_RC
1464/**
1465 * Sets the default logger instance.
1466 *
1467 * @returns iprt status code.
1468 * @param pLogger The new default logger instance.
1469 */
1470RTDECL(PRTLOGGER) RTLogSetDefaultInstance(PRTLOGGER pLogger)
1471{
1472 return (PRTLOGGER)ASMAtomicXchgPtr((void * volatile *)&g_pLogger, pLogger);
1473}
1474#endif /* !IN_RC */
1475
1476
1477#ifdef IN_RING0
1478/**
1479 * Changes the default logger instance for the current thread.
1480 *
1481 * @returns IPRT status code.
1482 * @param pLogger The logger instance. Pass NULL for deregistration.
1483 * @param uKey Associated key for cleanup purposes. If pLogger is NULL,
1484 * all instances with this key will be deregistered. So in
1485 * order to only deregister the instance associated with the
1486 * current thread use 0.
1487 */
1488RTDECL(int) RTLogSetDefaultInstanceThread(PRTLOGGER pLogger, uintptr_t uKey)
1489{
1490 int rc;
1491 RTNATIVETHREAD Self = RTThreadNativeSelf();
1492 if (pLogger)
1493 {
1494 int32_t i;
1495 unsigned j;
1496
1497 AssertReturn(pLogger->u32Magic == RTLOGGER_MAGIC, VERR_INVALID_MAGIC);
1498
1499 /*
1500 * Iterate the table to see if there is already an entry for this thread.
1501 */
1502 i = RT_ELEMENTS(g_aPerThreadLoggers);
1503 while (i-- > 0)
1504 if (g_aPerThreadLoggers[i].NativeThread == Self)
1505 {
1506 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, (void *)uKey);
1507 g_aPerThreadLoggers[i].pLogger = pLogger;
1508 return VINF_SUCCESS;
1509 }
1510
1511 /*
1512 * Allocate a new table entry.
1513 */
1514 i = ASMAtomicIncS32(&g_cPerThreadLoggers);
1515 if (i > (int32_t)RT_ELEMENTS(g_aPerThreadLoggers))
1516 {
1517 ASMAtomicDecS32(&g_cPerThreadLoggers);
1518 return VERR_BUFFER_OVERFLOW; /* horrible error code! */
1519 }
1520
1521 for (j = 0; j < 10; j++)
1522 {
1523 i = RT_ELEMENTS(g_aPerThreadLoggers);
1524 while (i-- > 0)
1525 {
1526 AssertCompile(sizeof(RTNATIVETHREAD) == sizeof(void*));
1527 if ( g_aPerThreadLoggers[i].NativeThread == NIL_RTNATIVETHREAD
1528 && ASMAtomicCmpXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].NativeThread, (void *)Self, (void *)NIL_RTNATIVETHREAD))
1529 {
1530 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, (void *)uKey);
1531 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].pLogger, pLogger);
1532 return VINF_SUCCESS;
1533 }
1534 }
1535 }
1536
1537 ASMAtomicDecS32(&g_cPerThreadLoggers);
1538 rc = VERR_INTERNAL_ERROR;
1539 }
1540 else
1541 {
1542 /*
1543 * Search the array for the current thread.
1544 */
1545 int32_t i = RT_ELEMENTS(g_aPerThreadLoggers);
1546 while (i-- > 0)
1547 if ( g_aPerThreadLoggers[i].NativeThread == Self
1548 || g_aPerThreadLoggers[i].uKey == uKey)
1549 {
1550 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].uKey, NULL);
1551 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].pLogger, NULL);
1552 ASMAtomicXchgPtr((void * volatile *)&g_aPerThreadLoggers[i].NativeThread, (void *)NIL_RTNATIVETHREAD);
1553 ASMAtomicDecS32(&g_cPerThreadLoggers);
1554 }
1555
1556 rc = VINF_SUCCESS;
1557 }
1558 return rc;
1559}
1560#endif
1561
1562
1563/**
1564 * Write to a logger instance.
1565 *
1566 * @param pLogger Pointer to logger instance.
1567 * @param pszFormat Format string.
1568 * @param args Format arguments.
1569 */
1570RTDECL(void) RTLogLoggerV(PRTLOGGER pLogger, const char *pszFormat, va_list args)
1571{
1572 RTLogLoggerExV(pLogger, 0, ~0U, pszFormat, args);
1573}
1574
1575
1576/**
1577 * Write to a logger instance.
1578 *
1579 * This function will check whether the instance, group and flags makes up a
1580 * logging kind which is currently enabled before writing anything to the log.
1581 *
1582 * @param pLogger Pointer to logger instance. If NULL the default logger instance will be attempted.
1583 * @param fFlags The logging flags.
1584 * @param iGroup The group.
1585 * The value ~0U is reserved for compatability with RTLogLogger[V] and is
1586 * only for internal usage!
1587 * @param pszFormat Format string.
1588 * @param args Format arguments.
1589 */
1590RTDECL(void) RTLogLoggerExV(PRTLOGGER pLogger, unsigned fFlags, unsigned iGroup, const char *pszFormat, va_list args)
1591{
1592 int rc;
1593
1594 /*
1595 * A NULL logger means default instance.
1596 */
1597 if (!pLogger)
1598 {
1599 pLogger = RTLogDefaultInstance();
1600 if (!pLogger)
1601 return;
1602 }
1603
1604 /*
1605 * Validate and correct iGroup.
1606 */
1607 if (iGroup != ~0U && iGroup >= pLogger->cGroups)
1608 iGroup = 0;
1609
1610 /*
1611 * If no output, then just skip it.
1612 */
1613 if ( (pLogger->fFlags & RTLOGFLAGS_DISABLED)
1614#ifndef IN_RC
1615 || !pLogger->fDestFlags
1616#endif
1617 || !pszFormat || !*pszFormat)
1618 return;
1619 if ( iGroup != ~0U
1620 && (pLogger->afGroups[iGroup] & (fFlags | RTLOGGRPFLAGS_ENABLED)) != (fFlags | RTLOGGRPFLAGS_ENABLED))
1621 return;
1622
1623 /*
1624 * Acquire logger instance sem.
1625 */
1626 rc = rtlogLock(pLogger);
1627 if (RT_FAILURE(rc))
1628 {
1629#ifdef IN_RING0
1630 if (pLogger->fDestFlags & ~RTLOGDEST_FILE)
1631 rtR0LogLoggerExFallback(pLogger->fDestFlags, pszFormat, args);
1632#endif
1633 return;
1634 }
1635
1636 /*
1637 * Format the message and perhaps flush it.
1638 */
1639 if (pLogger->fFlags & (RTLOGFLAGS_PREFIX_MASK | RTLOGFLAGS_USECRLF))
1640 {
1641 RTLOGOUTPUTPREFIXEDARGS OutputArgs;
1642 OutputArgs.pLogger = pLogger;
1643 OutputArgs.iGroup = iGroup;
1644 OutputArgs.fFlags = fFlags;
1645 RTLogFormatV(rtLogOutputPrefixed, &OutputArgs, pszFormat, args);
1646 }
1647 else
1648 RTLogFormatV(rtLogOutput, pLogger, pszFormat, args);
1649 if ( !(pLogger->fFlags & RTLOGFLAGS_BUFFERED)
1650 && pLogger->offScratch)
1651 rtlogFlush(pLogger);
1652
1653 /*
1654 * Release the semaphore.
1655 */
1656 rtlogUnlock(pLogger);
1657}
1658
1659#ifdef IN_RING0
1660/**
1661 * For rtR0LogLoggerExFallbackOutput and rtR0LogLoggerExFallbackFlush.
1662 */
1663typedef struct RTR0LOGLOGGERFALLBACK
1664{
1665 /** The current scratch buffer offset. */
1666 uint32_t offScratch;
1667 /** The destination flags. */
1668 uint32_t fDestFlags;
1669 /** The scratch buffer. */
1670 char achScratch[80];
1671} RTR0LOGLOGGERFALLBACK;
1672/** Pointer to RTR0LOGLOGGERFALLBACK which is used by
1673 * rtR0LogLoggerExFallbackOutput. */
1674typedef RTR0LOGLOGGERFALLBACK *PRTR0LOGLOGGERFALLBACK;
1675
1676
1677/**
1678 * Flushes the fallback buffer.
1679 *
1680 * @param pThis The scratch buffer.
1681 */
1682static void rtR0LogLoggerExFallbackFlush(PRTR0LOGLOGGERFALLBACK pThis)
1683{
1684 if (!pThis->offScratch)
1685 return;
1686
1687 if (pThis->fDestFlags & RTLOGDEST_USER)
1688 RTLogWriteUser(pThis->achScratch, pThis->offScratch);
1689
1690 if (pThis->fDestFlags & RTLOGDEST_DEBUGGER)
1691 RTLogWriteDebugger(pThis->achScratch, pThis->offScratch);
1692
1693 if (pThis->fDestFlags & RTLOGDEST_STDOUT)
1694 RTLogWriteStdOut(pThis->achScratch, pThis->offScratch);
1695
1696 if (pThis->fDestFlags & RTLOGDEST_STDERR)
1697 RTLogWriteStdErr(pThis->achScratch, pThis->offScratch);
1698
1699#ifndef LOG_NO_COM
1700 if (pThis->fDestFlags & RTLOGDEST_COM)
1701 RTLogWriteCom(pThis->achScratch, pThis->offScratch);
1702#endif
1703
1704 /* empty the buffer. */
1705 pThis->offScratch = 0;
1706}
1707
1708
1709/**
1710 * Callback for RTLogFormatV used by rtR0LogLoggerExFallback.
1711 * See PFNLOGOUTPUT() for details.
1712 */
1713static DECLCALLBACK(size_t) rtR0LogLoggerExFallbackOutput(void *pv, const char *pachChars, size_t cbChars)
1714{
1715 PRTR0LOGLOGGERFALLBACK pThis = (PRTR0LOGLOGGERFALLBACK)pv;
1716 if (cbChars)
1717 {
1718 size_t cbRet = 0;
1719 for (;;)
1720 {
1721 /* how much */
1722 uint32_t cb = sizeof(pThis->achScratch) - pThis->offScratch - 1; /* minus 1 - for the string terminator. */
1723 if (cb > cbChars)
1724 cb = (RTUINT)cbChars;
1725
1726 /* copy */
1727 memcpy(&pThis->achScratch[pThis->offScratch], pachChars, cb);
1728
1729 /* advance */
1730 pThis->offScratch += cb;
1731 cbRet += cb;
1732 cbChars -= cb;
1733
1734 /* done? */
1735 if (cbChars <= 0)
1736 return cbRet;
1737
1738 pachChars += cb;
1739
1740 /* flush */
1741 pThis->achScratch[pThis->offScratch] = '\0';
1742 rtR0LogLoggerExFallbackFlush(pThis);
1743 }
1744
1745 /* won't ever get here! */
1746 }
1747 else
1748 {
1749 /*
1750 * Termination call, flush the log.
1751 */
1752 pThis->achScratch[pThis->offScratch] = '\0';
1753 rtR0LogLoggerExFallbackFlush(pThis);
1754 return 0;
1755 }
1756}
1757
1758
1759/**
1760 * Ring-0 fallback for cases where we're unable to grab the lock.
1761 *
1762 * This will happen when we're at a too high IRQL on Windows for instance and
1763 * needs to be dealt with or we'll drop a lot of log output. This fallback will
1764 * only output to some of the log destinations as a few of them may be doing
1765 * dangerouse things. We won't be doing any prefixing here either, at least not
1766 * for the present, because it's too much hazzle.
1767 *
1768 * @param pLogger The destination flags.
1769 * @param pszFormat The format string.
1770 * @param va The format arguments.
1771 */
1772static void rtR0LogLoggerExFallback(uint32_t fDestFlags, const char *pszFormat, va_list va)
1773{
1774 RTR0LOGLOGGERFALLBACK This;
1775 This.fDestFlags = fDestFlags;
1776 This.offScratch = 0;
1777 RTLogFormatV(rtR0LogLoggerExFallbackOutput, &This, pszFormat, va);
1778}
1779#endif /* IN_RING0 */
1780
1781
1782/**
1783 * vprintf like function for writing to the default log.
1784 *
1785 * @param pszFormat Printf like format string.
1786 * @param args Optional arguments as specified in pszFormat.
1787 *
1788 * @remark The API doesn't support formatting of floating point numbers at the moment.
1789 */
1790RTDECL(void) RTLogPrintfV(const char *pszFormat, va_list args)
1791{
1792 RTLogLoggerV(NULL, pszFormat, args);
1793}
1794
1795
1796/**
1797 * Writes the buffer to the given log device without checking for buffered
1798 * data or anything.
1799 * Used by the RTLogFlush() function.
1800 *
1801 * @param pLogger The logger instance to write to. NULL is not allowed!
1802 */
1803static void rtlogFlush(PRTLOGGER pLogger)
1804{
1805#ifndef IN_RC
1806 if (pLogger->fDestFlags & RTLOGDEST_USER)
1807 RTLogWriteUser(pLogger->achScratch, pLogger->offScratch);
1808
1809 if (pLogger->fDestFlags & RTLOGDEST_DEBUGGER)
1810 RTLogWriteDebugger(pLogger->achScratch, pLogger->offScratch);
1811
1812# ifdef IN_RING3
1813 if (pLogger->fDestFlags & RTLOGDEST_FILE)
1814 RTFileWrite(pLogger->File, pLogger->achScratch, pLogger->offScratch, NULL);
1815# endif
1816
1817 if (pLogger->fDestFlags & RTLOGDEST_STDOUT)
1818 RTLogWriteStdOut(pLogger->achScratch, pLogger->offScratch);
1819
1820 if (pLogger->fDestFlags & RTLOGDEST_STDERR)
1821 RTLogWriteStdErr(pLogger->achScratch, pLogger->offScratch);
1822
1823# if (defined(IN_RING0) || defined(IN_RC)) && !defined(LOG_NO_COM)
1824 if (pLogger->fDestFlags & RTLOGDEST_COM)
1825 RTLogWriteCom(pLogger->achScratch, pLogger->offScratch);
1826# endif
1827#endif /* !IN_RC */
1828
1829 if (pLogger->pfnFlush)
1830 pLogger->pfnFlush(pLogger);
1831
1832 /* empty the buffer. */
1833 pLogger->offScratch = 0;
1834}
1835
1836
1837/**
1838 * Callback for RTLogFormatV which writes to the com port.
1839 * See PFNLOGOUTPUT() for details.
1840 */
1841static DECLCALLBACK(size_t) rtLogOutput(void *pv, const char *pachChars, size_t cbChars)
1842{
1843 PRTLOGGER pLogger = (PRTLOGGER)pv;
1844 if (cbChars)
1845 {
1846 size_t cbRet = 0;
1847 for (;;)
1848 {
1849#if defined(DEBUG) && defined(IN_RING3)
1850 /* sanity */
1851 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
1852 {
1853 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
1854 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
1855 AssertBreakpoint(); AssertBreakpoint();
1856 }
1857#endif
1858
1859 /* how much */
1860 size_t cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
1861 if (cb > cbChars)
1862 cb = cbChars;
1863
1864 /* copy */
1865 memcpy(&pLogger->achScratch[pLogger->offScratch], pachChars, cb);
1866
1867 /* advance */
1868 pLogger->offScratch += (RTUINT)cb;
1869 cbRet += cb;
1870 cbChars -= cb;
1871
1872 /* done? */
1873 if (cbChars <= 0)
1874 return cbRet;
1875
1876 pachChars += cb;
1877
1878 /* flush */
1879 rtlogFlush(pLogger);
1880 }
1881
1882 /* won't ever get here! */
1883 }
1884 else
1885 {
1886 /*
1887 * Termination call.
1888 * There's always space for a terminator, and it's not counted.
1889 */
1890 pLogger->achScratch[pLogger->offScratch] = '\0';
1891 return 0;
1892 }
1893}
1894
1895
1896
1897/**
1898 * Callback for RTLogFormatV which writes to the logger instance.
1899 * This version supports prefixes.
1900 *
1901 * See PFNLOGOUTPUT() for details.
1902 */
1903static DECLCALLBACK(size_t) rtLogOutputPrefixed(void *pv, const char *pachChars, size_t cbChars)
1904{
1905 PRTLOGOUTPUTPREFIXEDARGS pArgs = (PRTLOGOUTPUTPREFIXEDARGS)pv;
1906 PRTLOGGER pLogger = pArgs->pLogger;
1907 if (cbChars)
1908 {
1909 size_t cbRet = 0;
1910 for (;;)
1911 {
1912 size_t cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
1913 char *psz;
1914 const char *pszNewLine;
1915
1916 /*
1917 * Pending prefix?
1918 */
1919 if (pLogger->fPendingPrefix)
1920 {
1921 pLogger->fPendingPrefix = false;
1922
1923#if defined(DEBUG) && defined(IN_RING3)
1924 /* sanity */
1925 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
1926 {
1927 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
1928 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
1929 AssertBreakpoint(); AssertBreakpoint();
1930 }
1931#endif
1932
1933 /*
1934 * Flush the buffer if there isn't enough room for the maximum prefix config.
1935 * Max is 224, add a couple of extra bytes.
1936 */
1937 if (cb < 224 + 16)
1938 {
1939 rtlogFlush(pLogger);
1940 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
1941 }
1942
1943 /*
1944 * Write the prefixes.
1945 * psz is pointing to the current position.
1946 */
1947 psz = &pLogger->achScratch[pLogger->offScratch];
1948 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TS)
1949 {
1950#if defined(IN_RING3) || defined(IN_RC)
1951 uint64_t u64 = RTTimeNanoTS();
1952#else
1953 uint64_t u64 = ~0;
1954#endif
1955 int iBase = 16;
1956 unsigned int fFlags = RTSTR_F_ZEROPAD;
1957 if (pLogger->fFlags & RTLOGFLAGS_DECIMAL_TS)
1958 {
1959 iBase = 10;
1960 fFlags = 0;
1961 }
1962 if (pLogger->fFlags & RTLOGFLAGS_REL_TS)
1963 {
1964 static volatile uint64_t s_u64LastTs;
1965 uint64_t u64DiffTs = u64 - s_u64LastTs;
1966 s_u64LastTs = u64;
1967 /* We could have been preempted just before reading of s_u64LastTs by
1968 * another thread which wrote s_u64LastTs. In that case the difference
1969 * is negative which we simply ignore. */
1970 u64 = (int64_t)u64DiffTs < 0 ? 0 : u64DiffTs;
1971 }
1972 /* 1E15 nanoseconds = 11 days */
1973 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags); /* +17 */
1974 *psz++ = ' ';
1975 }
1976 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TSC)
1977 {
1978 uint64_t u64 = ASMReadTSC();
1979 int iBase = 16;
1980 unsigned int fFlags = RTSTR_F_ZEROPAD;
1981 if (pLogger->fFlags & RTLOGFLAGS_DECIMAL_TS)
1982 {
1983 iBase = 10;
1984 fFlags = 0;
1985 }
1986 if (pLogger->fFlags & RTLOGFLAGS_REL_TS)
1987 {
1988 static volatile uint64_t s_u64LastTsc;
1989 int64_t i64DiffTsc = u64 - s_u64LastTsc;
1990 s_u64LastTsc = u64;
1991 /* We could have been preempted just before reading of s_u64LastTsc by
1992 * another thread which wrote s_u64LastTsc. In that case the difference
1993 * is negative which we simply ignore. */
1994 u64 = i64DiffTsc < 0 ? 0 : i64DiffTsc;
1995 }
1996 /* 1E15 ticks at 4GHz = 69 hours */
1997 psz += RTStrFormatNumber(psz, u64, iBase, 16, 0, fFlags); /* +17 */
1998 *psz++ = ' ';
1999 }
2000 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_MS_PROG)
2001 {
2002#if defined(IN_RING3) || defined(IN_RC)
2003 uint64_t u64 = RTTimeProgramMilliTS();
2004#else
2005 uint64_t u64 = 0;
2006#endif
2007 /* 1E8 milliseconds = 27 hours */
2008 psz += RTStrFormatNumber(psz, u64, 10, 9, 0, RTSTR_F_ZEROPAD);
2009 *psz++ = ' ';
2010 }
2011 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TIME)
2012 {
2013#ifdef IN_RING3
2014 RTTIMESPEC TimeSpec;
2015 RTTIME Time;
2016 RTTimeExplode(&Time, RTTimeNow(&TimeSpec));
2017 psz += RTStrFormatNumber(psz, Time.u8Hour, 10, 2, 0, RTSTR_F_ZEROPAD);
2018 *psz++ = ':';
2019 psz += RTStrFormatNumber(psz, Time.u8Minute, 10, 2, 0, RTSTR_F_ZEROPAD);
2020 *psz++ = ':';
2021 psz += RTStrFormatNumber(psz, Time.u8Second, 10, 2, 0, RTSTR_F_ZEROPAD);
2022 *psz++ = '.';
2023 psz += RTStrFormatNumber(psz, Time.u32Nanosecond / 1000000, 10, 3, 0, RTSTR_F_ZEROPAD);
2024 *psz++ = ' '; /* +17 (3+1+3+1+3+1+4+1) */
2025#else
2026 memset(psz, ' ', 13);
2027 psz += 13;
2028#endif
2029 }
2030 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TIME_PROG)
2031 {
2032#ifdef IN_RING3
2033 uint64_t u64 = RTTimeProgramMilliTS();
2034 psz += RTStrFormatNumber(psz, (uint32_t)(u64 / (60 * 60 * 1000)), 10, 2, 0, RTSTR_F_ZEROPAD);
2035 *psz++ = ':';
2036 uint32_t u32 = (uint32_t)(u64 % (60 * 60 * 1000));
2037 psz += RTStrFormatNumber(psz, u32 / (60 * 1000), 10, 2, 0, RTSTR_F_ZEROPAD);
2038 *psz++ = ':';
2039 u32 %= 60 * 1000;
2040 psz += RTStrFormatNumber(psz, u32 / 1000, 10, 2, 0, RTSTR_F_ZEROPAD);
2041 *psz++ = '.';
2042 psz += RTStrFormatNumber(psz, u32 % 1000, 10, 3, 0, RTSTR_F_ZEROPAD);
2043 *psz++ = ' '; /* +20 (9+1+2+1+2+1+3+1) */
2044#else
2045 memset(psz, ' ', 13);
2046 psz += 13;
2047#endif
2048 }
2049# if 0
2050 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_DATETIME)
2051 {
2052 char szDate[32];
2053 RTTIMESPEC Time;
2054 RTTimeSpecToString(RTTimeNow(&Time), szDate, sizeof(szDate));
2055 size_t cch = strlen(szDate);
2056 memcpy(psz, szDate, cch);
2057 psz += cch;
2058 *psz++ = ' '; /* +32 */
2059 }
2060# endif
2061 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_PID)
2062 {
2063#ifndef IN_RC
2064 RTPROCESS Process = RTProcSelf();
2065#else
2066 RTPROCESS Process = NIL_RTPROCESS;
2067#endif
2068 psz += RTStrFormatNumber(psz, Process, 16, sizeof(RTPROCESS) * 2, 0, RTSTR_F_ZEROPAD);
2069 *psz++ = ' '; /* +9 */
2070 }
2071 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_TID)
2072 {
2073#ifndef IN_RC
2074 RTNATIVETHREAD Thread = RTThreadNativeSelf();
2075#else
2076 RTNATIVETHREAD Thread = NIL_RTNATIVETHREAD;
2077#endif
2078 psz += RTStrFormatNumber(psz, Thread, 16, sizeof(RTNATIVETHREAD) * 2, 0, RTSTR_F_ZEROPAD);
2079 *psz++ = ' '; /* +17 */
2080 }
2081 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_THREAD)
2082 {
2083#ifdef IN_RING3
2084 const char *pszName = RTThreadSelfName();
2085#elif defined IN_RC
2086 const char *pszName = "EMT-GC";
2087#else
2088 const char *pszName = "EMT-R0";
2089#endif
2090 size_t cch = 0;
2091 if (pszName)
2092 {
2093 cch = strlen(pszName);
2094 cch = RT_MIN(cch, 16);
2095 memcpy(psz, pszName, cch);
2096 psz += cch;
2097 }
2098 do
2099 *psz++ = ' ';
2100 while (cch++ < 8); /* +17 */
2101 }
2102 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_CPUID)
2103 {
2104#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
2105 const uint8_t idCpu = ASMGetApicId();
2106#else
2107 const RTCPUID idCpu = RTMpCpuId();
2108#endif
2109 psz += RTStrFormatNumber(psz, idCpu, 16, sizeof(idCpu) * 2, 0, RTSTR_F_ZEROPAD);
2110 *psz++ = ' '; /* +17 */
2111 }
2112 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_LOCK_COUNTS)
2113 {
2114#ifdef IN_RING3 /** @todo implement these counters in ring-0 too? */
2115 RTTHREAD Thread = RTThreadSelf();
2116 if (Thread != NIL_RTTHREAD)
2117 {
2118 uint32_t cReadLocks = RTThreadGetReadLockCount(Thread);
2119 uint32_t cWriteLocks = RTThreadGetWriteLockCount(Thread) - g_cLoggerLockCount;
2120 cReadLocks = RT_MIN(0xfff, cReadLocks);
2121 cWriteLocks = RT_MIN(0xfff, cWriteLocks);
2122 psz += RTStrFormatNumber(psz, cReadLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
2123 *psz++ = '/';
2124 psz += RTStrFormatNumber(psz, cWriteLocks, 16, 1, 0, RTSTR_F_ZEROPAD);
2125 }
2126 else
2127#endif
2128 {
2129 *psz++ = '?';
2130 *psz++ = '/';
2131 *psz++ = '?';
2132 }
2133 *psz++ = ' '; /* +8 */
2134 }
2135 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_FLAG_NO)
2136 {
2137 psz += RTStrFormatNumber(psz, pArgs->fFlags, 16, 8, 0, RTSTR_F_ZEROPAD);
2138 *psz++ = ' '; /* +9 */
2139 }
2140 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_FLAG)
2141 {
2142#ifdef IN_RING3
2143 const char *pszGroup = pArgs->iGroup != ~0U ? pLogger->papszGroups[pArgs->iGroup] : NULL;
2144#else
2145 const char *pszGroup = NULL;
2146#endif
2147 size_t cch = 0;
2148 if (pszGroup)
2149 {
2150 cch = strlen(pszGroup);
2151 cch = RT_MIN(cch, 16);
2152 memcpy(psz, pszGroup, cch);
2153 psz += cch;
2154 }
2155 do
2156 *psz++ = ' ';
2157 while (cch++ < 8); /* +17 */
2158 }
2159 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_GROUP_NO)
2160 {
2161 if (pArgs->iGroup != ~0U)
2162 {
2163 psz += RTStrFormatNumber(psz, pArgs->iGroup, 16, 3, 0, RTSTR_F_ZEROPAD);
2164 *psz++ = ' ';
2165 }
2166 else
2167 {
2168 memcpy(psz, "-1 ", sizeof("-1 ") - 1);
2169 psz += sizeof("-1 ") - 1;
2170 } /* +9 */
2171 }
2172 if (pLogger->fFlags & RTLOGFLAGS_PREFIX_GROUP)
2173 {
2174 const unsigned fGrp = pLogger->afGroups[pArgs->iGroup != ~0U ? pArgs->iGroup : 0];
2175 const char *pszGroup;
2176 size_t cch;
2177 switch (pArgs->fFlags & fGrp)
2178 {
2179 case 0: pszGroup = "--------"; cch = sizeof("--------") - 1; break;
2180 case RTLOGGRPFLAGS_ENABLED: pszGroup = "enabled" ; cch = sizeof("enabled" ) - 1; break;
2181 case RTLOGGRPFLAGS_LEVEL_1: pszGroup = "level 1" ; cch = sizeof("level 1" ) - 1; break;
2182 case RTLOGGRPFLAGS_LEVEL_2: pszGroup = "level 2" ; cch = sizeof("level 2" ) - 1; break;
2183 case RTLOGGRPFLAGS_LEVEL_3: pszGroup = "level 3" ; cch = sizeof("level 3" ) - 1; break;
2184 case RTLOGGRPFLAGS_LEVEL_4: pszGroup = "level 4" ; cch = sizeof("level 4" ) - 1; break;
2185 case RTLOGGRPFLAGS_LEVEL_5: pszGroup = "level 5" ; cch = sizeof("level 5" ) - 1; break;
2186 case RTLOGGRPFLAGS_LEVEL_6: pszGroup = "level 6" ; cch = sizeof("level 6" ) - 1; break;
2187 case RTLOGGRPFLAGS_FLOW: pszGroup = "flow" ; cch = sizeof("flow" ) - 1; break;
2188
2189 /* personal groups */
2190 case RTLOGGRPFLAGS_LELIK: pszGroup = "lelik" ; cch = sizeof("lelik" ) - 1; break;
2191 case RTLOGGRPFLAGS_MICHAEL: pszGroup = "Michael" ; cch = sizeof("Michael" ) - 1; break;
2192 case RTLOGGRPFLAGS_DMIK: pszGroup = "dmik" ; cch = sizeof("dmik" ) - 1; break;
2193 case RTLOGGRPFLAGS_SUNLOVER: pszGroup = "sunlover"; cch = sizeof("sunlover") - 1; break;
2194 case RTLOGGRPFLAGS_ACHIM: pszGroup = "Achim" ; cch = sizeof("Achim" ) - 1; break;
2195 case RTLOGGRPFLAGS_SANDER: pszGroup = "Sander" ; cch = sizeof("Sander" ) - 1; break;
2196 case RTLOGGRPFLAGS_KLAUS: pszGroup = "Klaus" ; cch = sizeof("Klaus" ) - 1; break;
2197 case RTLOGGRPFLAGS_FRANK: pszGroup = "Frank" ; cch = sizeof("Frank" ) - 1; break;
2198 case RTLOGGRPFLAGS_BIRD: pszGroup = "bird" ; cch = sizeof("bird" ) - 1; break;
2199 case RTLOGGRPFLAGS_NONAME: pszGroup = "noname" ; cch = sizeof("noname" ) - 1; break;
2200 default: pszGroup = "????????"; cch = sizeof("????????") - 1; break;
2201 }
2202 if (pszGroup)
2203 {
2204 cch = RT_MIN(cch, 16);
2205 memcpy(psz, pszGroup, cch);
2206 psz += cch;
2207 }
2208 do
2209 *psz++ = ' ';
2210 while (cch++ < 8); /* +17 */
2211 }
2212
2213 /*
2214 * Done, figure what we've used and advance the buffer and free size.
2215 */
2216 cb = psz - &pLogger->achScratch[pLogger->offScratch];
2217 Assert(cb <= 198);
2218 pLogger->offScratch += (RTUINT)cb;
2219 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
2220 }
2221 else if (cb <= 0)
2222 {
2223 rtlogFlush(pLogger);
2224 cb = sizeof(pLogger->achScratch) - pLogger->offScratch - 1;
2225 }
2226
2227#if defined(DEBUG) && defined(IN_RING3)
2228 /* sanity */
2229 if (pLogger->offScratch >= sizeof(pLogger->achScratch))
2230 {
2231 fprintf(stderr, "pLogger->offScratch >= sizeof(pLogger->achScratch) (%#x >= %#x)\n",
2232 pLogger->offScratch, (unsigned)sizeof(pLogger->achScratch));
2233 AssertBreakpoint(); AssertBreakpoint();
2234 }
2235#endif
2236
2237 /* how much */
2238 if (cb > cbChars)
2239 cb = cbChars;
2240
2241 /* have newline? */
2242 pszNewLine = (const char *)memchr(pachChars, '\n', cb);
2243 if (pszNewLine)
2244 {
2245 if (pLogger->fFlags & RTLOGFLAGS_USECRLF)
2246 cb = pszNewLine - pachChars;
2247 else
2248 {
2249 cb = pszNewLine - pachChars + 1;
2250 pLogger->fPendingPrefix = true;
2251 }
2252 }
2253
2254 /* copy */
2255 memcpy(&pLogger->achScratch[pLogger->offScratch], pachChars, cb);
2256
2257 /* advance */
2258 pLogger->offScratch += (RTUINT)cb;
2259 cbRet += cb;
2260 cbChars -= cb;
2261
2262 if ( pszNewLine
2263 && (pLogger->fFlags & RTLOGFLAGS_USECRLF)
2264 && pLogger->offScratch + 2 < sizeof(pLogger->achScratch))
2265 {
2266 memcpy(&pLogger->achScratch[pLogger->offScratch], "\r\n", 2);
2267 pLogger->offScratch += 2;
2268 cbRet++;
2269 cbChars--;
2270 cb++;
2271 pLogger->fPendingPrefix = true;
2272 }
2273
2274 /* done? */
2275 if (cbChars <= 0)
2276 return cbRet;
2277 pachChars += cb;
2278 }
2279
2280 /* won't ever get here! */
2281 }
2282 else
2283 {
2284 /*
2285 * Termination call.
2286 * There's always space for a terminator, and it's not counted.
2287 */
2288 pLogger->achScratch[pLogger->offScratch] = '\0';
2289 return 0;
2290 }
2291}
2292
Note: See TracBrowser for help on using the repository browser.

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