#!/bin/sh # # Copyright 2011 # Kaz Kylheku # Vancouver, Canada # All rights reserved. # # BSD License: # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in # the documentation and/or other materials provided with the # distribution. # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior # written permission. # # THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR # IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. # # Save command line in a way that can be re-run. # This takes care of spaces, but if there are shell-meta characters # in the arguments, oops. # set -u cmdline= for arg in "$0" ${@+"$@"} ; do [ -n "$cmdline" ] && cmdline="$cmdline " case $arg in *" "* | " "* | *" " ) cmdline=$cmdline$(printf "\"%s\"" "$arg") ;; * ) cmdline=$cmdline$arg ;; esac done # # Establish default values for any variables that are not specified # on the command line. The default derivations from prefix are in # Make syntax. They go verbatim into the generated config.make. # This way they can be overridden more flexibly at make time. # # # non-config # help= # # config # prefix=/usr/local install_prefix= bindir='$(prefix)/bin' datadir='$(prefix)/share/txr' mandir='$(prefix)/share/man' make= cross= compiler_prefix= ccname=gcc cc='$(cross)$(compiler_prefix)$(ccname)' intptr= tool_prefix= lex='$(cross)$(tool_prefix)flex' lexlib=-lfl yaccname_given= yaccname= yacc='$(cross)$(tool_prefix)$(yaccname)' yacc_given= nm='$(cross)$(tool_prefix)nm' opt_flags=-O2 lang_flags='--ansi -D_XOPEN_SOURCE=2' diag_flags='-Wall -Wmissing-prototypes -Wstrict-prototypes' debug_flags=-g inline= platform_flags= remove_flags= lex_dbg_flags= txr_dbg_opts=--gc-debug valgrind= lit_align= extra_debugging= debug_support=y gen_gc= mpi_version=1.8.6 have_quilt= have_patch= # # Parse configuration variables # while [ $# -gt 0 ] ; do case $1 in --no-* | --no_* ) var=${1#--no?} val= ;; --*=* ) var=${1%%=*} var=${var#--} val=${1#*=} ;; --*= ) var=${1%%=*} var=${var#--} val= ;; --* ) var=${1#--} val=y ;; *=* ) var=${1%%=*} val=${1#*=} ;; *= ) var=${1%%=*} val= ;; * ) printf "$0: '$1' doesn't look like a configuration variable assignment\n" printf "$0: use --help to get help\n" exit 1 esac var=$(echo "$var" | tr - _) if ! echo $var | grep -q -E '^[A-Za-z_][A-Za-z0-9_]*$' ; then printf "$0: '$var' isn't a proper configuration variable name\n" exit 1 fi eval "var_exists=\${$var+y}" if [ "$var_exists" != y ] ; then printf "$0: nonexistent option: '%s'\n" "$1" exit 1 fi eval "$var='$val'" eval "var_given_exists=\${${var}_given+y}" if [ "$var_given_exists" = y ] ; then eval "${var}_given=y" fi shift done # # If --help was given (or --help= or help=) then # print help and exit. The termination status is failed, to indicate # that configuration was not done. # if [ -n "$help" ] ; then cat < /dev/null) || true set -- $output printf "\$@=<$1> <$2> <$3>\n" if [ $1 != "GNU" -o $2 != "Make" ] ; then continue fi break done fi if [ -z "$make" ] ; then printf "missing\n" exit 1 fi make_version=$3 save_ifs=$IFS ; IFS=. ; set -- $make_version ; IFS=$save_ifs if [ $1 -lt 3 -o \( $1 -eq 3 -a $2 -lt 80 \) ] ; then printf "too old (%s found, 3.80 or newer needed)\n" $make_version exit 1 else printf "yes (%s found)\n" $make_version fi # # Verify sanity of --prefix and other directories. # printf "Checking installation paths:\n" for name in prefix bindir datadir mandir; do eval path="\$install_prefix\${$name}" printf "\$(install_prefix)\$(%s)=%s ... " $name "$path" test_access=y case "$path" in " "* | *" "* | *" " ) printf "incorrect (contains spaces)\n" exit 1 ;; -* ) printf "incorrect (resembles a command option)\n" exit 1 ;; *'$('* ) # It's a make expression; can't test it test_access= ;; /* ) ;; * ) printf "incorrect (must be absolute path)\n" exit 1 ;; esac if [ $test_access ] ; then test_prefix=$path while true ; do if [ -e $test_prefix ] ; then if [ ! -d $test_prefix ] ; then printf "incorrect ('%s' is not a directory)!\n" $test_prefix exit 1 fi if [ ! -w $test_prefix ] ; then printf "okay\n (but no write access to '%s'\n" $test_prefix printf " so '$make install' will require root privileges)\n" else printf "okay\n" fi break fi test_prefix=$(dirname $test_prefix) done else printf "okay\n (make variable derivation)\n" fi done # # First, we have to figure out whether we are configured straight # in the source directory, or whether we are in a separate build directory. # In the latter case, we set up a symbolic link to the Makefile. # source_dir="$(dirname $0)" # # Compute an absolute path to the source directory. # top_srcdir="$(cd "$source_dir" ; pwd -P)" printf "Checking source directory %s ..." "$top_srcdir" case "$top_srcdir" in " "* | *" "* | *" " ) printf " bad (contains spaces)\n" exit 1 ;; * ) printf " okay\n" ;; esac if [ "$source_dir" != "." ] ; then printf "Symlinking Makefile -> $source_dir/Makefile\n" ln -sf "$source_dir/Makefile" . else printf "Warning: its recommended to build in a separate directory\n" fi gen_config_make() { cat > config.make < config.h /* * Header file automatically generated by $0. * Tweaking this file may seem like a good temporary workaround * than tweak the file, but you probably should fix the script * to do the job. In any case, be aware that you will lose your * changes if you re-run $0. */ ! # # Check C compiler sanity # printf "Checking whether your C compiler can make a simple executable ... " cat > conftest.c < int main(void) { printf("Hello, world!\n"); return 0; } ! rm -f conftest if ! $make conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "failed\n\n" printf "Errors from compilation: \n\n" cat conftest.err exit 1 fi rm -f conftest printf "okay\n" # # Check for annoying clashes from non-conforming BSD-derived systems that don't # honor Unix/POSIX feature selection macros! # printf "Checking for name clashes caused by nonconforming toolchains ... " for ident in trunc floorf random longlong_t ; do cat > conftest.c < #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include struct txr_foo { int txr; } $ident; int $ident(void); int main(void) { return 0; } ! rm -f conftest if ! $make conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "#define %s txr_%s\n" $ident $ident >> config.h fi done printf "done\n" # # Check for annoying warnings from ctype.h macros # printf "Checking for annoying warnings from macros ... " cat > conftest.c < int main(void) { char x = '3'; return isdigit(x); } ! if ! $make EXTRA_FLAGS=-Werror conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "present\n" cat >> config.h < conftest.c < conftest.err 2>&1 ; then longlong=$try_type break fi done if [ -n "$longlong" ] ; then printf '"%s"\n' "$longlong" printf "#define HAVE_LONGLONG_T 1\n" >> config.h printf "typedef $longlong longlong_t;\n" >> config.h else printf "none\n" fi printf "Checking what C type we have for unsigned integers wider than \"long\" ... " ulonglong= for try_type in uint64 __uint64 "unsigned long long" ; do cat > conftest.c < conftest.err 2>&1 ; then ulonglong=$try_type break fi done if [ -n "$ulonglong" ] ; then printf '"%s"\n' "$ulonglong" printf "#define HAVE_ULONGLONG_T 1\n" >> config.h printf "typedef $ulonglong ulonglong_t;\n" >> config.h else printf "none\n" fi printf "Checking what C type we have for integers wider than \"long long\" ... " broken128= output=$($make conftest.ccver) set -- $output if [ "$1" = "gcc" ] ; then gcc_version=$3 save_ifs=$IFS ; IFS=. ; set -- $gcc_version ; IFS=$save_ifs if [ $1 -lt 4 ] || [ $1 -eq 4 -a $2 -le 3 ] ; then broken128=y fi fi superlong= if [ -z "$broken128" ] ; then for try_type in int128 int128_t __int128 __int128_t ; do cat > conftest.c < conftest.err 2>&1 ; then superlong=$try_type break fi done fi if [ -n "$superlong" ] ; then printf '"%s"\n' "$superlong" printf "#define HAVE_SUPERLONG_T 1\n" >> config.h printf "typedef $superlong superlong_t;\n" >> config.h else printf "none\n" fi printf "Checking what C type we have for u. integers wider than \"long long\" ... " usuperlong= if [ -z "$broken128" ] ; then for try_type in uint128 uint128_t __uint128 __uint128_t ; do cat > conftest.c < conftest.err 2>&1 ; then usuperlong=$try_type break fi done fi if [ -n "$usuperlong" ] ; then printf '"%s"\n' "$usuperlong" printf "#define HAVE_USUPERLONG_T 1\n" >> config.h printf "typedef $usuperlong usuperlong_t;\n" >> config.h else printf "none\n" fi printf "Checking what C integer type can hold a pointer ... " read_syms() { print_into_config=${1-} deferred_offset= while read symbol type offset size ; do size=$(( 0$size + 0 )) offset=$(( 0$offset + 0 )) symbol=${symbol#_} case "$type" in C ) size=$(( offset + 0 )) ;; S ) if [ -n "$deferred_offset" ] ; then size=$(( offset - deferred_offset )) case "$deferred_sym" in SIZEOF* ) eval $(printf "%s=%d\n" "$deferred_sym" "$size") if [ -n "$print_into_config" ] ; then printf "#define %s %s\n" "$deferred_sym" "$size" >> config.h fi ;; esac fi deferred_sym=$symbol deferred_offset=$offset continue ;; esac case "$symbol" in SIZEOF* ) eval $(printf "%s=%d\n" "$symbol" "$size") if [ -n "$print_into_config" ] ; then printf "#define %s %s\n" "$symbol" "$size" >> config.h fi ;; esac done < conftest.syms } if [ -z "$intptr" ] ; then cat > conftest.c < conftest.err 2>&1 ; then printf "failed\n\n" printf "Errors from compilation: \n\n" cat conftest.err exit 1 fi SIZEOF_PTR=0 SIZEOF_SHORT=0 SIZEOF_INT=0 SIZEOF_LONG=0 SIZEOF_LONGLONG_T=0 SIZEOF_SUPERLONG_T=0 read_syms y rm -f conftest.syms conftest.o if [ $SIZEOF_PTR -eq 0 ] ; then printf "failed\n" exit 1 fi if [ $SIZEOF_PTR -eq $SIZEOF_SHORT ] ; then intptr="short" uintptr=y elif [ $SIZEOF_PTR -eq $SIZEOF_INT ] ; then intptr="int" uintptr=y elif [ $SIZEOF_PTR -eq $SIZEOF_LONG ] ; then intptr="long" uintptr=y elif [ $SIZEOF_PTR -eq $SIZEOF_LONG_LONG_T ] ; then intptr="longlong_t" uintptr=$ulonglong fi if [ -z "$intptr" ] ; then printf "failed\n" exit 1 fi fi printf '"%s"\n' "$intptr" printf "typedef $intptr int_ptr_t;\n" >> config.h if [ -n "$uintptr" ] ; then printf "#define HAVE_UINTPTR_T 1\n" >> config.h printf "typedef unsigned $intptr uint_ptr_t;\n" >> config.h fi intptr_max_expr="((((($intptr) 1 << $((SIZEOF_PTR * 8 - 2))) - 1) << 1) + 1)" printf "#define INT_PTR_MAX %s\n" "$intptr_max_expr" >> config.h printf "#define INT_PTR_MIN (-INT_PTR_MAX)\n" >> config.h if [ -n "$longlong" ] && [ $SIZEOF_LONGLONG_T -eq $(( 2 * $SIZEOF_PTR )) ] then printf "#define HAVE_DOUBLE_INTPTR_T 1\n" >> config.h printf "typedef longlong_t double_intptr_t;\n" >> config.h elif [ -n "$superlong" ] && [ $SIZEOF_SUPERLONG_T -eq $(( 2 * $SIZEOF_PTR )) ] then printf "#define HAVE_DOUBLE_INTPTR_T 1\n" >> config.h printf "typedef superlong_t double_intptr_t;\n" >> config.h fi #if HAVE_LONGLONG_T && # # Alignment of wchar_t # # What we really want to know is the alignment of wide string literals # like L"wide literal". # # We make pessimistic assumption that the size of the wchar_t type is this # alignment. # # There is no easy way to get the information without running a compiled # program. # printf "Conservatively guessing the alignment of wide literals ... " if [ -z "$lit_align" ] ; then cat > conftest.c < char SIZEOF_WCHAR_T[sizeof (wchar_t)]; char DUMMY; ! rm -f conftest.o conftest.syms if ! $make conftest.syms > conftest.err 2>&1 ; then printf "failed\n\n" printf "Errors from compilation: \n\n" cat conftest.err exit 1 fi SIZEOF_WCHAR_T=0 deferred_offset= read_syms rm -f conftest.syms conftest.o if [ $SIZEOF_WCHAR_T -eq 0 ] ; then printf "failed\n" exit 1 fi lit_align=$SIZEOF_WCHAR_T fi printf "%d\n" "$lit_align" printf "#define LIT_ALIGN %d\n" "$lit_align" >> config.h # # Inline functions # printf "Checking how to declare inline functions ... " if [ -z "$inline" ] ; then for inline in \ "inline" "static inline" "extern inline" \ "__inline__" "static __inline__" "extern __inline__" \ "static" do cat > conftest1.c < conftest2.c < conftest.err 2>&1 ; then continue fi break done fi printf '"%s"\n' "$inline" printf "#define INLINE $inline\n" >> config.h # # Valgrind # if [ -n "$valgrind" ] ; then printf "Checking valgrind API availability ... " cat > conftest.c < #ifdef VALGRIND_DO_CLIENT_REQUEST int main(void) { return 0; } #else syntax error #endif ! rm -rf conftest if ! $make conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "failed\n\n" printf "Errors from compilation: \n\n" cat conftest.err exit 1 fi printf "okay\n" printf "#define HAVE_VALGRIND\n" >> config.h fi # # Yacc tests # printf "Checking for yacc program ... " if [ -z "$yacc_given" -a -z "$yaccname_given" ] ; then rm -f conftest.yacc for yaccname in "yacc" "byacc" "bison -y" "" ; do yaccpath=$($make yaccname="$yaccname" conftest.yacc) if command -v $yaccpath > /dev/null ; then break; fi done if [ -z "$yaccname" ] ; then printf "not found\n" exit 1 fi printf '"%s"\n' "$yaccpath" else yaccpath=$($make conftest.yacc) case $yaccpath in *bison ) printf "error\n\n" printf "GNU Bison needs -y to behave like yacc\n\n" printf "This needs to be specified in the --yaccname or --yacc option\n\n" exit 1 ;; * ) if ! command -v $yaccpath > /dev/null ; then printf "not found\n\n" exit 1 fi printf "given\n" ;; esac fi # # sys/wait.h # printf "Checking whether we have ... " cat > conftest.c < int main(void) { return 0; } ! rm -f conftest if ! $make conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "no\n" else printf "yes\n" printf "#define HAVE_SYS_WAIT 1\n" >> config.h fi # # sys/stat.h # printf "Checking whether we have ... " cat > conftest.c < int main(void) { struct stat s; return 0; } ! rm -f conftest if ! $make conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "no\n" else printf "yes\n" printf "#define HAVE_SYS_STAT 1\n" >> config.h fi # # environ # printf "Checking whether we have environ ... " cat > conftest.c < int main(void) { extern char **environ; puts(environ[0]); return 0; } ! rm -f conftest if ! $make conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "no\n" else printf "yes\n" printf "#define HAVE_ENVIRON 1\n" >> config.h fi # # GetEnvironmentStrings # printf "Checking whether we have GetEnvironmentStrings ... " cat > conftest.c < int main(void) { WCHAR *ptr = GetEnvironmentStringsW(); return 0; } ! rm -f conftest if ! $make conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "no\n" else printf "yes\n" printf "#define HAVE_GETENVIRONMENTSTRINGS 1\n" >> config.h fi # # fork, pipe, exec, waitpid. # printf "Checking for POSIX fork/pipe/exec/waitpid ... " cat > conftest.c < #endif #include int main(int argc, char **argv) { int status, fd[2]; pid_t p = fork(); (void) execvp(argv[0], argv); (void) waitpid(p, &status, 0); (void) pipe(fd); return 0; } ! rm -f conftest if ! $make conftest > conftest.err 2>&1 || ! [ -x conftest ] ; then printf "no\n" else printf "yes\n" printf "#define HAVE_FORK_STUFF 1\n" >> config.h fi # # Check for fields inside struct tm # printf "Printf detecting timezone fields in struct tm ..." tm_gmtoff= tm_tmzone= for try_field in tm_gmtoff __tm_gmtoff ; do cat > conftest.c < int x = sizeof ((struct tm *) 0)->$try_field; ! rm -f conftest.o if $make conftest.o > conftest.err 2>&1 ; then printf "#define HAVE_TM_GMTOFF 1\n" >> config.h printf "#define TM_GMTOFF %s\n" $try_field >> config.h break fi done for try_field in tm_zone __tm_zone ; do cat > conftest.c < int x = sizeof ((struct tm *) 0)->$try_field; ! rm -f conftest.o if $make conftest.o > conftest.err 2>&1 ; then printf "#define HAVE_TM_ZONE 1\n" >> config.h printf "#define TM_ZONE %s\n" $try_field >> config.h break fi done printf "done\n" # # Extra debugging. # if [ -n "$extra_debugging" ] ; then printf "Configuring extra debugging, as requested ...\n" printf "#define EXTRA_DEBUGGING 1\n" >> config.h fi # # Clean up # rm -f conftest conftest.[co] conftest.{err,syms} rm -f conftest2 conftest[12].[oc] # # What do we have for patch management. # printf "Checking for quilt ... " if ! quilt --version > /dev/null 2>&1 ; then printf "not found\n" else printf "found\n" have_quilt=y fi printf "Checking for patch ... " if ! patch --version > /dev/null 2>&1 ; then printf "not found\n" printf "\npatch tool required!\n\n" exit 1 else printf "found\n" have_patch=y fi # # Function to apply patches. # apply_patches() { if ! [ -e patches/series ] ; then echo "no patches" return 0 fi while read patch patchlevel ; do case patch in '#' ) continue ;; * ) patch ${patchlevel:--p1} < patches/$patch ;; esac done < patches/series } # # Try to extract MPI if not already. # printf "Extracting MPI ... " if [ -e mpi-${mpi_version} ] ; then printf "already extracted\n" else tar -xzf $top_srcdir/mpi-${mpi_version}.tar.gz printf "\n" printf "Symlinking MPI patches ...\n" ln -sf $top_srcdir/mpi-patches mpi-${mpi_version}/patches printf "Applying MPI patches ...\n" if [ -n "$have_quilt" ] ; then ( cd mpi-${mpi_version}/patches ; if [ -e series ] ; then quilt push -a ; else echo "no patches" ; fi ) else ( cd mpi-${mpi_version} ; apply_patches ) fi fi # # Some final blurbs into config.h # [ -n "$debug_support" ] && printf "#define CONFIG_DEBUG_SUPPORT 1\n" >> config.h [ -n "$gen_gc" ] && printf "#define CONFIG_GEN_GC 1\n" >> config.h # # Regenerate config.make # printf "Regenerating config.make ... " gen_config_make printf "\n" # # Save configuration in config.log # cat > config.log <844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859
/* Copyright 2009-2014
 * Kaz Kylheku <kaz@kylheku.com>
 * Vancouver, Canada
 * All rights reserved.
 *
 * BSD License:
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   1. Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 *   2. Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in
 *      the documentation and/or other materials provided with the
 *      distribution.
 *   3. The name of the author may not be used to endorse or promote
 *      products derived from this software without specific prior
 *      written permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

#include <stdio.h>
#include <string.h>
#include <dirent.h>
#include <stdarg.h>
#include <stdlib.h>
#include <setjmp.h>
#include <errno.h>
#include <ctype.h>
#include <wchar.h>
#include <signal.h>
#include "config.h"
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#if HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <float.h>
#if HAVE_SYS_WAIT
#include <sys/wait.h>
#endif
#if HAVE_SYS_STAT
#include <sys/stat.h>
#endif
#if HAVE_WINDOWS_H
#include <windows.h>
#endif
#if HAVE_MAKEDEV
#include <sys/types.h>
#endif
#include "lib.h"
#include "gc.h"
#include "signal.h"
#include "unwind.h"
#include "stream.h"
#include "utf8.h"
#include "eval.h"

val output_produced;

val stdin_s, stdout_s, stddebug_s, stderr_s, stdnull_s;

val dev_k, ino_k, mode_k, nlink_k, uid_k;
val gid_k, rdev_k, size_k, blksize_k, blocks_k;
val atime_k, mtime_k, ctime_k;
val from_start_k, from_current_k, from_end_k;
val real_time_k, name_k;
val format_s;

static void common_destroy(val obj)
{
  (void) close_stream(obj, nil);
}

static void null_stream_print(val stream, val out)
{
  format(out, lit("#<~s null>"), stream->co.cls, nao);
}

static val null_get_prop(val stream, val ind)
{
  if (ind == name_k)
    return lit("null-stream");
  return nil;
}

static struct strm_ops null_ops = {
  { eq,
    null_stream_print,
    cobj_destroy_stub_op,
    cobj_mark_op,
    cobj_hash_op },
  0, /* put_string */
  0, /*_put_char */
  0, /* put_byte, */
  0, /* get_line, */
  0, /* get_char, */
  0, /* get_byte, */
  0, /* unget_char, */
  0, /* unget_byte, */
  0, /* close, */
  0, /* flush, */
  0, /* seek, */
  null_get_prop,
  0, /* set_prop */
};

