Pack file_contexts into target_files zip.

file_contexts (specified by SELINUX_FC) is needed both when building
and (re)packaging. We used to use the copy in out/ when building, and
looked for the copy in BOOT/RAMDISK/ when packaging from target_files
zip. With system_root_image enabled, the file_contexts needed for
building and packaging might be different from the one on device. So
we explicitly pack the file as META/file_contexts in target_files zip.

Also refactor out the overriding of selinux_fc property into
common.LoadInfoDict().

Change-Id: I94f9ea6671b3792c12c1c21573840743d63da39a
(cherry picked from commit aa7318c3849095aeb3bea00efbf303c0c40a089d)
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 701bb7c..87099c2 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -94,7 +94,7 @@
       pass
 
 
-def LoadInfoDict(input_file):
+def LoadInfoDict(input_file, input_dir=None):
   """Read and parse the META/misc_info.txt key/value pairs from the
   input target files and return a dict."""
 
@@ -145,6 +145,23 @@
   if "fstab_version" not in d:
     d["fstab_version"] = "1"
 
+  # During building, we use the "file_contexts" in the out/ directory tree.
+  # It is no longer available when (re)generating from target_files zip. So
+  # when generating from target_files zip, we look for a copy under META/
+  # first, if not available search under BOOT/RAMDISK/. Note that we may need
+  # a different file_contexts to build images than the one running on device,
+  # such as when enabling system_root_image. In that case, we must have the
+  # one for building copied to META/.
+  if input_dir is not None:
+    fc_config = os.path.join(input_dir, "META", "file_contexts")
+    if not os.path.exists(fc_config):
+      fc_config = os.path.join(input_dir, "BOOT", "RAMDISK", "file_contexts")
+      if not os.path.exists(fc_config):
+        fc_config = None
+
+    if fc_config:
+      d["selinux_fc"] = fc_config
+
   try:
     data = read_helper("META/imagesizes.txt")
     for line in data.split("\n"):