Debian Codegraph @

texk/xdvik/util.c

raw
1 /*========================================================================*\
2
3 Copyright (c) 1990-2022 Paul Vojta and others
4
5 Permission is hereby granted, free of charge, to any person obtaining a copy
6 of this software and associated documentation files (the "Software"), to
7 deal in the Software without restriction, including without limitation the
8 rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9 sell copies of the Software, and to permit persons to whom the Software is
10 furnished to do so, subject to the following conditions:
11
12 The above copyright notice and this permission notice shall be included in
13 all copies or substantial portions of the Software.
14
15 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
18 PAUL VOJTA OR ANY OTHER AUTHOR OF THIS SOFTWARE BE LIABLE FOR ANY CLAIM,
19 DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
20 ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
21 OTHER DEALINGS IN THE SOFTWARE.
22
23 NOTE:
24 xdvi is based on prior work, as noted in the modification history
25 in xdvi.c.
26
27 \*========================================================================*/
28
29 #include "xdvi-config.h"
30
31 #include <sys/types.h> /* ZLB: must be before sys/socket.h for IRIX 5.3 */
32 #include <sys/socket.h>
33 #include <sys/file.h> /* this defines FASYNC */
34 #include <sys/ioctl.h> /* this defines SIOCSPGRP and FIOASYNC */
35 #include <sys/wait.h> /* this defines WIFEXITED and WEXITSTATUS */
36
37 #include "xdvi.h"
38 #include "hypertex.h"
39 #include "dvi-init.h"
40 #include "special.h"
41 #include "string-utils.h"
42
43 #include "kpathsea/tex-file.h"
44
45 #include "events.h"
46 #include "util.h"
47 #include "x_util.h"
48 #include "message-window.h"
49 #include "search-internal.h"
50 #include "encodings.h"
51 #include "filehist.h"
52 #include "xm_prefs.h" /* for preferences_changed() */
53
54 #include <errno.h>
55
56 #ifndef HAVE_MEMICMP
57 #include <ctype.h>
58 #endif
59
60 #ifdef VMS
61 #include <rmsdef.h>
62 #endif /* VMS */
63
64 #ifdef X_NOT_STDC_ENV
65 extern int errno;
66 extern void *malloc();
67 extern void *realloc();
68 #endif
69
70
71 #ifdef DOPRNT /* define this if vfprintf gives you trouble */
72 #define vfprintf(stream, message, args) _doprnt(message, args, stream)
73 #endif
74
75 #ifdef VMS
76 #include <rmsdef.h>
77 #endif /* VMS */
78
79 #ifdef X_NOT_STDC_ENV
80 extern int errno;
81 extern void *malloc();
82 extern void *realloc();
83 #endif
84
85 #if HAVE_XKB_BELL_EXT
86 # include <X11/XKBlib.h>
87 # define XBell(dpy, percent) XkbBell(dpy, mane.win, percent, (Atom) None)
88 #endif
89
90 /* if POSIX O_NONBLOCK is not available, use O_NDELAY */
91 #if !defined O_NONBLOCK && defined O_NDELAY
92 # define O_NONBLOCK O_NDELAY
93 #endif
94
95 /* Linux prefers O_ASYNC over FASYNC; SGI IRIX does the opposite. */
96 #if !defined(FASYNC) && defined(O_ASYNC)
97 # define FASYNC O_ASYNC
98 #endif
99
100 #if !defined(FLAKY_SIGPOLL) && !HAVE_STREAMS && !defined(FASYNC)
101 # if !defined(SIOCSPGRP) || !defined(FIOASYNC)
102 # define FLAKY_SIGPOLL 1
103 # endif
104 #endif
105
106 #if !FLAKY_SIGPOLL && HAVE_STREAMS
107 # include <stropts.h>
108
109 # ifndef S_RDNORM
110 # define S_RDNORM S_INPUT
111 # endif
112
113 # ifndef S_RDBAND
114 # define S_RDBAND 0
115 # endif
116
117 # ifndef S_HANGUP
118 # define S_HANGUP 0
119 # endif
120
121 # ifndef S_WRNORM
122 # define S_WRNORM S_OUTPUT
123 # endif
124
125 #endif /* not FLAKY_SIGPOLL && HAVE_STREAMS */
126
127 #include <sys/param.h>
128 #include <sys/stat.h>
129 #include <pwd.h>
130 #include <errno.h>
131
132 #ifndef MAXSYMLINKS /* Workaround for Linux libc 4.x/5.x */
133 #define MAXSYMLINKS 5
134 #endif
135
136 #if HAVE_ICONV_H
137 #include <iconv.h>
138 #endif
139
140 #include <locale.h>
141
142 #if USE_LANGINFO
143 #include <langinfo.h>
144 #endif
145
146 #define BUF_SIZE 1024
147
148 void
149 xdvi_assert(const char *version,
150 const char *filename,
151 int lineno,
152 Boolean condition,
153 const char *fmt, ...)
154 {
155 if (!(condition)) {
156 va_list argp;
157 fprintf(stderr,
158 "\n************************************************************\n"
159 "XDvi %s: Failed assertion:\n%s:%d: ",
160 version, filename, lineno);
161 va_start(argp, fmt);
162 (void)vfprintf(stderr, fmt, argp);
163 va_end(argp);
164 #ifdef NDEBUG
165 fprintf(stderr,
166 "\nAborting now. Please report this as a bug to:\n"
167 "http://sourceforge.net/tracker/?group_id=23164&atid=377580\n"
168 "If a core dump has been produced, please invoke:\n"
169 "gdb %s core\nThen type \"bt\", "
170 "and include the resulting output in your bug report.\n"
171 "************************************************************\n",
172 globals.program_name);
173 do_abort();
174 #else
175 fprintf(stderr,
176 "\nPlease report this as a bug to:\n"
177 "http://sourceforge.net/tracker/?group_id=23164&atid=377580\n"
178 "************************************************************\n");
179 #endif
180 }
181 }
182
183
184 void
185 xdvi_bell(void)
186 {
187 if (!resource.hush_bell) {
188 XBell(DISP, 0);
189 }
190 }
191
192
193
194 /* NOTE: keep this table in sync with the #defines in xdvi-debug.h! */
195 struct debug_string_options debug_options[] = {
196 { DBG_BITMAP, "bitmap", ", " },
197 { DBG_DVI, "dvi", ", " },
198 { DBG_PK, "pk", ", " },
199 { DBG_BATCH, "batch", ", " },
200 { DBG_EVENT, "events", ", " },
201 { DBG_PS, "ps", ",\n"},
202 { DBG_STAT, "stat", ", " },
203 { DBG_HASH, "hash", ", " },
204 { DBG_OPEN, "open", ", " },
205 { DBG_PATHS, "paths", ", " },
206 { DBG_EXPAND, "expand", ", " },
207 { DBG_SEARCH, "search", ", " },
208 { DBG_KPATHSEA, "kpathsea", ",\n"},
209 { DBG_HTEX, "htex", ", " },
210 { DBG_SRC_SPECIALS,"src", ", " },
211 { DBG_CLIENT, "client", ", " },
212 { DBG_FT, "ft", ", " },
213 { DBG_FT_VERBOSE, "ft_verbose", ",\n"},
214 { DBG_GUI, "gui", ", " },
215 { DBG_FIND, "find", ", " },
216 { DBG_FILES, "files", ", " },
217 { DBG_ALL, "all", "\n" },
218 /* end marker */
219 { 0, NULL, NULL }
220 };
221
222 /*
223 * General utility routines.
224 */
225
226 /*
227 * 2-step fopen using close_a_file() if first opening attempt fails with
228 * `too many open files'.
229 */
230 FILE *
231 try_fopen(const char *fname, const char *mode)
232 {
233 FILE *fp = fopen(fname, mode);
234 if (fp == NULL && (errno == EMFILE || errno == ENFILE)) {
235 close_a_file();
236 fp = fopen(fname, mode);
237 }
238 return fp;
239 }
240
241 /*
242 * Like try_fopen(), for fdopen().
243 */
244 FILE *
245 try_fdopen(int fd, const char *mode)
246 {
247 FILE *fp = fdopen(fd, mode);
248 if (fp == NULL && (errno == EMFILE || errno == ENFILE)) {
249 close_a_file();
250 fp = fdopen(fd, mode);
251 }
252 return fp;
253 }
254
255
256 /*
257 * Like try_fopen(), for open().
258 */
259 int
260 try_open(const char *fname, int flags)
261 {
262 int fd = open(fname, flags);
263 if (fd < 0 && (errno == EMFILE || errno == ENFILE)) {
264 close_a_file();
265 fd = open(fname, flags);
266 }
267 return fd;
268 }
269
270 /*
271 * Like try_fopen(), for open() with 3 arguments.
272 */
273 int
274 try_open_mode(const char *fname, int flags, mode_t mode)
275 {
276 int fd = open(fname, flags, mode);
277 if (fd < 0 && (errno == EMFILE || errno == ENFILE)) {
278 close_a_file();
279 fd = open(fname, flags, mode);
280 }
281 return fd;
282 }
283
284 /*
285 * Like try_fopen(), for dup().
286 */
287 int
288 try_dup(int oldfd)
289 {
290 int fd = dup(oldfd);
291 if (fd < 0 && (errno == EMFILE || errno == ENFILE)) {
292 close_a_file();
293 fd = dup(oldfd);
294 }
295 return fd;
296 }
297
298
299 /*
300 * invoked on SIGSEGV: try to stop gs before aborting, to prevent gs
301 * running on with 100% CPU consumption - this can be annoying during
302 * testing. We'd also like to clean up the "xdvi windows" property in
303 * the root window, but it might be already too late to talk to the
304 * X server here (the code can also be triggered by X errors).
305 */
306 void
307 do_abort(void)
308 {
309 #if PS
310 ps_destroy();
311 #endif
312 /* if (globals.widgets.top_level) */
313 /* exit_clean_windows(); */
314 abort();
315 }
316
317 /*
318 Expand leading ~ or ~user in path to the actual homedirectory of the user.
319 Returns either NULL if unsuccessful, or result in freshly allocated string.
320 Bugs: ~user doesn't work with NIS/yellow pages.
321 */
322 char *
323 expand_homedir(const char *path)
324 {
325 char *resolved = NULL;
326 const char *orig_path = path;
327 UNUSED(orig_path); /* if HAVE_GETPWNAM or HAVE_GETPWUID && HAVE_GETUID */
328
329 if (path == NULL)
330 return NULL;
331
332 /* if path doesn't start with ~, just return a copy of path */
333 if (*path != '~')
334 return xstrdup(path);
335
336 /* expand ~/ or ~user */
337 path++;
338 if (*path == '/') { /* expand `~/' to `$HOME/' */
339 char *homedir = getenv("HOME");
340 if (homedir != NULL) {
341 resolved = xstrdup(homedir);
342 resolved = xstrcat(resolved, path);
343 }
344 else {
345 #if defined(HAVE_GETPWUID) && defined(HAVE_GETUID)
346 /* homedir not set */
347 struct passwd *entry = getpwuid(getuid());
348 if (entry != NULL) {
349 homedir = entry->pw_dir;
350 if (homedir != NULL) {
351 resolved = xstrdup(homedir);
352 resolved = xstrcat(resolved, path);
353 }
354 else {
355 XDVI_ERROR((stderr, "getpwnam returned NULL for entry->pw_dir: %s", strerror(errno)));
356 return NULL;
357 }
358 }
359 else {
360 XDVI_ERROR((stderr, "getpwnam failed: %s", strerror(errno)));
361 return NULL;
362 }
363 #else
364 popup_message(globals.widgets.top_level,
365 MSG_WARN,
366 NULL,
367 "$HOME not set, and getpwuid() or getuid() not supported - could not expand \"%s\".",
368 orig_path);
369 return NULL;
370 #endif
371 }
372 TRACE_GUI((stderr, "resolved: |%s|", resolved));
373 return resolved;
374 }
375 else { /* ~user -> try getpwnam() to get homedir */
376 #ifdef HAVE_GETPWNAM
377 struct passwd *entry;
378 char *separator = strchr(path, '/');
379 char *homedir;
380
381 TRACE_GUI((stderr, "separator is: |%s|, len of username: %d",
382 separator, (int)(separator - path)));
383 if (separator == NULL)
384 return NULL;
385
386 resolved = xmalloc(separator - path + 1);
387 memcpy(resolved, path, separator - path);
388 resolved[separator - path] = '\0';
389
390 TRACE_GUI((stderr, "username is: |%s|", resolved));
391 entry = getpwnam(resolved);
392 if (entry == NULL) {
393 XDVI_ERROR((stderr, "getpwnam failed: %s", strerror(errno)));
394 return NULL;
395 }
396 TRACE_GUI((stderr, "homedir of user is: |%s|", entry->pw_dir));
397 homedir = entry->pw_dir;
398
399 free(resolved);
400 resolved = xstrdup(homedir);
401 resolved = xstrcat(resolved, path + (separator - path));
402 TRACE_GUI((stderr, "resolved: |%s|", resolved));
403 return resolved;
404 #else
405 popup_message(globals.widgets.top_level,
406 MSG_WARN,
407 NULL,
408 "Expanding \"%s\" failed: This platform doesn't support getpwnam().",
409 orig_path);
410 return NULL;
411 #endif
412 }
413
414 }
415
416 /*
417 realpath implementation if no implementation available.
418 Try to canonicalize path, removing `~', `.' and `..' and expanding symlinks.
419
420 Adopted from wu-ftpd's fb_realpath (in realpath.c), but without the
421 seteuid(0) stuff (which we don't need, since we never change into
422 directories or read files the user has no permissions for), and
423 without the ugly goto(). Special care has been taken to avoid buffer
424 overflows (e.g. this version is not affected by
425 http://isec.pl/vulnerabilities/isec-0011-wu-ftpd.txt).
426
427 `resolved' should be a buffer of size MAXPATHLEN. */
428
429 char *
430 my_realpath(const char *path, char *resolved)
431 {
432 struct stat sb;
433 int n;
434 /* char *p, *q, *tmp; */
435 char *base;
436 char tmpbuf[MAXPATHLEN];
437 int symlinks = 0;
438 #ifdef HAVE_FCHDIR
439 int fd;
440 #else
441 char cwd[MAXPATHLEN];
442 #endif
443
444 /* Save cwd for going back later */
445 #ifdef HAVE_FCHDIR
446 if ((fd = try_open(".", O_RDONLY)) < 0)
447 return NULL;
448 #else /* HAVE_FCHDIR */
449 if (
450 # ifdef HAVE_GETCWD
451 getcwd(cwd, MAXPATHLEN)
452 # else
453 getwd(cwd)
454 # endif
455 == NULL)
456 return NULL;
457 #endif /* HAVE_FCHDIR */
458
459 if (strlen(path) + 1 > MAXPATHLEN) {
460 errno = ENAMETOOLONG;
461 return NULL;
462 }
463
464 strcpy(resolved, path);
465
466 for (;;) { /* loop for resolving symlinks in base name */
467 /* get base name and dir name components */
468 char *p = strrchr(resolved, '/');
469 if (p != NULL) {
470 base = p + 1;
471 if (p == resolved) {
472 /* resolved is in root dir; this must be treated as a special case,
473 since we can't chop off at `/'; instead, just use the `/':
474 */
475 p = "/";
476 }
477 else {
478 /* not in root dir; chop off path name at slash */
479 while (p > resolved && *p == '/') /* for multiple trailing slashes */
480 p--;
481 *(p + 1) = '\0';
482 p = resolved;
483 }
484
485 /* change into that dir */
486 if (chdir(p) != 0)
487 break;
488 }
489 else /* no directory component */
490 base = resolved;
491
492 /* resolve symlinks or directory names (not used in our case) in basename */
493 if (*base != '\0') {
494 if (
495 #ifdef HAVE_LSTAT
496 lstat(base, &sb)
497 #else
498 stat(base, &sb)
499 #endif
500 == 0) {
501 #ifdef HAVE_LSTAT
502 if (S_ISLNK(sb.st_mode)) { /* if it's a symlink, iterate for what it links to */
503 if (++symlinks > MAXSYMLINKS) {
504 errno = ELOOP;
505 break;
506 }
507
508 if ((n = readlink(base, resolved, MAXPATHLEN)) < 0)
509 break;
510
511 resolved[n] = '\0';
512 continue;
513 }
514 #endif /* HAVE_LSTAT */
515 if (S_ISDIR(sb.st_mode)) { /* if it's a directory, go there */
516 if (chdir(base) != 0)
517 break;
518
519 base = "";
520 }
521 }
522 }
523
524 /* Now get full pathname of current directory and concatenate it with saved copy of base name */
525 strcpy(tmpbuf, base); /* cannot overrun, since strlen(base) <= strlen(path) < MAXPATHLEN */
526 if (
527 #ifdef HAVE_GETCWD
528 getcwd(resolved, MAXPATHLEN)
529 #else
530 getwd(resolved)
531 #endif
532 == NULL)
533 break;
534
535 /* need to append a slash if resolved is not the root dir */
536 if (!(resolved[0] == '/' && resolved[1] == '\0')) {
537 if (strlen(resolved) + 2 > MAXPATHLEN) {
538 errno = ENAMETOOLONG;
539 break;
540 }
541 strcat(resolved, "/");
542 }
543
544 if (*tmpbuf) {
545 if (strlen(resolved) + strlen(tmpbuf) + 1 > MAXPATHLEN) {
546 errno = ENAMETOOLONG;
547 break;
548 }
549 strcat(resolved, tmpbuf);
550 }
551
552 /* go back to where we came from */
553 #ifdef HAVE_FCHDIR
554 (void)fchdir(fd);
555 close(fd);
556 #else
557 (void)chdir(cwd);
558 #endif
559 return resolved;
560 }
561
562 /* arrive here in case of error: go back to where we came from, and return NULL */
563 #ifdef HAVE_FCHDIR
564 (void)fchdir(fd);
565 close(fd);
566 #else
567 (void)chdir(cwd);
568 #endif
569 return NULL;
570 }
571
572
573 #ifndef KPATHSEA
574
575 /*
576 * Either (re)allocate storage or fail with explanation.
577 */
578
579 void *
580 xmalloc(unsigned size)
581 {
582 void *mem = malloc(size);
583
584 if (mem == NULL)
585 XDVI_FATAL((stderr, "Out of memory (allocating %u bytes).", size));
586 return mem;
587 }
588
589 void *
590 xrealloc(void *where, unsigned size)
591 {
592 void *mem = realloc(where, size);
593
594 if (mem == NULL)
595 XDVI_FATAL((stderr, "Out of memory (reallocating %u bytes).", size));
596 return mem;
597 }
598
599
600 /*
601 * Allocate a new string.
602 */
603
604 char *
605 xstrdup(const char *str)
606 {
607 size_t len;
608 char *new;
609
610 ASSERT(fprintf(stderr, "Test assertion!\n") && 1 == 0);
611 ASSERT(str != NULL, "");
612 len = strlen(str) + 1;
613 new = xmalloc(len);
614 memcpy(new, str, len);
615 return new;
616 }
617
618 #endif /* not KPATHSEA */
619
620
621 /*
622 * Allocate a new string. The second argument is the length.
623 */
624
625 char *
626 xmemdup(const char *str, size_t len)
627 {
628 char *new;
629
630 new = xmalloc(len);
631 memcpy(new, str, len);
632 return new;
633 }
634
635 /* like xstrdup(), but with XtMalloc() */
636 char *
637 xt_strdup(const char *ptr)
638 {
639 char *ret = XtMalloc(strlen(ptr) + 1);
640 return strcpy(ret, ptr);
641 }
642
643
644 /*
645 * Append str2 to str1, reallocating str1 as neccessary.
646 * Note that this modifies str1, so if you want a clean
647 * new copy, use xstrdup() first, then xstrcat().
648 * str1 should be either NULL, or a valid char * that has
649 * previously been malloc()ed.
650 */
651
652 char *
653 xstrcat(char *str1, const char *str2)
654 {
655 size_t len1 = (str1 == NULL) ? 0 : strlen(str1);
656 size_t len2 = strlen(str2) + 1;
657
658 str1 = xrealloc(str1, len1 + len2);
659 memcpy(str1 + len1, str2, len2);
660 return str1;
661 }
662
663
664 /*
665 * Allocate bitmap for given font and character
666 */
667
668 void
669 alloc_bitmap(struct bitmap *bitmap)
670 {
671 unsigned int size;
672
673 /* fprintf(stderr, "allocating bitmap of size %u x %u\n", bitmap->w, bitmap->h); */
674 /* width must be multiple of <arch-defined> bits for raster_op */
675 bitmap->bytes_wide = ROUNDUP((int)bitmap->w, BMBITS) * BMBYTES;
676 size = bitmap->bytes_wide * bitmap->h;
677 bitmap->bits = xmalloc(size != 0 ? size : 1);
678 }
679
680
681 #ifndef HAVE_MEMICMP
682 /*
683 * Case-insensitive version of memcmp(). This code assumes that the second
684 * argument (i.e. what is being compared with) is lower case.
685 */
686
687 int
688 memicmp(const char *s1, const char *s2, size_t n)
689 {
690 while (n > 0) {
691 int i = tolower((int)*s1) - *s2;
692 if (i != 0)
693 return i;
694 ++s1;
695 ++s2;
696 --n;
697 }
698 return 0;
699 }
700 #endif /* HAVE_MEMICMP */
701
702 /*
703 * Try to close the pixel file for the least recently used font.
704 * Invoked when we've run out of file descriptors.
705 */
706 void
707 close_a_file(void)
708 {
709 struct font *fontp;
710 unsigned short oldest = USHRT_MAX;
711 struct font *f = NULL;
712
713 if (globals.debug & DBG_OPEN)
714 puts("Calling close_a_file().");
715
716 for (fontp = font_head; fontp != NULL; fontp = fontp->next) {
717 if (fontp->file != NULL && fontp->timestamp <= oldest) {
718 f = fontp;
719 oldest = fontp->timestamp;
720 }
721 }
722 /* fprintf(stderr, "oldest = %u\n", oldest); */
723 if (f == NULL)
724 XDVI_FATAL((stderr, "Can't find an open pixel file to close"));
725 fclose(f->file);
726 f->file = NULL;
727 }
728
729 /*
730 * Open a file in the given mode. We use XFOPEN since xfopen is already
731 * usurpated by kpathsea's xfopen.c, which just exits rather ungracefully
732 * if it detects a NULL return value; most certainly NOT what we want here.
733 */
734 FILE *
735 XFOPEN(const char *path, const char *mode)
736 {
737 FILE *fp = NULL;
738 #ifdef TESTING_OPEN_FILES
739 fprintf(stderr, "trying to open |%s|\n", path);
740 #endif
741 if ((fp = try_fopen(path, mode)) == NULL && (errno == EMFILE || errno == ENFILE)) {
742 XDVI_FATAL((stderr, "too many open files"));
743 }
744 return fp;
745 }
746
747 /*
748 * Create a pipe, closing a file if necessary.
749 * We use socketpair() instead of pipe() because several operating
750 * systems don't support SIGPOLL/SIGIO on pipes:
751 * SGI IRIX 6.5 F_SETOWN not implemented
752 * Linux 2.4.2 Not supported
753 */
754
755 int
756 xpipe(int *fd)
757 {
758 int retval;
759
760 for (;;) {
761 retval = socketpair(AF_UNIX, SOCK_STREAM, 0, fd);
762 if (retval == 0) { /* success */
763 break;
764 }
765 if ((errno != EMFILE && errno != ENFILE)) {
766 /* failed, but not because of too many files */
767 break;
768 }
769 close_a_file();
770 }
771 return retval;
772 }
773
774
775
776 /*
777 *
778 * Read size bytes from the FILE fp, constructing them into a
779 * signed/unsigned integer.
780 *
781 */
782
783 unsigned long
784 get_bytes(FILE *fp, int size)
785 {
786 long x = 0;
787
788 while (size--)
789 x = (x << 8) | get_byte(fp);
790 return x;
791 }
792
793 long
794 get_lbytes(FILE *fp, int size)
795 {
796 long x;
797
798 #if __STDC__
799 x = (signed char)getc(fp);
800 #else
801 x = (unsigned char)getc(fp);
802 if (x & 0x80)
803 x -= 0x100;
804 #endif
805 while (--size)
806 x = (x << 8) | get_byte(fp);
807 return x;
808 }
809
810
811
812 /*
813 * Create a temporary file and return its fd. Also put its filename
814 * in str. Create str if it's NULL.
815 */
816
817 #ifndef P_tmpdir
818 #define P_tmpdir "/tmp"
819 #endif
820
821 static const char tmp_suffix[] = "/xdvi-XXXXXX";
822
823 int
824 xdvi_temp_fd(char **str)
825 {
826 int fd;
827 char *p;
828 size_t len;
829 static const char *template = NULL;
830 #if !HAVE_MKSTEMP
831 static unsigned long seed;
832 static char letters[] =
833 "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._";
834 char *p1;
835 #endif
836
837 if (*str != NULL) {
838 p = *str;
839
840 /* O_EXCL is there for security (if root runs xdvi) */
841 if (!((fd = try_open_mode(p, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR)) == -1
842 && errno == EEXIST))
843 return fd;
844 #if HAVE_MKSTEMP
845 memcpy(p + strlen(p) - 6, "XXXXXX", 6);
846 #endif
847 }
848 else {
849 if (template == NULL) {
850 const char *ourdir;
851
852 ourdir = getenv("TMPDIR");
853 if (ourdir == NULL || access(ourdir, W_OK) < 0) {
854 ourdir = P_tmpdir;
855 if (access(ourdir, W_OK) < 0)
856 ourdir = ".";
857 }
858 len = strlen(ourdir);
859 if (len > 0 && ourdir[len - 1] == '/')
860 --len;
861 template = p = xmalloc(len + sizeof tmp_suffix);
862 memcpy(p, ourdir, len);
863 memcpy(p + len, tmp_suffix, sizeof tmp_suffix);
864 #if !HAVE_MKSTEMP
865 seed = 123456789 * time(NULL) + 987654321 * getpid();
866 #endif
867 }
868 *str = p = xstrdup(template);
869 }
870
871 #if HAVE_MKSTEMP
872 fd = mkstemp(p);
873 if (fd == -1 && (errno == EMFILE || errno == ENFILE)) {
874 close_a_file();
875 memcpy(p + strlen(p) - 6, "XXXXXX", 6);
876 fd = mkstemp(p);
877 }
878 #else
879 p1 = p + strlen(p) - 6;
880 for (;;) {
881 unsigned long s = ++seed;
882 char *p2;
883
884 for (p2 = p1 + 5; p2 >= p1; --p2) {
885 *p2 = letters[s & 63];
886 s >>= 6;
887 }
888 if (!((fd = try_open_mode(p, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR)) == -1
889 && errno == EEXIST))
890 break;
891 }
892 #endif
893 return fd;
894 }
895
896
897 /* print a GUI error message for childs that exited with an errorcode */
898 void
899 handle_child_exit(int status, struct xchild *this)
900 {
901 char *err_msg = NULL;
902
903 /* if child exited with error and xio struct is available for child,
904 print error text */
905 if (this->io != NULL
906 && (WIFEXITED(status) != 0)
907 && (WEXITSTATUS(status) != 0)
908 && (err_msg = (this->io->read_proc)(this->io->fd, NULL)) != NULL) {
909
910 if (this->name == NULL) {
911 popup_message(globals.widgets.top_level,
912 MSG_WARN,
913 NULL,
914 err_msg[0] == '\0' ? "An unknown error occurred" : err_msg);
915 }
916 else {
917 popup_message(globals.widgets.top_level,
918 MSG_WARN,
919 "Xdvi tries to collect all messages from STDERR. "
920 "When no useful error message is available "
921 "(e.g. because the program has written to STDOUT instead), "
922 "try to run the command again from the command line "
923 "to find out what the problem was.",
924 "Command \"%s\" exited with error code %d\n%s\n",
925 this->name, WEXITSTATUS(status), err_msg);
926 }
927 free(err_msg);
928 }
929 free(this->name);
930 free(this->io);
931 free(this);
932 }
933
934 static void
935 dummy_write_proc(int fd, void *data)
936 {
937 UNUSED(fd);
938 UNUSED(data);
939
940 fprintf(stderr, "============== dummy_write_proc called for fd %d\n", fd);
941 }
942
943 /*
944 * read what child printed to fd (should be set up to be stderr).
945 * Allocates and returns error text; caller is responsible for free()ing it
946 * afterwards.
947 */
948 char *
949 read_child_error(int fd, void *data)
950 {
951 int bytes = 0, buf_old_size = 0, buf_new_size = 0;
952 char tmp_buf[BUF_SIZE];
953 char *err_buf = xstrdup("");
954 char *ret;
955 UNUSED(data);
956
957 /* collect stderr messages into err_buf */
958 while ((bytes = read(fd, tmp_buf, BUF_SIZE - 1)) > 0) {
959 buf_old_size = buf_new_size;
960 buf_new_size += bytes;
961 err_buf = xrealloc(err_buf, buf_new_size + 1);
962 memcpy(err_buf + buf_old_size, tmp_buf, buf_new_size - buf_old_size);
963 err_buf[buf_new_size] = '\0';
964 }
965
966 close(fd);
967 ret = escape_format_arg(err_buf); /* this allocates ret */
968 free(err_buf);
969 return ret;
970 }
971
972 /*
973 * Fork a child process. If exit_proc is NULL, the process' error messages
974 * will be collected and a window popped up for GUI display. If exit_proc
975 * is non-NULL, it should be a function that does something reasonable
976 * with the error messages itself. It should also free the xchild struct.
977 *
978 * If dirname != NULL, the child will chdir into dirname before running the
979 * command.
980 *
981 * If killsig == 0, the process will not be killed when xdvi terminates.
982 * If killsig > 0, the process will be sent this signal when xdvi terminates.
983 * If killsig < 0, the process will be given its own group, and the whole group
984 * will be sent -killsig when xdvi terminates. This is useful when invoking
985 * /bin/sh. Generally killsig (if nonzero) should be SIGKILL or -SIGKILL.
986 */
987 Boolean
988 fork_process(const char *proc_name, Boolean redirect_stdout,
989 const char *dirname,
990 childProcT exit_proc, void *data,
991 int killsig,
992 char *const argv[])
993 {
994 int i, pid;
995 struct xchild *my_child = xmalloc(sizeof *my_child);
996 struct xio *my_io = xmalloc(sizeof *my_io);
997 int err_pipe[2];
998 char *volatile buf = xstrdup("");
999
1000 for (i = 0; argv[i] != NULL; i++) {
1001 TRACE_GUI((stderr, "argv: |%s|", argv[i]));
1002 buf = xstrcat(buf, argv[i]);
1003 buf = xstrcat(buf, " ");
1004 }
1005
1006 if (i > 0)
1007 buf[strlen(buf) - 1] = '\0'; /* chop off trailing space */
1008
1009 TRACE_GUI((stderr, "forking: |%s|", buf));
1010
1011 /* flush output buffers to avoid double buffering (i.e. data
1012 waiting in the output buffer being written twice, by the parent
1013 and the child) */
1014 fflush(stdout);
1015 fflush(stderr);
1016
1017 if (pipe(err_pipe) < 0) {
1018 XDVI_FATAL((stderr, "pipe error"));
1019 }
1020
1021 switch (pid = vfork()) {
1022 case -1: /* forking error */
1023 perror("vfork");
1024 close(err_pipe[0]);
1025 close(err_pipe[1]);
1026 return False;
1027 case 0: /* child */
1028 if (dirname != NULL)
1029 (void)chdir(dirname);
1030 if (globals.debug & DBG_FILES) {
1031 char path[MAXPATHLEN];
1032 (void)getcwd(path, MAXPATHLEN);
1033 fprintf(stderr, "Directory of running `%s': `%s'\n",
1034 proc_name, path);
1035 }
1036 /* FIXME: There's a bug which prevents this from working
1037 with xdvi as child: Whenever xdvi tries to print to stderr,
1038 this will hang the child forever. Closing all other file
1039 descriptors, as in the #if TRY_FIX regions, seems to fix
1040 this, but it also loses all output ...
1041 */
1042 #if TRY_FIX
1043 close(0);
1044 close(1);
1045 #endif /* TRY_FIX */
1046 close(err_pipe[0]); /* no reading from stderr */
1047
1048 /* (Maybe) set session ID, so that kill will also affect subprocesses */
1049 if (killsig < 0) {
1050 if (setsid() == -1) {
1051 perror("setsid");
1052 _exit(EXIT_FAILURE);
1053 return False; /* make compiler happy */
1054 }
1055 }
1056
1057 /* redirect writing to stderr */
1058 if (dup2(err_pipe[1], STDERR_FILENO) != STDERR_FILENO) {
1059 perror("dup2 for stderr");
1060 _exit(EXIT_FAILURE);
1061 return False; /* make compiler happy */
1062 }
1063 if (redirect_stdout) {
1064 /* also redirect writing to stdout */
1065 if (dup2(err_pipe[1], STDOUT_FILENO) != STDOUT_FILENO) {
1066 perror("dup2 for stdout");
1067 _exit(EXIT_FAILURE);
1068 return False; /* make compiler happy */
1069 }
1070 }
1071
1072 #if TRY_FIX
1073 /* close all remaining descriptors */
1074 i = 2;
1075 while (i < 256 /* TODO: better handling of OPEN_MAX; see Stevens p. 43 */) {
1076 close(i++);
1077 }
1078 #endif /* TRY_FIX */
1079 execvp(proc_name, argv);
1080
1081 /* arrive here only if execvp failed */
1082 fprintf(stderr, "%s: Execution of %s failed.\n", globals.program_name, proc_name);
1083 fflush(stderr);
1084 close(err_pipe[1]);
1085 _exit(EXIT_FAILURE);
1086 return False; /* make compiler happy */
1087 default: /* parent */
1088 close(err_pipe[1]); /* no writing to stderr */
1089
1090 my_io->next = NULL;
1091 my_io->fd = err_pipe[0];
1092 my_io->xio_events = XIO_IN;
1093 #if HAVE_POLL
1094 my_io->pfd = NULL;
1095 #endif
1096 my_io->read_proc = read_child_error;
1097 my_io->write_proc = dummy_write_proc;
1098 my_io->data = data;
1099
1100 my_child->next = NULL;
1101 my_child->pid = pid;
1102 my_child->name = buf;
1103 my_child->data = data;
1104 my_child->killsig = killsig;
1105 if (exit_proc == NULL) { /* use default exit procedure */
1106 my_child->proc = handle_child_exit;
1107 }
1108 else {
1109 my_child->proc = exit_proc;
1110 }
1111 my_child->io = my_io;
1112
1113 set_chld(my_child);
1114
1115 return True;
1116 }
1117 }
1118
1119
1120
1121 /*
1122 * Prepare the file descriptor to generate SIGPOLL/SIGIO events.
1123 * If called with a True argument, set it up for non-blocking I/O.
1124 */
1125
1126 void
1127 prep_fd(int fd, wide_bool noblock)
1128 {
1129 /* Set file descriptor for non-blocking I/O */
1130 if (noblock)
1131 (void) fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | O_NONBLOCK);
1132
1133 #if !FLAKY_SIGPOLL
1134 # if HAVE_STREAMS
1135 if (isastream(fd) > 0) {
1136 if (ioctl(fd, I_SETSIG,
1137 S_RDNORM | S_RDBAND | S_HANGUP | S_WRNORM) == -1)
1138 perror("xdvi: ioctl I_SETSIG");
1139 }
1140 else
1141 # endif
1142 {
1143 # ifdef FASYNC
1144 if (fcntl(fd, F_SETOWN, getpid()) == -1)
1145 perror("xdvi: fcntl F_SETOWN");
1146 if (fcntl(fd, F_SETFL, fcntl(fd, F_GETFL, 0) | FASYNC) == -1)
1147 perror("xdvi: fcntl F_SETFL");
1148 # elif defined SIOCSPGRP && defined FIOASYNC
1149 /* For HP-UX B.10.10 and maybe others. See "man 7 socket". */
1150 int arg;
1151
1152 arg = getpid();
1153 if (ioctl(fd, SIOCSPGRP, &arg) == -1)
1154 perror("xdvi: ioctl SIOCSPGRP");
1155 arg = 1;
1156 if (ioctl(fd, FIOASYNC, &arg) == -1)
1157 perror("xdvi: ioctl FIOASYNC");
1158 # endif
1159 }
1160 #endif /* not FLAKY_SIGPOLL */
1161 }
1162
1163
1164 /* APS Pointer locator: */
1165 /* Return screen positions */
1166 Boolean
1167 pointerlocate(int *xpos, int *ypos)
1168 {
1169 Window root, child;
1170 int root_x, root_y;
1171 unsigned int keys_buttons;
1172
1173 if (!XtIsRealized(globals.widgets.top_level))
1174 return False;
1175
1176 return XQueryPointer(DISP, mane.win, &root, &child,
1177 &root_x, &root_y, xpos, ypos, &keys_buttons);
1178 }
1179
1180 unsigned long
1181 parse_debugging_string(const char *arg)
1182 {
1183 int retval = 0;
1184 const char *curr, *last;
1185 size_t i;
1186
1187 curr = last = arg;
1188
1189 while (*curr != '\0') {
1190 Boolean matched = False;
1191
1192 while (isspace((int)*curr))
1193 curr++;
1194 for (i = 0; debug_options[i].description != NULL; i++) {
1195 size_t curr_opt_len = strlen(debug_options[i].description);
1196 /* Should we match on length of passed argument, to allow for abbreviations? */
1197 if (memicmp(curr,
1198 debug_options[i].description,
1199 curr_opt_len) == 0
1200 && (curr[curr_opt_len] == '\0'
1201 || curr[curr_opt_len] == ','
1202 || isspace((int)curr[curr_opt_len]))) {
1203 matched = True;
1204 retval |= debug_options[i].bitmap;
1205 fprintf(stderr, "Debugging option: \"%s\" = \"%s\", debug: %d\n",
1206 curr, debug_options[i].description, retval);
1207 }
1208 }
1209 if (!matched) {
1210 char *tempstr = xstrdup(curr);
1211 char *test;
1212 if ((test = strchr(curr, ',')) != NULL) {
1213 *test = '\0';
1214 }
1215 XDVI_WARNING((stderr, "Ignoring unknown debugging option \"%s\". Valid options are:\n", tempstr));
1216 for (i = 0; debug_options[i].description != NULL; i++) {
1217 fprintf(stderr, "`%s'%s",
1218 debug_options[i].description,
1219 debug_options[i].help_formatting);
1220 }
1221 fprintf(stderr, "\n");
1222 free(tempstr);
1223 }
1224 curr = strchr(curr, ',');
1225 if (curr == NULL)
1226 break;
1227 curr++;
1228 }
1229
1230 return retval;
1231 }
1232
1233 unsigned long
1234 parse_debugging_option(const char *ptr)
1235 {
1236 if (ptr == NULL)
1237 return 0L;
1238 else if (isdigit((int)*ptr)) {
1239 if (resource.debug_arg == NULL)
1240 return DBG_ALL; /* per default debug everything */
1241 else
1242 return strtol(resource.debug_arg, (char **)NULL, 10);
1243 } else if (*ptr == '-')
1244 return DBG_ALL;
1245 else return parse_debugging_string(ptr);
1246 }
1247
1248 /* determine average width of a font */
1249 int
1250 get_avg_font_width(XFontStruct *font)
1251 {
1252 int width;
1253
1254 assert(font != NULL);
1255 width = font->max_bounds.width + font->min_bounds.width / 2;
1256 if (width == 0) {
1257 /* if min_bounds.width = -max_bounds.width, we probably
1258 have a scalable TT font; try to determine its actual
1259 width by measuring the letter `x':
1260 */
1261 width = XTextWidth(font, "x", 1);
1262 }
1263 if (width == 0) { /* last resort */
1264 width = font->max_bounds.width / 2;
1265 }
1266 return width;
1267
1268 }
1269
1270 /*
1271 Splits LINE from BEGIN to END (not neccessarily null-terminated)
1272 into items separated by SEP, removes leading or trailing whitespace,
1273 and saves the items as newly allocated char*s into the return array.
1274 Returns the number of items that have been saved as RET_ITEMS.
1275 Empty entries are returned as such, i.e. both `abc:' and `abc: '
1276 return RET_ITEMS = 2 and "" as second entry.
1277 */
1278 char **
1279 split_line(const char *line, char sep, size_t begin, size_t end, size_t *ret_items)
1280 {
1281 const char *c_ptr = line + begin;
1282 const char *e_ptr = line + end;
1283 const char *test_end;
1284
1285 size_t result_cnt = 0;
1286 size_t alloc_len = 0;
1287 size_t len;
1288 const size_t ALLOC_STEP = 8;
1289 char **result_arr = NULL;
1290
1291 /* create new result item, resizing result_arr as needed
1292 * (an empty string will coun1 as 1 item: "") */
1293 while (result_cnt + 1 >= alloc_len) {
1294 alloc_len += ALLOC_STEP;
1295 result_arr = xrealloc(result_arr, alloc_len * sizeof *result_arr);
1296 }
1297
1298 while (c_ptr <= e_ptr) {
1299 /* skip leading whitespace */
1300 while (c_ptr < e_ptr && isspace((int)*c_ptr)) {
1301 c_ptr++;
1302 }
1303
1304 /* find end of current elem, which is either the separator or out of range */
1305 test_end = strchr(c_ptr, sep);
1306 /* skip escaped separators */
1307 while (test_end != NULL && test_end <= e_ptr) {
1308 if (test_end > c_ptr && *(test_end - 1) == '\\') {
1309 test_end = strchr(test_end + 1, sep);
1310 }
1311 else
1312 break;
1313 }
1314 /* if nothing found, use e_ptr */
1315 if (test_end == NULL || test_end > e_ptr) {
1316 test_end = e_ptr;
1317 }
1318
1319 len = test_end - c_ptr;
1320
1321 /* skip trailing whitespace */
1322 while (len > 0 && isspace((int)c_ptr[len - 1])) {
1323 len--;
1324 }
1325
1326 result_arr[result_cnt] = xmalloc(len + 1);
1327 /* copy into result item, skipping the escape '\\' characters */
1328 {
1329 size_t i = 0, j = 0;
1330 while (i < len) {
1331 if (c_ptr[i] == '\\' && c_ptr[i + 1] == sep) /* i + 1 is safe since (i < len) */
1332 i++;
1333 result_arr[result_cnt][j++] = c_ptr[i++];
1334 }
1335 result_arr[result_cnt][j] = '\0';
1336 }
1337 result_cnt++;
1338
1339 /* skip to next item */
1340 c_ptr = test_end + 1;
1341 }
1342 result_arr[result_cnt] = NULL; /* null-terminate return array, just to be safe */
1343 *ret_items = result_cnt;
1344 return result_arr;
1345 }
1346
1347
1348 /*------------------------------------------------------------
1349 * find_file
1350 *
1351 * Arguments:
1352 * filename - absolute or relative file name
1353 * statbuf - buffer to stat filename
1354 * pathinfo - kpse_file_format_type, only used if a kpathsearch for the
1355 * file is performed.
1356 * See kpathsea/tex-file.h for a list of possible values.
1357 *
1358 * Returns:
1359 * expanded filename
1360 *
1361 * Purpose:
1362 * Find a file name corresponding to <filename>, possibly
1363 * expanding it to a full path name; checks if the file
1364 * exists by stat()ing it; returns NULL if nothing has
1365 * been found, else the expanded filename in fresh memory.
1366 *
1367
1368 *------------------------------------------------------------*/
1369
1370 char *
1371 find_file(const char *filename, struct stat *statbuf, kpse_file_format_type pathinfo)
1372 {
1373 char *tmp;
1374 char *pathname;
1375
1376 TRACE_SRC((stderr, "checking filename \"%s\"", filename));
1377
1378 /*
1379 * case 1:
1380 * try absolute filename
1381 */
1382 if (filename[0] == '/') {
1383 if (stat(filename, statbuf) == 0) {
1384 TRACE_SRC((stderr, "Found absolute filename \"%s\"", filename));
1385 return xstrdup(filename);
1386 }
1387 else {
1388 TRACE_SRC((stderr, "Can't stat absolute filename \"%s\"\n", filename));
1389 return NULL;
1390 }
1391 }
1392
1393 /*
1394 * case 2:
1395 * prepend filename with dir component from the `main' xdvi file (globals.dvi_file.dirname).
1396 * This works for both
1397 * /absolute/path/ + filename
1398 * and
1399 * /absolute/path/ + relative/path/filename
1400 */
1401 ASSERT(globals.dvi_file.dirname != NULL, "globals.dvi_file.dirname should have been initialized");
1402
1403 pathname = xstrdup(globals.dvi_file.dirname);
1404 pathname = xstrcat(pathname, filename);
1405
1406 TRACE_SRC((stderr, "Trying globals.dvi_file.dirname: \"%s\"", pathname));
1407 if (stat(pathname, statbuf) == 0) {
1408 return pathname;
1409 }
1410
1411 /*
1412 * case 3:
1413 * try current directory; if it's a match, expand to full (but uncanonicalized) path name.
1414 */
1415 if (stat(filename, statbuf) == 0) {
1416 TRACE_SRC((stderr, "Found file \"%s\" in current dir", filename));
1417 free(pathname);
1418 return expand_filename(filename, USE_CWD_PATH);
1419 }
1420
1421 /*
1422 * case 4a:
1423 * try a kpathsea search for filename, from globals.dvi_file.dirname
1424 */
1425 {
1426 #ifdef HAVE_FCHDIR
1427 int fd;
1428 #else
1429 char cwd[MAXPATHLEN];
1430 #endif
1431
1432 /* Save cwd for going back later */
1433 if (
1434 #ifdef HAVE_FCHDIR
1435 (fd = try_open(".", O_RDONLY)) >= 0
1436 #else /* HAVE_FCHDIR */
1437 # ifdef HAVE_GETCWD
1438 getcwd(cwd, MAXPATHLEN)
1439 # else
1440 getwd(cwd)
1441 # endif
1442 != NULL
1443 #endif /* HAVE_FCHDIR */
1444 ) {
1445 if (chdir(globals.dvi_file.dirname) == 0) {
1446
1447 TRACE_SRC((stderr,
1448 "trying kpathsearch for filename \"%s\" from %s",
1449 filename, globals.dvi_file.dirname));
1450 tmp = kpse_find_file(filename, pathinfo, True);
1451
1452 if (tmp != NULL && stat(tmp, statbuf) == 0) {
1453 free(pathname);
1454 /* go back to where we came from */
1455 #ifdef HAVE_FCHDIR
1456 (void)fchdir(fd);
1457 close(fd);
1458 #else
1459 (void)chdir(cwd);
1460 #endif
1461 if (tmp[0] == '/') { /* is it an absolute path? */
1462 pathname = xstrdup(tmp);
1463 }
1464 else {
1465 pathname = xstrdup(globals.dvi_file.dirname);
1466 pathname = xstrcat(pathname, tmp);
1467 }
1468 TRACE_SRC((stderr, "Found file: `%s'", pathname));
1469 free(tmp);
1470 return pathname;
1471 }
1472 }
1473 else {
1474 /*
1475 * case 4b:
1476 * couldn't change to globals.dvi_file.dirname - try a kpathsea search from CWD
1477 */
1478 TRACE_SRC((stderr,
1479 "trying kpathsearch for filename \"%s\" from CWD",
1480 filename));
1481 tmp = kpse_find_file(filename, pathinfo, True);
1482
1483 if (tmp != NULL && stat(tmp, statbuf) == 0) {
1484 TRACE_SRC((stderr, "Found file: `%s'", tmp));
1485 free(pathname);
1486 return tmp;
1487 }
1488 }
1489 }
1490 }
1491 /*
1492 * case 5:
1493 * try a kpathsea search for pathname
1494 */
1495 TRACE_SRC((stderr,
1496 "trying kpathsearch for pathname \"%s\"",
1497 pathname));
1498 tmp = kpse_find_file(pathname, pathinfo, True);
1499
1500 if (tmp != NULL && stat(tmp, statbuf) == 0) {
1501 TRACE_SRC((stderr, "Found file: `%s'", tmp));
1502 free(pathname);
1503 return tmp;
1504 }
1505
1506 /* not found */
1507 free(pathname);
1508 free(tmp);
1509 errno = 0;
1510 return NULL;
1511 }
1512
1513 /*
1514 Hashtable functions
1515
1516 The purpose of these is to wrap kpathsea's rather strange hash
1517 functions that can be used to store 2 type of values: char *, and
1518 long, where the latter is interpreted as char *. (See kpathsea/dir.c
1519 for an example of where this is used).
1520
1521 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1522 BUG ALERT: Note however that a long value may never be removed from
1523 the hash table with hash_delete(), since it would do a strcmp() on
1524 the long interpreted as a pointer!
1525 !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
1526
1527 We can't use a different approach (like using a void *) since
1528 the debugging ouput of kpathsea relies on printing the value
1529 either as char * or long (depending on the value of the global flag
1530 `kpse_debug_hash_lookup_int').
1531 */
1532 /*
1533 If key is in hashtable, return True and the integer value in val;
1534 else return False (and leave val untouched).
1535 */
1536 Boolean
1537 find_str_int_hash(hashTableT *hashtable, const char *key, size_t *val)
1538 {
1539 const_string *ret;
1540 #ifdef KPSE_DEBUG
1541 if (KPSE_DEBUG_P (KPSE_DEBUG_HASH))
1542 kpse_debug_hash_lookup_int = True;
1543 #endif
1544 ret = hash_lookup(*hashtable, key);
1545 #ifdef KPSE_DEBUG
1546 if (KPSE_DEBUG_P (KPSE_DEBUG_HASH))
1547 kpse_debug_hash_lookup_int = False;
1548 #endif
1549
1550 if (ret != NULL) {
1551 long l = (long)*ret;
1552 *val = (size_t)l;
1553 return True;
1554 }
1555 return False;
1556 }
1557
1558 /*
1559 Insert key-value pair into hashtable. Note that the key is
1560 *not* copied (i.e. it is expected that is had been allocated
1561 somewhere else, and persists throughout the program).
1562 */
1563 void
1564 put_str_int_hash(hashTableT *hashtable, const char *key, size_t val)
1565 {
1566 long ptr = (long)val;
1567 hash_insert(hashtable, key, (const string)ptr);
1568 }
1569
1570
1571 /*
1572 * General AVL tree mechanism. Search for a node, and return it if found.
1573 * Otherwise insert a node.
1574 * This uses the AVL algorithm from Knuth Vol. 3.
1575 */
1576
1577 struct avl *
1578 avladd(const char *key, size_t key_len, struct avl **headp, size_t size)
1579 {
1580 struct avl *ap;
1581 struct avl **app;
1582 struct avl *sp; /* place where rebalancing may be necessary */
1583 struct avl **spp; /* points to sp */
1584 int i;
1585
1586 /* Search */
1587 spp = app = headp;
1588 for (;;) {
1589 ap = *app;
1590 if (ap == NULL) /* bottom of tree */
1591 break;
1592 if (ap->bal != 0)
1593 spp = app;
1594 i = key_len - ap->key_len;
1595 if (i == 0)
1596 i = memcmp(key, ap->key, key_len);
1597 if (i == 0) /* found record already */
1598 return ap;
1599 if (i < 0) /* move left */
1600 app = &ap->left;
1601 else
1602 app = &ap->right;
1603 }
1604
1605 /* Insert */
1606 ap = xmalloc(size);
1607 ap->key = key;
1608 ap->key_len = key_len;
1609 ap->bal = 0;
1610 ap->left = ap->right = NULL;
1611 *app = ap;
1612
1613 /* Adjust balance factors */
1614 sp = *spp;
1615 if (sp == ap)
1616 return ap;
1617 i = key_len - sp->key_len;
1618 if (i == 0)
1619 i = memcmp(key, sp->key, key_len);
1620 sp = (i < 0 ? sp->left : sp->right);
1621 while (sp != ap) {
1622 i = key_len - sp->key_len;
1623 if (i == 0)
1624 i = memcmp(key, sp->key, key_len);
1625 if (i < 0) {
1626 sp->bal = -1;
1627 sp = sp->left;
1628 }
1629 else {
1630 sp->bal = 1;
1631 sp = sp->right;
1632 }
1633 }
1634
1635 /* Balancing act */
1636 sp = *spp;
1637 i = key_len - sp->key_len;
1638 if (i == 0)
1639 i = memcmp(key, sp->key, key_len);
1640 if (i < 0) {
1641 if (sp->bal >= 0)
1642 --sp->bal;
1643 else { /* need to rebalance */
1644 struct avl *left;
1645
1646 left = sp->left;
1647 if (left->bal < 0) { /* single rotation */
1648 sp->left = left->right;
1649 left->right = sp;
1650 sp->bal = left->bal = 0;
1651 *spp = left;
1652 }
1653 else { /* double rotation */
1654 struct avl *newtop;
1655
1656 newtop = left->right;
1657 sp->left = newtop->right;
1658 newtop->right = sp;
1659 left->right = newtop->left;
1660 newtop->left = left;
1661 sp->bal = left->bal = 0;
1662 if (newtop->bal < 0) ++sp->bal;
1663 else if (newtop->bal > 0) --left->bal;
1664 newtop->bal = 0;
1665 *spp = newtop;
1666 }
1667 }
1668 }
1669 else {
1670 if (sp->bal <= 0)
1671 ++sp->bal;
1672 else { /* need to rebalance */
1673 struct avl *right;
1674
1675 right = sp->right;
1676 if (right->bal > 0) { /* single rotation */
1677 sp->right = right->left;
1678 right->left = sp;
1679 sp->bal = right->bal = 0;
1680 *spp = right;
1681 }
1682 else { /* double rotation */
1683 struct avl *newtop;
1684
1685 newtop = right->left;
1686 sp->right = newtop->left;
1687 newtop->left = sp;
1688 right->left = newtop->right;
1689 newtop->right = right;
1690 sp->bal = right->bal = 0;
1691 if (newtop->bal > 0) --sp->bal;
1692 else if (newtop->bal < 0) ++right->bal;
1693 newtop->bal = 0;
1694 *spp = newtop;
1695 }
1696 }
1697 }
1698
1699 return ap;
1700 }
1701
1702
1703 /* set globals.dvi_name, globals.dvi_file.dirname and globals.dvi_file.dirlen */
1704 void
1705 set_dvi_name_expand(const char *new_filename)
1706 {
1707 ASSERT(new_filename != NULL, "");
1708 free(globals.dvi_name);
1709 globals.dvi_name = expand_filename_append_dvi(new_filename, USE_CWD_PATH, True);
1710
1711 free(globals.dvi_file.dirname);
1712 globals.dvi_file.dirname = get_dir_component(globals.dvi_name);
1713
1714 ASSERT(globals.dvi_file.dirname != NULL, "dvi_name should be a path with dir component");
1715 globals.dvi_file.dirlen = strlen(globals.dvi_file.dirname);
1716 }
1717
1718 /* set globals.dvi_name, globals.dvi_file.dirname and globals.dvi_file.dirlen
1719 In contrast to previous function, input filename is not copied.
1720 */
1721 void
1722 set_dvi_name(char *new_filename)
1723 {
1724 ASSERT(new_filename != NULL, "");
1725 free(globals.dvi_name);
1726 globals.dvi_name = new_filename;
1727
1728 free(globals.dvi_file.dirname);
1729 globals.dvi_file.dirname = get_dir_component(globals.dvi_name);
1730
1731 ASSERT(globals.dvi_file.dirname != NULL, "dvi_name should be a path with dir component");
1732 globals.dvi_file.dirlen = strlen(globals.dvi_file.dirname);
1733 }
1734
1735 /*
1736 * Copy the file pointer `in' to the file pointer `out'. Return True
1737 * if successful, False else (in which case caller should examine
1738 * errno to find the error).
1739 * The caller is responsible for closing the files.
1740 */
1741 Boolean
1742 copy_fp(FILE *in, FILE *out)
1743 {
1744 #define TMP_BUF_SIZE 4 * 1024
1745 char buf[TMP_BUF_SIZE];
1746
1747 while (feof(in) == 0) {
1748 size_t bytes_in, bytes_out;
1749
1750 bytes_in = fread(buf, 1, TMP_BUF_SIZE, in);
1751 if (bytes_in < TMP_BUF_SIZE && !feof(in))
1752 return False;
1753 bytes_out = fwrite(buf, 1, bytes_in, out);
1754 /* fprintf(stderr, "read %d, wrote %d bytes\n", bytes_in, bytes_out); */
1755 if (bytes_out < bytes_in)
1756 return False;
1757 }
1758 return True;
1759
1760 #undef TMP_BUF_SIZE
1761 }
1762
1763
1764 /*
1765 * Copy a file from `from_path' to `to'. Return True if successful, False else
1766 * (in which case caller should examine errno to find the error).
1767 */
1768 Boolean
1769 copy_file(const char *from_path, const char *to_path) {
1770 FILE *from_fp;
1771 FILE *to_fp;
1772
1773 Boolean retval;
1774
1775 if ((from_fp = try_fopen(from_path, "rb")) == NULL) {
1776 XDVI_ERROR((stderr, "opening %s for reading failed: %s", from_path, strerror(errno)));
1777 return False;
1778 }
1779
1780 if ((to_fp = try_fopen(to_path, "wb")) == NULL) {
1781 XDVI_ERROR((stderr, "opening %s for writing failed: %s", to_path, strerror(errno)));
1782 return False;
1783 }
1784
1785 retval = copy_fp(from_fp, to_fp);
1786
1787 fclose(from_fp);
1788 fclose(to_fp);
1789
1790 return retval;
1791 }
1792
1793 const char *
1794 get_text_encoding(void)
1795 {
1796 const char *text_encoding = NULL;
1797
1798 /* if resource.text_encoding isn't set, use nl_langinfo() if langinfo is available */
1799 if (resource.text_encoding == NULL) {
1800 #if USE_LANGINFO
1801 if (globals.orig_locale == NULL) {
1802 XDVI_ERROR((stderr, "Call to setlocale() returned NULL; assuming ISO-8859-1 charset."));
1803 text_encoding = "ISO-8859-1";
1804 }
1805 else {
1806 if (strcmp(globals.orig_locale, "C") == 0 || strcmp(globals.orig_locale, "POSIX") == 0) {
1807 /* nl_langinfo returns rather strange values for these ... */
1808 text_encoding = "ISO-8859-1";
1809 TRACE_FIND((stderr, "Assuming |%s| for locale |%s|",
1810 text_encoding, globals.orig_locale));
1811 }
1812 else {
1813 text_encoding = nl_langinfo(CODESET);
1814 TRACE_FIND((stderr, "nl_langinfo returned: |%s| for locale |%s|",
1815 text_encoding, globals.orig_locale));
1816 }
1817 }
1818 #else
1819 XDVI_WARNING((stderr,
1820 "nl_langinfo() not available on this platform, "
1821 "and XDvi.textEncoding resource not set; using default "
1822 "encoding ISO-8859-1."));
1823 text_encoding = "ISO-8859-1";
1824 #endif
1825 }
1826 else {
1827 text_encoding = resource.text_encoding;
1828 }
1829 return text_encoding;
1830 }
1831
1832 char *
1833 iconv_convert_string(const char *from_enc, const char *to_enc, const char *str)
1834 {
1835 static Boolean have_warned = False;
1836 #if HAVE_ICONV_H
1837 size_t input_len = strlen(str);
1838 size_t conv_len = input_len * 4 + 1; /* worst case ... */
1839 int conv_len_save = conv_len;
1840 char *conv_buf = xmalloc(conv_len);
1841 const char *in_ptr = str;
1842 const char *out_ptr = conv_buf;
1843
1844 iconv_t conv_desc = iconv_open(to_enc, from_enc);
1845
1846 if (conv_desc == (iconv_t)(-1)) {
1847 if (!have_warned) {
1848 popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
1849 MSG_ERR,
1850 NULL,
1851 "iconv_open() error: Encoding \"%s\" is not supported by this version of iconv.\n"
1852 "Please check the output of \"iconv -l\" and set the X resource\n"
1853 "\"XDvi.textEncoding\" to an appropriate value.", from_enc);
1854 have_warned = True;
1855 }
1856 free(conv_buf);
1857 return NULL;
1858 }
1859
1860 TRACE_FIND((stderr, "iconv_convert_string: from `%s', to `%s'", from_enc, to_enc));
1861 if (iconv(conv_desc, (iconv_char_pptrT)&in_ptr, &input_len, (char **)&out_ptr, &conv_len) == (size_t)(-1)) {
1862 popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
1863 MSG_ERR,
1864 NULL,
1865 "iconv_convert_string(): Could not convert %s to %s: %s.",
1866 from_enc, to_enc, strerror(errno));
1867 iconv_close(conv_desc);
1868 free(conv_buf);
1869 return NULL;
1870 }
1871
1872 iconv_close(conv_desc);
1873 conv_len = conv_len_save - conv_len;
1874 conv_buf[conv_len] = '\0';
1875
1876 TRACE_FIND((stderr, "after iconv conversion: |%s| %lu bytes\n",
1877 conv_buf, (unsigned long)conv_len));
1878
1879
1880 return conv_buf;
1881
1882 #else /* HAVE_ICONV_H */
1883
1884 UNUSED(from_enc);
1885 UNUSED(to_enc);
1886 UNUSED(str);
1887
1888 /* no iconv available */
1889 if (!have_warned) {
1890 popup_message(XtNameToWidget(globals.widgets.top_level, "*find_popup"),
1891 MSG_ERR,
1892 "You can either set the \"LANG\" environment variable or the X resource "
1893 "\"XDvi.textEncoding\" to make xdvi use a different language/encoding setting.\n"
1894 "Without iconv, only the encodings ISO-8859-1 and UTF-8 are supported. "
1895 "For real iconv support, you will need to install the iconv library "
1896 "and recompile xdvik.",
1897 "Cannot convert from %s to UTF-8 without iconv support compiled in.");
1898 have_warned = True;
1899 }
1900 return NULL;
1901
1902 #endif /* HAVE_ICONV_H */
1903 }
1904
1905
1906 /* Replace (pseudo-)format arguments in NULL-terminated argv list as follows:
1907 * %f -> filename, %l -> linenumber, %c -> column number.
1908 * If %f or %l are not specified, they are appended as %f and +%l.
1909 * If colno == 0, no %c argument is provided.
1910 */
1911 char **
1912 src_format_arguments(char **argv, const char *filename, int lineno, int colno)
1913 {
1914 size_t i;
1915 Boolean found_filename = False;
1916 Boolean found_lineno = False;
1917
1918 for (i = 0; argv[i] != NULL; i++) {
1919 char *ptr, *curr = argv[i];
1920 while ((ptr = strchr(curr, '%')) != NULL) {
1921 char *p1;
1922 if ((p1 = strchr("flc", ptr[1])) != NULL) { /* we have a formatting char */
1923 char digit_arg[LENGTH_OF_INT];
1924 const char *new_elem = NULL;
1925 /* remember offsets and lengths */
1926 size_t l_init = ptr - argv[i];
1927 size_t l_rest = strlen(ptr + 2) + 1;
1928 size_t l_mid;
1929
1930 if (*p1 == 'f') {
1931 found_filename = True;
1932 new_elem = filename;
1933 }
1934 else if (*p1 == 'l') {
1935 found_lineno = True;
1936 sprintf(digit_arg, "%d", lineno);
1937 new_elem = digit_arg;
1938 }
1939 else if (*p1 == 'c') {
1940 sprintf(digit_arg, "%d", colno);
1941 new_elem = digit_arg;
1942 }
1943
1944 l_mid = strlen(new_elem);
1945
1946 argv[i] = xrealloc(argv[i], strlen(argv[i]) + l_mid + 1);
1947 curr = argv[i] + l_init; /* need to reinitialize it because of realloc */
1948 memmove(curr + l_mid, curr + 2, l_rest);
1949 memcpy(curr, new_elem, l_mid);
1950 curr += l_mid;
1951 }
1952 else if (ptr[1] == '%') { /* escaped %, skip both */
1953 curr = ptr + 2;
1954 }
1955 else {
1956 curr = ptr + 1;
1957 }
1958 }
1959 }
1960
1961 /* append line number and file name arguments if they were not specified */
1962 if (!found_lineno) {
1963 i++;
1964 argv = xrealloc(argv, (i + 1) * sizeof *argv);
1965 argv[i - 1] = xmalloc(LENGTH_OF_INT + 2);
1966 sprintf(argv[i - 1], "+%d", lineno);
1967 argv[i] = NULL;
1968 }
1969
1970 if (!found_filename) {
1971 i++;
1972 argv = xrealloc(argv, (i + 1) * sizeof *argv);
1973 argv[i - 1] = xstrdup(filename);
1974 argv[i] = NULL;
1975 }
1976
1977 return argv;
1978 }
1979
1980 char *
1981 xstrndup(const char *str, size_t len)
1982 {
1983 char *new_str = xmalloc(len + 1);
1984 memcpy(new_str, str, len);
1985 new_str[len] = '\0';
1986 return new_str;
1987 }
1988
1989 #if 0
1990 /*
1991 * Search integer array <arr> of length <arr_len> for for <item>.
1992 * Return the index of the item, or the index of the next smaller item
1993 * if there's no exact match. (That we want the latter is the
1994 * reason why we can't use bsearch()).
1995 */
1996 int
1997 binary_search(int *arr, int arr_len, int item)
1998 {
1999 int lower = -1;
2000 int upper = arr_len;
2001 int mid;
2002
2003 ASSERT(arr_len >= 1, "binary_search expects arrays of length >= 1");
2004
2005 do {
2006 mid = (lower + upper) / 2;
2007 if (item > arr[mid])
2008 lower = mid;
2009 else if (item < arr[mid])
2010 upper = mid;
2011 else /* exact match */
2012 return mid;
2013 } while (upper - lower > 1);
2014
2015 /* no exact match, return next lower item */
2016 if (mid > 0 && arr[mid] > item)
2017 return mid - 1;
2018 else
2019 return mid;
2020 }
2021 #endif /* 0 */