source: trunk/src/kernel32/misc.cpp@ 5624

Last change on this file since 5624 was 5624, checked in by sandervl, 24 years ago

dprintf(NULL) flushes log stream

File size: 22.6 KB
Line 
1/* $Id: misc.cpp,v 1.35 2001-04-28 16:14:54 sandervl Exp $ */
2
3/*
4 * Project Odin Software License can be found in LICENSE.TXT
5 * Logging procedures
6 *
7 * Copyright 1998 Sander van Leeuwen (sandervl@xs4all.nl)
8 * Copyright 1998 Joel Troster
9 * Copyright 1998 Peter FitzSimmons
10 *
11 */
12
13
14/*****************************************************************************
15 * Includes *
16 *****************************************************************************/
17
18#define INCL_BASE
19#define INCL_WIN
20#define INCL_WINERRORS
21#define INCL_DOSFILEMGR
22#include <os2wrap.h> //Odin32 OS/2 api wrappers
23#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <stdarg.h>
27#include <win32type.h>
28#include <win32api.h>
29#include <misc.h>
30#include "initterm.h"
31#include "logging.h"
32#include "exceptutil.h"
33#include <wprocess.h>
34#include <versionos2.h>
35
36/*****************************************************************************
37 * PMPRINTF Version *
38 *****************************************************************************/
39
40#ifdef PMPRINTF
41
42/* ----- Customization variables ----- */
43#define PRINTFID ""
44#define PRINTFMAXLEN 300
45#define PRINTFLINELEN 100
46#define PRINTFTHREADS 54
47#define PRINTFQNAME "\\QUEUES\\PRINTF32"
48
49/* ----- Includes and externals ----- */
50#include <stddef.h> /* .. */
51#include <time.h> /* .. */
52
53extern ULONG flAllocMem; /*Tue 03.03.1998: knut */
54
55/* ----- Local defines ----- */
56#define PRINTFIDSIZE sizeof(PRINTFID)
57#define PRINTFMAXBUF PRINTFIDSIZE+PRINTFLINELEN
58
59
60/*****************************************************************************
61 * Structures *
62 *****************************************************************************/
63
64/* ----- Per-thread output buffer and current indices into line ---- */
65struct perthread {
66 LONG lineindex; /* where next char */
67 LONG tidemark; /* rightmost char */
68 int bell; /* TRUE if line has bell */
69 UCHAR line[PRINTFMAXBUF]; /* accumulator */
70 };
71
72/* ----- Local static variables ----- */
73static ULONG ourpid=0; /* our process ID */
74static ULONG servepid=0; /* process IDs of the server */
75static HQUEUE qhandle=0; /* handle for the queue */
76static struct perthread *tps[PRINTFTHREADS+1]; /* -> per-thread data */
77
78/* ----- Local subroutine ----- */
79static int printf_(struct perthread *);
80
81
82/* ----------------------------------------------------------------- */
83/* The "printf" function. Note this has a variable number of */
84/* arguments. */
85/* ----------------------------------------------------------------- */
86int SYSTEM WriteLog(char *f, ...)
87 {
88 TIB *ptib; /* process/thread id structures */
89 PIB *ppib; /* .. */
90 TID ourtid; /* thread ID */
91 struct perthread *tp; /* pointer to per-thread data */
92 int rc; /* returncode */
93 ULONG urc; /* returncode */
94
95 urc=DosOpenQueue(&servepid, &qhandle, PRINTFQNAME); /* Open the Q */
96 /* Non-0 RC means Q does not exist or cannot be opened */
97 if (urc==343) return 0; /* queue does not exist, so quit */
98 if (urc!=0) return -1; /* report any other error */
99
100 /* First determine our thread ID (and hence get access to the */
101 /* correct per-thread data. If the per-thread data has not been */
102 /* allocated, then allocate it now. It is never freed, once */
103 /* allocated, as PRINTF is not notified of end-of-thread. */
104 DosGetInfoBlocks(&ptib,&ppib); /* get process/thread info */
105 ourtid=ptib->tib_ptib2->tib2_ultid; /* .. and copy TID */
106 if (ourtid>PRINTFTHREADS) /* too many threads .. */
107 return 0; /* .. so quit, quietly */
108 tp=tps[ourtid]; /* copy to local pointer */
109 if (tp==NULL) { /* uninitialized (NULL=0) */
110 /* allocate a per-thread structure */
111 tp=(struct perthread *)malloc(sizeof(struct perthread));
112 if (tp==NULL) return -1; /* out of memory -- return error */
113 tps[ourtid]=tp; /* save for future calls */
114 strcpy(tp->line,PRINTFID); /* initialize: line.. */
115 tp->lineindex=PRINTFIDSIZE-1; /* ..where next char */
116 tp->tidemark =PRINTFIDSIZE-2; /* ..rightmost char */
117 tp->bell=FALSE; /* ..if line has bell */
118 if (ourpid==0) ourpid=ppib->pib_ulpid; /* save PID for all to use */
119 }
120
121 { /* Block for declarations -- only needed if queue exists, etc. */
122 LONG count; /* count of characters formatted */
123 UCHAR buffer[PRINTFMAXLEN+1]; /* formatting area */
124 LONG i, newind; /* work */
125 UCHAR ch; /* .. */
126 va_list argptr; /* -> variable argument list */
127
128 va_start(argptr, f); /* get pointer to argument list */
129 count=vsprintf(buffer, f, argptr);
130 va_end(argptr); /* done with variable arguments */
131
132 if (count<0) return count-1000;/* bad start */
133
134 if (count>PRINTFMAXLEN) {
135 /* Disaster -- we are probably "dead", but just in case we */
136 /* are not, carry on with truncated data. */
137 count=PRINTFMAXLEN;
138 }
139 buffer[count]='\0'; /* ensure terminated */
140 /* OK, ready to go with the data now in BUFFER */
141 /* We copy from the formatted string to the output (line) buffer, */
142 /* taking note of certain control characters and sending a line */
143 /* the queue whenever we see a LF control, or when the line */
144 /* fills (causing a forced break). */
145 for (i=0; ; i++) {
146 ch=buffer[i]; if (!ch) break;
147 switch(ch) {
148 case '\r': /* carriage return */
149 tp->lineindex=PRINTFIDSIZE-1; /* back to start of line */
150 break;
151 case '\n': /* new line */
152 case '\f': /* form feed */
153 rc=printf_(tp); /* print a line */
154 if (rc!=0) return rc; /* error */
155 break;
156 case '\t': /* tab */
157 newind=tp->lineindex-PRINTFIDSIZE+1; /* offset into data */
158 newind=tp->lineindex+5-newind%5; /* new index requested */
159 if (newind>=PRINTFMAXBUF) newind=PRINTFMAXBUF; /* clamp */
160 for (; tp->lineindex<newind; tp->lineindex++) {
161 if (tp->lineindex>tp->tidemark) { /* beyond current end */
162 tp->line[tp->lineindex]=' '; /* add space */
163 tp->tidemark=tp->lineindex;
164 }
165 }
166 break;
167 case '\v': /* vertical tab */
168 /* ignore it */
169 break;
170 case '\b': /* backspace */
171 tp->lineindex=max(tp->lineindex-1,PRINTFIDSIZE);
172 break;
173 case '\a': /* alert (bell) */
174 tp->bell=TRUE;
175 break;
176 default: /* ordinary character */
177 tp->line[tp->lineindex]=ch;
178 if (tp->lineindex>tp->tidemark) /* is rightmost.. */
179 tp->tidemark=tp->lineindex;
180 tp->lineindex++; /* step for next */
181 } /* switch */
182 if (tp->lineindex>=PRINTFMAXBUF) {
183 rc=printf_(tp); /* print a line */
184 if (rc!=0) return rc; /* error */
185 }
186
187 } /* copy loop */
188 return count; /* all formatted data processed */
189 } /* block */
190 } /* printf */
191
192/* ----- printf_(tp) -- Local subroutine to send a line ------------ */
193/* A line has been completed (or overflowed): write it to the queue. */
194int printf_(struct perthread *tp) /* pointer to per-thread data */
195 {
196 ULONG urc; /* unsigned returncode */
197 PSZ pszTo, pszFrom; /* character pointers */
198 PVOID addr; /* address of output data */
199 long size; /* total size of output data */
200 time_t timenow; /* holds current time */
201
202 tp->line[tp->tidemark+1]='\0'; /* add terminator */
203 size=tp->tidemark+2; /* total length of data */
204
205 /* Get some shared memory that can be given away */
206 urc=DosAllocSharedMem(&addr, NULL, (unsigned)size,
207 OBJ_GIVEABLE|PAG_WRITE|PAG_COMMIT|flAllocMem);
208 /*knut: added flAllocMem */
209
210 if (urc!=0) return -2; /* error */
211
212 pszTo=addr; /* copy for clarity */
213 pszFrom=&(tp->line[0]); /* pointer to source */
214 strcpy(pszTo,pszFrom); /* copy the string to shared memory */
215
216 if (ourpid!=servepid) { /* (no giveaway needed if to self) */
217 urc=DosGiveSharedMem(addr, servepid, PAG_READ); /* give access */
218 if (urc!=0) return -3;} /* error */
219
220 /* Write the selector, size, and timestamp to the queue */
221 if (tp->bell) size=-size; /* BELL passed by negation */
222 time(&timenow); /* optional - else use 0 */
223 urc=DosWriteQueue(qhandle, /* handle */
224 (unsigned)timenow, /* 'request' (timestamp) */
225 (unsigned)size, /* 'length' (length/bell) */
226 addr, /* 'address' (address) */
227 0); /* priority (FIFO if enabled) */
228 if (urc!=0) return -4; /* error */
229 if (ourpid!=servepid) { /* if given away.. */
230 urc=DosFreeMem(addr); /* .. *we* are done with it */
231 if (urc!=0) return -5;} /* error */
232 /* Reset the line buffer and indices */
233 tp->lineindex=PRINTFIDSIZE-1; /* where next char */
234 tp->tidemark =PRINTFIDSIZE-2; /* rightmost char */
235 tp->bell =FALSE; /* true if line has bell */
236 return 0; /* success! */
237 } /* printf_ */
238#endif
239
240
241
242/*****************************************************************************
243 * Standard Version *
244 *****************************************************************************/
245
246static FILE *flog = NULL; /*PLF Mon 97-09-08 20:00:15*/
247static BOOL init = FALSE;
248static BOOL fLogging = TRUE;
249static int dwEnableLogging = 1;
250static int oldcrtmsghandle = 0;
251
252static BOOL fDisableThread[5] = {0};
253
254#define CHECK_ODINHEAP
255#if defined(DEBUG) && defined(CHECK_ODINHEAP)
256int checkOdinHeap = 1;
257int checkingheap = 0;
258#define ODIN_HEAPCHECK() \
259 if(checkingheap) checkOdinHeap = 0; \
260 checkingheap++; \
261 if(checkOdinHeap) _heap_check(); \
262 checkingheap--;
263#else
264#define ODIN_HEAPCHECK()
265#endif
266
267//#define LOG_TIME
268
269int SYSTEM WriteLog(char *tekst, ...)
270{
271 USHORT sel = RestoreOS2FS();
272 va_list argptr;
273 TEB *teb = GetThreadTEB();
274
275 ODIN_HEAPCHECK();
276
277 if(!init)
278 {
279 init = TRUE;
280
281#ifdef DEFAULT_LOGGING_OFF
282 if(getenv("WIN32LOG_ENABLED")) {
283#else
284 if(!getenv("NOWIN32LOG")) {
285#endif
286 char logname[CCHMAXPATH];
287
288 sprintf(logname, "odin32_%d.log", loadNr);
289 flog = fopen(logname, "w");
290 if(flog == NULL) {//probably running exe on readonly device
291 sprintf(logname, "%sodin32_%d.log", kernel32Path, loadNr);
292 flog = fopen(logname, "w");
293 }
294 oldcrtmsghandle = _set_crt_msg_handle(fileno(flog));
295 }
296 else
297 fLogging = FALSE;
298
299 if(getenv("DISABLE_THREAD1")) {
300 fDisableThread[0] = TRUE;
301 }
302 if(getenv("DISABLE_THREAD2")) {
303 fDisableThread[1] = TRUE;
304 }
305 if(getenv("DISABLE_THREAD3")) {
306 fDisableThread[2] = TRUE;
307 }
308 if(getenv("DISABLE_THREAD4")) {
309 fDisableThread[3] = TRUE;
310 }
311 if(getenv("DISABLE_THREAD5")) {
312 fDisableThread[4] = TRUE;
313 }
314 }
315
316 if(teb) {
317 if(teb->o.odin.threadId < 5 && fDisableThread[teb->o.odin.threadId-1] == 1) {
318 SetFS(sel);
319 return 1;
320 }
321 }
322
323 if(!tekst) {
324 fflush( flog);
325 SetFS(sel);
326 return 1;
327 }
328
329 if(fLogging && flog && (dwEnableLogging > 0))
330 {
331 va_start(argptr, tekst);
332 if(teb) {
333 teb->o.odin.logfile = (DWORD)flog;
334#ifdef LOG_TIME
335 if(sel == 0x150b && !fIsOS2Image) {
336 fprintf(flog, "t%d: (%x) (FS=150B) ", teb->o.odin.threadId, GetTickCount());
337 }
338 else fprintf(flog, "t%d: (%x) ", teb->o.odin.threadId, GetTickCount());
339#else
340 if(sel == 0x150b && !fIsOS2Image) {
341 fprintf(flog, "t%d: (FS=150B) ", teb->o.odin.threadId);
342 }
343 else fprintf(flog, "t%d: ", teb->o.odin.threadId);
344#endif
345 }
346#ifdef LOG_TIME
347 else {
348 fprintf(flog, "tX: (%x) ", GetTickCount());
349 }
350#endif
351 vfprintf(flog, tekst, argptr);
352 if(teb) teb->o.odin.logfile = 0;
353 va_end(argptr);
354
355 if(tekst[strlen(tekst)-1] != '\n')
356 fprintf(flog, "\n");
357 }
358 fflush(flog);
359 SetFS(sel);
360 return 1;
361}
362//******************************************************************************
363//******************************************************************************
364int SYSTEM WriteLogNoEOL(char *tekst, ...)
365{
366 USHORT sel = RestoreOS2FS();
367 va_list argptr;
368
369 ODIN_HEAPCHECK();
370
371 if(!init)
372 {
373 init = TRUE;
374
375#ifdef DEFAULT_LOGGING_OFF
376 if(getenv("WIN32LOG_ENABLED")) {
377#else
378 if(!getenv("NOWIN32LOG")) {
379#endif
380 char logname[CCHMAXPATH];
381
382 sprintf(logname, "odin32_%d.log", loadNr);
383 flog = fopen(logname, "w");
384 if(flog == NULL) {//probably running exe on readonly device
385 sprintf(logname, "%sodin32_%d.log", kernel32Path, loadNr);
386 flog = fopen(logname, "w");
387 }
388 }
389 else
390 fLogging = FALSE;
391 }
392
393 if(fLogging && flog && (dwEnableLogging > 0))
394 {
395 TEB *teb = GetThreadTEB();
396
397 va_start(argptr, tekst);
398 if(teb) {
399 teb->o.odin.logfile = (DWORD)flog;
400 }
401 vfprintf(flog, tekst, argptr);
402 if(teb) teb->o.odin.logfile = 0;
403 va_end(argptr);
404 }
405 SetFS(sel);
406 return 1;
407}
408//******************************************************************************
409//******************************************************************************
410void SYSTEM DecreaseLogCount()
411{
412 dwEnableLogging--;
413}
414//******************************************************************************
415//******************************************************************************
416void SYSTEM IncreaseLogCount()
417{
418 dwEnableLogging++;
419}
420//******************************************************************************
421//******************************************************************************
422int SYSTEM WritePrivateLog(void *logfile, char *tekst, ...)
423{
424 USHORT sel = RestoreOS2FS();
425 va_list argptr;
426
427 if(fLogging && logfile)
428 {
429 TEB *teb = GetThreadTEB();
430
431 va_start(argptr, tekst);
432 if(teb) {
433 teb->o.odin.logfile = (DWORD)flog;
434 }
435 vfprintf((FILE *)logfile, tekst, argptr);
436 if(teb) teb->o.odin.logfile = 0;
437 va_end(argptr);
438
439 if(tekst[strlen(tekst)-1] != '\n')
440 fprintf((FILE *)logfile, "\n");
441 }
442
443 SetFS(sel);
444 return 1;
445}
446//******************************************************************************
447//WriteLog has to take special care to handle dprintfs inside our os/2 exception
448//handler; if an exception occurs inside a dprintf, using dprintf in the exception
449//handler will hang the process
450//******************************************************************************
451void LogException(int state)
452{
453 TEB *teb = GetThreadTEB();
454
455 if (!teb) return;
456
457#if !defined(__EMX__)
458 if (teb->o.odin.logfile)
459 {
460#if (__IBMCPP__ == 300) || (__IBMC__ == 300)
461 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
462#else
463#if __IBMC__ >= 360 || __IBMCPP__ >= 360
464//TODO: test this!!!!!!!
465 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
466#else
467#error Check the offset of the lock count word in the file stream structure for this compiler revision!!!!!
468#endif
469#endif
470 if (state == ENTER_EXCEPTION)
471 {
472 (*lock)--;
473 }
474 else
475 { //LEAVE_EXCEPTION
476 (*lock)++;
477 }
478 }
479#else
480//kso 2001-01-29: EMX/GCC
481// we maybe should do something with the _more->rsem (_rmutex) structure but
482// I wanna have this compile, so we'll address problems later.
483#endif
484}
485//******************************************************************************
486//Check if the exception occurred inside a fprintf (logging THDB member set)
487//If true, decrease the lock count for that file stream
488//NOTE: HACK: DEPENDS ON COMPILER VERSION!!!!
489//******************************************************************************
490void CheckLogException()
491{
492 TEB *teb = GetThreadTEB();
493 PUSHORT lock;
494
495 if(!teb) return;
496
497#if !defined(__EMX__)
498 if(teb->o.odin.logfile) {
499 //oops, exception in vfprintf; let's clear the lock count
500#if (__IBMCPP__ == 300) || (__IBMC__ == 300)
501 lock = (PUSHORT)(teb->o.odin.logfile+0x1C);
502#else
503#if __IBMC__ >= 360 || __IBMCPP__ >= 360
504//TODO: test this!!!!!!!
505 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
506#else
507#error Check the offset of the lock count word in the file stream structure for this compiler revision!!!!!
508#endif
509#endif
510 (*lock)--;
511 }
512#else
513//kso 2001-01-29: EMX/GCC
514// we maybe should do something with the _more->rsem (_rmutex) structure but
515// I wanna have this compile, so we'll address problems later.
516#endif
517}
518//******************************************************************************
519//NOTE: No need to save/restore FS, as our FS selectors have already been
520// destroyed and FS == 0x150B.
521//******************************************************************************
522void CloseLogFile()
523{
524 if(oldcrtmsghandle)
525 _set_crt_msg_handle(oldcrtmsghandle);
526
527 fclose(flog);
528 flog = 0;
529}
530//******************************************************************************
531//Used to open any private logfiles used in kernel32 (for now only in winimagepeldr.cpp)
532//******************************************************************************
533void OpenPrivateLogFiles()
534{
535#ifdef DEFAULT_LOGGING_OFF
536 if(getenv("WIN32LOG_ENABLED")) {
537#else
538 if(!getenv("NOWIN32LOG")) {
539#endif
540 OpenPrivateLogFilePE();
541 }
542}
543//******************************************************************************
544//Used to close all private logfiles used in kernel32 (for now only in winimagepeldr.cpp)
545//******************************************************************************
546void ClosePrivateLogFiles()
547{
548#ifdef DEFAULT_LOGGING_OFF
549 if(getenv("WIN32LOG_ENABLED")) {
550#else
551 if(!getenv("NOWIN32LOG")) {
552#endif
553 ClosePrivateLogFilePE();
554 }
555}
556//******************************************************************************
557//******************************************************************************
558int SYSTEM WriteLogError(char *tekst, ...)
559{
560 USHORT sel = RestoreOS2FS();
561 va_list argptr;
562
563 va_start(argptr, tekst);
564 printf("ERROR: ");
565 vprintf(tekst, argptr);
566 va_end(argptr);
567 if(tekst[strlen(tekst)-1] != '\n')
568 printf("\n");
569
570 SetFS(sel);
571 return 1;
572}
573//******************************************************************************
574//******************************************************************************
575void SYSTEM CheckVersion(ULONG version, char *modname)
576{
577 dprintf(("CheckVersion of %s, %d\n", modname, version));
578 if(version != PE2LX_VERSION){
579 static char msg[300];
580 int r;
581 dprintf(("Version mismatch! %d, %d: %s\n", version, PE2LX_VERSION, modname));
582 sprintf(msg, "%s is intended for use with a different release of Odin.\n", modname);
583 do{
584 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, msg, "Version Mismatch!", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
585 }while(r == MBID_RETRY); // giggle
586 if( r != MBID_IGNORE )
587 exit(987);
588 }
589}
590//******************************************************************************
591//******************************************************************************
592void SYSTEM CheckVersionFromHMOD(ULONG version, HMODULE hModule)
593{
594 char name[_MAX_PATH];
595
596 // query name of dll.
597 if(!DosQueryModuleName(hModule, sizeof(name), name))
598 CheckVersion(version, name);
599}
600//******************************************************************************
601//******************************************************************************
602#ifdef __WATCOMC__ /*PLF Sat 97-06-21 17:12:36*/
603 extern void interrupt3( void );
604 #pragma aux interrupt3= \
605 "int 3"
606#endif
607void WIN32API DebugBreak()
608{
609 dprintf(("DebugBreak\n"));
610
611 LPSTR lpstrEnv = getenv("WIN32.DEBUGBREAK"); /* query environment */
612 if (lpstrEnv == NULL) /* if environment is not set, don't call debugger ! */
613 return;
614
615#ifdef __WATCOMC__
616 interrupt3();
617#else
618 _interrupt(3);
619#endif
620}
621//******************************************************************************
622//******************************************************************************
623
624
625/*****************************************************************************
626 * Name : DebugErrorBox
627 * Purpose : display an apprioriate error box with detailed information
628 * about the error cause
629 * Parameters: APIRET iErrorCode - OS/2 error code
630 * PSZ pszFormat - printf-format string
631 * ...
632 * Variables :
633 * Result : return code of the message box
634 * Remark :
635 * Status :
636 *
637 * Author : Patrick Haller [Tue, 1999/09/13 19:55]
638 *****************************************************************************/
639
640int SYSTEM DebugErrorBox(ULONG iErrorCode,
641 char* pszFormat,
642 ...)
643{
644 char szMessageBuffer[1024]; /* buffer for the text message */
645 char szErrorBuffer[1024]; /* buffer for the operating system text */
646 ULONG bc; /* dummy */
647 APIRET rc2; /* API returncode */
648 int iRC; /* message box return code */
649
650 USHORT sel = RestoreOS2FS();
651 va_list argptr;
652
653 // clear memory
654 memset (szMessageBuffer, 0, sizeof(szMessageBuffer));
655 memset (szErrorBuffer, 0, sizeof(szErrorBuffer));
656
657 // build message string
658 va_start(argptr, pszFormat);
659 vsprintf(szMessageBuffer, pszFormat, argptr);
660 va_end(argptr);
661
662 // query error string
663 rc2 = DosGetMessage(NULL,
664 0,
665 szErrorBuffer,
666 sizeof(szErrorBuffer),
667 iErrorCode,
668 "OSO001.MSG",
669 &bc);
670
671 // display message box
672 iRC = WinMessageBox(HWND_DESKTOP,
673 NULLHANDLE,
674 szMessageBuffer,
675 szErrorBuffer,
676 0,
677 MB_OK | MB_ICONEXCLAMATION | MB_MOVEABLE);
678 SetFS(sel);
679 return iRC;
680}
Note: See TracBrowser for help on using the repository browser.