VirtualBox

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

Last change on this file since 30859 was 30849, checked in by vboxsync, 14 years ago

fix comment

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