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

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

HeapReAlloc change

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