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

Last change on this file since 4658 was 4658, checked in by sandervl, 25 years ago

Updates for TEB changes

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