val make_null_stream(void)
{
  return cobj((mem_t *) 0, stream_s, &null_ops.cobj_ops);
}

struct stdio_handle {
  FILE *f;
  val descr;
  val unget_c;
  utf8_decoder_t ud;
#if HAVE_FORK_STUFF
  pid_t pid;
#else
  int pid;
#endif
  val mode; /* used by tail */
  unsigned is_rotated; /* used by tail */
  unsigned is_real_time;
};

static void stdio_stream_print(val stream, val out)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  if (h->pid)
    format(out, lit("#<~s ~s>"), stream->co.cls, h->descr, nao);
  else
    format(out, lit("#<~s ~s ~s>"), stream->co.cls, h->descr, h->pid, nao);
}

static void stdio_stream_destroy(val stream)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  common_destroy(stream);
  free(h);
}

static void stdio_stream_mark(val stream)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  gc_mark(h->descr);
  gc_mark(h->mode);
}

static val stdio_maybe_read_error(val stream)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  if (h->f == 0)
    uw_throwf(file_error_s, lit("error reading ~a: file closed"), stream, nao);
  if (ferror(h->f)) {
    clearerr(h->f);
    uw_throwf(file_error_s, lit("error reading ~a: ~a/~s"),
              stream, num(errno), string_utf8(strerror(errno)), nao);
  }
  return nil;
}

static val stdio_maybe_error(val stream, val action)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  if (h->f == 0)
    uw_throwf(file_error_s, lit("error ~a ~a: file closed"), stream, action, nao);
  clearerr(h->f);
  uw_throwf(file_error_s, lit("error ~a ~a: ~a/~s"),
            stream, action, num(errno), string_utf8(strerror(errno)), nao);
}

