#!/bin/sh
#
# SYNOPSIS
#	fixproto TARGET-DIR SOURCE-DIR-ALL SOURCE-DIR-STD
#
# COPYRIGHT
#	Copyright (C) 1993, 1994 Free Software Foundation, Inc.
#	This file is part of GNU CC.
#
#	GNU CC is free software; you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation; either version 2, or (at your option)
#	any later version.
#
#	GNU CC is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#
#	You should have received a copy of the GNU General Public License
#	along with GNU CC; see the file COPYING.  If not, write to
#	the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
#
# DESCRIPTION
#	Adjunct script for GNU CC to populate a directory with ANSI,
#	Posix.1, and C++ compatible header files.
#
#	Each file found under SOURCE-DIR-ALL is analyzed and "fixed."
#       Only standard ANSI/POSIX files found under SOURCE-DIR-STD
#       are analyzed and "fixed."
#	The SOURCE-DIRs are searched in order; a file found
#	under multiple SOURCE-DIRs is only handled for the first one.
#
# STRATEGY
#       Each include file is fed through cpp, and the scan-decls program
#	parses it, and emits any found function declarations.
#	The fix-header program analyzes the scan-decls output,
#	together with the original include file, and writes a "fixed"
#	include file, if needed.
#
#	The comment at the beginning of fix-header.c lists specifically
#	what kind of changes are made.
#
# NOTE
#	Some file space will be wasted, because the original header
#	files are copied.  An earlier version just included the original
#	by "reference", using GNU cpp's #include_next mechanism.
#	This is currently not done, partly because #include_next is
#	fragile (susceptible to version incompatibilties, and depends
#	and GCC-specific features), and partly for performance reasons.
#
# AUTHORS
#	Ron Guilmette (rfg@netcom.com) (original idea and code)
#	Per Bothner (bothner@cygnus.com) (major re-write)

progname=$0
progname=`basename $progname`
original_dir=`pwd`
CPP=${CPP-./cpp}
DEFINES="-D__STDC__=0 -D__cplusplus ${FIXPROTO_DEFINES}"

if [ `echo $1 | wc -w` = 0 ] ; then
  echo $progname\: usage\: $progname target-dir \[ source-dir \.\.\. \]
  exit 1
fi

std_files="ctype.h dirent.h errno.h curses.h fcntl.h grp.h locale.h math.h pwd.h setjmp.h signal.h stdio.h stdlib.h string.h sys/stat.h sys/times.h sys/resource.h sys/utsname.h sys/wait.h tar.h termios.h time.h unistd.h"

rel_target_dir=$1
# All files in $src_dir_all (normally same as $rel_target_dir) are
# processed.
src_dir_all=$2
# In $src_dir_std (normally same as /usr/include), only the
# "standard" ANSI/POSIX files listed in $std_files are processed.
src_dir_std=$3

if [ `expr $rel_target_dir : '\(.\)'` != '/' ] ; then
  abs_target_dir=$original_dir/$rel_target_dir
else
  abs_target_dir=$rel_target_dir
fi

# Determine whether this system has symbolic links.
if ln -s X $rel_target_dir/ShouldNotExist 2>/dev/null; then
  rm -f $rel_target_dir/ShouldNotExist
  LINKS=true
elif ln -s X /tmp/ShouldNotExist 2>/dev/null; then
  rm -f /tmp/ShouldNotExist
  LINKS=true
else
  LINKS=false
fi

if [ \! -d $abs_target_dir ] ; then
  echo $progname\: creating directory $rel_target_dir
  mkdir $abs_target_dir
fi

