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

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

pe loader fix (graceful failure when unable to find dll) + several small changes

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