gsi_service.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  1. /*
  2. * Copyright (C) 2019 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 "gsi_service.h"
  17. #include <errno.h>
  18. #include <linux/fs.h>
  19. #include <sys/ioctl.h>
  20. #include <sys/stat.h>
  21. #include <sys/statvfs.h>
  22. #include <sys/types.h>
  23. #include <sys/vfs.h>
  24. #include <unistd.h>
  25. #include <chrono>
  26. #include <string>
  27. #include <vector>
  28. #include <android-base/file.h>
  29. #include <android-base/logging.h>
  30. #include <android-base/stringprintf.h>
  31. #include <android-base/strings.h>
  32. #include <android/gsi/IGsiService.h>
  33. #include <ext4_utils/ext4_utils.h>
  34. #include <fs_mgr.h>
  35. #include <fs_mgr_dm_linear.h>
  36. #include <fstab/fstab.h>
  37. #include <libdm/dm.h>
  38. #include <libfiemap_writer/fiemap_writer.h>
  39. #include <logwrap/logwrap.h>
  40. #include <private/android_filesystem_config.h>
  41. #include "file_paths.h"
  42. #include "libgsi_private.h"
  43. namespace android {
  44. namespace gsi {
  45. using namespace std::literals;
  46. using namespace android::dm;
  47. using namespace android::fs_mgr;
  48. using namespace android::fiemap_writer;
  49. using android::base::StringPrintf;
  50. using android::base::unique_fd;
  51. static constexpr char kUserdataDevice[] = "/dev/block/by-name/userdata";
  52. // The default size of userdata.img for GSI.
  53. // We are looking for /data to have atleast 40% free space
  54. static constexpr uint32_t kMinimumFreeSpaceThreshold = 40;
  55. // We determine the fragmentation by making sure the files
  56. // we create don't have more than 16 extents.
  57. static constexpr uint32_t kMaximumExtents = 512;
  58. // Default userdata image size.
  59. static constexpr int64_t kDefaultUserdataSize = int64_t(8) * 1024 * 1024 * 1024;
  60. static constexpr std::chrono::milliseconds kDmTimeout = 5000ms;
  61. void GsiService::Register() {
  62. auto ret = android::BinderService<GsiService>::publish();
  63. if (ret != android::OK) {
  64. LOG(FATAL) << "Could not register gsi service: " << ret;
  65. }
  66. }
  67. GsiService::GsiService() {
  68. progress_ = {};
  69. }
  70. GsiService::~GsiService() {
  71. PostInstallCleanup();
  72. }
  73. #define ENFORCE_SYSTEM \
  74. do { \
  75. binder::Status status = CheckUid(); \
  76. if (!status.isOk()) return status; \
  77. } while (0)
  78. #define ENFORCE_SYSTEM_OR_SHELL \
  79. do { \
  80. binder::Status status = CheckUid(AccessLevel::SystemOrShell); \
  81. if (!status.isOk()) return status; \
  82. } while (0)
  83. binder::Status GsiService::startGsiInstall(int64_t gsiSize, int64_t userdataSize, bool wipeUserdata,
  84. int* _aidl_return) {
  85. GsiInstallParams params;
  86. params.gsiSize = gsiSize;
  87. params.userdataSize = userdataSize;
  88. params.wipeUserdata = wipeUserdata;
  89. return beginGsiInstall(params, _aidl_return);
  90. }
  91. binder::Status GsiService::beginGsiInstall(const GsiInstallParams& given_params, int* _aidl_return) {
  92. ENFORCE_SYSTEM;
  93. std::lock_guard<std::mutex> guard(main_lock_);
  94. // Make sure any interrupted installations are cleaned up.
  95. PostInstallCleanup();
  96. // Do some precursor validation on the arguments before diving into the
  97. // install process.
  98. GsiInstallParams params = given_params;
  99. if (int status = ValidateInstallParams(&params)) {
  100. *_aidl_return = status;
  101. return binder::Status::ok();
  102. }
  103. int status = StartInstall(params);
  104. if (status != INSTALL_OK) {
  105. // Perform local cleanup and delete any lingering files.
  106. PostInstallCleanup();
  107. RemoveGsiFiles(params.installDir, wipe_userdata_on_failure_);
  108. }
  109. *_aidl_return = status;
  110. // Clear the progress indicator.
  111. UpdateProgress(STATUS_NO_OPERATION, 0);
  112. return binder::Status::ok();
  113. }
  114. binder::Status GsiService::commitGsiChunkFromStream(const android::os::ParcelFileDescriptor& stream,
  115. int64_t bytes, bool* _aidl_return) {
  116. ENFORCE_SYSTEM;
  117. std::lock_guard<std::mutex> guard(main_lock_);
  118. *_aidl_return = CommitGsiChunk(stream.get(), bytes);
  119. // Clear the progress indicator.
  120. UpdateProgress(STATUS_NO_OPERATION, 0);
  121. return binder::Status::ok();
  122. }
  123. void GsiService::StartAsyncOperation(const std::string& step, int64_t total_bytes) {
  124. std::lock_guard<std::mutex> guard(progress_lock_);
  125. progress_.step = step;
  126. progress_.status = STATUS_WORKING;
  127. progress_.bytes_processed = 0;
  128. progress_.total_bytes = total_bytes;
  129. }
  130. void GsiService::UpdateProgress(int status, int64_t bytes_processed) {
  131. std::lock_guard<std::mutex> guard(progress_lock_);
  132. progress_.status = status;
  133. if (status == STATUS_COMPLETE) {
  134. progress_.bytes_processed = progress_.total_bytes;
  135. } else {
  136. progress_.bytes_processed = bytes_processed;
  137. }
  138. }
  139. binder::Status GsiService::getInstallProgress(::android::gsi::GsiProgress* _aidl_return) {
  140. ENFORCE_SYSTEM;
  141. std::lock_guard<std::mutex> guard(progress_lock_);
  142. *_aidl_return = progress_;
  143. return binder::Status::ok();
  144. }
  145. binder::Status GsiService::commitGsiChunkFromMemory(const std::vector<uint8_t>& bytes,
  146. bool* _aidl_return) {
  147. ENFORCE_SYSTEM;
  148. std::lock_guard<std::mutex> guard(main_lock_);
  149. *_aidl_return = CommitGsiChunk(bytes.data(), bytes.size());
  150. return binder::Status::ok();
  151. }
  152. binder::Status GsiService::setGsiBootable(bool one_shot, int* _aidl_return) {
  153. std::lock_guard<std::mutex> guard(main_lock_);
  154. if (installing_) {
  155. ENFORCE_SYSTEM;
  156. int error = SetGsiBootable(one_shot);
  157. PostInstallCleanup();
  158. if (error) {
  159. RemoveGsiFiles(install_dir_, wipe_userdata_on_failure_);
  160. *_aidl_return = error;
  161. } else {
  162. *_aidl_return = INSTALL_OK;
  163. }
  164. } else {
  165. ENFORCE_SYSTEM_OR_SHELL;
  166. *_aidl_return = ReenableGsi(one_shot);
  167. PostInstallCleanup();
  168. }
  169. return binder::Status::ok();
  170. }
  171. binder::Status GsiService::isGsiEnabled(bool* _aidl_return) {
  172. ENFORCE_SYSTEM_OR_SHELL;
  173. std::lock_guard<std::mutex> guard(main_lock_);
  174. std::string boot_key;
  175. if (!GetInstallStatus(&boot_key)) {
  176. *_aidl_return = false;
  177. } else {
  178. *_aidl_return = (boot_key == kInstallStatusOk);
  179. }
  180. return binder::Status::ok();
  181. }
  182. binder::Status GsiService::removeGsiInstall(bool* _aidl_return) {
  183. ENFORCE_SYSTEM_OR_SHELL;
  184. std::lock_guard<std::mutex> guard(main_lock_);
  185. // Just in case an install was left hanging.
  186. std::string install_dir;
  187. if (installing_) {
  188. install_dir = install_dir_;
  189. PostInstallCleanup();
  190. } else {
  191. install_dir = GetInstalledImageDir();
  192. }
  193. if (IsGsiRunning()) {
  194. // Can't remove gsi files while running.
  195. *_aidl_return = UninstallGsi();
  196. } else {
  197. *_aidl_return = RemoveGsiFiles(install_dir, true /* wipeUserdata */);
  198. }
  199. return binder::Status::ok();
  200. }
  201. binder::Status GsiService::disableGsiInstall(bool* _aidl_return) {
  202. ENFORCE_SYSTEM_OR_SHELL;
  203. std::lock_guard<std::mutex> guard(main_lock_);
  204. *_aidl_return = DisableGsiInstall();
  205. return binder::Status::ok();
  206. }
  207. binder::Status GsiService::isGsiRunning(bool* _aidl_return) {
  208. ENFORCE_SYSTEM_OR_SHELL;
  209. std::lock_guard<std::mutex> guard(main_lock_);
  210. *_aidl_return = IsGsiRunning();
  211. return binder::Status::ok();
  212. }
  213. binder::Status GsiService::isGsiInstalled(bool* _aidl_return) {
  214. ENFORCE_SYSTEM_OR_SHELL;
  215. std::lock_guard<std::mutex> guard(main_lock_);
  216. *_aidl_return = IsGsiInstalled();
  217. return binder::Status::ok();
  218. }
  219. binder::Status GsiService::isGsiInstallInProgress(bool* _aidl_return) {
  220. ENFORCE_SYSTEM_OR_SHELL;
  221. std::lock_guard<std::mutex> guard(main_lock_);
  222. *_aidl_return = installing_;
  223. return binder::Status::ok();
  224. }
  225. binder::Status GsiService::cancelGsiInstall(bool* _aidl_return) {
  226. ENFORCE_SYSTEM;
  227. should_abort_ = true;
  228. std::lock_guard<std::mutex> guard(main_lock_);
  229. should_abort_ = false;
  230. if (installing_) {
  231. PostInstallCleanup();
  232. RemoveGsiFiles(install_dir_, wipe_userdata_on_failure_);
  233. }
  234. *_aidl_return = true;
  235. return binder::Status::ok();
  236. }
  237. binder::Status GsiService::getGsiBootStatus(int* _aidl_return) {
  238. ENFORCE_SYSTEM_OR_SHELL;
  239. std::lock_guard<std::mutex> guard(main_lock_);
  240. if (!IsGsiInstalled()) {
  241. *_aidl_return = BOOT_STATUS_NOT_INSTALLED;
  242. return binder::Status::ok();
  243. }
  244. std::string boot_key;
  245. if (!GetInstallStatus(&boot_key)) {
  246. PLOG(ERROR) << "read " << kGsiInstallStatusFile;
  247. *_aidl_return = BOOT_STATUS_NOT_INSTALLED;
  248. return binder::Status::ok();
  249. }
  250. bool single_boot = !access(kGsiOneShotBootFile, F_OK);
  251. if (boot_key == kInstallStatusWipe) {
  252. // This overrides all other statuses.
  253. *_aidl_return = BOOT_STATUS_WILL_WIPE;
  254. } else if (boot_key == kInstallStatusDisabled) {
  255. // A single-boot GSI will have a "disabled" status, because it's
  256. // disabled immediately upon reading the one_shot_boot file. However,
  257. // we still want to return SINGLE_BOOT, because it makes the
  258. // transition clearer to the user.
  259. if (single_boot) {
  260. *_aidl_return = BOOT_STATUS_SINGLE_BOOT;
  261. } else {
  262. *_aidl_return = BOOT_STATUS_DISABLED;
  263. }
  264. } else if (single_boot) {
  265. *_aidl_return = BOOT_STATUS_SINGLE_BOOT;
  266. } else {
  267. *_aidl_return = BOOT_STATUS_ENABLED;
  268. }
  269. return binder::Status::ok();
  270. }
  271. binder::Status GsiService::getUserdataImageSize(int64_t* _aidl_return) {
  272. ENFORCE_SYSTEM;
  273. std::lock_guard<std::mutex> guard(main_lock_);
  274. *_aidl_return = -1;
  275. if (installing_) {
  276. // Size has already been computed.
  277. *_aidl_return = userdata_size_;
  278. } else if (IsGsiRunning()) {
  279. // :TODO: libdm
  280. unique_fd fd(open(kUserdataDevice, O_RDONLY | O_NOFOLLOW | O_CLOEXEC));
  281. if (fd < 0) {
  282. PLOG(ERROR) << "open " << kUserdataDevice;
  283. return binder::Status::ok();
  284. }
  285. int64_t size;
  286. if (ioctl(fd, BLKGETSIZE64, &size)) {
  287. PLOG(ERROR) << "BLKGETSIZE64 " << kUserdataDevice;
  288. return binder::Status::ok();
  289. }
  290. *_aidl_return = size;
  291. } else {
  292. // Stat the size of the userdata file.
  293. auto userdata_gsi = GetInstalledImagePath("userdata_gsi");
  294. struct stat s;
  295. if (stat(userdata_gsi.c_str(), &s)) {
  296. if (errno != ENOENT) {
  297. PLOG(ERROR) << "open " << userdata_gsi;
  298. return binder::Status::ok();
  299. }
  300. *_aidl_return = 0;
  301. } else {
  302. *_aidl_return = s.st_size;
  303. }
  304. }
  305. return binder::Status::ok();
  306. }
  307. binder::Status GsiService::getInstalledGsiImageDir(std::string* _aidl_return) {
  308. ENFORCE_SYSTEM;
  309. std::lock_guard<std::mutex> guard(main_lock_);
  310. if (IsGsiInstalled()) {
  311. *_aidl_return = GetInstalledImageDir();
  312. }
  313. return binder::Status::ok();
  314. }
  315. binder::Status GsiService::wipeGsiUserdata(int* _aidl_return) {
  316. ENFORCE_SYSTEM_OR_SHELL;
  317. std::lock_guard<std::mutex> guard(main_lock_);
  318. if (IsGsiRunning() || !IsGsiInstalled()) {
  319. *_aidl_return = IGsiService::INSTALL_ERROR_GENERIC;
  320. return binder::Status::ok();
  321. }
  322. *_aidl_return = WipeUserdata();
  323. return binder::Status::ok();
  324. }
  325. binder::Status GsiService::CheckUid(AccessLevel level) {
  326. std::vector<uid_t> allowed_uids{AID_ROOT, AID_SYSTEM};
  327. if (level == AccessLevel::SystemOrShell) {
  328. allowed_uids.push_back(AID_SHELL);
  329. }
  330. uid_t uid = IPCThreadState::self()->getCallingUid();
  331. for (const auto& allowed_uid : allowed_uids) {
  332. if (allowed_uid == uid) {
  333. return binder::Status::ok();
  334. }
  335. }
  336. auto message = StringPrintf("UID %d is not allowed", uid);
  337. return binder::Status::fromExceptionCode(binder::Status::EX_SECURITY,
  338. String8(message.c_str()));
  339. }
  340. void GsiService::PostInstallCleanup() {
  341. // This must be closed before unmapping partitions.
  342. system_writer_ = nullptr;
  343. const auto& dm = DeviceMapper::Instance();
  344. if (dm.GetState("userdata_gsi") != DmDeviceState::INVALID) {
  345. DestroyLogicalPartition("userdata_gsi", kDmTimeout);
  346. }
  347. if (dm.GetState("system_gsi") != DmDeviceState::INVALID) {
  348. DestroyLogicalPartition("system_gsi", kDmTimeout);
  349. }
  350. installing_ = false;
  351. partitions_ .clear();
  352. }
  353. static bool IsExternalStoragePath(const std::string& path) {
  354. if (!android::base::StartsWith(path, "/mnt/media_rw/")) {
  355. return false;
  356. }
  357. unique_fd fd(open(path.c_str(), O_RDONLY | O_CLOEXEC | O_NOFOLLOW));
  358. if (fd < 0) {
  359. PLOG(ERROR) << "open failed: " << path;
  360. return false;
  361. }
  362. struct statfs info;
  363. if (fstatfs(fd, &info)) {
  364. PLOG(ERROR) << "statfs failed: " << path;
  365. return false;
  366. }
  367. LOG(ERROR) << "fs type: " << info.f_type;
  368. return info.f_type == MSDOS_SUPER_MAGIC;
  369. }
  370. int GsiService::ValidateInstallParams(GsiInstallParams* params) {
  371. // If no install path was specified, use the default path. We also allow
  372. // specifying the top-level folder, and then we choose the correct location
  373. // underneath.
  374. if (params->installDir.empty() || params->installDir == "/data/gsi") {
  375. params->installDir = kDefaultGsiImageFolder;
  376. }
  377. // Normalize the path and add a trailing slash.
  378. std::string origInstallDir = params->installDir;
  379. if (!android::base::Realpath(origInstallDir, &params->installDir)) {
  380. PLOG(ERROR) << "realpath failed: " << origInstallDir;
  381. return INSTALL_ERROR_GENERIC;
  382. }
  383. // Ensure the path ends in / for consistency. Even though GetImagePath()
  384. // does this already, we want it to appear this way in install_dir.
  385. if (!android::base::EndsWith(params->installDir, "/")) {
  386. params->installDir += "/";
  387. }
  388. // Currently, we can only install to /data/gsi/ or external storage.
  389. if (IsExternalStoragePath(params->installDir)) {
  390. Fstab fstab;
  391. if (!ReadDefaultFstab(&fstab)) {
  392. LOG(ERROR) << "cannot read default fstab";
  393. return INSTALL_ERROR_GENERIC;
  394. }
  395. FstabEntry* system = GetEntryForMountPoint(&fstab, "/system");
  396. if (!system) {
  397. LOG(ERROR) << "cannot find /system fstab entry";
  398. return INSTALL_ERROR_GENERIC;
  399. }
  400. if (fs_mgr_verity_is_check_at_most_once(*system)) {
  401. LOG(ERROR) << "cannot install GSIs to external media if verity uses check_at_most_once";
  402. return INSTALL_ERROR_GENERIC;
  403. }
  404. } else if (params->installDir != kDefaultGsiImageFolder) {
  405. LOG(ERROR) << "cannot install GSI to " << params->installDir;
  406. return INSTALL_ERROR_GENERIC;
  407. }
  408. if (params->gsiSize % LP_SECTOR_SIZE) {
  409. LOG(ERROR) << "GSI size " << params->gsiSize << " is not a multiple of " << LP_SECTOR_SIZE;
  410. return INSTALL_ERROR_GENERIC;
  411. }
  412. if (params->userdataSize % LP_SECTOR_SIZE) {
  413. LOG(ERROR) << "userdata size " << params->userdataSize << " is not a multiple of "
  414. << LP_SECTOR_SIZE;
  415. return INSTALL_ERROR_GENERIC;
  416. }
  417. return INSTALL_OK;
  418. }
  419. int GsiService::StartInstall(const GsiInstallParams& params) {
  420. installing_ = true;
  421. userdata_block_size_ = 0;
  422. system_block_size_ = 0;
  423. gsi_size_ = params.gsiSize;
  424. userdata_size_ = (params.userdataSize) ? params.userdataSize : kDefaultUserdataSize;
  425. wipe_userdata_ = params.wipeUserdata;
  426. can_use_devicemapper_ = false;
  427. gsi_bytes_written_ = 0;
  428. install_dir_ = params.installDir;
  429. userdata_gsi_path_ = GetImagePath(install_dir_, "userdata_gsi");
  430. system_gsi_path_ = GetImagePath(install_dir_, "system_gsi");
  431. // Only rm userdata_gsi if one didn't already exist.
  432. wipe_userdata_on_failure_ = wipe_userdata_ || access(userdata_gsi_path_.c_str(), F_OK);
  433. if (int status = PerformSanityChecks()) {
  434. return status;
  435. }
  436. if (int status = PreallocateFiles()) {
  437. return status;
  438. }
  439. if (int status = DetermineReadWriteMethod()) {
  440. return status;
  441. }
  442. if (!FormatUserdata()) {
  443. return INSTALL_ERROR_GENERIC;
  444. }
  445. // Map system_gsi so we can write to it.
  446. system_writer_ = OpenPartition("system_gsi");
  447. if (!system_writer_) {
  448. return INSTALL_ERROR_GENERIC;
  449. }
  450. return INSTALL_OK;
  451. }
  452. int GsiService::DetermineReadWriteMethod() {
  453. // If there is a device-mapper node wrapping the block device, then we're
  454. // able to create another node around it; the dm layer does not carry the
  455. // exclusion lock down the stack when a mount occurs.
  456. //
  457. // If there is no intermediate device-mapper node, then partitions cannot be
  458. // opened writable due to sepolicy and exclusivity of having a mounted
  459. // filesystem. This should only happen on devices with no encryption, or
  460. // devices with FBE and no metadata encryption. For these cases it suffices
  461. // to perform normal file writes to /data/gsi (which is unencrypted).
  462. std::string block_device;
  463. if (!FiemapWriter::GetBlockDeviceForFile(system_gsi_path_.c_str(), &block_device,
  464. &can_use_devicemapper_)) {
  465. return INSTALL_ERROR_GENERIC;
  466. }
  467. if (install_dir_ != kDefaultGsiImageFolder && can_use_devicemapper_) {
  468. // Never use device-mapper on external media. We don't support adopted
  469. // storage yet, and accidentally using device-mapper could be dangerous
  470. // as we hardcode the userdata device as backing storage.
  471. LOG(ERROR) << "unexpected device-mapper node used to mount external media";
  472. return INSTALL_ERROR_GENERIC;
  473. }
  474. return INSTALL_OK;
  475. }
  476. std::string GsiService::GetImagePath(const std::string& image_dir, const std::string& name) {
  477. std::string dir = image_dir;
  478. if (!android::base::EndsWith(dir, "/")) {
  479. dir += "/";
  480. }
  481. return dir + name + ".img";
  482. }
  483. std::string GsiService::GetInstalledImageDir() {
  484. // If there's no install left, just return /data/gsi since that's where
  485. // installs go by default.
  486. std::string dir;
  487. if (android::base::ReadFileToString(kGsiInstallDirFile, &dir)) {
  488. return dir;
  489. }
  490. return kDefaultGsiImageFolder;
  491. }
  492. std::string GsiService::GetInstalledImagePath(const std::string& name) {
  493. return GetImagePath(GetInstalledImageDir(), name);
  494. }
  495. int GsiService::PerformSanityChecks() {
  496. if (gsi_size_ < 0) {
  497. LOG(ERROR) << "image size " << gsi_size_ << " is negative";
  498. return INSTALL_ERROR_GENERIC;
  499. }
  500. if (android::gsi::IsGsiRunning()) {
  501. LOG(ERROR) << "cannot install gsi inside a live gsi";
  502. return INSTALL_ERROR_GENERIC;
  503. }
  504. struct statvfs sb;
  505. if (statvfs(install_dir_.c_str(), &sb)) {
  506. PLOG(ERROR) << "failed to read file system stats";
  507. return INSTALL_ERROR_GENERIC;
  508. }
  509. // This is the same as android::vold::GetFreebytes() but we also
  510. // need the total file system size so we open code it here.
  511. uint64_t free_space = 1ULL * sb.f_bavail * sb.f_frsize;
  512. uint64_t fs_size = sb.f_blocks * sb.f_frsize;
  513. if (free_space <= (gsi_size_ + userdata_size_)) {
  514. LOG(ERROR) << "not enough free space (only " << free_space << " bytes available)";
  515. return INSTALL_ERROR_NO_SPACE;
  516. }
  517. // We are asking for 40% of the /data to be empty.
  518. // TODO: may be not hard code it like this
  519. double free_space_percent = ((1.0 * free_space) / fs_size) * 100;
  520. if (free_space_percent < kMinimumFreeSpaceThreshold) {
  521. LOG(ERROR) << "free space " << static_cast<uint64_t>(free_space_percent)
  522. << "% is below the minimum threshold of " << kMinimumFreeSpaceThreshold << "%";
  523. return INSTALL_ERROR_FILE_SYSTEM_CLUTTERED;
  524. }
  525. return INSTALL_OK;
  526. }
  527. int GsiService::PreallocateFiles() {
  528. if (wipe_userdata_) {
  529. SplitFiemap::RemoveSplitFiles(userdata_gsi_path_);
  530. }
  531. SplitFiemap::RemoveSplitFiles(system_gsi_path_);
  532. // TODO: trigger GC from fiemap writer.
  533. // Create fallocated files.
  534. if (int status = PreallocateUserdata()) {
  535. return status;
  536. }
  537. if (int status = PreallocateSystem()) {
  538. return status;
  539. }
  540. // Save the extent information in liblp.
  541. metadata_ = CreateMetadata();
  542. if (!metadata_) {
  543. return INSTALL_ERROR_GENERIC;
  544. }
  545. UpdateProgress(STATUS_COMPLETE, 0);
  546. return INSTALL_OK;
  547. }
  548. int GsiService::PreallocateUserdata() {
  549. int error;
  550. std::unique_ptr<SplitFiemap> userdata_image;
  551. if (wipe_userdata_ || access(userdata_gsi_path_.c_str(), F_OK)) {
  552. StartAsyncOperation("create userdata", userdata_size_);
  553. userdata_image = CreateFiemapWriter(userdata_gsi_path_, userdata_size_, &error);
  554. if (!userdata_image) {
  555. LOG(ERROR) << "Could not create userdata image: " << userdata_gsi_path_;
  556. return error;
  557. }
  558. // Signal that we need to reformat userdata.
  559. wipe_userdata_ = true;
  560. } else {
  561. userdata_image = CreateFiemapWriter(userdata_gsi_path_, 0, &error);
  562. if (!userdata_image) {
  563. LOG(ERROR) << "Could not open userdata image: " << userdata_gsi_path_;
  564. return error;
  565. }
  566. if (userdata_size_ && userdata_image->size() < userdata_size_) {
  567. // :TODO: need to fallocate more blocks and resizefs.
  568. }
  569. userdata_size_ = userdata_image->size();
  570. }
  571. userdata_block_size_ = userdata_image->block_size();
  572. Image image = {
  573. .writer = std::move(userdata_image),
  574. .actual_size = userdata_size_,
  575. };
  576. partitions_.emplace(std::make_pair("userdata_gsi", std::move(image)));
  577. return INSTALL_OK;
  578. }
  579. int GsiService::PreallocateSystem() {
  580. StartAsyncOperation("create system", gsi_size_);
  581. int error;
  582. auto system_image = CreateFiemapWriter(system_gsi_path_, gsi_size_, &error);
  583. if (!system_image) {
  584. return error;
  585. }
  586. system_block_size_ = system_image->block_size();
  587. Image image = {
  588. .writer = std::move(system_image),
  589. .actual_size = gsi_size_,
  590. };
  591. partitions_.emplace(std::make_pair("system_gsi", std::move(image)));
  592. return INSTALL_OK;
  593. }
  594. std::unique_ptr<SplitFiemap> GsiService::CreateFiemapWriter(const std::string& path,
  595. uint64_t size, int* error) {
  596. bool create = (size != 0);
  597. std::function<bool(uint64_t, uint64_t)> progress;
  598. if (create) {
  599. // TODO: allow cancelling inside cancelGsiInstall.
  600. progress = [this](uint64_t bytes, uint64_t /* total */) -> bool {
  601. UpdateProgress(STATUS_WORKING, bytes);
  602. if (should_abort_) return false;
  603. return true;
  604. };
  605. }
  606. std::unique_ptr<SplitFiemap> file;
  607. if (!size) {
  608. file = SplitFiemap::Open(path);
  609. } else {
  610. file = SplitFiemap::Create(path, size, 0, std::move(progress));
  611. }
  612. if (!file) {
  613. LOG(ERROR) << "failed to create or open " << path;
  614. *error = INSTALL_ERROR_GENERIC;
  615. return nullptr;
  616. }
  617. uint64_t extents = file->extents().size();
  618. if (extents > kMaximumExtents) {
  619. LOG(ERROR) << "file " << path << " has too many extents: " << extents;
  620. *error = INSTALL_ERROR_FILE_SYSTEM_CLUTTERED;
  621. return nullptr;
  622. }
  623. return file;
  624. }
  625. // Write data through an fd.
  626. class FdWriter final : public GsiService::WriteHelper {
  627. public:
  628. FdWriter(const std::string& path, unique_fd&& fd) : path_(path), fd_(std::move(fd)) {}
  629. bool Write(const void* data, uint64_t bytes) override {
  630. return android::base::WriteFully(fd_, data, bytes);
  631. }
  632. bool Flush() override {
  633. if (fsync(fd_)) {
  634. PLOG(ERROR) << "fsync failed: " << path_;
  635. return false;
  636. }
  637. return true;
  638. }
  639. uint64_t Size() override { return get_block_device_size(fd_); }
  640. private:
  641. std::string path_;
  642. unique_fd fd_;
  643. };
  644. // Write data through a SplitFiemap.
  645. class SplitFiemapWriter final : public GsiService::WriteHelper {
  646. public:
  647. explicit SplitFiemapWriter(SplitFiemap* writer) : writer_(writer) {}
  648. bool Write(const void* data, uint64_t bytes) override {
  649. return writer_->Write(data, bytes);
  650. }
  651. bool Flush() override {
  652. return writer_->Flush();
  653. }
  654. uint64_t Size() override { return writer_->size(); }
  655. private:
  656. SplitFiemap* writer_;
  657. };
  658. std::unique_ptr<GsiService::WriteHelper> GsiService::OpenPartition(const std::string& name) {
  659. if (can_use_devicemapper_) {
  660. std::string path;
  661. if (!CreateLogicalPartition(kUserdataDevice, *metadata_.get(), name, true, kDmTimeout,
  662. &path)) {
  663. LOG(ERROR) << "Error creating device-mapper node for " << name;
  664. return {};
  665. }
  666. static const int kOpenFlags = O_RDWR | O_NOFOLLOW | O_CLOEXEC;
  667. unique_fd fd(open(path.c_str(), kOpenFlags));
  668. if (fd < 0) {
  669. PLOG(ERROR) << "could not open " << path;
  670. }
  671. return std::make_unique<FdWriter>(GetImagePath(install_dir_, name), std::move(fd));
  672. }
  673. auto iter = partitions_.find(name);
  674. if (iter == partitions_.end()) {
  675. LOG(ERROR) << "could not find partition " << name;
  676. return {};
  677. }
  678. return std::make_unique<SplitFiemapWriter>(iter->second.writer.get());
  679. }
  680. bool GsiService::CommitGsiChunk(int stream_fd, int64_t bytes) {
  681. StartAsyncOperation("write gsi", gsi_size_);
  682. if (bytes < 0) {
  683. LOG(ERROR) << "chunk size " << bytes << " is negative";
  684. return false;
  685. }
  686. auto buffer = std::make_unique<char[]>(system_block_size_);
  687. int progress = -1;
  688. uint64_t remaining = bytes;
  689. while (remaining) {
  690. // :TODO: check file pin status!
  691. size_t max_to_read = std::min(system_block_size_, remaining);
  692. ssize_t rv = TEMP_FAILURE_RETRY(read(stream_fd, buffer.get(), max_to_read));
  693. if (rv < 0) {
  694. PLOG(ERROR) << "read gsi chunk";
  695. return false;
  696. }
  697. if (rv == 0) {
  698. LOG(ERROR) << "no bytes left in stream";
  699. return false;
  700. }
  701. if (!CommitGsiChunk(buffer.get(), rv)) {
  702. return false;
  703. }
  704. CHECK(static_cast<uint64_t>(rv) <= remaining);
  705. remaining -= rv;
  706. // Only update the progress when the % (or permille, in this case)
  707. // significantly changes.
  708. int new_progress = ((gsi_size_ - remaining) * 1000) / gsi_size_;
  709. if (new_progress != progress) {
  710. UpdateProgress(STATUS_WORKING, gsi_size_ - remaining);
  711. }
  712. }
  713. UpdateProgress(STATUS_COMPLETE, gsi_size_);
  714. return true;
  715. }
  716. bool GsiService::CommitGsiChunk(const void* data, size_t bytes) {
  717. if (!installing_) {
  718. LOG(ERROR) << "no gsi installation in progress";
  719. return false;
  720. }
  721. if (static_cast<uint64_t>(bytes) > gsi_size_ - gsi_bytes_written_) {
  722. // We cannot write past the end of the image file.
  723. LOG(ERROR) << "chunk size " << bytes << " exceeds remaining image size (" << gsi_size_
  724. << " expected, " << gsi_bytes_written_ << " written)";
  725. return false;
  726. }
  727. if (!system_writer_->Write(data, bytes)) {
  728. PLOG(ERROR) << "write failed";
  729. return false;
  730. }
  731. gsi_bytes_written_ += bytes;
  732. return true;
  733. }
  734. int GsiService::SetGsiBootable(bool one_shot) {
  735. if (gsi_bytes_written_ != gsi_size_) {
  736. // We cannot boot if the image is incomplete.
  737. LOG(ERROR) << "image incomplete; expected " << gsi_size_ << " bytes, waiting for "
  738. << (gsi_size_ - gsi_bytes_written_) << " bytes";
  739. return INSTALL_ERROR_GENERIC;
  740. }
  741. if (!system_writer_->Flush()) {
  742. return INSTALL_ERROR_GENERIC;
  743. }
  744. // If files moved (are no longer pinned), the metadata file will be invalid.
  745. for (const auto& [name, image] : partitions_) {
  746. if (!image.writer->HasPinnedExtents()) {
  747. LOG(ERROR) << name << " no longer has pinned extents";
  748. return INSTALL_ERROR_GENERIC;
  749. }
  750. }
  751. // Remember the installation directory.
  752. if (!android::base::WriteStringToFile(install_dir_, kGsiInstallDirFile)) {
  753. PLOG(ERROR) << "write failed: " << kGsiInstallDirFile;
  754. return INSTALL_ERROR_GENERIC;
  755. }
  756. // Note: create the install status file last, since this is the actual boot
  757. // indicator.
  758. if (!CreateMetadataFile() || !SetBootMode(one_shot) || !CreateInstallStatusFile()) {
  759. return INSTALL_ERROR_GENERIC;
  760. }
  761. return INSTALL_OK;
  762. }
  763. int GsiService::ReenableGsi(bool one_shot) {
  764. if (!android::gsi::IsGsiInstalled()) {
  765. LOG(ERROR) << "no gsi installed - cannot re-enable";
  766. return INSTALL_ERROR_GENERIC;
  767. }
  768. std::string boot_key;
  769. if (!GetInstallStatus(&boot_key)) {
  770. PLOG(ERROR) << "read " << kGsiInstallStatusFile;
  771. return INSTALL_ERROR_GENERIC;
  772. }
  773. if (boot_key != kInstallStatusDisabled) {
  774. LOG(ERROR) << "GSI is not currently disabled";
  775. return INSTALL_ERROR_GENERIC;
  776. }
  777. if (IsGsiRunning()) {
  778. if (!SetBootMode(one_shot) || !CreateInstallStatusFile()) {
  779. return INSTALL_ERROR_GENERIC;
  780. }
  781. return INSTALL_OK;
  782. }
  783. // Note: this metadata is only used to recover the original partition sizes.
  784. // We do not trust the extent information, which will get rebuilt later.
  785. auto old_metadata = ReadFromImageFile(kGsiLpMetadataFile);
  786. if (!old_metadata) {
  787. LOG(ERROR) << "GSI install is incomplete";
  788. return INSTALL_ERROR_GENERIC;
  789. }
  790. // Set up enough installer state so that we can use various helper
  791. // methods.
  792. //
  793. // TODO(dvander) Extract all of the installer state into a separate
  794. // class so this is more manageable.
  795. install_dir_ = GetInstalledImageDir();
  796. system_gsi_path_ = GetImagePath(install_dir_, "system_gsi");
  797. if (int error = DetermineReadWriteMethod()) {
  798. return error;
  799. }
  800. // Recover parition information.
  801. Image userdata_image;
  802. if (int error = GetExistingImage(*old_metadata.get(), "userdata_gsi", &userdata_image)) {
  803. return error;
  804. }
  805. partitions_.emplace(std::make_pair("userdata_gsi", std::move(userdata_image)));
  806. Image system_image;
  807. if (int error = GetExistingImage(*old_metadata.get(), "system_gsi", &system_image)) {
  808. return error;
  809. }
  810. partitions_.emplace(std::make_pair("system_gsi", std::move(system_image)));
  811. metadata_ = CreateMetadata();
  812. if (!metadata_) {
  813. return INSTALL_ERROR_GENERIC;
  814. }
  815. if (!CreateMetadataFile() || !SetBootMode(one_shot) || !CreateInstallStatusFile()) {
  816. return INSTALL_ERROR_GENERIC;
  817. }
  818. return INSTALL_OK;
  819. }
  820. int GsiService::WipeUserdata() {
  821. // Note: this metadata is only used to recover the original partition sizes.
  822. // We do not trust the extent information, which will get rebuilt later.
  823. auto old_metadata = ReadFromImageFile(kGsiLpMetadataFile);
  824. if (!old_metadata) {
  825. LOG(ERROR) << "GSI install is incomplete";
  826. return INSTALL_ERROR_GENERIC;
  827. }
  828. install_dir_ = GetInstalledImageDir();
  829. system_gsi_path_ = GetImagePath(install_dir_, "system_gsi");
  830. if (int error = DetermineReadWriteMethod()) {
  831. return error;
  832. }
  833. // Recover parition information.
  834. Image userdata_image;
  835. if (int error = GetExistingImage(*old_metadata.get(), "userdata_gsi", &userdata_image)) {
  836. return error;
  837. }
  838. partitions_.emplace(std::make_pair("userdata_gsi", std::move(userdata_image)));
  839. metadata_ = CreateMetadata();
  840. if (!metadata_) {
  841. return INSTALL_ERROR_GENERIC;
  842. }
  843. auto writer = OpenPartition("userdata_gsi");
  844. if (!writer) {
  845. return IGsiService::INSTALL_ERROR_GENERIC;
  846. }
  847. // Wipe the first 1MiB of the device, ensuring both the first block and
  848. // the superblock are destroyed.
  849. static constexpr uint64_t kEraseSize = 1024 * 1024;
  850. std::string zeroes(4096, 0);
  851. uint64_t erase_size = std::min(kEraseSize, writer->Size());
  852. for (uint64_t i = 0; i < erase_size; i += zeroes.size()) {
  853. if (!writer->Write(zeroes.data(), zeroes.size())) {
  854. PLOG(ERROR) << "write userdata_gsi";
  855. return IGsiService::INSTALL_ERROR_GENERIC;
  856. }
  857. }
  858. return INSTALL_OK;
  859. }
  860. static uint64_t GetPartitionSize(const LpMetadata& metadata, const LpMetadataPartition& partition) {
  861. uint64_t total = 0;
  862. for (size_t i = 0; i < partition.num_extents; i++) {
  863. const auto& extent = metadata.extents[partition.first_extent_index + i];
  864. if (extent.target_type != LP_TARGET_TYPE_LINEAR) {
  865. LOG(ERROR) << "non-linear extent detected";
  866. return 0;
  867. }
  868. total += extent.num_sectors * LP_SECTOR_SIZE;
  869. }
  870. return total;
  871. }
  872. static uint64_t GetPartitionSize(const LpMetadata& metadata, const std::string& name) {
  873. for (const auto& partition : metadata.partitions) {
  874. if (GetPartitionName(partition) == name) {
  875. return GetPartitionSize(metadata, partition);
  876. }
  877. }
  878. return 0;
  879. }
  880. int GsiService::GetExistingImage(const LpMetadata& metadata, const std::string& name,
  881. Image* image) {
  882. int error;
  883. std::string path = GetInstalledImagePath(name);
  884. auto writer = CreateFiemapWriter(path.c_str(), 0, &error);
  885. if (!writer) {
  886. return error;
  887. }
  888. // Even after recovering the FIEMAP, we also need to know the exact intended
  889. // size of the image, since FiemapWriter may have extended the final block.
  890. uint64_t actual_size = GetPartitionSize(metadata, name);
  891. if (!actual_size) {
  892. LOG(ERROR) << "Could not determine the pre-existing size of " << name;
  893. return INSTALL_ERROR_GENERIC;
  894. }
  895. image->writer = std::move(writer);
  896. image->actual_size = actual_size;
  897. return INSTALL_OK;
  898. }
  899. bool GsiService::RemoveGsiFiles(const std::string& install_dir, bool wipeUserdata) {
  900. bool ok = true;
  901. std::string message;
  902. if (!SplitFiemap::RemoveSplitFiles(GetImagePath(install_dir, "system_gsi"), &message)) {
  903. LOG(ERROR) << message;
  904. ok = false;
  905. }
  906. if (wipeUserdata &&
  907. !SplitFiemap::RemoveSplitFiles(GetImagePath(install_dir, "userdata_gsi"), &message)) {
  908. LOG(ERROR) << message;
  909. ok = false;
  910. }
  911. std::vector<std::string> files{
  912. kGsiInstallStatusFile,
  913. kGsiLpMetadataFile,
  914. kGsiOneShotBootFile,
  915. kGsiInstallDirFile,
  916. };
  917. for (const auto& file : files) {
  918. if (!android::base::RemoveFileIfExists(file, &message)) {
  919. LOG(ERROR) << message;
  920. ok = false;
  921. }
  922. }
  923. return ok;
  924. }
  925. bool GsiService::DisableGsiInstall() {
  926. if (!android::gsi::IsGsiInstalled()) {
  927. LOG(ERROR) << "cannot disable gsi install - no install detected";
  928. return false;
  929. }
  930. if (installing_) {
  931. LOG(ERROR) << "cannot disable gsi during GSI installation";
  932. return false;
  933. }
  934. if (!DisableGsi()) {
  935. PLOG(ERROR) << "could not write gsi status";
  936. return false;
  937. }
  938. return true;
  939. }
  940. std::unique_ptr<LpMetadata> GsiService::CreateMetadata() {
  941. std::string data_device_path;
  942. if (install_dir_ == kDefaultGsiImageFolder && !access(kUserdataDevice, F_OK)) {
  943. data_device_path = kUserdataDevice;
  944. } else {
  945. auto writer = partitions_["system_gsi"].writer.get();
  946. data_device_path = writer->bdev_path();
  947. }
  948. auto data_device_name = android::base::Basename(data_device_path);
  949. PartitionOpener opener;
  950. BlockDeviceInfo data_device_info;
  951. if (!opener.GetInfo(data_device_path, &data_device_info)) {
  952. LOG(ERROR) << "Error reading userdata partition";
  953. return nullptr;
  954. }
  955. std::vector<BlockDeviceInfo> block_devices = {data_device_info};
  956. auto builder = MetadataBuilder::New(block_devices, data_device_name, 128 * 1024, 1);
  957. if (!builder) {
  958. LOG(ERROR) << "Error creating metadata builder";
  959. return nullptr;
  960. }
  961. builder->IgnoreSlotSuffixing();
  962. for (const auto& [name, image] : partitions_) {
  963. uint32_t flags = LP_PARTITION_ATTR_NONE;
  964. if (name == "system_gsi") {
  965. flags |= LP_PARTITION_ATTR_READONLY;
  966. }
  967. Partition* partition = builder->AddPartition(name, flags);
  968. if (!partition) {
  969. LOG(ERROR) << "Error adding " << name << " to partition table";
  970. return nullptr;
  971. }
  972. if (!AddPartitionFiemap(builder.get(), partition, image, data_device_name)) {
  973. return nullptr;
  974. }
  975. }
  976. auto metadata = builder->Export();
  977. if (!metadata) {
  978. LOG(ERROR) << "Error exporting partition table";
  979. return nullptr;
  980. }
  981. return metadata;
  982. }
  983. bool GsiService::CreateMetadataFile() {
  984. if (!WriteToImageFile(kGsiLpMetadataFile, *metadata_.get())) {
  985. LOG(ERROR) << "Error writing GSI partition table image";
  986. return false;
  987. }
  988. return true;
  989. }
  990. bool GsiService::FormatUserdata() {
  991. auto writer = OpenPartition("userdata_gsi");
  992. if (!writer) {
  993. return false;
  994. }
  995. // libcutils checks the first 4K, no matter the block size.
  996. std::string zeroes(4096, 0);
  997. if (!writer->Write(zeroes.data(), zeroes.size())) {
  998. PLOG(ERROR) << "write userdata_gsi";
  999. return false;
  1000. }
  1001. return true;
  1002. }
  1003. bool GsiService::AddPartitionFiemap(MetadataBuilder* builder, Partition* partition,
  1004. const Image& image, const std::string& block_device) {
  1005. uint64_t sectors_needed = image.actual_size / LP_SECTOR_SIZE;
  1006. for (const auto& extent : image.writer->extents()) {
  1007. // :TODO: block size check for length, not sector size
  1008. if (extent.fe_length % LP_SECTOR_SIZE != 0) {
  1009. LOG(ERROR) << "Extent is not sector-aligned: " << extent.fe_length;
  1010. return false;
  1011. }
  1012. if (extent.fe_physical % LP_SECTOR_SIZE != 0) {
  1013. LOG(ERROR) << "Extent physical sector is not sector-aligned: " << extent.fe_physical;
  1014. return false;
  1015. }
  1016. uint64_t num_sectors =
  1017. std::min(static_cast<uint64_t>(extent.fe_length / LP_SECTOR_SIZE), sectors_needed);
  1018. if (!num_sectors || !sectors_needed) {
  1019. // This should never happen, but we include it just in case. It would
  1020. // indicate that the last filesystem block had multiple extents.
  1021. LOG(WARNING) << "FiemapWriter allocated extra blocks";
  1022. break;
  1023. }
  1024. uint64_t physical_sector = extent.fe_physical / LP_SECTOR_SIZE;
  1025. if (!builder->AddLinearExtent(partition, block_device, num_sectors, physical_sector)) {
  1026. LOG(ERROR) << "Could not add extent to lp metadata";
  1027. return false;
  1028. }
  1029. sectors_needed -= num_sectors;
  1030. }
  1031. return true;
  1032. }
  1033. bool GsiService::SetBootMode(bool one_shot) {
  1034. if (one_shot) {
  1035. if (!android::base::WriteStringToFile("1", kGsiOneShotBootFile)) {
  1036. PLOG(ERROR) << "write " << kGsiOneShotBootFile;
  1037. return false;
  1038. }
  1039. } else if (!access(kGsiOneShotBootFile, F_OK)) {
  1040. std::string error;
  1041. if (!android::base::RemoveFileIfExists(kGsiOneShotBootFile, &error)) {
  1042. LOG(ERROR) << error;
  1043. return false;
  1044. }
  1045. }
  1046. return true;
  1047. }
  1048. bool GsiService::CreateInstallStatusFile() {
  1049. if (!android::base::WriteStringToFile("0", kGsiInstallStatusFile)) {
  1050. PLOG(ERROR) << "write " << kGsiInstallStatusFile;
  1051. return false;
  1052. }
  1053. return true;
  1054. }
  1055. void GsiService::RunStartupTasks() {
  1056. if (!IsGsiInstalled()) {
  1057. return;
  1058. }
  1059. std::string boot_key;
  1060. if (!GetInstallStatus(&boot_key)) {
  1061. PLOG(ERROR) << "read " << kGsiInstallStatusFile;
  1062. return;
  1063. }
  1064. if (!IsGsiRunning()) {
  1065. // Check if a wipe was requested from fastboot or adb-in-gsi.
  1066. if (boot_key == kInstallStatusWipe) {
  1067. RemoveGsiFiles(GetInstalledImageDir(), true /* wipeUserdata */);
  1068. }
  1069. } else {
  1070. // NB: When single-boot is enabled, init will write "disabled" into the
  1071. // install_status file, which will cause GetBootAttempts to return
  1072. // false. Thus, we won't write "ok" here.
  1073. int ignore;
  1074. if (GetBootAttempts(boot_key, &ignore)) {
  1075. // Mark the GSI as having successfully booted.
  1076. if (!android::base::WriteStringToFile(kInstallStatusOk, kGsiInstallStatusFile)) {
  1077. PLOG(ERROR) << "write " << kGsiInstallStatusFile;
  1078. }
  1079. }
  1080. }
  1081. }
  1082. } // namespace gsi
  1083. } // namespace android