fs_mgr_fstab.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849
  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. #include <ctype.h>
  17. #include <dirent.h>
  18. #include <errno.h>
  19. #include <stdio.h>
  20. #include <stdlib.h>
  21. #include <string.h>
  22. #include <sys/mount.h>
  23. #include <unistd.h>
  24. #include <algorithm>
  25. #include <array>
  26. #include <utility>
  27. #include <vector>
  28. #include <android-base/file.h>
  29. #include <android-base/parseint.h>
  30. #include <android-base/stringprintf.h>
  31. #include <android-base/strings.h>
  32. #include <libgsi/libgsi.h>
  33. #include "fs_mgr_priv.h"
  34. using android::base::ParseByteCount;
  35. using android::base::ParseInt;
  36. using android::base::ReadFileToString;
  37. using android::base::Split;
  38. using android::base::StartsWith;
  39. namespace android {
  40. namespace fs_mgr {
  41. namespace {
  42. const std::string kDefaultAndroidDtDir("/proc/device-tree/firmware/android");
  43. struct FlagList {
  44. const char *name;
  45. uint64_t flag;
  46. };
  47. FlagList kMountFlagsList[] = {
  48. {"noatime", MS_NOATIME},
  49. {"noexec", MS_NOEXEC},
  50. {"nosuid", MS_NOSUID},
  51. {"nodev", MS_NODEV},
  52. {"nodiratime", MS_NODIRATIME},
  53. {"ro", MS_RDONLY},
  54. {"rw", 0},
  55. {"sync", MS_SYNCHRONOUS},
  56. {"remount", MS_REMOUNT},
  57. {"bind", MS_BIND},
  58. {"rec", MS_REC},
  59. {"unbindable", MS_UNBINDABLE},
  60. {"private", MS_PRIVATE},
  61. {"slave", MS_SLAVE},
  62. {"shared", MS_SHARED},
  63. {"defaults", 0},
  64. };
  65. off64_t CalculateZramSize(int percentage) {
  66. off64_t total;
  67. total = sysconf(_SC_PHYS_PAGES);
  68. total *= percentage;
  69. total /= 100;
  70. total *= sysconf(_SC_PAGESIZE);
  71. return total;
  72. }
  73. // Fills 'dt_value' with the underlying device tree value string without the trailing '\0'.
  74. // Returns true if 'dt_value' has a valid string, 'false' otherwise.
  75. bool ReadDtFile(const std::string& file_name, std::string* dt_value) {
  76. if (android::base::ReadFileToString(file_name, dt_value)) {
  77. if (!dt_value->empty()) {
  78. // Trim the trailing '\0' out, otherwise the comparison will produce false-negatives.
  79. dt_value->resize(dt_value->size() - 1);
  80. return true;
  81. }
  82. }
  83. return false;
  84. }
  85. const std::array<const char*, 3> kFileContentsEncryptionMode = {
  86. "aes-256-xts",
  87. "adiantum",
  88. "ice",
  89. };
  90. const std::array<const char*, 3> kFileNamesEncryptionMode = {
  91. "aes-256-cts",
  92. "aes-256-heh",
  93. "adiantum",
  94. };
  95. void ParseFileEncryption(const std::string& arg, FstabEntry* entry) {
  96. // The fileencryption flag is followed by an = and the mode of contents encryption, then
  97. // optionally a and the mode of filenames encryption (defaults to aes-256-cts). Get it and
  98. // return it.
  99. entry->fs_mgr_flags.file_encryption = true;
  100. auto parts = Split(arg, ":");
  101. if (parts.empty() || parts.size() > 2) {
  102. LWARNING << "Warning: fileencryption= flag malformed: " << arg;
  103. return;
  104. }
  105. // Alias for backwards compatibility.
  106. if (parts[0] == "software") {
  107. parts[0] = "aes-256-xts";
  108. }
  109. if (std::find(kFileContentsEncryptionMode.begin(), kFileContentsEncryptionMode.end(),
  110. parts[0]) == kFileContentsEncryptionMode.end()) {
  111. LWARNING << "fileencryption= flag malformed, file contents encryption mode not found: "
  112. << arg;
  113. return;
  114. }
  115. entry->file_contents_mode = parts[0];
  116. if (parts.size() == 2) {
  117. if (std::find(kFileNamesEncryptionMode.begin(), kFileNamesEncryptionMode.end(), parts[1]) ==
  118. kFileNamesEncryptionMode.end()) {
  119. LWARNING << "fileencryption= flag malformed, file names encryption mode not found: "
  120. << arg;
  121. return;
  122. }
  123. entry->file_names_mode = parts[1];
  124. } else if (entry->file_contents_mode == "adiantum") {
  125. entry->file_names_mode = "adiantum";
  126. } else {
  127. entry->file_names_mode = "aes-256-cts";
  128. }
  129. }
  130. bool SetMountFlag(const std::string& flag, FstabEntry* entry) {
  131. for (const auto& [name, value] : kMountFlagsList) {
  132. if (flag == name) {
  133. entry->flags |= value;
  134. return true;
  135. }
  136. }
  137. return false;
  138. }
  139. void ParseMountFlags(const std::string& flags, FstabEntry* entry) {
  140. std::string fs_options;
  141. for (const auto& flag : Split(flags, ",")) {
  142. if (!SetMountFlag(flag, entry)) {
  143. // Unknown flag, so it must be a filesystem specific option.
  144. if (!fs_options.empty()) {
  145. fs_options.append(","); // appends a comma if not the first
  146. }
  147. fs_options.append(flag);
  148. }
  149. }
  150. entry->fs_options = std::move(fs_options);
  151. }
  152. void ParseFsMgrFlags(const std::string& flags, FstabEntry* entry) {
  153. for (const auto& flag : Split(flags, ",")) {
  154. if (flag.empty() || flag == "defaults") continue;
  155. std::string arg;
  156. if (auto equal_sign = flag.find('='); equal_sign != std::string::npos) {
  157. arg = flag.substr(equal_sign + 1);
  158. }
  159. // First handle flags that simply set a boolean.
  160. #define CheckFlag(flag_name, value) \
  161. if (flag == flag_name) { \
  162. entry->fs_mgr_flags.value = true; \
  163. continue; \
  164. }
  165. CheckFlag("wait", wait);
  166. CheckFlag("check", check);
  167. CheckFlag("nonremovable", nonremovable);
  168. CheckFlag("recoveryonly", recovery_only);
  169. CheckFlag("noemulatedsd", no_emulated_sd);
  170. CheckFlag("notrim", no_trim);
  171. CheckFlag("verify", verify);
  172. CheckFlag("formattable", formattable);
  173. CheckFlag("slotselect", slot_select);
  174. CheckFlag("latemount", late_mount);
  175. CheckFlag("nofail", no_fail);
  176. CheckFlag("verifyatboot", verify_at_boot);
  177. CheckFlag("quota", quota);
  178. CheckFlag("avb", avb);
  179. CheckFlag("logical", logical);
  180. CheckFlag("checkpoint=block", checkpoint_blk);
  181. CheckFlag("checkpoint=fs", checkpoint_fs);
  182. CheckFlag("first_stage_mount", first_stage_mount);
  183. CheckFlag("slotselect_other", slot_select_other);
  184. CheckFlag("fsverity", fs_verity);
  185. #undef CheckFlag
  186. // Then handle flags that take an argument.
  187. if (StartsWith(flag, "encryptable=")) {
  188. // The encryptable flag is followed by an = and the location of the keys.
  189. entry->fs_mgr_flags.crypt = true;
  190. entry->key_loc = arg;
  191. } else if (StartsWith(flag, "voldmanaged=")) {
  192. // The voldmanaged flag is followed by an = and the label, a colon and the partition
  193. // number or the word "auto", e.g. voldmanaged=sdcard:3
  194. entry->fs_mgr_flags.vold_managed = true;
  195. auto parts = Split(arg, ":");
  196. if (parts.size() != 2) {
  197. LWARNING << "Warning: voldmanaged= flag malformed: " << arg;
  198. continue;
  199. }
  200. entry->label = std::move(parts[0]);
  201. if (parts[1] == "auto") {
  202. entry->partnum = -1;
  203. } else {
  204. if (!ParseInt(parts[1], &entry->partnum)) {
  205. entry->partnum = -1;
  206. LWARNING << "Warning: voldmanaged= flag malformed: " << arg;
  207. continue;
  208. }
  209. }
  210. } else if (StartsWith(flag, "length=")) {
  211. // The length flag is followed by an = and the size of the partition.
  212. if (!ParseInt(arg, &entry->length)) {
  213. LWARNING << "Warning: length= flag malformed: " << arg;
  214. }
  215. } else if (StartsWith(flag, "swapprio=")) {
  216. if (!ParseInt(arg, &entry->swap_prio)) {
  217. LWARNING << "Warning: length= flag malformed: " << arg;
  218. }
  219. } else if (StartsWith(flag, "zramsize=")) {
  220. if (!arg.empty() && arg.back() == '%') {
  221. arg.pop_back();
  222. int val;
  223. if (ParseInt(arg, &val, 0, 100)) {
  224. entry->zram_size = CalculateZramSize(val);
  225. } else {
  226. LWARNING << "Warning: zramsize= flag malformed: " << arg;
  227. }
  228. } else {
  229. if (!ParseInt(arg, &entry->zram_size)) {
  230. LWARNING << "Warning: zramsize= flag malformed: " << arg;
  231. }
  232. }
  233. } else if (StartsWith(flag, "verify=")) {
  234. // If the verify flag is followed by an = and the location for the verity state.
  235. entry->fs_mgr_flags.verify = true;
  236. entry->verity_loc = arg;
  237. } else if (StartsWith(flag, "forceencrypt=")) {
  238. // The forceencrypt flag is followed by an = and the location of the keys.
  239. entry->fs_mgr_flags.force_crypt = true;
  240. entry->key_loc = arg;
  241. } else if (StartsWith(flag, "fileencryption=")) {
  242. ParseFileEncryption(arg, entry);
  243. } else if (StartsWith(flag, "forcefdeorfbe=")) {
  244. // The forcefdeorfbe flag is followed by an = and the location of the keys. Get it and
  245. // return it.
  246. entry->fs_mgr_flags.force_fde_or_fbe = true;
  247. entry->key_loc = arg;
  248. entry->file_contents_mode = "aes-256-xts";
  249. entry->file_names_mode = "aes-256-cts";
  250. } else if (StartsWith(flag, "max_comp_streams=")) {
  251. if (!ParseInt(arg, &entry->max_comp_streams)) {
  252. LWARNING << "Warning: max_comp_streams= flag malformed: " << arg;
  253. }
  254. } else if (StartsWith(flag, "reservedsize=")) {
  255. // The reserved flag is followed by an = and the reserved size of the partition.
  256. uint64_t size;
  257. if (!ParseByteCount(arg, &size)) {
  258. LWARNING << "Warning: reservedsize= flag malformed: " << arg;
  259. } else {
  260. entry->reserved_size = static_cast<off64_t>(size);
  261. }
  262. } else if (StartsWith(flag, "eraseblk=")) {
  263. // The erase block size flag is followed by an = and the flash erase block size. Get it,
  264. // check that it is a power of 2 and at least 4096, and return it.
  265. off64_t val;
  266. if (!ParseInt(arg, &val) || val < 4096 || (val & (val - 1)) != 0) {
  267. LWARNING << "Warning: eraseblk= flag malformed: " << arg;
  268. } else {
  269. entry->erase_blk_size = val;
  270. }
  271. } else if (StartsWith(flag, "logicalblk=")) {
  272. // The logical block size flag is followed by an = and the flash logical block size. Get
  273. // it, check that it is a power of 2 and at least 4096, and return it.
  274. off64_t val;
  275. if (!ParseInt(arg, &val) || val < 4096 || (val & (val - 1)) != 0) {
  276. LWARNING << "Warning: logicalblk= flag malformed: " << arg;
  277. } else {
  278. entry->logical_blk_size = val;
  279. }
  280. } else if (StartsWith(flag, "avb_keys=")) { // must before the following "avb"
  281. entry->avb_keys = arg;
  282. } else if (StartsWith(flag, "avb")) {
  283. entry->fs_mgr_flags.avb = true;
  284. entry->vbmeta_partition = arg;
  285. } else if (StartsWith(flag, "keydirectory=")) {
  286. // The metadata flag is followed by an = and the directory for the keys.
  287. entry->key_dir = arg;
  288. } else if (StartsWith(flag, "sysfs_path=")) {
  289. // The path to trigger device gc by idle-maint of vold.
  290. entry->sysfs_path = arg;
  291. } else if (StartsWith(flag, "zram_loopback_path=")) {
  292. // The path to use loopback for zram.
  293. entry->zram_loopback_path = arg;
  294. } else if (StartsWith(flag, "zram_loopback_size=")) {
  295. if (!ParseByteCount(arg, &entry->zram_loopback_size)) {
  296. LWARNING << "Warning: zram_loopback_size= flag malformed: " << arg;
  297. }
  298. } else if (StartsWith(flag, "zram_backing_dev_path=")) {
  299. entry->zram_backing_dev_path = arg;
  300. } else {
  301. LWARNING << "Warning: unknown flag: " << flag;
  302. }
  303. }
  304. }
  305. std::string InitAndroidDtDir() {
  306. std::string android_dt_dir;
  307. // The platform may specify a custom Android DT path in kernel cmdline
  308. if (!fs_mgr_get_boot_config_from_kernel_cmdline("android_dt_dir", &android_dt_dir)) {
  309. // Fall back to the standard procfs-based path
  310. android_dt_dir = kDefaultAndroidDtDir;
  311. }
  312. return android_dt_dir;
  313. }
  314. bool IsDtFstabCompatible() {
  315. std::string dt_value;
  316. std::string file_name = get_android_dt_dir() + "/fstab/compatible";
  317. if (ReadDtFile(file_name, &dt_value) && dt_value == "android,fstab") {
  318. // If there's no status property or its set to "ok" or "okay", then we use the DT fstab.
  319. std::string status_value;
  320. std::string status_file_name = get_android_dt_dir() + "/fstab/status";
  321. return !ReadDtFile(status_file_name, &status_value) || status_value == "ok" ||
  322. status_value == "okay";
  323. }
  324. return false;
  325. }
  326. std::string ReadFstabFromDt() {
  327. if (!is_dt_compatible() || !IsDtFstabCompatible()) {
  328. return {};
  329. }
  330. std::string fstabdir_name = get_android_dt_dir() + "/fstab";
  331. std::unique_ptr<DIR, int (*)(DIR*)> fstabdir(opendir(fstabdir_name.c_str()), closedir);
  332. if (!fstabdir) return {};
  333. dirent* dp;
  334. // Each element in fstab_dt_entries is <mount point, the line format in fstab file>.
  335. std::vector<std::pair<std::string, std::string>> fstab_dt_entries;
  336. while ((dp = readdir(fstabdir.get())) != NULL) {
  337. // skip over name, compatible and .
  338. if (dp->d_type != DT_DIR || dp->d_name[0] == '.') continue;
  339. // create <dev> <mnt_point> <type> <mnt_flags> <fsmgr_flags>\n
  340. std::vector<std::string> fstab_entry;
  341. std::string file_name;
  342. std::string value;
  343. // skip a partition entry if the status property is present and not set to ok
  344. file_name = android::base::StringPrintf("%s/%s/status", fstabdir_name.c_str(), dp->d_name);
  345. if (ReadDtFile(file_name, &value)) {
  346. if (value != "okay" && value != "ok") {
  347. LINFO << "dt_fstab: Skip disabled entry for partition " << dp->d_name;
  348. continue;
  349. }
  350. }
  351. file_name = android::base::StringPrintf("%s/%s/dev", fstabdir_name.c_str(), dp->d_name);
  352. if (!ReadDtFile(file_name, &value)) {
  353. LERROR << "dt_fstab: Failed to find device for partition " << dp->d_name;
  354. return {};
  355. }
  356. fstab_entry.push_back(value);
  357. std::string mount_point;
  358. file_name =
  359. android::base::StringPrintf("%s/%s/mnt_point", fstabdir_name.c_str(), dp->d_name);
  360. if (ReadDtFile(file_name, &value)) {
  361. LINFO << "dt_fstab: Using a specified mount point " << value << " for " << dp->d_name;
  362. mount_point = value;
  363. } else {
  364. mount_point = android::base::StringPrintf("/%s", dp->d_name);
  365. }
  366. fstab_entry.push_back(mount_point);
  367. file_name = android::base::StringPrintf("%s/%s/type", fstabdir_name.c_str(), dp->d_name);
  368. if (!ReadDtFile(file_name, &value)) {
  369. LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
  370. return {};
  371. }
  372. fstab_entry.push_back(value);
  373. file_name = android::base::StringPrintf("%s/%s/mnt_flags", fstabdir_name.c_str(), dp->d_name);
  374. if (!ReadDtFile(file_name, &value)) {
  375. LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
  376. return {};
  377. }
  378. fstab_entry.push_back(value);
  379. file_name = android::base::StringPrintf("%s/%s/fsmgr_flags", fstabdir_name.c_str(), dp->d_name);
  380. if (!ReadDtFile(file_name, &value)) {
  381. LERROR << "dt_fstab: Failed to find type for partition " << dp->d_name;
  382. return {};
  383. }
  384. fstab_entry.push_back(value);
  385. // Adds a fstab_entry to fstab_dt_entries, to be sorted by mount_point later.
  386. fstab_dt_entries.emplace_back(mount_point, android::base::Join(fstab_entry, " "));
  387. }
  388. // Sort fstab_dt entries, to ensure /vendor is mounted before /vendor/abc is attempted.
  389. std::sort(fstab_dt_entries.begin(), fstab_dt_entries.end(),
  390. [](const auto& a, const auto& b) { return a.first < b.first; });
  391. std::string fstab_result;
  392. for (const auto& [_, dt_entry] : fstab_dt_entries) {
  393. fstab_result += dt_entry + "\n";
  394. }
  395. return fstab_result;
  396. }
  397. // Identify path to fstab file. Lookup is based on pattern fstab.<hardware>,
  398. // fstab.<hardware.platform> in folders /odm/etc, vendor/etc, or /.
  399. std::string GetFstabPath() {
  400. for (const char* prop : {"hardware", "hardware.platform"}) {
  401. std::string hw;
  402. if (!fs_mgr_get_boot_config(prop, &hw)) continue;
  403. if (access("/.cell", F_OK) == 0) {
  404. for (const char *prefix : {"/cells/fstab."}) {
  405. std::string fstab_path = prefix + hw;
  406. if (access(fstab_path.c_str(), F_OK) == 0) {
  407. return fstab_path;
  408. }
  409. }
  410. }else{
  411. for (const char* prefix : {"/odm/etc/fstab.", "/vendor/etc/fstab.", "/fstab."}) {
  412. std::string fstab_path = prefix + hw;
  413. if (access(fstab_path.c_str(), F_OK) == 0) {
  414. return fstab_path;
  415. }
  416. }
  417. }
  418. }
  419. return "";
  420. }
  421. bool ReadFstabFile(FILE* fstab_file, bool proc_mounts, Fstab* fstab_out) {
  422. ssize_t len;
  423. size_t alloc_len = 0;
  424. char *line = NULL;
  425. const char *delim = " \t";
  426. char *save_ptr, *p;
  427. Fstab fstab;
  428. while ((len = getline(&line, &alloc_len, fstab_file)) != -1) {
  429. /* if the last character is a newline, shorten the string by 1 byte */
  430. if (line[len - 1] == '\n') {
  431. line[len - 1] = '\0';
  432. }
  433. /* Skip any leading whitespace */
  434. p = line;
  435. while (isspace(*p)) {
  436. p++;
  437. }
  438. /* ignore comments or empty lines */
  439. if (*p == '#' || *p == '\0')
  440. continue;
  441. FstabEntry entry;
  442. if (!(p = strtok_r(line, delim, &save_ptr))) {
  443. LERROR << "Error parsing mount source";
  444. goto err;
  445. }
  446. entry.blk_device = p;
  447. if (!(p = strtok_r(NULL, delim, &save_ptr))) {
  448. LERROR << "Error parsing mount_point";
  449. goto err;
  450. }
  451. entry.mount_point = p;
  452. if (!(p = strtok_r(NULL, delim, &save_ptr))) {
  453. LERROR << "Error parsing fs_type";
  454. goto err;
  455. }
  456. entry.fs_type = p;
  457. if (!(p = strtok_r(NULL, delim, &save_ptr))) {
  458. LERROR << "Error parsing mount_flags";
  459. goto err;
  460. }
  461. ParseMountFlags(p, &entry);
  462. // For /proc/mounts, ignore everything after mnt_freq and mnt_passno
  463. if (proc_mounts) {
  464. p += strlen(p);
  465. } else if (!(p = strtok_r(NULL, delim, &save_ptr))) {
  466. LERROR << "Error parsing fs_mgr_options";
  467. goto err;
  468. }
  469. ParseFsMgrFlags(p, &entry);
  470. if (entry.fs_mgr_flags.logical) {
  471. entry.logical_partition_name = entry.blk_device;
  472. }
  473. fstab.emplace_back(std::move(entry));
  474. }
  475. if (fstab.empty()) {
  476. LERROR << "No entries found in fstab";
  477. goto err;
  478. }
  479. /* If an A/B partition, modify block device to be the real block device */
  480. if (!fs_mgr_update_for_slotselect(&fstab)) {
  481. LERROR << "Error updating for slotselect";
  482. goto err;
  483. }
  484. free(line);
  485. *fstab_out = std::move(fstab);
  486. return true;
  487. err:
  488. free(line);
  489. return false;
  490. }
  491. /* Extracts <device>s from the by-name symlinks specified in a fstab:
  492. * /dev/block/<type>/<device>/by-name/<partition>
  493. *
  494. * <type> can be: platform, pci or vbd.
  495. *
  496. * For example, given the following entries in the input fstab:
  497. * /dev/block/platform/soc/1da4000.ufshc/by-name/system
  498. * /dev/block/pci/soc.0/f9824900.sdhci/by-name/vendor
  499. * it returns a set { "soc/1da4000.ufshc", "soc.0/f9824900.sdhci" }.
  500. */
  501. std::set<std::string> ExtraBootDevices(const Fstab& fstab) {
  502. std::set<std::string> boot_devices;
  503. for (const auto& entry : fstab) {
  504. std::string blk_device = entry.blk_device;
  505. // Skips blk_device that doesn't conform to the format.
  506. if (!android::base::StartsWith(blk_device, "/dev/block") ||
  507. android::base::StartsWith(blk_device, "/dev/block/by-name") ||
  508. android::base::StartsWith(blk_device, "/dev/block/bootdevice/by-name")) {
  509. continue;
  510. }
  511. // Skips non-by_name blk_device.
  512. // /dev/block/<type>/<device>/by-name/<partition>
  513. // ^ slash_by_name
  514. auto slash_by_name = blk_device.find("/by-name");
  515. if (slash_by_name == std::string::npos) continue;
  516. blk_device.erase(slash_by_name); // erases /by-name/<partition>
  517. // Erases /dev/block/, now we have <type>/<device>
  518. blk_device.erase(0, std::string("/dev/block/").size());
  519. // <type>/<device>
  520. // ^ first_slash
  521. auto first_slash = blk_device.find('/');
  522. if (first_slash == std::string::npos) continue;
  523. auto boot_device = blk_device.substr(first_slash + 1);
  524. if (!boot_device.empty()) boot_devices.insert(std::move(boot_device));
  525. }
  526. return boot_devices;
  527. }
  528. FstabEntry BuildGsiUserdataFstabEntry() {
  529. constexpr uint32_t kFlags = MS_NOATIME | MS_NOSUID | MS_NODEV;
  530. FstabEntry userdata = {
  531. .blk_device = "userdata_gsi",
  532. .mount_point = "/data",
  533. .fs_type = "ext4",
  534. .flags = kFlags,
  535. .reserved_size = 128 * 1024 * 1024,
  536. };
  537. userdata.fs_mgr_flags.wait = true;
  538. userdata.fs_mgr_flags.check = true;
  539. userdata.fs_mgr_flags.logical = true;
  540. userdata.fs_mgr_flags.quota = true;
  541. userdata.fs_mgr_flags.late_mount = true;
  542. userdata.fs_mgr_flags.formattable = true;
  543. return userdata;
  544. }
  545. bool EraseFstabEntry(Fstab* fstab, const std::string& mount_point) {
  546. auto iter = std::remove_if(fstab->begin(), fstab->end(),
  547. [&](const auto& entry) { return entry.mount_point == mount_point; });
  548. if (iter != fstab->end()) {
  549. fstab->erase(iter, fstab->end());
  550. return true;
  551. }
  552. return false;
  553. }
  554. void TransformFstabForGsi(Fstab* fstab) {
  555. // Inherit fstab properties for userdata.
  556. FstabEntry userdata;
  557. if (FstabEntry* entry = GetEntryForMountPoint(fstab, "/data")) {
  558. userdata = *entry;
  559. userdata.blk_device = "userdata_gsi";
  560. userdata.fs_mgr_flags.logical = true;
  561. userdata.fs_mgr_flags.formattable = true;
  562. if (!userdata.key_dir.empty()) {
  563. userdata.key_dir += "/gsi";
  564. }
  565. } else {
  566. userdata = BuildGsiUserdataFstabEntry();
  567. }
  568. if (EraseFstabEntry(fstab, "/system")) {
  569. fstab->emplace_back(BuildGsiSystemFstabEntry());
  570. }
  571. if (EraseFstabEntry(fstab, "/data")) {
  572. fstab->emplace_back(userdata);
  573. }
  574. }
  575. } // namespace
  576. bool ReadFstabFromFile(const std::string& path, Fstab* fstab) {
  577. auto fstab_file = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
  578. if (!fstab_file) {
  579. PERROR << __FUNCTION__ << "(): cannot open file: '" << path << "'";
  580. return false;
  581. }
  582. bool is_proc_mounts = path == "/proc/mounts";
  583. if (!ReadFstabFile(fstab_file.get(), is_proc_mounts, fstab)) {
  584. LERROR << __FUNCTION__ << "(): failed to load fstab from : '" << path << "'";
  585. return false;
  586. }
  587. if (!is_proc_mounts && !access(android::gsi::kGsiBootedIndicatorFile, F_OK)) {
  588. TransformFstabForGsi(fstab);
  589. }
  590. SkipMountingPartitions(fstab);
  591. return true;
  592. }
  593. // Returns fstab entries parsed from the device tree if they exist
  594. bool ReadFstabFromDt(Fstab* fstab, bool log) {
  595. std::string fstab_buf = ReadFstabFromDt();
  596. if (fstab_buf.empty()) {
  597. if (log) LINFO << __FUNCTION__ << "(): failed to read fstab from dt";
  598. return false;
  599. }
  600. std::unique_ptr<FILE, decltype(&fclose)> fstab_file(
  601. fmemopen(static_cast<void*>(const_cast<char*>(fstab_buf.c_str())),
  602. fstab_buf.length(), "r"), fclose);
  603. if (!fstab_file) {
  604. if (log) PERROR << __FUNCTION__ << "(): failed to create a file stream for fstab dt";
  605. return false;
  606. }
  607. if (!ReadFstabFile(fstab_file.get(), false, fstab)) {
  608. if (log) {
  609. LERROR << __FUNCTION__ << "(): failed to load fstab from kernel:" << std::endl
  610. << fstab_buf;
  611. }
  612. return false;
  613. }
  614. SkipMountingPartitions(fstab);
  615. return true;
  616. }
  617. // For GSI to skip mounting /product and /product_services, until there are
  618. // well-defined interfaces between them and /system. Otherwise, the GSI flashed
  619. // on /system might not be able to work with /product and /product_services.
  620. // When they're skipped here, /system/product and /system/product_services in
  621. // GSI will be used.
  622. bool SkipMountingPartitions(Fstab* fstab) {
  623. constexpr const char kSkipMountConfig[] = "/system/etc/init/config/skip_mount.cfg";
  624. std::string skip_config;
  625. auto save_errno = errno;
  626. if (!ReadFileToString(kSkipMountConfig, &skip_config)) {
  627. errno = save_errno; // missing file is expected
  628. return true;
  629. }
  630. for (const auto& skip_mount_point : Split(skip_config, "\n")) {
  631. if (skip_mount_point.empty()) {
  632. continue;
  633. }
  634. auto it = std::remove_if(fstab->begin(), fstab->end(),
  635. [&skip_mount_point](const auto& entry) {
  636. return entry.mount_point == skip_mount_point;
  637. });
  638. fstab->erase(it, fstab->end());
  639. LOG(INFO) << "Skip mounting partition: " << skip_mount_point;
  640. }
  641. return true;
  642. }
  643. // Loads the fstab file and combines with fstab entries passed in from device tree.
  644. bool ReadDefaultFstab(Fstab* fstab) {
  645. Fstab dt_fstab;
  646. ReadFstabFromDt(&dt_fstab, false);
  647. *fstab = std::move(dt_fstab);
  648. std::string default_fstab_path;
  649. // Use different fstab paths for normal boot and recovery boot, respectively
  650. if (access("/system/bin/recovery", F_OK) == 0) {
  651. default_fstab_path = "/etc/recovery.fstab";
  652. } else { // normal boot
  653. default_fstab_path = GetFstabPath();
  654. }
  655. Fstab default_fstab;
  656. if (!default_fstab_path.empty()) {
  657. ReadFstabFromFile(default_fstab_path, &default_fstab);
  658. } else {
  659. LINFO << __FUNCTION__ << "(): failed to find device default fstab";
  660. }
  661. for (auto&& entry : default_fstab) {
  662. fstab->emplace_back(std::move(entry));
  663. }
  664. return !fstab->empty();
  665. }
  666. FstabEntry* GetEntryForMountPoint(Fstab* fstab, const std::string& path) {
  667. if (fstab == nullptr) {
  668. return nullptr;
  669. }
  670. for (auto& entry : *fstab) {
  671. if (entry.mount_point == path) {
  672. return &entry;
  673. }
  674. }
  675. return nullptr;
  676. }
  677. std::set<std::string> GetBootDevices() {
  678. // First check the kernel commandline, then try the device tree otherwise
  679. std::string dt_file_name = get_android_dt_dir() + "/boot_devices";
  680. std::string value;
  681. if (fs_mgr_get_boot_config_from_kernel_cmdline("boot_devices", &value) ||
  682. ReadDtFile(dt_file_name, &value)) {
  683. auto boot_devices = Split(value, ",");
  684. return std::set<std::string>(boot_devices.begin(), boot_devices.end());
  685. }
  686. // Fallback to extract boot devices from fstab.
  687. Fstab fstab;
  688. if (!ReadDefaultFstab(&fstab)) {
  689. return {};
  690. }
  691. return ExtraBootDevices(fstab);
  692. }
  693. FstabEntry BuildGsiSystemFstabEntry() {
  694. // .logical_partition_name is required to look up AVB Hashtree descriptors.
  695. FstabEntry system = {.blk_device = "system_gsi",
  696. .mount_point = "/system",
  697. .fs_type = "ext4",
  698. .flags = MS_RDONLY,
  699. .fs_options = "barrier=1",
  700. // could add more keys separated by ':'.
  701. .avb_keys =
  702. "/avb/q-gsi.avbpubkey:/avb/q-developer-gsi.avbpubkey:"
  703. "/avb/r-gsi.avbpubkey:/avb/s-gsi.avbpubkey",
  704. .logical_partition_name = "system"};
  705. system.fs_mgr_flags.wait = true;
  706. system.fs_mgr_flags.logical = true;
  707. system.fs_mgr_flags.first_stage_mount = true;
  708. return system;
  709. }
  710. std::string GetVerityDeviceName(const FstabEntry& entry) {
  711. std::string base_device;
  712. if (entry.mount_point == "/") {
  713. // In AVB, the dm device name is vroot instead of system.
  714. base_device = entry.fs_mgr_flags.avb ? "vroot" : "system";
  715. } else {
  716. base_device = android::base::Basename(entry.mount_point);
  717. }
  718. return base_device + "-verity";
  719. }
  720. } // namespace fs_mgr
  721. } // namespace android
  722. // FIXME: The same logic is duplicated in system/core/init/
  723. const std::string& get_android_dt_dir() {
  724. // Set once and saves time for subsequent calls to this function
  725. static const std::string kAndroidDtDir = android::fs_mgr::InitAndroidDtDir();
  726. return kAndroidDtDir;
  727. }
  728. bool is_dt_compatible() {
  729. std::string file_name = get_android_dt_dir() + "/compatible";
  730. std::string dt_value;
  731. if (android::fs_mgr::ReadDtFile(file_name, &dt_value)) {
  732. if (dt_value == "android,firmware") {
  733. return true;
  734. }
  735. }
  736. return false;
  737. }