VirtualBox

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

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

IPRT: gcc warnings when compiled as ISO C

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