make/common/JavaCompilation.gmk
author ihse
Tue, 03 Nov 2015 17:48:01 +0100
changeset 33437 1cf150337073
parent 33055 3676b99f33cf
child 33438 35cd6a1619df
permissions -rw-r--r--
8141261: Clean up building of demos Reviewed-by: erikj, tbell

#
# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
#
# This code is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 only, as
# published by the Free Software Foundation.  Oracle designates this
# particular file as subject to the "Classpath" exception as provided
# by Oracle in the LICENSE file that accompanied this code.
#
# This code 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
# version 2 for more details (a copy is included in the LICENSE file that
# accompanied this code).
#
# You should have received a copy of the GNU General Public License version
# 2 along with this work; if not, write to the Free Software Foundation,
# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
# or visit www.oracle.com if you need additional information or have any
# questions.
#

# This makefile is much simpler now that it can use the smart javac wrapper
# for dependency tracking between java packages and incremental compiles.
# It could be even more simple if we added support for incremental jar updates
# directly from the smart javac wrapper.

# Cleaning/copying properties here is not a good solution. The properties
# should be cleaned/copied by a annotation processor in sjavac.

# When you read this source. Remember that $(sort ...) has the side effect
# of removing duplicates. It is actually this side effect that is
# desired whenever sort is used below!

ifndef _JAVA_COMPILATION_GMK
_JAVA_COMPILATION_GMK := 1

ifeq (,$(_MAKEBASE_GMK))
  $(error You must include MakeBase.gmk prior to including JavaCompilation.gmk)
endif

# Java compilation needs SetupZipArchive if we're generating a source zip.
include ZipArchive.gmk

FALSE_FIND_PATTERN:=-name FILE_NAME_THAT_DOESNT_EXIST

# Setup make rules for defining a Java compiler, which is needed to compile
# Java code. This rule generates no output.
#
# Parameter 1 is the name of the compiler definition. This name needs to be
# passed to SetupJavaCompilation. This name is used as variable prefix.
#
# Remaining parameters are named arguments. These include:
#   JVM:=The jvm used to run the javac/javah command
#   JAVAC:=The javac jar and bootstrap classpath changes, or just bin/javac if JVM is left out
#   FLAGS:=Flags to be supplied to javac
#   SERVER_DIR:=Use a javac server (-XDserver) and store the server related files here
#   SERVER_JVM:=Use this JVM for the server. Defaults to the JVM above.
#   DISABLE_SJAVAC:=Set to true if this setup does not support sjavac
SetupJavaCompiler = $(NamedParamsMacroTemplate)
define SetupJavaCompilerBody
  # The port file contains the tcp/ip on which the server listens
  # and the cookie necessary to talk to the server.
  $1_SJAVAC_PORTFILE:=$$($1_SERVER_DIR)/server.port
  # You can use a different JVM to run the background javac server.
  ifeq ($$($1_SERVER_JVM),)
    # It defaults to the same JVM that is used to start the javac command.
    $1_SERVER_JVM:=$$($1_JVM)
  endif
endef

