source: git/src/message.c @ 2109b07

RELEASE/1.0RELEASE/1.1RELEASE/1.2debug-cidebug-ci-sanitisersfaster-cavernloglog-selectstereostereo-2025walls-datawalls-data-hanging-as-warningwarn-only-for-hanging-survey
Last change on this file since 2109b07 was 7f94ee7, checked in by Olly Betts <olly@…>, 25 years ago

Fixed stdarg issue

git-svn-id: file:///home/survex-svn/survex/trunk@388 4b37db11-9a0c-4f06-9ece-9ab7cdaee568

  • Property mode set to 100644
File size: 16.9 KB
Line 
1/* > message.c
2 * Fairly general purpose message and error routines
3 * Copyright (C) 1993-2000 Olly Betts
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
18 */
19
20/*#define DEBUG 1*/
21
22#ifdef HAVE_CONFIG_H
23# include <config.h>
24#endif
25
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <ctype.h>
30#include <limits.h>
31#include <errno.h>
32
33#include "whichos.h"
34#include "filename.h"
35#include "message.h"
36#include "osdepend.h"
37#include "filelist.h"
38#include "debug.h"
39
40#ifdef HAVE_SIGNAL
41# ifdef HAVE_SETJMP
42#  include <setjmp.h>
43static jmp_buf jmpbufSignal;
44#  include <signal.h>
45# else
46#  undef HAVE_SIGNAL
47# endif
48#endif
49
50/* This is the name of the default language -- set like this so folks can
51 * add (for eg) -DDEFAULTLANG="fr" to UFLG in the makefile
52 * FIXME - update wrt automake/autoconf
53 */
54#ifndef DEFAULTLANG
55# define DEFAULTLANG "en"
56#endif
57
58/* For funcs which want to be immune from messing around with different
59 * calling conventions */
60#ifndef CDECL
61# define CDECL
62#endif
63
64static int cWarnings = 0; /* keep track of how many warnings we've given */
65static int cErrors = 0;   /* and how many (non-fatal) errors */
66
67extern int error_summary(void) {
68   fprintf(STDERR, msg(/*There were %d warning(s) and %d non-fatal error(s).*/16),
69           cWarnings, cErrors);
70   fputnl(STDERR);
71   return (cErrors ? EXIT_FAILURE : EXIT_SUCCESS);
72}
73
74/* in case osmalloc() fails before szAppNameCopy is set up */
75const char *szAppNameCopy = "anonymous program";
76
77/* error code for failed osmalloc and osrealloc calls */
78static void
79outofmem(OSSIZE_T size)
80{
81   fatalerror(1/*Out of memory (couldn't find %lu bytes).*/, (unsigned long)size);
82}
83
84#ifdef TOMBSTONES
85#define TOMBSTONE_SIZE 16
86static char tombstone[TOMBSTONE_SIZE] = "012345\xfftombstone";
87#endif
88
89/* malloc with error catching if it fails. Also allows us to write special
90 * versions easily eg for DOS EMS or MS Windows.
91 */
92extern void FAR *
93osmalloc(OSSIZE_T size)
94{
95   void FAR *p;
96#ifdef TOMBSTONES
97   size += TOMBSTONE_SIZE * 2;
98   p = malloc(size);
99#else
100   p = xosmalloc(size);
101#endif
102   if (p == NULL) outofmem(size);
103#ifdef TOMBSTONES
104printf("osmalloc truep=%p truesize=%d\n",p,size);
105   memcpy(p, tombstone, TOMBSTONE_SIZE);
106   memcpy(p + size - TOMBSTONE_SIZE, tombstone, TOMBSTONE_SIZE);
107   *(size_t *)p = size;
108   p += TOMBSTONE_SIZE;
109#endif
110   return p;
111}
112
113/* realloc with error catching if it fails. */
114extern void FAR *
115osrealloc(void *p, OSSIZE_T size)
116{
117   /* some pre-ANSI realloc implementations don't cope with a NULL pointer */
118   if (p == NULL) {
119      p = xosmalloc(size);
120   } else {
121#ifdef TOMBSTONES
122      int true_size;
123      size += TOMBSTONE_SIZE * 2;
124      p -= TOMBSTONE_SIZE;
125      true_size = *(size_t *)p;
126printf("osrealloc (in truep=%p truesize=%d)\n",p,true_size);
127      if (memcmp(p + sizeof(size_t), tombstone + sizeof(size_t),
128                 TOMBSTONE_SIZE - sizeof(size_t)) != 0) {
129         printf("start tombstone for block %p, size %d corrupted!",
130                p + TOMBSTONE_SIZE, true_size - TOMBSTONE_SIZE * 2);     
131      }
132      if (memcmp(p + true_size - TOMBSTONE_SIZE, tombstone,
133                 TOMBSTONE_SIZE) != 0) {
134         printf("end tombstone for block %p, size %d corrupted!",
135                p + TOMBSTONE_SIZE, true_size - TOMBSTONE_SIZE * 2);     
136      }
137      p = realloc(p, size);
138      if (p == NULL) outofmem(size);
139printf("osrealloc truep=%p truesize=%d\n",p,size);
140      memcpy(p, tombstone, TOMBSTONE_SIZE);
141      memcpy(p + size - TOMBSTONE_SIZE, tombstone, TOMBSTONE_SIZE);
142      *(size_t *)p = size;
143      p += TOMBSTONE_SIZE;
144#else
145      p = xosrealloc(p, size);
146#endif
147   }
148   if (p == NULL) outofmem(size);
149   return p;
150}
151
152extern void FAR *
153osstrdup(const char *str)
154{
155   char *p;
156   OSSIZE_T len;
157   len = strlen(str) + 1;
158   p = osmalloc(len);
159   memcpy(p, str, len);
160   return p;
161}
162
163/* osfree is usually just a macro in osalloc.h */
164#ifdef TOMBSTONES
165extern void
166osfree(void *p)
167{
168   int true_size;
169   if (!p) return;
170   p -= TOMBSTONE_SIZE;
171   true_size = *(size_t *)p;
172printf("osfree truep=%p truesize=%d\n",p,true_size);
173   if (memcmp(p + sizeof(size_t), tombstone + sizeof(size_t),
174              TOMBSTONE_SIZE - sizeof(size_t)) != 0) {
175      printf("start tombstone for block %p, size %d corrupted!",
176             p + TOMBSTONE_SIZE, true_size - TOMBSTONE_SIZE * 2);     
177   }
178   if (memcmp(p + true_size - TOMBSTONE_SIZE, tombstone,
179              TOMBSTONE_SIZE) != 0) {
180      printf("end tombstone for block %p, size %d corrupted!",
181             p + TOMBSTONE_SIZE, true_size - TOMBSTONE_SIZE * 2);     
182   }
183   free(p);
184}
185#endif
186
187#ifdef HAVE_SIGNAL
188
189static int sigReceived;
190
191/* for systems not using autoconf, assume the signal handler returns void
192 * unless specified elsewhere */
193#ifndef RETSIGTYPE
194# define RETSIGTYPE void
195#endif
196
197static CDECL RETSIGTYPE FAR report_sig( int sig ) {
198   sigReceived = sig;
199   longjmp(jmpbufSignal, 1);
200}
201
202static void
203init_signals(void)
204{
205   int en;
206   if (!setjmp(jmpbufSignal)) {
207#if 0 /* FIXME: disable for now so we get a core dump */
208      signal(SIGABRT, report_sig); /* abnormal termination eg abort() */
209      signal(SIGFPE,  report_sig); /* arithmetic error eg /0 or overflow */
210      signal(SIGILL,  report_sig); /* illegal function image eg illegal instruction */
211      signal(SIGSEGV, report_sig); /* illegal storage access eg access outside memory limits */
212#endif
213      signal(SIGINT,  report_sig); /* interactive attention eg interrupt */
214      signal(SIGTERM, report_sig); /* termination request sent to program */
215# ifdef SIGSTAK /* only on RISC OS AFAIK */
216      signal(SIGSTAK, report_sig); /* stack overflow */
217# endif
218      return;
219   }
220
221   switch (sigReceived) {
222   case SIGABRT: en=90; break;
223   case SIGFPE:  en=91; break;
224   case SIGILL:  en=92; break;
225   case SIGINT:  en=93; break;
226   case SIGSEGV: en=94; break;
227   case SIGTERM: en=95; break;
228# ifdef SIGSTAK
229   case SIGSTAK: en=96; break;
230# endif
231   default:      en=97; break;
232   }
233   fputsnl(msg(en), STDERR);
234   if (errno >= 0) {
235# ifdef HAVE_STRERROR
236      fputsnl(strerror(errno), STDERR);
237# elif defined(HAVE_SYS_ERRLIST)
238      if (errno < sys_nerr) fputsnl(STDERR, sys_errlist[errno]);
239# elif defined(HAVE_PERROR)
240      perror(NULL); /* always goes to stderr */
241      /* if (arg!=NULL && *arg!='\0') fputs("<arg>: <err>\n",stderr); */
242      /* else fputs("<err>\n",stderr); */
243# else
244      fprintf(STDERR, "error code %d\n", errno);
245# endif
246   }
247   /* Any signals apart from SIGINT and SIGTERM suggest a bug */
248   if (sigReceived != SIGINT && sigReceived != SIGTERM)
249      fatalerror(/*Bug in program detected! Please report this to the authors*/11);
250
251   exit(EXIT_FAILURE);
252}
253#endif
254
255#define CHARSET_BAD       -1
256#define CHARSET_USASCII    0
257#define CHARSET_ISO_8859_1 1
258#define CHARSET_DOSCP850   2
259#define CHARSET_RISCOS31   3
260static int default_charset( void ) {
261#ifdef ISO8859_1
262   return CHARSET_ISO_8859_1;
263#elif (OS==RISCOS)
264/* RISCOS 3.1 and above CHARSET_RISCOS31 (ISO_8859_1 + extras in 128-159)
265 * RISCOS < 3.1 is ISO_8859_1 !HACK! */
266   return CHARSET_RISCOS31;
267#elif (OS==MSDOS)
268   return CHARSET_DOSCP850;
269#else
270   return CHARSET_ISO_8859_1; /* Look at env var CHARSET ? !HACK! */
271#endif
272}
273
274#if (OS==MSDOS)
275static int
276xlate_dos_cp850(int unicode)
277{
278   switch (unicode) {
279#include "uni2dos.h"
280   }
281   return 0;
282}
283#endif
284
285static int
286add_unicode(int charset, unsigned char *p, int value)
287{
288#ifdef DEBUG
289   fprintf(stderr, "add_unicode(%d, %p, %d)\n", charset, p, value);
290#endif
291   if (value == 0) return 0;
292   switch (charset) {
293   case CHARSET_USASCII:
294      if (value < 128) {
295         *p = value;
296         return 1;
297      }
298      break;
299   case CHARSET_ISO_8859_1:
300#if (OS==RISCOS)
301   case CHARSET_RISCOS31: /* RISC OS 3.1 has a few extras in 128-159 */
302#endif
303      if (value < 256) {
304         *p = value;
305         return 1;
306      }
307#if (OS==RISCOS)
308      /* FIXME: if OS version >= 3.1 handle extras here */
309      /* RISC OS 3.1 (and later) extensions to ISO-8859-1:
310       * \^y = \x86
311       * \^Y = \x85
312       * \^w = \x82
313       * \^W = \x81
314       * \oe = \x9b
315       * \OE = \x9a
316       */
317#endif
318      break;
319#if (OS==MSDOS)
320   case CHARSET_DOSCP850:
321      value = xlate_dos_cp850(value);
322      if (value) {
323         *p = value;
324         return 1;
325      }
326      break;
327#endif
328   }
329   return 0;
330}
331
332/* fall back on looking in the current directory */
333static const char *pth_cfg_files = "";
334
335static int num_msgs = 0;
336static char **msg_array = NULL;
337
338static void
339parse_msg_file(int charset_code)
340{
341   FILE *fh;
342   unsigned char header[20];
343   /*const*/ char *lang;
344   int i;
345   unsigned len;
346   unsigned char *p;
347   
348#ifdef DEBUG
349   fprintf(stderr, "parse_msg_file(%d)\n", charset_code);
350#endif
351
352   lang = getenv("SURVEXLANG");
353#ifdef DEBUG
354   fprintf(stderr, "lang = %p (= \"%s\")\n", lang, lang?lang:"(null)");
355#endif
356   
357   if (!lang || !*lang) {
358      lang = getenv("LANG");
359      if (!lang || !*lang) lang = DEFAULTLANG;
360   }
361#ifdef DEBUG
362   fprintf(stderr, "lang = %p (= \"%s\")\n", lang, lang?lang:"(null)");
363#endif
364
365#if 1
366   /* backward compatibility - FIXME deprecate? */
367   if (strcasecmp(lang, "engi") == 0) {
368      lang = "en";
369   } else if (strcasecmp(lang, "engu") == 0) {
370      lang = "en-us";
371   } else if (strcasecmp(lang, "fren") == 0) {
372      lang = "fr";
373   } else if (strcasecmp(lang, "germ") == 0) {
374      lang = "de";
375   } else if (strcasecmp(lang, "ital") == 0) {
376      lang = "it";
377   } else if (strcasecmp(lang, "span") == 0) {
378      lang = "es";
379   } else if (strcasecmp(lang, "cata") == 0) {
380      lang = "ca";
381   } else if (strcasecmp(lang, "port") == 0) {
382      lang = "pt";
383   }
384#endif
385#ifdef DEBUG
386   fprintf(stderr, "lang = %p (= \"%s\")\n", lang, lang?lang:"(null)");
387#endif
388
389   lang = osstrdup(lang);
390   /* On my RedHat 6.1 Linux box, LANG defaults to en_US - be nice and
391    * handle this... */
392   if (strchr(lang, '_')) {
393      char *under = strchr(lang, '_');
394      *under++ = '-';
395      while (*under) {
396         *under = tolower(*under);
397         under++;
398      }
399   }
400
401   fh = fopenWithPthAndExt(pth_cfg_files, lang, EXT_SVX_MSG, "rb", NULL);
402
403   if (!fh) {
404      /* e.g. if 'en-COCKNEY' is unknown, see if we know 'en' */
405      if (strlen(lang) > 3 && lang[2] == '-') {
406         char lang_generic[3];
407         lang_generic[0] = lang[0];
408         lang_generic[1] = lang[1];
409         lang_generic[2] = '\0';
410         fh = fopenWithPthAndExt(pth_cfg_files, lang_generic, EXT_SVX_MSG,
411                                 "rb", NULL);
412      }
413   }
414
415   if (!fh) {
416      /* no point extracting this error, as it won't get used if file opens */
417      fprintf(STDERR, "Can't open message file '%s' using path '%s'\n",
418              lang, pth_cfg_files);
419      exit(EXIT_FAILURE);
420   }
421
422   if (fread(header, 1, 20, fh) < 20 ||
423       memcmp(header, "Svx\nMsg\r\n\xfe\xff", 12) != 0) {
424      /* no point extracting this error, as it won't get used if file opens */
425      fprintf(STDERR, "Problem with message file '%s'\n", lang);
426      exit(EXIT_FAILURE);
427   }
428
429   if (header[12] != 0) {
430      /* no point extracting this error, as it won't get used if file opens */
431      fprintf(STDERR, "I don't understand this message file version\n");
432      exit(EXIT_FAILURE);
433   }
434
435   num_msgs = (header[14] << 8) | header[15];
436
437   len = 0;
438   for (i = 16; i < 20; i++) len = (len << 8) | header[i];
439
440   p = osmalloc(len);
441   if (fread(p, 1, len, fh) < len) {
442      /* no point extracting this error - it won't get used once file's read */
443      fprintf(STDERR, "Message file truncated?\n");
444      exit(EXIT_FAILURE);
445   }
446   fclose(fh);
447
448#ifdef DEBUG
449   fprintf(stderr, "lang = '%s', num_msgs = %d, len = %d\n", lang, num_msgs, len);
450#endif
451
452   msg_array = osmalloc(sizeof(char *) * num_msgs);
453
454   for (i = 0; i < num_msgs; i++) {
455      unsigned char *to = p;
456      int ch;
457      msg_array[i] = (char *)p;
458      while ((ch = *p++) != 0) {
459         /* A byte in the range 0x80-0xbf or 0xf0-0xff isn't valid in
460          * this state, (0xf0-0xfd mean values > 0xffff) so treat as
461          * literal and try to resync so we cope better when fed
462          * non-utf-8 data.  Similarly we abandon a multibyte sequence
463          * if we hit an invalid character. */
464         if (ch >= 0xc0 && ch < 0xf0) {
465            int ch1 = *p;
466            if ((ch1 & 0xc0) != 0x80) goto resync;
467               
468            if (ch < 0xe0) {
469               /* 2 byte sequence */
470               ch = ((ch & 0x1f) << 6) | (ch1 & 0x3f);
471               p++;
472            } else {
473               /* 3 byte sequence */
474               int ch2 = p[1];
475               if ((ch2 & 0xc0) != 0x80) goto resync;
476               ch = ((ch & 0x1f) << 12) | ((ch1 & 0x3f) << 6) | (ch2 & 0x3f);
477               p += 2;
478            }
479         }
480           
481         resync:
482           
483         if (ch < 127) {
484            *to++ = (char)ch;
485         } else {
486            /* FIXME this rather assumes a 2 byte UTF-8 code never
487             * transliterates to more than 2 characters */
488            to += add_unicode(charset_code, to, ch);
489         }
490      }
491      *to++ = '\0';
492   }
493}
494
495const char *
496msg_cfgpth(void)
497{
498   return pth_cfg_files;
499}
500
501void
502msg_init(const char *argv0)
503{
504   char *p;
505
506#ifdef HAVE_SIGNAL
507   init_signals();
508#endif
509   /* This code *should* be completely bomb-proof even if strcpy
510    * generates a signal
511    */
512   szAppNameCopy = argv0; /* FIXME... */
513   szAppNameCopy = osstrdup(argv0);
514
515   /* Look for env. var. "SURVEXHOME" or the like */
516   p = getenv("SURVEXHOME");
517   if (p && *p) {
518      pth_cfg_files = osstrdup(p);
519#if (OS==UNIX) && defined(DATADIR) && defined(PACKAGE)
520   } else {
521      /* under Unix, we compile in the configured path */
522      pth_cfg_files = DATADIR "/" PACKAGE;
523#else
524   } else if (argv0) {
525      /* else try the path on argv[0] */
526      pth_cfg_files = path_from_fnm(argv0);
527#endif
528   }
529
530   select_charset(default_charset());
531}
532
533/* message may be overwritten by next call (but not in current implementation) */
534extern const char *
535msg(int en)
536{
537   static const char *szBadEn = "???";
538
539   if (!msg_array) {
540      if (en != 1) return szBadEn;
541      /* this should be the only message which can be requested before
542       * the message file is opened and read... */
543      return "Out of memory (couldn't find %ul bytes).\n";
544   }
545
546   if (en < 0 || en >= num_msgs) return szBadEn;
547
548   return msg_array[en];
549}
550
551/* returns persistent copy of message */
552extern const char *
553msgPerm(int en)
554{
555   return msg(en);
556}
557
558void
559v_report(int severity, const char *fnm, int line, int en, va_list ap)
560{
561   if (fnm) {
562      fputs(fnm, STDERR);
563      if (line) fprintf(STDERR, ":%d", line);
564   } else {
565      fputs(szAppNameCopy, STDERR);
566   }   
567   fputs(": ", STDERR);
568
569   if (severity == 0) {
570      fputs(msg(/*warning*/4), STDERR);
571      fputs(": ", STDERR);
572   }
573
574   vfprintf(STDERR, msg(en), ap);
575   fputnl(STDERR);
576   
577   /* FIXME allow "warnings are errors" and/or "errors are fatal" */
578   switch (severity) {
579    case 0:
580      cWarnings++;
581      break;
582    case 1:
583      cErrors++;
584      if (cErrors == 50)
585         fatalerror_in_file(fnm, 0, /*Too many errors - giving up*/19);
586      break;
587    case 2:
588      exit(EXIT_FAILURE);
589   }
590}
591
592void
593warning(int en, ...)
594{
595   va_list ap;
596   va_start(ap, en);
597   v_report(0, NULL, 0, en, ap);
598   va_end(ap);
599}
600
601void
602error(int en, ...)
603{
604   va_list ap;
605   va_start(ap, en);
606   v_report(1, NULL, 0, en, ap);
607   va_end(ap);
608}
609
610void
611fatalerror(int en, ...)
612{
613   va_list ap;
614   va_start(ap, en);
615   v_report(2, NULL, 0, en, ap);
616   va_end(ap);
617}
618
619void
620warning_in_file(const char *fnm, int line, int en, ...)
621{
622   va_list ap;
623   va_start(ap, en);
624   v_report(0, fnm, line, en, ap);
625   va_end(ap);
626}
627
628void
629error_in_file(const char *fnm, int line, int en, ...)
630{
631   va_list ap;
632   va_start(ap, en);
633   v_report(1, fnm, line, en, ap);
634   va_end(ap);
635}
636
637void
638fatalerror_in_file(const char *fnm, int line, int en, ...)
639{
640   va_list ap;
641   va_start(ap, en);
642   v_report(2, fnm, line, en, ap);
643   va_end(ap);
644}
645
646/* Code to support switching character set at runtime (e.g. for a printer
647 * driver to support different character sets on screen and on the printer)
648 */
649typedef struct charset_li {
650   struct charset_li *next;
651   int code;
652   char **msg_array;
653} charset_li;
654
655static charset_li *charset_head = NULL;
656
657static int charset = CHARSET_BAD;
658
659int
660select_charset(int charset_code)
661{
662   int old_charset = charset;
663   charset_li *p;
664
665#ifdef DEBUG
666   fprintf(stderr, "select_charset(%d), old charset = %d\n", charset_code, charset);
667#endif
668   
669   charset = charset_code;
670
671   /* check if we've already parsed messages for new charset */
672   for (p = charset_head; p; p = p->next) {
673#ifdef DEBUG
674      printf("%p: code %d msg_array %p\n", p, p->code, p->msg_array);
675#endif
676      if (p->code == charset) {
677         msg_array = p->msg_array;
678         return old_charset;
679      }
680   }
681
682   /* nope, got to reparse message file */
683   parse_msg_file(charset_code);
684
685   /* add to list */
686   p = osnew(charset_li);
687   p->code = charset;
688   p->msg_array = msg_array;
689   p->next = charset_head;
690   charset_head = p;
691
692   return old_charset;
693}
Note: See TracBrowser for help on using the repository browser.