1# ungetc.m4 serial 10
2dnl Copyright (C) 2009-2021 Free Software Foundation, Inc.
3dnl This file is free software; the Free Software Foundation
4dnl gives unlimited permission to copy and/or distribute it,
5dnl with or without modifications, as long as this notice is preserved.
6
7AC_DEFUN_ONCE([gl_FUNC_UNGETC_WORKS],
8[
9  AC_REQUIRE([AC_PROG_CC])
10  AC_REQUIRE([AC_CANONICAL_HOST]) dnl for cross-compiles
11
12  AC_CACHE_CHECK([whether ungetc works on arbitrary bytes],
13    [gl_cv_func_ungetc_works],
14    [AC_RUN_IFELSE([AC_LANG_PROGRAM([[
15#include <stdio.h>
16      ]], [[FILE *f;
17            if (!(f = fopen ("conftest.tmp", "w+")))
18              return 1;
19            if (fputs ("abc", f) < 0)
20              { fclose (f); return 2; }
21            rewind (f);
22            if (fgetc (f) != 'a')
23              { fclose (f); return 3; }
24            if (fgetc (f) != 'b')
25              { fclose (f); return 4; }
26            if (ungetc ('d', f) != 'd')
27              { fclose (f); return 5; }
28            if (ftell (f) != 1)
29              { fclose (f); return 6; }
30            if (fgetc (f) != 'd')
31              { fclose (f); return 7; }
32            if (ftell (f) != 2)
33              { fclose (f); return 8; }
34            if (fseek (f, 0, SEEK_CUR) != 0)
35              { fclose (f); return 9; }
36            if (ftell (f) != 2)
37              { fclose (f); return 10; }
38            if (fgetc (f) != 'c')
39              { fclose (f); return 11; }
40            fclose (f);
41            remove ("conftest.tmp");
42          ]])],
43        [gl_cv_func_ungetc_works=yes], [gl_cv_func_ungetc_works=no],
44        [case "$host_os" in
45                          # Guess yes on glibc systems.
46           *-gnu* | gnu*) gl_cv_func_ungetc_works="guessing yes" ;;
47                          # Guess yes on musl systems.
48           *-musl*)       gl_cv_func_ungetc_works="guessing yes" ;;
49                          # Guess yes on bionic systems.
50           *-android*)    gl_cv_func_ungetc_works="guessing yes" ;;
51                          # Guess yes on native Windows.
52           mingw*)        gl_cv_func_ungetc_works="guessing yes" ;;
53                          # If we don't know, obey --enable-cross-guesses.
54           *)             gl_cv_func_ungetc_works="$gl_cross_guess_normal" ;;
55         esac
56        ])
57    ])
58  gl_ftello_broken_after_ungetc=no
59  case "$gl_cv_func_ungetc_works" in
60    *yes) ;;
61    *)
62      dnl On macOS >= 10.15, where the above program fails with exit code 6,
63      dnl we fix it through an ftello override.
64      case "$host_os" in
65        darwin*) gl_ftello_broken_after_ungetc=yes ;;
66        *)
67          AC_DEFINE([FUNC_UNGETC_BROKEN], [1],
68            [Define to 1 if ungetc is broken when used on arbitrary bytes.])
69          ;;
70      esac
71      ;;
72  esac
73])
74