source: git/src/message.c @ 0087185

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

Change '...' to `...' in messages; .svx file reading errors now fatal;
unattached survey error now fatal; syntax errors in survex wrapper now
fatal.

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

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