Asking Gradle to dump the heap if it runs out

Bug: 166798518
Test: change the heap size to 1g, run androidx.sh, see a heap dump in the dist dir
Test: Hopefully if the build server runs out of heap then it will export a heap dump

Change-Id: I91dd21bad013d6a9bff5adbc745688c83c83b439
diff --git a/gradlew b/gradlew
index aa73e6f..ad1d59d 100755
--- a/gradlew
+++ b/gradlew
@@ -21,7 +21,7 @@
     export OUT_DIR="$CHECKOUT_ROOT/out"
 fi
 
-XMX_ARG="$(cd $SCRIPT_PATH && grep org.gradle.jvmargs gradle.properties | sed 's/^/-D/')"
+ORG_GRADLE_JVMARGS="$(cd $SCRIPT_PATH && grep org.gradle.jvmargs gradle.properties | sed 's/^/-D/')"
 if [ -n "$DIST_DIR" ]; then
     mkdir -p "$DIST_DIR"
     DIST_DIR="$(cd $DIST_DIR && pwd -P)"
@@ -29,7 +29,10 @@
 
     #Set the initial heap size to match the max heap size,
     #by replacing a string like "-Xmx1g" with one like "-Xms1g -Xmx1g"
-    XMX_ARG="$(echo $XMX_ARG | sed 's/-Xmx\([^ ]*\)/-Xms\1 -Xmx\1/')"
+    ORG_GRADLE_JVMARGS="$(echo $ORG_GRADLE_JVMARGS | sed 's/-Xmx\([^ ]*\)/-Xms\1 -Xmx\1/')"
+
+    # tell Gradle where to put a heap dump on failure
+    ORG_GRADLE_JVMARGS="$(echo $ORG_GRADLE_JVMARGS | sed "s|$| -XX:HeapDumpPath=$DIST_DIR|")"
 
     # We don't set a default DIST_DIR in an else clause here because Studio doesn't use gradlew
     # and doesn't set DIST_DIR and we want gradlew and Studio to match
@@ -227,7 +230,7 @@
 }
 
 function runGradle() {
-  if "$JAVACMD" "${JVM_OPTS[@]}" $TMPDIR_ARG -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain $HOME_SYSTEM_PROPERTY_ARGUMENT $TMPDIR_ARG "$XMX_ARG" "$@"; then
+  if "$JAVACMD" "${JVM_OPTS[@]}" $TMPDIR_ARG -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain $HOME_SYSTEM_PROPERTY_ARGUMENT $TMPDIR_ARG "$ORG_GRADLE_JVMARGS" "$@"; then
     return 0
   else
     tryToDiagnosePossibleDaemonFailure