Install stdlib source

Installs the stdlib sources the compiler built against to allow Android
to build sysroots using the same sources the compiler would use.

Only installed for the Linux target since the sources should be
identical, and the OSX build can use the Linux sources.

Bug: 139486496
Change-Id: If359eeef4c9c14bfada5ffa043143f53ba6c29f2
diff --git a/build.py b/build.py
index c672460..381cfee 100755
--- a/build.py
+++ b/build.py
@@ -20,6 +20,7 @@
 import glob
 import os
 import os.path
+import shutil
 import subprocess
 import sys
 
@@ -28,6 +29,25 @@
 import paths
 
 
+STDLIB_SOURCES = [
+        "src/liballoc",
+        "src/libcore",
+        "src/libpanic_abort",
+        "src/libpanic_unwind",
+        "src/libstd",
+        "src/libterm",
+        "src/libtest",
+        "src/libunwind",
+        "src/stdsimd",
+        "vendor/cfg-if",
+        "vendor/compiler_builtins",
+        "vendor/getopts",
+        "vendor/hashbrown",
+        "vendor/libc",
+        "vendor/unicode-width",
+]
+
+
 def parse_args():
     """Parses arguments and returns the parsed structure."""
     parser = argparse.ArgumentParser('Build the Rust Toolchain')
@@ -89,6 +109,11 @@
         print("Build stage failed with error {}".format(ec))
         sys.exit(ec)
 
+    # Install sources
+    if build_platform.system() == 'linux':
+        for stdlib in STDLIB_SOURCES:
+            shutil.copytree(paths.rustc_path(stdlib), paths.stdlib_srcs(stdlib))
+
     # Fixup
     # The Rust build doesn't have an option to auto-strip binaries, so we do
     # it here.
@@ -102,6 +127,14 @@
         paths.out_path('bin', 'cargo'),
         paths.out_path('bin', 'rustdoc')])
 
+    # Some stdlib crates might include Android.mk or Android.bp files.
+    # If they do, filter them out.
+    if build_platform.system() == 'linux':
+        for root, _, files in os.walk(paths.stdlib_srcs()):
+            for f in files:
+                if f in ('Android.mk', 'Android.bp'):
+                    os.remove(os.path.join(root, f))
+
     # Dist
     tarball_path = os.path.join(dist_dir, 'rust-{0}.tar.gz'.format(build_name))
     subprocess.check_call(['tar', 'czf', tarball_path, '.'],
diff --git a/paths.py b/paths.py
index b44f30d..385d324 100644
--- a/paths.py
+++ b/paths.py
@@ -46,6 +46,9 @@
     """Generates a path relative to the output directory of the build."""
     return workspace_path('out', *args)
 
+def stdlib_srcs(*args):
+    """Generates a path relative to the directory to install stdlib sources."""
+    return out_path('src', 'stdlibs', *args)
 
 def rust_prebuilt(*args):
     """Generates a path relative to the rust prebuilt directory."""