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