source: git/src/message.c @ b3756e0

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 b3756e0 was b3756e0, checked in by Olly Betts <olly@…>, 24 years ago

Better internationalisation - select localised system messages using
setlocale().

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

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