am 45734df7: Merge "Add new jd_lists_unified template for unified metadata. Expose page tags to JavaScript through metaTags var." into klp-docs

* commit '45734df779f3653c3b9f1ecdc0aa21ddc4c76cf0':
  Add new jd_lists_unified template for unified metadata. Expose page tags to JavaScript through metaTags var.
diff --git a/CleanSpec.mk b/CleanSpec.mk
index 877c690..c912497 100644
--- a/CleanSpec.mk
+++ b/CleanSpec.mk
@@ -205,6 +205,9 @@
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/app/*)
 $(call add-clean-step, rm -rf $(PRODUCT_OUT)/obj/APPS/*)
 
+# 4.4.1
+$(call add-clean-step, rm -rf $(PRODUCT_OUT)/system/build.prop)
+
 # ************************************************
 # NEWER CLEAN STEPS MUST BE AT THE END OF THE LIST
 # ************************************************
diff --git a/core/Makefile b/core/Makefile
index 298eef1..f118cea 100644
--- a/core/Makefile
+++ b/core/Makefile
@@ -1262,6 +1262,7 @@
 endif
 	$(hide) echo "mkbootimg_args=$(BOARD_MKBOOTIMG_ARGS)" >> $(zip_root)/META/misc_info.txt
 	$(hide) echo "use_set_metadata=1" >> $(zip_root)/META/misc_info.txt
+	$(hide) echo "update_rename_support=1" >> $(zip_root)/META/misc_info.txt
 	$(call generate-userimage-prop-dictionary, $(zip_root)/META/misc_info.txt)
 	@# Zip everything up, preserving symlinks
 	$(hide) (cd $(zip_root) && zip -qry ../$(notdir $@) .)
diff --git a/core/version_defaults.mk b/core/version_defaults.mk
index faa12d2..9ed75c9 100644
--- a/core/version_defaults.mk
+++ b/core/version_defaults.mk
@@ -41,7 +41,7 @@
   # which is the version that we reveal to the end user.
   # Update this value when the platform version changes (rather
   # than overriding it somewhere else).  Can be an arbitrary string.
-  PLATFORM_VERSION := 4.4
+  PLATFORM_VERSION := 4.4.1
 endif
 
 ifeq "" "$(PLATFORM_SDK_VERSION)"
diff --git a/target/product/core_minimal.mk b/target/product/core_minimal.mk
index fc2fc80..159e7b2 100644
--- a/target/product/core_minimal.mk
+++ b/target/product/core_minimal.mk
@@ -33,6 +33,8 @@
     bu \
     com.android.location.provider \
     com.android.location.provider.xml \
+    com.android.media.remotedisplay \
+    com.android.media.remotedisplay.xml \
     drmserver \
     framework-res \
     installd \
diff --git a/tools/releasetools/check_target_files_signatures b/tools/releasetools/check_target_files_signatures
index ae372ba..45d30a6 100755
--- a/tools/releasetools/check_target_files_signatures
+++ b/tools/releasetools/check_target_files_signatures
@@ -135,7 +135,7 @@
 
     for i in to_load:
       f = open(i)
-      cert = ParseCertificate(f.read())
+      cert = common.ParseCertificate(f.read())
       f.close()
       name, _ = os.path.splitext(i)
       name, _ = os.path.splitext(name)
@@ -144,21 +144,6 @@
 ALL_CERTS = CertDB()
 
 
-def ParseCertificate(data):
-  """Parse a PEM-format certificate."""
-  cert = []
-  save = False
-  for line in data.split("\n"):
-    if "--END CERTIFICATE--" in line:
-      break
-    if save:
-      cert.append(line)
-    if "--BEGIN CERTIFICATE--" in line:
-      save = True
-  cert = "".join(cert).decode('base64')
-  return cert
-
-
 def CertFromPKCS7(data, filename):
   """Read the cert out of a PKCS#7-format file (which is what is
   stored in a signed .apk)."""
@@ -175,7 +160,7 @@
       AddProblem("error reading cert:\n" + err)
       return None
 
-    cert = ParseCertificate(out)
+    cert = common.ParseCertificate(out)
     if not cert:
       AddProblem("error parsing cert output")
       return None
diff --git a/tools/releasetools/common.py b/tools/releasetools/common.py
index 58582ba..a3217dd 100644
--- a/tools/releasetools/common.py
+++ b/tools/releasetools/common.py
@@ -954,3 +954,18 @@
     return PARTITION_TYPES[fstab[mount_point].fs_type], fstab[mount_point].device
   else:
     return None
+
+
+def ParseCertificate(data):
+  """Parse a PEM-format certificate."""
+  cert = []
+  save = False
+  for line in data.split("\n"):
+    if "--END CERTIFICATE--" in line:
+      break
+    if save:
+      cert.append(line)
+    if "--BEGIN CERTIFICATE--" in line:
+      save = True
+  cert = "".join(cert).decode('base64')
+  return cert
diff --git a/tools/releasetools/edify_generator.py b/tools/releasetools/edify_generator.py
index 2c3b9e7..189672c 100644
--- a/tools/releasetools/edify_generator.py
+++ b/tools/releasetools/edify_generator.py
@@ -184,6 +184,11 @@
     cmd = "delete(" + ",\0".join(['"%s"' % (i,) for i in file_list]) + ");"
     self.script.append(self._WordWrap(cmd))
 
+  def RenameFile(self, srcfile, tgtfile):
+    """Moves a file from one location to another."""
+    if self.info.get("update_rename_support", False):
+      self.script.append('rename("%s", "%s");' % (srcfile, tgtfile))
+
   def ApplyPatch(self, srcfile, tgtfile, tgtsize, tgtsha1, *patchpairs):
     """Apply binary patches (in *patchpairs) to the given srcfile to
     produce tgtfile (which may be "-" to indicate overwriting the
diff --git a/tools/releasetools/ota_from_target_files b/tools/releasetools/ota_from_target_files
index a6b9b69..2ef896f 100755
--- a/tools/releasetools/ota_from_target_files
+++ b/tools/releasetools/ota_from_target_files
@@ -108,6 +108,31 @@
   symlink."""
   return (info.external_attr >> 28) == 010
 
+def ClosestFileMatch(src, tgtfiles, existing):
+  """Returns the closest file match between a source file and list
+     of potential matches.  The exact filename match is preferred,
+     then the sha1 is searched for, and finally a file with the same
+     basename is evaluated.  Rename support in the updater-binary is
+     required for the latter checks to be used."""
+
+  result = tgtfiles.get("path:" + src.name)
+  if result is not None:
+    return result
+
+  if not OPTIONS.target_info_dict.get("update_rename_support", False):
+    return None
+
+  if src.size < 1000:
+    return None
+
+  result = tgtfiles.get("sha1:" + src.sha1)
+  if result is not None and existing.get(result.name) is None:
+    return result
+  result = tgtfiles.get("file:" + src.name.split("/")[-1])
+  if result is not None and existing.get(result.name) is None:
+    return result
+  return None
+
 class Item:
   """Items represent the metadata (user, group, mode) of files and
   directories in the system image."""
@@ -514,11 +539,27 @@
   verbatim_targets = []
   patch_list = []
   diffs = []
+  renames = {}
   largest_source_size = 0
+
+  matching_file_cache = {}
+  for fn in source_data.keys():
+    sf = source_data[fn]
+    assert fn == sf.name
+    matching_file_cache["path:" + fn] = sf
+    # Only allow eligability for filename/sha matching
+    # if there isn't a perfect path match.
+    if target_data.get(sf.name) is None:
+      matching_file_cache["file:" + fn.split("/")[-1]] = sf
+      matching_file_cache["sha:" + sf.sha1] = sf
+
   for fn in sorted(target_data.keys()):
     tf = target_data[fn]
     assert fn == tf.name
-    sf = source_data.get(fn, None)
+    sf = ClosestFileMatch(tf, matching_file_cache, renames)
+    if sf is not None and sf.name != tf.name:
+      print "File has moved from " + sf.name + " to " + tf.name
+      renames[sf.name] = tf
 
     if sf is None or fn in OPTIONS.require_verbatim:
       # This file should be included verbatim
@@ -531,7 +572,7 @@
       # File is different; consider sending as a patch
       diffs.append(common.Difference(tf, sf))
     else:
-      # Target file identical to source.
+      # Target file data identical to source (may still be renamed)
       pass
 
   common.ComputeDifferences(diffs)
@@ -543,8 +584,8 @@
       tf.AddToZip(output_zip)
       verbatim_targets.append((tf.name, tf.size))
     else:
-      common.ZipWriteStr(output_zip, "patch/" + tf.name + ".p", d)
-      patch_list.append((tf.name, tf, sf, tf.size, common.sha1(d).hexdigest()))
+      common.ZipWriteStr(output_zip, "patch/" + sf.name + ".p", d)
+      patch_list.append((sf.name, tf, sf, tf.size, common.sha1(d).hexdigest()))
       largest_source_size = max(largest_source_size, sf.size)
 
   source_fp = GetBuildProp("ro.build.fingerprint", OPTIONS.source_info_dict)
@@ -626,7 +667,8 @@
   script.Print("Removing unneeded files...")
   script.DeleteFiles(["/"+i[0] for i in verbatim_targets] +
                      ["/"+i for i in sorted(source_data)
-                            if i not in target_data] +
+                            if i not in target_data and
+                            i not in renames] +
                      ["/system/recovery.img"])
 
   script.ShowProgress(0.8, 0)
@@ -713,6 +755,13 @@
     script.Print("Unpacking new recovery...")
     script.UnpackPackageDir("recovery", "/system")
 
+  if len(renames) > 0:
+    script.Print("Renaming files...")
+
+  for src in renames:
+    print "Renaming " + src + " to " + renames[src].name
+    script.RenameFile(src, renames[src].name)
+
   script.Print("Symlinks and permissions...")
 
   # Create all the symlinks that don't already exist, or point to
diff --git a/tools/releasetools/sign_target_files_apks b/tools/releasetools/sign_target_files_apks
index 5556573..00693b8 100755
--- a/tools/releasetools/sign_target_files_apks
+++ b/tools/releasetools/sign_target_files_apks
@@ -71,8 +71,10 @@
   print >> sys.stderr, "Python 2.4 or newer is required."
   sys.exit(1)
 
+import base64
 import cStringIO
 import copy
+import errno
 import os
 import re
 import subprocess
@@ -161,11 +163,45 @@
       print "rewriting %s:" % (info.filename,)
       new_data = RewriteProps(data)
       output_tf_zip.writestr(out_info, new_data)
+    elif info.filename.endswith("mac_permissions.xml"):
+      print "rewriting %s with new keys." % (info.filename,)
+      new_data = ReplaceCerts(data)
+      output_tf_zip.writestr(out_info, new_data)
     else:
       # a non-APK file; copy it verbatim
       output_tf_zip.writestr(out_info, data)
 
 
+def ReplaceCerts(data):
+  """Given a string of data, replace all occurences of a set
+  of X509 certs with a newer set of X509 certs and return
+  the updated data string."""
+  for old, new in OPTIONS.key_map.iteritems():
+    try:
+      if OPTIONS.verbose:
+        print "    Replacing %s.x509.pem with %s.x509.pem" % (old, new)
+      f = open(old + ".x509.pem")
+      old_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
+      f.close()
+      f = open(new + ".x509.pem")
+      new_cert16 = base64.b16encode(common.ParseCertificate(f.read())).lower()
+      f.close()
+      # Only match entire certs.
+      pattern = "\\b"+old_cert16+"\\b"
+      (data, num) = re.subn(pattern, new_cert16, data, flags=re.IGNORECASE)
+      if OPTIONS.verbose:
+        print "    Replaced %d occurence(s) of %s.x509.pem with " \
+            "%s.x509.pem" % (num, old, new)
+    except IOError, e:
+      if (e.errno == errno.ENOENT and not OPTIONS.verbose):
+        continue
+
+      print "    Error accessing %s. %s. Skip replacing %s.x509.pem " \
+          "with %s.x509.pem." % (e.filename, e.strerror, old, new)
+
+  return data
+
+
 def EditTags(tags):
   """Given a string containing comma-separated tags, apply the edits
   specified in OPTIONS.tag_changes and return the updated string."""