• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <iostream>
17 #include <string_view>
18 
19 #include <android-base/logging.h>
20 #include <android-base/parsebool.h>
21 #include <android-base/parseint.h>
22 #include <android-base/strings.h>
23 #include <gflags/gflags.h>
24 
25 #include "common/libs/fs/shared_buf.h"
26 #include "common/libs/fs/shared_fd.h"
27 #include "common/libs/utils/contains.h"
28 #include "common/libs/utils/environment.h"
29 #include "common/libs/utils/files.h"
30 #include "common/libs/utils/flag_parser.h"
31 #include "common/libs/utils/tee_logging.h"
32 #include "host/commands/assemble_cvd/clean.h"
33 #include "host/commands/assemble_cvd/disk_flags.h"
34 #include "host/commands/assemble_cvd/display.h"
35 #include "host/commands/assemble_cvd/flag_feature.h"
36 #include "host/commands/assemble_cvd/flags.h"
37 #include "host/commands/assemble_cvd/flags_defaults.h"
38 #include "host/commands/assemble_cvd/touchpad.h"
39 #include "host/libs/command_util/snapshot_utils.h"
40 #include "host/libs/config/adb/adb.h"
41 #include "host/libs/config/config_flag.h"
42 #include "host/libs/config/custom_actions.h"
43 #include "host/libs/config/fastboot/fastboot.h"
44 #include "host/libs/config/fetcher_config.h"
45 #include "host/libs/config/inject.h"
46 
47 using cuttlefish::StringFromEnv;
48 
49 DEFINE_string(assembly_dir, CF_DEFAULTS_ASSEMBLY_DIR,
50               "A directory to put generated files common between instances");
51 DEFINE_string(instance_dir, CF_DEFAULTS_INSTANCE_DIR,
52               "This is a directory that will hold the cuttlefish generated"
53               "files, including both instance-specific and common files");
54 DEFINE_string(snapshot_path, "",
55               "Path to snapshot. Must not be empty if the device is to be "
56               "restored from a snapshot");
57 DEFINE_bool(resume, CF_DEFAULTS_RESUME,
58             "Resume using the disk from the last session, if "
59             "possible. i.e., if --noresume is passed, the disk "
60             "will be reset to the state it was initially launched "
61             "in. This flag is ignored if the underlying partition "
62             "images have been updated since the first launch."
63             "If the device starts from a snapshot, this will be always true.");
64 
65 DECLARE_bool(use_overlay);
66 
67 namespace cuttlefish {
68 namespace {
69 
70 static constexpr std::string_view kFetcherConfigFile = "fetcher_config.json";
71 
FindFetcherConfig(const std::vector<std::string> & files)72 FetcherConfig FindFetcherConfig(const std::vector<std::string>& files) {
73   FetcherConfig fetcher_config;
74   for (const auto& file : files) {
75     if (android::base::EndsWith(file, kFetcherConfigFile)) {
76       std::string home_directory = StringFromEnv("HOME", CurrentDirectory());
77       std::string fetcher_file = file;
78       if (!FileExists(file) &&
79           FileExists(home_directory + "/" + fetcher_file)) {
80         LOG(INFO) << "Found " << fetcher_file << " in HOME directory ('"
81                   << home_directory << "') and not current working directory";
82         fetcher_file = home_directory + "/" + fetcher_file;
83       }
84 
85       if (fetcher_config.LoadFromFile(fetcher_file)) {
86         return fetcher_config;
87       }
88       LOG(ERROR) << "Could not load fetcher config file.";
89     }
90   }
91   LOG(DEBUG) << "Could not locate fetcher config file.";
92   return fetcher_config;
93 }
94 
GetLegacyConfigFilePath(const CuttlefishConfig & config)95 std::string GetLegacyConfigFilePath(const CuttlefishConfig& config) {
96   return config.ForDefaultInstance().PerInstancePath("cuttlefish_config.json");
97 }
98 
SaveConfig(const CuttlefishConfig & tmp_config_obj)99 Result<void> SaveConfig(const CuttlefishConfig& tmp_config_obj) {
100   auto config_file = GetConfigFilePath(tmp_config_obj);
101   auto config_link = GetGlobalConfigFileLink();
102   // Save the config object before starting any host process
103   CF_EXPECT(tmp_config_obj.SaveToFile(config_file),
104             "Failed to save to \"" << config_file << "\"");
105   auto legacy_config_file = GetLegacyConfigFilePath(tmp_config_obj);
106   CF_EXPECT(tmp_config_obj.SaveToFile(legacy_config_file),
107             "Failed to save to \"" << legacy_config_file << "\"");
108 
109   setenv(kCuttlefishConfigEnvVarName, config_file.c_str(), true);
110   if (symlink(config_file.c_str(), config_link.c_str()) != 0) {
111     return CF_ERRNO("symlink(\"" << config_file << "\", \"" << config_link
112                                  << ") failed");
113   }
114 
115   return {};
116 }
117 
118 #ifndef O_TMPFILE
119 # define O_TMPFILE (020000000 | O_DIRECTORY)
120 #endif
121 
CreateLegacySymlinks(const CuttlefishConfig::InstanceSpecific & instance,const CuttlefishConfig::EnvironmentSpecific & environment)122 Result<void> CreateLegacySymlinks(
123     const CuttlefishConfig::InstanceSpecific& instance,
124     const CuttlefishConfig::EnvironmentSpecific& environment) {
125   std::string log_files[] = {"kernel.log",
126                              "launcher.log",
127                              "logcat",
128                              "metrics.log",
129                              "modem_simulator.log",
130                              "crosvm_openwrt.log",
131                              "crosvm_openwrt_boot.log"};
132   for (const auto& log_file : log_files) {
133     auto symlink_location = instance.PerInstancePath(log_file.c_str());
134     auto log_target = "logs/" + log_file;  // Relative path
135     if (FileExists(symlink_location, /* follow_symlinks */ false)) {
136       CF_EXPECT(RemoveFile(symlink_location),
137                 "Failed to remove symlink " << symlink_location);
138     }
139     if (symlink(log_target.c_str(), symlink_location.c_str()) != 0) {
140       return CF_ERRNO("symlink(\"" << log_target << ", " << symlink_location
141                                    << ") failed");
142     }
143   }
144 
145   std::stringstream legacy_instance_path_stream;
146   legacy_instance_path_stream << FLAGS_instance_dir;
147   if (gflags::GetCommandLineFlagInfoOrDie("instance_dir").is_default) {
148     legacy_instance_path_stream << "_runtime";
149   }
150   legacy_instance_path_stream << "." << instance.id();
151   auto legacy_instance_path = legacy_instance_path_stream.str();
152 
153   if (DirectoryExists(legacy_instance_path, /* follow_symlinks */ false)) {
154     CF_EXPECT(RecursivelyRemoveDirectory(legacy_instance_path));
155   } else if (FileExists(legacy_instance_path, /* follow_symlinks */ false)) {
156     CF_EXPECT(RemoveFile(legacy_instance_path),
157               "Failed to remove instance_dir symlink " << legacy_instance_path);
158   }
159   if (symlink(instance.instance_dir().c_str(), legacy_instance_path.c_str())) {
160     return CF_ERRNO("symlink(\"" << instance.instance_dir() << "\", \""
161                                  << legacy_instance_path << "\") failed");
162   }
163 
164   const auto mac80211_uds_name = "vhost_user_mac80211";
165 
166   const auto mac80211_uds_path =
167       environment.PerEnvironmentUdsPath(mac80211_uds_name);
168   const auto legacy_mac80211_uds_path =
169       instance.PerInstanceInternalPath(mac80211_uds_name);
170 
171   if (symlink(mac80211_uds_path.c_str(), legacy_mac80211_uds_path.c_str())) {
172     return CF_ERRNO("symlink(\"" << mac80211_uds_path << "\", \""
173                                  << legacy_mac80211_uds_path << "\") failed");
174   }
175 
176   return {};
177 }
178 
RestoreHostFiles(const std::string & cuttlefish_root_dir,const std::string & snapshot_dir_path)179 Result<void> RestoreHostFiles(const std::string& cuttlefish_root_dir,
180                               const std::string& snapshot_dir_path) {
181   const auto meta_json_path = SnapshotMetaJsonPath(snapshot_dir_path);
182 
183   auto guest_snapshot_dirs =
184       CF_EXPECT(GuestSnapshotDirectories(snapshot_dir_path));
185   auto filter_guest_dir =
186       [&guest_snapshot_dirs](const std::string& src_dir) -> bool {
187     return !Contains(guest_snapshot_dirs, src_dir);
188   };
189   // cp -r snapshot_dir_path HOME
190   CF_EXPECT(CopyDirectoryRecursively(snapshot_dir_path, cuttlefish_root_dir,
191                                      /* delete destination first */ false,
192                                      filter_guest_dir));
193 
194   return {};
195 }
196 
PreservingOnResume(const bool creating_os_disk,const int modem_simulator_count)197 Result<std::set<std::string>> PreservingOnResume(
198     const bool creating_os_disk, const int modem_simulator_count) {
199   const auto snapshot_path = FLAGS_snapshot_path;
200   const bool resume_requested = FLAGS_resume || !snapshot_path.empty();
201   if (!resume_requested) {
202     return std::set<std::string>{};
203   }
204   CF_EXPECT(snapshot_path.empty() || !creating_os_disk,
205             "Restoring from snapshot requires not creating OS disks");
206   if (creating_os_disk) {
207     // not snapshot restore, must be --resume
208     LOG(INFO) << "Requested resuming a previous session (the default behavior) "
209               << "but the base images have changed under the overlay, making "
210               << "the overlay incompatible. Wiping the overlay files.";
211     return std::set<std::string>{};
212   }
213 
214   // either --resume && !creating_os_disk, or restoring from a snapshot
215   std::set<std::string> preserving;
216   preserving.insert("overlay.img");
217   preserving.insert("ap_composite.img");
218   preserving.insert("ap_composite_disk_config.txt");
219   preserving.insert("ap_composite_gpt_footer.img");
220   preserving.insert("ap_composite_gpt_header.img");
221   preserving.insert("ap_overlay.img");
222   preserving.insert("os_composite_disk_config.txt");
223   preserving.insert("os_composite_gpt_header.img");
224   preserving.insert("os_composite_gpt_footer.img");
225   preserving.insert("os_composite.img");
226   preserving.insert("os_vbmeta.img");
227   preserving.insert("sdcard.img");
228   preserving.insert("sdcard_overlay.img");
229   preserving.insert("boot_repacked.img");
230   preserving.insert("vendor_dlkm_repacked.img");
231   preserving.insert("vendor_boot_repacked.img");
232   preserving.insert("access-kregistry");
233   preserving.insert("hwcomposer-pmem");
234   preserving.insert("NVChip");
235   preserving.insert("gatekeeper_secure");
236   preserving.insert("gatekeeper_insecure");
237   preserving.insert("keymint_secure_deletion_data");
238   preserving.insert("modem_nvram.json");
239   preserving.insert("recording");
240   preserving.insert("persistent_composite_disk_config.txt");
241   preserving.insert("persistent_composite_gpt_header.img");
242   preserving.insert("persistent_composite_gpt_footer.img");
243   preserving.insert("persistent_composite.img");
244   preserving.insert("persistent_composite_overlay.img");
245   preserving.insert("pflash.img");
246   preserving.insert("uboot_env.img");
247   preserving.insert("factory_reset_protected.img");
248   preserving.insert("misc.img");
249   preserving.insert("metadata.img");
250   preserving.insert("persistent_vbmeta.img");
251   preserving.insert("oemlock_secure");
252   preserving.insert("oemlock_insecure");
253   // Preserve logs if restoring from a snapshot.
254   if (!snapshot_path.empty()) {
255     preserving.insert("kernel.log");
256     preserving.insert("launcher.log");
257     preserving.insert("logcat");
258     preserving.insert("modem_simulator.log");
259     preserving.insert("crosvm_openwrt.log");
260     preserving.insert("crosvm_openwrt_boot.log");
261     preserving.insert("metrics.log");
262   }
263   for (int i = 0; i < modem_simulator_count; i++) {
264     std::stringstream ss;
265     ss << "iccprofile_for_sim" << i << ".xml";
266     preserving.insert(ss.str());
267   }
268   return preserving;
269 }
270 
SetLogger(std::string runtime_dir_parent)271 Result<SharedFD> SetLogger(std::string runtime_dir_parent) {
272   while (runtime_dir_parent[runtime_dir_parent.size() - 1] == '/') {
273     runtime_dir_parent =
274         runtime_dir_parent.substr(0, FLAGS_instance_dir.rfind('/'));
275   }
276   runtime_dir_parent =
277       runtime_dir_parent.substr(0, FLAGS_instance_dir.rfind('/'));
278   auto log = SharedFD::Open(runtime_dir_parent, O_WRONLY | O_TMPFILE,
279                             S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP);
280   if (!log->IsOpen()) {
281     LOG(ERROR) << "Could not open O_TMPFILE precursor to assemble_cvd.log: "
282                << log->StrError();
283   } else {
284     android::base::SetLogger(TeeLogger({
285         {ConsoleSeverity(), SharedFD::Dup(2), MetadataLevel::ONLY_MESSAGE},
286         {LogFileSeverity(), log, MetadataLevel::FULL},
287     }));
288   }
289   return log;
290 }
291 
InitFilesystemAndCreateConfig(FetcherConfig fetcher_config,const std::vector<GuestConfig> & guest_configs,fruit::Injector<> & injector,SharedFD log)292 Result<const CuttlefishConfig*> InitFilesystemAndCreateConfig(
293     FetcherConfig fetcher_config, const std::vector<GuestConfig>& guest_configs,
294     fruit::Injector<>& injector, SharedFD log) {
295   {
296     // The config object is created here, but only exists in memory until the
297     // SaveConfig line below. Don't launch cuttlefish subprocesses between these
298     // two operations, as those will assume they can read the config object from
299     // disk.
300     auto config = CF_EXPECT(
301         InitializeCuttlefishConfiguration(FLAGS_instance_dir, guest_configs,
302                                           injector, fetcher_config),
303         "cuttlefish configuration initialization failed");
304 
305     const std::string snapshot_path = FLAGS_snapshot_path;
306     if (!snapshot_path.empty()) {
307       CF_EXPECT(RestoreHostFiles(config.root_dir(), snapshot_path));
308 
309       // Add a delimiter to each log file so that we can clearly tell what
310       // happened before vs after the restore.
311       const std::string snapshot_delimiter =
312           "\n\n\n"
313           "============ SNAPSHOT RESTORE POINT ============\n"
314           "Lines above are pre-snapshot.\n"
315           "Lines below are post-restore.\n"
316           "================================================\n"
317           "\n\n\n";
318       for (const auto& instance : config.Instances()) {
319         const auto log_files =
320             CF_EXPECT(DirectoryContents(instance.PerInstanceLogPath("")));
321         for (const auto& filename : log_files) {
322           if (filename == "." || filename == "..") {
323             continue;
324           }
325           const std::string path = instance.PerInstanceLogPath(filename);
326           auto fd = SharedFD::Open(path, O_WRONLY | O_APPEND);
327           CF_EXPECT(fd->IsOpen(),
328                     "failed to open " << path << ": " << fd->StrError());
329           const ssize_t n = WriteAll(fd, snapshot_delimiter);
330           CF_EXPECT(n == snapshot_delimiter.size(),
331                     "failed to write to " << path << ": " << fd->StrError());
332         }
333       }
334     }
335 
336     // take the max value of modem_simulator_instance_number in each instance
337     // which is used for preserving/deleting iccprofile_for_simX.xml files
338     int modem_simulator_count = 0;
339 
340     bool creating_os_disk = false;
341     // if any device needs to rebuild its composite disk,
342     // then don't preserve any files and delete everything.
343     for (const auto& instance : config.Instances()) {
344       auto os_builder = OsCompositeDiskBuilder(config, instance);
345       creating_os_disk |= CF_EXPECT(os_builder.WillRebuildCompositeDisk());
346       if (instance.ap_boot_flow() != CuttlefishConfig::InstanceSpecific::APBootFlow::None) {
347         auto ap_builder = ApCompositeDiskBuilder(config, instance);
348         creating_os_disk |= CF_EXPECT(ap_builder.WillRebuildCompositeDisk());
349       }
350       if (instance.modem_simulator_instance_number() > modem_simulator_count) {
351         modem_simulator_count = instance.modem_simulator_instance_number();
352       }
353     }
354     // TODO(schuffelen): Add smarter decision for when to delete runtime files.
355     // Files like NVChip are tightly bound to Android keymint and should be
356     // deleted when userdata is reset. However if the user has ever run without
357     // the overlay, then we want to keep this until userdata.img was externally
358     // replaced.
359     creating_os_disk &= FLAGS_use_overlay;
360 
361     std::set<std::string> preserving =
362         CF_EXPECT(PreservingOnResume(creating_os_disk, modem_simulator_count),
363                   "Error in Preserving set calculation.");
364     auto instance_dirs = config.instance_dirs();
365     auto environment_dirs = config.environment_dirs();
366     std::vector<std::string> clean_dirs;
367     clean_dirs.push_back(config.assembly_dir());
368     clean_dirs.insert(clean_dirs.end(), instance_dirs.begin(),
369                       instance_dirs.end());
370     clean_dirs.insert(clean_dirs.end(), environment_dirs.begin(),
371                       environment_dirs.end());
372     CF_EXPECT(CleanPriorFiles(preserving, clean_dirs),
373               "Failed to clean prior files");
374 
375     auto default_group = "cvdnetwork";
376     const mode_t default_mode = S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH;
377 
378     CF_EXPECT(EnsureDirectoryExists(config.root_dir()));
379     CF_EXPECT(EnsureDirectoryExists(config.assembly_dir()));
380     CF_EXPECT(EnsureDirectoryExists(config.instances_dir()));
381     CF_EXPECT(EnsureDirectoryExists(config.instances_uds_dir(), default_mode,
382                                     default_group));
383     CF_EXPECT(EnsureDirectoryExists(config.environments_dir(), default_mode,
384                                     default_group));
385     CF_EXPECT(EnsureDirectoryExists(config.environments_uds_dir(), default_mode,
386                                     default_group));
387     if (!snapshot_path.empty()) {
388       SharedFD temp = SharedFD::Creat(config.AssemblyPath("restore"), 0660);
389       if (!temp->IsOpen()) {
390         return CF_ERR("Failed to create restore file: " << temp->StrError());
391       }
392     }
393 
394     auto environment =
395         const_cast<const CuttlefishConfig&>(config).ForDefaultEnvironment();
396 
397     CF_EXPECT(EnsureDirectoryExists(environment.environment_dir(), default_mode,
398                                     default_group));
399     CF_EXPECT(EnsureDirectoryExists(environment.environment_uds_dir(),
400                                     default_mode, default_group));
401     CF_EXPECT(EnsureDirectoryExists(environment.PerEnvironmentLogPath(""),
402                                     default_mode, default_group));
403     CF_EXPECT(
404         EnsureDirectoryExists(environment.PerEnvironmentGrpcSocketPath(""),
405                               default_mode, default_group));
406 
407     LOG(INFO) << "Path for instance UDS: " << config.instances_uds_dir();
408 
409     if (log->LinkAtCwd(config.AssemblyPath("assemble_cvd.log"))) {
410       LOG(ERROR) << "Unable to persist assemble_cvd log at "
411                   << config.AssemblyPath("assemble_cvd.log")
412                   << ": " << log->StrError();
413     }
414     for (const auto& instance : config.Instances()) {
415       // Create instance directory if it doesn't exist.
416       CF_EXPECT(EnsureDirectoryExists(instance.instance_dir()));
417       auto internal_dir = instance.instance_dir() + "/" + kInternalDirName;
418       CF_EXPECT(EnsureDirectoryExists(internal_dir));
419       auto shared_dir = instance.instance_dir() + "/" + kSharedDirName;
420       CF_EXPECT(EnsureDirectoryExists(shared_dir));
421       auto recording_dir = instance.instance_dir() + "/recording";
422       CF_EXPECT(EnsureDirectoryExists(recording_dir));
423       CF_EXPECT(EnsureDirectoryExists(instance.PerInstanceLogPath("")));
424 
425       CF_EXPECT(EnsureDirectoryExists(instance.instance_uds_dir(), default_mode,
426                                       default_group));
427       CF_EXPECT(EnsureDirectoryExists(instance.instance_internal_uds_dir(),
428                                       default_mode, default_group));
429       CF_EXPECT(EnsureDirectoryExists(instance.PerInstanceGrpcSocketPath(""),
430                                       default_mode, default_group));
431       auto vsock_dir =
432           fmt::format("/tmp/vsock_{0}_{1}", instance.vsock_guest_cid(),
433                       std::to_string(getuid()));
434       if (DirectoryExists(vsock_dir, /* follow_symlinks */ false)) {
435         CF_EXPECT(RecursivelyRemoveDirectory(vsock_dir));
436       }
437       CF_EXPECT(EnsureDirectoryExists(vsock_dir, default_mode, default_group));
438 
439       // TODO(schuffelen): Move this code somewhere better
440       CF_EXPECT(CreateLegacySymlinks(instance, environment));
441     }
442     CF_EXPECT(SaveConfig(config), "Failed to initialize configuration");
443   }
444 
445   // Do this early so that the config object is ready for anything that needs
446   // it
447   auto config = CuttlefishConfig::Get();
448   CF_EXPECT(config != nullptr, "Failed to obtain config singleton");
449 
450   if (DirectoryExists(FLAGS_assembly_dir, /* follow_symlinks */ false)) {
451     CF_EXPECT(RecursivelyRemoveDirectory(FLAGS_assembly_dir));
452   } else if (FileExists(FLAGS_assembly_dir, /* follow_symlinks */ false)) {
453     CF_EXPECT(RemoveFile(FLAGS_assembly_dir),
454               "Failed to remove file" << FLAGS_assembly_dir);
455   }
456   if (symlink(config->assembly_dir().c_str(),
457               FLAGS_assembly_dir.c_str())) {
458     return CF_ERRNO("symlink(\"" << config->assembly_dir() << "\", \""
459                                  << FLAGS_assembly_dir << "\") failed");
460   }
461 
462   std::string first_instance = config->Instances()[0].instance_dir();
463   std::string double_legacy_instance_dir = FLAGS_instance_dir + "_runtime";
464   if (FileExists(double_legacy_instance_dir, /* follow_symlinks */ false)) {
465     CF_EXPECT(RemoveFile(double_legacy_instance_dir),
466               "Failed to remove symlink " << double_legacy_instance_dir);
467   }
468   if (symlink(first_instance.c_str(), double_legacy_instance_dir.c_str())) {
469     return CF_ERRNO("symlink(\"" << first_instance << "\", \""
470                                  << double_legacy_instance_dir
471                                  << "\") failed");
472   }
473 
474   CF_EXPECT(CreateDynamicDiskFiles(fetcher_config, *config));
475 
476   return config;
477 }
478 
479 const std::string kKernelDefaultPath = "kernel";
480 const std::string kInitramfsImg = "initramfs.img";
ExtractKernelParamsFromFetcherConfig(const FetcherConfig & fetcher_config)481 static void ExtractKernelParamsFromFetcherConfig(
482     const FetcherConfig& fetcher_config) {
483   std::string discovered_kernel =
484       fetcher_config.FindCvdFileWithSuffix(kKernelDefaultPath);
485   std::string discovered_ramdisk =
486       fetcher_config.FindCvdFileWithSuffix(kInitramfsImg);
487 
488   SetCommandLineOptionWithMode("kernel_path", discovered_kernel.c_str(),
489                                google::FlagSettingMode::SET_FLAGS_DEFAULT);
490 
491   SetCommandLineOptionWithMode("initramfs_path", discovered_ramdisk.c_str(),
492                                google::FlagSettingMode::SET_FLAGS_DEFAULT);
493 }
494 
VerifyConditionsOnSnapshotRestore(const std::string & snapshot_path)495 Result<void> VerifyConditionsOnSnapshotRestore(
496     const std::string& snapshot_path) {
497   if (snapshot_path.empty()) {
498     return {};
499   }
500   const std::string instance_dir(FLAGS_instance_dir);
501   const std::string assembly_dir(FLAGS_assembly_dir);
502   CF_EXPECT(snapshot_path.empty() || FLAGS_resume,
503             "--resume must be true when restoring from snapshot.");
504   CF_EXPECT_EQ(instance_dir, CF_DEFAULTS_INSTANCE_DIR,
505                "--snapshot_path does not allow customizing --instance_dir");
506   CF_EXPECT_EQ(assembly_dir, CF_DEFAULTS_ASSEMBLY_DIR,
507                "--snapshot_path does not allow customizing --assembly_dir");
508   return {};
509 }
510 
FlagsComponent()511 fruit::Component<> FlagsComponent() {
512   return fruit::createComponent()
513       .install(AdbConfigComponent)
514       .install(AdbConfigFlagComponent)
515       .install(AdbConfigFragmentComponent)
516       .install(DisplaysConfigsComponent)
517       .install(DisplaysConfigsFlagComponent)
518       .install(DisplaysConfigsFragmentComponent)
519       .install(TouchpadsConfigsComponent)
520       .install(TouchpadsConfigsFlagComponent)
521       .install(FastbootConfigComponent)
522       .install(FastbootConfigFlagComponent)
523       .install(FastbootConfigFragmentComponent)
524       .install(GflagsComponent)
525       .install(ConfigFlagComponent)
526       .install(CustomActionsComponent);
527 }
528 
529 } // namespace
530 
AssembleCvdMain(int argc,char ** argv)531 Result<int> AssembleCvdMain(int argc, char** argv) {
532   setenv("ANDROID_LOG_TAGS", "*:v", /* overwrite */ 0);
533   ::android::base::InitLogging(argv, android::base::StderrLogger);
534 
535   auto log = CF_EXPECT(SetLogger(AbsolutePath(FLAGS_instance_dir)));
536 
537   int tty = isatty(0);
538   int error_num = errno;
539   CF_EXPECT(tty == 0,
540             "stdin was a tty, expected to be passed the output of a "
541             "previous stage. Did you mean to run launch_cvd?");
542   CF_EXPECT(error_num != EBADF,
543             "stdin was not a valid file descriptor, expected to be "
544             "passed the output of launch_cvd. Did you mean to run launch_cvd?");
545 
546   std::string input_files_str;
547   {
548     auto input_fd = SharedFD::Dup(0);
549     auto bytes_read = ReadAll(input_fd, &input_files_str);
550     CF_EXPECT(bytes_read >= 0, "Failed to read input files. Error was \""
551                                    << input_fd->StrError() << "\"");
552   }
553   std::vector<std::string> input_files = android::base::Split(input_files_str, "\n");
554 
555   FetcherConfig fetcher_config = FindFetcherConfig(input_files);
556 
557   // set gflags defaults to point to kernel/RD from fetcher config
558   ExtractKernelParamsFromFetcherConfig(fetcher_config);
559 
560   auto args = ArgsToVec(argc - 1, argv + 1);
561 
562   bool help = false;
563   std::string help_str;
564   bool helpxml = false;
565 
566   std::vector<Flag> help_flags = {
567       GflagsCompatFlag("help", help),
568       GflagsCompatFlag("helpfull", help),
569       GflagsCompatFlag("helpshort", help),
570       GflagsCompatFlag("helpmatch", help_str),
571       GflagsCompatFlag("helpon", help_str),
572       GflagsCompatFlag("helppackage", help_str),
573       GflagsCompatFlag("helpxml", helpxml),
574   };
575   for (const auto& help_flag : help_flags) {
576     CF_EXPECT(help_flag.Parse(args), "Failed to process help flag");
577   }
578 
579   fruit::Injector<> injector(FlagsComponent);
580 
581   for (auto& late_injected : injector.getMultibindings<LateInjected>()) {
582     CF_EXPECT(late_injected->LateInject(injector));
583   }
584 
585   auto flag_features = injector.getMultibindings<FlagFeature>();
586   CF_EXPECT(FlagFeature::ProcessFlags(flag_features, args),
587             "Failed to parse flags.");
588 
589   if (help || !help_str.empty()) {
590     LOG(WARNING) << "TODO(schuffelen): Implement `--help` for assemble_cvd.";
591     LOG(WARNING) << "In the meantime, call `launch_cvd --help`";
592     return 1;
593   } else if (helpxml) {
594     if (!FlagFeature::WriteGflagsHelpXml(flag_features, std::cout)) {
595       LOG(ERROR) << "Failure in writing gflags helpxml output";
596     }
597     return 1;  // For parity with gflags
598   }
599 
600   CF_EXPECT(VerifyConditionsOnSnapshotRestore(FLAGS_snapshot_path),
601             "The conditions for --snapshot_path=<dir> do not meet.");
602 
603   // TODO(schuffelen): Put in "unknown flag" guards after gflags is removed.
604   // gflags either consumes all arguments that start with - or leaves all of
605   // them in place, and either errors out on unknown flags or accepts any flags.
606 
607   auto guest_configs =
608       CF_EXPECT(GetGuestConfigAndSetDefaults(), "Failed to parse arguments");
609 
610   auto config =
611       CF_EXPECT(InitFilesystemAndCreateConfig(std::move(fetcher_config),
612                                               guest_configs, injector, log),
613                 "Failed to create config");
614 
615   std::cout << GetConfigFilePath(*config) << "\n";
616   std::cout << std::flush;
617 
618   return 0;
619 }
620 
621 } // namespace cuttlefish
622 
main(int argc,char ** argv)623 int main(int argc, char** argv) {
624   auto res = cuttlefish::AssembleCvdMain(argc, argv);
625   if (res.ok()) {
626     return *res;
627   }
628   LOG(ERROR) << "assemble_cvd failed: \n" << res.error().FormatForEnv();
629   abort();
630 }
631