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

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

removed test fflush call

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