Make tools/retrace.py use R8 version of retrace

We might as well dogfood our own retrace tool.

Change-Id: Iacd7e04a9b9afa460e6c13855afaa94c5d8a6cd7
diff --git a/src/main/java/com/android/tools/r8/utils/SelfRetraceTest.java b/src/main/java/com/android/tools/r8/utils/SelfRetraceTest.java
index ab891e8..dc7ce2b 100644
--- a/src/main/java/com/android/tools/r8/utils/SelfRetraceTest.java
+++ b/src/main/java/com/android/tools/r8/utils/SelfRetraceTest.java
@@ -22,7 +22,7 @@
   }
 
   public static void test() {
-    if (System.getenv(SELFRETRACETEST_ENVIRONMENT_VAR) != null) {
+    if (System.getProperty(SELFRETRACETEST_ENVIRONMENT_VAR) != null) {
       new SelfRetraceTest().foo1();
     }
   }
diff --git a/src/test/java/com/android/tools/r8/cf/bootstrap/BootstrapCurrentEqualityTest.java b/src/test/java/com/android/tools/r8/cf/bootstrap/BootstrapCurrentEqualityTest.java
index a19cfec..0ba8510 100644
--- a/src/test/java/com/android/tools/r8/cf/bootstrap/BootstrapCurrentEqualityTest.java
+++ b/src/test/java/com/android/tools/r8/cf/bootstrap/BootstrapCurrentEqualityTest.java
@@ -5,8 +5,12 @@
 
 import static com.android.tools.r8.utils.FileUtils.JAR_EXTENSION;
 import static com.google.common.io.ByteStreams.toByteArray;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
 import static org.junit.Assert.assertArrayEquals;
 import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
 
 import com.android.tools.r8.ArchiveClassFileProvider;
 import com.android.tools.r8.CompilationFailedException;
@@ -18,8 +22,12 @@
 import com.android.tools.r8.TestRuntime;
 import com.android.tools.r8.ToolHelper;
 import com.android.tools.r8.ToolHelper.ProcessResult;
+import com.android.tools.r8.retrace.Retrace;
+import com.android.tools.r8.retrace.RetraceCommand;
 import com.android.tools.r8.utils.FileUtils;
 import com.android.tools.r8.utils.Pair;
+import com.android.tools.r8.utils.StringUtils;
+import com.google.common.collect.Lists;
 import java.io.BufferedInputStream;
 import java.io.FileInputStream;
 import java.io.IOException;
@@ -104,14 +112,59 @@
 
   @Test
   public void testRetrace() throws IOException {
-    ProcessResult result =
+    ProcessResult processResult =
         ToolHelper.runProcess(
-            new ProcessBuilder(
-                "python",
-                Paths.get(ToolHelper.TOOLS_DIR, "test_self_retrace.py").toString(),
-                r8R8Release.getFirst().toString(),
-                r8R8Release.getSecond().toString()));
-    assertEquals(result.toString(), 0, result.exitCode);
+            new ProcessBuilder()
+                .command(
+                    parameters.getRuntime().asCf().getJavaExecutable().toString(),
+                    "-DR8_THROW_EXCEPTION_FOR_TESTING_RETRACE=1",
+                    "-cp",
+                    r8R8Release.getFirst().toString(),
+                    "com.android.tools.r8.R8",
+                    "--help"));
+    assertNotEquals(0, processResult.exitCode);
+    assertThat(processResult.stderr, not(containsString("SelfRetraceTest")));
+
+    List<String> expectedStackTrace =
+        Lists.newArrayList(
+            "Intentional exception for testing retrace.",
+            "com.android.tools.r8.utils.SelfRetraceTest.foo3(SelfRetraceTest.java:13)",
+            "com.android.tools.r8.utils.SelfRetraceTest.foo2(SelfRetraceTest.java:17)",
+            "com.android.tools.r8.utils.SelfRetraceTest.foo1(SelfRetraceTest.java:21)",
+            "com.android.tools.r8.utils.SelfRetraceTest.test(SelfRetraceTest.java:26)",
+            "com.android.tools.r8.R8.run(R8.java:");
+
+    RetraceCommand retraceCommand =
+        RetraceCommand.builder()
+            .setStackTrace(StringUtils.splitLines(processResult.stderr))
+            .setProguardMapProducer(
+                () -> {
+                  Path mappingFile = r8R8Release.getSecond();
+                  try {
+                    return new String(Files.readAllBytes(mappingFile));
+                  } catch (IOException e) {
+                    e.printStackTrace();
+                    throw new RuntimeException(
+                        "Could not read mapping file " + mappingFile.toString());
+                  }
+                })
+            .setRetracedStackTraceConsumer(
+                retraced -> {
+                  int expectedIndex = -1;
+                  for (String line : retraced) {
+                    if (expectedIndex >= expectedStackTrace.size()) {
+                      break;
+                    } else if (expectedIndex == -1 && line.contains("java.lang.RuntimeException")) {
+                      expectedIndex = 0;
+                    }
+                    if (expectedIndex > -1) {
+                      assertThat(line, containsString(expectedStackTrace.get(expectedIndex++)));
+                    }
+                  }
+                  assertEquals(expectedStackTrace.size(), expectedIndex);
+                })
+            .build();
+    Retrace.run(retraceCommand);
   }
 
   @Test
