source: git/src/message.c @ 1d44389

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 1d44389 was a2f9d5c, checked in by Olly Betts <olly@…>, 25 years ago

Language used for messages available to other modules in msg_lang.

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

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