source: git/src/message.c @ 57c18b4c

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

Fixed up untested code from China so "make check" passes.

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

  • Property mode set to 100644
File size: 16.6 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 = (char*) 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 0 /* 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# ifdef SIGSTAK /* only on RISC OS AFAIK */
210      signal(SIGSTAK, report_sig); /* stack overflow */
211# endif
212      return;
213   }
214
215   switch (sigReceived) {
216      case SIGABRT: en = /*Abnormal termination*/90; break;
217      case SIGFPE:  en = /*Arithmetic error*/91; break;
218      case SIGILL:  en = /*Illegal instruction*/92; break;
219      case SIGSEGV: en = /*Bad memory access*/94; break;
220# ifdef SIGSTAK
221      case SIGSTAK: en = /*Stack overflow*/96; break;
222# endif
223      default:      en = /*Unknown signal received*/97; break;
224   }
225   fputsnl(msg(en), STDERR);
226
227   /* Any of the signals we catch indicates a bug */
228   fatalerror(/*Bug in program detected! Please report this to the authors*/11);
229
230   exit(EXIT_FAILURE);
231}
232#endif
233
234static int
235default_charset(void)
236{
237#if (OS==RISCOS)
238   /* RISCOS 3.1 and above CHARSET_RISCOS31 (ISO_8859_1 + extras in 128-159)
239    * RISCOS < 3.1 is ISO_8859_1 */
240 
241   if (xwimpreadsysinfo_version(&version) != NULL) {
242      /* RISC OS 2 or some error (don't care which) */
243      return CHARSET_ISO_8859_1;
244   }
245
246   /* oddly wimp_VERSION_RO3 is RISC OS 3.1 */
247   if (version < wimp_VERSION_RO3) return CHARSET_ISO_8859_1;
248     
249   return CHARSET_RISCOS31;
250#elif (OS==MSDOS)
251   return CHARSET_DOSCP850;
252#else
253   /* FIXME: assume ISO_8859_1 for now */
254   return CHARSET_ISO_8859_1;
255#endif
256}
257
258#if (OS==MSDOS)
259static int
260xlate_dos_cp850(int unicode)
261{
262   switch (unicode) {
263#include "uni2dos.h"
264   }
265   return 0;
266}
267#endif
268
269static int
270add_unicode(int charset, unsigned char *p, int value)
271{
272#ifdef DEBUG
273   fprintf(stderr, "add_unicode(%d, %p, %d)\n", charset, p, value);
274#endif
275   if (value == 0) return 0;
276   switch (charset) {
277   case CHARSET_USASCII:
278      if (value < 0x80) {
279         *p = value;
280         return 1;
281      }
282      break;
283   case CHARSET_ISO_8859_1:
284      if (value < 0x100) {
285         *p = value;
286         return 1;
287      }
288      break;
289#if (OS==RISCOS)
290   case CHARSET_RISCOS31:
291      /* RISC OS 3.1 (and later) extensions to ISO-8859-1 */
292      switch (value) {
293       case 0x152: value = 0x9a; break; /* &OElig; */
294       case 0x153: value = 0x9b; break; /* &oelig; */
295       case 0x174: value = 0x81; break; /* &Wcirc; */
296       case 0x175: value = 0x82; break; /* &wcirc; */
297       case 0x176: value = 0x85; break; /* &Ycirc; */
298       case 0x177: value = 0x86; break; /* &ycirc; */
299      }
300      if (value < 0x100) {
301         *p = value;
302         return 1;
303      }
304      break;
305#endif
306#if (OS==MSDOS)
307   case CHARSET_DOSCP850:
308      value = xlate_dos_cp850(value);
309      if (value) {
310         *p = value;
311         return 1;
312      }
313      break;
314#endif
315   }
316   return 0;
317}
318
319/* fall back on looking in the current directory */
320#ifdef _WIN32
321static const char *pth_cfg_files = "C:\\";
322#else
323static const char *pth_cfg_files = "";
324#endif
325
326static int num_msgs = 0;
327static char **msg_array = NULL;
328
329const char *msg_lang = NULL;
330const char *msg_lang2 = NULL;
331
332static void
333parse_msg_file(int charset_code)
334{
335   FILE *fh;
336   unsigned char header[20];
337   int i;
338   unsigned len;
339   unsigned char *p;
340   char *fnm, *s;
341
342#ifdef DEBUG
343   fprintf(stderr, "parse_msg_file(%d)\n", charset_code);
344#endif
345
346#ifdef _WIN32
347   fnm = (char*) osstrdup("messages");
348#else
349   fnm = (char*) osstrdup(msg_lang);
350#endif
351   /* trim off charset from stuff like "de_DE.iso8859_1" */
352   s = strchr(fnm, '.');
353   if (s) *s = '\0';
354
355   fh = fopenWithPthAndExt(pth_cfg_files, fnm, EXT_SVX_MSG, "rb", NULL);
356
357   if (!fh) {
358      /* e.g. if 'en-COCKNEY' is unknown, see if we know 'en' */
359      if (strlen(fnm) > 3 && fnm[2] == '-') {
360         fnm[2] = '\0';
361         fh = fopenWithPthAndExt(pth_cfg_files, fnm, EXT_SVX_MSG, "rb", NULL);
362         if (!fh) fnm[2] = '-'; /* for error reporting */
363      }
364   }
365
366   if (!fh) {
367      /* no point extracting this error as it won't get used if file opens */
368      fprintf(STDERR, "Can't open message file `%s' using path `%s'\n",
369              fnm, pth_cfg_files);
370      exit(EXIT_FAILURE);
371   }
372
373   if (fread(header, 1, 20, fh) < 20 ||
374       memcmp(header, "Svx\nMsg\r\n\xfe\xff", 12) != 0) {
375      /* no point extracting this error as it won't get used if file opens */
376      fprintf(STDERR, "Problem with message file `%s'\n", fnm);
377      exit(EXIT_FAILURE);
378   }
379
380   if (header[12] != 0) {
381      /* no point extracting this error as it won't get used if file opens */
382      fprintf(STDERR, "I don't understand this message file version\n");
383      exit(EXIT_FAILURE);
384   }
385
386   num_msgs = (header[14] << 8) | header[15];
387
388   len = 0;
389   for (i = 16; i < 20; i++) len = (len << 8) | header[i];
390
391   p = (unsigned char*) osmalloc(len);
392   if (fread(p, 1, len, fh) < len) {
393      /* no point extracting this error - translation will never be used */
394      fprintf(STDERR, "Message file truncated?\n");
395      exit(EXIT_FAILURE);
396   }
397   fclose(fh);
398
399#ifdef DEBUG
400   fprintf(stderr, "fnm = `%s', num_msgs = %d, len = %d\n", fnm, num_msgs, len);
401#endif
402   osfree(fnm);
403
404   msg_array = (char**) osmalloc(sizeof(char *) * num_msgs);
405
406   for (i = 0; i < num_msgs; i++) {
407      unsigned char *to = p;
408      int ch;
409      msg_array[i] = (char *)p;
410
411      /* If we want UTF8 anyway, we just need to find the start of each
412       * message */
413      if (charset_code == CHARSET_UTF8) {
414         p += strlen((char *)p) + 1;
415         continue;
416      }
417
418      while ((ch = *p++) != 0) {
419         /* A byte in the range 0x80-0xbf or 0xf0-0xff isn't valid in
420          * this state, (0xf0-0xfd mean values > 0xffff) so treat as
421          * literal and try to resync so we cope better when fed
422          * non-utf-8 data.  Similarly we abandon a multibyte sequence
423          * if we hit an invalid character. */
424         if (ch >= 0xc0 && ch < 0xf0) {
425            int ch1 = *p;
426            if ((ch1 & 0xc0) != 0x80) goto resync;
427
428            if (ch < 0xe0) {
429               /* 2 byte sequence */
430               ch = ((ch & 0x1f) << 6) | (ch1 & 0x3f);
431               p++;
432            } else {
433               /* 3 byte sequence */
434               int ch2 = p[1];
435               if ((ch2 & 0xc0) != 0x80) goto resync;
436               ch = ((ch & 0x1f) << 12) | ((ch1 & 0x3f) << 6) | (ch2 & 0x3f);
437               p += 2;
438            }
439         }
440
441         resync:
442
443         if (ch < 127) {
444            *to++ = (char)ch;
445         } else {
446            /* FIXME: this rather assumes a 2 byte UTF-8 code never
447             * transliterates to more than 2 characters */
448            to += add_unicode(charset_code, to, ch);
449         }
450      }
451      *to++ = '\0';
452   }
453}
454
455const char *
456msg_cfgpth(void)
457{
458   return pth_cfg_files;
459}
460
461void
462msg_init(const char *argv0)
463{
464   char *p;
465
466#ifdef HAVE_SIGNAL
467   init_signals();
468#endif
469   /* Point to argv0 itself so we get the app name correct if osstrdup()
470    * generates a signal */
471   szAppNameCopy = argv0;
472   szAppNameCopy = (char*) osstrdup(argv0);
473
474#ifndef _WIN32
475
476   /* Look for env. var. "SURVEXHOME" or the like */
477   p = getenv("SURVEXHOME");
478   if (p && *p) {
479      pth_cfg_files = (char*) osstrdup(p);
480#if (OS==UNIX) && defined(DATADIR) && defined(PACKAGE)
481   } else {
482      /* under Unix, we compile in the configured path */
483      pth_cfg_files = DATADIR "/" PACKAGE;
484#else
485   } else if (argv0) {
486      /* else try the path on argv[0] */
487      pth_cfg_files = path_from_fnm(argv0);
488#endif
489   }
490
491#endif
492
493   msg_lang = getenv("SURVEXLANG");
494#ifdef DEBUG
495   fprintf(stderr, "lang = %p (= \"%s\")\n", lang, lang?lang:"(null)");
496#endif
497
498   if (!msg_lang || !*msg_lang) {
499      msg_lang = getenv("LANG");
500      if (!msg_lang || !*msg_lang) msg_lang = DEFAULTLANG;
501   }
502#ifdef DEBUG
503   fprintf(stderr, "msg_lang = %p (= \"%s\")\n", msg_lang, msg_lang?msg_lang:"(null)");
504#endif
505
506   /* On Mandrake LANG defaults to C */
507   if (strcmp(msg_lang, "C") == 0) msg_lang = "en";
508
509   msg_lang = (char*) osstrdup(msg_lang);
510
511   /* Convert en-us to en_US, etc */
512   p = strchr(msg_lang, '-');
513   if (p) {
514      *p++ = '_';
515      while (*p) {
516         *p = toupper(*p);
517         p++;
518      }
519   }
520
521   p = strchr(msg_lang, '_');
522   if (p) {
523      *p = '\0';
524      msg_lang2 = (char*) osstrdup(msg_lang);
525      *p = '_';
526   }
527
528#ifdef LC_MESSAGES
529   /* try to setlocale() appropriately too */
530   if (!setlocale(LC_MESSAGES, msg_lang)) {
531      if (msg_lang2) setlocale(LC_MESSAGES, msg_lang2);
532   }
533#endif
534
535   select_charset(default_charset());
536}
537
538/* message may be overwritten by next call
539 * (but not in current implementation) */
540const char *
541msg(int en)
542{
543   /* NB can't use ASSERT here! */
544   static char badbuf[256];
545   if (!msg_array) {
546      if (en != 1)  {
547         sprintf(badbuf, "Message %d requested before msg_array initialised\n", en);
548         return badbuf;
549      }
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) {
556      sprintf(badbuf, "Message %d out of range\n", en);
557      return badbuf;
558   }
559
560   return msg_array[en];
561}
562
563/* returns persistent copy of message */
564const char *
565msgPerm(int en)
566{
567   return msg(en);
568}
569
570void
571v_report(int severity, const char *fnm, int line, int en, va_list ap)
572{
573   if (fnm) {
574      fputs(fnm, STDERR);
575      if (line) fprintf(STDERR, ":%d", line);
576   } else {
577      fputs(szAppNameCopy, STDERR);
578   }
579   fputs(": ", STDERR);
580
581   if (severity == 0) {
582      fputs(msg(/*warning*/4), STDERR);
583      fputs(": ", STDERR);
584   }
585
586   vfprintf(STDERR, msg(en), ap);
587   fputnl(STDERR);
588
589   switch (severity) {
590    case 0:
591      msg_warnings++;
592      break;
593    case 1:
594      msg_errors++;
595      if (msg_errors == 50)
596         fatalerror_in_file(fnm, 0, /*Too many errors - giving up*/19);
597      break;
598    case 2:
599      exit(EXIT_FAILURE);
600   }
601}
602
603void
604warning(int en, ...)
605{
606   va_list ap;
607   va_start(ap, en);
608   v_report(0, NULL, 0, en, ap);
609   va_end(ap);
610}
611
612void
613error(int en, ...)
614{
615   va_list ap;
616   va_start(ap, en);
617   v_report(1, NULL, 0, en, ap);
618   va_end(ap);
619}
620
621void
622fatalerror(int en, ...)
623{
624   va_list ap;
625   va_start(ap, en);
626   v_report(2, NULL, 0, en, ap);
627   va_end(ap);
628}
629
630void
631warning_in_file(const char *fnm, int line, int en, ...)
632{
633   va_list ap;
634   va_start(ap, en);
635   v_report(0, fnm, line, en, ap);
636   va_end(ap);
637}
638
639void
640error_in_file(const char *fnm, int line, int en, ...)
641{
642   va_list ap;
643   va_start(ap, en);
644   v_report(1, fnm, line, en, ap);
645   va_end(ap);
646}
647
648void
649fatalerror_in_file(const char *fnm, int line, int en, ...)
650{
651   va_list ap;
652   va_start(ap, en);
653   v_report(2, fnm, line, en, ap);
654   va_end(ap);
655}
656
657/* Code to support switching character set at runtime (e.g. for a printer
658 * driver to support different character sets on screen and on the printer)
659 */
660typedef struct charset_li {
661   struct charset_li *next;
662   int code;
663   char **msg_array;
664} charset_li;
665
666static charset_li *charset_head = NULL;
667
668static int charset = CHARSET_BAD;
669
670int
671select_charset(int charset_code)
672{
673   int old_charset = charset;
674   charset_li *p;
675
676#ifdef DEBUG
677   fprintf(stderr, "select_charset(%d), old charset = %d\n", charset_code,
678           charset);
679#endif
680
681   charset = charset_code;
682
683   /* check if we've already parsed messages for new charset */
684   for (p = charset_head; p; p = p->next) {
685#ifdef DEBUG
686      printf("%p: code %d msg_array %p\n", p, p->code, p->msg_array);
687#endif
688      if (p->code == charset) {
689         msg_array = p->msg_array;
690         return old_charset;
691      }
692   }
693
694   /* nope, got to reparse message file */
695   parse_msg_file(charset_code);
696
697   /* add to list */
698   p = osnew(charset_li);
699   p->code = charset;
700   p->msg_array = msg_array;
701   p->next = charset_head;
702   charset_head = p;
703
704   return old_charset;
705}
Note: See TracBrowser for help on using the repository browser.