static int se_putc(int ch, FILE *f)
{
  int ret;
  sig_save_enable;
  ret = putc(ch, f);
  sig_restore_enable;
  return ret;
}

static int se_getc(FILE *f)
{
  int ret;
  sig_save_enable;
  ret = getc(f);
  sig_restore_enable;
  return ret;
}

static int se_fflush(FILE *f)
{
  int ret;
  sig_save_enable;
  ret = fflush(f);
  sig_restore_enable;
  return ret;
}

static int stdio_put_char_callback(int ch, mem_t *f)
{
  int ret = se_putc(ch, (FILE *) f) != EOF;
  return ret;
}

static int stdio_get_char_callback(mem_t *f)
{
  return se_getc((FILE *) f);
}

static val stdio_put_string(val stream, val str)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  if (stream != std_debug && stream != std_error)
    output_produced = t;

  if (h->f != 0) {
    const wchar_t *s = c_str(str);

    while (*s) {
      if (!utf8_encode(*s++, stdio_put_char_callback, (mem_t *) h->f))
        return stdio_maybe_error(stream, lit("writing"));
    }
    return t;
  }
  return stdio_maybe_error(stream, lit("writing"));
}

static val stdio_put_char(val stream, val ch)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  if (stream != std_debug && stream != std_error)
    output_produced = t;

  return h->f != 0 && utf8_encode(c_chr(ch), stdio_put_char_callback, (mem_t *) h->f)
         ? t : stdio_maybe_error(stream, lit("writing"));
}

static val stdio_put_byte(val stream, int b)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  if (stream != std_debug && stream != std_error)
    output_produced = t;

  return h->f != 0 && se_putc(b, (FILE *) h->f) != EOF
         ? t : stdio_maybe_error(stream, lit("writing"));
}

static val stdio_flush(val stream)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  return (h->f != 0 && se_fflush(h->f) == 0)
         ? t : stdio_maybe_error(stream, lit("flushing"));
}

static val stdio_seek(val stream, cnum offset, enum strm_whence whence)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  if (h->f != 0) {
    if (offset == 0 && whence == strm_cur) {
      long where = ftell(h->f);
      if (where >= 0)
        return num(where);
    } else {
      if (fseek(h->f, offset, whence) == 0) {
        utf8_decoder_init(&h->ud);
        h->unget_c = nil;
        return t;
      }
    }
  }

  return stdio_maybe_error(stream, lit("seeking"));
}

static val stdio_get_prop(val stream, val ind)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  if (ind == real_time_k) {
    return h->is_real_time ? t : nil;
  } else if (ind == name_k) {
    return h->descr;
  }
  return nil;
}

static val stdio_set_prop(val stream, val ind, val prop)
{
  if (ind == real_time_k) {
    struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
    h->is_real_time = prop ? 1 : 0;
    return t;
  }
  return nil;
}

static wchar_t *snarf_line(struct stdio_handle *h)
{
  const size_t min_size = 512;
  size_t size = 0;
  size_t fill = 0;
  wchar_t *buf = 0;

  for (;;) {
    wint_t ch;
   
    if (h->unget_c) {
      ch = c_chr(h->unget_c);
      h->unget_c = nil;
    } else {
      ch = utf8_decode(&h->ud, stdio_get_char_callback, (mem_t *) h->f);
    }

    if (ch == WEOF && buf == 0)
      break;

    if (fill >= size) {
      size_t newsize = size ? size * 2 : min_size;
      buf = (wchar_t *) chk_realloc((mem_t *) buf, newsize * sizeof *buf);
      size = newsize;
    }

    if (ch == '\n' || ch == WEOF) {
      buf[fill++] = 0;
      break;
    }
    buf[fill++] = ch;
  }

  if (buf)
    buf = (wchar_t *) chk_realloc((mem_t *) buf, fill * sizeof *buf);

  return buf;
}

static val stdio_get_line(val stream)
{
  if (stream->co.handle == 0) {
    return stdio_maybe_read_error(stream);
  } else {
    struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
    wchar_t *line = snarf_line(h);
    if (!line)
      return stdio_maybe_read_error(stream);
    return string_own(line);
  }
}

static val stdio_get_char(val stream)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  val uc = h->unget_c;
  if (uc) {
    h->unget_c = nil;
    return uc;
  }
  if (h->f) {
    wint_t ch = utf8_decode(&h->ud, stdio_get_char_callback, (mem_t *) h->f);
    return (ch != WEOF) ? chr(ch) : stdio_maybe_read_error(stream);
  }
  return stdio_maybe_read_error(stream);
}

static val stdio_get_byte(val stream)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  if (h->f) {
    int ch = se_getc(h->f);
    return (ch != EOF) ? num(ch) : stdio_maybe_read_error(stream);
  }
  return stdio_maybe_read_error(stream);
}

static val stdio_unget_char(val stream, val ch)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  if (!is_chr(ch))
    type_mismatch(lit("unget-char: ~s is not a character"), ch, nao);

  if (h->unget_c)
    uw_throwf(file_error_s, lit("unget-char overflow on ~a: "), stream, nao);

  h->unget_c = ch;
  return ch;
}

static val stdio_unget_byte(val stream, int byte)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  return h->f != 0 && ungetc(byte, (FILE *) h->f) != EOF
         ? num_fast(byte)
         : stdio_maybe_error(stream, lit("pushing back byte into"));
}

static val stdio_close(val stream, val throw_on_error)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  if (h->f != 0 && h->f != stdin && h->f != stdout) {
    int result = fclose(h->f);
    h->f = 0;
    if (result == EOF && throw_on_error) {
      uw_throwf(file_error_s, lit("error closing ~a: ~a/~s"),
                stream, num(errno), string_utf8(strerror(errno)), nao);
    }
    return result != EOF ? t : nil;
  }
  return nil;
}

static struct strm_ops stdio_ops = {
  { eq,
    stdio_stream_print,
    stdio_stream_destroy,
    stdio_stream_mark,
    cobj_hash_op },
  stdio_put_string,
  stdio_put_char,
  stdio_put_byte,
  stdio_get_line,
  stdio_get_char,
  stdio_get_byte,
  stdio_unget_char,
  stdio_unget_byte,
  stdio_close,
  stdio_flush,
  stdio_seek,
  stdio_get_prop,
  stdio_set_prop
};

static void tail_calc(unsigned long *state, int *sec, int *mod)
{
  unsigned long count = (*state)++;
  if (count > 32)
    count = 32;
  *sec = 1 << (count / 8);
  *mod = 8 >> (count / 8);
  if (*mod == 0)
    *mod = 1;
}

#if !HAVE_POSIX_SLEEP && HAVE_WINDOWS_H

int sleep(int sec);

int sleep(int sec)
{
   Sleep(sec * 1000);
   return 0;
}

#endif

static void tail_strategy(val stream, unsigned long *state)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  int sec = 0, mod = 0;

  tail_calc(state, &sec, &mod);

  if (h->is_rotated) {
    /* We already know that the file has rotated. The caller
     * has read through to the end of the old open file, and
     * so we can close it now and open a new file.
     */
    fclose(h->f);
    h->f = 0;
    h->is_rotated = 0;
  } else if (h->f != 0) {
    /* We have a file and it hasn't rotated; so sleep on it. */
    sig_save_enable;
    sleep(sec);
    sig_restore_enable;
  }

  /* If the state indicates we should poll for a file rotation,
   * or we have no file ...
   */
  if (h->f == 0 || *state % mod == 0) {
    long save_pos = 0, size;

    if (h->f != 0 && (save_pos = ftell(h->f)) == -1)
      return;

    for (;;) {
      FILE *newf;

      /* Try to open the file. 
       */
      if (!(newf = w_fopen(c_str(h->descr), c_str(h->mode)))) {
        /* If already have the file open previously, and the name
         * does not open any more, then the file has rotated.
         * Have the caller try to read the last bit of data
         * from the old h->f.
         */
        if (h->f) {
          h->is_rotated = 1;
          return;
        }

        /* Unable to open; keep trying. */
        tail_calc(state, &sec, &mod);
        sig_save_enable;
        sleep(sec);
        sig_restore_enable;
        continue;
      }

      /* We opened the new file. If we have no old file,
       * then this is all we have.
       */
      if (!h->f) {
        h->f = newf;
        break;
      }

      /* Obtain size of new file. If we can't, then let's just pretend we never
       * opened it and bail out. 
       */
      if (fseek(newf, 0, SEEK_END) == -1 || (size = ftell(newf)) == -1) {
        fclose(newf);
        return;
      }

      /* The newly opened file is smaller than the previously opened
       * file. The file has rotated and is quite possibly a new object.
       * We just close newf, and let the caller read the last bit of data from
       * the old stream before cutting over.
       */
      if (size < save_pos) {
        /* TODO: optimize: keep newf in the handle so as not to have to
           re-open it again. */
        h->is_rotated = 1;
        fclose(newf);
        return;
      }

      /* Newly opened file is not smaller. We take a gamble and say
       * that it's the same object as h->f, since rotating files 
       * are usually large and it is unlikely that it is a new file
       * which has grown larger than the original. Just in case,
       * though, we take the new file handle. But we do not reset
       * the UTF8 machine.
       */
      if (save_pos)
        fseek(newf, save_pos, SEEK_SET);
      fclose(h->f);
      h->f = newf;
      return;
    }

    utf8_decoder_init(&h->ud);
  }
}

static val tail_get_line(val stream)
{
  unsigned long state = 0;
  val ret;

  while ((ret = stdio_get_line(stream)) == nil)
    tail_strategy(stream, &state);

  return ret;
}

static val tail_get_char(val stream)
{
  unsigned long state = 0;
  val ret;

  while ((ret = stdio_get_char(stream)) == nil)
    tail_strategy(stream, &state);

  return ret;
}

static val tail_get_byte(val stream)
{
  unsigned long state = 0;
  val ret;

  while ((ret = stdio_get_byte(stream)) == nil)
    tail_strategy(stream, &state);

  return ret;
}


static struct strm_ops tail_ops = {
  { eq,
    stdio_stream_print,
    stdio_stream_destroy,
    stdio_stream_mark,
    cobj_hash_op },
  stdio_put_string,
  stdio_put_char,
  stdio_put_byte,
  tail_get_line,
  tail_get_char,
  tail_get_byte,
  stdio_unget_char,
  stdio_unget_byte,
  stdio_close,
  stdio_flush,
  stdio_seek,
  stdio_get_prop,
  stdio_set_prop
};


#if HAVE_FORK_STUFF
static int pipevp_close(FILE *f, pid_t pid)
{
  int status;
  fclose(f);
  sig_save_enable;
  while (waitpid(pid, &status, 0) == -1 && errno == EINTR)
    ;
  sig_restore_enable;
  return status;
}
#endif

static int se_pclose(FILE *f)
{
  int ret;
  sig_save_enable;
  ret = pclose(f);
  sig_restore_enable;
  return ret;
}

static val pipe_close(val stream, val throw_on_error)
{
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;

  if (h->f != 0) {
#if HAVE_FORK_STUFF
    int status = h->pid != 0 ? pipevp_close(h->f, h->pid) : se_pclose(h->f);
#else
    int status = se_pclose(h->f);
#endif
    h->f = 0;

    if (status < 0) {
      if (throw_on_error)
        uw_throwf(process_error_s,
                  lit("unable to obtain status of command ~a: ~a/~s"),
                  stream, num(errno), string_utf8(strerror(errno)), nao);
    } else {
#ifdef HAVE_SYS_WAIT
      if (throw_on_error) {
        if (WIFSIGNALED(status)) {
          int termsig = WTERMSIG(status);
          uw_throwf(process_error_s, lit("pipe ~a terminated by signal ~a"),
                    stream, num(termsig), nao);
#ifndef WIFCONTINUED
#define WIFCONTINUED(X) 0
#endif
        } else if (WIFSTOPPED(status) || WIFCONTINUED(status)) {
          uw_throwf(process_error_s,
                    lit("processes of closed pipe ~a still running"),
                    stream, nao);
        }
      }
      if (WIFEXITED(status)) {
        int exitstatus = WEXITSTATUS(status);
        return num(exitstatus);
      }
#else
      if (status != 0 && throw_on_error)
        uw_throwf(process_error_s, lit("closing pipe ~a failed"), stream, nao);
#endif
      return status == 0 ? zero : nil;
    } 
  }
  return nil;
}

