source: git/src/message.c @ 8d07761

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

LC_MESSAGES is POSIX, but not ANSI so check it's defined before trying
to use it.

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

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