VirtualBox

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

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

warnings

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