static struct strm_ops pipe_ops = {
  { eq,
    stdio_stream_print,
    stdio_stream_destroy,
    stdio_stream_mark,
    cobj_hash_op },
  stdio_put_string,
  stdio_put_char,
  stdio_put_byte,
  stdio_get_line,
  stdio_get_char,
  stdio_get_byte,
  stdio_unget_char,
  stdio_unget_byte,
  pipe_close,
  stdio_flush,
  0, /* seek: not on pipes */
  stdio_get_prop,
  stdio_set_prop
};

static void string_in_stream_mark(val stream)
{
  val stuff = (val) stream->co.handle;
  gc_mark(stuff);
}

static val find_char(val string, val start, val ch)
{
  const wchar_t *str = c_str(string);
  cnum pos = c_num(start);
  cnum len = c_num(length_str(string));
  wchar_t c = c_chr(ch);

  for (; pos < len; pos++) {
    if (str[pos] == c)
      return num(pos);
  }

  return nil;
}

static val string_in_get_line(val stream)
{
  val pair = (val) stream->co.handle;
  val string = car(pair);
  val pos = cdr(pair);

  if (lt(pos, length_str(string))) {
    val nlpos = find_char(string, pos, chr('\n'));
    val result = sub_str(string, pos, nlpos);
    set(*cdr_l(pair), nlpos ? plus(nlpos, one) : length_str(string));
    return result;
  }

  return nil;
}

static val string_in_get_char(val stream)
{
  val pair = (val) stream->co.handle;
  val string = car(pair);
  val pos = cdr(pair);

  if (lt(pos, length_str(string))) {
    set(*cdr_l(pair), plus(pos, one));
    return chr_str(string, pos);
  }

  return nil;
}

static val string_in_unget_char(val stream, val ch)
{
  val pair = (val) stream->co.handle;
  val string = car(pair);
  val pos = cdr(pair);

  if (pos == zero)
    uw_throwf(file_error_s,
              lit("unget-char: cannot push past beginning of string"), nao);

  pos = minus(pos, one);

  if (chr_str(string, pos) != ch)
    uw_throwf(file_error_s,
              lit("unget-char: ~s doesn't match the character that was read"),
              nao);

  set(*cdr_l(pair), plus(pos, one));
  return ch;
}

static val string_in_get_prop(val stream, val ind)
{
  if (ind == name_k) {
    val pair = (val) stream->co.handle;
    return format(nil, lit("string-stream (~s)"), car(pair), nao);
  }
  return nil;
}

static struct strm_ops string_in_ops = {
  { eq,
    cobj_print_op,
    cobj_destroy_stub_op,
    string_in_stream_mark,
    cobj_hash_op },
  0, /* put_string */
  0, /* put_char */
  0, /* put_byte */
  string_in_get_line,
  string_in_get_char,
  0, /* get_byte */
  string_in_unget_char,
  0, /* unget_byte, */
  0, /* close */
  0, /* flush */
  0, /* TODO: seek */
  string_in_get_prop,
  0  /* set_prop */
};

struct byte_input {
  unsigned char *buf;
  size_t size;
  size_t index;
};

static void byte_in_stream_destroy(val stream)
{
  struct byte_input *bi = (struct byte_input *) stream->co.handle;

  if (bi) {
    free(bi->buf);
    bi->buf = 0;
    free(bi);
    stream->co.handle = 0;
  }
}

static val byte_in_get_byte(val stream)
{
  struct byte_input *bi = (struct byte_input *) stream->co.handle;

  if (bi->index < bi->size)
    return num(bi->buf[bi->index++]);
  return nil;
}

static val byte_in_unget_byte(val stream, int byte)
{
  struct byte_input *bi = (struct byte_input *) stream->co.handle;

  if (bi->index == 0)
    uw_throwf(file_error_s,
              lit("unget-char: cannot push past beginning of byte stream"),
              nao);

  bi->buf[--bi->index] = byte;
  return num_fast(byte);
}

static struct strm_ops byte_in_ops = {
  { eq,
    cobj_print_op,
    byte_in_stream_destroy,
    cobj_mark_op,
    cobj_hash_op },
  0, /* put_string */
  0, /* put_char */
  0, /* put_byte */
  0, /* get_line */
  0, /* get_char */
  byte_in_get_byte,
  0, /* unget_char, */
  byte_in_unget_byte,
  0, /* close */
  0, /* flush */
  0, /* TODO: support seek */
  0, /* get_prop */
  0  /* set_prop */
};


struct string_output {
  wchar_t *buf;
  size_t size;
  size_t fill;
  utf8_decoder_t ud; 
  unsigned char byte_buf[4];
  int head, tail;
};

static void string_out_stream_destroy(val stream)
{
  struct string_output *so = (struct string_output *) stream->co.handle;

  if (so) {
    free(so->buf);
    so->buf = 0;
    free(so);
    stream->co.handle = 0;
  }
}

static int string_out_byte_callback(mem_t *ctx)
{
  struct string_output *so = (struct string_output *) ctx;
  if (so->tail >= so->head)
    return EOF;
  return so->byte_buf[so->tail++];
}

static val string_out_put_char(val stream, val ch);

static val string_out_byte_flush(struct string_output *so, val stream)
{
  val result = nil;

  if (so->tail < so->head) {
    wint_t ch = utf8_decode(&so->ud, string_out_byte_callback, (mem_t *) so);
    int remaining = so->head - so->tail;
    if (remaining != 0)
      memmove(so->byte_buf, so->byte_buf + so->tail, remaining);
    so->head = so->tail = remaining;
    utf8_decoder_init(&so->ud);
    if (ch == WEOF)
      internal_error("unexpected WEOF from utf8_decode");
    result = string_out_put_char(stream, chr(ch));
    so->tail = 0;
  }
  return result;
}

static val string_out_put_string(val stream, val str)
{
  struct string_output *so = (struct string_output *) stream->co.handle;

  if (so == 0)
    return nil;

  while (so->head != so->tail)
    string_out_byte_flush(so, stream);

  {
    const wchar_t *s = c_str(str);
    size_t len = c_num(length_str(str));
    size_t old_size = so->size;
    size_t required_size = len + so->fill + 1;

    if (required_size < len)
      return nil;

    while (so->size <= required_size) {
      so->size *= 2;
      if (so->size < old_size)
        return nil;
    }

    if (so->size != old_size)
      so->buf = (wchar_t *) chk_realloc((mem_t *) so->buf,
                                        so->size * sizeof *so->buf);
    wmemcpy(so->buf + so->fill, s, len + 1);
    so->fill += len;
    return t;
  }
}

static val string_out_put_char(val stream, val ch)
{
  wchar_t onech[] = wini(" ");
  wref(onech)[0] = c_chr(ch);
  return string_out_put_string(stream, auto_str((const wchli_t *) wref(onech)));
}

static val string_out_put_byte(val stream, int ch)
{
  struct string_output *so = (struct string_output *) stream->co.handle;

  if (so == 0)
    return nil;

  so->byte_buf[so->head++] = ch;

  if (so->head >= (int) sizeof so->byte_buf)
    return string_out_byte_flush(so, stream);

  return t;
}

static struct strm_ops string_out_ops = {
  { eq,
    cobj_print_op,
    string_out_stream_destroy,
    cobj_mark_op,
    cobj_hash_op },
  string_out_put_string,
  string_out_put_char,
  string_out_put_byte,
  0, /* get_line */
  0, /* get_char */
  0, /* get_byte */
  0, /* unget_char, */
  0, /* unget_byte, */
  0, /* close */
  0, /* flush */
  0, /* TODO: seek, with fill-with-spaces semantics if past end. */
  0, /* get_prop */
  0  /* set_prop */
};

static void strlist_mark(val stream)
{
  val stuff = (val) stream->co.handle;
  gc_mark(stuff);
}

static val strlist_out_put_string(val stream, val str)
{
  val cell = (val) stream->co.handle;
  cons_bind (lines, strstream, cell);

  for (;;) {
    val length = length_str(str);
    val span_to_newline = compl_span_str(str, lit("\n"));

    if (zerop(length))
      break;

    put_string(sub_str(str, nil, span_to_newline), strstream);

    if (equal(span_to_newline, length))
      break;

    str = sub_str(str, plus(span_to_newline, num(1)), nil);
    push(get_string_from_stream(strstream), &lines);
    strstream = make_string_output_stream();
  }

  set(*car_l(cell), lines);
  set(*cdr_l(cell), strstream);

  return t;
}

static val strlist_out_put_char(val stream, val ch)
{
  val cell = (val) stream->co.handle;
  cons_bind (lines, strstream, cell);

  if (ch == chr('\n')) {
    push(get_string_from_stream(strstream), &lines);
    strstream = make_string_output_stream();
  } else {
    put_char(ch, strstream);
  }

  set(*car_l(cell), lines);
  set(*cdr_l(cell), strstream);

  return t;
}

static struct strm_ops strlist_out_ops = {
  { eq,
    cobj_print_op,
    cobj_destroy_stub_op,
    strlist_mark,
    cobj_hash_op },
  strlist_out_put_string,
  strlist_out_put_char,
  0, /* TODO: put_byte */
  0, /* get_line */
  0, /* get_char */
  0, /* get_byte */
  0, /* unget_char, */
  0, /* unget_byte, */
  0, /* close */
  0, /* flush */
  0, /* seek */
  0, /* get_prop */
  0  /* set_prop */
};

val make_strlist_output_stream(void)
{
  return cobj((mem_t *) cons(nil, make_string_output_stream()), 
              stream_s, &strlist_out_ops.cobj_ops);
}

val get_list_from_stream(val stream)
{
  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s,
               (lit("~a is not a stream"), stream, nao));

  if (stream->co.ops == &strlist_out_ops.cobj_ops) {
    val cell = (val) stream->co.handle;
    cons_bind (lines, strstream, cell);
    val stray = get_string_from_stream(strstream);
    if (!zerop(length_str(stray)))
      push(stray, &lines);
    return nreverse(lines);
  }

  type_mismatch(lit("~s is not a string list stream"), stream);
}

static val dir_get_line(val stream)
{
  DIR *handle = (DIR *) stream->co.handle;

  if (handle == 0) {
    return nil;
  } else {
    for (;;) {
      struct dirent *e = readdir(handle);
      if (!e)
        return nil;
      if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, ".."))
        continue;
      return string_utf8(e->d_name);
    }
  }
}

static val dir_close(val stream, val throw_on_error)
{
  if (stream->co.handle != 0) {
    closedir((DIR *) stream->co.handle);
    stream->co.handle = 0;
    return t;
  }

  return nil;
}

static struct strm_ops dir_ops = {
  { eq,
    cobj_print_op,
    common_destroy,
    cobj_mark_op,
    cobj_hash_op },
  0, /* put_string */
  0, /* put_char */
  0, /* put_byte */
  dir_get_line,
  0, /* get_char */
  0, /* get_byte */
  0, /* unget_char, */
  0, /* unget_byte, */
  dir_close,
  0, /* flush */
  0, /* seek */
  0, /* get_prop */
  0  /* set_prop */
};

static val make_stdio_stream_common(FILE *f, val descr, struct cobj_ops *ops)
{
  struct stdio_handle *h = (struct stdio_handle *) chk_malloc(sizeof *h);
  val stream = cobj((mem_t *) h, stream_s, ops);
  h->f = f;
  h->descr = descr;
  h->unget_c = nil;
  utf8_decoder_init(&h->ud);
  h->pid = 0;
  h->mode = nil;
  h->is_rotated = 0;
#if HAVE_ISATTY
  h->is_real_time = (h->f != 0 && isatty(fileno(h->f)) == 1);
#else
  h->is_real_time = 0;
#endif
  return stream;
}

