1 /*
2 * Copyright (C) 2014 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 #include <ctype.h>
18 #include <dirent.h>
19 #include <errno.h>
20 #include <fnmatch.h>
21 #include <stdio.h>
22 #include <stdlib.h>
23 #include <string.h>
24 #include <sys/mount.h>
25 #include <unistd.h>
26
27 #include <algorithm>
28 #include <array>
29 #include <utility>
30 #include <vector>
31
32 #include <android-base/file.h>
33 #include <android-base/parseint.h>
34 #include <android-base/properties.h>
35 #include <android-base/stringprintf.h>
36 #include <android-base/strings.h>
37 #include <libgsi/libgsi.h>
38
39 #include "fstab_priv.h"
40 #include "logging_macros.h"
41
42 using android::base::EndsWith;
43 using android::base::ParseByteCount;
44 using android::base::ParseInt;
45 using android::base::ReadFileToString;
46 using android::base::Readlink;
47 using android::base::Split;
48 using android::base::StartsWith;
49
50 namespace android {
51 namespace fs_mgr {
52 namespace {
53
54 constexpr char kProcMountsPath[] = "/proc/mounts";
55
56 struct FlagList {
57 const char* name;
58 uint64_t flag;
59 };
60
61 FlagList kMountFlagsList[] = {
62 {"noatime", MS_NOATIME},
63 {"noexec", MS_NOEXEC},
64 {"nosuid", MS_NOSUID},
65 {"nodev", MS_NODEV},
66 {"nodiratime", MS_NODIRATIME},
67 {"ro", MS_RDONLY},
68 {"rw", 0},
69 {"sync", MS_SYNCHRONOUS},
70 {"remount", MS_REMOUNT},
71 {"bind", MS_BIND},
72 {"rec", MS_REC},
73 {"unbindable", MS_UNBINDABLE},
74 {"private", MS_PRIVATE},
75 {"slave", MS_SLAVE},
76 {"shared", MS_SHARED},
77 {"defaults", 0},
78 };
79
CalculateZramSize(int percentage)80 off64_t CalculateZramSize(int percentage) {
81 off64_t total;
82
83 total = sysconf(_SC_PHYS_PAGES);
84 total *= percentage;
85 total /= 100;
86
87 total *= sysconf(_SC_PAGESIZE);
88
89 return total;
90 }
91
92 // Fills 'dt_value' with the underlying device tree value string without the trailing '\0'.
93 // Returns true if 'dt_value' has a valid string, 'false' otherwise.
ReadDtFile(const std::string & file_name,std::string * dt_value)94 bool ReadDtFile(const std::string& file_name, std::string* dt_value) {
95 if (android::base::ReadFileToString(file_name, dt_value)) {
96 if (!dt_value->empty()) {
97 // Trim the trailing '\0' out, otherwise the comparison will produce false-negatives.
98 dt_value->resize(dt_value->size() - 1);
99 return true;
100 }
101 }
102
103 return false;
104 }
105
ParseFileEncryption(const std::string & arg,FstabEntry * entry)106 void ParseFileEncryption(const std::string& arg, FstabEntry* entry) {
107 entry->fs_mgr_flags.file_encryption = true;
108 entry->encryption_options = arg;
109 }
110
SetMountFlag(const std::string & flag,FstabEntry * entry)111 bool SetMountFlag(const std::string& flag, FstabEntry* entry) {
112 for (const auto& [name, value] : kMountFlagsList) {
113 if (flag == name) {
114 entry->flags |= value;
115 return true;
116 }
117 }
118 return false;
119 }
120
ParseMountFlags(const std::string & flags,FstabEntry * entry)121 void ParseMountFlags(const std::string& flags, FstabEntry* entry) {
122 std::string fs_options;
123 for (const auto& flag : Split(flags, ",")) {
124 if (!SetMountFlag(flag, entry)) {
125 // Unknown flag, so it must be a filesystem specific option.
126 if (!fs_options.empty()) {
127 fs_options.append(","); // appends a comma if not the first
128 }
129 fs_options.append(flag);
130
131 if (auto equal_sign = flag.find('='); equal_sign != std::string::npos) {
132 const auto arg = flag.substr(equal_sign + 1);
133 if (entry->fs_type == "f2fs" && StartsWith(flag, "reserve_root=")) {
134 off64_t size_in_4k_blocks;
135 if (!ParseInt(arg, &size_in_4k_blocks, static_cast<off64_t>(0),
136 std::numeric_limits<off64_t>::max() >> 12)) {
137 LWARNING << "Warning: reserve_root= flag malformed: " << arg;
138 } else {
139 entry->reserved_size = size_in_4k_blocks << 12;
140 }
141 } else if (StartsWith(flag, "lowerdir=")) {
142 entry->lowerdir = arg;
143 }
144 }
145 }
146 }
147 entry->fs_options = std::move(fs_options);
148 }
149
ParseUserDevices(const std::string & arg,FstabEntry * entry)150 void ParseUserDevices(const std::string& arg, FstabEntry* entry) {
151 auto param = Split(arg, ":");
152 if (param.size() != 2) {
153 LWARNING << "Warning: device= malformed: " << arg;
154 return;
155 }
156
157 if (access(param[1].c_str(), F_OK) != 0) {
158 LWARNING << "Warning: device does not exist : " << param[1];
159 return;
160 }
161
162 if (param[0] == "zoned") {
163 // atgc in f2fs does not support a zoned device
164 auto options = Split(entry->fs_options, ",");
165 options.erase(std::remove(options.begin(), options.end(), "atgc"), options.end());
166 entry->fs_options = android::base::Join(options, ",");
167 LINFO << "Removed ATGC in fs_options as " << entry->fs_options << " for zoned device";
168 entry->fs_mgr_flags.is_zoned = true;
169 }
170 entry->user_devices.push_back(param[1]);
171 }
172
ParseFsMgrFlags(const std::string & flags,FstabEntry * entry)173 bool ParseFsMgrFlags(const std::string& flags, FstabEntry* entry) {
174 for (const auto& flag : Split(flags, ",")) {
175 if (flag.empty() || flag == "defaults") continue;
176 std::string arg;
177 if (auto equal_sign = flag.find('='); equal_sign != std::string::npos) {
178 arg = flag.substr(equal_sign + 1);
179 }
180
181 // First handle flags that simply set a boolean.
182 #define CheckFlag(flag_name, value) \
183 if (flag == flag_name) { \
184 entry->fs_mgr_flags.value = true; \
185 continue; \
186 }
187
188 CheckFlag("wait", wait);
189 CheckFlag("check", check);
190 CheckFlag("nonremovable", nonremovable);
191 CheckFlag("recoveryonly", recovery_only);
192 CheckFlag("noemulatedsd", no_emulated_sd);
193 CheckFlag("notrim", no_trim);
194 CheckFlag("formattable", formattable);
195 CheckFlag("slotselect", slot_select);
196 CheckFlag("latemount", late_mount);
197 CheckFlag("nofail", no_fail);
198 CheckFlag("quota", quota);
199 CheckFlag("avb", avb);
200 CheckFlag("logical", logical);
201 CheckFlag("checkpoint=block", checkpoint_blk);
202 CheckFlag("checkpoint=fs", checkpoint_fs);
203 CheckFlag("first_stage_mount", first_stage_mount);
204 CheckFlag("slotselect_other", slot_select_other);
205 CheckFlag("fsverity", fs_verity);
206 CheckFlag("metadata_csum", ext_meta_csum);
207 CheckFlag("fscompress", fs_compress);
208 CheckFlag("overlayfs_remove_missing_lowerdir", overlayfs_remove_missing_lowerdir);
209
210 #undef CheckFlag
211
212 // Then handle flags that take an argument.
213 if (StartsWith(flag, "encryptable=")) {
214 // The "encryptable" flag identifies adoptable storage volumes. The
215 // argument to this flag is ignored, but it should be "userdata".
216 //
217 // Historical note: this flag was originally meant just for /data,
218 // to indicate that FDE (full disk encryption) can be enabled.
219 // Unfortunately, it was also overloaded to identify adoptable
220 // storage volumes. Today, FDE is no longer supported, leaving only
221 // the adoptable storage volume meaning for this flag.
222 entry->fs_mgr_flags.crypt = true;
223 } else if (StartsWith(flag, "forceencrypt=") || StartsWith(flag, "forcefdeorfbe=")) {
224 LERROR << "flag no longer supported: " << flag;
225 return false;
226 } else if (StartsWith(flag, "voldmanaged=")) {
227 // The voldmanaged flag is followed by an = and the label, a colon and the partition
228 // number or the word "auto", e.g. voldmanaged=sdcard:3
229 entry->fs_mgr_flags.vold_managed = true;
230 auto parts = Split(arg, ":");
231 if (parts.size() != 2) {
232 LWARNING << "Warning: voldmanaged= flag malformed: " << arg;
233 continue;
234 }
235
236 entry->label = std::move(parts[0]);
237 if (parts[1] == "auto") {
238 entry->partnum = -1;
239 } else {
240 if (!ParseInt(parts[1], &entry->partnum)) {
241 entry->partnum = -1;
242 LWARNING << "Warning: voldmanaged= flag malformed: " << arg;
243 continue;
244 }
245 }
246 } else if (StartsWith(flag, "length=")) {
247 // The length flag is followed by an = and the size of the partition.
248 if (!ParseInt(arg, &entry->length)) {
249 LWARNING << "Warning: length= flag malformed: " << arg;
250 }
251 } else if (StartsWith(flag, "swapprio=")) {
252 if (!ParseInt(arg, &entry->swap_prio)) {
253 LWARNING << "Warning: swapprio= flag malformed: " << arg;
254 }
255 } else if (StartsWith(flag, "zramsize=")) {
256 if (!arg.empty() && arg.back() == '%') {
257 arg.pop_back();
258 int val;
259 if (ParseInt(arg, &val, 0, 100)) {
260 entry->zram_size = CalculateZramSize(val);
261 } else {
262 LWARNING << "Warning: zramsize= flag malformed: " << arg;
263 }
264 } else {
265 if (!ParseInt(arg, &entry->zram_size)) {
266 LWARNING << "Warning: zramsize= flag malformed: " << arg;
267 }
268 }
269 } else if (StartsWith(flag, "fileencryption=") || flag == "fileencryption") {
270 // "fileencryption" enables file-based encryption. It's normally followed by an = and
271 // then the encryption options. But that can be omitted to use the default options.
272 ParseFileEncryption(arg, entry);
273 } else if (StartsWith(flag, "max_comp_streams=")) {
274 if (!ParseInt(arg, &entry->max_comp_streams)) {
275 LWARNING << "Warning: max_comp_streams= flag malformed: " << arg;
276 }
277 } else if (StartsWith(flag, "reservedsize=")) {
278 // The reserved flag is followed by an = and the reserved size of the partition.
279 uint64_t size;
280 if (!ParseByteCount(arg, &size)) {
281 LWARNING << "Warning: reservedsize= flag malformed: " << arg;
282 } else {
283 entry->reserved_size = static_cast<off64_t>(size);
284 }
285 } else if (StartsWith(flag, "readahead_size_kb=")) {
286 int val;
287 if (ParseInt(arg, &val, 0, 16 * 1024)) {
288 entry->readahead_size_kb = val;
289 } else {
290 LWARNING << "Warning: readahead_size_kb= flag malformed (0 ~ 16MB): " << arg;
291 }
292 } else if (StartsWith(flag, "eraseblk=")) {
293 // The erase block size flag is followed by an = and the flash erase block size. Get it,
294 // check that it is a power of 2 and at least 4096, and return it.
295 off64_t val;
296 if (!ParseInt(arg, &val) || val < 4096 || (val & (val - 1)) != 0) {
297 LWARNING << "Warning: eraseblk= flag malformed: " << arg;
298 } else {
299 entry->erase_blk_size = val;
300 }
301 } else if (StartsWith(flag, "logicalblk=")) {
302 // The logical block size flag is followed by an = and the flash logical block size. Get
303 // it, check that it is a power of 2 and at least 4096, and return it.
304 off64_t val;
305 if (!ParseInt(arg, &val) || val < 4096 || (val & (val - 1)) != 0) {
306 LWARNING << "Warning: logicalblk= flag malformed: " << arg;
307 } else {
308 entry->logical_blk_size = val;
309 }
310 } else if (StartsWith(flag, "avb_keys=")) { // must before the following "avb"
311 entry->avb_keys = arg;
312 } else if (StartsWith(flag, "avb_hashtree_digest=")) {
313 // "avb_hashtree_digest" must before the following "avb"
314 // The path where hex-encoded hashtree descriptor root digest is located.
315 entry->avb_hashtree_digest = arg;
316 } else if (StartsWith(flag, "avb")) {
317 entry->fs_mgr_flags.avb = true;
318 entry->vbmeta_partition = arg;
319 } else if (StartsWith(flag, "keydirectory=")) {
320 // The keydirectory flag enables metadata encryption. It is
321 // followed by an = and the directory containing the metadata
322 // encryption key.
323 entry->metadata_key_dir = arg;
324 } else if (StartsWith(flag, "metadata_encryption=")) {
325 // The metadata_encryption flag specifies the cipher and flags to
326 // use for metadata encryption, if the defaults aren't sufficient.
327 // It doesn't actually enable metadata encryption; that is done by
328 // "keydirectory".
329 entry->metadata_encryption_options = arg;
330 } else if (StartsWith(flag, "sysfs_path=")) {
331 // The path to trigger device gc by idle-maint of vold.
332 entry->sysfs_path = arg;
333 } else if (StartsWith(flag, "zram_backingdev_size=")) {
334 if (!ParseByteCount(arg, &entry->zram_backingdev_size)) {
335 LWARNING << "Warning: zram_backingdev_size= flag malformed: " << arg;
336 }
337 } else if (StartsWith(flag, "device=")) {
338 ParseUserDevices(arg, entry);
339 } else {
340 LWARNING << "Warning: unknown flag: " << flag;
341 }
342 }
343
344 // FDE is no longer supported, so reject "encryptable" when used without
345 // "vold_managed". For now skip this check when in recovery mode, since
346 // some recovery fstabs still contain the FDE options since they didn't do
347 // anything in recovery mode anyway (except possibly to cause the
348 // reservation of a crypto footer) and thus never got removed.
349 if (entry->fs_mgr_flags.crypt && !entry->fs_mgr_flags.vold_managed && !InRecovery()) {
350 LERROR << "FDE is no longer supported; 'encryptable' can only be used for adoptable "
351 "storage";
352 return false;
353 }
354 return true;
355 }
356
IsDtFstabCompatible()357 bool IsDtFstabCompatible() {
358 std::string dt_value;
359 std::string file_name = GetAndroidDtDir() + "fstab/compatible";
360
361 if (ReadDtFile(file_name, &dt_value) && dt_value == "android,fstab") {
362 // If there's no status property or its set to "ok" or "okay", then we use the DT fstab.
363 std::string status_value;
364 std::string status_file_name = GetAndroidDtDir() + "fstab/status";
365 return !ReadDtFile(status_file_name, &status_value) || status_value == "ok" ||
366 status_value == "okay";
367 }
368
369 return false;
370 }
371
ReadFstabFromDt()372 std::string ReadFstabFromDt() {
373 if (!is_dt_compatible() || !IsDtFstabCompatible()) {
374 return {};
375 }
376
377 std::string fstabdir_name = GetAndroidDtDir() + "fstab";
378 std::unique_ptr<DIR, int (*)(DIR*)> fstabdir(opendir(fstabdir_name.c_str()), closedir);
379 if (!fstabdir) return {};
380
381 dirent* dp;
382 // Each element in fstab_dt_entries is <mount point, the line format in fstab file>.
383 std::vector<std::pair<std::string, std::string>> fstab_dt_entries;
384 while ((dp = readdir(fstabdir.get())) != NULL) {
385 // skip over name, compatible and .
386 if (dp->d_type != DT_DIR || dp->d_name[0] == '.') continue;
387
388 // create <dev> <mnt_point> <type> <mnt_flags> <fsmgr_flags>\n
389 std::vector<std::string> fstab_entry;
390 std::string file_name;
391 std::string value;
392 // skip a partition entry if the status property is present and not set to ok
393 file_name = android::base::StringPrintf("%s/%s/status", fstabdir_name.c_str(), dp->d_name);
394 if (ReadDtFile(file_name, &value)) {
395 if (value != "okay" && value != "ok") {
396 LINFO << "dt_fstab: Skip disabled entry for partition " << dp->d_name;
397 continue;
398 }
399 }
400
401 file_name = android::base::StringPrintf("%s/%s/dev", fstabdir_name.c_str(), dp->d_name);
402 if (!ReadDtFile(file_name, &value)) {
403 LERROR << "dt_fstab: Failed to find device for partition " << dp->d_name;
404 return {};
405 }
406 fstab_entry.push_back(value);
407
408 std::string mount_point;
409 file_name =
410 android::base::StringPrintf("%s/%s/mnt_point", fstabdir_name.c_str(), dp->d_name);
411 if (ReadDtFile(file_name, &value)) {
412 LINFO << "dt_fstab: Using a specified mount point " << value << " for " << dp->d_name;
413 mount_point = value;
414 } else {
415 mount_point = android::base::StringPrintf("/%s", dp->d_name);
416 }
417 fstab_entry.push_back(mount_point);
418
419 file_name = android::base::StringPrintf("%s/%s/type", fstabdir_name.c_str(), dp->d_name);
420 if (!ReadDtFile(file_name, &value)) {
421 LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
422 return {};
423 }
424 fstab_entry.push_back(value);
425
426 file_name =
427 android::base::StringPrintf("%s/%s/mnt_flags", fstabdir_name.c_str(), dp->d_name);
428 if (!ReadDtFile(file_name, &value)) {
429 LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
430 return {};
431 }
432 fstab_entry.push_back(value);
433
434 file_name =
435 android::base::StringPrintf("%s/%s/fsmgr_flags", fstabdir_name.c_str(), dp->d_name);
436 if (!ReadDtFile(file_name, &value)) {
437 LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
438 return {};
439 }
440 fstab_entry.push_back(value);
441 // Adds a fstab_entry to fstab_dt_entries, to be sorted by mount_point later.
442 fstab_dt_entries.emplace_back(mount_point, android::base::Join(fstab_entry, " "));
443 }
444
445 // Sort fstab_dt entries, to ensure /vendor is mounted before /vendor/abc is attempted.
446 std::sort(fstab_dt_entries.begin(), fstab_dt_entries.end(),
447 [](const auto& a, const auto& b) { return a.first < b.first; });
448
449 std::string fstab_result;
450 for (const auto& [_, dt_entry] : fstab_dt_entries) {
451 fstab_result += dt_entry + "\n";
452 }
453 return fstab_result;
454 }
455
456 /* Extracts <device>s from the by-name symlinks specified in a fstab:
457 * /dev/block/<type>/<device>/by-name/<partition>
458 *
459 * <type> can be: platform, pci or vbd.
460 *
461 * For example, given the following entries in the input fstab:
462 * /dev/block/platform/soc/1da4000.ufshc/by-name/system
463 * /dev/block/pci/soc.0/f9824900.sdhci/by-name/vendor
464 * it returns a set { "soc/1da4000.ufshc", "soc.0/f9824900.sdhci" }.
465 */
ExtraBootDevices(const Fstab & fstab)466 std::set<std::string> ExtraBootDevices(const Fstab& fstab) {
467 std::set<std::string> boot_devices;
468
469 for (const auto& entry : fstab) {
470 std::string blk_device = entry.blk_device;
471 // Skips blk_device that doesn't conform to the format.
472 if (!android::base::StartsWith(blk_device, "/dev/block") ||
473 android::base::StartsWith(blk_device, "/dev/block/by-name") ||
474 android::base::StartsWith(blk_device, "/dev/block/bootdevice/by-name")) {
475 continue;
476 }
477 // Skips non-by_name blk_device.
478 // /dev/block/<type>/<device>/by-name/<partition>
479 // ^ slash_by_name
480 auto slash_by_name = blk_device.find("/by-name");
481 if (slash_by_name == std::string::npos) continue;
482 blk_device.erase(slash_by_name); // erases /by-name/<partition>
483
484 // Erases /dev/block/, now we have <type>/<device>
485 blk_device.erase(0, std::string("/dev/block/").size());
486
487 // <type>/<device>
488 // ^ first_slash
489 auto first_slash = blk_device.find('/');
490 if (first_slash == std::string::npos) continue;
491
492 auto boot_device = blk_device.substr(first_slash + 1);
493 if (!boot_device.empty()) boot_devices.insert(std::move(boot_device));
494 }
495
496 return boot_devices;
497 }
498
499 // Helper class that maps Fstab* -> FstabEntry; const Fstab* -> const FstabEntry.
500 template <typename FstabPtr>
501 struct FstabPtrEntry {
502 using is_const_fstab = std::is_const<std::remove_pointer_t<FstabPtr>>;
503 using type = std::conditional_t<is_const_fstab::value, const FstabEntry, FstabEntry>;
504 };
505
506 template <typename FstabPtr, typename FstabPtrEntryType = typename FstabPtrEntry<FstabPtr>::type,
507 typename Pred>
GetEntriesByPred(FstabPtr fstab,const Pred & pred)508 std::vector<FstabPtrEntryType*> GetEntriesByPred(FstabPtr fstab, const Pred& pred) {
509 if (fstab == nullptr) {
510 return {};
511 }
512 std::vector<FstabPtrEntryType*> entries;
513 for (FstabPtrEntryType& entry : *fstab) {
514 if (pred(entry)) {
515 entries.push_back(&entry);
516 }
517 }
518 return entries;
519 }
520
521 } // namespace
522
523 // Return the path to the fstab file. There may be multiple fstab files; the
524 // one that is returned will be the first that exists of fstab.<fstab_suffix>,
525 // fstab.<hardware>, and fstab.<hardware.platform>. The fstab is searched for
526 // in /odm/etc/ and /vendor/etc/, as well as in the locations where it may be in
527 // the first stage ramdisk during early boot. Previously, the first stage
528 // ramdisk's copy of the fstab had to be located in the root directory, but now
529 // the system/etc directory is supported too and is the preferred location.
GetFstabPath()530 std::string GetFstabPath() {
531 if (InRecovery()) {
532 return "/etc/recovery.fstab";
533 }
534 for (const char* prop : {"fstab_suffix", "hardware", "hardware.platform"}) {
535 std::string suffix;
536
537 if (!fs_mgr_get_boot_config(prop, &suffix)) continue;
538
539 for (const char* prefix : {// late-boot/post-boot locations
540 "/odm/etc/fstab.", "/vendor/etc/fstab.",
541 // early boot locations
542 "/system/etc/fstab.", "/first_stage_ramdisk/system/etc/fstab.",
543 "/fstab.", "/first_stage_ramdisk/fstab."}) {
544 std::string fstab_path = prefix + suffix;
545 if (access(fstab_path.c_str(), F_OK) == 0) {
546 return fstab_path;
547 }
548 }
549 }
550
551 return "";
552 }
553
ParseFstabFromString(const std::string & fstab_str,bool proc_mounts,Fstab * fstab_out)554 bool ParseFstabFromString(const std::string& fstab_str, bool proc_mounts, Fstab* fstab_out) {
555 const int expected_fields = proc_mounts ? 4 : 5;
556
557 Fstab fstab;
558
559 for (const auto& line : android::base::Split(fstab_str, "\n")) {
560 auto fields = android::base::Tokenize(line, " \t");
561
562 // Ignore empty lines and comments.
563 if (fields.empty() || android::base::StartsWith(fields.front(), '#')) {
564 continue;
565 }
566
567 if (fields.size() < expected_fields) {
568 LERROR << "Error parsing fstab: expected " << expected_fields << " fields, got "
569 << fields.size();
570 return false;
571 }
572
573 FstabEntry entry;
574 auto it = fields.begin();
575
576 entry.blk_device = std::move(*it++);
577 entry.mount_point = std::move(*it++);
578 entry.fs_type = std::move(*it++);
579 ParseMountFlags(std::move(*it++), &entry);
580
581 // For /proc/mounts, ignore everything after mnt_freq and mnt_passno
582 if (!proc_mounts && !ParseFsMgrFlags(std::move(*it++), &entry)) {
583 LERROR << "Error parsing fs_mgr_flags";
584 return false;
585 }
586
587 if (entry.fs_mgr_flags.logical) {
588 entry.logical_partition_name = entry.blk_device;
589 }
590
591 fstab.emplace_back(std::move(entry));
592 }
593
594 if (fstab.empty()) {
595 LERROR << "No entries found in fstab";
596 return false;
597 }
598
599 /* If an A/B partition, modify block device to be the real block device */
600 if (!fs_mgr_update_for_slotselect(&fstab)) {
601 LERROR << "Error updating for slotselect";
602 return false;
603 }
604
605 *fstab_out = std::move(fstab);
606 return true;
607 }
608
TransformFstabForDsu(Fstab * fstab,const std::string & dsu_slot,const std::vector<std::string> & dsu_partitions)609 void TransformFstabForDsu(Fstab* fstab, const std::string& dsu_slot,
610 const std::vector<std::string>& dsu_partitions) {
611 static constexpr char kDsuKeysDir[] = "/avb";
612 for (auto&& partition : dsu_partitions) {
613 if (!EndsWith(partition, gsi::kDsuPostfix)) {
614 continue;
615 }
616 // scratch is handled by fs_mgr_overlayfs
617 if (partition == android::gsi::kDsuScratch) {
618 continue;
619 }
620 // Convert userdata partition.
621 if (partition == android::gsi::kDsuUserdata) {
622 for (auto&& entry : GetEntriesForMountPoint(fstab, "/data")) {
623 entry->blk_device = android::gsi::kDsuUserdata;
624 entry->fs_mgr_flags.logical = true;
625 entry->fs_mgr_flags.formattable = true;
626 if (!entry->metadata_key_dir.empty()) {
627 entry->metadata_key_dir = android::gsi::GetDsuMetadataKeyDir(dsu_slot);
628 }
629 }
630 continue;
631 }
632 // Convert RO partitions.
633 //
634 // dsu_partition_name = corresponding_partition_name + kDsuPostfix
635 // e.g.
636 // system_gsi for system
637 // product_gsi for product
638 // vendor_gsi for vendor
639 std::string lp_name = partition.substr(0, partition.length() - strlen(gsi::kDsuPostfix));
640 std::string mount_point = "/" + lp_name;
641
642 // List of fs_type entries we're lacking, need to synthesis these later.
643 std::vector<std::string> lack_fs_list = {"ext4", "erofs"};
644
645 // Only support early mount (first_stage_mount) partitions.
646 auto pred = [&mount_point](const FstabEntry& entry) {
647 return entry.fs_mgr_flags.first_stage_mount && entry.mount_point == mount_point;
648 };
649
650 // Transform all matching entries and assume they are all adjacent for simplicity.
651 for (auto&& entry : GetEntriesByPred(fstab, pred)) {
652 // .blk_device is replaced with the DSU partition.
653 entry->blk_device = partition;
654 // .avb_keys hints first_stage_mount to load the chained-vbmeta image from partition
655 // footer. See aosp/932779 for more details.
656 entry->avb_keys = kDsuKeysDir;
657 // .logical_partition_name is required to look up AVB Hashtree descriptors.
658 entry->logical_partition_name = lp_name;
659 entry->fs_mgr_flags.logical = true;
660 entry->fs_mgr_flags.slot_select = false;
661 entry->fs_mgr_flags.slot_select_other = false;
662
663 if (auto it = std::find(lack_fs_list.begin(), lack_fs_list.end(), entry->fs_type);
664 it != lack_fs_list.end()) {
665 lack_fs_list.erase(it);
666 }
667 }
668
669 if (!lack_fs_list.empty()) {
670 // Insert at the end of the existing mountpoint group, or at the end of fstab.
671 // We assume there is at most one matching mountpoint group, which is the common case.
672 auto it = std::find_if_not(std::find_if(fstab->begin(), fstab->end(), pred),
673 fstab->end(), pred);
674 for (const auto& fs_type : lack_fs_list) {
675 it = std::next(fstab->insert(it, {.blk_device = partition,
676 .logical_partition_name = lp_name,
677 .mount_point = mount_point,
678 .fs_type = fs_type,
679 .flags = MS_RDONLY,
680 .avb_keys = kDsuKeysDir,
681 .fs_mgr_flags{
682 .wait = true,
683 .logical = true,
684 .first_stage_mount = true,
685 }}));
686 }
687 }
688 }
689 }
690
EnableMandatoryFlags(Fstab * fstab)691 void EnableMandatoryFlags(Fstab* fstab) {
692 // Devices launched in R and after must support fs_verity. Set flag to cause tune2fs
693 // to enable the feature on userdata and metadata partitions.
694 if (android::base::GetIntProperty("ro.product.first_api_level", 0) >= 30) {
695 // Devices launched in R and after should enable fs_verity on userdata.
696 // A better alternative would be to enable on mkfs at the beginning.
697 std::vector<FstabEntry*> data_entries = GetEntriesForMountPoint(fstab, "/data");
698 for (auto&& entry : data_entries) {
699 // Besides ext4, f2fs is also supported. But the image is already created with verity
700 // turned on when it was first introduced.
701 if (entry->fs_type == "ext4") {
702 entry->fs_mgr_flags.fs_verity = true;
703 }
704 }
705 // Devices shipping with S and earlier likely do not already have fs_verity enabled via
706 // mkfs, so enable it here.
707 std::vector<FstabEntry*> metadata_entries = GetEntriesForMountPoint(fstab, "/metadata");
708 for (auto&& entry : metadata_entries) {
709 entry->fs_mgr_flags.fs_verity = true;
710 }
711 }
712 }
713
ReadFstabFromFileCommon(const std::string & path,Fstab * fstab_out)714 static bool ReadFstabFromFileCommon(const std::string& path, Fstab* fstab_out) {
715 std::string fstab_str;
716 if (!android::base::ReadFileToString(path, &fstab_str, /* follow_symlinks = */ true)) {
717 PERROR << __FUNCTION__ << "(): failed to read file: '" << path << "'";
718 return false;
719 }
720
721 Fstab fstab;
722 if (!ParseFstabFromString(fstab_str, path == kProcMountsPath, &fstab)) {
723 LERROR << __FUNCTION__ << "(): failed to load fstab from : '" << path << "'";
724 return false;
725 }
726
727 EnableMandatoryFlags(&fstab);
728
729 *fstab_out = std::move(fstab);
730 return true;
731 }
732
ReadFstabFromFile(const std::string & path,Fstab * fstab)733 bool ReadFstabFromFile(const std::string& path, Fstab* fstab) {
734 if (!ReadFstabFromFileCommon(path, fstab)) {
735 return false;
736 }
737 if (path != kProcMountsPath && !InRecovery()) {
738 if (!access(android::gsi::kGsiBootedIndicatorFile, F_OK)) {
739 std::string dsu_slot;
740 if (!android::gsi::GetActiveDsu(&dsu_slot)) {
741 PERROR << __FUNCTION__ << "(): failed to get active DSU slot";
742 return false;
743 }
744 std::string lp_names;
745 if (!ReadFileToString(gsi::kGsiLpNamesFile, &lp_names)) {
746 PERROR << __FUNCTION__ << "(): failed to read DSU LP names";
747 return false;
748 }
749 TransformFstabForDsu(fstab, dsu_slot, Split(lp_names, ","));
750 } else if (errno != ENOENT) {
751 PERROR << __FUNCTION__ << "(): failed to access() DSU booted indicator";
752 return false;
753 }
754
755 SkipMountingPartitions(fstab, false /* verbose */);
756 }
757 return true;
758 }
759
ReadFstabFromProcMounts(Fstab * fstab)760 bool ReadFstabFromProcMounts(Fstab* fstab) {
761 // Don't call `ReadFstabFromFile` because the code for `path != kProcMountsPath` has an extra
762 // code size cost, even if it's never executed.
763 return ReadFstabFromFileCommon(kProcMountsPath, fstab);
764 }
765
766 // Returns fstab entries parsed from the device tree if they exist
ReadFstabFromDt(Fstab * fstab,bool verbose)767 bool ReadFstabFromDt(Fstab* fstab, bool verbose) {
768 std::string fstab_buf = ReadFstabFromDt();
769 if (fstab_buf.empty()) {
770 if (verbose) LINFO << __FUNCTION__ << "(): failed to read fstab from dt";
771 return false;
772 }
773
774 if (!ParseFstabFromString(fstab_buf, /* proc_mounts = */ false, fstab)) {
775 if (verbose) {
776 LERROR << __FUNCTION__ << "(): failed to load fstab from kernel:" << std::endl
777 << fstab_buf;
778 }
779 return false;
780 }
781
782 SkipMountingPartitions(fstab, verbose);
783
784 return true;
785 }
786
787 #ifdef NO_SKIP_MOUNT
788 static constexpr bool kNoSkipMount = true;
789 #else
790 static constexpr bool kNoSkipMount = false;
791 #endif
792
793 // For GSI to skip mounting /product and /system_ext, until there are well-defined interfaces
794 // between them and /system. Otherwise, the GSI flashed on /system might not be able to work with
795 // device-specific /product and /system_ext. skip_mount.cfg belongs to system_ext partition because
796 // only common files for all targets can be put into system partition. It is under
797 // /system/system_ext because GSI is a single system.img that includes the contents of system_ext
798 // partition and product partition under /system/system_ext and /system/product, respectively.
SkipMountingPartitions(Fstab * fstab,bool verbose)799 bool SkipMountingPartitions(Fstab* fstab, bool verbose) {
800 if (kNoSkipMount) {
801 return true;
802 }
803
804 static constexpr char kSkipMountConfig[] = "/system/system_ext/etc/init/config/skip_mount.cfg";
805
806 std::string skip_mount_config;
807 auto save_errno = errno;
808 if (!ReadFileToString(kSkipMountConfig, &skip_mount_config)) {
809 errno = save_errno; // missing file is expected
810 return true;
811 }
812 return SkipMountWithConfig(skip_mount_config, fstab, verbose);
813 }
814
SkipMountWithConfig(const std::string & skip_mount_config,Fstab * fstab,bool verbose)815 bool SkipMountWithConfig(const std::string& skip_mount_config, Fstab* fstab, bool verbose) {
816 std::vector<std::string> skip_mount_patterns;
817 for (const auto& line : Split(skip_mount_config, "\n")) {
818 if (line.empty() || StartsWith(line, "#")) {
819 continue;
820 }
821 skip_mount_patterns.push_back(line);
822 }
823
824 // Returns false if mount_point matches any of the skip mount patterns, so that the FstabEntry
825 // would be partitioned to the second group.
826 auto glob_pattern_mismatch = [&skip_mount_patterns](const FstabEntry& entry) -> bool {
827 for (const auto& pattern : skip_mount_patterns) {
828 if (!fnmatch(pattern.c_str(), entry.mount_point.c_str(), 0 /* flags */)) {
829 return false;
830 }
831 }
832 return true;
833 };
834 auto remove_from = std::stable_partition(fstab->begin(), fstab->end(), glob_pattern_mismatch);
835 if (verbose) {
836 for (auto it = remove_from; it != fstab->end(); ++it) {
837 LINFO << "Skip mounting mountpoint: " << it->mount_point;
838 }
839 }
840 fstab->erase(remove_from, fstab->end());
841 return true;
842 }
843
844 // Loads the fstab file and combines with fstab entries passed in from device tree.
ReadDefaultFstab(Fstab * fstab)845 bool ReadDefaultFstab(Fstab* fstab) {
846 fstab->clear();
847 ReadFstabFromDt(fstab, false /* verbose */);
848
849 Fstab default_fstab;
850 const std::string default_fstab_path = GetFstabPath();
851 if (!default_fstab_path.empty() && ReadFstabFromFile(default_fstab_path, &default_fstab)) {
852 fstab->insert(fstab->end(), std::make_move_iterator(default_fstab.begin()),
853 std::make_move_iterator(default_fstab.end()));
854 } else {
855 LINFO << __FUNCTION__ << "(): failed to find device default fstab";
856 }
857
858 return !fstab->empty();
859 }
860
GetEntriesForMountPoint(Fstab * fstab,const std::string & path)861 std::vector<FstabEntry*> GetEntriesForMountPoint(Fstab* fstab, const std::string& path) {
862 return GetEntriesByPred(fstab,
863 [&path](const FstabEntry& entry) { return entry.mount_point == path; });
864 }
865
GetEntryForMountPoint(Fstab * fstab,const std::string_view path,const std::string_view fstype)866 FstabEntry* GetEntryForMountPoint(Fstab* fstab, const std::string_view path,
867 const std::string_view fstype) {
868 auto&& vec = GetEntriesByPred(fstab, [&path, fstype](const FstabEntry& entry) {
869 return entry.mount_point == path && entry.fs_type == fstype;
870 });
871 return vec.empty() ? nullptr : vec.front();
872 }
873
GetEntriesForMountPoint(const Fstab * fstab,const std::string & path)874 std::vector<const FstabEntry*> GetEntriesForMountPoint(const Fstab* fstab,
875 const std::string& path) {
876 return GetEntriesByPred(fstab,
877 [&path](const FstabEntry& entry) { return entry.mount_point == path; });
878 }
879
GetEntryForMountPoint(Fstab * fstab,const std::string & path)880 FstabEntry* GetEntryForMountPoint(Fstab* fstab, const std::string& path) {
881 std::vector<FstabEntry*> entries = GetEntriesForMountPoint(fstab, path);
882 return entries.empty() ? nullptr : entries.front();
883 }
884
GetEntryForMountPoint(const Fstab * fstab,const std::string & path)885 const FstabEntry* GetEntryForMountPoint(const Fstab* fstab, const std::string& path) {
886 std::vector<const FstabEntry*> entries = GetEntriesForMountPoint(fstab, path);
887 return entries.empty() ? nullptr : entries.front();
888 }
889
GetBootDevices()890 std::set<std::string> GetBootDevices() {
891 std::set<std::string> boot_devices;
892 // First check bootconfig, then kernel commandline, then the device tree
893 std::string value;
894 if (GetBootconfig("androidboot.boot_devices", &value) ||
895 GetBootconfig("androidboot.boot_device", &value)) {
896 // split by spaces and trim the trailing comma.
897 for (std::string_view device : android::base::Split(value, " ")) {
898 base::ConsumeSuffix(&device, ",");
899 boot_devices.emplace(device);
900 }
901 return boot_devices;
902 }
903
904 const std::string dt_file_name = GetAndroidDtDir() + "boot_devices";
905 if (GetKernelCmdline("androidboot.boot_devices", &value) || ReadDtFile(dt_file_name, &value)) {
906 auto boot_devices_list = Split(value, ",");
907 return {std::make_move_iterator(boot_devices_list.begin()),
908 std::make_move_iterator(boot_devices_list.end())};
909 }
910
911 ImportKernelCmdline([&](std::string key, std::string value) {
912 if (key == "androidboot.boot_device") {
913 boot_devices.emplace(std::move(value));
914 }
915 });
916 if (!boot_devices.empty()) {
917 return boot_devices;
918 }
919
920 // Fallback to extract boot devices from fstab.
921 Fstab fstab;
922 if (!ReadDefaultFstab(&fstab)) {
923 return {};
924 }
925
926 return ExtraBootDevices(fstab);
927 }
928
GetVerityDeviceName(const FstabEntry & entry)929 std::string GetVerityDeviceName(const FstabEntry& entry) {
930 std::string base_device;
931 if (entry.mount_point == "/") {
932 // When using system-as-root, the device name is fixed as "vroot".
933 if (entry.fs_mgr_flags.avb) {
934 return "vroot";
935 }
936 base_device = "system";
937 } else {
938 base_device = android::base::Basename(entry.mount_point);
939 }
940 return base_device + "-verity";
941 }
942
InRecovery()943 bool InRecovery() {
944 // Check the existence of recovery binary instead of using the compile time
945 // __ANDROID_RECOVERY__ macro.
946 // If BOARD_USES_RECOVERY_AS_BOOT is true, both normal and recovery boot
947 // mode would use the same init binary, which would mean during normal boot
948 // the '/init' binary is actually a symlink pointing to
949 // init_second_stage.recovery, which would be compiled with
950 // __ANDROID_RECOVERY__ defined.
951 return access("/system/bin/recovery", F_OK) == 0 || access("/sbin/recovery", F_OK) == 0;
952 }
953
954 } // namespace fs_mgr
955 } // namespace android
956
is_dt_compatible()957 bool is_dt_compatible() {
958 std::string file_name = android::fs_mgr::GetAndroidDtDir() + "compatible";
959 std::string dt_value;
960 if (android::fs_mgr::ReadDtFile(file_name, &dt_value)) {
961 if (dt_value == "android,firmware") {
962 return true;
963 }
964 }
965
966 return false;
967 }
968