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

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

LoadLibrary change: refuse to load non-Odin OS/2 dlls

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