val make_stdio_stream(FILE *f, val descr)
{
  return make_stdio_stream_common(f, descr, &stdio_ops.cobj_ops);
}

val make_tail_stream(FILE *f, val descr)
{
  val stream = make_stdio_stream_common(f, descr, &tail_ops.cobj_ops);
  stream_set_prop(stream, real_time_k, t);
  return stream;
}

val make_pipe_stream(FILE *f, val descr)
{
  return make_stdio_stream_common(f, descr, &pipe_ops.cobj_ops);
}

#if HAVE_FORK_STUFF
static val make_pipevp_stream(FILE *f, val descr, pid_t pid)
{
  val stream = make_stdio_stream_common(f, descr, &pipe_ops.cobj_ops);
  struct stdio_handle *h = (struct stdio_handle *) stream->co.handle;
  h->pid = pid;
  return stream;
}
#endif

val make_string_input_stream(val string)
{
  return cobj((mem_t *) cons(string, zero), stream_s, &string_in_ops.cobj_ops);
}

val make_string_byte_input_stream(val string)
{
  type_assert (stringp(string), (lit("~a is not a string"), string, nao));

  {
    struct byte_input *bi = (struct byte_input *) chk_malloc(sizeof *bi);
    unsigned char *utf8 = utf8_dup_to_uc(c_str(string));
    bi->buf = utf8;
    bi->size = strlen((char *) utf8);
    bi->index = 0;
    return cobj((mem_t *) bi, stream_s, &byte_in_ops.cobj_ops);
  }
}

val make_string_output_stream(void)
{
  struct string_output *so = (struct string_output *) chk_malloc(sizeof *so);
  so->size = 128;
  so->buf = (wchar_t *) chk_malloc(so->size * sizeof so->buf);
  so->fill = 0;
  so->buf[0] = 0;
  utf8_decoder_init(&so->ud);
  so->head = so->tail = 0;
  return cobj((mem_t *) so, stream_s, &string_out_ops.cobj_ops);
}

val get_string_from_stream(val stream)
{
  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s,
               (lit("~a is not a stream"),
                stream, nao));

  if (stream->co.ops == &string_out_ops.cobj_ops) {
    struct string_output *so = (struct string_output *) stream->co.handle;
    val out = nil;

    if (!so)
      return out;

    while (so->head != so->tail)
      out = string_out_byte_flush(so, stream);

    stream->co.handle = 0;

    so->buf = (wchar_t *) chk_realloc((mem_t *) so->buf,
                                      (so->fill + 1) * sizeof *so->buf);
    out = string_own(so->buf);
    free(so);
    return out;
  } else {
    type_assert (stream->co.ops == &string_in_ops.cobj_ops,
                 (lit("~a is not a string stream"), stream, nao));
    {
      val pair = (val) stream->co.handle;
      return pair ? car(pair) : nil;
    }
  }
}

val make_dir_stream(DIR *dir)
{
  return cobj((mem_t *) dir, stream_s, &dir_ops.cobj_ops);
}

val streamp(val obj)
{
  return typeof(obj) == stream_s ? t : nil;
}

val stream_set_prop(val stream, val ind, val prop)
{
  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->set_prop ? ops->set_prop(stream, ind, prop) : nil;
  }
}

val stream_get_prop(val stream, val ind)
{
  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->get_prop ? ops->get_prop(stream, ind) : nil;
  }
}

val real_time_stream_p(val obj)
{
  if (streamp(obj)) {
    struct strm_ops *ops = (struct strm_ops *) obj->co.ops;
    return ops->get_prop ? ops->get_prop(obj, real_time_k) : nil;
  }

  return nil;
}

val close_stream(val stream, val throw_on_error)
{
  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->close ? ops->close(stream, throw_on_error) : nil;
  }
}

val get_line(val stream)
{
  if (!stream)
    stream = std_input;

  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->get_line ? ops->get_line(stream) : nil;
  }
}

val get_char(val stream)
{
  if (!stream)
    stream = std_input;

  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->get_char ? ops->get_char(stream) : nil;
  }
}

val get_byte(val stream)
{
  if (!stream)
    stream = std_input;

  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->get_byte ? ops->get_byte(stream) : nil;
  }
}

val unget_char(val ch, val stream)
{
  stream = default_arg(stream, std_input);

  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->unget_char ? ops->unget_char(stream, ch) : nil;
  }
}

val unget_byte(val byte, val stream)
{
  cnum b = c_num(byte);

  stream = default_arg(stream, std_input);

  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  if (b < 0 || b > 255)
    uw_throwf(file_error_s, lit("unget-byte on ~a: byte value ~a out of range"),
              stream, byte, nao);

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->unget_byte ? ops->unget_byte(stream, b) : nil;
  }
}

struct fmt {
  size_t minsize;
  const char *dec;
  const char *oct;
  const char *hex;
  const char *HEX;
};

static struct fmt fmt_tab[] = {
  { sizeof(short),"%hd",   "%ho",   "%hx",   "%hX"   },
  { sizeof(int),  "%d",    "%o",    "%x",    "%X"    },
  { sizeof(long), "%ld",   "%lo",   "%lx",   "%llX"  },
  { sizeof(cnum), "%lld",  "%llo",  "%llx",  "%llX"  },
  { sizeof(cnum), "%Ld",   "%Lo",   "%Lx",   "%llX"  },
  { sizeof(cnum), "%qd",   "%qo",   "%qx",   "%qX",  },
  { sizeof(cnum), "%I64d", "%I64o", "%I64x", "%I64X" },
  { 0,            0,       0,       0,       0       }
};

static struct fmt *num_fmt;

static void detect_format_string(void)
{
  struct fmt *f;
  char buf[64];
  cnum num = 1234;

  for (f = fmt_tab; f->minsize != 0; f++) {
    memset(buf, 0, sizeof buf);
    if (f->minsize != sizeof num)
      continue;
    if (sprintf(buf, f->dec, num) == 4 && strcmp(buf, "1234") == 0) {
      num_fmt = f;
      break;
    }
  }
}

static val vformat_num(val stream, const char *str,
                       int width, int left, int zeropad, 
                       int precision, int sign)
{
  int sign_char = (str[0] == '-' || str[0] == '+') ? str[0] : 0;
  int digit_len = strlen(str) - (sign_char != 0);
  int padlen = precision > digit_len ? precision - digit_len : 0;
  int total_len = digit_len + padlen + (sign_char || sign); 
  int slack = (total_len < width) ? width - total_len : 0;
  int i;

  if (!left)
    for (i = 0; i < slack; i++)
      if (!put_char(chr(' '), stream))
        return nil;

  if (!zeropad)
    for (i = 0; i < padlen; i++)
      if (!put_char(chr(' '), stream))
        return nil;

  if (sign_char) {
    put_char(chr(sign_char), stream);
    str++;
  } else if (sign) {
    put_char(chr(sign), stream);
  }

  if (zeropad)
    for (i = 0; i < padlen; i++)
      if (!put_char(chr('0'), stream))
        return nil;

  while (*str)
    if (!put_char(chr(*str++), stream))
      return nil;

  if (left)
    for (i = 0; i < slack; i++)
      if (!put_char(chr(' '), stream))
        return nil;

  return t;
}

static val vformat_str(val stream, val str, int width, int left,
                       int precision)
{
  const wchar_t *cstr = c_str(str);
  int len = c_num(length_str(str));
  int truelen = (precision && precision < len) ? precision : len;
  int slack = (truelen < width) ? width - truelen : 0;
  int i;

  if (!left)
    for (i = 0; i < slack; i++)
      if (!put_char(chr(' '), stream))
        return nil;

  for (i = 0; i < truelen; i++)
    if (!put_char(chr(cstr[i]), stream))
      return nil;

  if (left)
    for (i = 0; i < slack; i++)
      if (!put_char(chr(' '), stream))
        return nil;

  return t;
}