diff --git a/tools/retrace.py b/tools/retrace.py
index 6f3593f..e8fdf89 100755
--- a/tools/retrace.py
+++ b/tools/retrace.py
@@ -71,8 +71,13 @@
       return 1
 
   retrace_args = [
-    jdk.GetJavaExecutable(), '-jar', utils.RETRACE_JAR, r8lib_map_path
+    jdk.GetJavaExecutable(),
+    '-cp',
+    utils.R8LIB_JAR,
+    'com.android.tools.r8.retrace.Retrace',
+    r8lib_map_path
   ]
+
   if args.stacktrace:
     retrace_args.append(args.stacktrace)
 
diff --git a/tools/test_self_retrace.py b/tools/test_self_retrace.py
deleted file mode 100755
index d7ab9aa..0000000
--- a/tools/test_self_retrace.py
+++ /dev/null
@@ -1,77 +0,0 @@
-#!/usr/bin/env python
-# Copyright (c) 2018, the R8 project authors. Please see the AUTHORS file
-# for details. All rights reserved. Use of this source code is governed by a
-# BSD-style license that can be found in the LICENSE file.
-
-from __future__ import absolute_import
-from __future__ import division
-from __future__ import print_function
-
-import gradle
-import jdk
-import os
-import subprocess
-import sys
-
-import utils
-
-EXCEPTION_LINE = 'Intentional exception for testing retrace.'
-EXPECTED_LINES = [
-  'com.android.tools.r8.utils.SelfRetraceTest.foo3(SelfRetraceTest.java:13)',
-  'com.android.tools.r8.utils.SelfRetraceTest.foo2(SelfRetraceTest.java:17)',
-  'com.android.tools.r8.utils.SelfRetraceTest.foo1(SelfRetraceTest.java:21)',
-  'com.android.tools.r8.utils.SelfRetraceTest.test(SelfRetraceTest.java:26)',
-  'com.android.tools.r8.R8.run(R8.java:',
-]
-
-def main():
-  args = sys.argv[1:]
-  if len(args) == 0:
-    gradle.RunGradle(['r8lib'])
-    r8lib = utils.R8LIB_JAR
-    r8map = utils.R8LIB + '.map'
-  elif len(args) == 2:
-    r8lib = args[0]
-    r8map = args[1]
-  elif len(args) == 1 and args[0] == '--help':
-    print('Usage: test_self_retrace.py [<path-to-r8lib-jar> <path-to-r8lib-map]')
-    print('If the path is missing the script builds and uses ' + utils.R8LIB_JAR)
-    return
-  else:
-    raise Exception("Only two argument allowed, see '--help'.")
-
-  # Run 'r8 --help' which throws an exception.
-  cmd = [
-    jdk.GetJavaExecutable(),'-cp', r8lib, 'com.android.tools.r8.R8', '--help'
-  ]
-  os.environ["R8_THROW_EXCEPTION_FOR_TESTING_RETRACE"] = "1"
-  utils.PrintCmd(cmd)
-  p = subprocess.Popen(cmd, stderr=subprocess.PIPE)
-  _, stacktrace = p.communicate()
-  assert(p.returncode != 0)
-  assert(EXCEPTION_LINE in stacktrace)
-  # r8lib must be minified, original class names must not be present.
-  assert('SelfRetraceTest' not in stacktrace)
-
-  # Run the retrace tool.
-  cmd = [jdk.GetJavaExecutable(), '-jar', utils.RETRACE_JAR, r8map]
-  utils.PrintCmd(cmd)
-  p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
-  retrace_stdout, _ = p.communicate(stacktrace)
-  assert p.returncode == 0
-  retrace_lines = retrace_stdout.splitlines()
-  line_index = -1
-  for line in retrace_lines:
-    if line_index < 0:
-      if 'java.lang.RuntimeException' in line:
-        assert(EXCEPTION_LINE in line)
-        line_index = 0;
-    else:
-      assert EXPECTED_LINES[line_index] in line
-      line_index += 1
-      if line_index >= len(EXPECTED_LINES):
-         break
-  assert(line_index >= 0)
-
-if __name__ == '__main__':
-  sys.exit(main())
diff --git a/tools/utils.py b/tools/utils.py
index 51c5a12..6690ba2 100644
--- a/tools/utils.py
+++ b/tools/utils.py
@@ -60,12 +60,6 @@
 GENERATED_LICENSE = os.path.join(GENERATED_LICENSE_DIR, 'LICENSE')
 RT_JAR = os.path.join(REPO_ROOT, 'third_party/openjdk/openjdk-rt-1.8/rt.jar')
 R8LIB_KEEP_RULES = os.path.join(REPO_ROOT, 'src/main/keep.txt')
-RETRACE_JAR = os.path.join(
-    THIRD_PARTY,
-    'proguard',
-    'proguard6.0.1',
-    'lib',
-    'retrace.jar')
 PROGUARD_JAR = os.path.join(
     THIRD_PARTY,
     'proguard',