echo $progname\: populating \`$rel_target_dir\'

include_path=""

if [ `echo $* | wc -w` != 0 ] ; then
  for rel_source_dir in $src_dir_all $src_dir_std; do
    if [ `expr $rel_source_dir : '\(.\)'` != '/' ] ; then
      abs_source_dir=$original_dir/$rel_source_dir
    else
      abs_source_dir=$rel_source_dir
    fi
    include_path="$include_path -I$abs_source_dir"
  done
fi

required_stdlib_h="abort abs atexit atof atoi atol bsearch calloc exit free getenv labs malloc putenv qsort rand realloc srand strtod strtol strtoul system"
# "div ldiv", - ignored because these depend on div_t, ldiv_t
# ignore these: "mblen mbstowcs mbstowc wcstombs wctomb"
# Left out getgroups, because SunOS4 has incompatible BSD and SVR4 versions.
# Should perhaps also add NULL
required_unistd_h="_exit access alarm chdir chown close ctermid cuserid dup dup2 execl execle execlp execv execve execvp fork fpathconf getcwd getegid geteuid getgid getlogin getopt getpgrp getpid getppid getuid isatty link lseek pathconf pause pipe read rmdir setgid setpgid setsid setuid sleep sysconf tcgetpgrp tcsetpgrp ttyname unlink write"

done_dirs=""
echo "" >fixproto.list

for code in ALL STD ; do

  subdirs="."

  case $code in
    ALL)
      rel_source_dir=$src_dir_all

      dirs="."
      levels=2
      while $LINKS && test -n "$dirs" -a $levels -gt 0
      do
        levels=`expr $levels - 1`
	newdirs=
	for d in $dirs ; do
	  # Find all directories under $d, relative to $d, excluding $d itself.
	  # Assume directory names ending in CC or containing ++ are
	  # for C++, so skip those.
	  subdirs="$subdirs "`cd $rel_source_dir/$d; find . -type d -print | \
	           sed -e '/^\.$/d' -e "s|^\./|${d}/|" -e 's|^\./||' \
		     -e '/CC$/d' -e '/\+\+/d'`
	  links=
	  links=`cd $rel_source_dir; find $d/. -type l -print | \
		       sed -e "s|$d/./|$d/|" -e 's|^\./||'`
	  for link in $links --dummy-- ; do
	    test -d $rel_source_dir/$link/. && newdirs="$newdirs $link"
	  done
	done
	dirs="$newdirs"
	subdirs="$subdirs $newdirs"
      done
      ;;
    STD)
      rel_source_dir=$src_dir_std
      ;;
  esac

  if [ `expr $rel_source_dir : '\(.\)'` != '/' ] ; then
    abs_source_dir=$original_dir/$rel_source_dir
  else
    abs_source_dir=$rel_source_dir
  fi

  if [ \! -d $abs_source_dir ] ; then
    echo $progname\: warning\: no such directory\: \`$rel_source_dir\'
    continue
  fi

  for rel_source_subdir in $subdirs; do

      abs_target_subdir=${abs_target_dir}/${rel_source_subdir}
      if [ \! -d $abs_target_subdir ] ; then
        mkdir $abs_target_subdir
      fi
      # Append "/"; remove initial "./". Hence "." -> "" and "sys" -> "sys/".
      rel_source_prefix=`echo $rel_source_subdir | sed -e 's|$|/|' -e 's|^./||'`

      case $code in
	ALL)
	  # The 'sed' is in case the *.h matches nothing, which yields "*.h"
	  # which would then get re-globbed in the current directory.  Sigh.
	  rel_source_files=`cd ${abs_source_dir}/${rel_source_subdir}; echo *.h | sed -e 's|[*].h|NONE|'`
	  ;;

	STD)
	  files_to_check="$std_files"
	  rel_source_files=""

	  # Also process files #included by the $std_files.
	  while [ -n "${files_to_check}" ]
	  do
	    new_files_to_check=""
	    for file in $files_to_check ; do
	      xxfile=`echo $file | sed -e 's|/\([^/\.][^/\.]*\)/\.\./|/|'`
	      # Create the dir where this file will go when fixed.
	      xxdir=`echo ./$file | sed -e 's|/[^/]*$||'`
	      if [ \! -d $abs_target_subdir/$xxdir ] ; then
		mkdir $abs_target_subdir/$xxdir
	      fi
	      # Just in case we have edited out a symbolic link
	      if [ -f $src_dir_std/$file -a -f $src_dir_std/$xxfile ] ; then
		file=$xxfile
	      fi
	      case " $rel_source_files " in
	        *" ${file} "*)
		  # Already seen $file; nothing to do
		  ;;
		*)
		  if test -f $src_dir_std/$file ; then
		    rel_dir=`echo $file | sed -n -e 's|^\(.*/\)[^/]*$|\1|p'`
		    # For #include "foo.h", that might be either "foo.h"
		    # or "${rel_dir}foo.h (or something bogus).
	            new_files_to_check="$new_files_to_check "`sed -n \
			-e 's@	@ @g' \
		        -e 's@^ *# *include *<\([^>]*\)>.*$@\1@p' -e \
		        's@^ *# *include *\"\([^\"]*\)\".*$@\1 '$rel_dir'\1@p'\
			<$src_dir_std/$file`
	            rel_source_files="$rel_source_files $file"
		  fi
		  ;;
	      esac
	    done
	    files_to_check="$new_files_to_check"
	  done
	  rel_source_files="$rel_source_files"
	  ;;
      esac

      for filename in $rel_source_files ; do
	rel_source_file=${rel_source_prefix}${filename}
	abs_source_file=$abs_source_dir/$rel_source_file
	abs_target_file=$abs_target_dir/$rel_source_file

	if test "$filename" = 'NONE' ; then
	  echo "(No *.h files in $abs_source_dir/$rel_source_subdir)"
	# If target file exists, check if was written while processing one
	# of the earlier source directories;  if so ignore it.
	elif test -f $abs_target_file -a -n "$done_dirs" \
	  && grep "$rel_source_file" fixproto.list >/dev/null
	then true
	else
	  # echo doing $rel_source_file from $abs_source_dir
	  required_list=
	  extra_check_list=
	  case $rel_source_file in
	    ctype.h)
	      required_list="isalnum isalpha iscntrl isdigit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper" ;;
	    dirent.h)
	      required_list="closedir opendir readdir rewinddir" ;;
	    errno.h)
	      extra_check_list="errno" ;;
	    curses.h)
	      required_list="box delwin endwin getcurx getcury initscr mvcur mvwprintw mvwscanw newwin overlay overwrite scroll subwin touchwin waddstr wclear wclrtobot wclrtoeol waddch wdelch wdeleteln werase wgetch wgetstr winsch winsertln wmove wprintw wrefresh wscanw wstandend wstandout" ;;
	    fcntl.h)
	      required_list="creat fcntl open" ;;
	    grp.h)
	      #Maybe also "getgrent fgetgrent setgrent endgrent" */
	      required_list="getgrgid getgrnam" ;;
	    limit.h)
	      required_list= /* Lots of macros */ ;;
	    locale.h)
	      required_list="localeconv setlocale" ;;
	    math.h)
	      required_list="acos asin atan atan2 ceil cos cosh exp fabs floor fmod frexp ldexp log10 log modf pow sin sinh sqrt tan tanh"
	      extra_check_list="HUGE_VAL" ;;
	    pwd.h)
	      required_list="getpwnam getpwuid" ;;
	    setjmp.h)
	      # Left out siglongjmp sigsetjmp - these depend on sigjmp_buf.
	      required_list="longjmp setjmp" ;;
	    signal.h)
	      # Left out signal() - its prototype is too complex for us!
	      # Also left out "sigaction sigaddset sigdelset sigemptyset
	      # sigfillset sigismember sigpending sigprocmask sigsuspend"
	      # because these need sigset_t or struct sigaction.
	      # Most systems that provide them will also declare them.
	      required_list="kill raise" ;;
	    stdio.h)
	      required_list="clearerr fclose feof ferror fflush fgetc fgetpos fgets fopen fprintf fputc fputs fread freopen fscanf fseek fsetpos ftell fwrite getc getchar gets pclose perror popen printf putc putchar puts remove rename rewind scanf setbuf setvbuf sprintf sscanf vprintf vsprintf vfprintf tmpfile tmpnam ungetc"
	      if grep '[^_a-zA-Z0-9]_flsbuf' <$abs_source_file >/dev/null; then
		required_list="$required_list _flsbuf _filbuf"
	      fi
	      # Should perhaps also handle NULL, EOF, ... ?
	      ;;
	    stdlib.h)
	      required_list="$required_stdlib_h" ;;
	    string.h)
	      required_list="memchr memcmp memcpy memmove memset strcat strchr strcmp strcoll strcpy strcspn strerror strlen strncat strncmp strncpy strpbrk strrchr strspn strstr strtok strxfrm" ;;
# Should perhaps also add NULL and size_t
	    sys/stat.h)
	      required_list="chmod fstat mkdir mkfifo stat lstat umask"
	      extra_check_list="S_ISDIR S_ISBLK S_ISCHR S_ISFIFO S_ISREG S_ISLNK S_IFDIR S_IFBLK S_IFCHR S_IFIFO S_IFREG S_IFLNK" ;;
	    sys/times.h)
	      required_list="times" ;;
# "sys/types.h" add types (not in old g++-include)
	    sys/utsname.h)
	      required_list="uname" ;;
	    sys/wait.h)
	      required_list="wait waitpid"
	      extra_check_list="WEXITSTATUS WIFEXITED WIFSIGNALED WIFSTOPPED WSTOPSIG WTERMSIG WNOHANG WNOTRACED" ;;
	    tar.h)
	      required_list=  ;;
	    termios.h)
	      required_list="cfgetispeed cfgetospeed cfsetispeed cfsetospeed tcdrain tcflow tcflush tcgetattr tcsendbreak tcsetattr" ;;
	    time.h)
	      required_list="asctime clock ctime difftime gmtime localtime mktime strftime time tzset" ;;
	    unistd.h)
	      required_list="$required_unistd_h" ;;
	  esac
	  rm -f fixtmp.c fixtmp.i
	  echo "#include <${rel_source_file}>" >fixtmp.c
	  for macro in ${required_list} ${extra_check_list}
	  do
	    echo "#ifdef ${macro}" >>fixtmp.c
	    echo "__DEFINED_MACRO_${macro};" >>fixtmp.c
	    echo "#endif" >>fixtmp.c
	  done
	  if ${CPP} ${DEFINES} $include_path fixtmp.c >fixtmp.i 2>/dev/null
	  then
	   $original_dir/fix-header $rel_source_file $abs_source_file $abs_target_file "$required_list" <fixtmp.i
	  else
	    echo "${progname}: cpp could not parse ${abs_source_file} (ignored)"
	  fi
	  echo "${rel_source_file}" >>fixproto.list
	fi
      done
      rm -f fixtmp.c fixtmp.i
    done
    done_dirs="$done_dir $rel_source_dir"
done

# This might be more cleanly moved into the main loop, by adding
# a <dummy> source directory at the end.  FIXME!
for rel_source_file in unistd.h stdlib.h
do
  if grep "$rel_source_file" fixproto.list >/dev/null
  then true
  else
    echo Adding missing $rel_source_file
    rel_source_ident=`echo $rel_source_file | tr ./ __`
    required_list=`eval echo '${required_'${rel_source_ident}'-}'`
    cat >tmp.h <<EOF
#ifndef ${rel_source_ident}
#define ${rel_source_ident}
#endif
EOF
    $original_dir/fix-header $rel_source_file tmp.h $abs_target_dir/$rel_source_file "$required_list" </dev/null
    rm tmp.h
  fi
done
exit 0
