source: git/src/message.c @ 9539d38

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 9539d38 was b4ab19e, checked in by Olly Betts <olly@…>, 26 years ago

And tolower the "US" in en_US

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

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