# Setup make rules for creating a jar archive.
#
# Parameter 1 is the name of the rule. This name is used as variable prefix,
# and the targets generated are listed in a variable by that name.
#
# Remaining parameters are named arguments. These include:
#   DEPENDENCIES:=List of dependencies for the jar target. If left empty,
#       dependencies are calculated automatically from the source files found.
#       For this to work, the source files must exist when the makefile is
#       parsed.
#   SRCS:=List of directories in where to find files to add to archive
#   SUFFIXES:=File suffixes to include in jar
#   INCLUDES:=List of directories/packages in SRCS that should be included
#   EXCLUDES:=List of directories/packages in SRCS that should be excluded
#   EXCLUDE_FILES:=List of files in SRCS that should be excluded
#   EXTRA_FILES:=List of files in SRCS that should be included regardless of suffix match.
#   JAR:=Jar file to create
#   MANIFEST:=Optional manifest file template.
#   JARMAIN:=Optional main class to add to manifest
#   JARINDEX:=true means generate the index in the jar file.
#   SKIP_METAINF:=Set to prevent contents of an META-INF directory to be automatically
#       added to the archive.
#   EXTRA_MANIFEST_ATTR:=Extra attribute to add to manifest.
#   CHECK_COMPRESS_JAR Check the COMPRESS_JAR variable
SetupArchive = $(NamedParamsMacroTemplate)
define SetupArchiveBody

  $1_JARMAIN:=$(strip $$($1_JARMAIN))
  $1_JARNAME:=$$(notdir $$($1_JAR))
  $1_MANIFEST_FILE:=$$(dir $$($1_JAR))_the.$$($1_JARNAME)_manifest
  $1_DELETESS_FILE:=$$(dir $$($1_JAR))_the.$$($1_JARNAME)_deletess
  $1_DELETES_FILE:=$$(dir $$($1_JAR))_the.$$($1_JARNAME)_deletes
  $1_BIN:=$$(dir $$($1_JAR))

  ifeq (,$$($1_SUFFIXES))
    # No suffix was set, default to classes.
    $1_SUFFIXES:=.class
  endif
  # Convert suffixes to a find expression
  $1_FIND_PATTERNS:=$(FALSE_FIND_PATTERN) $$(patsubst %,$(SPACE)-o$(SPACE)-name$(SPACE)$(DQUOTE)*%$(DQUOTE),$$($1_SUFFIXES))
  # On windows, a lot of includes/excludes risk making the command line too long, so
  # writing the grep patterns to files.
  # Grep returns 1 if nothing is matched. Do not fail the build for this.
  ifneq (,$$($1_INCLUDES))
    $1_GREP_INCLUDE_PATTERNS:=$$(call EscapeDollar, \
        $$(foreach src,$$($1_SRCS), $$(addprefix $$(src)/,$$($1_INCLUDES))))
    # If there are a lot of include patterns, output to file to shorten command lines
    ifeq ($$(word 20,$$($1_GREP_INCLUDE_PATTERNS)),)
      $1_GREP_INCLUDES:=| ( $(GREP) $$(patsubst %,$(SPACE)-e$(SPACE)$(DQUOTE)%$(DQUOTE),$$($1_GREP_INCLUDE_PATTERNS)) \
          || test "$$$$?" = "1" )
    else
      $1_GREP_INCLUDE_OUTPUT = \
          $$(eval $$(call ListPathsSafely,$1_GREP_INCLUDE_PATTERNS, \
              $$($1_BIN)/_the.$$($1_JARNAME)_include))
      $1_GREP_INCLUDES:=| ( $(GREP) -f $$($1_BIN)/_the.$$($1_JARNAME)_include \
          || test "$$$$?" = "1" )
    endif
  endif
  ifneq (,$$($1_EXCLUDES)$$($1_EXCLUDE_FILES))
    $1_GREP_EXCLUDE_PATTERNS:=$$(call EscapeDollar, \
        $$(foreach src,$$($1_SRCS),$$(addprefix $$(src)/, \
        $$($1_EXCLUDES) $$($1_EXCLUDE_FILES))))
    # If there are a lot of include patterns, output to file to shorten command lines
    ifeq ($$(word 20,$$($1_GREP_EXCLUDE_PATTERNS)),)
      $1_GREP_EXCLUDES:=| ( $(GREP) -v $$(patsubst %,$(SPACE)-e$(SPACE)$(DQUOTE)%$(DQUOTE),$$($1_GREP_EXCLUDE_PATTERNS)) \
          || test "$$$$?" = "1" )
    else
      $1_GREP_EXCLUDE_OUTPUT = \
          $$(eval $$(call ListPathsSafely,$1_GREP_EXCLUDE_PATTERNS, \
              $$($1_BIN)/_the.$$($1_JARNAME)_exclude))
      $1_GREP_EXCLUDES:=| ( $(GREP) -v -f $$($1_BIN)/_the.$$($1_JARNAME)_exclude \
          || test "$$$$?" = "1" )
    endif
  endif

  # Check if this jar needs to have its index generated.
  ifneq (,$$($1_JARINDEX))
    $1_JARINDEX = (cd $$(dir $$@) && $(JAR) -i $$(notdir $$@))
  else
    $1_JARINDEX = true
  endif
  # When this macro is run in the same makefile as the java compilation, dependencies are
  # transfered in make variables. When the macro is run in a different makefile than the
  # java compilation, the dependencies need to be found in the filesystem.
  $1_ORIG_DEPS := $$($1_DEPENDENCIES)
  ifeq ($$($1_DEPENDENCIES), )
    # Add all source roots to the find cache since we are likely going to run find
    # on these more than once. The cache will only be updated if necessary.
    $$(eval $$(call FillCacheFind, $$($1_FIND_LIST)))
    $1_DEPENDENCIES:=$$(filter $$(addprefix %,$$($1_SUFFIXES)), \
        $$(call CacheFind,$$($1_SRCS)))
    ifneq (,$$($1_GREP_INCLUDE_PATTERNS))
      $1_DEPENDENCIES:=$$(filter $$(addsuffix %,$$($1_GREP_INCLUDE_PATTERNS)),$$($1_DEPENDENCIES))
    endif
    ifneq (,$$($1_GREP_EXCLUDE_PATTERNS))
      $1_DEPENDENCIES:=$$(filter-out $$(addsuffix %,$$($1_GREP_EXCLUDE_PATTERNS)),$$($1_DEPENDENCIES))
    endif
    # Look for EXTRA_FILES in all SRCS dirs and as absolute paths.
    $1_DEPENDENCIES+=$$(wildcard $$(foreach src, $$($1_SRCS), \
        $$(addprefix $$(src)/, $$($1_EXTRA_FILES))) $$($1_EXTRA_FILES))
    ifeq (,$$($1_SKIP_METAINF))
      $1_DEPENDENCIES+=$$(call CacheFind,$$(wildcard $$(addsuffix /META-INF,$$($1_SRCS))))
    endif
  endif
  # The dependency list should never be empty
  ifeq ($$(strip $$($1_DEPENDENCIES)), )
    $$(warning No dependencies found for $1)
  endif

  # Utility macros, to make the shell script receipt somewhat easier to decipher.

  # Capture extra files is the same for both CAPTURE_CONTENTS and SCAPTURE_CONTENTS so
  # only define it once to avoid duplication.
  # The list of extra files might be long, so need to use ListPathsSafely to print
  # them out to a separte file. Then process the contents of that file to rewrite
  # into -C <dir> <file> lines.
  # The EXTRA_FILES_RESOLVED varible must be set in the macro so that it's evaluated
  # in the recipe when the files are guaranteed to exist.
  $1_CAPTURE_EXTRA_FILES=\
      $$(eval $1_EXTRA_FILES_RESOLVED:=$$(call DoubleDollar, \
          $$(wildcard $$(foreach src, $$($1_SRCS), \
          $$(addprefix $$(src)/, $$($1_EXTRA_FILES))) $$($1_EXTRA_FILES)))) \
      $$(if $$($1_EXTRA_FILES_RESOLVED), \
        $$(eval $$(call ListPathsSafely,$1_EXTRA_FILES_RESOLVED, \
            $$($1_BIN)/_the.$$($1_JARNAME)_contents.extra)) \
        $(SED) $$(foreach src,$$($1_SRCS), -e 's|$$(src)/|-C $$(src) |g') \
            $$($1_BIN)/_the.$$($1_JARNAME)_contents.extra \
            >> $$($1_BIN)/_the.$$($1_JARNAME)_contents $$(NEWLINE))

  # The capture contents macro finds all files (matching the patterns, typically
  # .class and .prp) that are newer than the jar-file, ie the new content to be put into the jar.
  # NOTICE: please leave the parentheses space separated otherwise the AIX build will break!
  $1_CAPTURE_CONTENTS=\
      $(RM) $$($1_BIN)/_the.$$($1_JARNAME)_contents $$(NEWLINE) \
      $$(foreach src,$$($1_SRCS), \
        $(FIND) $$(src) -type f -a \( $$($1_FIND_PATTERNS) \) -a -newer $$@ $$($1_GREP_INCLUDES) \
          $$($1_GREP_EXCLUDES) | $(SED) 's|$$(src)/|-C $$(src) |g' \
        >> $$($1_BIN)/_the.$$($1_JARNAME)_contents $$(NEWLINE)) \
      $$($1_CAPTURE_EXTRA_FILES)

  # The capture metainf macro finds all files below the META-INF directory that are newer than the jar-file.
  # Find returns non zero if the META-INF dir does not exist, ignore this.
  ifeq (,$$($1_SKIP_METAINF))
    $1_CAPTURE_METAINF =$$(foreach src,$$($1_SRCS), \
        ( ( $(FIND) $$(src)/META-INF -type f -a -newer $$@ 2> /dev/null || true ) \
            | $(SED) 's|$$(src)/|-C $$(src) |g' >> \
        $$($1_BIN)/_the.$$($1_JARNAME)_contents ) $$(NEWLINE) )
  endif
  # The capture deletes macro finds all deleted files and concatenates them. The resulting file
  # tells us what to remove from the jar-file.
  $1_CAPTURE_DELETES=$$(foreach src,$$($1_SRCS),($(FIND) $$(src) -name _the.package.deleted -newer $$@ \
      -exec $(SED) 's|$$(src)||g' \{\} >> $$($1_DELETES_FILE) \;) $$(NEWLINE))
  # The update contents macro updates the jar file with the previously capture contents.
  # Use 'wc -w' to see if the contents file is empty.
  $1_UPDATE_CONTENTS=\
      if [ "`$(WC) -l $$($1_BIN)/_the.$$($1_JARNAME)_contents | $(AWK) '{ print $$$$1 }'`" -gt "0" ]; then \
        $(ECHO) "  updating" `$(WC) -l $$($1_BIN)/_the.$$($1_JARNAME)_contents | $(AWK) '{ print $$$$1 }'` files && \
        $(JAR) $$($1_JAR_UPDATE_OPTIONS) $$@ @$$($1_BIN)/_the.$$($1_JARNAME)_contents; \
      fi $$(NEWLINE)
  # The s-variants of the above macros are used when the jar is created from scratch.
  # NOTICE: please leave the parentheses space separated otherwise the AIX build will break!
  $1_SCAPTURE_CONTENTS=\
      $(RM) $$($1_BIN)/_the.$$($1_JARNAME)_contents $$(NEWLINE) \
      $$(foreach src,$$($1_SRCS), \
        $(FIND) $$(src) -type f -a \( $$($1_FIND_PATTERNS) \) $$($1_GREP_INCLUDES) \
            $$($1_GREP_EXCLUDES) | $(SED) 's|$$(src)/|-C $$(src) |g' \
            >> $$($1_BIN)/_the.$$($1_JARNAME)_contents $$(NEWLINE)) \
      $$($1_CAPTURE_EXTRA_FILES)

  # Find returns non zero if the META-INF dir does not exist, ignore this.
  ifeq (,$$($1_SKIP_METAINF))
    $1_SCAPTURE_METAINF=$$(foreach src,$$($1_SRCS), \
        ( ( $(FIND) $$(src)/META-INF -type f 2> /dev/null || true ) \
            | $(SED) 's|$$(src)/|-C $$(src) |g' >> \
        $$($1_BIN)/_the.$$($1_JARNAME)_contents) $$(NEWLINE) )
  endif
  $1_SUPDATE_CONTENTS=$(JAR) $$($1_JAR_UPDATE_OPTIONS) $$@ @$$($1_BIN)/_the.$$($1_JARNAME)_contents $$(NEWLINE)

  # Use a slightly shorter name for logging, but with enough path to identify this jar.
  $1_NAME:=$$(subst $$(OUTPUT_ROOT)/,,$$($1_JAR))

  ifneq (,$$($1_CHECK_COMPRESS_JAR))
    $1_JAR_CREATE_OPTIONS := c0fm
    $1_JAR_UPDATE_OPTIONS := u0f
    ifeq ($(COMPRESS_JARS), true)
      $1_JAR_CREATE_OPTIONS := cfm
      $1_JAR_UPDATE_OPTIONS := uf
    endif
  else
    $1_JAR_CREATE_OPTIONS := cfm
    $1_JAR_UPDATE_OPTIONS := uf
  endif

  # Include all variables of significance in the vardeps file
  $1_VARDEPS := $(JAR) $$($1_JAR_CREATE_OPTIONS) $$($1_MANIFEST) \
      $$($1_JARMAIN) $$($1_EXTRA_MANIFEST_ATTR) $$($1_ORIG_DEPS) $$($1_SRCS) \
      $$($1_INCLUDES) $$($1_EXCLUDES) $$($1_EXCLUDE_FILES) $$($1_EXTRA_FILES)
  $1_VARDEPS_FILE := $$(call DependOnVariable, $1_VARDEPS, $$(dir $$($1_JAR))_the.$$($1_JARNAME).vardeps)

  # Here is the rule that creates/updates the jar file.
  $$($1_JAR) : $$($1_DEPENDENCIES) $$($1_MANIFEST) $$($1_VARDEPS_FILE)
	$(MKDIR) -p $$($1_BIN)
	$$($1_GREP_INCLUDE_OUTPUT)
	$$($1_GREP_EXCLUDE_OUTPUT)
        # If the vardeps file is part of the newer prereq list, it means that
        # either the jar file does not exist, or we need to recreate it from
        # from scratch anyway since a simple update will not catch all the
        # potential changes.
	$$(if $$(filter $$($1_VARDEPS_FILE) $$($1_MANIFEST), $$?), \
	  $$(if $$($1_MANIFEST), \
	    $(SED) -e '$(DOLLAR)$(DOLLAR)a\' $$($1_MANIFEST) > $$($1_MANIFEST_FILE) $$(NEWLINE) \
	  , \
	    $(RM) $$($1_MANIFEST_FILE) && $(TOUCH) $$($1_MANIFEST_FILE) $$(NEWLINE)) \
	  $$(if $$($1_JARMAIN), \
	    $(ECHO) "Main-Class: $$(strip $$($1_JARMAIN))" >> $$($1_MANIFEST_FILE) $$(NEWLINE)) \
	  $$(if $$($1_EXTRA_MANIFEST_ATTR), \
	    $(PRINTF) "$$($1_EXTRA_MANIFEST_ATTR)\n" >> $$($1_MANIFEST_FILE) $$(NEWLINE)) \
	  $(ECHO) Creating $$($1_NAME) $$(NEWLINE) \
	  $(JAR) $$($1_JAR_CREATE_OPTIONS) $$@ $$($1_MANIFEST_FILE) $$(NEWLINE) \
	  $$($1_SCAPTURE_CONTENTS) \
	  $$($1_SCAPTURE_METAINF) \
	  $$($1_SUPDATE_CONTENTS) \
	  $$($1_JARINDEX) && true \
	, \
	  $(ECHO) Modifying $$($1_NAME) $$(NEWLINE) \
	  $$($1_CAPTURE_CONTENTS) \
	  $$($1_CAPTURE_METAINF) \
	  $(RM) $$($1_DELETES_FILE) $$(NEWLINE) \
	  $$($1_CAPTURE_DELETES) \
	  $(CAT) $$($1_DELETES_FILE) > $$($1_DELETESS_FILE) $$(NEWLINE) \
	  if [ -s $$($1_DELETESS_FILE) ]; then \
	    $(ECHO) "  deleting" `$(WC) -l $$($1_DELETESS_FILE) | $(AWK) '{ print $$$$1 }'` files && \
	    $(ZIP) -q -d $$@ `$(CAT) $$($1_DELETESS_FILE)` ; \
	  fi $$(NEWLINE) \
	  $$($1_UPDATE_CONTENTS) true $$(NEWLINE) \
	  $$($1_JARINDEX) && true )

  # Add jar to target list
  $1 += $$($1_JAR)
endef


define add_file_to_copy
  # param 1 = BUILD_MYPACKAGE
  # parma 2 = The source file to copy.
  $2_TARGET:=$2
  # Remove the source prefix.
  $$(foreach i,$$($1_SRC),$$(eval $$(call remove_string,$$i,$2_TARGET)))
  # To allow for automatic overrides, do not create a rule for a target file that
  # already has one
  ifneq ($$($1_COPY_$$($2_TARGET)), 1)
    $1_COPY_$$($2_TARGET) := 1
    # Now we can setup the depency that will trigger the copying.
    $$($1_BIN)$$($2_TARGET) : $2
	$(MKDIR) -p $$(@D)
	$(CP) $$< $$@
	$(CHMOD) -f ug+w $$@

    # And do not forget this target
    $1_ALL_COPY_TARGETS += $$($1_BIN)$$($2_TARGET)
  endif
endef


# This macro is used only for properties files that are to be
# copied over to the classes directory in cleaned form:
# Previously this was inconsistently done in different repositories.
# This is the new clean standard. Though it is to be superseded by
# a standard annotation processor from with sjavac.
#
# An empty echo ensures that the input to sed always ends with a newline.
# Certain implementations (e.g. Solaris) will skip the last line without
# it.
#
# The sed expression does this:
# 1. Add a backslash before any :, = or ! that do not have a backslash already.
# 2. Apply the file unicode2x.sed which does a whole bunch of \u00XX to \xXX
#    conversions.
# 3. Delete all lines starting with #.
# 4. Delete empty lines.
# 5. Append lines ending with \ with the next line.
# 6. Remove leading and trailing white space. Note that tabs must be explicit
#    as sed on macosx does not understand '\t'.
# 7. Replace the first \= with just =.
# 8. Finally it's all sorted to create a stable output.
#
# It is assumed that = is the character used for separating names and values.
define add_file_to_clean
  # param 1 = BUILD_MYPACKAGE
  # parma 2 = The source file to copy and clean.
  $2_TARGET:=$2
  # Remove the source prefix.
  $$(foreach i,$$($1_SRC),$$(eval $$(call remove_string,$$i,$2_TARGET)))
  # Now we can setup the depency that will trigger the copying.
  # To allow for automatic overrides, do not create a rule for a target file that
  # already has one
  ifneq ($$($1_CLEAN_$$($2_TARGET)), 1)
    $1_CLEAN_$$($2_TARGET) := 1
    $$($1_BIN)$$($1_MODULE_SUBDIR)$$($2_TARGET) : $2
	$(MKDIR) -p $$(@D)
	export LC_ALL=C ; ( $(CAT) $$< && $(ECHO) "" ) \
	    | $(SED) -e 's/\([^\\]\):/\1\\:/g' -e 's/\([^\\]\)=/\1\\=/g' \
	        -e 's/\([^\\]\)!/\1\\!/g' -e 's/^[ 	]*#.*/#/g' \
	    | $(SED) -f "$(SRC_ROOT)/make/common/support/unicode2x.sed" \
	    | $(SED) -e '/^#/d' -e '/^$$$$/d' \
	        -e :a -e '/\\$$$$/N; s/\\\n//; ta' \
	        -e 's/^[ 	]*//;s/[ 	]*$$$$//' \
	        -e 's/\\=/=/' \
	    | $(SORT) > $$@
	$(CHMOD) -f ug+w $$@

    # And do not forget this target
    $1_ALL_COPY_CLEAN_TARGETS += $$($1_BIN)$$($2_TARGET)
  endif
endef

define remove_string
  $2 := $$(subst $1,,$$($2))
endef

# Setup make rules for compiling Java source code to class files and/or a
# resulting jar file.
#
# Parameter 1 is the name of the rule. This name is used as variable prefix,
# and the targets generated are listed in a variable by that name.
#
# Remaining parameters are named arguments. These include:
#   SETUP:=must point to a previously setup java compiler, for example: SETUP:=BOOTJAVAC
#   JVM:=path to ..bin/java
#   ADD_JAVAC_FLAGS:=javac flags to append to the default ones.
#   SRC:=one or more directories to search for sources. The order of the source roots
#        is significant. The first found file of a certain name has priority.
#   BIN:=store classes here
#   CLASSPATH:=a list of additional entries to set as classpath to javac
#   INCLUDES:=myapp.foo means will only compile java files in myapp.foo or any of its sub-packages.
#   EXCLUDES:=myapp.foo means will do not compile java files in myapp.foo or any of its sub-packages.
#   COPY:=.prp means copy all prp files to the corresponding package in BIN.
#   COPY_FILES:=myapp/foo/setting.txt means copy this file over to the package myapp/foo
#   CLEAN:=.properties means copy and clean all properties file to the corresponding package in BIN.
#   CLEAN_FILES:=myapp/foo/setting.txt means clean this file over to the package myapp/foo
#   SRCZIP:=Create a src.zip based on the found sources and copied files.
#   INCLUDE_FILES:="com/sun/SolarisFoobar.java" means only compile this file!
#   EXCLUDE_FILES:="com/sun/SolarisFoobar.java" means do not compile this particular file!
#       "SolarisFoobar.java" means do not compile SolarisFoobar, wherever it is found.
#   HEADERS:=path to directory where all generated c-headers are written.
#   DEPENDS:=Extra dependecy
#   DISABLE_SJAVAC:=Explicitly disable the use of sjavac for this compilation unit.
#   KEEP_DUPS:=Do not remove duplicate file names from different source roots.
SetupJavaCompilation = $(NamedParamsMacroTemplate)
define SetupJavaCompilationBody

  # Verify arguments
  ifeq ($$($1_BIN),)
    $$(error Must specify BIN (in $1))
  endif

  # Extract the info from the java compiler setup.
  $1_JVM := $$($$($1_SETUP)_JVM)
  $1_JAVAC := $$($$($1_SETUP)_JAVAC)
  $1_FLAGS := $$($$($1_SETUP)_FLAGS) $(JAVAC_FLAGS) $$($1_ADD_JAVAC_FLAGS)
  ifneq ($$($1_CLASSPATH), )
    $1_FLAGS += -cp $$(call PathList, $$($1_CLASSPATH))
  endif
  ifeq ($$($1_JAVAC),)
    $$(error The Java compilation $1 refers to a non-existant java compiler setup $$($1_SETUP))
  endif
  $1_SJAVAC_PORTFILE := $$($$($1_SETUP)_SJAVAC_PORTFILE)
  $1_SERVER_JVM := $$($$($1_SETUP)_SERVER_JVM)
  $1_DISABLE_SJAVAC := $$($$($1_SETUP)_DISABLE_SJAVAC)

  # Handle addons and overrides.
  $1_SRC:=$$(call ADD_SRCS,$$($1_SRC))
  # Make sure the dirs exist.
  $$(foreach d,$$($1_SRC), $$(if $$(wildcard $$d),,$$(error SRC specified to SetupJavaCompilation $1 contains missing directory >$$d<)))
  $$(call MakeDir,$$($1_BIN))
  # Add all source roots to the find cache since we are likely going to run find
  # on these more than once. The cache will only be updated if necessary.
  $$(eval $$(call FillCacheFind,$$($1_SRC)))
  # Find all files in the source trees. Preserve order of source roots for overrides to
  # work correctly. CacheFind does not preserve order so need to call it for each root.
  $1_ALL_SRCS += $$(filter-out $(OVR_SRCS),$$(foreach s,$$($1_SRC),$$(call CacheFind,$$(s))))
  # Extract the java files.
  ifneq ($$($1_EXCLUDE_FILES),)
    $1_EXCLUDE_FILES_PATTERN:=$$(addprefix %,$$($1_EXCLUDE_FILES))
  endif
  $1_SRCS := $$(filter-out $$($1_EXCLUDE_FILES_PATTERN),$$(filter %.java,$$($1_ALL_SRCS)))
  ifneq ($$($1_INCLUDE_FILES),)
    $1_INCLUDE_FILES:=$$(foreach i,$$($1_SRC),$$(addprefix $$i/,$$($1_INCLUDE_FILES)))
    $1_SRCS := $$(filter $$($1_INCLUDE_FILES), $$($1_SRCS))
  endif

  # Prepend the source/bin path to the filter expressions.
  ifneq ($$($1_INCLUDES),)
    $1_SRC_INCLUDES := $$(foreach i,$$($1_SRC),$$(addprefix $$i/,$$(addsuffix /%,$$($1_INCLUDES))))
    $1_SRCS := $$(filter $$($1_SRC_INCLUDES),$$($1_SRCS))
  endif
  ifneq ($$($1_EXCLUDES),)
    $1_SRC_EXCLUDES := $$(foreach i,$$($1_SRC),$$(addprefix $$i/,$$(addsuffix /%,$$($1_EXCLUDES))))
    $1_SRCS := $$(filter-out $$($1_SRC_EXCLUDES),$$($1_SRCS))
  endif

  ifneq ($$($1_KEEP_DUPS), true)
    # Remove duplicate source files by keeping the first found of each duplicate.
    # This allows for automatic overrides with custom or platform specific versions
    # source files.
    #
    # For the smart javac wrapper case, add each removed file to an extra exclude
    # file list to prevent sjavac from finding duplicate sources.
    $1_SRCS := $$(strip $$(foreach s, $$($1_SRCS), \
        $$(eval relative_src := $$(call remove-prefixes, $$($1_SRC), $$(s))) \
        $$(if $$($1_$$(relative_src)), \
          $$(eval $1_SJAVAC_EXCLUDE_FILES += $$(s)), \
          $$(eval $1_$$(relative_src) := 1) $$(s))))
  endif

  ifeq ($$(strip $$($1_SRCS)), )
    $$(error No source files found for $1)
  endif

  $1_SAFE_NAME := $$(strip $$(subst /,_, $1))

  # Create the corresponding smart javac wrapper command line.
  $1_SJAVAC_ARGS:=$$(addprefix -x ,$$(addsuffix /*,$$($1_EXCLUDES))) \
      $$(addprefix -i ,$$(addsuffix /*,$$($1_INCLUDES))) \
      $$(addprefix -xf *,$$(strip $$($1_EXCLUDE_FILES) $$($1_SJAVAC_EXCLUDE_FILES))) \
      $$(addprefix -if *,$$(strip $$($1_INCLUDE_FILES))) \
      -src $$(call PathList, $$($1_SRC))

  # All files below META-INF are always copied.
  $1_ALL_COPIES := $$(filter $$(addsuffix /META-INF%,$$($1_SRC)),$$($1_ALL_SRCS))
  # Find all files to be copied from source to bin.
  ifneq (,$$($1_COPY)$$($1_COPY_FILES))
    # Search for all files to be copied.
    $1_ALL_COPIES += $$(filter $$(addprefix %,$$($1_COPY)),$$($1_ALL_SRCS))
    # Copy these explicitly
    $1_ALL_COPIES += $$($1_COPY_FILES)
  endif
  # Copy must also respect filters.
  ifneq (,$$($1_INCLUDES))
    $1_ALL_COPIES := $$(filter $$($1_SRC_INCLUDES),$$($1_ALL_COPIES))
  endif
  ifneq (,$$($1_EXCLUDES))
    $1_ALL_COPIES := $$(filter-out $$($1_SRC_EXCLUDES),$$($1_ALL_COPIES))
  endif
  ifneq (,$$($1_EXCLUDE_FILES))
    $1_ALL_COPIES := $$(filter-out $$($1_EXCLUDE_FILES_PATTERN),$$($1_ALL_COPIES))
  endif
  ifneq (,$$($1_ALL_COPIES))
    # Yep, there are files to be copied!
    $1_ALL_COPY_TARGETS:=
        $$(foreach i,$$($1_ALL_COPIES),$$(eval $$(call add_file_to_copy,$1,$$i)))
    # Now we can depend on $$($1_ALL_COPY_TARGETS) to copy all files!
  endif

  # Find all property files to be copied and cleaned from source to bin.
  ifneq (,$$($1_CLEAN)$$($1_CLEAN_FILES))
    # Search for all files to be copied.
    $1_ALL_CLEANS := $$(filter $$(addprefix %,$$($1_CLEAN)),$$($1_ALL_SRCS))
    # Clean these explicitly
    $1_ALL_CLEANS += $$($1_CLEAN_FILES)
    # Copy and clean must also respect filters.
    ifneq (,$$($1_INCLUDES))
      $1_ALL_CLEANS := $$(filter $$($1_SRC_INCLUDES),$$($1_ALL_CLEANS))
    endif
    ifneq (,$$($1_EXCLUDES))
      $1_ALL_CLEANS := $$(filter-out $$($1_SRC_EXCLUDES),$$($1_ALL_CLEANS))
    endif
    ifneq (,$$($1_EXCLUDE_FILES))
      $1_ALL_CLEANS := $$(filter-out $$($1_EXCLUDE_FILES_PATTERN),$$($1_ALL_CLEANS))
    endif
    ifneq (,$$($1_ALL_CLEANS))
      # Yep, there are files to be copied and cleaned!
      $1_ALL_COPY_CLEAN_TARGETS:=
          $$(foreach i,$$($1_ALL_CLEANS),$$(eval $$(call add_file_to_clean,$1,$$i)))
      # Now we can depend on $$($1_ALL_COPY_CLEAN_TARGETS) to copy all files!
    endif
  endif

  # Create a sed expression to remove the source roots and to replace / with .
  # and remove .java at the end.
  $1_REWRITE_INTO_CLASSES:=$$(foreach i,$$($1_SRC),-e 's|$$i/||g') -e 's|/|.|g' -e 's|.java$$$$||g'

  # Create SJAVAC variable from JAVAC variable. Expects $1_JAVAC to be
  # "bootclasspathprepend -cp .../javac.jar com.sun.tools.javac.Main"
  # and javac is simply replaced with sjavac.
  $1_SJAVAC:=$$(subst com.sun.tools.javac.Main,com.sun.tools.sjavac.Main,$$($1_JAVAC))

  # Set the $1_REMOTE to spawn a background javac server.
  $1_REMOTE:=--server:portfile=$$($1_SJAVAC_PORTFILE),id=$1,sjavac=$$(subst \
      $$(SPACE),%20,$$(subst $$(COMMA),%2C,$$(strip $$($1_SERVER_JVM) $$($1_SJAVAC))))

  ifeq ($$($1_DISABLE_SJAVAC)x$$(ENABLE_SJAVAC),xyes)
    ifneq (,$$($1_HEADERS))
      $1_HEADERS_ARG := -h $$($1_HEADERS)
    endif

    # Using sjavac to compile.
    $1_COMPILE_TARGETS := $$($1_BIN)/_the.$1_batch

    $1_VARDEPS := $$($1_JVM) $$($1_SJAVAC) $$($1_SJAVAC_ARGS) $$($1_FLAGS) \
        $$($1_HEADERS_ARG) $$($1_BIN) $$($1_EXCLUDES) $$($1_INCLUDES) \
        $$($1_EXCLUDE_FILES) $$($1_INCLUDE_FILES)
    $1_VARDEPS_FILE := $$(call DependOnVariable, $1_VARDEPS, $$($1_BIN)/_the.$1.vardeps)

    $$($1_BIN)/_the.$1_batch: $$($1_SRCS) $$($1_DEPENDS) $$($1_VARDEPS_FILE)
	$(MKDIR) -p $$(@D) $$(dir $$($1_SJAVAC_PORTFILE))
	$$(eval $$(call ListPathsSafely,$1_SRCS, $$($1_BIN)/_the.$1_batch.tmp))
	$(ECHO) Compiling $1
	$(call LogFailures, $$($1_BIN)/_the.$$($1_SAFE_NAME)_batch.log, $$($1_SAFE_NAME), \
	    $$($1_JVM) $$($1_SJAVAC) \
	        $$($1_REMOTE) \
	        -j 1 \
	        --permit-unidentified-artifacts \
	        --permit-sources-without-package \
	        --compare-found-sources $$($1_BIN)/_the.$1_batch.tmp \
	        --log=$(LOG_LEVEL) \
	        --state-dir=$$($1_BIN) \
	        $$($1_SJAVAC_ARGS) \
	        $$($1_FLAGS) \
	        $$($1_HEADERS_ARG) \
	        -d $$($1_BIN)) && \
	$(MV) $$($1_BIN)/_the.$1_batch.tmp $$($1_BIN)/_the.$1_batch
        # Create a pubapi file that only changes when the pubapi changes. Dependent
        # compilations can use this file to only get recompiled when pubapi has changed.
        # Grep returns 1 if no matching lines are found. Do not fail for this.
	$(GREP) -e "^I" $$($1_BIN)/javac_state > $$($1_BIN)/_the.$1_pubapi.tmp \
	    || test "$$$$?" = "1"
	if [ ! -f $$($1_BIN)/_the.$1_pubapi ] \
	    || [ "`$(DIFF) $$($1_BIN)/_the.$1_pubapi $$($1_BIN)/_the.$1_pubapi.tmp`" != "" ]; then \
	  $(MV) $$($1_BIN)/_the.$1_pubapi.tmp $$($1_BIN)/_the.$1_pubapi; \
	fi

  else
    # Using plain javac to batch compile everything.
    $1_COMPILE_TARGETS := $$($1_BIN)/_the.$1_batch

    # When building in batch, put headers in a temp dir to filter out those that actually
    # changed before copying them to the real header dir.
    ifneq (,$$($1_HEADERS))
      $1_HEADERS_ARG := -h $$($1_HEADERS).$1.tmp

      $$($1_HEADERS)/_the.$1_headers: $$($1_BIN)/_the.$1_batch
		$(MKDIR) -p $$(@D)
		if [ -d "$$($1_HEADERS).$1.tmp" ]; then \
		  for f in `ls $$($1_HEADERS).$1.tmp`; do \
		    if [ ! -f "$$($1_HEADERS)/$$$$f" ] \
		        || [ "`$(DIFF) $$($1_HEADERS)/$$$$f $$($1_HEADERS).$1.tmp/$$$$f`" != "" ]; then \
		    $(CP) -f $$($1_HEADERS).$1.tmp/$$$$f $$($1_HEADERS)/$$$$f; \
		  fi; \
		  done; \
		fi
		$(RM) -r $$($1_HEADERS).$1.tmp
		$(TOUCH) $$@

      $1_HEADER_TARGETS := $$($1_HEADERS)/_the.$1_headers
    endif

    $1_VARDEPS := $$($1_JVM) $$($1_JAVAC) $$($1_FLAGS) $$($1_BIN) \
        $$($1_HEADERS_ARG) $$($1_EXCLUDES) $$($1_INCLUDES) \
        $$($1_EXCLUDE_FILES) $$($1_INCLUDE_FILES)
    $1_VARDEPS_FILE := $$(call DependOnVariable, $1_VARDEPS, $$($1_BIN)/_the.$1.vardeps)

    ifeq ($$($1_DISABLE_SJAVAC)x$(ENABLE_JAVAC_SERVER), xyes)
      $1_JAVAC_CMD := $$($1_SJAVAC) $$($1_REMOTE)
    else
      $1_JAVAC_CMD := $$($1_JAVAC)
    endif

    # When not using sjavac, pass along all sources to javac using an @file.
    $$($1_BIN)/_the.$1_batch: $$($1_SRCS) $$($1_DEPENDS) $$($1_VARDEPS_FILE)
	$(MKDIR) -p $$(@D)
	$$(eval $$(call ListPathsSafely,$1_SRCS, $$($1_BIN)/_the.$1_batch.tmp))
	$(ECHO) Compiling `$(WC) $$($1_BIN)/_the.$1_batch.tmp | $(TR) -s ' ' | $(CUT) -f 2 -d ' '` files for $1
	$(call LogFailures, $$($1_BIN)/_the.$$($1_SAFE_NAME)_batch.log, $$($1_SAFE_NAME), \
	    $$($1_JVM) $$($1_JAVAC_CMD) $$($1_FLAGS) \
	        -implicit:none \
	        -d $$($1_BIN) $$($1_HEADERS_ARG) @$$($1_BIN)/_the.$1_batch.tmp) && \
	$(MV) $$($1_BIN)/_the.$1_batch.tmp $$($1_BIN)/_the.$1_batch
  endif

  # Add all targets to main variable
  $1 := $$($1_ALL_COPY_TARGETS) $$($1_ALL_COPY_CLEAN_TARGETS) $$($1_COMPILE_TARGETS) \
      $$($1_HEADER_TARGETS)

  # Check if a jar file was specified, then setup the rules for the jar.
  ifneq (,$$($1_JAR))
    # If no suffixes was explicitly set for this jar file.
    # Use class and the cleaned/copied properties file suffixes as the default
    # for the types of files to be put into the jar.
    ifeq (,$$($1_SUFFIXES))
      $1_SUFFIXES:=.class $$($1_CLEAN) $$($1_COPY)
    endif

    $$(eval $$(call SetupArchive,ARCHIVE_$1, \
        DEPENDENCIES:=$$($1), \
        SRCS:=$$($1_BIN), \
        SUFFIXES:=$$($1_SUFFIXES), \
        EXCLUDE:=$$($1_EXCLUDES), \
        INCLUDES:=$$($1_INCLUDES), \
        EXTRA_FILES:=$$($1_ALL_COPY_TARGETS) $$($1_ALL_COPY_CLEAN_TARGETS), \
        JAR:=$$($1_JAR), \
        JARMAIN:=$$($1_JARMAIN), \
        MANIFEST:=$$($1_MANIFEST), \
        EXTRA_MANIFEST_ATTR:=$$($1_EXTRA_MANIFEST_ATTR), \
        JARINDEX:=$$($1_JARINDEX), \
        HEADERS:=$$($1_HEADERS), \
        SETUP:=$$($1_SETUP)))

    # Add jar to target list
    $1 += $$($1_JAR)
  endif

  # Check if a srczip was specified, then setup the rules for the srczip.
  ifneq (,$$($1_SRCZIP))
    $$(eval $$(call SetupZipArchive, ZIP_ARCHIVE_$1, \
        SRC:=$$($1_SRC), \
        ZIP:=$$($1_SRCZIP), \
        INCLUDES:=$$($1_INCLUDES), \
        EXCLUDES:=$$($1_EXCLUDES), \
        EXCLUDE_FILES:=$$($1_EXCLUDE_FILES)))

    # Add zip to target list
    $1 += $$($1_SRCZIP)
  endif
endef

# Use this macro to find the correct target to depend on when the original
# SetupJavaCompilation is declared in a different makefile, to avoid having
# to declare and evaluate it again.
# param 1 is for example BUILD_MYPACKAGE
# param 2 is the output directory (BIN)
define SetupJavaCompilationCompileTarget
  $(if $(findstring yes, $(ENABLE_SJAVAC)), $(strip $2)/_the.$(strip $1)_pubapi, \
      $(strip $2)/_the.$(strip $1)_batch)
endef

endif # _JAVA_COMPILATION_GMK