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

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

writelog update for disabling logging for threads

File size: 22.4 KB
Line 
1/* $Id: misc.cpp,v 1.33 2001-03-21 12:32:55 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;
257#define ODIN_HEAPCHECK() if(checkOdinHeap) _heap_check();
258#else
259#define ODIN_HEAPCHECK()
260#endif
261
262//#define LOG_TIME
263
264int SYSTEM WriteLog(char *tekst, ...)
265{
266 USHORT sel = RestoreOS2FS();
267 va_list argptr;
268 TEB *teb = GetThreadTEB();
269
270 ODIN_HEAPCHECK();
271
272 if(!init)
273 {
274 init = TRUE;
275
276#ifdef DEFAULT_LOGGING_OFF
277 if(getenv("WIN32LOG_ENABLED")) {
278#else
279 if(!getenv("NOWIN32LOG")) {
280#endif
281 char logname[CCHMAXPATH];
282
283 sprintf(logname, "odin32_%d.log", loadNr);
284 flog = fopen(logname, "w");
285 if(flog == NULL) {//probably running exe on readonly device
286 sprintf(logname, "%sodin32_%d.log", kernel32Path, loadNr);
287 flog = fopen(logname, "w");
288 }
289 oldcrtmsghandle = _set_crt_msg_handle(fileno(flog));
290 }
291 else
292 fLogging = FALSE;
293
294 if(getenv("DISABLE_THREAD1")) {
295 fDisableThread[0] = TRUE;
296 }
297 if(getenv("DISABLE_THREAD2")) {
298 fDisableThread[1] = TRUE;
299 }
300 if(getenv("DISABLE_THREAD3")) {
301 fDisableThread[2] = TRUE;
302 }
303 if(getenv("DISABLE_THREAD4")) {
304 fDisableThread[3] = TRUE;
305 }
306 if(getenv("DISABLE_THREAD5")) {
307 fDisableThread[4] = TRUE;
308 }
309 }
310
311 if(teb) {
312 if(teb->o.odin.threadId < 5 && fDisableThread[teb->o.odin.threadId-1] == 1) {
313 SetFS(sel);
314 return 1;
315 }
316 }
317
318 if(fLogging && flog && (dwEnableLogging > 0))
319 {
320 va_start(argptr, tekst);
321 if(teb) {
322 teb->o.odin.logfile = (DWORD)flog;
323#ifdef LOG_TIME
324 if(sel == 0x150b && !fIsOS2Image) {
325 fprintf(flog, "t%d: (%x) (FS=150B) ", teb->o.odin.threadId, GetTickCount());
326 }
327 else fprintf(flog, "t%d: (%x) ", teb->o.odin.threadId, GetTickCount());
328#else
329 if(sel == 0x150b && !fIsOS2Image) {
330 fprintf(flog, "t%d: (FS=150B) ", teb->o.odin.threadId);
331 }
332 else fprintf(flog, "t%d: ", teb->o.odin.threadId);
333#endif
334 }
335#ifdef LOG_TIME
336 else {
337 fprintf(flog, "tX: (%x) ", GetTickCount());
338 }
339#endif
340 vfprintf(flog, tekst, argptr);
341 if(teb) teb->o.odin.logfile = 0;
342 va_end(argptr);
343
344 if(tekst[strlen(tekst)-1] != '\n')
345 fprintf(flog, "\n");
346 }
347 SetFS(sel);
348 return 1;
349}
350//******************************************************************************
351//******************************************************************************
352int SYSTEM WriteLogNoEOL(char *tekst, ...)
353{
354 USHORT sel = RestoreOS2FS();
355 va_list argptr;
356
357 ODIN_HEAPCHECK();
358
359 if(!init)
360 {
361 init = TRUE;
362
363#ifdef DEFAULT_LOGGING_OFF
364 if(getenv("WIN32LOG_ENABLED")) {
365#else
366 if(!getenv("NOWIN32LOG")) {
367#endif
368 char logname[CCHMAXPATH];
369
370 sprintf(logname, "odin32_%d.log", loadNr);
371 flog = fopen(logname, "w");
372 if(flog == NULL) {//probably running exe on readonly device
373 sprintf(logname, "%sodin32_%d.log", kernel32Path, loadNr);
374 flog = fopen(logname, "w");
375 }
376 }
377 else
378 fLogging = FALSE;
379 }
380
381 if(fLogging && flog && (dwEnableLogging > 0))
382 {
383 TEB *teb = GetThreadTEB();
384
385 va_start(argptr, tekst);
386 if(teb) {
387 teb->o.odin.logfile = (DWORD)flog;
388 }
389 vfprintf(flog, tekst, argptr);
390 if(teb) teb->o.odin.logfile = 0;
391 va_end(argptr);
392 }
393 SetFS(sel);
394 return 1;
395}
396//******************************************************************************
397//******************************************************************************
398void SYSTEM DecreaseLogCount()
399{
400 dwEnableLogging--;
401}
402//******************************************************************************
403//******************************************************************************
404void SYSTEM IncreaseLogCount()
405{
406 dwEnableLogging++;
407}
408//******************************************************************************
409//******************************************************************************
410int SYSTEM WritePrivateLog(void *logfile, char *tekst, ...)
411{
412 USHORT sel = RestoreOS2FS();
413 va_list argptr;
414
415 if(fLogging && logfile)
416 {
417 TEB *teb = GetThreadTEB();
418
419 va_start(argptr, tekst);
420 if(teb) {
421 teb->o.odin.logfile = (DWORD)flog;
422 }
423 vfprintf((FILE *)logfile, tekst, argptr);
424 if(teb) teb->o.odin.logfile = 0;
425 va_end(argptr);
426
427 if(tekst[strlen(tekst)-1] != '\n')
428 fprintf((FILE *)logfile, "\n");
429 }
430
431 SetFS(sel);
432 return 1;
433}
434//******************************************************************************
435//WriteLog has to take special care to handle dprintfs inside our os/2 exception
436//handler; if an exception occurs inside a dprintf, using dprintf in the exception
437//handler will hang the process
438//******************************************************************************
439void LogException(int state)
440{
441 TEB *teb = GetThreadTEB();
442
443 if (!teb) return;
444
445#if !defined(__EMX__)
446 if (teb->o.odin.logfile)
447 {
448#if (__IBMCPP__ == 300) || (__IBMC__ == 300)
449 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
450#else
451#if __IBMC__ >= 360 || __IBMCPP__ >= 360
452//TODO: test this!!!!!!!
453 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
454#else
455#error Check the offset of the lock count word in the file stream structure for this compiler revision!!!!!
456#endif
457#endif
458 if (state == ENTER_EXCEPTION)
459 {
460 (*lock)--;
461 }
462 else
463 { //LEAVE_EXCEPTION
464 (*lock)++;
465 }
466 }
467#else
468//kso 2001-01-29: EMX/GCC
469// we maybe should do something with the _more->rsem (_rmutex) structure but
470// I wanna have this compile, so we'll address problems later.
471#endif
472}
473//******************************************************************************
474//Check if the exception occurred inside a fprintf (logging THDB member set)
475//If true, decrease the lock count for that file stream
476//NOTE: HACK: DEPENDS ON COMPILER VERSION!!!!
477//******************************************************************************
478void CheckLogException()
479{
480 TEB *teb = GetThreadTEB();
481 PUSHORT lock;
482
483 if(!teb) return;
484
485#if !defined(__EMX__)
486 if(teb->o.odin.logfile) {
487 //oops, exception in vfprintf; let's clear the lock count
488#if (__IBMCPP__ == 300) || (__IBMC__ == 300)
489 lock = (PUSHORT)(teb->o.odin.logfile+0x1C);
490#else
491#if __IBMC__ >= 360 || __IBMCPP__ >= 360
492//TODO: test this!!!!!!!
493 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
494#else
495#error Check the offset of the lock count word in the file stream structure for this compiler revision!!!!!
496#endif
497#endif
498 (*lock)--;
499 }
500#else
501//kso 2001-01-29: EMX/GCC
502// we maybe should do something with the _more->rsem (_rmutex) structure but
503// I wanna have this compile, so we'll address problems later.
504#endif
505}
506//******************************************************************************
507//NOTE: No need to save/restore FS, as our FS selectors have already been
508// destroyed and FS == 0x150B.
509//******************************************************************************
510void CloseLogFile()
511{
512 if(oldcrtmsghandle)
513 _set_crt_msg_handle(oldcrtmsghandle);
514
515 fclose(flog);
516 flog = 0;
517}
518//******************************************************************************
519//Used to open any private logfiles used in kernel32 (for now only in winimagepeldr.cpp)
520//******************************************************************************
521void OpenPrivateLogFiles()
522{
523#ifdef DEFAULT_LOGGING_OFF
524 if(getenv("WIN32LOG_ENABLED")) {
525#else
526 if(!getenv("NOWIN32LOG")) {
527#endif
528 OpenPrivateLogFilePE();
529 }
530}
531//******************************************************************************
532//Used to close all private logfiles used in kernel32 (for now only in winimagepeldr.cpp)
533//******************************************************************************
534void ClosePrivateLogFiles()
535{
536#ifdef DEFAULT_LOGGING_OFF
537 if(getenv("WIN32LOG_ENABLED")) {
538#else
539 if(!getenv("NOWIN32LOG")) {
540#endif
541 ClosePrivateLogFilePE();
542 }
543}
544//******************************************************************************
545//******************************************************************************
546int SYSTEM WriteLogError(char *tekst, ...)
547{
548 USHORT sel = RestoreOS2FS();
549 va_list argptr;
550
551 va_start(argptr, tekst);
552 printf("ERROR: ");
553 vprintf(tekst, argptr);
554 va_end(argptr);
555 if(tekst[strlen(tekst)-1] != '\n')
556 printf("\n");
557
558 SetFS(sel);
559 return 1;
560}
561//******************************************************************************
562//******************************************************************************
563void SYSTEM CheckVersion(ULONG version, char *modname)
564{
565 dprintf(("CheckVersion of %s, %d\n", modname, version));
566 if(version != PE2LX_VERSION){
567 static char msg[300];
568 int r;
569 dprintf(("Version mismatch! %d, %d: %s\n", version, PE2LX_VERSION, modname));
570 sprintf(msg, "%s is intended for use with a different release of Odin.\n", modname);
571 do{
572 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, msg, "Version Mismatch!", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
573 }while(r == MBID_RETRY); // giggle
574 if( r != MBID_IGNORE )
575 exit(987);
576 }
577}
578//******************************************************************************
579//******************************************************************************
580void SYSTEM CheckVersionFromHMOD(ULONG version, HMODULE hModule)
581{
582 char name[_MAX_PATH];
583
584 // query name of dll.
585 if(!DosQueryModuleName(hModule, sizeof(name), name))
586 CheckVersion(version, name);
587}
588//******************************************************************************
589//******************************************************************************
590#ifdef __WATCOMC__ /*PLF Sat 97-06-21 17:12:36*/
591 extern void interrupt3( void );
592 #pragma aux interrupt3= \
593 "int 3"
594#endif
595void WIN32API DebugBreak()
596{
597 dprintf(("DebugBreak\n"));
598
599 LPSTR lpstrEnv = getenv("WIN32.DEBUGBREAK"); /* query environment */
600 if (lpstrEnv == NULL) /* if environment is not set, don't call debugger ! */
601 return;
602
603#ifdef __WATCOMC__
604 interrupt3();
605#else
606 _interrupt(3);
607#endif
608}
609//******************************************************************************
610//******************************************************************************
611
612
613/*****************************************************************************
614 * Name : DebugErrorBox
615 * Purpose : display an apprioriate error box with detailed information
616 * about the error cause
617 * Parameters: APIRET iErrorCode - OS/2 error code
618 * PSZ pszFormat - printf-format string
619 * ...
620 * Variables :
621 * Result : return code of the message box
622 * Remark :
623 * Status :
624 *
625 * Author : Patrick Haller [Tue, 1999/09/13 19:55]
626 *****************************************************************************/
627
628int SYSTEM DebugErrorBox(ULONG iErrorCode,
629 char* pszFormat,
630 ...)
631{
632 char szMessageBuffer[1024]; /* buffer for the text message */
633 char szErrorBuffer[1024]; /* buffer for the operating system text */
634 ULONG bc; /* dummy */
635 APIRET rc2; /* API returncode */
636 int iRC; /* message box return code */
637
638 USHORT sel = RestoreOS2FS();
639 va_list argptr;
640
641 // clear memory
642 memset (szMessageBuffer, 0, sizeof(szMessageBuffer));
643 memset (szErrorBuffer, 0, sizeof(szErrorBuffer));
644
645 // build message string
646 va_start(argptr, pszFormat);
647 vsprintf(szMessageBuffer, pszFormat, argptr);
648 va_end(argptr);
649
650 // query error string
651 rc2 = DosGetMessage(NULL,
652 0,
653 szErrorBuffer,
654 sizeof(szErrorBuffer),
655 iErrorCode,
656 "OSO001.MSG",
657 &bc);
658
659 // display message box
660 iRC = WinMessageBox(HWND_DESKTOP,
661 NULLHANDLE,
662 szMessageBuffer,
663 szErrorBuffer,
664 0,
665 MB_OK | MB_ICONEXCLAMATION | MB_MOVEABLE);
666 SetFS(sel);
667 return iRC;
668}
Note: See TracBrowser for help on using the repository browser.