val vformat(val stream, val fmtstr, va_list vl)
{
  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    const wchar_t *fmt = c_str(fmtstr);
    enum {
      vf_init, vf_width, vf_digits, vf_star, vf_precision, vf_spec
    } state = vf_init, saved_state = vf_init;
    int width = 0, precision = 0, precision_p = 0, digits = 0;
    int left = 0, sign = 0, zeropad = 0;
    cnum value;
    void *ptr;

    for (;;) {
      val obj;
      wchar_t ch = *fmt++;
      char num_buf[512], *pnum = num_buf;

      switch (state) {
      case vf_init:
        switch (ch) {
        case 0:
          break;
        case '~':
          state = vf_width;
          width = 0;
          left = 0;
          zeropad = 0;
          precision = 0;
          precision_p = 0;
          digits = 0;
          continue;
        default:
          put_char(chr(ch), stream);
          continue;
        }
        break;
      case vf_width:
        switch (ch) {
        case '~':
          put_char(chr('~'), stream);
          state = vf_init;
          continue;
        case '<':
          left = 1;
          continue;
        case ',':
          state = vf_precision;
          continue;
        case '0': case '1': case '2': case '3': case '4': case '5':
        case '6': case '7': case '8': case '9':
          saved_state = state;
          state = vf_digits;
          digits = ch - '0';
          continue;
        case '*':
          saved_state = state;
          state = vf_star;
          continue;
        default:
          state = vf_spec;
          --fmt;
          continue;
        }
        break;
      case vf_precision:
        switch (ch) {
        case '0':
          zeropad = 1;
          continue;
        case '1': case '2': case '3': case '4': case '5':
        case '6': case '7': case '8': case '9':
          saved_state = state;
          state = vf_digits;
          digits = ch - '0';
          continue;
        case '+': case ' ':
          sign = ch;
          continue;
        case '*':
          saved_state = state;
          state = vf_star;
          continue;
        default:
          state = vf_spec;
          --fmt;
          continue;
        }
        break;
      case vf_digits:
        switch (ch) {
        case '0': case '1': case '2': case '3': case '4':
        case '5': case '6': case '7': case '8': case '9':
          digits = (digits * 10) + (ch - '0');
          if (digits > 999999)
            goto toobig;
          continue;
        default:
  do_digits:
          switch (saved_state) {
          case vf_width:
            if (width < 0) {
              width = -digits;
              left = 1;
            } else {
              width = digits;
            }
            if (ch == ',') {
              state = vf_precision;
            } else {
              state = vf_spec;
              --fmt;
            }
            continue;
          case vf_precision:
            precision = digits;
            precision_p = 1;
            state = vf_spec;
            --fmt;
            continue;
          default:
            internal_error("unexpected state in formatter");
          }
        }
        break;
      case vf_star:
        obj = va_arg(vl, val);
        digits = c_num(obj);
        goto do_digits;
        break;
      case vf_spec:
        state = vf_init;
        switch (ch) {
        case 'x': case 'X':
          obj = va_arg(vl, val);
          if (bignump(obj)) {
            int nchars = mp_radix_size(mp(obj), 16); 
            if (nchars >= (int) sizeof (num_buf))
              pnum = (char *) chk_malloc(nchars + 1);
            mp_toradix_case(mp(obj), (unsigned char *) pnum, 16, 1);
          } else {
            const char *fmt = ch == 'x' ? num_fmt->hex : num_fmt->HEX;
            value = c_num(obj);
            if (value < 0) {
              num_buf[0] = '-';
              sprintf(num_buf + 1, fmt, -value);
            } else {
              sprintf(num_buf, fmt, value);
            }
          }
          goto output_num;
        case 'o':
          obj = va_arg(vl, val);
          if (bignump(obj)) {
            int nchars = mp_radix_size(mp(obj), 8); 
            if (nchars >= (int) sizeof (num_buf))
              pnum = (char *) chk_malloc(nchars + 1);
            mp_toradix(mp(obj), (unsigned char *) pnum, 8);
          } else {
            value = c_num(obj);
            sprintf(num_buf, num_fmt->oct, value);
          }
          goto output_num;
        case 'f': case 'e':
          obj = va_arg(vl, val);

          if (obj == nao)
            goto premature;

          {
            double n;

            switch (type(obj)) {
            case BGNUM:
              obj = flo_int(obj);
              /* fallthrough */
            case FLNUM:
              n = c_flo(obj);
              break;
            case NUM:
              n = (double) c_num(obj);
              break;
            default:
              uw_throwf(error_s, lit("format: ~~~a conversion requires "
                                     "numeric arg: ~s given\n"),
                        chr(ch), obj, nao);
            }

            if (!precision_p)
              precision = 3;

            /* guard against num_buf overflow */
            if (precision > 128)
              uw_throwf(error_s, lit("excessive precision in format: ~s\n"),
                        num(precision), nao);

            if (ch == 'e') {
              sprintf(num_buf, "%.*e", precision, n);
              {
                char *dec = strchr(num_buf, '.');
                char *exp = strchr(dec ? dec : num_buf, 'e');

                if (exp) {
                  char *scan = ++exp;

                  if (*scan == '-')
                    *exp++ = *scan++;
                  else if (*scan == '+')
                    scan++;

                  while (*scan == '0')
                    scan++;

                  if (!*scan)
                    *exp++ = '0';
                  else
                    while (*scan)
                      *exp++ = *scan++;

                  *exp = 0;
                }
              }
            } else {
              sprintf(num_buf, "%.*f", precision, n);
            }
            if (!isdigit(num_buf[0]) && !isdigit(num_buf[1])) {
              if (!vformat_str(stream, lit("#<bad-float>"),
                               width, left, 0))
                return nil;
              continue;
            }
            precision = 0;
            goto output_num;
          }
        case 'a': case 's':
          obj = va_arg(vl, val);
          if (obj == nao)
            goto premature;
          switch (type(obj)) {
          case NUM:
            value = c_num(obj);
            sprintf(num_buf, num_fmt->dec, value);
            goto output_num;
          case BGNUM:
            {
              int nchars = mp_radix_size(mp(obj), 10); 
              if (nchars >= (int) sizeof (num_buf))
                pnum = (char *) chk_malloc(nchars + 1);
              mp_toradix(mp(obj), (unsigned char *) pnum, 10);
            }
            goto output_num;
          case FLNUM:
            if (!precision_p)
              precision = DBL_DIG;

            if (precision > 500)
              uw_throwf(error_s, lit("excessive precision in format: ~s\n"),
                        num(precision), nao);

            sprintf(num_buf, "%.*g", precision, obj->fl.n);

            {
              char *dec = strchr(num_buf, '.');
              char *exp = strchr(dec ? dec : num_buf, 'e');

              if (exp) {
                char *scan = ++exp;

                if (*scan == '-')
                  *exp++ = *scan++;
                else if (*scan == '+')
                  scan++;

                while (*scan == '0')
                  scan++;

                while (*scan)
                  *exp++ = *scan++;

                *exp = 0;
              }

              if (ch == 's' && (!precision_p || precision > 0) && !dec && !exp)
                  strcat(num_buf, ".0");
            }

            if (!isdigit(num_buf[0]) && !isdigit(num_buf[1])) {
              if (!vformat_str(stream, lit("#<bad-float>"),
                               width, left, 0))
                return nil;
              continue;
            }

            precision = 0;
            goto output_num;
          default:
            if (width != 0 || precision_p) {
              val str = format(nil, ch == 'a' ? lit("~a") : lit("~s"),
                               obj, nao);
              if (!vformat_str(stream, str, width, left, precision))
                return nil;
              continue;
            }
          }
          if (ch == 'a')
            obj_pprint(obj, stream);
          else
            obj_print(obj, stream);
          continue;
        case 'p':
          ptr = va_arg(vl, void *);
          value = (cnum) ptr;
          sprintf(num_buf, num_fmt->hex, value);
          goto output_num;
        default:
          uw_throwf(error_s, lit("unknown format directive character ~s\n"), 
                    chr(ch), nao);
        output_num:
          {
            val res = vformat_num(stream, pnum, width, left,
                                  zeropad, precision, sign);
            if (pnum != num_buf)
              free(pnum);
            if (!res)
              return nil;
            continue;
          }
        }
        continue;
      }

      break;
    }
  }

  if (va_arg(vl, val) != nao)
    internal_error("unterminated format argument list");
  return t;
premature:
  internal_error("insufficient arguments for format");
toobig:
  internal_error("ridiculous precision or field width in format");
}

val vformat_to_string(val fmtstr, va_list vl)
{
  val stream = make_string_output_stream();
  (void) vformat(stream, fmtstr, vl);
  return get_string_from_stream(stream);
}

val format(val stream, val str, ...)
{
  uses_or2;
  val st = if3(stream == t,
               std_output,
               or2(stream, make_string_output_stream()));
  type_check (st, COBJ);
  type_assert (st->co.cls == stream_s, (lit("~a is not a stream"), st, nao));

  {
    va_list vl;
    val ret;
    va_start (vl, str);
    ret = vformat(st, str, vl);
    va_end (vl);
    return (stream) ? ret : get_string_from_stream(st);
  }
}

val formatv(val stream, val string, val args)
{
  val arg[32], *p = arg;

  for (; args && p - arg < 32; args = cdr(args), p++)
    *p = car(args);

  switch (p - arg) {
  case  0: return format(stream, string,  nao);
  case  1: return format(stream, string, arg[0], nao);
  case  2: return format(stream, string, arg[0], arg[1], nao);
  case  3: return format(stream, string, arg[0], arg[1], arg[2], nao);
  case  4: return format(stream, string, arg[0], arg[1], arg[2], arg[3], nao);
  case  5: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], nao);
  case  6: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], nao);
  case  7: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], nao);
  case  8: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], nao);
  case  9: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], nao);
  case 10: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], nao);
  case 11: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], nao);
  case 12: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], nao);
  case 13: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], nao);
  case 14: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], nao);
  case 15: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], nao);
  case 16: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], nao);
  case 17: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], nao);
  case 18: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], nao);
  case 19: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], nao);
  case 20: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], nao);
  case 21: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], nao);
  case 22: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], nao);
  case 23: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], nao);
  case 24: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], nao);
  case 25: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], arg[24], nao);
  case 26: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], arg[24], arg[25], nao);
  case 27: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], arg[24], arg[25], arg[26], nao);
  case 28: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], arg[24], arg[25], arg[26], arg[27], nao);
  case 29: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], arg[24], arg[25], arg[26], arg[27], arg[28], nao);
  case 30: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], arg[24], arg[25], arg[26], arg[27], arg[28], arg[29], nao);
  case 31: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], arg[24], arg[25], arg[26], arg[27], arg[28], arg[29], arg[30], nao);
  case 32: return format(stream, string, arg[0], arg[1], arg[2], arg[3], arg[4], arg[5], arg[6], arg[7], arg[8], arg[9], arg[10], arg[11], arg[12], arg[13], arg[14], arg[15], arg[16], arg[17], arg[18], arg[19], arg[20], arg[21], arg[22], arg[23], arg[24], arg[25], arg[26], arg[27], arg[28], arg[29], arg[30], arg[31], nao);
  }

  uw_throwf(file_error_s, lit("too many arguments to format"), nao);
  abort();
}

val put_string(val string, val stream)
{
  stream = default_arg(stream, std_output);

  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->put_string ? ops->put_string(stream, string) : nil;
  }
}

val put_char(val ch, val stream)
{
  stream = default_arg(stream, std_output);

  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->put_char ? ops->put_char(stream, ch) : nil;
  }
}

val put_byte(val byte, val stream)
{
  cnum b = c_num(byte);

  stream = default_arg(stream, std_output);

  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  if (b < 0 || b > 255)
    uw_throwf(file_error_s, lit("put-byte on ~a: byte value ~a out of range"),
              stream, byte, nao);

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->put_byte ? ops->put_byte(stream, b) : nil;
  }
}

val put_line(val string, val stream)
{
  return (put_string(default_arg(string, null_string), stream), put_char(chr('\n'), stream));
}

val flush_stream(val stream)
{
  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    return ops->flush ? ops->flush(stream) : t;
  }
}

val seek_stream(val stream, val offset, val whence)
{
  type_check (stream, COBJ);
  type_assert (stream->co.cls == stream_s, (lit("~a is not a stream"),
                                            stream, nao));

  {
    struct strm_ops *ops = (struct strm_ops *) stream->co.ops;
    enum strm_whence w;
    cnum off = c_num(offset);

    if (whence == from_start_k)
      w = strm_start;
    else if (whence == from_current_k)
      w = strm_cur;
    else if (whence == from_end_k)
      w = strm_end;
    else
      uw_throwf(file_error_s, lit("seek: ~a is not a valid whence argument"),
                whence, nao);
    
    return ops->seek(stream, off, w);
  }
}

#if HAVE_SYS_STAT
static int w_stat(const wchar_t *wpath, struct stat *buf)
{
  char *path = utf8_dup_to(wpath);
  int res = stat(path, buf);
  free(path);
  return res;
}
#endif

val statf(val path)
{
#if HAVE_SYS_STAT
  struct stat st;
  int res = w_stat(c_str(path), &st);

  if (res == -1)
    uw_throwf(file_error_s, lit("unable to stat ~a: ~a/~s"),
              path, num(errno), string_utf8(strerror(errno)), nao);

  return list(dev_k, num(st.st_dev),
              ino_k, num(st.st_ino),
              mode_k, num(st.st_mode),
              nlink_k, num(st.st_nlink),
              uid_k, num(st.st_uid),
              gid_k, num(st.st_gid),
              rdev_k, num(st.st_rdev),
              size_k, num(st.st_size),
#if !HAVE_WINDOWS_H
              blksize_k, num(st.st_blksize),
              blocks_k, num(st.st_blocks),
#else
              blksize_k, zero,
              blocks_k, zero,
#endif
              atime_k, num(st.st_atime),
              mtime_k, num(st.st_mtime),
              ctime_k, num(st.st_ctime),
              nao);
#else
  uw_throwf(file_error_s, lit("stat is not implemented"), nao);
#endif
}

static DIR *w_opendir(const wchar_t *wname)
{
  char *name = utf8_dup_to(wname);
  DIR *d = opendir(name);
  free(name);
  return d;
}


val open_directory(val path)
{
  DIR *d = w_opendir(c_str(path));

  if (!d)
    uw_throwf(file_error_s, lit("error opening directory ~a: ~a/~s"),
              path, num(errno), string_utf8(strerror(errno)), nao);

  return make_dir_stream(d);
}

val open_file(val path, val mode_str)
{
  FILE *f = w_fopen(c_str(path), c_str(default_arg(mode_str, lit("r"))));

  if (!f)
    uw_throwf(file_error_s, lit("error opening ~a: ~a/~s"),
              path, num(errno), string_utf8(strerror(errno)), nao);

  return make_stdio_stream(f, path);
}

val open_tail(val path, val mode_str, val seek_end_p)
{
  val mode = default_arg(mode_str, lit("r"));
  FILE *f = w_fopen(c_str(path), c_str(mode));
  struct stdio_handle *h;
  val stream;
  unsigned long state = 0;

  if (f && default_bool_arg(seek_end_p))
    if (fseek(f, 0, SEEK_END) < 0)
      uw_throwf(file_error_s, lit("error seeking to end of ~a: ~a/~s"),
                path, num(errno), string_utf8(strerror(errno)), nao);

  stream = make_tail_stream(f, path);
  h = (struct stdio_handle *) stream->co.handle;
  h->mode = mode;
  if (!f)
    tail_strategy(stream, &state);
  return stream;
}

val open_command(val path, val mode_str)
{
  FILE *f = w_popen(c_str(path), c_str(default_arg(mode_str, lit("r"))));

  if (!f)
    uw_throwf(file_error_s, lit("error opening pipe ~a: ~a/~s"),
              path, num(errno), string_utf8(strerror(errno)), nao);

  return make_pipe_stream(f, path);
}

