blob: ec4bf92a2a7f33048b4f0d4a9cdc36589d4ae39f [file] [log] [blame]
Andreas Gampebec63582015-11-20 19:26:51 -08001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef ART_RUNTIME_GC_SPACE_IMAGE_SPACE_FS_H_
18#define ART_RUNTIME_GC_SPACE_IMAGE_SPACE_FS_H_
19
20#include <dirent.h>
21#include <dlfcn.h>
22
23#include "base/logging.h"
24#include "base/macros.h"
25#include "base/stringprintf.h"
26#include "base/unix_file/fd_file.h"
27#include "globals.h"
28#include "os.h"
29#include "utils.h"
30
31namespace art {
32namespace gc {
33namespace space {
34
35// This file contains helper code for ImageSpace. It has most of the file-system
36// related code, including handling A/B OTA.
37
38namespace impl {
39
40// Delete the directory and its (regular or link) contents. If the recurse flag is true, delete
41// sub-directories recursively.
42static void DeleteDirectoryContents(const std::string& dir, bool recurse) {
43 if (!OS::DirectoryExists(dir.c_str())) {
44 return;
45 }
46 DIR* c_dir = opendir(dir.c_str());
47 if (c_dir == nullptr) {
48 PLOG(WARNING) << "Unable to open " << dir << " to delete it's contents";
49 return;
50 }
51
52 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
53 const char* name = de->d_name;
54 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
55 continue;
56 }
57 // We only want to delete regular files and symbolic links.
58 std::string file = StringPrintf("%s/%s", dir.c_str(), name);
59 if (de->d_type != DT_REG && de->d_type != DT_LNK) {
60 if (de->d_type == DT_DIR) {
61 if (recurse) {
62 DeleteDirectoryContents(file, recurse);
63 // Try to rmdir the directory.
64 if (TEMP_FAILURE_RETRY(rmdir(file.c_str())) != 0) {
65 PLOG(ERROR) << "Unable to rmdir " << file;
66 }
67 }
68 } else {
69 LOG(WARNING) << "Unexpected file type of " << std::hex << de->d_type << " encountered.";
70 }
71 } else {
72 // Try to unlink the file.
73 if (TEMP_FAILURE_RETRY(unlink(file.c_str())) != 0) {
74 PLOG(ERROR) << "Unable to unlink " << file;
75 }
76 }
77 }
78 CHECK_EQ(0, TEMP_FAILURE_RETRY(closedir(c_dir))) << "Unable to close directory.";
79}
80
81static bool HasContent(const char* dir) {
82 if (!OS::DirectoryExists(dir)) {
83 return false;
84 }
85 DIR* c_dir = opendir(dir);
86 if (c_dir == nullptr) {
87 PLOG(WARNING) << "Unable to open " << dir << " to delete it if empty";
88 return false;
89 }
90
91 for (struct dirent* de = readdir(c_dir); de != nullptr; de = readdir(c_dir)) {
92 const char* name = de->d_name;
93 if (strcmp(name, ".") == 0 || strcmp(name, "..") == 0) {
94 continue;
95 }
96 // Something here.
97 CHECK_EQ(0, TEMP_FAILURE_RETRY(closedir(c_dir))) << "Unable to close directory.";
98 return true;
99 }
100 CHECK_EQ(0, TEMP_FAILURE_RETRY(closedir(c_dir))) << "Unable to close directory.";
101 return false;
102}
103
104// Delete this directory, if empty. Then repeat with the parents. Skips non-existing directories.
105// If stop_at isn't null, the recursion will stop when a directory with the given name is found.
106static void DeleteEmptyDirectoriesUpTo(const std::string& dir, const char* stop_at) {
107 if (HasContent(dir.c_str())) {
108 return;
109 }
110 if (stop_at != nullptr) {
111 // This check isn't precise, but good enough in practice.
112 if (EndsWith(dir, stop_at)) {
113 return;
114 }
115 }
116 if (OS::DirectoryExists(dir.c_str())) {
117 if (TEMP_FAILURE_RETRY(rmdir(dir.c_str())) != 0) {
118 PLOG(ERROR) << "Unable to rmdir " << dir;
119 return;
120 }
121 }
122 size_t last_slash = dir.rfind('/');
123 if (last_slash != std::string::npos) {
124 DeleteEmptyDirectoriesUpTo(dir.substr(0, last_slash), stop_at);
125 }
126}
127
128static void MoveOTAArtifacts(const char* src, const char* trg) {
129 DCHECK(OS::DirectoryExists(src));
130 DCHECK(OS::DirectoryExists(trg));
131
132 if (HasContent(trg)) {
133 LOG(WARNING) << "We do not support merging caches, but the target isn't empty: " << src
134 << " to " << trg;
135 return;
136 }
137
138 if (TEMP_FAILURE_RETRY(rename(src, trg)) != 0) {
139 PLOG(ERROR) << "Could not rename OTA cache " << src << " to target " << trg;
140 }
141}
142
143// This is some dlopen/dlsym and hardcoded data to avoid a dependency on libselinux. Make sure
144// this stays in sync!
145static bool RelabelOTAFiles(const std::string& dalvik_cache_dir) {
146 // We only expect selinux on devices. Don't even attempt this on the host.
147 if (!kIsTargetBuild) {
148 return true;
149 }
150
151 // Custom deleter, so we can use std::unique_ptr.
152 struct HandleDeleter {
153 void operator()(void* in) {
154 if (in != nullptr && dlclose(in) != 0) {
155 PLOG(ERROR) << "Could not close selinux handle.";
156 }
157 }
158 };
159
160 // Look for selinux library.
161 std::unique_ptr<void, HandleDeleter> selinux_handle(dlopen("libselinux.so", RTLD_NOW));
162 if (selinux_handle == nullptr) {
163 // Assume everything's OK if we can't open the library.
164 return true;
165 }
166 dlerror(); // Clean dlerror string.
167
168 void* restorecon_ptr = dlsym(selinux_handle.get(), "selinux_android_restorecon");
169 if (restorecon_ptr == nullptr) {
170 // Can't find the relabel function. That's bad. Make sure the zygote fails, as we have no
171 // other recourse to make this error obvious.
172 const char* error_string = dlerror();
173 LOG(FATAL) << "Could not find selinux restorecon function: "
174 << ((error_string != nullptr) ? error_string : "(unknown error)");
175 UNREACHABLE();
176 }
177
178 using RestoreconFn = int (*)(const char*, unsigned int);
179 constexpr unsigned int kRecursive = 4U;
180
181 RestoreconFn restorecon_fn = reinterpret_cast<RestoreconFn>(restorecon_ptr);
182 if (restorecon_fn(dalvik_cache_dir.c_str(), kRecursive) != 0) {
183 LOG(ERROR) << "Failed to restorecon " << dalvik_cache_dir;
184 return false;
185 }
186
187 return true;
188}
189
190} // namespace impl
191
192
193// We are relocating or generating the core image. We should get rid of everything. It is all
194// out-of-date. We also don't really care if this fails since it is just a convenience.
195// Adapted from prune_dex_cache(const char* subdir) in frameworks/native/cmds/installd/commands.c
196// Note this should only be used during first boot.
197static void PruneDalvikCache(InstructionSet isa) {
198 CHECK_NE(isa, kNone);
199 // Prune the base /data/dalvik-cache.
200 impl::DeleteDirectoryContents(GetDalvikCacheOrDie(".", false), false);
201 // Prune /data/dalvik-cache/<isa>.
202 impl::DeleteDirectoryContents(GetDalvikCacheOrDie(GetInstructionSetString(isa), false), false);
203}
204
205// We write out an empty file to the zygote's ISA specific cache dir at the start of
206// every zygote boot and delete it when the boot completes. If we find a file already
207// present, it usually means the boot didn't complete. We wipe the entire dalvik
208// cache if that's the case.
209static void MarkZygoteStart(const InstructionSet isa, const uint32_t max_failed_boots) {
210 const std::string isa_subdir = GetDalvikCacheOrDie(GetInstructionSetString(isa), false);
211 const std::string boot_marker = isa_subdir + "/.booting";
212 const char* file_name = boot_marker.c_str();
213
214 uint32_t num_failed_boots = 0;
215 std::unique_ptr<File> file(OS::OpenFileReadWrite(file_name));
216 if (file.get() == nullptr) {
217 file.reset(OS::CreateEmptyFile(file_name));
218
219 if (file.get() == nullptr) {
220 PLOG(WARNING) << "Failed to create boot marker.";
221 return;
222 }
223 } else {
224 if (!file->ReadFully(&num_failed_boots, sizeof(num_failed_boots))) {
225 PLOG(WARNING) << "Failed to read boot marker.";
226 file->Erase();
227 return;
228 }
229 }
230
231 if (max_failed_boots != 0 && num_failed_boots > max_failed_boots) {
232 LOG(WARNING) << "Incomplete boot detected. Pruning dalvik cache";
233 impl::DeleteDirectoryContents(isa_subdir, false);
234 }
235
236 ++num_failed_boots;
237 VLOG(startup) << "Number of failed boots on : " << boot_marker << " = " << num_failed_boots;
238
239 if (lseek(file->Fd(), 0, SEEK_SET) == -1) {
240 PLOG(WARNING) << "Failed to write boot marker.";
241 file->Erase();
242 return;
243 }
244
245 if (!file->WriteFully(&num_failed_boots, sizeof(num_failed_boots))) {
246 PLOG(WARNING) << "Failed to write boot marker.";
247 file->Erase();
248 return;
249 }
250
251 if (file->FlushCloseOrErase() != 0) {
252 PLOG(WARNING) << "Failed to flush boot marker.";
253 }
254}
255
256static void TryMoveOTAArtifacts(const std::string& cache_filename, bool dalvik_cache_exists) {
257 // We really assume here global means /data/dalvik-cache, and we'll inject 'ota.' Make sure
258 // that's true.
259 CHECK(StartsWith(cache_filename, "/data/dalvik-cache")) << cache_filename;
260
261 // Inject ota subdirectory.
262 std::string ota_filename(cache_filename);
263 ota_filename = ota_filename.insert(strlen("/data/"), "ota/");
264 CHECK(StartsWith(ota_filename, "/data/ota/dalvik-cache")) << ota_filename;
265
266 // See if the file exists.
267 if (OS::FileExists(ota_filename.c_str())) {
268 VLOG(startup) << "OTA directory does exist, checking for artifacts";
269
270 size_t last_slash = ota_filename.rfind('/');
271 CHECK_NE(last_slash, std::string::npos);
272 std::string ota_source_dir = ota_filename.substr(0, last_slash);
273
274 // We need the dalvik cache now, really.
275 if (dalvik_cache_exists) {
276 size_t last_cache_slash = cache_filename.rfind('/');
277 DCHECK_NE(last_cache_slash, std::string::npos);
278 std::string dalvik_cache_target_dir = cache_filename.substr(0, last_cache_slash);
279
280 // First clean the target cache.
281 impl::DeleteDirectoryContents(dalvik_cache_target_dir.c_str(), false);
282
283 // Now move things over.
284 impl::MoveOTAArtifacts(ota_source_dir.c_str(), dalvik_cache_target_dir.c_str());
285
286 // Last step: ensure the files have the right selinux label.
287 if (!impl::RelabelOTAFiles(dalvik_cache_target_dir)) {
288 // This isn't good. We potentially moved files, but they have the wrong label. Delete the
289 // files.
290 LOG(WARNING) << "Could not relabel files, must delete dalvik-cache.";
291 impl::DeleteDirectoryContents(dalvik_cache_target_dir.c_str(), false);
292 }
293 }
294
295 // Cleanup.
296 impl::DeleteDirectoryContents(ota_source_dir.c_str(), true);
297 impl::DeleteEmptyDirectoriesUpTo(ota_source_dir, "ota");
298 } else {
299 VLOG(startup) << "No OTA directory.";
300 }
301}
302
303} // namespace space
304} // namespace gc
305} // namespace art
306
307#endif // ART_RUNTIME_GC_SPACE_IMAGE_SPACE_FS_H_