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

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

Update for VAC 3.6.5

File size: 21.5 KB
Line 
1/* $Id: misc.cpp,v 1.30 2001-02-11 10:34:44 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 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 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 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 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
404 if (!teb) return;
405
406#if !defined(__EMX__)
407 if (teb->o.odin.logfile)
408 {
409#if (__IBMCPP__ == 300) || (__IBMC__ == 300)
410 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
411#else
412#if __IBMC__ >= 360 || __IBMCPP__ >= 360
413//TODO: test this!!!!!!!
414 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
415#else
416#error Check the offset of the lock count word in the file stream structure for this compiler revision!!!!!
417#endif
418#endif
419 if (state == ENTER_EXCEPTION)
420 {
421 (*lock)--;
422 }
423 else
424 { //LEAVE_EXCEPTION
425 (*lock)++;
426 }
427 }
428#else
429//kso 2001-01-29: EMX/GCC
430// we maybe should do something with the _more->rsem (_rmutex) structure but
431// I wanna have this compile, so we'll address problems later.
432#endif
433}
434//******************************************************************************
435//Check if the exception occurred inside a fprintf (logging THDB member set)
436//If true, decrease the lock count for that file stream
437//NOTE: HACK: DEPENDS ON COMPILER VERSION!!!!
438//******************************************************************************
439void CheckLogException()
440{
441 TEB *teb = GetThreadTEB();
442 PUSHORT lock;
443
444 if(!teb) return;
445
446#if !defined(__EMX__)
447 if(teb->o.odin.logfile) {
448 //oops, exception in vfprintf; let's clear the lock count
449#if (__IBMCPP__ == 300) || (__IBMC__ == 300)
450 lock = (PUSHORT)(teb->o.odin.logfile+0x1C);
451#else
452#if __IBMC__ >= 360 || __IBMCPP__ >= 360
453//TODO: test this!!!!!!!
454 PUSHORT lock = (USHORT *)(teb->o.odin.logfile+0x1C);
455#else
456#error Check the offset of the lock count word in the file stream structure for this compiler revision!!!!!
457#endif
458#endif
459 (*lock)--;
460 }
461#else
462//kso 2001-01-29: EMX/GCC
463// we maybe should do something with the _more->rsem (_rmutex) structure but
464// I wanna have this compile, so we'll address problems later.
465#endif
466}
467//******************************************************************************
468//NOTE: No need to save/restore FS, as our FS selectors have already been
469// destroyed and FS == 0x150B.
470//******************************************************************************
471void CloseLogFile()
472{
473 if(oldcrtmsghandle)
474 _set_crt_msg_handle(oldcrtmsghandle);
475
476 fclose(flog);
477 flog = 0;
478}
479//******************************************************************************
480//Used to open any private logfiles used in kernel32 (for now only in winimagepeldr.cpp)
481//******************************************************************************
482void OpenPrivateLogFiles()
483{
484#ifdef DEFAULT_LOGGING_OFF
485 if(getenv("WIN32LOG_ENABLED")) {
486#else
487 if(!getenv("NOWIN32LOG")) {
488#endif
489 OpenPrivateLogFilePE();
490 }
491}
492//******************************************************************************
493//Used to close all private logfiles used in kernel32 (for now only in winimagepeldr.cpp)
494//******************************************************************************
495void ClosePrivateLogFiles()
496{
497#ifdef DEFAULT_LOGGING_OFF
498 if(getenv("WIN32LOG_ENABLED")) {
499#else
500 if(!getenv("NOWIN32LOG")) {
501#endif
502 ClosePrivateLogFilePE();
503 }
504}
505//******************************************************************************
506//******************************************************************************
507int SYSTEM WriteLogError(char *tekst, ...)
508{
509 USHORT sel = RestoreOS2FS();
510 va_list argptr;
511
512 va_start(argptr, tekst);
513 printf("ERROR: ");
514 vprintf(tekst, argptr);
515 va_end(argptr);
516 if(tekst[strlen(tekst)-1] != '\n')
517 printf("\n");
518
519 SetFS(sel);
520 return 1;
521}
522//******************************************************************************
523//******************************************************************************
524void SYSTEM CheckVersion(ULONG version, char *modname)
525{
526 dprintf(("CheckVersion of %s, %d\n", modname, version));
527 if(version != PE2LX_VERSION){
528 static char msg[300];
529 int r;
530 dprintf(("Version mismatch! %d, %d: %s\n", version, PE2LX_VERSION, modname));
531 sprintf(msg, "%s is intended for use with a different release of PE2LX.\n", modname);
532 do{
533 r = WinMessageBox(HWND_DESKTOP, NULLHANDLE, msg, "Version Mismatch!", 0, MB_ABORTRETRYIGNORE | MB_ICONEXCLAMATION | MB_MOVEABLE);
534 }while(r == MBID_RETRY); // giggle
535 if( r != MBID_IGNORE )
536 exit(987);
537 }
538}
539//******************************************************************************
540//******************************************************************************
541void SYSTEM CheckVersionFromHMOD(ULONG version, HMODULE hModule)
542{
543 char name[_MAX_PATH];
544
545 // query name of dll.
546 if(!DosQueryModuleName(hModule, sizeof(name), name))
547 CheckVersion(version, name);
548}
549//******************************************************************************
550//******************************************************************************
551#ifdef __WATCOMC__ /*PLF Sat 97-06-21 17:12:36*/
552 extern void interrupt3( void );
553 #pragma aux interrupt3= \
554 "int 3"
555#endif
556void WIN32API DebugBreak()
557{
558 dprintf(("DebugBreak\n"));
559
560 LPSTR lpstrEnv = getenv("WIN32.DEBUGBREAK"); /* query environment */
561 if (lpstrEnv == NULL) /* if environment is not set, don't call debugger ! */
562 return;
563
564#ifdef __WATCOMC__
565 interrupt3();
566#else
567 _interrupt(3);
568#endif
569}
570//******************************************************************************
571//******************************************************************************
572
573
574/*****************************************************************************
575 * Name : DebugErrorBox
576 * Purpose : display an apprioriate error box with detailed information
577 * about the error cause
578 * Parameters: APIRET iErrorCode - OS/2 error code
579 * PSZ pszFormat - printf-format string
580 * ...
581 * Variables :
582 * Result : return code of the message box
583 * Remark :
584 * Status :
585 *
586 * Author : Patrick Haller [Tue, 1999/09/13 19:55]
587 *****************************************************************************/
588
589int SYSTEM DebugErrorBox(ULONG iErrorCode,
590 char* pszFormat,
591 ...)
592{
593 char szMessageBuffer[1024]; /* buffer for the text message */
594 char szErrorBuffer[1024]; /* buffer for the operating system text */
595 ULONG bc; /* dummy */
596 APIRET rc2; /* API returncode */
597 int iRC; /* message box return code */
598
599 USHORT sel = RestoreOS2FS();
600 va_list argptr;
601
602 // clear memory
603 memset (szMessageBuffer, 0, sizeof(szMessageBuffer));
604 memset (szErrorBuffer, 0, sizeof(szErrorBuffer));
605
606 // build message string
607 va_start(argptr, pszFormat);
608 vsprintf(szMessageBuffer, pszFormat, argptr);
609 va_end(argptr);
610
611 // query error string
612 rc2 = DosGetMessage(NULL,
613 0,
614 szErrorBuffer,
615 sizeof(szErrorBuffer),
616 iErrorCode,
617 "OSO001.MSG",
618 &bc);
619
620 // display message box
621 iRC = WinMessageBox(HWND_DESKTOP,
622 NULLHANDLE,
623 szMessageBuffer,
624 szErrorBuffer,
625 0,
626 MB_OK | MB_ICONEXCLAMATION | MB_MOVEABLE);
627 SetFS(sel);
628 return iRC;
629}
Note: See TracBrowser for help on using the repository browser.