Restorecon in two phases when creating files and dirs for artifacts.

Suggested by alanstokes@ in aosp/2388476. The reason for each phase is
stated in the comments.

Bug: 262230400
Test: -
  1. Remove the "oat" directory of an app.
  2. Dexopt the app using ART Service.
  3. See no SELinux denials.
Ignore-AOSP-First: ART Services.
Change-Id: Id2b894cecbbf4ad7658339387c6e067b20536eaa
diff --git a/artd/artd.cc b/artd/artd.cc
index b6304d2..e053504 100644
--- a/artd/artd.cc
+++ b/artd/artd.cc
@@ -788,6 +788,13 @@
   std::string oat_dir_path;  // For restorecon, can be empty if the artifacts are in dalvik-cache.
   OR_RETURN_NON_FATAL(PrepareArtifactsDirs(in_outputArtifacts, &oat_dir_path));
 
+  // First-round restorecon. artd doesn't have the permission to create files with the
+  // `apk_data_file` label, so we need to restorecon the "oat" directory first so that files will
+  // inherit `dalvikcache_data_file` rather than `apk_data_file`.
+  if (!in_outputArtifacts.artifactsPath.isInDalvikCache) {
+    OR_RETURN_NON_FATAL(Restorecon(oat_dir_path, in_outputArtifacts.permissionSettings.seContext));
+  }
+
   FdLogger fd_logger;
 
   CmdlineBuilder art_exec_args;
@@ -904,12 +911,12 @@
     // TODO(b/260228411): Check uid and gid.
   }
 
-  // Restorecon recursively after the output files are created, so that the SELinux context is
-  // applied to all of them. The SELinux context of a file is mostly inherited from the parent
-  // directory upon creation, but the MLS label is not inherited, so we need to restorecon every
-  // file so that they have the right MLS label. If the files are in dalvik-cache, there's no need
-  // to restorecon because they inherits the SELinux context of the dalvik-cache directory and they
-  // don't need to have MLS labels.
+  // Second-round restorecon. Restorecon recursively after the output files are created, so that the
+  // SELinux context is applied to all of them. The SELinux context of a file is mostly inherited
+  // from the parent directory upon creation, but the MLS label is not inherited, so we need to
+  // restorecon every file so that they have the right MLS label. If the files are in dalvik-cache,
+  // there's no need to restorecon because they inherits the SELinux context of the dalvik-cache
+  // directory and they don't need to have MLS labels.
   if (!in_outputArtifacts.artifactsPath.isInDalvikCache) {
     OR_RETURN_NON_FATAL(Restorecon(oat_dir_path, in_outputArtifacts.permissionSettings.seContext));
   }