backuptool: Preserve the SELinux context of the files

Add a function that allows to copy files preserving their SELinux
context that is generic enough to work with both busybox and toybox.

Change-Id: If2c245863df5675c18dbf43b6bcedeb33383fc38
diff --git a/prebuilt/common/bin/backuptool.functions b/prebuilt/common/bin/backuptool.functions
index b3610e7..2bc821b 100644
--- a/prebuilt/common/bin/backuptool.functions
+++ b/prebuilt/common/bin/backuptool.functions
@@ -5,6 +5,16 @@
 
 DEBUG=0
 
+copy_file() {
+  cp -dp "$1" "$2"
+  # symlinks don't have a context
+  if [ ! -L "$1" ]; then
+    # it is assumed that every label starts with 'u:object_r' and has no white-spaces
+    local context=`ls -Z "$1" | grep -o 'u:object_r:[^ ]*' | head -1`
+    chcon "$context" "$2"
+  fi
+}
+
 backup_file() {
   if [ -e "$1" ]; then
     local F=`basename "$1"`
@@ -14,7 +24,7 @@
       echo "Skipping odexed apk $1"
     else
       mkdir -p "$C/$D"
-      cp -dp "$1" "$C/$D/$F"
+      copy_file "$1" "$C/$D/$F"
       if [ $DEBUG -eq 1 ]; then 
         echo backup_file "$1" "$C/$D/$F"
       fi
@@ -29,7 +39,7 @@
     if [ ! -d "$DIR" ]; then
       mkdir -p "$DIR"
     fi
-    cp -dp "$C/$DIR/$FILE" "$1"
+    copy_file "$C/$DIR/$FILE" "$1"
     if [ $DEBUG -eq 1 ]; then 
       echo restore_file "$C/$DIR/$FILE" "$1"
     fi