#if HAVE_FORK_STUFF
val open_process(val name, val mode_str, val args)
{
  int input = equal(mode_str, lit("r")) || equal(mode_str, lit("rb"));
  int fd[2];
  pid_t pid;
  char **argv = 0, *utf8name = 0;
  val iter;
  int i, nargs;

  args = default_bool_arg(args);
  nargs = c_num(length(args)) + 1;

  if (pipe(fd) == -1) {
    uw_throwf(file_error_s, lit("opening pipe ~a, pipe syscall failed: ~a/~s"),
              name, num(errno), string_utf8(strerror(errno)), nao);
  }

  argv = (char **) chk_malloc((nargs + 2) * sizeof *argv);

  for (i = 0, iter = cons(name, args); iter; i++, iter = cdr(iter)) {
    val arg = car(iter);
    argv[i] = utf8_dup_to(c_str(arg));
  }
  argv[i] = 0;

  utf8name = utf8_dup_to(c_str(name));

  pid = fork();

  if (pid == -1) {
    for (i = 0; i < nargs; i++)
      free(argv[i]);
    free(argv);
    uw_throwf(file_error_s, lit("opening pipe ~a, fork syscall failed: ~a/~s"),
              name, num(errno), string_utf8(strerror(errno)), nao);
  } 
  
  if (pid == 0) {
    if (input) {
      dup2(fd[1], STDOUT_FILENO);
      if (fd[1] != STDOUT_FILENO) /* You never know */
        close(fd[1]);
      close(fd[0]);
    } else {
      dup2(fd[0], STDIN_FILENO);
      if (fd[0] != STDIN_FILENO) /* You never know */
        close(fd[0]);
      close(fd[1]);
    }

    execvp(utf8name, argv);
    _exit(errno);
  } else {
    int whichfd;
    char *utf8mode = utf8_dup_to(c_str(mode_str));
    FILE *f;

    if (input) {
      close(fd[1]);
      whichfd = fd[0];
    } else {
      close(fd[0]);
      whichfd = fd[1];
    }

    for (i = 0; i < nargs; i++)
      free(argv[i]);
    free(argv);

#if HAVE_FCNTL_H
    fcntl(whichfd, F_SETFD, FD_CLOEXEC);
#endif

    if ((f = fdopen(whichfd, utf8mode)) == 0) {
      int status;
      kill(pid, SIGINT);
      kill(pid, SIGTERM);
      while (waitpid(pid, &status, 0) == -1 && errno == EINTR)
        ;
      free(utf8mode);
      uw_throwf(file_error_s, lit("opening pipe ~a, fdopen failed: ~a/~s"),
                name, num(errno), string_utf8(strerror(errno)), nao);
    }

    free(utf8mode);
    /* TODO: catch potential OOM exception here and kill process. */
    return make_pipevp_stream(f, name, pid);
  }
}
#else

static val win_escape_arg(val str)
{
  int bscount = 0, i;
  const wchar_t *s;
  val out = string(L"");

  for (s = c_str(str); *s; s++) {
    switch (*s) {
    case '"':
      for (i = 0; i < bscount; i++)
        string_extend(out, lit("\\\\"));
      string_extend(out, lit("\\\""));
      bscount = 0;
      break;
    case '\\':
      bscount++;
      break;
    default:
      for (i = 0; i < bscount; i++)
        string_extend(out, lit("\\"));
      string_extend(out, chr(*s));
      bscount = 0;
      break;
    }
  }

  for (i = 0; i < bscount; i++)
    string_extend(out, lit("\\"));

  return out;
}

static val win_make_cmdline(val args)
{
  val out = string(L"");

  string_extend(out, pop(&args));
  string_extend(out, lit(" "));

  for (; args; args = cdr(args)) {
    string_extend(out, lit("\""));
    string_extend(out, win_escape_arg(car(args)));
    if (cdr(args))
      string_extend(out, lit("\" "));
    else
      string_extend(out, lit("\""));
  }

  return out;
}

val open_process(val name, val mode_str, val args)
{
  val win_cmdline = win_make_cmdline(cons(name, default_bool_arg(args)));
  return open_command(win_cmdline, mode_str);
}
#endif

static val sh(val command)
{
  char *cmd = utf8_dup_to(c_str(command));
  int status = system(cmd);
  if (status < 0)
    return nil;
#if HAVE_SYS_WAIT
  if (WIFEXITED(status)) {
    int exitstatus = WEXITSTATUS(status);
    return num(exitstatus);
  }
#endif
  return status == 0 ? zero : nil;
}

#if HAVE_FORK_STUFF
static val run(val name, val args)
{
  pid_t pid;
  char **argv = 0, *utf8name = 0;
  val iter;
  int i, nargs;

  args = default_bool_arg(args);
  nargs = c_num(length(args)) + 1;

  argv = (char **) chk_malloc((nargs + 2) * sizeof *argv);

  for (i = 0, iter = cons(name, args); iter; i++, iter = cdr(iter)) {
    val arg = car(iter);
    argv[i] = utf8_dup_to(c_str(arg));
  }
  argv[i] = 0;

  utf8name = utf8_dup_to(c_str(name));

  pid = fork();

  if (pid == -1) {
    for (i = 0; i < nargs; i++)
      free(argv[i]);
    free(argv);
    uw_throwf(file_error_s, lit("opening process ~a, fork syscall failed: ~a/~s"),
              name, num(errno), string_utf8(strerror(errno)), nao);
  } 
  
  if (pid == 0) {
    execvp(utf8name, argv);
    _exit(errno);
  } else {
    int status;
    for (i = 0; i < nargs; i++)
      free(argv[i]);
    free(argv);
    while (waitpid(pid, &status, 0) == -1 && errno == EINTR)
      ;
    if (status < 0)
      return nil;
#if HAVE_SYS_WAIT
    if (WIFEXITED(status)) {
      int exitstatus = WEXITSTATUS(status);
      return num(exitstatus);
    }
#endif
    return status == 0 ? zero : nil;
  }
}
#elif HAVE_WSPAWN
static val run(val command, val args)
{
  const wchar_t **wargv = 0;
  val iter;
  int i, nargs, status;

  args = default_bool_arg(args);
  nargs = c_num(length(args)) + 1;

  wargv = (const wchar_t **) chk_malloc((nargs + 2) * sizeof *wargv);

  for (i = 0, iter = cons(command, args); iter; i++, iter = cdr(iter))
    wargv[i] = c_str(car(iter));
  wargv[i] = 0;

  status = _wspawnvp(_P_WAIT, c_str(command), wargv);
 
  for (i = 0; i < nargs; i++)
    free((void *) wargv[i]);
  free((void *) wargv);

  return (status < 0) ? nil : num(status);
}
#else
static val run(val command, val args)
{
  val win_cmdline = win_make_cmdline(cons(command, default_bool_arg(args)));
  return sh(win_cmdline);
}
#endif

static void cat_stream_print(val stream, val out)
{
  val streams = (val) stream->co.handle;
  format(out, lit("#<~s catenated ~s>"), stream->co.cls, streams, nao);
}

static val cat_get_line(val stream)
{
  val streams = (val) stream->co.handle;

  while (streams) {
    val line = get_line(first(streams));
    if (line)
      return line;
    if ((streams = rest(streams)) != nil)
      stream->co.handle = (mem_t *) streams;
  }

  return nil;
}

static val cat_get_char(val stream)
{
  val streams = (val) stream->co.handle;

  while (streams) {
    val ch = get_char(first(streams));
    if (ch)
      return ch;
    if ((streams = rest(streams)) != nil)
      stream->co.handle = (mem_t *) streams;
  }

  return nil;
}

static val cat_get_byte(val stream)
{
  val streams = (val) stream->co.handle;

  while (streams) {
    val byte = get_byte(first(streams));
    if (byte)
      return byte;
    if ((streams = rest(streams)) != nil)
      stream->co.handle = (mem_t *) streams;
  }

  return nil;
}

static val cat_unget_byte(val stream, int byte)
{
  val streams = (val) stream->co.handle;

  if (!streams) {
    uw_throwf(file_error_s,
              lit("unget-byte on catenated stream ~a: stream list empty"),
              stream, nao);
  } else {
    val stream = car(streams);
    return unget_byte(stream, num_fast(byte));
  }

  return nil;
}

static val cat_unget_char(val stream, val ch)
{
  val streams = (val) stream->co.handle;

  if (!streams) {
    uw_throwf(file_error_s,
              lit("unget-char on catenated stream ~a: stream list empty"),
              stream, nao);
  } else {
    val stream = car(streams);
    return unget_char(stream, ch);
  }
}

static val cat_get_prop(val stream, val ind)
{
  val streams = (val) stream->co.handle;
  if (streams)
    return stream_get_prop(first(streams), ind);
  return nil;
}

static void cat_mark(val stream)
{
  val obj = (val) stream->co.handle;
  gc_mark(obj);
}

static struct strm_ops cat_stream_ops = {
  { eq,
    cat_stream_print,
    cobj_destroy_stub_op,
    cat_mark,
    cobj_hash_op },
  0, /* put_string */
  0, /*_put_char */
  0, /* put_byte, */
  cat_get_line,
  cat_get_char,
  cat_get_byte,
  cat_unget_char,
  cat_unget_byte,
  0, /* close, */
  0, /* flush, */
  0, /* seek, */
  cat_get_prop,
  0, /* set_prop */
};

val make_catenated_stream(val stream_list)
{
  return cobj((mem_t *) stream_list, stream_s, &cat_stream_ops.cobj_ops);
}

val remove_path(val path)
{
  if (w_remove(c_str(path)) < 0)
    uw_throwf(file_error_s, lit("trying to remove ~a: ~a/~s"),
                path, num(errno), string_utf8(strerror(errno)), nao);
  return t;
}

val rename_path(val from, val to)
{
  if (w_rename(c_str(from), c_str(to)) < 0)
    uw_throwf(file_error_s, lit("trying to rename ~a to ~a: ~a/~s"),
                from, to, num(errno), string_utf8(strerror(errno)), nao);
  return t;
}

#if HAVE_MKDIR
val mkdir_wrap(val path, val mode)
{
  char *u8path = utf8_dup_to(c_str(path));
  int err = mkdir(u8path, c_num(default_arg(mode, num_fast(0777))));
  free(u8path);

  if (err < 0)
    uw_throwf(file_error_s, lit("mkdir ~a: ~a/~s"),
              path, num(errno), string_utf8(strerror(errno)), nao);

  return t;
}
#elif HAVE_WINDOWS_H
val mkdir_wrap(val path, val mode)
{
  int err = _wmkdir(c_str(path));

  (void) mode;
  if (err < 0)
    uw_throwf(file_error_s, lit("mkdir ~a: ~a/~s"),
              path, num(errno), string_utf8(strerror(errno)), nao);

  return t;
}
#endif

#if HAVE_UNISTD_H
val chdir_wrap(val path)
{
  char *u8path = utf8_dup_to(c_str(path));
  int err = chdir(u8path);
  free(u8path);

  if (err < 0)
    uw_throwf(file_error_s, lit("chdir ~a: ~a/~s"),
              path, num(errno), string_utf8(strerror(errno)), nao);
  return t;
}

val getcwd_wrap(void)
{
  size_t guess = 256;

  for (;;) {
    char *u8buf = (char *) chk_malloc(guess);

    if (getcwd(u8buf, guess) == 0) {
      free(u8buf);
      if (errno != ERANGE) {
        uw_throwf(file_error_s, lit("getcwd: ~a/~s"),
                  num(errno), string_utf8(strerror(errno)), nao);
      }
      if (2 * guess > guess)
        guess *= 2;
      else
        uw_throwf(file_error_s, lit("getcwd: weird problem"), nao);
    } else {
      val out = string_utf8(u8buf);
      free(u8buf);
      return out;
    }
  }
}

