1 /* Understanding is not required. Only obedience.
3 * This program is free software. It comes without any warranty, to
4 * the extent permitted by applicable law. You can redistribute it
5 * and/or modify it under the terms of the Do What The Fuck You Want
6 * To Public License, Version 2, as published by Sam Hocevar. See
7 * http://sam.zoy.org/wtfpl/COPYING for more details. */
11 #define DBG_TMP_BUF_SIZE (65536)
24 #include <sys/types.h>
27 ////////////////////////////////////////////////////////////////////////////////
28 DbgLogUpdateFn dbgLogPreUpdate
= NULL
;
29 DbgLogUpdateFn dbgLogPostUpdate
= NULL
;
32 ////////////////////////////////////////////////////////////////////////////////
33 static char ccLock
= 0;
36 static void dbgLock (void) {
37 while (__sync_bool_compare_and_swap(&ccLock
, 0, 1)) {
41 Sleep(1); // i don't care
47 static void dbgUnlock (void) {
48 //__sync_synchronize();
50 __sync_fetch_and_and(&ccLock
, 0);
54 ////////////////////////////////////////////////////////////////////////////////
56 static char dbgLogFileName
[8192] = {0};
57 static int dbgLogWriteToFile
= 1;
58 static int dbgLogWriteToScr
= 0;
63 static __attribute__((constructor(DBGLOG_CONSTRUCTOR_PRIO
))) void dbgLogInit (void) {
64 if (!dbgLogFileName
[0]) dbglog_set_filename("dlog.log");
69 void dbglog_set_filename (const char *fname
) {
72 if (fname
&& fname
[0]) {
73 strcpy(dbgLogFileName
, fname
);
75 dbgLogFileName
[0] = '\0';
82 int dbglog_set_fileout (int doIt
) {
86 old
= dbgLogWriteToFile
;
87 dbgLogWriteToFile
= (doIt
? 1 : 0);
96 int dbglog_set_screenout (int doIt
) {
100 old
= dbgLogWriteToScr
;
101 dbgLogWriteToScr
= (doIt
? 1 : 0);
111 __attribute__((format(printf
, 1, 2))) void dlogf (const char *fmt
, ...) {
119 static void writebuf (FILE *fo
, const char *sbuf
, const char *pfx
) {
120 int plen
= (pfx
!= NULL
? strlen(pfx
) : 0);
122 if (plen
> 0) fwrite(pfx
, plen
, 1, fo
);
123 fwrite("\n", 1, 1, fo
);
129 if (plen
> 0) fwrite(pfx
, plen
, 1, fo
);
130 nlp
= strchr(sbuf
, '\n');
136 if (olen
> 1 && nlp
[-1] == '\r') --olen
;
137 ++nlp
; // skip 'newline'
139 if (olen
> 0) fwrite(sbuf
, olen
, 1, fo
);
140 fwrite("\n", 1, 1, fo
);
146 void dlogfVA (const char *fmt
, va_list inap
) {
147 static char timebuf
[128];
148 static char buf
[DBG_TMP_BUF_SIZE
];
151 if (fmt
== NULL
&& !fmt
[0]) return;
153 if (dbgLogWriteToFile
|| dbgLogWriteToScr
) {
154 vsnprintf(buf
, sizeof(buf
), fmt
, inap
);
155 if (dbgLogPreUpdate
) dbgLogPreUpdate();
158 snprintf(timebuf
, sizeof(timebuf
), "[%05u] %04d/%02d/%02d %02d:%02d:%02d: ",
159 (unsigned int)getpid(),
160 bt
->tm_year
+1900, bt
->tm_mon
+1, bt
->tm_mday
,
161 bt
->tm_hour
, bt
->tm_min
, bt
->tm_sec
163 if (dbgLogWriteToFile
&& dbgLogFileName
[0]) {
164 FILE *outfile
= fopen(dbgLogFileName
, "ab");
166 writebuf(outfile
, buf
, timebuf
);
170 if (dbgLogWriteToScr
&& stderr
!= NULL
) writebuf(stderr
, buf
, timebuf
+13); // skip PID and year
171 if (dbgLogPostUpdate
) dbgLogPostUpdate();