#if HAVE_MAKEDEV

val makedev_wrap(val major, val minor)
{
  return num(makedev(c_num(major), c_num(minor)));
}

val minor_wrap(val dev)
{
  return num(minor(c_num(dev)));
}

val major_wrap(val dev)
{
  return num(major(c_num(dev)));
}

#endif

#if HAVE_MKNOD

val mknod_wrap(val path, val mode, val dev)
{
  char *u8path = utf8_dup_to(c_str(path));
  int err = mknod(u8path, c_num(mode), c_num(default_arg(dev, zero)));
  free(u8path);

  if (err < 0)
#if HAVE_MAKEDEV
    uw_throwf(file_error_s, lit("mknod ~a ~a ~a (~a:~a): ~a/~s"),
              path, mode, dev, major_wrap(dev), minor_wrap(dev), num(errno),
              string_utf8(strerror(errno)), nao);
#else
    uw_throwf(file_error_s, lit("mknod ~a ~a ~a: ~a/~s"),
              path, mode, dev, num(errno),
              string_utf8(strerror(errno)), nao);
#endif

  return t;
}

#endif

#if HAVE_SYMLINK

val symlink_wrap(val target, val to)
{
  char *u8target = utf8_dup_to(c_str(target));
  char *u8to = utf8_dup_to(c_str(to));
  int err = symlink(u8target, u8to);
  free(u8target);
  free(u8to);
  if (err < 0)
    uw_throwf(file_error_s, lit("symlink ~a ~a: ~a/~s"),
              target, to, num(errno), string_utf8(strerror(errno)), nao);
  return t;
}

val link_wrap(val target, val to)
{
  char *u8target = utf8_dup_to(c_str(target));
  char *u8to = utf8_dup_to(c_str(to));
  int err = link(u8target, u8to);
  free(u8target);
  free(u8to);
  if (err < 0)
    uw_throwf(file_error_s, lit("link ~a ~a: ~a/~s"),
              target, to, num(errno), string_utf8(strerror(errno)), nao);
  return t;
}

val readlink_wrap(val path)
{
  char *u8path = utf8_dup_to(c_str(path));
  ssize_t guess = 256;

  for (;;) {
    char *u8buf = (char *) chk_malloc(guess);
    ssize_t bytes = readlink(u8path, u8buf, guess);

    if (bytes >= guess) {
      free(u8buf);
      if (2 * guess > guess)
        guess *= 2;
      else
        uw_throwf(file_error_s, lit("readlink: weird problem"), nao);
    } else if (bytes <= 0) {
      free(u8buf);
      uw_throwf(file_error_s, lit("readlink ~a: ~a/~s"),
                path, num(errno), string_utf8(strerror(errno)), nao);
    } else {
      val out;
      u8buf[bytes] = 0;
      out = string_utf8(u8buf);
      free(u8buf);
      return out;
    }
  }
}

#endif

static val open_files(val file_list, val substitute_stream)
{
  substitute_stream = default_bool_arg(substitute_stream);

  if (nilp(file_list) && substitute_stream) {
    return substitute_stream;
  } else {
    return apply_intrinsic(func_n0v(make_catenated_stream),
                           cons(mapcar(func_n2o(open_file, 1), file_list), nil));

  }
}

static val open_files_star(val file_list, val substitute_stream)
{
  substitute_stream = default_bool_arg(substitute_stream);

  if (nilp(file_list) && substitute_stream) {
    return substitute_stream;
  } else {
    return apply_intrinsic(func_n0v(make_catenated_stream),
                           cons(lazy_mapcar(func_n2o(open_file, 1), file_list), nil));
  }
}

#endif

void stream_init(void)
{
  protect(&std_input, &std_output, &std_debug, &std_error, &std_null, (val *) 0);
  detect_format_string();

  dev_k = intern(lit("dev"), keyword_package);
  ino_k = intern(lit("ino"), keyword_package);
  mode_k = intern(lit("mode"), keyword_package);
  nlink_k = intern(lit("nlink"), keyword_package);
  uid_k = intern(lit("uid"), keyword_package);
  gid_k = intern(lit("gid"), keyword_package);
  rdev_k = intern(lit("rdev"), keyword_package);
  size_k = intern(lit("size"), keyword_package);
  blksize_k = intern(lit("blksize"), keyword_package);
  blocks_k = intern(lit("blocks"), keyword_package);
  atime_k = intern(lit("atime"), keyword_package);
  mtime_k = intern(lit("mtime"), keyword_package);
  ctime_k = intern(lit("ctime"), keyword_package);
  from_start_k = intern(lit("from-start"), keyword_package);
  from_current_k = intern(lit("from-current"), keyword_package);
  from_end_k = intern(lit("from-end"), keyword_package);
  real_time_k = intern(lit("real-time"), keyword_package);
  name_k = intern(lit("name"), keyword_package);
  format_s = intern(lit("format"), user_package);

#ifndef S_IFSOCK
#define S_IFSOCK 0
#endif

#ifndef S_IFLNK
#define S_IFLNK 0
#endif

#ifndef S_ISUID
#define S_ISUID 0
#endif

#ifndef S_ISGID
#define S_ISGID 0
#endif

#ifndef S_ISVTX
#define S_ISVTX 0
#endif

#ifndef S_IRWXG
#define S_IRWXG 0
#endif

#ifndef S_IRGRP
#define S_IRGRP 0
#endif

#ifndef S_IWGRP
#define S_IWGRP 0
#endif

#ifndef S_IXGRP
#define S_IXGRP 0
#endif

#ifndef S_IRWXO
#define S_IRWXO 0
#endif

#ifndef S_IROTH
#define S_IROTH 0
#endif

#ifndef S_IWOTH
#define S_IWOTH 0
#endif

#ifndef S_IXOTH
#define S_IXOTH 0
#endif

#if HAVE_SYS_STAT
  reg_var(intern(lit("s-ifmt"), user_package), num_fast(S_IFMT));
  reg_var(intern(lit("s-ifsock"), user_package), num_fast(S_IFSOCK));
  reg_var(intern(lit("s-iflnk"), user_package), num_fast(S_IFLNK));
  reg_var(intern(lit("s-ifreg"), user_package), num_fast(S_IFREG));
  reg_var(intern(lit("s-ifblk"), user_package), num_fast(S_IFBLK));
  reg_var(intern(lit("s-ifdir"), user_package), num_fast(S_IFDIR));
  reg_var(intern(lit("s-ifchr"), user_package), num_fast(S_IFCHR));
  reg_var(intern(lit("s-ififo"), user_package), num_fast(S_IFIFO));
  reg_var(intern(lit("s-isuid"), user_package), num_fast(S_ISUID));
  reg_var(intern(lit("s-isgid"), user_package), num_fast(S_ISGID));
  reg_var(intern(lit("s-isvtx"), user_package), num_fast(S_ISVTX));
  reg_var(intern(lit("s-irwxu"), user_package), num_fast(S_IRWXU));
  reg_var(intern(lit("s-irusr"), user_package), num_fast(S_IRUSR));
  reg_var(intern(lit("s-iwusr"), user_package), num_fast(S_IWUSR));
  reg_var(intern(lit("s-ixusr"), user_package), num_fast(S_IXUSR));
  reg_var(intern(lit("s-irwxg"), user_package), num_fast(S_IRWXG));
  reg_var(intern(lit("s-irgrp"), user_package), num_fast(S_IRGRP));
  reg_var(intern(lit("s-iwgrp"), user_package), num_fast(S_IWGRP));
  reg_var(intern(lit("s-ixgrp"), user_package), num_fast(S_IXGRP));
  reg_var(intern(lit("s-irwxo"), user_package), num_fast(S_IRWXO));
  reg_var(intern(lit("s-iroth"), user_package), num_fast(S_IROTH));
  reg_var(intern(lit("s-iwoth"), user_package), num_fast(S_IWOTH));
  reg_var(intern(lit("s-ixoth"), user_package), num_fast(S_IXOTH));
#endif

  reg_var(stdin_s = intern(lit("*stdin*"), user_package),
          make_stdio_stream(stdin, lit("stdin")));
  reg_var(stdout_s = intern(lit("*stdout*"), user_package),
          make_stdio_stream(stdout, lit("stdout")));
  reg_var(stddebug_s = intern(lit("*stddebug*"), user_package),
          make_stdio_stream(stdout, lit("debug")));
  reg_var(stderr_s = intern(lit("*stderr*"), user_package),
          make_stdio_stream(stderr, lit("stderr")));
  reg_var(stdnull_s = intern(lit("*stdnull*"), user_package),
          make_null_stream());

  reg_fun(format_s, func_n2v(formatv));
  reg_fun(intern(lit("make-string-input-stream"), user_package), func_n1(make_string_input_stream));
  reg_fun(intern(lit("make-string-byte-input-stream"), user_package), func_n1(make_string_byte_input_stream));
  reg_fun(intern(lit("make-string-output-stream"), user_package), func_n0(make_string_output_stream));
  reg_fun(intern(lit("get-string-from-stream"), user_package), func_n1(get_string_from_stream));
  reg_fun(intern(lit("make-strlist-output-stream"), user_package), func_n0(make_strlist_output_stream));
  reg_fun(intern(lit("get-list-from-stream"), user_package), func_n1(get_list_from_stream));
  reg_fun(intern(lit("close-stream"), user_package), func_n2o(close_stream, 1));
  reg_fun(intern(lit("get-line"), user_package), func_n1o(get_line, 0));
  reg_fun(intern(lit("get-char"), user_package), func_n1o(get_char, 0));
  reg_fun(intern(lit("get-byte"), user_package), func_n1o(get_byte, 0));
  reg_fun(intern(lit("put-string"), user_package), func_n2o(put_string, 1));
  reg_fun(intern(lit("put-line"), user_package), func_n2o(put_line, 0));
  reg_fun(intern(lit("put-char"), user_package), func_n2o(put_char, 1));
  reg_fun(intern(lit("put-byte"), user_package), func_n2o(put_byte, 1));
  reg_fun(intern(lit("unget-char"), user_package), func_n2o(unget_char, 1));
  reg_fun(intern(lit("unget-byte"), user_package), func_n2o(unget_byte, 1));
  reg_fun(intern(lit("flush-stream"), user_package), func_n1(flush_stream));
  reg_fun(intern(lit("seek-stream"), user_package), func_n3(seek_stream));
  reg_fun(intern(lit("stat"), user_package), func_n1(statf));
  reg_fun(intern(lit("streamp"), user_package), func_n1(streamp));
  reg_fun(intern(lit("real-time-stream-p"), user_package), func_n1(real_time_stream_p));
  reg_fun(intern(lit("stream-set-prop"), user_package), func_n3(stream_set_prop));
  reg_fun(intern(lit("stream-get-prop"), user_package), func_n2(stream_get_prop));
  reg_fun(intern(lit("make-catenated-stream"), user_package), func_n0v(make_catenated_stream));

  reg_fun(intern(lit("open-directory"), user_package), func_n1(open_directory));
  reg_fun(intern(lit("open-file"), user_package), func_n2o(open_file, 1));
  reg_fun(intern(lit("open-tail"), user_package), func_n3o(open_tail, 1));
  reg_fun(intern(lit("open-command"), user_package), func_n2o(open_command, 1));
  reg_fun(intern(lit("open-pipe"), user_package), func_n2(open_command));
  reg_fun(intern(lit("open-process"), user_package), func_n3o(open_process, 2));
  reg_fun(intern(lit("sh"), user_package), func_n1(sh));
  reg_fun(intern(lit("run"), user_package), func_n2o(run, 1));
  reg_fun(intern(lit("remove-path"), user_package), func_n1(remove_path));
  reg_fun(intern(lit("rename-path"), user_package), func_n2(rename_path));
  reg_fun(intern(lit("open-files"), user_package), func_n2o(open_files, 1));
  reg_fun(intern(lit("open-files*"), user_package), func_n2o(open_files_star, 1));
}